问:
Angular2 - update bound property immediately
at the beginning I have a simple question: "when and why are bindings in Angular2 evaluated/updated?"

I'd like to achieve the bound property will be updated immediately when the source one is set.

This very simple plunker demo demonstrates the behavior:

Plunker demo

And the most interesting part of the code:

```<code>setValue() {
   console.log(this.childComponent.prop);
   this.propValue = "button clicked";
   //NOW I WANT TO GET THE NEW VALUE
   console.log(this.childComponent.prop);
}
</code>```

The updated interpolation in template says the binding is evaluated correctly and the destination property is updated, however sometimes later out of setValue method scope.

Why do I want this behavior?

I know this way of work with components interaction is not necessary, but ... I have a more complex custom form-control (implementing ControlValueAccessor). Now I am working on some "business-process": the ngModel of this complex component is part of more complex object that can be accessed by more components which can generally affect each other's part of the object.

Simplified example:

Model

```<code>{
 public modelA: SomeClasss; <-- this is ngModel of comp. A
 public modelB: SomeClasss; {...} <-- this is ngModel of comp. B
}
</code>```

Meanwhile somewhere else in the code:

```<code>update(X: SomeClass) {
    this.modelA = X;
    this.componentA.updateMagicUI();
}
</code>```

Where the updateMagicUI method carries some complex logic working with the ComponentA's internal structures based on it's newly set value. Note that I want to execute this logic if and only if it is invoked explicitly, not every time the value is changed.

答:
One method suggested in this answer to trigger change detection is to call the tick method of ApplicationRef:

```<code>import { ..., ApplicationRef } from '@angular/core'
...

export class App {
  ...
  constructor(private applicationRef: ApplicationRef) {
    ...
  }
  setValue() {
    console.log(this.childComponent.prop);
    this.propValue = "button clicked";
    this.applicationRef.tick(); // Trigger change detection
    console.log(this.childComponent.prop);
  }
}
</code>```

You can test it in this plunker.

Body:
at the beginning I have a simple question: "when and why are bindings in Angular2 evaluated/updated?"

I'd like to achieve the bound property will be updated immediately when the source one is set.

This very simple plunker demo demonstrates the behavior:

Plunker demo

And the most interesting part of the code:

setValue() {
   console.log(this.childComponent.prop);
   this.propValue = "button clicked";
   //NOW I WANT TO GET THE NEW VALUE
   console.log(this.childComponent.prop);
}

The updated interpolation in template says the binding is evaluated correctly and the destination property is updated, however sometimes later out of setValue method scope.

Why do I want this behavior?

I know this way of work with components interaction is not necessary, but ... I have a more complex custom form-control (implementing ControlValueAccessor). Now I am working on some "business-process": the ngModel of this complex component is part of more complex object that can be accessed by more components which can generally affect each other's part of the object.

Simplified example:

Model

{
 public modelA: SomeClasss; <-- this is ngModel of comp. A
 public modelB: SomeClasss; {...} <-- this is ngModel of comp. B
}

Meanwhile somewhere else in the code:

update(X: SomeClass) {
    this.modelA = X;
    this.componentA.updateMagicUI();
}

Where the updateMagicUI method carries some complex logic working with the ComponentA's internal structures based on it's newly set value. Note that I want to execute this logic if and only if it is invoked explicitly, not every time the value is changed.

Body:
One method suggested in this answer to trigger change detection is to call the tick method of ApplicationRef:

import { ..., ApplicationRef } from '@angular/core'
...

export class App {
  ...
  constructor(private applicationRef: ApplicationRef) {
    ...
  }
  setValue() {
    console.log(this.childComponent.prop);
    this.propValue = "button clicked";
    this.applicationRef.tick(); // Trigger change detection
    console.log(this.childComponent.prop);
  }
}

You can test it in this plunker.


来源: stackexchange

问:
iOS/iPhone Reachability - How to only check when internet is lost/not reachable using Reachability.m/.h
Currently i am using the class by apple reachability.m/.h and it works, except it notifies me for any change, where as i would like to only notify the user if the network is not reachable. Currently if i have a internet connection and then loose the network it tells me. However when you reconnect to the network it also tells me, which i do not want. I want it to only tell me when there is a loss/no network.

I believe it has something to do with the call:

```<code>- (void)viewWillAppear:(BOOL)animated
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter]
          addObserver:self
             selector:@selector(checkNetworkStatus:)
                 name:kReachabilityChangedNotification
               object:nil];

    internetReachable = [[Reachability
                         reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName:
                     @"www.google.ca"] retain];
    [hostReachable startNotifier];

    // now patiently wait for the notification
}
</code>```

when calling -[NSNotificationCenter addObserver:selector:name:object:], does the name have any other function then being literally a name? this is my first time using NSNotificationCenter so i am not well versed in this matter.

EDIT:

Here is my checkNetworkStatus function: (The problem is i am getting "NotReachable" as the network connection is coming back and NSAlert goes off multiple times)

```<code>- (void) checkNetworkStatus:(NSNotification *)notice
{
        // called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)

{
    case NotReachable:
    {
        UIAlertView * alert  = [[UIAlertView alloc] initWithTitle:@"Network Failed" message:@"Please check your connection and try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ];
        [alert show];
        NSLog(@"The internet is down.");

        break;

    }
    case ReachableViaWiFi:
    {
        NSLog(@"The internet is working via WIFI.");

        break;

    }
    case ReachableViaWWAN:
    {
        NSLog(@"The internet is working via WWAN.");

        break;

    }
}

NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)

{
    case NotReachable:
    {
        NSLog(@"A gateway to the host server is down.");

        break;

    }
    case ReachableViaWiFi:
    {
        NSLog(@"A gateway to the host server is working via WIFI.");

        break;

    }
    case ReachableViaWWAN:
    {
        NSLog(@"A gateway to the host server is working via WWAN.");

        break;

    }
}
</code>```

}

答:
Reachability will send a notification when the status has changed, but what you do with that notification is entirely up to you.  If you don't want to tell the user that the network is back, you don't have to.

The "name" parameter in the NSNotificationCenter method indicates what notification you are subscribing to.  When an object posts a notification, it does so with a particular name.

ContentLicense: CC BY-SA 2.5

Body:
Currently i am using the class by apple reachability.m/.h and it works, except it notifies me for any change, where as i would like to only notify the user if the network is not reachable. Currently if i have a internet connection and then loose the network it tells me. However when you reconnect to the network it also tells me, which i do not want. I want it to only tell me when there is a loss/no network.

I believe it has something to do with the call:

- (void)viewWillAppear:(BOOL)animated
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter]
          addObserver:self
             selector:@selector(checkNetworkStatus:)
                 name:kReachabilityChangedNotification
               object:nil];

    internetReachable = [[Reachability
                         reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName:
                     @"www.google.ca"] retain];
    [hostReachable startNotifier];

    // now patiently wait for the notification
}

when calling -[NSNotificationCenter addObserver:selector:name:object:], does the name have any other function then being literally a name? this is my first time using NSNotificationCenter so i am not well versed in this matter.

EDIT:

Here is my checkNetworkStatus function: (The problem is i am getting "NotReachable" as the network connection is coming back and NSAlert goes off multiple times)

- (void) checkNetworkStatus:(NSNotification *)notice
{
        // called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)

{
    case NotReachable:
    {
        UIAlertView * alert  = [[UIAlertView alloc] initWithTitle:@"Network Failed" message:@"Please check your connection and try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ];
        [alert show];
        NSLog(@"The internet is down.");

        break;

    }
    case ReachableViaWiFi:
    {
        NSLog(@"The internet is working via WIFI.");

        break;

    }
    case ReachableViaWWAN:
    {
        NSLog(@"The internet is working via WWAN.");

        break;

    }
}

NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)

{
    case NotReachable:
    {
        NSLog(@"A gateway to the host server is down.");

        break;

    }
    case ReachableViaWiFi:
    {
        NSLog(@"A gateway to the host server is working via WIFI.");

        break;

    }
    case ReachableViaWWAN:
    {
        NSLog(@"A gateway to the host server is working via WWAN.");

        break;

    }
}

}


问:
How to convert specific algorithm with streams
The task is to return String with sum of every letter. The input is also a String.

For example

```<code>input: dasamdw
output: s1d2a2m1w1
</code>```

I came out with a simple quick algorithm:

```<code>private String method(String input) {
    Map<String, Integer> integerMap = new HashMap<>();
    for( char c : input.toCharArray()) {
        String key = String.valueOf(c);
        if(integerMap.containsKey(key)) {
            integerMap.put(key, integerMap.get(key) + 1);
        } else {
            integerMap.put(key, 1);
        }
    }

    StringBuilder sb = new StringBuilder();
    for(Map.Entry<String, Integer> e : integerMap.entrySet()) {
        sb.append(e.getKey());
        sb.append(e.getValue());
    }
    return sb.toString();
}
</code>```

But I really would like to use streams for that, someting like:

```<code>private String method(String input) {
    Map<Character, Integer> collect =
        input.chars().
        mapToObj(i -> (char)i).collect(Collectors.groupingBy(Function.identity(), Collectors.counting() ));

    return collect.entrySet()
                    .stream()
                    .map(entry -> entry.getKey() + "" + entry.getValue())
                    .collect(Collectors.joining(""));
}
</code>```

But I can't figure out the right groupingBy part...

答:
Here's my version, I added some comments so you can get by easier:

```<code>package com.company;

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class Main {

    public static void main(String[] args) throws InterruptedException {

        // your given string
        String x = "dasamdw";
        // map to store each letter:numberOfRepetition pairs (I used   TreeMap just to print letters alphabetically)
        Map<String, Integer> letters = new TreeMap<>();

        // stream of char[] from the given string, add letter to the map if it doesnt exist with value 1
        // if it already exists, just increase value by 1
        Arrays.stream(x.split("")).forEach(y -> letters.put(y, letters.get(y) == null ? 1 : letters.get(y) + 1));

        // loop over map and print out the results of lambda above
        for (Map.Entry s : letters.entrySet()) {
            System.out.print(s.getKey() + "" + s.getValue());
        }
    }
}
</code>```

You can also replace ternary with Merge

ContentLicense: CC BY-SA 3.0

Body:
The task is to return String with sum of every letter. The input is also a String.

For example

input: dasamdw
output: s1d2a2m1w1

I came out with a simple quick algorithm:

