问:
Storage Queue Connection String Environment variable
Is there an environment variable I can set in my azure app settings to have a function pick up my storage queue connection string? I've been looking over the source and I don't see anything.

But I do see this section (https://github.com/Azure/azure-content-nlnl/blob/master/articles/azure-functions/functions-run-local.md#to-run-locally) about running locally and being able to specify a connection string. I can't ship a connection string in my oss app.

答:
son
 "queueBinding": {
      "properties": {
        "queueName": {
          "type": "string",
          "description": "The queue name."
        },
        "connection": {
          "type": "string",
          "description": "An app setting (or environment variable) with the storage connection string to be used by this binding."
        }
      }

After looking at the spec it appear this is possible by just putting the environment variable name for the connection.


来源: stackexchange

问:
Check if date is within X number of days of today
I have a date variable being set on my page like this:

```<code>startDate =  "03/28/2017";
</code>```

How can I check if that date is 7 or less days before today's date?

It will need to be used in a conditional if statement.

答:
You can try using moment.js,

```<code>var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
</code>```

or even better, it has an inbuilt method, which says after how many days.

```<code>moment([2007, 0, 29]).toNow(); // in 4 years
</code>```

and if you want to use old plain javascript :

```<code>var date1 = new Date("3/30/2017");
var date2 = new Date("3/23/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
</code>```

If you want to compare with today

```<code>var date1 = new Date("3/23/2017")
var date2 = new Date();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a date variable being set on my page like this:

startDate =  "03/28/2017";

How can I check if that date is 7 or less days before today's date?

It will need to be used in a conditional if statement.

Body:
You can try using moment.js,

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

or even better, it has an inbuilt method, which says after how many days.

moment([2007, 0, 29]).toNow(); // in 4 years

and if you want to use old plain javascript :

var date1 = new Date("3/30/2017");
var date2 = new Date("3/23/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

If you want to compare with today

var date1 = new Date("3/23/2017")
var date2 = new Date();


问:
Decorator pattern in Objective-C
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

```<code>// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end
</code>```

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.

答:
it is not (only) a problem of boring method coding but of duplication of the object i.e. there will be created two UIScrollView objects, decorator and decorated object. This might be useful sometimes when you really need two different objects and their data, but one of them is the master, I call this a "cheap decorator". But if the decorator itself does not need and use its own members I call it a "dirty decorator" (no worries, you are not alone and I dit it as well a few times ;-) The pure decorator will implement the same interface (Java) resp. category (Obj-C) like the decorated object.

Maybe it is sufficient to subclass UIScrolView an overwrite those methods you are interested in. Or categories like Matthew suggested.

Cheers

Kay

ContentLicense: CC BY-SA 2.5

Title: Decorator pattern in Objective-C

Body:
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.


问:
CSS Border-length Control w/o Div
I have a border that goes around a super short two line text above a picture that is width 500px and height 400px. Is there a way to control the length of the border so it is only 500px in length to make it line up just above the picture? Im not using div and i have tried border-length: 500px but that isnt working and when I tired border-width: 500px it just messed it up. I just want the border around the text to be the same length as the picture to make it look cleaner. (I also know there is probably a lot cleaner way of doing the style then what I have, but I would like to try and keep it in the format I have if possible!) Thank you in advance!!

h2.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h3.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h4.dotted {
  border-style: dotted;
  border-length: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" src="http://arrow.scrolltotop.com/arrow39.js"></script>

<BODY bgColor="#87CEFA">
  <div id="wrapper">
    <section id="top area">
      <article class="box-right">
        <form action="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/search.php" method="post">
          <Center>
            <h2 class="border"> Search for Content</h2>
            <p>
              <label>Category (Dog, cat, Hamster):</label>
              <input name="category" placeholder="Dog, cat, hamster" type="text">
            </p>
            <!-- Changed Animal type to Animal size(animal_size)-->
            <p>
              <label>Animal size (Large, Small, Small, Tiny/Dawf):</label>
              <input name="animal_size" placeholder="Dawf Hamster" type="text">
            </p>
            <p>
              <input value="Submit" type="submit">
            </p>

     Return to Main page
            </br>
            <h3 class="border"> Pictures of a few animals we have right now</h3>
            <h4 class="dotted"> Large Dog </br> Name: Tiny</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/bigdog.jpg" alt="Big Dog" Style="width:500px;height:400px;"></br>
            <h4 class="dotted"> Small Dog </br> Name: Yippy</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/smalldog.jpg" alt="Small Dog" Style="width:400px;height:600px;"></br>
            <h4 class="dotted"> Small Cat </br> Name: Teddy</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/smallcat.jpeg" alt="Small Cat" Style="width:400px;height:600px;"></br>
            <h4 class="dotted"> Small Hamster </br> Name: Digger</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/dawfhamster.jpg" alt="Small hamster" Style="width:400px;height:600px;">
            </br>
            </br>

    Return to Main page
          </center>
        </form>
      </article>
    </section>
  </div>
</body></code>```

答: Have you tried just using width: 500px; instead of border-whatever? Also, are you wanting all of these header texts to have the same width? Because it looks like your second, third, and fourth picture are all different widths than the first.

Title: CSS Border-length Control w/o Div

Body:
I have a border that goes around a super short two line text above a picture that is width 500px and height 400px. Is there a way to control the length of the border so it is only 500px in length to make it line up just above the picture? Im not using div and i have tried border-length: 500px but that isnt working and when I tired border-width: 500px it just messed it up. I just want the border around the text to be the same length as the picture to make it look cleaner. (I also know there is probably a lot cleaner way of doing the style then what I have, but I would like to try and keep it in the format I have if possible!) Thank you in advance!!

h2.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h3.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h4.dotted {
  border-style: dotted;
  border-length: 500px;
}

        <form action="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/search.php" method="post">

 Search for Content

              Category (Dog, cat, Hamster):
              <input name="category" placeholder="Dog, cat, hamster" type="text">

              Animal size (Large, Small, Small, Tiny/Dawf):
              <input name="animal_size" placeholder="Dawf Hamster" type="text">

              <input value="Submit" type="submit">

     Return to Main page

 Pictures of a few animals we have right now

 Large Dog
 Name: Tiny

 Small Dog
 Name: Yippy

 Small Cat
 Name: Teddy

 Small Hamster
 Name: Digger

    Return to Main page

        </form>


答:
Alternatively, you can create a new dataframe (or overwrite the current one, as the example below) so you do not need to use of any external package. However this way may not be efficient with huge dataframes.</p>

```<code>df <- data.frame(names = row.names(df), df)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can I convert row names into the first column?

Body:
I have a data frame like this:

df
              VALUE              ABS_CALL DETECTION P-VALUE
    1007_s_at "957.729231881542" "P"      "0.00486279317241156"
    1053_at   "320.632701283368" "P"      "0.0313356324173416"
    117_at    "429.842323161046" "P"      "0.0170004527476119"
    121_at    "2395.7364289242"  "P"      "0.0114473584876183"
    1255_g_at "116.493632746934" "A"      "0.39799368200131"
    1294_at   "739.927122116896" "A"      "0.0668649772942343"

I want to convert the row names into the first column. Currently I use something  like this to make row names as the first column:

  d <- df
  names <- rownames(d)
  rownames(d) <- NULL
  data <- cbind(names,d)

Is there a single line to do this?

Body:
Alternatively, you can create a new dataframe (or overwrite the current one, as the example below) so you do not need to use of any external package. However this way may not be efficient with huge dataframes.

df <- data.frame(names = row.names(df), df)


问:
MSSQL - Use hierarchical query result as subquery
i want to use  hierarchical query result as subquery but i get some errors:
My hierarchical query: </p>

```<code>   select * from (WITH tree (Oid, name, level) AS ( SELECT Oid, Name, 1 as level FROM Company
                where Oid='20C269DE-A15F-48B3-AFC2-47FBF53C1EAE' and GCRecord is null
                UNION ALL SELECT child.Oid, child.name, parent.level + 1 FROM Company as child
                JOIN tree parent on parent.Oid = child.ParentCompany where child.GCRecord is null ) SELECT Oid FROM tree) t
</code>```

<p>And my problematic query as below: </p>

```<code>select  *from DeliverySchedule where Company in (
WITH tree (Oid, name, level) AS ( SELECT Oid, Name, 1 as level FROM Company
                where Oid='20C269DE-A15F-48B3-AFC2-47FBF53C1EAE' and GCRecord is null
                UNION ALL SELECT child.Oid, child.name, parent.level + 1 FROM Company as child
                JOIN tree parent on parent.Oid = child.ParentCompany where child.GCRecord is null ) SELECT Oid FROM tree)
</code>```

答:
Try this instead:</p>

```<code>;with tree ( Oid , name , level ) as (
  select Oid
    , name
    , 1 as level
  from Company
  where Oid = '20C269DE-A15F-48B3-AFC2-47FBF53C1EAE'
    and GCRecord is null
 union all
 select
      child.Oid
    , child.name
    , parent.level + 1
  from Company as child
    inner join tree parent
      on parent.Oid = child.ParentCompany
  where child.GCRecord is null
)

select *
from DeliverySchedule
where Company in (select Oid from tree);
</code>```

Body:
i want to use  hierarchical query result as subquery but i get some errors:
My hierarchical query:

   select * from (WITH tree (Oid, name, level) AS ( SELECT Oid, Name, 1 as level FROM Company
                where Oid='20C269DE-A15F-48B3-AFC2-47FBF53C1EAE' and GCRecord is null
                UNION ALL SELECT child.Oid, child.name, parent.level + 1 FROM Company as child
                JOIN tree parent on parent.Oid = child.ParentCompany where child.GCRecord is null ) SELECT Oid FROM tree) t

And my problematic query as below:

select  *from DeliverySchedule where Company in (
WITH tree (Oid, name, level) AS ( SELECT Oid, Name, 1 as level FROM Company
                where Oid='20C269DE-A15F-48B3-AFC2-47FBF53C1EAE' and GCRecord is null
                UNION ALL SELECT child.Oid, child.name, parent.level + 1 FROM Company as child
                JOIN tree parent on parent.Oid = child.ParentCompany where child.GCRecord is null ) SELECT Oid FROM tree)

Body:
Try this instead:

;with tree ( Oid , name , level ) as (
  select Oid
    , name
    , 1 as level
  from Company
  where Oid = '20C269DE-A15F-48B3-AFC2-47FBF53C1EAE'
    and GCRecord is null
 union all
 select
      child.Oid
    , child.name
    , parent.level + 1
  from Company as child
    inner join tree parent
      on parent.Oid = child.ParentCompany
  where child.GCRecord is null
)

select *
from DeliverySchedule
where Company in (select Oid from tree);


问:
How to subtract each item in a group against other items in group in t-sql
I have a table of transactions per company.  If company, transaction date, and transaction type are the same and the difference between one record's transaction price is greater than .25% with another record's of the same company, transaction date, and transaction type, then I need to select the two (or more) records.

I know I need to use group by to do this, and I will probably need to join the table to itself, but I am struggling to come up with an approach here.  How should I do this?

```<code>Transaction_ID | Company | Transction_date | Transaction_Type | Price
1              | A       |   01/01/2017     |       BUY       |   30.01
2              |   A     |     01//01/2017  |         BUY     |       37
3              |   A     |     01/02/2017   |         BUY     |      31
</code>```

答:
You can do this using exists:

```<code>select t.*
from t
where exists (select 1
              from t t2
              where t2.Company = t.Company and
                    t2.Transaction_date = t.Transaction_date and
                    t2.Transaction_Type = t.Transaction_Type and
                    t2.Price not between t.Price / 1.0025 and t.Price * 1.0025;
</code>```

Body:
I have a table of transactions per company.  If company, transaction date, and transaction type are the same and the difference between one record's transaction price is greater than .25% with another record's of the same company, transaction date, and transaction type, then I need to select the two (or more) records.

I know I need to use group by to do this, and I will probably need to join the table to itself, but I am struggling to come up with an approach here.  How should I do this?

Transaction_ID | Company | Transction_date | Transaction_Type | Price
1              | A       |   01/01/2017     |       BUY       |   30.01
2              |   A     |     01//01/2017  |         BUY     |       37
3              |   A     |     01/02/2017   |         BUY     |      31

Body:
You can do this using exists:

select t.*
from t
where exists (select 1
              from t t2
              where t2.Company = t.Company and
                    t2.Transaction_date = t.Transaction_date and
                    t2.Transaction_Type = t.Transaction_Type and
                    t2.Price not between t.Price / 1.0025 and t.Price * 1.0025;


问:
Set currentPage using dialog property in Adobe AEM
I am creating a menu component. Mouting a tree with the pages and its children.

```

It's working fine, but I need to replace the currentPage using a property of my dialog component.

How can I do this?

I already have the dialog component and I'm able to retrieve the property value.

I don't wanna use java classes, I am assuming that there's a way to do
  this using only htl

答:
There is no shorthand for getting a Page specified by a path, mostly because HTL sits lower than the WCM layer in AEM.

You can find an example of how to do this using the Use-API (JS, but it's similar in Java) at https://github.com/Adobe-Marketing-Cloud/aem-htl-repl/blob/master/content-pkg/jcr_root/apps/repl/components/repl/template.html and https://github.com/Adobe-Marketing-Cloud/aem-htl-repl/blob/master/content-pkg/jcr_root/apps/repl/components/repl/logic.js

Body:
I am creating a menu component. Mouting a tree with the pages and its children.

It's working fine, but I need to replace the currentPage using a property of my dialog component.

How can I do this?

I already have the dialog component and I'm able to retrieve the property value.

I don't wanna use java classes, I am assuming that there's a way to do
  this using only htl


问:
Creating new rails action doesn't work?
i have a controller "Apps". It consists of one action "index". Now I want to add a new action called "buy":

```<code>def buy
  respond_to do |format|
    format.html
  end
end
</code>```

i added a buy.html.erb to the views, but when browsing to /apps/buy, i get following message:

```<code>Unknown action - The action 'show' could not be found for AppsController
</code>```

in the routes I added this:

```<code>  match '/apps/buy', :controller => 'apps', :action => 'buy'
</code>```

thanks in advance!

答:
The url is being caught by the standard /apps/:id route, I assume you also have resources :apps in your routes?

Simply place the buy route first:

```<code>match '/apps/buy', :controller => 'apps', :action => 'buy'
resources :apps
</code>```

Bear in mind that routes are executed in the order they are defined, so the specific ones need to precede the general.

A simpler approach as @Ryan suggests is adding a collection route to the resource:

```<code>resources :apps, :collection => { :buy => :get }
</code>```

Title: Creating new rails action doesn't work?

Body:
i have a controller "Apps". It consists of one action "index". Now I want to add a new action called "buy":

def buy
  respond_to do |format|
    format.html
  end
end

i added a buy.html.erb to the views, but when browsing to /apps/buy, i get following message:

Unknown action - The action 'show' could not be found for AppsController

in the routes I added this:

  match '/apps/buy', :controller => 'apps', :action => 'buy'

thanks in advance!

Body:
The url is being caught by the standard /apps/:id route, I assume you also have resources :apps in your routes?

Simply place the buy route first:

match '/apps/buy', :controller => 'apps', :action => 'buy'
resources :apps

Bear in mind that routes are executed in the order they are defined, so the specific ones need to precede the general.

A simpler approach as @Ryan suggests is adding a collection route to the resource:

resources :apps, :collection => { :buy => :get }


答:
Actually what you need to control is the size of the container for the text. That way the border will take just that space, since you have a fixed width on your imgs you can do the same for the container and use auto margin to keep the center:

h2.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h3.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h4.dotted {
  border-style: dotted;
  max-width:500px;
  margin-left: auto;
  margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" src="http://arrow.scrolltotop.com/arrow39.js"></script>

<BODY bgColor="#87CEFA">
  <div id="wrapper">
    <section id="top area">
      <article class="box-right">
        <form action="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/search.php" method="post">
          <Center>
            <h2 class="border"> Search for Content</h2>
            <p>
              <label>Category (Dog, cat, Hamster):</label>
              <input name="category" placeholder="Dog, cat, hamster" type="text">
            </p>
            <!-- Changed Animal type to Animal size(animal_size)-->
            <p>
              <label>Animal size (Large, Small, Small, Tiny/Dawf):</label>
              <input name="animal_size" placeholder="Dawf Hamster" type="text">
            </p>
            <p>
              <input value="Submit" type="submit">
            </p>

     Return to Main page
            </br>
            <h3 class="border"> Pictures of a few animals we have right now</h3>
            <h4 class="dotted"> Large Dog </br> Name: Tiny</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/bigdog.jpg" alt="Big Dog" Style="width:500px;height:400px;"></br>
            <h4 class="dotted"> Small Dog </br> Name: Yippy</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/smalldog.jpg" alt="Small Dog" Style="width:400px;height:600px;"></br>
            <h4 class="dotted"> Small Cat </br> Name: Teddy</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/smallcat.jpeg" alt="Small Cat" Style="width:400px;height:600px;"></br>
            <h4 class="dotted"> Small Hamster </br> Name: Digger</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/dawfhamster.jpg" alt="Small hamster" Style="width:400px;height:600px;">
            </br>
            </br>

    Return to Main page
          </center>
        </form>
      </article>
    </section>
  </div>
</body></code>```

Title: CSS Border-length Control w/o Div

Body:
Actually what you need to control is the size of the container for the text. That way the border will take just that space, since you have a fixed width on your imgs you can do the same for the container and use auto margin to keep the center:

h2.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h3.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h4.dotted {
  border-style: dotted;
  max-width:500px;
  margin-left: auto;
  margin-right: auto;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" src="http://arrow.scrolltotop.com/arrow39.js"></script>

<BODY bgColor="#87CEFA">
  <div id="wrapper">
    <section id="top area">
      <article class="box-right">
        <form action="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/search.php" method="post">
          <Center>
            <h2 class="border"> Search for Content</h2>
            <p>
              <label>Category (Dog, cat, Hamster):</label>
              <input name="category" placeholder="Dog, cat, hamster" type="text">
            </p>
            <!-- Changed Animal type to Animal size(animal_size)-->
            <p>
              <label>Animal size (Large, Small, Small, Tiny/Dawf):</label>
              <input name="animal_size" placeholder="Dawf Hamster" type="text">
            </p>
            <p>
              <input value="Submit" type="submit">
            </p>
            <a href="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/FinalPro_Main.html">
     Return to Main page </a>
            </br>
            <h3 class="border"> Pictures of a few animals we have right now</h3>
            <h4 class="dotted"> Large Dog </br> Name: Tiny</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/bigdog.jpg" alt="Big Dog" Style="width:500px;height:400px;"></br>
            <h4 class="dotted"> Small Dog </br> Name: Yippy</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/smalldog.jpg" alt="Small Dog" Style="width:400px;height:600px;"></br>
            <h4 class="dotted"> Small Cat </br> Name: Teddy</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/smallcat.jpeg" alt="Small Cat" Style="width:400px;height:600px;"></br>
            <h4 class="dotted"> Small Hamster </br> Name: Digger</h4>
            <img src="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/dawfhamster.jpg" alt="Small hamster" Style="width:400px;height:600px;">
            </br>
            </br>
            <a href="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/FinalPro_Main.html">
    Return to Main page </a>
          </center>
        </form>
      </article>
    </section>
  </div>
</body>


问:
How to pass values to directive in angular
My code,

```<code>  <modal *ngIf='showModal' [imageValue]="imageId"></modal>
</code>```

My model component,

```<code>@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})

export class ModalComponent  {
  imageValue:any;
</code>```

I want to get the value of this 'imageValue' but I dont know how to do it.Can anyone please help me.Thanks.

答:
This is an Example how you can pass value to a Directive

Directive

```<code>    import {Directive, Input, HostListener} from '@angular/core';

    @Directive({
      selector: '[appConfirm]'
    })
    export class ConfirmDirective {

      //we can also add the attribute directive liek this [appconfirm] if the input in the directive has same name as appConfirm like
      //@Input() appConfirm:string; and then in component button we can use the directive like
      //<button type="button" [appConfirm] = "Rahul">Click to Send to Directive</button>
      @Input() value:string;

      @HostListener('click',['$event'])
      confirm(){
          const confirmed = window.confirm("Are you Sure ?");
          if(confirmed){
            window.alert("This is Value ["+this.value+"] Passed by the Component to the Directive")
          }
      }

  constructor() { }

}
</code>```

ComponentTemplate.html

```<code><button type="button" appConfirm value = "Rahul">Click to Send to Directive</button>
</code>```

For more info look this repo https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/directives

Body:
My code,

  <modal *ngIf='showModal' [imageValue]="imageId"></modal>

My model component,

@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})

export class ModalComponent  {
  imageValue:any;

I want to get the value of this 'imageValue' but I dont know how to do it.Can anyone please help me.Thanks.

Body:
This is an Example how you can pass value to a Directive

Directive

    import {Directive, Input, HostListener} from '@angular/core';

    @Directive({
      selector: '[appConfirm]'
    })
    export class ConfirmDirective {

      //we can also add the attribute directive liek this [appconfirm] if the input in the directive has same name as appConfirm like
      //@Input() appConfirm:string; and then in component button we can use the directive like
      //<button type="button" [appConfirm] = "Rahul">Click to Send to Directive</button>
      @Input() value:string;

      @HostListener('click',['$event'])
      confirm(){
          const confirmed = window.confirm("Are you Sure ?");
          if(confirmed){
            window.alert("This is Value ["+this.value+"] Passed by the Component to the Directive")
          }
      }

  constructor() { }

}

ComponentTemplate.html

<button type="button" appConfirm value = "Rahul">Click to Send to Directive</button>

For more info look this repo https://github.com/rahulrsingh09/AngularConcepts/tree/master/src/app/directives


问:
How can we monitor a process with cloudwatch
I have a Java process that runs on EC2 I would like to setup an alert in Cloudwatch when the process goes down or is in a bad state (e.g does not send heartbeat to Cloudwatch for the last 10 secs or so).

What is the best way to do this ? I think I need the custom metrics, but did not find any documentation for specifically monitoring a process.

I can use the AWS SDK if needed.

答:
AWS Custom Metrics can be used to publish the health of the Program.

Below Java Code can be used to Publish the Heart Beat. Using Custom Metrics Alarm can be configured in CloudWatch.

```<code>AmazonCloudWatch amazonCloudWatch = AmazonCloudWatchClientBuilder.standard().
                                            withEndpointConfiguration(new AwsClientBuilder.
                                                    EndpointConfiguration("monitoring.us-west-1.amazonaws.com","us-west-1")).build();
        PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest();
        putMetricDataRequest.setNamespace("CUSTOM/SQS");

        MetricDatum metricDatum1 = new MetricDatum().withMetricName("MessageCount").withDimensions(new Dimension().withName("Personalization").withValue("123"));
        metricDatum1.setValue(-1.00);
        metricDatum1.setUnit(StandardUnit.Count);
        putMetricDataRequest.getMetricData().add(metricDatum1);

        PutMetricDataResult result = amazonCloudWatch.putMetricData(putMetricDataRequest);
</code>```

Body:
AWS Custom Metrics can be used to publish the health of the Program.

Below Java Code can be used to Publish the Heart Beat. Using Custom Metrics Alarm can be configured in CloudWatch.

AmazonCloudWatch amazonCloudWatch = AmazonCloudWatchClientBuilder.standard().
                                            withEndpointConfiguration(new AwsClientBuilder.
                                                    EndpointConfiguration("monitoring.us-west-1.amazonaws.com","us-west-1")).build();
        PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest();
        putMetricDataRequest.setNamespace("CUSTOM/SQS");

        MetricDatum metricDatum1 = new MetricDatum().withMetricName("MessageCount").withDimensions(new Dimension().withName("Personalization").withValue("123"));
        metricDatum1.setValue(-1.00);
        metricDatum1.setUnit(StandardUnit.Count);
        putMetricDataRequest.getMetricData().add(metricDatum1);

        PutMetricDataResult result = amazonCloudWatch.putMetricData(putMetricDataRequest);


问:
UI-grid exporter: How to right align data within the table
I want to right align certain elements of the exported ui grid pdf.

I have a header, main table, and footer that i have exported.  I would like only the parts of the table and footer that contain numbered data to be right aligned.

This code aligns the text to the center.  It is the column header for the table.

```<code>exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red', alignment: 'center'},
</code>```

This does not solve the issue because it right aligns ALL the content that is exported. That's not what I want.

```<code>exporterPdfDefaultStyle: {fontSize: 9, alignment: 'right'},
</code>```

The header (which is its own table), table data, and footer are all left aligned by default.

Any exporters that can help me right alignment certain parts of my table?  Any help is appreciated.

答:
Within my columnDefs, I use

```<code>exporterPdfAlign: 'right',
</code>```

this aligns the content under each column header

Body:
I want to right align certain elements of the exported ui grid pdf.

I have a header, main table, and footer that i have exported.  I would like only the parts of the table and footer that contain numbered data to be right aligned.

This code aligns the text to the center.  It is the column header for the table.

exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red', alignment: 'center'},

This does not solve the issue because it right aligns ALL the content that is exported. That's not what I want.

exporterPdfDefaultStyle: {fontSize: 9, alignment: 'right'},

The header (which is its own table), table data, and footer are all left aligned by default.

Any exporters that can help me right alignment certain parts of my table?  Any help is appreciated.

Body:
Within my columnDefs, I use

exporterPdfAlign: 'right',

this aligns the content under each column header


答:
You can easily achieve a border of 500px using this :

```<code>h4.dotted {
  border-style: dotted;
  max-width: 500px;
}
</code>```

Does that solve your issue? Hope this helps.

Title: CSS Border-length Control w/o Div

Body:
You can easily achieve a border of 500px using this :

h4.dotted {
  border-style: dotted;
  max-width: 500px;
}

Does that solve your issue? Hope this helps.


问:
Microsoft Access 2007 Database related
For my recent work, I am using Microsoft Access 2007 Database. In a table there are two fields text and Date/Time. When I am accessing the table through java code externally, I am getting error message at the time of execution.
Particularly on Execute Query which is related to Date Between.

Following is my Code :-

```<code>import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.text.ParseException;
import java.lang.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.Console;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
import oracle.jdbc.driver.OracleDriver;
public class test_data_view {
  public static void main(String [] args) {

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String imp_str="01-feb-2017";
    String imp_end="11-mar-2017";
    try {
      Connection con = null;
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:ADB");

      /*Here ADB is the User DSN name which indicates "Microsoft Access Driver(*.mdb,*.accdb)
        and the database Database1.accdb is assigned with ADB.*/

      Statement sta = con.createStatement();
      Statement stmt = con.createStatement();
      Statement stmt2 = con.createStatement();
      Statement stmt3 = con.createStatement();
      ResultSet rs = null;
      ResultSet rs1 = null;
      ResultSet rs2 = null;
      ResultSet rs3 = null;
      try {

                rs=sta.executeQuery("select count(*) from test");
                while (rs.next()) {
                    String tot = rs.getString(1);
                    System.out.println("==================");
                    System.out.println("Total Count : "+tot);
                    System.out.println("==================");
                                   }

                rs1=stmt.executeQuery("select X.ename,X.bdate from test X");
                while (rs1.next()) {
                    String t_name        = rs1.getString(1);
                    String t_bdate       = rs1.getString(2);

                    System.out.println(t_name+"  "+t_bdate);
                                   }

                    rs2=stmt2.executeQuery("select X.ename,X.bdate from test X where X.bdate BETWEEN '"+ imp_str +"' "+" AND '"+ imp_end +"'");
                    while (rs2.next()) {
                       String t_name_a        = rs2.getString(1);
                       String t_bdate_a       = rs2.getString(2);

                       System.out.println(t_name_a+"  "+t_bdate_a);
                                       }

          }
      catch (Exception e) {
                           System.out.println("Test Error "+e.getMessage());
                           e.printStackTrace();
                           }

                             finally{
                                     try {
                                          stmt3.close();
                                          if (rs2 != null)
                                              rs2.close();
                                          if (stmt2 != null)
                                              stmt2.close();
                                               rs1.close();
                                              stmt.close();
                                          if (rs != null)
                                              rs.close();
                                          if (sta != null)
                                              sta.close();
                                         }

                                     catch (SQLException se) {
                                            se.printStackTrace();
                                                             }
                             con.close();
                                    }

    }
    catch(Exception ex){
                       }

  }
}
</code>```

And the result along with Error Message At the Time Of Execution  :-

```<code>==================
Total Count : 7
==================
sumit  2017-02-01 00:00:00
probir  2017-02-01 00:00:00
subhajit  2017-02-01 10:40:30
supriyo  2017-02-09 10:40:30
rajdip  2017-01-01 00:00:00
indranil  2017-03-07 16:06:19
sudip  2017-03-07 21:17:24
Test Error [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in crite
ria expression.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type misma
tch in criteria expression.
        at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
        at test_data_view.main(test_data_view.java:61)
</code>```

Please help me to generate report between date range.

答: Date/Time values use # delimiter instead of ' in SQL statements.</p>

Title: Microsoft Access 2007 Database related

Body:
For my recent work, I am using Microsoft Access 2007 Database. In a table there are two fields text and Date/Time. When I am accessing the table through java code externally, I am getting error message at the time of execution.
Particularly on Execute Query which is related to Date Between.

Following is my Code :-

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.text.ParseException;
import java.lang.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.Console;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
import oracle.jdbc.driver.OracleDriver;
public class test_data_view {
  public static void main(String [] args) {

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String imp_str="01-feb-2017";
    String imp_end="11-mar-2017";
    try {
      Connection con = null;
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:ADB");

      /*Here ADB is the User DSN name which indicates "Microsoft Access Driver(*.mdb,*.accdb)
        and the database Database1.accdb is assigned with ADB.*/

      Statement sta = con.createStatement();
      Statement stmt = con.createStatement();
      Statement stmt2 = con.createStatement();
      Statement stmt3 = con.createStatement();
      ResultSet rs = null;
      ResultSet rs1 = null;
      ResultSet rs2 = null;
      ResultSet rs3 = null;
      try {

                rs=sta.executeQuery("select count(*) from test");
                while (rs.next()) {
                    String tot = rs.getString(1);
                    System.out.println("==================");
                    System.out.println("Total Count : "+tot);
                    System.out.println("==================");
                                   }

                rs1=stmt.executeQuery("select X.ename,X.bdate from test X");
                while (rs1.next()) {
                    String t_name        = rs1.getString(1);
                    String t_bdate       = rs1.getString(2);

                    System.out.println(t_name+"  "+t_bdate);
                                   }

                    rs2=stmt2.executeQuery("select X.ename,X.bdate from test X where X.bdate BETWEEN '"+ imp_str +"' "+" AND '"+ imp_end +"'");
                    while (rs2.next()) {
                       String t_name_a        = rs2.getString(1);
                       String t_bdate_a       = rs2.getString(2);

                       System.out.println(t_name_a+"  "+t_bdate_a);
                                       }

          }
      catch (Exception e) {
                           System.out.println("Test Error "+e.getMessage());
                           e.printStackTrace();
                           }

                             finally{
                                     try {
                                          stmt3.close();
                                          if (rs2 != null)
                                              rs2.close();
                                          if (stmt2 != null)
                                              stmt2.close();
                                               rs1.close();
                                              stmt.close();
                                          if (rs != null)
                                              rs.close();
                                          if (sta != null)
                                              sta.close();
                                         }

                                     catch (SQLException se) {
                                            se.printStackTrace();
                                                             }
                             con.close();
                                    }

    }
    catch(Exception ex){
                       }

  }
}

And the result along with Error Message At the Time Of Execution  :-

==================
Total Count : 7
==================
sumit  2017-02-01 00:00:00
probir  2017-02-01 00:00:00
subhajit  2017-02-01 10:40:30
supriyo  2017-02-09 10:40:30
rajdip  2017-01-01 00:00:00
indranil  2017-03-07 16:06:19
sudip  2017-03-07 21:17:24
Test Error [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in crite
ria expression.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type misma
tch in criteria expression.
        at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
        at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
        at test_data_view.main(test_data_view.java:61)

Please help me to generate report between date range.


问:
How to unit test 3rd party API endpoints that need access_token?
I'm developing a backend API that consumes Github's API to retrieve some repos and do some stuff with it. Also I'm using Codeship CI, so all my data need to be in the code in order to be properly built.

There's a route in my backend /api/github/repos that takes an Github access_token as parameter and consumes https://api.github.com/user/repos endpoint which lists all logged user repositories.

My doubt is: how do I unit test this route? I cannot write my access_token in the unit test since it's sensitive data and I'm storing it in Github public repository nor I can seed that data to a database because the access_token will still be written in the code. Where should I keep my access_token? Is there another approach?

I'm developing in PHP using Laravel framework but as you can see this problem is language independent.

答:
There are multiple ways you can do this:

Use a test table / file (or .env) / cache key value pair, store the api key in the test table / file / cache and then retrieve the key in the unit test, which passes the params to the request for testing

Pass command line arguments to phpunit

Use a repository interface to fetch the api key in your controller class. You can have 2 repository class implementations of this interface - the first fetching the key from the request param and the second fetching the key from say a test table / file / cache as in point #1

There may be other ways as well. Which one you choose would depend on your app. If the api key is relevant for most unit tests, you may go for #2, else #1. #3 would be ideal for large apps - more layers of abstraction and cleaner code but over-engineering for small/mid apps


问:
Rejecting a the returned promise inside a then block
Say I have two promises I want to combine with a when(resolved:). I want to reject the promise if there was a problem with the first promise, but resolve otherwise. Essentially, this is what I want to do:

```<code>func personAndPetPromise() -> Promise<(Person, Pet?)> {
    let personPromise: Promise<Person> = ...
    let petPromise: Promise<Pet> = ...

    when(resolved: personPromise, petPromise).then { _ -> (Person, Pet?) in
        if let error = personPromise.error {
            return Promise(error: error) // syntax error
        }
        guard let person = personPromise.value else {
            return Promise(error: myError) // syntax error
        }
        return (person, petPromise.value)
    }
}
</code>```

such that externally I can do something like this:

```<code>personAndPetPromise().then { person, pet in
    doSomethingWith(person, pet)
}.catch { error in
    showError(error)
}
</code>```

The problem lies within the the then { _ in block in personAndPetPromise. There's no way that method can return both a Promise(error:) and a (Person, Pet?).

How else can I reject the block?

答:
The problem is that there are two overloads of the then function:

```<code>public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U>
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U>
</code>```

The first one's body returns a U and causes then to return Promise.

The second one's body returns a Promise and causes then to return Promise.

Since in this case we want to return an error or a valid response, we're forced to use the second overload.

Here's a working version. The main difference is I changed it from -> (Person, Pet?) to -> Promise<(Person, Pet?)>:

```<code>func personAndPetPromise() -> Promise<(Person, Pet?)> {
    let personPromise: Promise<Person> = ...
    let petPromise: Promise<Pet> = ...

    when(resolved: personPromise, petPromise).then { _ -> Promise<(Person, Pet?)> in
        if let error = personPromise.error {
            return Promise(error: error)
        }
        guard let person = personPromise.value else {
            return Promise(error: myError)
        }
        return Promise(value: (person, petPromise.value))
    }
}
</code>```

Another way to do the same thing is by throwing the error rather than attempting to return it:

```<code>func personAndPetPromise() -> Promise<(Person, Pet?)> {
    let personPromise: Promise<Person> = ...
    let petPromise: Promise<Pet> = ...

    when(resolved: personPromise, petPromise).then { _ -> (Person, Pet?) in
        if let error = personPromise.error {
            throw error
        }
        guard let person = personPromise.value else {
            throw myError
        }
        return (person, petPromise.value)
    }
}
</code>```

Body:
Say I have two promises I want to combine with a when(resolved:). I want to reject the promise if there was a problem with the first promise, but resolve otherwise. Essentially, this is what I want to do:

func personAndPetPromise() -> Promise<(Person, Pet?)> {
    let personPromise: Promise<Person> = ...
    let petPromise: Promise<Pet> = ...

    when(resolved: personPromise, petPromise).then { _ -> (Person, Pet?) in
        if let error = personPromise.error {
            return Promise(error: error) // syntax error
        }
        guard let person = personPromise.value else {
            return Promise(error: myError) // syntax error
        }
        return (person, petPromise.value)
    }
}

such that externally I can do something like this:

personAndPetPromise().then { person, pet in
    doSomethingWith(person, pet)
}.catch { error in
    showError(error)
}

The problem lies within the the then { _ in block in personAndPetPromise. There's no way that method can return both a Promise(error:) and a (Person, Pet?).

How else can I reject the block?

Body:
The problem is that there are two overloads of the then function:

public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> U) -> Promise<U>
public func then<U>(on q: DispatchQueue = .default, execute body: @escaping (T) throws -> Promise<U>) -> Promise<U>

The first one's body returns a U and causes then to return Promise<U>.

The second one's body returns a Promise<U> and causes then to return Promise<U>.

Since in this case we want to return an error or a valid response, we're forced to use the second overload.

Here's a working version. The main difference is I changed it from -> (Person, Pet?) to -> Promise<(Person, Pet?)>:

func personAndPetPromise() -> Promise<(Person, Pet?)> {
    let personPromise: Promise<Person> = ...
    let petPromise: Promise<Pet> = ...

    when(resolved: personPromise, petPromise).then { _ -> Promise<(Person, Pet?)> in
        if let error = personPromise.error {
            return Promise(error: error)
        }
        guard let person = personPromise.value else {
            return Promise(error: myError)
        }
        return Promise(value: (person, petPromise.value))
    }
}

Another way to do the same thing is by throwing the error rather than attempting to return it:

func personAndPetPromise() -> Promise<(Person, Pet?)> {
    let personPromise: Promise<Person> = ...
    let petPromise: Promise<Pet> = ...

    when(resolved: personPromise, petPromise).then { _ -> (Person, Pet?) in
        if let error = personPromise.error {
            throw error
        }
        guard let person = personPromise.value else {
            throw myError
        }
        return (person, petPromise.value)
    }
}


问:
Using value field in a dictionary as a key to split out into multiple dictionaries
I have a Python Dictionary that currently looks like this:

```<code>A = {'Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-13'],'Type':['One','Two','Three','Four','One','Two','Three','Four'],'Value':[1,1,1,1,1,1,1,1]}
print A
</code>```

I would like to create a top level dictionary such as each unique value in Type becomes part of the key itself.

Such that in this example, my top dictionary will have four dictionaries in it, one with the keys (A,One), the next one with keys (A,Two), next one with (A,Three) and the last one with (A,Four). The values inside those individual dicts will be be filtered accordingly. Thus the first underlying dict will only have values where the Type is 'One' and so on.

The top level dictionary will then be the combination of these four unique dictionaries. Any idea how I can arrive at this?

Body:
I have a Python Dictionary that currently looks like this:

A = {'Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-13'],'Type':['One','Two','Three','Four','One','Two','Three','Four'],'Value':[1,1,1,1,1,1,1,1]}
print A

I would like to create a top level dictionary such as each unique value in Type becomes part of the key itself.

Such that in this example, my top dictionary will have four dictionaries in it, one with the keys (A,One), the next one with keys (A,Two), next one with (A,Three) and the last one with (A,Four). The values inside those individual dicts will be be filtered accordingly. Thus the first underlying dict will only have values where the Type is 'One' and so on.

The top level dictionary will then be the combination of these four unique dictionaries. Any idea how I can arrive at this?

Body:
from collections import defaultdict

A = {'Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-13'],'Type':['One','Two','Three','Four','One','Two','Three','Four'],'Value':[1,1,1,1,1,1,1,1]}

B=defaultdict(list)
# group by index in the individual lists [ ( D[0], T[0], V[0]), ...]
for (d,t,v) in zip(A["Date"],A["Type"],A["Value"]):
    # each group (D[0],T[0],V[0])
    # Create dict B["A" + {"One"}]
    #                    insert in dict B["AOne"][{Date}] = {Value}
    B["A"+t].append({d:v})

print(dict(B))
>>> {'AFour': [{'2017-03-10': 1}, {'2017-03-13': 1}], 'AOne': [{'2017-03-10': 1}, {'2017-03-13': 1}], 'ATwo': [{'2017-03-10': 1}, {'2017-03-13': 1}], 'AThree': [{'2017-03-10': 1}, {'2017-03-13': 1}]}

Something like that ?

Ideone test : http://ideone.com/e.js/5x2xs6


问:
Installing Roundcube with MSSQL Server 2016 not recognized

PHP 7.1.2

Roundcube 1.2.3 - Complete

SQL Server 2016

Windows Server 2016

Downloaded Microsoft PHP drivers (SQLSRV40.EXE) from:

https://learn.microsoft.com/en-us/sql/connect/php/step-1-configure-development-environment-for-php-development

I get the following error message when trying to run the Roundcube installer and unable to continue:

Sorry but your webserver does not meet the requirements for Roundcube!
  Please install the missing modules or fix the php.ini settings according to the > above check results.
  Hint: only checks showing NOT OK need to be fixed.

Nothing is marked as "NOT OK" on the entire page, however the database does not appear to be recognized. See the following copied from the installer page:

Checking available databases

Check which of the supported extensions are installed. At least one of them is required.

MySQL:  NOT AVAILABLE(See http://www.php.net/manual/en/ref.pdo-mysql.php)

PostgreSQL:  NOT AVAILABLE(See http://www.php.net/manual/en/ref.pdo-pgsql.php)

SQLite:  NOT AVAILABLE(See http://www.php.net/manual/en/ref.pdo-sqlite.php)

SQLite (v2):  NOT AVAILABLE(See http://www.php.net/manual/en/ref.pdo-sqlite.php)

SQL Server (SQLSRV):  NOT AVAILABLE(See http://www.php.net/manual/en/ref.pdo-sqlsrv.php)

SQL Server (DBLIB):  NOT AVAILABLE(See http://www.php.net/manual/en/ref.pdo-dblib.php)

Oracle:  NOT AVAILABLE(See http://www.php.net/manual/en/book.oci8.php)

I have verified the Microsoft drivers are in the PHP extension directory and attempted to include the following extensions (one at a time) in PHP.ini:

extension=php_sqlsrv_7_nts_x64.dll

extension=php_pdo_sqlsrv_7_nts_x64.dll

I have also tried other various SQL related extensions and restarted IIS and/or Windows with no success.

答:
It appears that the SQLSRV dll files must match the version of your PHP. I installed PHP 7.1 and attempted to use Microsoft's 7.0 driver.

After locating the proper driver from GitHub.com/Microsoft/... it placed the "OK" next to the MS SQLSRV and enabled the "Next" button to continue the RoundCube WebMail install.


问:
Using izip over second dimension of numpy array
I have the following:

```<code>for i in xrange(n):
    label = labels[i]
    frame = data[:, i]
    dostuff()
</code>```

Where data is a 2-D numpy array.  I'd like to rewrite it using izip.

```<code>for label, frame in izip(labels, ???):
    dostuff()
</code>```

What do I replace ??? with to get this to work?

答:
If you really want to use izip(), you can do it like this:

```<code>for label, frame in izip(labels, data.T):
    dostuff()
</code>```

It is generally advisable not to iterate over a NumPy array using a Python loop, but rather use NumPy ufuncs to do the loops in C code.  How to do this, depends on what dostuff() actually does.

Body:
I have the following:

for i in xrange(n):
    label = labels[i]
    frame = data[:, i]
    dostuff()

Where data is a 2-D numpy array.  I'd like to rewrite it using izip.

for label, frame in izip(labels, ???):
    dostuff()

What do I replace ??? with to get this to work?

Body:
If you really want to use izip(), you can do it like this:

for label, frame in izip(labels, data.T):
    dostuff()

It is generally advisable not to iterate over a NumPy array using a Python loop, but rather use NumPy ufuncs to do the loops in C code.  How to do this, depends on what dostuff() actually does.


问:
SCRIPT - Multiple programs in multiple terminals
I made a script so I can easily execute multiple programs in different terminals by just writing

```<code>./script.sh (numberofprogramstype1) (numberofprogramstype2)
</code>```

The problem is it only executes one of each type, even though I am looping it based on the arguments given. Here is my code:

```<code>gcc program1.c -lpthread

for i in {1..$1}
do
       gnome-terminal -e ./a.out
done

gcc program2.c -lpthread

for i in {1..$2}
do
        gnome-terminal -e ./a.out
done
</code>```

Why is this happening and how can I solve it?

答:
Brace expansion happens before parameter expansion; you can only use hard-coded numbers in them. Use a C-style for loop instead.

```<code># {1..$1}
for ((i=1;i<=$1;i++)); do
   ...
</code>```

Body:
I made a script so I can easily execute multiple programs in different terminals by just writing

./script.sh (numberofprogramstype1) (numberofprogramstype2)

The problem is it only executes one of each type, even though I am looping it based on the arguments given. Here is my code:

gcc program1.c -lpthread

for i in {1..$1}
do
       gnome-terminal -e ./a.out
done

gcc program2.c -lpthread

for i in {1..$2}
do
        gnome-terminal -e ./a.out
done

Why is this happening and how can I solve it?

Body:
Brace expansion happens before parameter expansion; you can only use hard-coded numbers in them. Use a C-style for loop instead.

# {1..$1}
for ((i=1;i<=$1;i++)); do
   ...


答:
You said:

Is there a way to control the length of the border so it is only 500px
  in length to make it line up just above the picture?

Assuming that you want that box to be 500px wide, do this for your h4.dotted:

```<code>h4.dotted {
  border-style: dotted;
  width: 500px;
  box-sizing: border-box;
}
</code>```

Title: CSS Border-length Control w/o Div

Body:
I have a border that goes around a super short two line text above a picture that is width 500px and height 400px. Is there a way to control the length of the border so it is only 500px in length to make it line up just above the picture? Im not using div and i have tried border-length: 500px but that isnt working and when I tired border-width: 500px it just messed it up. I just want the border around the text to be the same length as the picture to make it look cleaner. (I also know there is probably a lot cleaner way of doing the style then what I have, but I would like to try and keep it in the format I have if possible!) Thank you in advance!!

h2.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h3.border {
  border-top: 3px dotted #e5e5e5;
  border-bottom: 3px dotted #e5e5e5;
  box-shadow: inset 0 -1px 0 0 #e5e5e5, inset 0 1px 0 0 #e5e5e5, 0 1px 0 0 #e5e5e5, 0 -1px 0 0 #e5e5e5;
  margin-bottom: 1px;
}

h4.dotted {
  border-style: dotted;
  border-length: 500px;
}

        <form action="http://sarahmcintosh.x10host.com/Sarah%20McIntosh%20CS0334/Lab%20Assignments/Lab%2010/Lab%2010/search.php" method="post">

 Search for Content

              Category (Dog, cat, Hamster):
              <input name="category" placeholder="Dog, cat, hamster" type="text">

              Animal size (Large, Small, Small, Tiny/Dawf):
              <input name="animal_size" placeholder="Dawf Hamster" type="text">

              <input value="Submit" type="submit">

     Return to Main page

 Pictures of a few animals we have right now

 Large Dog
 Name: Tiny

 Small Dog
 Name: Yippy

 Small Cat
 Name: Teddy

 Small Hamster
 Name: Digger

    Return to Main page

        </form>

Body:
You said:

Is there a way to control the length of the border so it is only 500px
  in length to make it line up just above the picture?

Assuming that you want that box to be 500px wide, do this for your h4.dotted:

h4.dotted {
  border-style: dotted;
  width: 500px;
  box-sizing: border-box;
}


问:
Jquery Datepicker weekends only between certain dates
I'm trying to get datepicker to show only weekends available between two specific dates.  The code I have will show only weekends, or it will only show available between the dates, but not the expected result.  Here's what I've got right now:

$(function() {
  $('.datepicker').datepicker({
    "dateFormat": 'yy/mm/dd',
    'minDate': new Date(),
    beforeShowDay: function(dt) {
      if (dt.getMonth() > 3 && dt.getMonth() < 8) {
        return [dt.getDay() == 0 || dt.getDay() == 6, ""];
      } else {
        return [true, "", "Available"];
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" class="datepicker"></code>```

This shows only the weekends available, but now I need to limit that to weekends only between May 27th and August 17th and everything available after August 17th.  Does anyone have an idea how to do that?

答:
add another nested if section to define dates within months. if you wanna include the dates, just make it <= or >= instead of just < and >

$(function() {
  $('.datepicker').datepicker({
    "dateFormat": 'yy/mm/dd',
    'minDate': new Date(),
    beforeShowDay: function(dt) {
      if (dt.getMonth() > 3 && dt.getMonth() < 8) {
        if (dt.getMonth() == 4 && dt.getDate() < 26) {
          return [true, "", "Available"];
        }
        if (dt.getMonth() == 7 && dt.getDate() > 17) {
          return [true, "", "Available"];
        }
        return [dt.getDay() == 0 || dt.getDay() == 6, ""];
      }
      else {
        return [true, "", "Available"];
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" class="datepicker"></code>```

Body:
I'm trying to get datepicker to show only weekends available between two specific dates.  The code I have will show only weekends, or it will only show available between the dates, but not the expected result.  Here's what I've got right now:

$(function() {
  $('.datepicker').datepicker({
    "dateFormat": 'yy/mm/dd',
    'minDate': new Date(),
    beforeShowDay: function(dt) {
      if (dt.getMonth() > 3 && dt.getMonth() < 8) {
        return [dt.getDay() == 0 || dt.getDay() == 6, ""];
      } else {
        return [true, "", "Available"];
      }
    }
  });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>

<input type="text" class="datepicker">

This shows only the weekends available, but now I need to limit that to weekends only between May 27th and August 17th and everything available after August 17th.  Does anyone have an idea how to do that?

Body:
add another nested if section to define dates within months. if you wanna include the dates, just make it <= or >= instead of just < and >

$(function() {
  $('.datepicker').datepicker({
    "dateFormat": 'yy/mm/dd',
    'minDate': new Date(),
    beforeShowDay: function(dt) {
      if (dt.getMonth() > 3 && dt.getMonth() < 8) {
        if (dt.getMonth() == 4 && dt.getDate() < 26) {
          return [true, "", "Available"];
        }
        if (dt.getMonth() == 7 && dt.getDate() > 17) {
          return [true, "", "Available"];
        }
        return [dt.getDay() == 0 || dt.getDay() == 6, ""];
      }
      else {
        return [true, "", "Available"];
      }
    }
  });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<input type="text" class="datepicker">


问:
How to remotely unjoin and rejoin a computer from a domain?
May I unjoin and rejoin of a remote(physical) system from an another(also a physical) system, if both the system are in same domains(let say contoso.com)

Can I use this cmdline for this:

```<code>netdom remove %systemname% /domain:contoso.com /USER:contoso.comt\%username% /Password:%password%
netdom join %systemname% /domain:contoso.com /USER:contoso.com\%username% /Password:%password%
</code>```

Any suggestions?

答:
The PowerShell commands for this would be:</p>

```<code>Remove-Computer -ComputerName "Computer01" -UnjoinDomaincredential "Domain01\Admin01" -PassThru -Verbose -Restart

Add-Computer -ComputerName "Computer01" -LocalCredential "Computer01\Administrator" -DomainName "Domain01" -Credential "Domain01\Admin01" -Force -Verbose -Restart
</code>```

Body:
May I unjoin and rejoin of a remote(physical) system from an another(also a physical) system, if both the system are in same domains(let say contoso.com)

Can I use this cmdline for this:

netdom remove %systemname% /domain:contoso.com /USER:contoso.comt\%username% /Password:%password%
netdom join %systemname% /domain:contoso.com /USER:contoso.com\%username% /Password:%password%

Any suggestions?

Body:
The PowerShell commands for this would be:

Remove-Computer -ComputerName "Computer01" -UnjoinDomaincredential "Domain01\Admin01" -PassThru -Verbose -Restart

Add-Computer -ComputerName "Computer01" -LocalCredential "Computer01\Administrator" -DomainName "Domain01" -Credential "Domain01\Admin01" -Force -Verbose -Restart


问:
Natural sorting in SQL does not work
I am trying to sort a row "naturally" in SQL, and I found this answer which supposedly does exactly what I need:

https://stackoverflow.com/a/17354420/7563153

But when I tried recreating it in "SQL Fiddle" I couldn't get it to work...

Here's my attempt

What am I doing wrong?

答:
The difference between the example you cite and your own trial, is that your data combines numeric and non-numeric characters in the same field, so casting to an integer doesn't work (it just gives 0).  You can visualize why the query isn't working for you by adding the order by expressions in your select list like this:

```<code>SELECT test
       ,test REGEXP '^[A-Za-z]+$'
       ,CAST(test as SIGNED INTEGER)
       ,CAST(REPLACE(test,'-','')AS SIGNED INTEGER)
FROM table1
ORDER BY test REGEXP '^[A-Za-z]+$'
        ,CAST(test as SIGNED INTEGER)
        ,CAST(REPLACE(test,'-','')AS SIGNED INTEGER)
        ,test
</code>```

You'll see that they all evaluate to 0, which does not give you the sort order you're looking for.

You need to separate the numeric portion of your value from the non-numeric portion, and sort them separately.  Something like this:

```<code>SELECT test
FROM table1
ORDER BY substring_index(test,'-',1)
        ,CAST(substring(test, locate('-', test)+1)AS SIGNED INTEGER)
        ,test
</code>```

You might need to adjust that if your actual data isn't as simple and straightforward as your example data.

Title: Natural sorting in SQL does not work

Body:
The difference between the example you cite and your own trial, is that your data combines numeric and non-numeric characters in the same field, so casting to an integer doesn't work (it just gives 0).  You can visualize why the query isn't working for you by adding the order by expressions in your select list like this:

SELECT test
       ,test REGEXP '^[A-Za-z]+$'
       ,CAST(test as SIGNED INTEGER)
       ,CAST(REPLACE(test,'-','')AS SIGNED INTEGER)
FROM table1
ORDER BY test REGEXP '^[A-Za-z]+$'
        ,CAST(test as SIGNED INTEGER)
        ,CAST(REPLACE(test,'-','')AS SIGNED INTEGER)
        ,test

You'll see that they all evaluate to 0, which does not give you the sort order you're looking for.

You need to separate the numeric portion of your value from the non-numeric portion, and sort them separately.  Something like this:

SELECT test
FROM table1
ORDER BY substring_index(test,'-',1)
        ,CAST(substring(test, locate('-', test)+1)AS SIGNED INTEGER)
        ,test

You might need to adjust that if your actual data isn't as simple and straightforward as your example data.


问:
Substring between 2 indexes using recursion
I started learning Java, currently I'm playing around with recursion.

I wanted to try and make a substring method which will substring from both sides by 1 character until we get the desired string.

I managed to do the first part but I'm having problem figuring out how to substring from the back.

n and m should be the indexes between which we want to substring (inclusive).

In this example result of method should be "bstri"

Here is my code:

```<code>public static void main(String[] args) {
    String s = "substringme";

    System.out.println(rec(s,2,6));
}

public static String rec(String s, int n, int m) {
    if(n == 0 /* && missing 2nd part of condition */){
        return s;
    } else {
        if(n>0){
            s = s.substring(1);
            n--;
        }
        if(/* missing condition */){
            s= s.substring(0, s.length()-1);
        }
        return rec(s,n,m);
    }
}
</code>```

I would appreciate any help I can get.

答:
So fixing your recursive method is fairly easy. We just do exactly the same as you did for n:

```<code>public static String rec(String s, int n, int m) {
    if (n == 0 && m == 0) {
        return s;
    }
    else {
        if(n > 0) {
            s = s.substring(1);
            n--;
        }
        if(m > 0) {
            s = s.substring(0, s.length()-1);
            m--;
        }
        return rec(s,n,m);
    }
}
</code>```

The issue now is that the value of m given as input is measured from the start of the String and it would be way more convenient for us if it were measured from the end of the String.

We can introduce a new method to do this for us which acts as our entry point to the recursive method:

```<code>public static String substr(String s, int n, int m) {
    final int newM = s.length() - m - 1; //-1 to be inclusive of the char
    return rec(s, n, newM);
}
</code>```

You would then change your main method to call substr() instead:

```<code>public static void main(String[] args) {
    String s = "substringme";

    System.out.println(substr(s,2,6));
}
</code>```

I often find myself writing these kind of "entry point" methods when I'm using recursive methods. If you were doing this properly, substr would be your public-facing method and rec would be private.

Body:
I started learning Java, currently I'm playing around with recursion.

I wanted to try and make a substring method which will substring from both sides by 1 character until we get the desired string.

I managed to do the first part but I'm having problem figuring out how to substring from the back.

n and m should be the indexes between which we want to substring (inclusive).

In this example result of method should be "bstri"

Here is my code:

public static void main(String[] args) {
    String s = "substringme";

    System.out.println(rec(s,2,6));
}

public static String rec(String s, int n, int m) {
    if(n == 0 /* && missing 2nd part of condition */){
        return s;
    } else {
        if(n>0){
            s = s.substring(1);
            n--;
        }
        if(/* missing condition */){
            s= s.substring(0, s.length()-1);
        }
        return rec(s,n,m);
    }
}

I would appreciate any help I can get.

Body:
So fixing your recursive method is fairly easy. We just do exactly the same as you did for n:

public static String rec(String s, int n, int m) {
    if (n == 0 && m == 0) {
        return s;
    }
    else {
        if(n > 0) {
            s = s.substring(1);
            n--;
        }
        if(m > 0) {
            s = s.substring(0, s.length()-1);
            m--;
        }
        return rec(s,n,m);
    }
}

The issue now is that the value of m given as input is measured from the start of the String and it would be way more convenient for us if it were measured from the end of the String.

We can introduce a new method to do this for us which acts as our entry point to the recursive method:

public static String substr(String s, int n, int m) {
    final int newM = s.length() - m - 1; //-1 to be inclusive of the char
    return rec(s, n, newM);
}

You would then change your main method to call substr() instead:

public static void main(String[] args) {
    String s = "substringme";

    System.out.println(substr(s,2,6));
}

I often find myself writing these kind of "entry point" methods when I'm using recursive methods. If you were doing this properly, substr would be your public-facing method and rec would be private.


问:
AutoFlushWrapper with Mail target
I'm trying to send myself an email with the latest log entries when an error occurs. But I don't want to receive any mail unless an actual ERROR-level entry have been logged, so I've set the bufferSize to a big number. My problem is, the mail target isn't being triggered when the ERROR-level entry is logged, only when the actual bufferSize is hit, meaning I'm not receiving any mails at all since the bufferSize is so big. My NLog.config up like this:

<targets>
  <target name="mailautoflush" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Error">
    <target name="mailbuffer" xsi:type="BufferingWrapper" bufferSize="1000000">
      <target name="mail" xsi:type="Mail" ... />
    </target>
  </target>
</targets>
<rules>
    <logger name="*" minlevel="Info" writeTo="mailautoflush"></logger>
</rules>
```

What am I doing wrong? Also, is there a better way to do this? Using the AutoFlushWrapper/BufferingWrapper trick seems like a hack. Thanks!

答:
It only executes the flush after the triggering LogEvent has reported that it has reached its final target. Since the LogEvent is parked in the buffer, then the flush is never fired.

Created PR: https://github.com/NLog/NLog/pull/2042

Title: AutoFlushWrapper with Mail target

Body:
I'm trying to send myself an email with the latest log entries when an error occurs. But I don't want to receive any mail unless an actual ERROR-level entry have been logged, so I've set the bufferSize to a big number. My problem is, the mail target isn't being triggered when the ERROR-level entry is logged, only when the actual bufferSize is hit, meaning I'm not receiving any mails at all since the bufferSize is so big. My NLog.config up like this:

<targets>
  <target name="mailautoflush" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Error">
    <target name="mailbuffer" xsi:type="BufferingWrapper" bufferSize="1000000">
      <target name="mail" xsi:type="Mail" ... />
    </target>
  </target>
</targets>
<rules>
    <logger name="*" minlevel="Info" writeTo="mailautoflush"></logger>
</rules>

What am I doing wrong? Also, is there a better way to do this? Using the AutoFlushWrapper/BufferingWrapper trick seems like a hack. Thanks!


问:
Ajax ignores html validation
```<code>$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: $('#editOrderContent').attr('action'),
        data: data,

        success: function (html) {
            if (html.error) {
                $('.wrap_result')
                    .text(html.error)
                    .fadeIn(500).delay(3000).fadeOut(500);
            }
            else if (html.success) {
                $('#summary').before(html.tdProduct);
                $('#summary_qty').text(html.summaries['qty']);
                $('#summary_price').text(html.summaries['price'] + ' $.');
                $('#summary_sum').text(html.summaries['sum'] + ' $.');
                $('#product_id').val('');
                $('#qty').val(1);
            }
        }
    });
});
</code>```

These 2 fields has required attributes but ajax still completing even with empty values in these fields, also ajax ignores min value of #qty field

Why is this happening?

答:
e.preventDefault tells the event NOT to perform it's default action of submitting the form.

You're then making the fields required. That's fine - but they'll only be checked on submit. The form isn't actually being submitted at any point, you've told it to prevent that action.

You need to add a $('#form').submit(); Or add required directly to the html markup.

EDIT: Much more code added to the question. This may no longer apply.

Title: Ajax ignores html validation

Body:
$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

    $.ajax({
        type: 'POST',
        dataType: 'JSON',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: $('#editOrderContent').attr('action'),
        data: data,

        success: function (html) {
            if (html.error) {
                $('.wrap_result')
                    .text(html.error)
                    .fadeIn(500).delay(3000).fadeOut(500);
            }
            else if (html.success) {
                $('#summary').before(html.tdProduct);
                $('#summary_qty').text(html.summaries['qty']);
                $('#summary_price').text(html.summaries['price'] + ' $.');
                $('#summary_sum').text(html.summaries['sum'] + ' $.');
                $('#product_id').val('');
                $('#qty').val(1);
            }
        }
    });
});

These 2 fields has required attributes but ajax still completing even with empty values in these fields, also ajax ignores min value of #qty field

Why is this happening?


问:
AttributeError when clicking on new button added by custom module
I am trying to add a new button on a res.partner form view (base.view_partner_form) by custom module to open a new browser tab, but I am getting the following error:

```<code>    Traceback (most recent call last):
  File "/opt/odoo/odoo-server/openerp/http.py", line 540, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo-server/openerp/http.py", line 577, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/odoo-server/openerp/http.py", line 313, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo-server/openerp/service/model.py", line 118, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo-server/openerp/http.py", line 310, in checked_call
    return self.endpoint(*a, **kw)
  File "/opt/odoo/odoo-server/openerp/http.py", line 806, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo-server/openerp/http.py", line 406, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo-server/addons/web/controllers/main.py", line 948, in call_button
    action = self._call_kw(model, method, args, {})
  File "/opt/odoo/odoo-server/addons/web/controllers/main.py", line 936, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
AttributeError: 'res.partner' object has no attribute 'g_search'
</code>```

The button appears but I am getting stuck with that error. These are my files contents:

mymodule.py

```<code>import openerp
from openerp.osv import fields, osv, orm
from openerp import models

class cant_neg_gs(osv.osv):
    _inherit = 'res.partner'

    @api.multi
    def g_search(self):
        res = {
            'type': 'ir.actions.act_url',
            'url': 'http://www.myurl.com',
            'target': 'new',
        }
    return res
</code>```

mymodule.xml

```<code><?xml version="1.0"?>
<openerp>
    <data>
        <record id="gs_cant_neg_view" model="ir.ui.view">
            <field name="name">res.partner.cant_neg_gs.inherit</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_partner_form"/>
            <field name="arch" type="xml">
                <xpath expr="//field[@name='title']" position="after">
                    <button string="Buscar empresa" type="object" name="g_search" class="oe_highlight"/>
                </xpath>
            </field>
        </record>
    </data>
</openerp>
</code>```

__init__.py

```<code>import cant_neg_gs
</code>```

__openerp__.py

```<code>{
    'name': 'My Module,
    'version': '1.0',
    'category': 'Uncategorized',
    'summary': 'Summary',
    'sequence': 2,
    'description': """

Info
====================================================
More info

Things :
-------------------------------
* Button
""",
    'author': 'Name',
    'website': 'https://example.com',
    'depends': ['base',],
    'data': [
        'cant_neg_gs.xml',
    ],
    'installable': True,
    'application': True,
    'auto_install': False,
}
</code>```

Thank you very much in advance for your help!

Regards.

答:
You have import import cant_neg_gs class name, but you must import file. name not a class name Ex-: import mymodule.

There is one more issue in you code, you can follow below code.

```<code>from openerp import models,fields,api
class res_partner(models.Model):
    _inherit="res.partner"

    @api.multi
    def g_search(self):
        res = {
            'type': 'ir.actions.act_url',
            'url': 'http://www.myurl.com',
            'target': 'new',
        }
        return res
</code>```

In your file api is not imported, you have used @api.multi that's why you must import api.

This may help you.

Body:
I am trying to add a new button on a res.partner form view (base.view_partner_form) by custom module to open a new browser tab, but I am getting the following error:

    Traceback (most recent call last):
  File "/opt/odoo/odoo-server/openerp/http.py", line 540, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/opt/odoo/odoo-server/openerp/http.py", line 577, in dispatch
    result = self._call_function(**self.params)
  File "/opt/odoo/odoo-server/openerp/http.py", line 313, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/opt/odoo/odoo-server/openerp/service/model.py", line 118, in wrapper
    return f(dbname, *args, **kwargs)
  File "/opt/odoo/odoo-server/openerp/http.py", line 310, in checked_call
    return self.endpoint(*a, **kw)
  File "/opt/odoo/odoo-server/openerp/http.py", line 806, in __call__
    return self.method(*args, **kw)
  File "/opt/odoo/odoo-server/openerp/http.py", line 406, in response_wrap
    response = f(*args, **kw)
  File "/opt/odoo/odoo-server/addons/web/controllers/main.py", line 948, in call_button
    action = self._call_kw(model, method, args, {})
  File "/opt/odoo/odoo-server/addons/web/controllers/main.py", line 936, in _call_kw
    return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
AttributeError: 'res.partner' object has no attribute 'g_search'

The button appears but I am getting stuck with that error. These are my files contents:

mymodule.py

import openerp
from openerp.osv import fields, osv, orm
from openerp import models

class cant_neg_gs(osv.osv):
    _inherit = 'res.partner'

    @api.multi
    def g_search(self):
        res = {
            'type': 'ir.actions.act_url',
            'url': 'http://www.myurl.com',
            'target': 'new',
        }
    return res

mymodule.xml

<?xml version="1.0"?>
<openerp>
    <data>
        <record id="gs_cant_neg_view" model="ir.ui.view">
            <field name="name">res.partner.cant_neg_gs.inherit</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_partner_form"/>
            <field name="arch" type="xml">
                <xpath expr="//field[@name='title']" position="after">
                    <button string="Buscar empresa" type="object" name="g_search" class="oe_highlight"/>
                </xpath>
            </field>
        </record>
    </data>
</openerp>

__init__.py

import cant_neg_gs

__openerp__.py

{
    'name': 'My Module,
    'version': '1.0',
    'category': 'Uncategorized',
    'summary': 'Summary',
    'sequence': 2,
    'description': """

Info
====================================================
More info

Things :
-------------------------------
* Button
""",
    'author': 'Name',
    'website': 'https://example.com',
    'depends': ['base',],
    'data': [
        'cant_neg_gs.xml',
    ],
    'installable': True,
    'application': True,
    'auto_install': False,
}

Thank you very much in advance for your help!

Regards.

Body:
You have import import cant_neg_gs class name, but you must import file. name not a class name Ex-: import mymodule.

There is one more issue in you code, you can follow below code.

from openerp import models,fields,api
class res_partner(models.Model):
    _inherit="res.partner"

    @api.multi
    def g_search(self):
        res = {
            'type': 'ir.actions.act_url',
            'url': 'http://www.myurl.com',
            'target': 'new',
        }
        return res

In your file api is not imported, you have used @api.multi that's why you must import api.

This may help you.


问:
Search for lines that contain anything but alphabetic characters, dots and hyphens
I'm struggling to create a RegEx pattern to match lines that contain anything but a-zA-Z ,  . and -

So I don't want to match hello-world.txt , but I would like to match hello-world123.txt or hello-world(copy).txt

答:
Just need match full string with:

/^[a-zA-Z.-]+$/

[a-zA-Z.-] - match any of those characters

+ - repeat one or more

^, $ - anchor to start and end of the string


问:
how to remove the array values when table view cell is not selected in objective c?
This is my code

```<code> - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}
</code>```

when the table cell values are selected the selected values are store in the valueselectedcell array it's working fine.Now how to remove the values in the array when i deselect the rows .

答:
I have not enough reputation to comment, so i'm posting it as a answer. The answer from @Dipankar Das is totally correct, i'm just trying to answer the question from OP's comment.

if unselected cell value is same to the selected value of the cell it means it will remove the selected value too in the array how to validate that.

Update didSelectRowAtIndexPath & didDeselectRowAtIndexPath method like this-

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *indexofselectedcell = [[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    [indexofselectedcell addObject:indexPath];

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([indexofselectedcell containsObject: indexPath]) {
        NSInteger anIndex=[indexofselectedcell indexOfObject:indexPath];
        [indexofselectedcell removeObjectAtIndex:anIndex];
        [valueofselectedcell removeObjectAtIndex:anIndex];
    }
}
</code>```

Body:
This is my code

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}

when the table cell values are selected the selected values are store in the valueselectedcell array it's working fine.Now how to remove the values in the array when i deselect the rows .

Body:
I have not enough reputation to comment, so i'm posting it as a answer. The answer from @Dipankar Das is totally correct, i'm just trying to answer the question from OP's comment.

if unselected cell value is same to the selected value of the cell it means it will remove the selected value too in the array how to validate that.

Update didSelectRowAtIndexPath & didDeselectRowAtIndexPath method like this-

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *indexofselectedcell = [[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    [indexofselectedcell addObject:indexPath];

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([indexofselectedcell containsObject: indexPath]) {
        NSInteger anIndex=[indexofselectedcell indexOfObject:indexPath];
        [indexofselectedcell removeObjectAtIndex:anIndex];
        [valueofselectedcell removeObjectAtIndex:anIndex];
    }
}