private String method(String input) {
    Map<String, Integer> integerMap = new HashMap<>();
    for( char c : input.toCharArray()) {
        String key = String.valueOf(c);
        if(integerMap.containsKey(key)) {
            integerMap.put(key, integerMap.get(key) + 1);
        } else {
            integerMap.put(key, 1);
        }
    }

    StringBuilder sb = new StringBuilder();
    for(Map.Entry<String, Integer> e : integerMap.entrySet()) {
        sb.append(e.getKey());
        sb.append(e.getValue());
    }
    return sb.toString();
}

But I really would like to use streams for that, someting like:

private String method(String input) {
    Map<Character, Integer> collect =
        input.chars().
        mapToObj(i -> (char)i).collect(Collectors.groupingBy(Function.identity(), Collectors.counting() ));

    return collect.entrySet()
                    .stream()
                    .map(entry -> entry.getKey() + "" + entry.getValue())
                    .collect(Collectors.joining(""));
}

But I can't figure out the right groupingBy part...

Body:
Here's my version, I added some comments so you can get by easier:

package com.company;

import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;

public class Main {

    public static void main(String[] args) throws InterruptedException {

        // your given string
        String x = "dasamdw";
        // map to store each letter:numberOfRepetition pairs (I used   TreeMap just to print letters alphabetically)
        Map<String, Integer> letters = new TreeMap<>();

        // stream of char[] from the given string, add letter to the map if it doesnt exist with value 1
        // if it already exists, just increase value by 1
        Arrays.stream(x.split("")).forEach(y -> letters.put(y, letters.get(y) == null ? 1 : letters.get(y) + 1));

        // loop over map and print out the results of lambda above
        for (Map.Entry s : letters.entrySet()) {
            System.out.print(s.getKey() + "" + s.getValue());
        }
    }
}

You can also replace ternary with Merge


问:
Using DB2 Text Search with ranked results on small VARCHAR column
(edit) DB2 10.5.0 on Linux

Hoping someone might have some insight.  I am more or less forced to use DB2, so cannot bolt in something like elasticsearch, etc.

Say I have a simple table with single column COMPANY_NAME VARCHAR(240).  Has db2ts running and a text search index on it.

I have company names like this:

```<code>MY GENERAL COMPANY
MY COMPANY
MY SUPER AWESOME COMPANY
MY COMPANY NAMED DUDE
MYLO COMPANIO
</code>```

I execute query:

```<code>SELECT COMPANY_NAME FROM COMPANY_TABLE WHERE CONTAINS('MY COMPANY~0.6') = 1
</code>```

I can use SCORE to ORDER the results, but all SCORE does is count the number of times the word(s) appear in the text.  So in this case SCORE will sort that last name to the bottom, but all other names are on equal par.  Not helpful.

What I really want is an "affinity ranking" based on how CONTAINS decided to select the result set.  Intuitively I would expect a human to accept this ranked list as an answer:

```<code>COMPANY_NAME
---------------------------
MY COMPANY
MY COMPANY NAMED DUDE
MY GENERAL COMPANY
MY SUPER AWESOME COMPANY
MYLO COMPANIO
</code>```

I get the result set from CONTAINS as above, which is good.  I just cannot figure out how to get the result set to ORDER BY "affinity to search terms"

答:
Just a guess...think you want to use SCORE()...it shouldn't be returning 1, it should return a value between 0 and 1.

```<code>SELECT
   COMPANY_NAME
   , integer(score(COMPANY_NAME,'MY COMPANY~') * 100) as relevance
FROM COMPANY_TABLE
WHERE CONTAINS(COMPANY_NAME,'MY COMPANY~0.6') = 1
order by relevance desc
</code>```

Body:
(edit) DB2 10.5.0 on Linux

Hoping someone might have some insight.  I am more or less forced to use DB2, so cannot bolt in something like elasticsearch, etc.

Say I have a simple table with single column COMPANY_NAME VARCHAR(240).  Has db2ts running and a text search index on it.

I have company names like this:

MY GENERAL COMPANY
MY COMPANY
MY SUPER AWESOME COMPANY
MY COMPANY NAMED DUDE
MYLO COMPANIO

I execute query:

SELECT COMPANY_NAME FROM COMPANY_TABLE WHERE CONTAINS('MY COMPANY~0.6') = 1

I can use SCORE to ORDER the results, but all SCORE does is count the number of times the word(s) appear in the text.  So in this case SCORE will sort that last name to the bottom, but all other names are on equal par.  Not helpful.

What I really want is an "affinity ranking" based on how CONTAINS decided to select the result set.  Intuitively I would expect a human to accept this ranked list as an answer:

COMPANY_NAME
---------------------------
MY COMPANY
MY COMPANY NAMED DUDE
MY GENERAL COMPANY
MY SUPER AWESOME COMPANY
MYLO COMPANIO

I get the result set from CONTAINS as above, which is good.  I just cannot figure out how to get the result set to ORDER BY "affinity to search terms"

Body:
Just a guess...think you want to use SCORE()...it shouldn't be returning 1, it should return a value between 0 and 1.

SELECT
   COMPANY_NAME
   , integer(score(COMPANY_NAME,'MY COMPANY~') * 100) as relevance
FROM COMPANY_TABLE
WHERE CONTAINS(COMPANY_NAME,'MY COMPANY~0.6') = 1
order by relevance desc


问:
How to dynamically assign datasource to listview
I am having a problem with dynamically assigning datasource to listview.

For example I have list of receivedBonuses(Bonus), receivedLeaves(Leave) and I want listview to display those list items depending on what link button user clicked.

Researching internet and stackoverflow.com i found 3 solutions:

Using repeater inside the listview. But in my case, I could not apply it to my case and i got totally confused

Using nested listviews. I tried to do like this:

```<code>       <asp:ListView ID = "bonuses" runat="server" DataSource ='<%# Eval("received_bonuses") %>' >
        <ItemTemplate>

            <tr>

                <td><%# Eval("bonus_desc")%></td>

                <td><%# Eval("bonus_type")%></td>

            </tr>
            </ItemTemplate>
                 <LayoutTemplate>

             <table>

                    <tr>

                        <th>Bonus Description</th>

                        <th>Bonus Received Date</th>

                    </tr>

                    <tr ID="itemPlaceholder" runat="server" />

                        </table>

        </LayoutTemplate>
</code>```

```<code>             <table>

                    <tr>

                        <th>Bonus Description</th>

                        <th>Bonus Received Date</th>

                    </tr>

                    <tr ID="itemPlaceholder" runat="server" />

                        </table>

        </LayoutTemplate>

</asp:ListView>

    <br />
</code>```

and on back code I tried to write like this:

  protected void dataBound(object sender, ListViewItemEventArgs e)
        {
            this.DataBindChildren();

```<code>    }
</code>```

It didn't give any errors it just didn't work.

Using data pager

I have no idea how to apply it to my case.

Any help is appreciated.

Thanks a lot.

答:
All you have to do on the server side is change the DataSource or DataSourceID property and  call DataBind on the ListView.

You have to make sure when using <%# Eval("") %> syntax that the objects you are binding to have those properties that are named in the Eval. So you may have a problem with with switching datasources when your properties are prepended with the typename and underscore.
That being said.  There are 2 options you have an changing a data source.  In the click event of the button or whatever switching mechanism you are using you can just write something like.

Not using a DataSource in the markup:

```<code>List<Bonus> bonusList = GetBonuses();
MyListView.DataSource = bonusList;
MyListView.DataBind();
</code>```

Using a DataSource in the markup:

```<code>//where bonus list would be the id of the datasource in the markup
MyListView.DataSourceID= "BonusList";

MyListView.DataBind();
</code>```

Body:
I am having a problem with dynamically assigning datasource to listview.

For example I have list of receivedBonuses(Bonus), receivedLeaves(Leave) and I want listview to display those list items depending on what link button user clicked.

Researching internet and stackoverflow.com i found 3 solutions:

Using repeater inside the listview. But in my case, I could not apply it to my case and i got totally confused

Using nested listviews. I tried to do like this:

       <asp:ListView ID = "bonuses" runat="server" DataSource ='<%# Eval("received_bonuses") %>' >
        <ItemTemplate>

                <%# Eval("bonus_desc")%>

                <%# Eval("bonus_type")%>

            </ItemTemplate>
                 <LayoutTemplate>

                        Bonus Description

                        Bonus Received Date

        </LayoutTemplate>

                        Bonus Description

                        Bonus Received Date

        </LayoutTemplate>

</asp:ListView>

and on back code I tried to write like this:

  protected void dataBound(object sender, ListViewItemEventArgs e)
        {
            this.DataBindChildren();

    }

It didn't give any errors it just didn't work.

Using data pager

I have no idea how to apply it to my case.

Any help is appreciated.

Thanks a lot.

Body:
All you have to do on the server side is change the DataSource or DataSourceID property and  call DataBind on the ListView.

You have to make sure when using <%# Eval("") %> syntax that the objects you are binding to have those properties that are named in the Eval. So you may have a problem with with switching datasources when your properties are prepended with the typename and underscore.
That being said.  There are 2 options you have an changing a data source.  In the click event of the button or whatever switching mechanism you are using you can just write something like.

Not using a DataSource in the markup:

List<Bonus> bonusList = GetBonuses();
MyListView.DataSource = bonusList;
MyListView.DataBind();

Using a DataSource in the markup:

//where bonus list would be the id of the datasource in the markup
MyListView.DataSourceID= "BonusList";

MyListView.DataBind();


问:
How to cache packages which have been installed via `apt-get` in Travis CI?
So, with my .travis.yml, I'm installing some packages via apt-get which doesn't take too long to download, but a very long time to install.

Is there a way to make Travis CI remember the installed packages, so I won't have to install them from scratch for every build?

答:
There seems to be no easy or convenient way to cache all of the packages you need to install via apt-get. According to the Caching Dependencies and Directories documentation, Travis CI currently only provides "convenience" caching for Bundler, CocoaPods, Yarn (and a few others).

However! If you can determine where apt-get installs each of the packages you need (as install locations vary from one package to the next), you can cache each of those install directories individually by following the steps in the Arbitrary directories documentation.

I hope this helps. Please let me know if you have any other questions and I'd be happy to help in any way I can. Cheers!

ContentLicense: CC BY-SA 4.0


问:
Switching the value with order
Is there a pythonic shorter version for the flowing code:</p>

```<code>def method(a,b)
    if a > b:
        pass
    else:
        a, b = b, a
</code>```

答:
This is shorter:

```<code>def method(a,b)
    if a <= b:
        a, b = b, a
</code>```

I suppose you could compress it into one line, but I don't know if it counts as more readable:

```<code>(a,b) = (b,a) if a <= b else (a,b)
</code>```

Title: Switching the value with order

Body:
Is there a pythonic shorter version for the flowing code:

def method(a,b)
    if a > b:
        pass
    else:
        a, b = b, a

Body:
This is shorter:

def method(a,b)
    if a <= b:
        a, b = b, a

I suppose you could compress it into one line, but I don't know if it counts as more readable:

(a,b) = (b,a) if a <= b else (a,b)


问:
How to increment numbers on the end of variables?
I have a Python/Tkinter program and I am trying to increment some numbers that are at the end of a variable used for tk.Entry boxes.

For example, self.output0, self.output1, self.output2, etc

(Sorry, my code is long so I tried shortening it up for an example.)

```<code>    self.entries = []
    self.output0 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0')
    self.output0.grid(column=0, row=6, columnspan=5, padx=1)

    self.output1 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0')
    self.output1.grid(column=0, row=7, columnspan=5, padx=1)
</code>```

I grab the users input with another entry box such as 'self.first_entry' and run a SQL query on the user input.

For example:

```<code>class Adder(ttk.Frame):
    """The adders gui and functions."""
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()

    def authenticate(self):
        return pypyodbc.connect('Driver={SQL Server};Server=MYSERVERNAME;Database=MYDATABASENAME;Trusted_Connection=yes;')

    def calculate(self):
        firstname = str(self.first_entry.get()) # converts user entry into variable
        lastname = str(self.last_entry.get())
        license = str(self.lic_entry.get())

        try:
            connection = self.authenticate()
        except pypyodbc.Error as ex:
            sqlstate = ex.args[0]
            if sqlstate == '28000':
                self.output0.delete(0, END)
                self.output0.insert(0,"You do not have access.")
        cursor = connection.cursor()
        if (firstname and not lastname and not license):  # "You entered first name."
            SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER "
                "FROM MyTABLEName "   # table name
                "with (nolock)"
                "WHERE FIRSTNAME LIKE ?")
            Values = [firstname + '%']
        else:
            SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER "
                "FROM MyTABLEName "   # table name
                "(nolock)"
                "WHERE FIRSTNAME LIKE ? AND LASTNAME LIKE ? AND LICNUMBER LIKE ?")
            Values = [firstname + '%', lastname + '%', '%' + license + '%']
        cursor.execute(SQLCommand,Values)
        results = cursor.fetchmany(10)
        if results:
            self.output0.delete(0, END)  # clears entry
            self.output0.insert(0,results[0]) # enters results in entry
            self.output1.delete(0, END)  # clears entry
            self.output1.insert(0,results[1]) # enters results in entry
            self.output2.delete(0, END)  # clears entry
            self.output2.insert(0,results[2]) # enters results in entry
            self.output3.delete(0, END)  # clears entry
            self.output3.insert(0,results[3]) # enters results in entry
            self.output4.delete(0, END)  # clears entry
            self.output4.insert(0,results[4]) # enters results in entry
            connection.close()
        else:
            self.output0.delete(0, END)
            self.output0.insert(0,"There are no records for this input.")
</code>```

The above will output 5 rows from the database.

I am wanting to shorten the code up.  How can I take the below and write it so that I do not have to repeat

```<code>            self.output0.delete(0, END)  # clears entry
            self.output0.insert(0,results[0]) # enters results in entry
            self.output1.delete(0, END)  # clears entry
            self.output1.insert(0,results[1]) # enters results in entry
            2
            2
            3
            3
            ...etc
</code>```

I want to increment the outputX and the number in results[x]

This below is what I have been trying but it is not working:

```<code>    results = cursor.fetchmany(10)
    i = 0
    myDelete = (self.output%d.delete(0, END) % (i))
    myInsert = (sef.output%d.insert(0,results[0]) % (i))

    if results:
        for int(i) in myDelete, myInsert (i):
            i += 0
            print (myDelete)  # clears entry
            print (myInsert)  # enters results in entry
        connection.close()
    else:
            self.output0.delete(0, END)
            self.output0.insert(0,"There are no records for this input.")
</code>```

Right now I am getting a "Can't assign to function call" error but I am not even sure if I am going about this the right way.

答:
You could add all the outputs to a list:

```<code>self.outputs = [self.output0, self.output1, self.output2] #etc...
</code>```

And then loop through them:

```<code>for output in self.outputs:
    output.delete(0, END) #etc...
</code>```

You can even create outputs like such:

```<code>self.outputs = []

for i in range(4):
   output = tk.Entry(
       self, width=149, justify='center', bd='0', bg='#E0E0E0'
   )
   output.grid(column=0, row=6, columnspan=5, padx=1)
   self.outputs.append(output)
</code>```

Though you would need to add a way to change the row number and whatever else needs to be different for each iteration.

Body:
I have a Python/Tkinter program and I am trying to increment some numbers that are at the end of a variable used for tk.Entry boxes.

For example, self.output0, self.output1, self.output2, etc

(Sorry, my code is long so I tried shortening it up for an example.)

    self.entries = []
    self.output0 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0')
    self.output0.grid(column=0, row=6, columnspan=5, padx=1)

    self.output1 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0')
    self.output1.grid(column=0, row=7, columnspan=5, padx=1)

I grab the users input with another entry box such as 'self.first_entry' and run a SQL query on the user input.

For example:

class Adder(ttk.Frame):
    """The adders gui and functions."""
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()

    def authenticate(self):
        return pypyodbc.connect('Driver={SQL Server};Server=MYSERVERNAME;Database=MYDATABASENAME;Trusted_Connection=yes;')

    def calculate(self):
        firstname = str(self.first_entry.get()) # converts user entry into variable
        lastname = str(self.last_entry.get())
        license = str(self.lic_entry.get())

        try:
            connection = self.authenticate()
        except pypyodbc.Error as ex:
            sqlstate = ex.args[0]
            if sqlstate == '28000':
                self.output0.delete(0, END)
                self.output0.insert(0,"You do not have access.")
        cursor = connection.cursor()
        if (firstname and not lastname and not license):  # "You entered first name."
            SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER "
                "FROM MyTABLEName "   # table name
                "with (nolock)"
                "WHERE FIRSTNAME LIKE ?")
            Values = [firstname + '%']
        else:
            SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER "
                "FROM MyTABLEName "   # table name
                "(nolock)"
                "WHERE FIRSTNAME LIKE ? AND LASTNAME LIKE ? AND LICNUMBER LIKE ?")
            Values = [firstname + '%', lastname + '%', '%' + license + '%']
        cursor.execute(SQLCommand,Values)
        results = cursor.fetchmany(10)
        if results:
            self.output0.delete(0, END)  # clears entry
            self.output0.insert(0,results[0]) # enters results in entry
            self.output1.delete(0, END)  # clears entry
            self.output1.insert(0,results[1]) # enters results in entry
            self.output2.delete(0, END)  # clears entry
            self.output2.insert(0,results[2]) # enters results in entry
            self.output3.delete(0, END)  # clears entry
            self.output3.insert(0,results[3]) # enters results in entry
            self.output4.delete(0, END)  # clears entry
            self.output4.insert(0,results[4]) # enters results in entry
            connection.close()
        else:
            self.output0.delete(0, END)
            self.output0.insert(0,"There are no records for this input.")

The above will output 5 rows from the database.

I am wanting to shorten the code up.  How can I take the below and write it so that I do not have to repeat

            self.output0.delete(0, END)  # clears entry
            self.output0.insert(0,results[0]) # enters results in entry
            self.output1.delete(0, END)  # clears entry
            self.output1.insert(0,results[1]) # enters results in entry
            2
            2
            3
            3
            ...etc

I want to increment the outputX and the number in results[x]

This below is what I have been trying but it is not working:

    results = cursor.fetchmany(10)
    i = 0
    myDelete = (self.output%d.delete(0, END) % (i))
    myInsert = (sef.output%d.insert(0,results[0]) % (i))

    if results:
        for int(i) in myDelete, myInsert (i):
            i += 0
            print (myDelete)  # clears entry
            print (myInsert)  # enters results in entry
        connection.close()
    else:
            self.output0.delete(0, END)
            self.output0.insert(0,"There are no records for this input.")

Right now I am getting a "Can't assign to function call" error but I am not even sure if I am going about this the right way.

Body:
You could add all the outputs to a list:

self.outputs = [self.output0, self.output1, self.output2] #etc...

And then loop through them:

for output in self.outputs:
    output.delete(0, END) #etc...

You can even create outputs like such:

self.outputs = []

for i in range(4):
   output = tk.Entry(
       self, width=149, justify='center', bd='0', bg='#E0E0E0'
   )
   output.grid(column=0, row=6, columnspan=5, padx=1)
   self.outputs.append(output)

Though you would need to add a way to change the row number and whatever else needs to be different for each iteration.


问:
Looping through pandas series to return date in minutes
I have a pandas series that looks like:

```<code>505     00:12:00
325     00:10:00
2929    00:09:00
261     00:08:00
</code>```

I want to return the dates as an array in the form [12,10, 09, 08]. How would I go about doing this?

答:
Try</p>

```<code>l = pd.to_datetime(df.time, format = '%H:%M:%S').dt.minute.tolist()

[12, 10, 9, 8]
</code>```

Body:
I have a pandas series that looks like:

505     00:12:00
325     00:10:00
2929    00:09:00
261     00:08:00

I want to return the dates as an array in the form [12,10, 09, 08]. How would I go about doing this?

Body:
Try

l = pd.to_datetime(df.time, format = '%H:%M:%S').dt.minute.tolist()

[12, 10, 9, 8]


问:
Gitlab hooks - Changes removed from hooks after gitlab upgrade
I made changes in the /hooks/post-receive file and after upgrading gitlab I found that the changes were removed :/

How to keep my changes in future upgrades as they are important

thanks

答:
Instead of placing your custom hooks in the hooks directory, put them in a new directory called custom_hooks. GitLab will execute any server-side hooks in this directory.

https://docs.gitlab.com/ee/administration/custom_hooks.html gives more information. TL;DR, be sure the custom_hooks directory and the hook are owned by git and the hook should have the execute bit.


问:
Reading data files with no data between delimiters
I have a data file that is pipe-delimited, but occasionally an empty value will not have data between two delimiters, leading to the delimiter character being placed in the corresponding column and later columns being populated with NaN values.

My code for creating my dataframes:

```<code>for DF_Exec in pd.read_table(ExecSrcFile, sep='|', chunksize=5000, header=1, low_memory=False, na_filter=True, index_col=False):
    # process data here
</code>```

Each row in the file is 212 columns long, but I'll provide an example of what cases are not working

```<code>...|80|strdata|\x00|90.0| |...
</code>```

These all work just fine. Spaces or null symbols between delimiters will be handled just fine.

```<code>...|80|strdata|||strdata|...
</code>```

This will map to 4 columns, instead of 5, which causes null values in the last expected column. The 3rd column in this case only contains a | character.

A snippet of my actual data where this issue shows up:

```<code>...|0||||||USD|...
</code>```

Because the file is very large, I would like to avoid the solution of processing it line by line to add spaces between the delimiters. Is there another more efficient option for dealing with this sort of issue using pandas or another package?

答: Have you tried using pandas.read_csv(ExecSrcFile, sep='|') ?

Body:
I have a data file that is pipe-delimited, but occasionally an empty value will not have data between two delimiters, leading to the delimiter character being placed in the corresponding column and later columns being populated with NaN values.

My code for creating my dataframes:

for DF_Exec in pd.read_table(ExecSrcFile, sep='|', chunksize=5000, header=1, low_memory=False, na_filter=True, index_col=False):
    # process data here

Each row in the file is 212 columns long, but I'll provide an example of what cases are not working

...|80|strdata|\x00|90.0| |...

These all work just fine. Spaces or null symbols between delimiters will be handled just fine.

...|80|strdata|||strdata|...

This will map to 4 columns, instead of 5, which causes null values in the last expected column. The 3rd column in this case only contains a | character.

A snippet of my actual data where this issue shows up:

...|0||||||USD|...

Because the file is very large, I would like to avoid the solution of processing it line by line to add spaces between the delimiters. Is there another more efficient option for dealing with this sort of issue using pandas or another package?


问:
How to scrape multiple pages from a website?
(Very) New to Python and programming in general

I've been trying to scrape data from more pages/section of the same website with Scrapy

My code works, but it's unreadable and not practical

```<code>import scrapy

class SomeSpider(scrapy.Spider):
    name = 'some'
    allowed_domains = ['https://example.com']
    start_urls = [
        'https://example.com/Python/?k=books&p=1',
        'https://example.com/Python/?k=books&p=2',
        'https://example.com/Python/?k=books&p=3',
        'https://example.com/Python/?k=tutorials&p=1',
        'https://example.com/Python/?k=tutorials&p=2',
        'https://example.com/Python/?k=tutorials&p=3',
     ]

     def parse(self, response):
         response.selector.remove_namespaces()

         info1 = response.css("scrapedinfo1").extract()
         info2 = response.css("scrapedinfo2").extract()

         for item in zip(scrapedinfo1, scrapedinfo2):
           scraped_info = {
              'scrapedinfo1': item[0],
              'scrapedinfo2': item[1]}

              yield scraped_info
</code>```

How can I improve this?

I'd like to search within a certain amount of categories and pages

I need something like

```<code>categories = [books, tutorials, a, b, c, d, e, f]
in a range(1,3)
</code>```

So that Scrapy would be able to do its job through all categories and pages, while being easy to edit and adapt to other websites

Any ideas are welcome

What I have tried:

```<code>categories = ["books", "tutorials"]
base = "https://example.com/Python/?k={category}&p={index}"

def url_generator():
    for category, index in itertools.product(categories, range(1, 4)):
        yield base.format(category=category, index=index)
</code>```

But Scrapy returns

```<code>[scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min),
scraped 0 items (at 0 items/min)
</code>```

答:
You can use method start_requests() to generate urls at start using yield Request(url).

BTW: Later in parse() you can also use yield Request(url) to add new url.

I use portal toscrape.com which was created for testing spiders.

```<code>import scrapy

class MySpider(scrapy.Spider):

    name = 'myspider'

    allowed_domains = ['http://quotes.toqoute.com']

    #start_urls = []

    tags = ['love', 'inspirational', 'life', 'humor', 'books', 'reading']
    pages = 3
    url_template = 'http://quotes.toscrape.com/tag/{}/page/{}'

    def start_requests(self):

        for tag in self.tags:
            for page in range(self.pages):
                url = self.url_template.format(tag, page)
                yield scrapy.Request(url)

    def parse(self, response):
        # test if method was executed
        print('url:', response.url)

# --- run it without project ---

from scrapy.crawler import CrawlerProcess

#c = CrawlerProcess({
#    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
#    'FEED_FORMAT': 'csv',
#    'FEED_URI': 'output.csv',
#}

c = CrawlerProcess()
c.crawl(MySpider)
c.start()
</code>```

Body:
(Very) New to Python and programming in general

I've been trying to scrape data from more pages/section of the same website with Scrapy

My code works, but it's unreadable and not practical

import scrapy

class SomeSpider(scrapy.Spider):
    name = 'some'
    allowed_domains = ['https://example.com']
    start_urls = [
        'https://example.com/Python/?k=books&p=1',
        'https://example.com/Python/?k=books&p=2',
        'https://example.com/Python/?k=books&p=3',
        'https://example.com/Python/?k=tutorials&p=1',
        'https://example.com/Python/?k=tutorials&p=2',
        'https://example.com/Python/?k=tutorials&p=3',
     ]

     def parse(self, response):
         response.selector.remove_namespaces()

         info1 = response.css("scrapedinfo1").extract()
         info2 = response.css("scrapedinfo2").extract()

         for item in zip(scrapedinfo1, scrapedinfo2):
           scraped_info = {
              'scrapedinfo1': item[0],
              'scrapedinfo2': item[1]}

              yield scraped_info

How can I improve this?

I'd like to search within a certain amount of categories and pages

I need something like

categories = [books, tutorials, a, b, c, d, e, f]
in a range(1,3)

So that Scrapy would be able to do its job through all categories and pages, while being easy to edit and adapt to other websites

Any ideas are welcome

What I have tried:

categories = ["books", "tutorials"]
base = "https://example.com/Python/?k={category}&p={index}"

def url_generator():
    for category, index in itertools.product(categories, range(1, 4)):
        yield base.format(category=category, index=index)

But Scrapy returns

[scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min),
scraped 0 items (at 0 items/min)

Body:
You can use method start_requests() to generate urls at start using yield Request(url).

BTW: Later in parse() you can also use yield Request(url) to add new url.

I use portal toscrape.com which was created for testing spiders.

import scrapy

class MySpider(scrapy.Spider):

    name = 'myspider'

    allowed_domains = ['http://quotes.toqoute.com']

    #start_urls = []

    tags = ['love', 'inspirational', 'life', 'humor', 'books', 'reading']
    pages = 3
    url_template = 'http://quotes.toscrape.com/tag/{}/page/{}'

    def start_requests(self):

        for tag in self.tags:
            for page in range(self.pages):
                url = self.url_template.format(tag, page)
                yield scrapy.Request(url)

    def parse(self, response):
        # test if method was executed
        print('url:', response.url)

# --- run it without project ---

from scrapy.crawler import CrawlerProcess

#c = CrawlerProcess({
#    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
#    'FEED_FORMAT': 'csv',
#    'FEED_URI': 'output.csv',
#}

c = CrawlerProcess()
c.crawl(MySpider)
c.start()


问:
Syntax error: missing `closing parenthesis` MySQL

I don't know way I got this error message here:

Here is the query:

```<code>SELECT t1.*,t2.totalAvg, ABS(`average for this subject`-totalAvg)  AS Difference, 100*MIN(`average for this subject`,totalAvg)/MAX(`average for this subject`,totalAvg) AS precent
FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
      FROM tests
      INNER JOIN students ON tests.StudentID=students.StudentID
      GROUP BY StudentFirstName,StudentLastName,ClassName
     ) t1
JOIN (SELECT StudentFirstName,StudentLastName,AVG(`average for this subject`) as totalAvg
      FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
            FROM tests
            INNER JOIN students ON tests.StudentID=students.StudentID
            GROUP BY StudentFirstName,StudentLastName,ClassName
           ) t
      GROUP BY StudentFirstName,StudentLastName
     ) t2
ON t1.StudentFirstName=t2.StudentFirstName and t1.StudentLastName=t2.StudentLastName
</code>```

答:
Your code may have other errors, but this is definitely incorrect in MySQL:

```<code>MIN(`average for this subject`, totalAvg)
</code>```

MIN() only takes one argument.  Presumably, you want LEAST():

```<code>LEAST(`average for this subject`, totalAvg)
</code>```

Body:
I don't know way I got this error message here:

Here is the query:

SELECT t1.*,t2.totalAvg, ABS(`average for this subject`-totalAvg)  AS Difference, 100*MIN(`average for this subject`,totalAvg)/MAX(`average for this subject`,totalAvg) AS precent
FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
      FROM tests
      INNER JOIN students ON tests.StudentID=students.StudentID
      GROUP BY StudentFirstName,StudentLastName,ClassName
     ) t1
JOIN (SELECT StudentFirstName,StudentLastName,AVG(`average for this subject`) as totalAvg
      FROM (SELECT StudentFirstName,StudentLastName,ClassName,AVG(Grade) AS `average for this subject`
            FROM tests
            INNER JOIN students ON tests.StudentID=students.StudentID
            GROUP BY StudentFirstName,StudentLastName,ClassName
           ) t
      GROUP BY StudentFirstName,StudentLastName
     ) t2
ON t1.StudentFirstName=t2.StudentFirstName and t1.StudentLastName=t2.StudentLastName

Body:
Your code may have other errors, but this is definitely incorrect in MySQL:

MIN(`average for this subject`, totalAvg)

MIN() only takes one argument.  Presumably, you want LEAST():

LEAST(`average for this subject`, totalAvg)


问:
How to figure out the import rules for a given command?
So I'm looking at some access code, and trying to figure out what exactly it's doing. Semi-stuck at the following line:

```<code>SpecName = "DocLineDetailImportSpec"
    DoCmd.TransferText acImportDelim, SpecName, tblname, filenm, True
</code>```

Ok, let's do some googling. Microsoft tells us the following:
https://msdn.microsoft.com/en-us/vba/access-vba/articles/docmd-transfertext-method-access

Acimportdelin - ok, the default. Sure.
Specname - this is where I'm stuck
Tablename - yup, obviously going to the table named earlier
Filename - yup, obviously grabbing the file we declared earlier in the code
True - Sure, not too concerned about it.

So I'm on Specname - reading the documentation, it's a type of import rule. Ok, where are import rules kept? Apparently, in saved imports (from my googling). I get there and... there are two rules, neither of them have the name, and neither of them appear to have any sort of visibility. I can't see what they're doing (if they were even correct), or anything. How can I figure out (short of brute-force uploading data and tracing it all) what the speccommand is?

Uploading Excel files btw

Thank you

答:
Your question, essentially, boils down to the following: how can I view the import specifications?

Well, in the following way (screenshots: Access 2016)

Step 1: Try to add a new data source -> Text

Step 2: Go to advanced

Step 3: Go to specifications

You can view and adjust import and export specifications here.

Body:
So I'm looking at some access code, and trying to figure out what exactly it's doing. Semi-stuck at the following line:

SpecName = "DocLineDetailImportSpec"
    DoCmd.TransferText acImportDelim, SpecName, tblname, filenm, True

Ok, let's do some googling. Microsoft tells us the following:
https://msdn.microsoft.com/en-us/vba/access-vba/articles/docmd-transfertext-method-access

Acimportdelin - ok, the default. Sure.
Specname - this is where I'm stuck
Tablename - yup, obviously going to the table named earlier
Filename - yup, obviously grabbing the file we declared earlier in the code
True - Sure, not too concerned about it.

So I'm on Specname - reading the documentation, it's a type of import rule. Ok, where are import rules kept? Apparently, in saved imports (from my googling). I get there and... there are two rules, neither of them have the name, and neither of them appear to have any sort of visibility. I can't see what they're doing (if they were even correct), or anything. How can I figure out (short of brute-force uploading data and tracing it all) what the speccommand is?

Uploading Excel files btw

Thank you


答: I would implement the whole Reachability class, tie it into your code as necessary and remove or comment out parts of Reachability. Just remove, one by one, the things you do not want to be notified of. Obviously, you need a good understanding of obj-c, the Reachability class, notifications, etc., but it can be done.</p>

Title: iOS/iPhone Reachability - How to only check when internet is lost/not reachable using Reachability.m/.h

Body:
Currently i am using the class by apple reachability.m/.h and it works, except it notifies me for any change, where as i would like to only notify the user if the network is not reachable. Currently if i have a internet connection and then loose the network it tells me. However when you reconnect to the network it also tells me, which i do not want. I want it to only tell me when there is a loss/no network.

I believe it has something to do with the call:

- (void)viewWillAppear:(BOOL)animated
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter]
          addObserver:self
             selector:@selector(checkNetworkStatus:)
                 name:kReachabilityChangedNotification
               object:nil];

    internetReachable = [[Reachability
                         reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName:
                     @"www.google.ca"] retain];
    [hostReachable startNotifier];

    // now patiently wait for the notification
}

when calling -[NSNotificationCenter addObserver:selector:name:object:], does the name have any other function then being literally a name? this is my first time using NSNotificationCenter so i am not well versed in this matter.

EDIT:

Here is my checkNetworkStatus function: (The problem is i am getting "NotReachable" as the network connection is coming back and NSAlert goes off multiple times)

- (void) checkNetworkStatus:(NSNotification *)notice
{
        // called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)

{
    case NotReachable:
    {
        UIAlertView * alert  = [[UIAlertView alloc] initWithTitle:@"Network Failed" message:@"Please check your connection and try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ];
        [alert show];
        NSLog(@"The internet is down.");

        break;

    }
    case ReachableViaWiFi:
    {
        NSLog(@"The internet is working via WIFI.");

        break;

    }
    case ReachableViaWWAN:
    {
        NSLog(@"The internet is working via WWAN.");

        break;

    }
}

NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)

{
    case NotReachable:
    {
        NSLog(@"A gateway to the host server is down.");

        break;

    }
    case ReachableViaWiFi:
    {
        NSLog(@"A gateway to the host server is working via WIFI.");

        break;

    }
    case ReachableViaWWAN:
    {
        NSLog(@"A gateway to the host server is working via WWAN.");

        break;

    }
}

}


问:
Is it possible to set ISR Handler at runtime on M0+
I have a "default" resetVectors.c file for my SAMD21 ARM M0+. It has something that looks like:

```<code>__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {
    ...
};
</code>```

in it that defines where different handler stubs. For testing purposes, I want to use one of the unused peripheral IRQs.

By default, the unused ones are set to NULL addresses. I have demonstrated to myself that I can modify that file and at compile time change my unused IRQ (21) to fire a handler. BUT, is it possible to do this outside of compile time?

I observed that the table appears to be based at offset 0. So I tried this:

```<code>DeviceVectors *table = 0x0000000;
table->pvReserved21 = PV21Handler;
</code>```

But that just hangs the board. Is there a dynamic way to assign the handler at runtime?

答:
In Cortex-M it is possible to set the address of the vector table at runtime.  So in order to set a specific vector, you need to locate the vector table into RAM.

The simplest method in this case is to copy the vector table pointed to by exception_table to RAM, modify the specific vector you need to change in the RAM copy, then switch the vector table to the RAM copy.

Note however that the Vector Table Offset Register is optional on Cortex-M0+ and may not be implemented on all devices.  It is however implemented on SAMD21 (see 7.1.1 of the datasheet summary.

Body:
I have a "default" resetVectors.c file for my SAMD21 ARM M0+. It has something that looks like:

__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {
    ...
};

in it that defines where different handler stubs. For testing purposes, I want to use one of the unused peripheral IRQs.

By default, the unused ones are set to NULL addresses. I have demonstrated to myself that I can modify that file and at compile time change my unused IRQ (21) to fire a handler. BUT, is it possible to do this outside of compile time?

I observed that the table appears to be based at offset 0. So I tried this:

DeviceVectors *table = 0x0000000;
table->pvReserved21 = PV21Handler;

But that just hangs the board. Is there a dynamic way to assign the handler at runtime?


问:
Django: object has no attribute 'was_published_recently'
New to Django, I've been doing the 1st tutorial and I'm at part 5 now, which is automated testing.

After following the tutorial until step "Fixing the Bug", it pops up an error when I run the test, as follows:

```<code>   Traceback (most recent call last):
   File "D:\Python\Django\ui1\polls\tests.py", line 13, in test_was_published_recently_with_future_question
    self.assertIs(future_question.was_published_recently(), False)
AttributeError: 'Question' object has no attribute 'was_published_recently'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
Destroying test database for alias 'default'...
</code>```

Whereas in the tutorial page, it shows no error in the testing.

```<code>Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Destroying test database for alias 'default'...
</code>```

Here's my code.

tests.py

```<code>import datetime

from django.utils import timezone
from django.test import TestCase

from .models import Question

class QuestionMethodTests(TestCase):
    def test_was_published_recently_with_future_question(self):
#should return False for questions whose pub_date is in the future.
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)
</code>```

models.py

```<code>from django.db import models

class Question(models.Model):
    question_text= models.CharField(max_length=200)
    pub_date=models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question= models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now
</code>```

答:
In models.py add:

```<code>from django.db import models
from django.utils import timezone
</code>```

Body:
New to Django, I've been doing the 1st tutorial and I'm at part 5 now, which is automated testing.

After following the tutorial until step "Fixing the Bug", it pops up an error when I run the test, as follows:

   Traceback (most recent call last):
   File "D:\Python\Django\ui1\polls\tests.py", line 13, in test_was_published_recently_with_future_question
    self.assertIs(future_question.was_published_recently(), False)
AttributeError: 'Question' object has no attribute 'was_published_recently'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
Destroying test database for alias 'default'...

Whereas in the tutorial page, it shows no error in the testing.

Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Destroying test database for alias 'default'...

Here's my code.

tests.py

import datetime

from django.utils import timezone
from django.test import TestCase

from .models import Question

class QuestionMethodTests(TestCase):
    def test_was_published_recently_with_future_question(self):
#should return False for questions whose pub_date is in the future.
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

models.py

from django.db import models

class Question(models.Model):
    question_text= models.CharField(max_length=200)
    pub_date=models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question= models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text

def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now

Body:
In models.py add:

from django.db import models
from django.utils import timezone


问:
Can't style material-ui with its own props
I'm using the material-ui and try to style the background-color of the RaisedButton, using one of its props called backgroundColor:

```<code>import React, {Component} from 'react';
import RaisedButton from 'material-ui/lib/raised-button';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Home.scss';

class Home extends Component {
    render() {
        return (
            <div>
                <h1 className={s.h1}>Pomodoro Tech</h1>
                <div className={s.imgContain}>
                    <img src={require('./pom.png')} width="100%" height="100%"/>
                </div>
                <div>
                    <RaisedButton
                        label="Login"
                        secondary={true}
                        backgroundColor="#77CA2D"
                    />
                    <RaisedButton
                        backgroundColor="#77CA2D"
                        label="About"
                    />
                </div>
            </div>
        );
    }
}

export default withStyles(Home, s);
</code>```

But that property never makes any differences.

The version of the material-ui I am using is 0.15.0-alpha.1, according to the result of npm list --depth=0 command.

Before I ask this question I've done some search, but can't figure out what the problem is.

答:
Make sure you don't include primary={true}; it will ignore your backgroundColor otherwise. See mine below:

<RaisedButton
  label={stepIndex === 2 ? 'Finish' : 'Next'}
  disableTouchRipple={true}
  disableFocusRipple={true}
  onClick={this.handleNext}
  backgroundColor={teal400}
/>
```

Body:
I'm using the material-ui and try to style the background-color of the RaisedButton, using one of its props called backgroundColor:

import React, {Component} from 'react';
import RaisedButton from 'material-ui/lib/raised-button';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Home.scss';

class Home extends Component {
    render() {
        return (

Pomodoro Tech

                    <RaisedButton
                        label="Login"
                        secondary={true}
                        backgroundColor="#77CA2D"
                    />
                    <RaisedButton
                        backgroundColor="#77CA2D"
                        label="About"
                    />

        );
    }
}

export default withStyles(Home, s);

But that property never makes any differences.

The version of the material-ui I am using is 0.15.0-alpha.1, according to the result of npm list --depth=0 command.

Before I ask this question I've done some search, but can't figure out what the problem is.


问:
VBA: Code review - Skip 1st line of a sheet
I was trying to understand how to skip the 1st row (A) of my sheet when i use below code which check whether any value available on my excel sheet.

```<code>Sub IsActiveSheetEmpty()
    If WorksheetFunction.CountA(Cells) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If
End Sub
</code>```

Thanks in Advance

答:
Seems like it should be a boolean-returning function rather than sub, but:

```<code>Option explicit

Sub IsActiveSheetEmpty()

Dim ws as worksheet
Set ws = Activesheet

With ws

If application.CountA(.range(.range("B1"),.cells(.rows.count,.columns.count))) = 0 Then
MsgBox .Name & " is empty"
Else
MsgBox .Name & " is not empty"
End If

End with

End Sub
</code>```

Untested, written on mobile. Does it do what you want?

Edit: Think you mean column A?

Body:
I was trying to understand how to skip the 1st row (A) of my sheet when i use below code which check whether any value available on my excel sheet.

Sub IsActiveSheetEmpty()
    If WorksheetFunction.CountA(Cells) = 0 Then
       MsgBox ActiveSheet.Name & " is empty"
    Else
      MsgBox ActiveSheet.Name & " is not empty"
    End If
End Sub

Thanks in Advance

Body:
Seems like it should be a boolean-returning function rather than sub, but:

Option explicit

Sub IsActiveSheetEmpty()

Dim ws as worksheet
Set ws = Activesheet

With ws

If application.CountA(.range(.range("B1"),.cells(.rows.count,.columns.count))) = 0 Then
MsgBox .Name & " is empty"
Else
MsgBox .Name & " is not empty"
End If

End with

End Sub

Untested, written on mobile. Does it do what you want?

Edit: Think you mean column A?


问:
Validating user's API credentials - Rails, ActiveMerchant, and PayPal Express Gateway
I'm building a marketplace application that uses PayPal Express.  I've got a form for sellers to input their PayPal API credentials, but I need a way to validate them by making some sort of call to PayPal.

I'm using the PaypalExpressGateway in ActiveMerchant, and I don't see anything other than the standard purchase controls.  Is there any sort of null-operation that can be used?

Any help would be greatly appreciated!

答:
Ok, after 4 hours...

```
module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class PaypalExpressGateway < Gateway

      def get_balance(options = {})
        commit 'GetBalance', build_get_balance_request(options)
      end

    private
      def build_get_balance_request(options)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.tag! 'GetBalanceReq', 'xmlns' => PAYPAL_NAMESPACE do
          xml.tag! 'GetBalanceRequest', 'xmlns:n2' => EBAY_NAMESPACE do
            xml.tag! 'n2:Version', API_VERSION
            xml.tag! 'n2:ReturnAllCurrencies', '1'
          end
        end

        xml.target!
      end
    end
  end
end

class SellerMerchantValidator < ActiveModel::Validator
  def validate(record)
    paypal_attrs = ['paypal_api_username', 'paypal_api_password', 'paypal_api_signature']
    if record.paypal_merchant? && (record.changed - paypal_attrs).size < record.changed.size # one of paypal_attrs changed
      response = record.gateway.get_balance
      unless response.params['balance'].present?
        record.errors[:base] << "Please check the PayPal details and make sure all three are entered correctly."
      end
    end
  end
end

```

Thanks to Neils for the idea to check the TransactionSearch.

Please let me know if there is a better way to check if any of the api field changed.

OwnerDisplayName: Micah

Body:
Ok, after 4 hours...

module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class PaypalExpressGateway < Gateway

      def get_balance(options = {})
        commit 'GetBalance', build_get_balance_request(options)
      end

    private
      def build_get_balance_request(options)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.tag! 'GetBalanceReq', 'xmlns' => PAYPAL_NAMESPACE do
          xml.tag! 'GetBalanceRequest', 'xmlns:n2' => EBAY_NAMESPACE do
            xml.tag! 'n2:Version', API_VERSION
            xml.tag! 'n2:ReturnAllCurrencies', '1'
          end
        end

        xml.target!
      end
    end
  end
end

class SellerMerchantValidator < ActiveModel::Validator
  def validate(record)
    paypal_attrs = ['paypal_api_username', 'paypal_api_password', 'paypal_api_signature']
    if record.paypal_merchant? && (record.changed - paypal_attrs).size < record.changed.size # one of paypal_attrs changed
      response = record.gateway.get_balance
      unless response.params['balance'].present?
        record.errors[:base] << "Please check the PayPal details and make sure all three are entered correctly."
      end
    end
  end
end

Thanks to Neils for the idea to check the TransactionSearch.

Please let me know if there is a better way to check if any of the api field changed.


问:
Spring Data JPA - How can I fetch data from a Date column using only month and day?
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

```<code>1935-12-08 00:00:00
</code>```

If I want to do this in a db level it works fine:

```<code>SELECT * FROM my_database.event where event_date LIKE '%-12-08%';
</code>```

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

```<code>List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);
</code>```

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

答:
Java: Date to String
Convert java.util.Date to String

```<code>@Query("select e from Event e where e.eventDate like %:eventDate%")
List<Entity> findByEventDateLike(@Param("eventDate")String eventDate);
</code>```

for me the easy way is parse Date to String but I found another solution you could be try

%Like% Query in spring JpaRepository
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

Body:
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.

1935-12-08 00:00:00

If I want to do this in a db level it works fine:

SELECT * FROM my_database.event where event_date LIKE '%-12-08%';

It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:

List<Event> findByEventDateLike(
        @Param("eventDate") Date eventDate);

but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.

NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.

How can I do it?

Body:
Java: Date to String
Convert java.util.Date to String

@Query("select e from Event e where e.eventDate like %:eventDate%")
List<Entity> findByEventDateLike(@Param("eventDate")String eventDate);

for me the easy way is parse Date to String but I found another solution you could be try

%Like% Query in spring JpaRepository
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)


答:
One easy simplification is to flip the conditional case. The default return for a Python method is None, so the end result is the same as your snippet.

```<code>def method(a, b):
  if a <= b:
    a, b = b, a
</code>```

We might be able to do more if you provided more context around your question; what are you trying to accomplish?

Title: Switching the value with order

Body:
Is there a pythonic shorter version for the flowing code:

def method(a,b)
    if a > b:
        pass
    else:
        a, b = b, a

Body:
One easy simplification is to flip the conditional case. The default return for a Python method is None, so the end result is the same as your snippet.

def method(a, b):
  if a <= b:
    a, b = b, a

We might be able to do more if you provided more context around your question; what are you trying to accomplish?


问:
How to retrieve only some fields from a table using DbSqlQuery in EF 6 (Not Linq)
Using the EF, a Rates table was created based on the Rate model below:

```<code>public class Rate
{
     [Key]
    public int IdNo { get; set; }
    public string RateCode { get; set; }
    public string RateClass { get; set; }
    public string Basis { get; set; }
    public bool RateIsActive { get; set; }
    public DateTime? ValidFrom { get; set; }
    public DateTime? ValidTo { get; set; }
    public bool IsReservRate { get; set; }
    public decimal? CostDay { get; set; }
    public decimal? CostWeek { get; set; }
    public decimal? CostMonth { get; set; }
    public decimal? CostHour { get; set; }
}
</code>```

I have no problem retrieving all columns from the Rates table using the code below:

```<code>using (AppDbContext db = new AppDbContext())
{
    DbSqlQuery<Rate> data = db.Rates.SqlQuery("select * from Rates");
}
</code>```

but what I need is to select only two columns from the table

```<code>DbSqlQuery<Rate> data = db.Rates.SqlQuery("select Rate, Class from Rates");
</code>```

and it gives me the following error:

The data reader is incompatible with the specified 'RPManager.Models.Rate'. A member of the type, 'RateIsActive', does not have a corresponding column in the data reader with the same name.

Is there a way to active what is needed?
NOTE!!!! I know how to do it using Linq but for this specific case it has to be done, if possible, using db.Rates.SqlQuery()

答:
Is there a way to active what is needed?

Not with the code provided.  You have a few options.

Your best option:

Create a class that represents what you need instead of reusing a class just because:

```<code>public class RateInfo
{
  public x Rate { get; set; }
  public x Class { get; set; }
}

var data = db.Rates.SqlQuery<RateInfo>("select Rate, Class from Rates");
</code>```

or not quite as good; set default values via the sql alias:

```<code>// assumming you have an Id column
var data = db.Rates.SqlQuery<Rate>("select 0 as ID, Rate, Class from Rates");
</code>```

Body:
Using the EF, a Rates table was created based on the Rate model below:

public class Rate
{
     [Key]
    public int IdNo { get; set; }
    public string RateCode { get; set; }
    public string RateClass { get; set; }
    public string Basis { get; set; }
    public bool RateIsActive { get; set; }
    public DateTime? ValidFrom { get; set; }
    public DateTime? ValidTo { get; set; }
    public bool IsReservRate { get; set; }
    public decimal? CostDay { get; set; }
    public decimal? CostWeek { get; set; }
    public decimal? CostMonth { get; set; }
    public decimal? CostHour { get; set; }
}

I have no problem retrieving all columns from the Rates table using the code below:

using (AppDbContext db = new AppDbContext())
{
    DbSqlQuery<Rate> data = db.Rates.SqlQuery("select * from Rates");
}

but what I need is to select only two columns from the table

DbSqlQuery<Rate> data = db.Rates.SqlQuery("select Rate, Class from Rates");

and it gives me the following error:

The data reader is incompatible with the specified 'RPManager.Models.Rate'. A member of the type, 'RateIsActive', does not have a corresponding column in the data reader with the same name.

Is there a way to active what is needed?
NOTE!!!! I know how to do it using Linq but for this specific case it has to be done, if possible, using db.Rates.SqlQuery()

Body:
Is there a way to active what is needed?

Not with the code provided.  You have a few options.

Your best option:

Create a class that represents what you need instead of reusing a class just because:

public class RateInfo
{
  public x Rate { get; set; }
  public x Class { get; set; }
}

var data = db.Rates.SqlQuery<RateInfo>("select Rate, Class from Rates");

or not quite as good; set default values via the sql alias:

// assumming you have an Id column
var data = db.Rates.SqlQuery<Rate>("select 0 as ID, Rate, Class from Rates");


问:
Except replacement in mysql?
I have to write some code in mysql but mostly I write in MS SQL and here is problem, in MS SQL I can use EXCEPT and everything is fine for me. But in MySQL there is not that simple, I tried with NOT IN and NOT EXISTS but it didn't give me same output. My MS SQL code is:

```<code>SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
JOIN Hotel H ON P.IDHotelu = H.IDHotelu
WHERE P.NumberOfBeds = 2 AND H.IDHotelu = 2
EXCEPT
SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P JOIN Reservation R ON P.IDRoom = R.IDRoom
WHERE '2017-12-10' BETWEEN DataB AND DataE;
</code>```

Like u can see I look for hotel who have 2 beds and hotel id is 2. but I don't want to see rooms who are already booked so I use except and look for booked rooms... but it's easy in MS SQL, in MySQL nothing work for me -_-. Any ideas?

答:
The query below should behave like EXCEPT

```<code>SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P
LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
JOIN Hotel H ON P.IDHotelu = H.IDHotelu
WHERE P.NumberOfBeds = 2 AND H.IDHotelu = 2
    AND NOT EXISTS (
        SELECT 1
        FROM Room i_P
        JOIN Reservation i_R ON i_P.IDRoom = i_R.IDRoom
        WHERE '2017-12-10' BETWEEN DataB AND DataE
            AND i_P.IDRoom = P.IDRoom
    )
</code>```

Title: Except replacement in mysql?

Body:
I have to write some code in mysql but mostly I write in MS SQL and here is problem, in MS SQL I can use EXCEPT and everything is fine for me. But in MySQL there is not that simple, I tried with NOT IN and NOT EXISTS but it didn't give me same output. My MS SQL code is:

SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
JOIN Hotel H ON P.IDHotelu = H.IDHotelu
WHERE P.NumberOfBeds = 2 AND H.IDHotelu = 2
EXCEPT
SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P JOIN Reservation R ON P.IDRoom = R.IDRoom
WHERE '2017-12-10' BETWEEN DataB AND DataE;

Like u can see I look for hotel who have 2 beds and hotel id is 2. but I don't want to see rooms who are already booked so I use except and look for booked rooms... but it's easy in MS SQL, in MySQL nothing work for me -_-. Any ideas?

Body:
The query below should behave like EXCEPT

SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P
LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
JOIN Hotel H ON P.IDHotelu = H.IDHotelu
WHERE P.NumberOfBeds = 2 AND H.IDHotelu = 2
    AND NOT EXISTS (
        SELECT 1
        FROM Room i_P
        JOIN Reservation i_R ON i_P.IDRoom = i_R.IDRoom
        WHERE '2017-12-10' BETWEEN DataB AND DataE
            AND i_P.IDRoom = P.IDRoom
    )


问:
Notepad++ and regex with removal of unmatching sections
I'm using this regex string I've crafted...

```<code>['"]{1}\w+@\w+\.{1}\w\w\w?['"]
</code>```

To hunt for email addresses contained in quotes in an old badly formatted legacy file.

Example:

```<code> ADF325@#%jkdaf-@#%j-afd(#$w52'leroyjenkins@myguild.edu'@#%kladfjkla-235dsaf-'thisemail@example.com'2l35jk2dz-dl1jkozf-afajelj'gooselick@somebodyspastries.co'l2#%Jk23l5jlafafljewo8972509357
j2k3l5jadfjeljwfoobar'foobar@barfoo.foo'jk23j-zv8902354jlfa
('352lj53k2ljkumquat'fakeemail@realemail.wtf')lajflsdf
etc.
</code>```

The regex is working beautifully for me... except for one thing. I want to replace everything that -doesn't- match with whitespace so I can work on formatting this to migrate this to the proper DB. How can I delete everything that doesn't match (and preferably, throw a newline between each match)?

答:
Use

```<code>['"](\w+@\w+\.\w{2,3})['"]|(?s).
</code>```

and replace with (?{1}\1\n).

A bit faster equivalent (demo):

```<code>['"](\w+@\w+\.\w{2,3})['"]|[^'"]*(?:['"](?!\w+@\w+\.\w{2,3}['"])[^'"]*)*
</code>```

Details

['"] - a quote

(\w+@\w+\.\w{2,3}) - Group 1: 1+ word chars, @, 1+ word chars, . and then 2 or 3 word chars

['"] - a quote

| - or

(?s). - any single char.

If Group 1 matches ((?{1}) the match is replaced with the Group 1 contents (\1\n). If the (?s). matches, the match gets removed.

Body:
I'm using this regex string I've crafted...

['"]{1}\w+@\w+\.{1}\w\w\w?['"]

To hunt for email addresses contained in quotes in an old badly formatted legacy file.

Example:

 ADF325@#%jkdaf-@#%j-afd(#$w52'leroyjenkins@myguild.edu'@#%kladfjkla-235dsaf-'thisemail@example.com'2l35jk2dz-dl1jkozf-afajelj'gooselick@somebodyspastries.co'l2#%Jk23l5jlafafljewo8972509357
j2k3l5jadfjeljwfoobar'foobar@barfoo.foo'jk23j-zv8902354jlfa
('352lj53k2ljkumquat'fakeemail@realemail.wtf')lajflsdf
etc.

The regex is working beautifully for me... except for one thing. I want to replace everything that -doesn't- match with whitespace so I can work on formatting this to migrate this to the proper DB. How can I delete everything that doesn't match (and preferably, throw a newline between each match)?

Body:
Use

['"](\w+@\w+\.\w{2,3})['"]|(?s).

and replace with (?{1}\1\n).

A bit faster equivalent (demo):

['"](\w+@\w+\.\w{2,3})['"]|[^'"]*(?:['"](?!\w+@\w+\.\w{2,3}['"])[^'"]*)*

Details

['"] - a quote

(\w+@\w+\.\w{2,3}) - Group 1: 1+ word chars, @, 1+ word chars, . and then 2 or 3 word chars

['"] - a quote

| - or

(?s). - any single char.

If Group 1 matches ((?{1}) the match is replaced with the Group 1 contents (\1\n). If the (?s). matches, the match gets removed.


问:
padding is removed on scroll outlook 2016 (windows)
I've run into what I think is a bug with Outlook 2016 (windows 7) that I just can't figure out or get around. Even if I can't fix it, I would like to know if anyone else has run into this issue before.  Every other email client I have tested renders my code perfectly.

When you scroll through the email, the layout changes (see link before, look for the jagged edge on the right). The edge should of course all be flush, with the same padding as the left side.

layout changes on scroll

I have done everything I can think of to prevent this. I have wrapped everything in more tables, change the padding to be on inner table cells, etc.  Has anyone else seen this before?

答:
We've all run into padding issues with Outlook.

https://www.campaignmonitor.com/css/box-model/padding/

http://www.informz.com/blog/email-marketing-tips/top-5-tips-for-optimizing-your-email-for-outlook-2016/

css padding is not working in outlook

Without an idea which Outlook client you're talking about, the html code, there's not much we can do to help you with your issue, other than tell you don't use padding.


问:
Does jQuery have a handleout for .delegate('hover')?
I am trying to use:  </p>

```<code>$('mydiv').delegate('hover', function() {
    $('seconddiv').show();
}, function() {
    //For some reason jQuery won't run this line of code
    $('seconddiv').hide();
});
</code>```

答:
With delegate()(docs) , you assign it to a container, and the first argument is the element that should trigger the event.

Also, .delegate() accepts only one function, so for the hover event you need to test the event.type to determine show()(docs)  or hide()(docs) .

```<code>$('.someContainer').delegate('.someTarget','hover', function( event ) {
    if( event.type === 'mouseenter' )
        $('seconddiv').show();
    else
        $('seconddiv').hide();
});
</code>```

For show/hide, a shorter way to write this is to use toggle()(docs), which can accept a switch argument where true means show and false means hide:

```<code>$('.someContainer').delegate('.someTarget','hover', function( event ) {
    $('seconddiv').toggle( event.type === 'mouseenter' );
});
</code>```

Note that the mouseenter event is reported as of jQuery 1.4.3. If you're using 1.4.2, it will be reported as mouseover.

EDIT:

If I'm understanding your comments below, you'd have something like this (using the proper selectors of course).

```<code>$('mydiv').delegate('seconddiv','hover', function( event ) {
    $(this).toggle( event.type === 'mouseenter' );
});
</code>```

Body:
I am trying to use:

$('mydiv').delegate('hover', function() {
    $('seconddiv').show();
}, function() {
    //For some reason jQuery won't run this line of code
    $('seconddiv').hide();
});

Body:
With delegate()(docs) , you assign it to a container, and the first argument is the element that should trigger the event.

Also, .delegate() accepts only one function, so for the hover event you need to test the event.type to determine show()(docs)  or hide()(docs) .

$('.someContainer').delegate('.someTarget','hover', function( event ) {
    if( event.type === 'mouseenter' )
        $('seconddiv').show();
    else
        $('seconddiv').hide();
});

For show/hide, a shorter way to write this is to use toggle()(docs), which can accept a switch argument where true means show and false means hide:

$('.someContainer').delegate('.someTarget','hover', function( event ) {
    $('seconddiv').toggle( event.type === 'mouseenter' );
});

Note that the mouseenter event is reported as of jQuery 1.4.3. If you're using 1.4.2, it will be reported as mouseover.

EDIT:

If I'm understanding your comments below, you'd have something like this (using the proper selectors of course).

$('mydiv').delegate('seconddiv','hover', function( event ) {
    $(this).toggle( event.type === 'mouseenter' );
});


答:
```<code>Option Explicit
Sub IsActiveSheetEmpty()
   Dim myRange As Range
   Set myRange = Range("A2",Cells(2,1).SpecialCells(XlCellType.xlCellTypeLastCell))

   If WorksheetFunction.CountA(myRange) = 0 Then
      MsgBox ActiveSheet.Name & " is empty"
   Else
      MsgBox ActiveSheet.Name & " is not empty"
   End If
End Sub
</code>```

Title: VBA: Code review - Skip 1st line of a sheet


问:
Replication issue
We have a one master and two VIP slave database servers. We changed data type of column from VARCHAR(255) to TEXT on master.
The application is currently configured to use master only for writing operations and configured slaves for reading operation.
After changing the data type on master server using ALTER TABLE command the slave server becomes unresponsive.
We are using Mariadb 10.0
[PROCESSES INFORMATION]

```
Id  User    Host    Db  Command Time(sec)   State   Info
-----------------------------------------------------------------------
203739  repl    slave1      Binlog Dump 75,143,121  Master has sent all binlog to slave; waiting for binlog to be updated

203740  repl    slave2      Binlog Dump 75,143,121  Master has sent all binlog to slave; waiting for binlog to be updated
```

The slave instance becomes very slow due to slow queries.
number of sessions: 1590
thread_pool_max_thread=500
Current value =648

After performing ALTER TABLE on Master server, it was replicating to slave server and in the same time number of sessions were get increased rapidly on slave server.
I think slaves becomes unresponsive because of slow queries.

But I don't know why this queries became so slow and slaves got unresponsive.
The DBA's saying that after executing ANALYZE TABLE command, the issue has been solved.
But I don't understand why this happened because ANALYZE TABLE only update the statistic information.
It would be helpful if anyone comment on this why it happened?
How to avoid such issues in future.

答:
There is one minor case where TEXT is slower than VARCHAR.  When a SELECT needs to build a temporary table (often for sorting due to GROUP BY or ORDER BY), it first tries to build a MEMORY table.  But, TEXT and BLOB prevent it from using such, so it uses MyISAM instead.  This is slower (but gets the job done).

I say this is a "minor case" because users rarely identify it with phrases like "very slow" and "becomes unresponsive".  I would guess that a SELECT might run twice as slow.

Also, the ANALYZE TABLE discussion does not hold water.  Again it may be coincidence, not causation.

So, the change to TEXT may be a 'red herring'.  Instead, let's discover what is being slow by using the slowlog.  See this for what I like to work from.

Title: Replication issue

Body:
We have a one master and two VIP slave database servers. We changed data type of column from VARCHAR(255) to TEXT on master.
The application is currently configured to use master only for writing operations and configured slaves for reading operation.
After changing the data type on master server using ALTER TABLE command the slave server becomes unresponsive.
We are using Mariadb 10.0
[PROCESSES INFORMATION]

Id  User    Host    Db  Command Time(sec)   State   Info
-----------------------------------------------------------------------
203739  repl    slave1      Binlog Dump 75,143,121  Master has sent all binlog to slave; waiting for binlog to be updated

203740  repl    slave2      Binlog Dump 75,143,121  Master has sent all binlog to slave; waiting for binlog to be updated

The slave instance becomes very slow due to slow queries.
number of sessions: 1590
thread_pool_max_thread=500
Current value =648

After performing ALTER TABLE on Master server, it was replicating to slave server and in the same time number of sessions were get increased rapidly on slave server.
I think slaves becomes unresponsive because of slow queries.

But I don't know why this queries became so slow and slaves got unresponsive.
The DBA's saying that after executing ANALYZE TABLE command, the issue has been solved.
But I don't understand why this happened because ANALYZE TABLE only update the statistic information.
It would be helpful if anyone comment on this why it happened?
How to avoid such issues in future.


问:
How to display a paragraph / block of words using A-Frame?
I am currently developing a tool in my work which will be having augmented reality (AR.js). My problem is that I must display a paragraph of text using A-frame. My question is how to do it?

I am using the  tag in displaying the text. If there is only 1 line of text that I am displaying, I have no difficulty in displaying it but if I have many words and I needed to display it, the lines overlaps with each other.

Here is a sample output of a single line of text:

Here is the output of the paragraph. The lines of the paragraph overlaps with each other.

P.S.

Here is my code. I am separating the paragraph first in a controller to smaller strings that the monitor can display.

```<code>@if (isset($value->words))
    @foreach ($value->words as $key => $words)
        <a-text value="{{ $words }}" rotation="-90 0 0"></a-text>
    @endforeach
@else
    <a-text value="{{ $value->text }}" rotation="-90 0 0"></a-text>
@endif
</code>```

It is in Blade. The $value->words contains the array of strings that has been separated and the $value->text is the original text.

答:
If you want multiple entities layed out, you can use the layout component https://github.com/ngokevin/kframe/tree/master/components/layout to automatically lay them out in however you need (e.g., column).

```<code><a-entity layout="type: box; columns: 1; margin: -0.05">
  <a-entity id="line1" layout="type: line; margin: 0.5">
    <a-entity text="value: 1"></a-entity>
    <a-entity text="value: 1.1"></a-entity>
  </a-entity>

  <a-entity id="line2" text="value: 2"></a-entity>

  <a-entity id="line3" text="value: 3"></a-entity>
</a-entity>
</code>```

Else you can use \n break text="value: a\nb\n\c" or specify text="wrapCount: 80"

Body:
I am currently developing a tool in my work which will be having augmented reality (AR.js). My problem is that I must display a paragraph of text using A-frame. My question is how to do it?

I am using the  tag in displaying the text. If there is only 1 line of text that I am displaying, I have no difficulty in displaying it but if I have many words and I needed to display it, the lines overlaps with each other.

Here is a sample output of a single line of text:

Here is the output of the paragraph. The lines of the paragraph overlaps with each other.

P.S.

Here is my code. I am separating the paragraph first in a controller to smaller strings that the monitor can display.

@if (isset($value->words))
    @foreach ($value->words as $key => $words)

    @endforeach
@else
    text }}" rotation="-90 0 0">
@endif

It is in Blade. The $value->words contains the array of strings that has been separated and the $value->text is the original text.

Body:
If you want multiple entities layed out, you can use the layout component https://github.com/ngokevin/kframe/tree/master/components/layout to automatically lay them out in however you need (e.g., column).

<a-entity layout="type: box; columns: 1; margin: -0.05">
  <a-entity id="line1" layout="type: line; margin: 0.5">
    <a-entity text="value: 1"></a-entity>
    <a-entity text="value: 1.1"></a-entity>
  </a-entity>

  <a-entity id="line2" text="value: 2"></a-entity>

  <a-entity id="line3" text="value: 3"></a-entity>
</a-entity>

Else you can use \n break text="value: a\nb\n\c" or specify text="wrapCount: 80"


问:
configuring multiple domains with nginx
First of all there's already a server running on 80 port(with domain, let's say domainA.com ), and I have another domain(domainB.com). Here's what I'm trying to do.

80 port: domainA.com

3000 port: domainB.com

so If I make a request to domainB.com It shouldn't redirect to domainA.com:3000 but should actually works on the same server. and DNS server ip is set to the server as the same as domainA.com is connected to (so if I go to domainB.com it just redirects to domainA.com, I think I need to fix this part but I have no idea). how can I make this happen?

答:
```<code>server {
    listen      80;
    server_name domainA.com;
    root /var/www/domainA;
}

server {
    listen       3000;
    server_name domainB.com ;
    root /var/www/domainB;
}
</code>```

you now can access this sites via : domainA.com and domainB.com:333
also you can make both of them listen on port 80 :
nginx can detect that request is coming for which domain and redirect request to that domain :

```<code>server {
    listen      80;
    server_name domainA.com;
    root /var/www/domainA;
}

server {
    listen       80;
    server_name domainB.com ;
    root /var/www/domainB;
}
</code>```

see this : nginx server_names

source : diffrent domain on same ip

Title: configuring multiple domains with nginx

Body:
server {
    listen      80;
    server_name domainA.com;
    root /var/www/domainA;
}

server {
    listen       3000;
    server_name domainB.com ;
    root /var/www/domainB;
}

you now can access this sites via : domainA.com and domainB.com:333
also you can make both of them listen on port 80 :
nginx can detect that request is coming for which domain and redirect request to that domain :

server {
    listen      80;
    server_name domainA.com;
    root /var/www/domainA;
}

server {
    listen       80;
    server_name domainB.com ;
    root /var/www/domainB;
}

see this : nginx server_names

source : diffrent domain on same ip


问:
transforming width of a polygon in SVG only hopefully
Using basically SVG( except for PHP loops for positioning) only I would like to create a polygon shaped similar to >XX> where each X is simply top and bottom lines basically an arrow, which I have done.I duplicate this polygon offset by its width plus a few pixels along x.

Now I want to do a graduated fill of a different color on each polygon and it is offset by a about .1 secs

I do this with rectangles by simply printing them all out in first color then in the same xy coord locations draw the same rectangle in second color and animate its width from 0 to the normal width
the result is a graduated fill that moves along the x axis.

This can almost be achieved by redrawing each one uniquely in the different color but it would be very blocky I want each polygon to gradually fill from left to right
 I have looked at grouping, animate with the fill attribute and animateTransform with the scale attribute but am still learning the subtleties of each and may be missing something

the problem I see am seeing is the polygon has no width as designed and maybe I am just missing it.

I can use the rectangles for now but just wanted something flashier.

Any other avenues you could suggest I check out would be great

Here is code I have for the rectangles

```<code><rect x='".($blk*$x)."' y='110' height='30' width='0' style='stroke:none; fill: #ffff00'>
                    <animate attributeName='width' attributeType='XML'
                        to='".($blk-3)."'
                        begin='".($x/15)."s'
                        dur='.5s'
                        fill='freeze'
                    />
</rect>
</code>```

I use PHP for the blk size and the x translation

答:
You can achieve a similar effect with animateTransform, applying a scale transform. animateTransform applies to all shapes including rect elements.

Don't forget that dur attributes must start with a leading 0 if they are less than 1 i.e. .5s is invalid and should be written as 0.5s

<svg>
<rect x='100' y='20' height='30' width='0' style='fill: #ffff00'>
                    <animate attributeName='width' attributeType='XML'
                        to='100'
                        begin='1s'
                        dur='0.5s'
                        fill='freeze'
                    />
</rect>
<g transform='translate(100, 0)'>
<polygon transform='scale(0, 1)'
         points='0, 110 40, 110, 40 140, 0 140'
         style='fill: #ffff00'>
                    <animateTransform attributeName='transform'
                        type='scale'
                        to='2.5, 1'
                        begin='1s'
                        dur='0.5s'
                        fill='freeze'
                    />
</polygon>
</g>
</svg>```

Body:
Using basically SVG( except for PHP loops for positioning) only I would like to create a polygon shaped similar to >XX> where each X is simply top and bottom lines basically an arrow, which I have done.I duplicate this polygon offset by its width plus a few pixels along x.

Now I want to do a graduated fill of a different color on each polygon and it is offset by a about .1 secs

I do this with rectangles by simply printing them all out in first color then in the same xy coord locations draw the same rectangle in second color and animate its width from 0 to the normal width
the result is a graduated fill that moves along the x axis.

This can almost be achieved by redrawing each one uniquely in the different color but it would be very blocky I want each polygon to gradually fill from left to right
 I have looked at grouping, animate with the fill attribute and animateTransform with the scale attribute but am still learning the subtleties of each and may be missing something

the problem I see am seeing is the polygon has no width as designed and maybe I am just missing it.

I can use the rectangles for now but just wanted something flashier.

Any other avenues you could suggest I check out would be great

Here is code I have for the rectangles

<rect x='".($blk*$x)."' y='110' height='30' width='0' style='stroke:none; fill: #ffff00'>
                    <animate attributeName='width' attributeType='XML'
                        to='".($blk-3)."'
                        begin='".($x/15)."s'
                        dur='.5s'
                        fill='freeze'
                    />
</rect>

I use PHP for the blk size and the x translation