问:
convert new line /n to a line break in angular
I have a string which contain new line character /n. Trying to display

the string. Instead of taking the /n as new line, it displays '/n' as text.

```<code>   $scope.myOutput = " Hello /n"

    {{ myOutput | textFormat }}
</code>```

Required -> Hello (on html page)

Tried :

```<code> app.filter('textFormat', function() {
    return function(x) {
      return x.replace(/\\n/g, '<br/>');
   }
</code>```

Tried css styles like white-space: pre;

答:
1 - rewrite your filter next way:

```<code>.filter('textFormat', function() {
    return function (x) {
      return x.replace(new RegExp('\/n', 'g'), '<br/>');
    }
 })
</code>```

2 - in your html you should use the next syntax:

```<code><span ng-bind-html="myOutput | textFormat"></span>
</code>```

Where myOutput is $scope.myOutput = ' Hello /n'

Body:
I have a string which contain new line character /n. Trying to display

the string. Instead of taking the /n as new line, it displays '/n' as text.

   $scope.myOutput = " Hello /n"

    {{ myOutput | textFormat }}

Required -> Hello (on html page)

Tried :

 app.filter('textFormat', function() {
    return function(x) {
      return x.replace(/\\n/g, '
');
   }

Tried css styles like white-space: pre;

Body:
1 - rewrite your filter next way:

.filter('textFormat', function() {
    return function (x) {
      return x.replace(new RegExp('\/n', 'g'), '<br/>');
    }
 })

2 - in your html you should use the next syntax:

<span ng-bind-html="myOutput | textFormat"></span>

Where myOutput is $scope.myOutput = ' Hello /n'


来源: stackexchange

问:
instantiate a sub-type object in ModelBinder
I have a base class, and two other classes derived for it, and each class of these two classes has two derived classes. I need in my modelBinder to instantiate my object according to the subtype instantiate the corresponding class

see my code here

```<code>public class Product
{
    public ProductType ProductType;//ProductA,ProductB
}

public class ProductA : Product
{
    public subType AsubType;// AsubType ProductAH et ProductAF
}

public class ProductB : Product
{
    public subType BsubType; // BsubType ProductBC et ProductBD
}

public class ProductAH : ProductA { }

public class ProductAF : ProductA { }

public class ProductBC : ProductB { }

public class ProductBD : ProductB { }

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
    if (modelType.Equals(typeof(Product)))
    {
        //instantiate a object ProductAH or ProductAF or BC or BD according to subtype

        Type instantiationType = typeof(xxxx);
        var obj = Activator.CreateInstance(instantiationType);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, instantiationType);
        bindingContext.ModelMetadata.Model = obj;
        return obj;
    }
    else
    {
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}
</code>```

答:
I resolved my problem with this code :</p>

```<code>var keySubType = bindingContext.ModelName.ToString() + "."+"SubType";
string subtypeName = bindingContext.ValueProvider.GetValue(keySubType).AttemptedValue;

Type instantiationType = null;
switch (subtypeName)
{
    case "ProductAH":
        instantiationType = typeof(ProductAH );
        break;
    case "ProductAF":
        instantiationType = typeof(ProductAF );
        break;
    case "ProductBC":
        instantiationType = typeof(ProductBC );
        break;
    case "ProductBD":
        instantiationType = typeof(ProductBD );
        break;
}

//Create an instance of the specified type
var obj = Activator.CreateInstance(instantiationType);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a base class, and two other classes derived for it, and each class of these two classes has two derived classes. I need in my modelBinder to instantiate my object according to the subtype instantiate the corresponding class

see my code here

public class Product
{
    public ProductType ProductType;//ProductA,ProductB
}

public class ProductA : Product
{
    public subType AsubType;// AsubType ProductAH et ProductAF
}

public class ProductB : Product
{
    public subType BsubType; // BsubType ProductBC et ProductBD
}

public class ProductAH : ProductA { }

public class ProductAF : ProductA { }

public class ProductBC : ProductB { }

public class ProductBD : ProductB { }

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
    if (modelType.Equals(typeof(Product)))
    {
        //instantiate a object ProductAH or ProductAF or BC or BD according to subtype

        Type instantiationType = typeof(xxxx);
        var obj = Activator.CreateInstance(instantiationType);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, instantiationType);
        bindingContext.ModelMetadata.Model = obj;
        return obj;
    }
    else
    {
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

Body:
I resolved my problem with this code :

var keySubType = bindingContext.ModelName.ToString() + "."+"SubType";
string subtypeName = bindingContext.ValueProvider.GetValue(keySubType).AttemptedValue;

Type instantiationType = null;
switch (subtypeName)
{
    case "ProductAH":
        instantiationType = typeof(ProductAH );
        break;
    case "ProductAF":
        instantiationType = typeof(ProductAF );
        break;
    case "ProductBC":
        instantiationType = typeof(ProductBC );
        break;
    case "ProductBD":
        instantiationType = typeof(ProductBD );
        break;
}

//Create an instance of the specified type
var obj = Activator.CreateInstance(instantiationType);


问:
How do I write a recursive function that multiplies each character in a string by 2?
I'm trying to complete a recursive function which given a number, returns a string where the returned value has duplicate of each digit

Example: if 507, returns 550077

if the number is only 0 then just return 0

also if it is a negative number, return the negative sign only once

Example: -507 returns -550077

I haven't yet implemented anything to recognize a negative number, I was just trying to get my function to work first

so far I have:

```<code>def double(x):
    if x == 0:
        return x
    else:
        x = str(x)
        return x[0]*2 + double(x[1: ])

print(double(527))
</code>```

however this returns IndexError: string index out of range
I had it working by printing the result instead of returning the result, but the problem I am trying to solve strictly wants the result returned, not printed. What am I doing wrong?

答:
Something like this might work.     </p>

```<code>def double(x):
    if x == 0:
        return x
    else:
        x = str(x)
        l=[]
        for a in x:
            if a == '-':
                l.append(a)
            else:
                l.append(a*2)
        return ''.join(l)
</code>```

Body:
I'm trying to complete a recursive function which given a number, returns a string where the returned value has duplicate of each digit

Example: if 507, returns 550077

if the number is only 0 then just return 0

also if it is a negative number, return the negative sign only once

Example: -507 returns -550077

I haven't yet implemented anything to recognize a negative number, I was just trying to get my function to work first

so far I have:

def double(x):
    if x == 0:
        return x
    else:
        x = str(x)
        return x[0]*2 + double(x[1: ])

print(double(527))

however this returns IndexError: string index out of range
I had it working by printing the result instead of returning the result, but the problem I am trying to solve strictly wants the result returned, not printed. What am I doing wrong?

Body:
Something like this might work.

def double(x):
    if x == 0:
        return x
    else:
        x = str(x)
        l=[]
        for a in x:
            if a == '-':
                l.append(a)
            else:
                l.append(a*2)
        return ''.join(l)


问:
Find Monday's date with Python
How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: datetime.weekday() to do it, but I am getting stuck.

I basically want to find today's date and Mondays date to construct a date range query in django using: created__range=(start_date, end_date).

答:
For future googlers who show up on this page looking for a way to get "the most recent Sunday", rather than "the most recent Monday", you need to do some additional math because datetime.weekday() treats Monday as the first day of the week:

```<code>today = datetime.date.today()
weekday = today.weekday() + 1
start_day = today - datetime.timedelta(days=weekday % 7)
</code>```

If today is Tuesday, this sets start_day to last Sunday. If today is Sunday, this sets start_day to today. Take away the % 7 if you want "last Sunday" to be a week ago if it's currently Sunday.

ContentLicense: CC BY-SA 2.5

Title: Find Monday's date with Python

Body:
For future googlers who show up on this page looking for a way to get "the most recent Sunday", rather than "the most recent Monday", you need to do some additional math because datetime.weekday() treats Monday as the first day of the week:

today = datetime.date.today()
weekday = today.weekday() + 1
start_day = today - datetime.timedelta(days=weekday % 7)

If today is Tuesday, this sets start_day to last Sunday. If today is Sunday, this sets start_day to today. Take away the % 7 if you want "last Sunday" to be a week ago if it's currently Sunday.


问:
2 Dimensional Arrays.Why do I have to declare size of Columns in C
I want to ask a question about 2D arrays in C .First Let me explain what I want to do.

I am trying to read names into a 2D array till user enters 0 and from that array I want to randomly pick an name. Now I have couple of questions.

Why do I have to declare the size of arr? I want to do it like char arr[][50] the reason that am asking this is because I took a semester of C before my current semester and I remember my tutor said something like you don't have to declare size of column as long as you declare a row size.

```<code>#include <stdio.h>

void main(){
    char arr[50][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%s",&arr[i]);
    }
}
</code>```

I just found that I was missing braces after if inside for code gives no error at the moment but entering 0 from the keyboard does not executes the proccess.

```<code>#include <stdio.h>

void main(){
    char arr[0][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%49s", arr[i]);
        if(arr[i]== 0){
            arr[i][0] = '\0';
            break;}

    }
}
</code>```

Also I want to read names in a function but couldn't figure out how to pass the arr[50][50] to a function So I can read names in that function.

I am trying to work with ANSI C

答:
This may not be an answer - but probably help you to develop code better

I just found that i was missing braces after if inside for code gives
  no error at the moment but entering 0 from the keyboard does not
  executes the procces.

If i understand correctly, you want to exit the application when you type 0. If so the condition if(arr[i]== 0) would not work. When you type 0 , the it stores its ASCII value in the character array. To tell compiler you are looking for ASCII 0, you need use '0'.

Now how entered value stored on to arr[50][50].

For the first iteration i=0 , and you entered abcd(hit enter) ->
arr[0][0] = 'a', arr[0][1] = 'b' arr[0][2] = 'c', arr[0][3] = 'd' and arr[0][4] ='\0'

for second iteration i =1 and you entered   mnop(hit enter) ->
arr[1][0] = 'm', arr[1][1] = 'n' arr[1][2] = 'o', arr[1][3] = 'p' and arr[1][4] ='\0'
and so on

To exit application when you type 0, you can probably use if(arr[i][0]== '0') condition. But this condition will not work in all cases, it works only if the first character you typed (after you hit enter which means it is stepping up to next array location) is 0

Body:
I want to ask a question about 2D arrays in C .First Let me explain what I want to do.

I am trying to read names into a 2D array till user enters 0 and from that array I want to randomly pick an name. Now I have couple of questions.

Why do I have to declare the size of arr? I want to do it like char arr[][50] the reason that am asking this is because I took a semester of C before my current semester and I remember my tutor said something like you don't have to declare size of column as long as you declare a row size.

#include <stdio.h>

void main(){
    char arr[50][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%s",&arr[i]);
    }
}

I just found that I was missing braces after if inside for code gives no error at the moment but entering 0 from the keyboard does not executes the proccess.

#include <stdio.h>

void main(){
    char arr[0][50];
    int i;
    for(i= 0 ; i < 50; i++){
        scanf("%49s", arr[i]);
        if(arr[i]== 0){
            arr[i][0] = '\0';
            break;}

    }
}

Also I want to read names in a function but couldn't figure out how to pass the arr[50][50] to a function So I can read names in that function.

I am trying to work with ANSI C


问:
Pending Intent always return null for AlarmManager
I'm creating an alarm mananger that should run every day.
The alarm should only be set once, since the method is called in my MainActivity.But always the Pending intent return null.
I hoped that after it was created it would return the same pending intent, without having to set the alarm again.</p>

```<code>public void setAlarm() {
    Intent intent = new Intent(context, BroadcastLogRaces.class);

    PendingIntent pi = PendingIntent.getBroadcast(context, 99,
            intent,PendingIntent.FLAG_NO_CREATE);

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (pi == null) {

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 19);
        calendar.set(Calendar.MINUTE,00);
        calendar.set(Calendar.SECOND, 00);

        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pi);

        Log.i("alarme", "alarme agendado as "+ new Date().toString());

    }
}
</code>```

答:
You have used flag FLAG_NO_CREATE while creating your PendingIntent, it says

```<code> /**
 * Flag indicating that if the described PendingIntent does not
 * already exist, then simply return null instead of creating it.
 * For use with {@link #getActivity}, {@link #getBroadcast}, and
 * {@link #getService}.
 */
</code>```

You need to use FLAG_CANCEL_CURRENTor FLAG_UPDATE_CURRENT which basically cancels current pending intent and replaces extra data if current pending intent still exists, respectively.

Body:
I'm creating an alarm mananger that should run every day.
The alarm should only be set once, since the method is called in my MainActivity.But always the Pending intent return null.
I hoped that after it was created it would return the same pending intent, without having to set the alarm again.

public void setAlarm() {
    Intent intent = new Intent(context, BroadcastLogRaces.class);

    PendingIntent pi = PendingIntent.getBroadcast(context, 99,
            intent,PendingIntent.FLAG_NO_CREATE);

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (pi == null) {

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, 19);
        calendar.set(Calendar.MINUTE,00);
        calendar.set(Calendar.SECOND, 00);

        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pi);

        Log.i("alarme", "alarme agendado as "+ new Date().toString());

    }
}

Body:
You have used flag FLAG_NO_CREATE while creating your PendingIntent, it says

 /**
 * Flag indicating that if the described PendingIntent does not
 * already exist, then simply return null instead of creating it.
 * For use with {@link #getActivity}, {@link #getBroadcast}, and
 * {@link #getService}.
 */

You need to use FLAG_CANCEL_CURRENTor FLAG_UPDATE_CURRENT which basically cancels current pending intent and replaces extra data if current pending intent still exists, respectively.


问:
wp7-how to make a thread navigate pages
I want to check for changes in the aplication state every time interval, and if it has changed, to open a window, and  give the user 10 seconds to press on the window, if he does press on the window, then to allow him to navigate freely in the window, and if he doesn't press, to return back to the window before. I thought to implement it with a thread running in the background and waking up every time interval I want. Maybe there is a better way?</p>

答:
I didn't know you could do a pop-up window, could you elaborate?
I've made a thread that is running at the background and making some work, if it decides that a change is necessary, I want to give the user a chance to react to it, or ignore it.
I'm pretty new to this, so if there is a better way than to navigate to a different page i would love to hear it.
Thanks.</p>

Title: wp7-how to make a thread navigate pages


问:
Python Data frame: If Column Name is contained in the String Row of Another Column Then 1 Otherwise 0
```<code>Column A          2C GAD D2 6F  ABCDE
2C 1B D2 6F ABC   1   0  1  1   0
2C 1248 Bulers    1   0  0  0   0
</code>```

Above is the dataframe I want to create.

The first row represents the field names.  The logic I want to employ is as follows:
If the column name is in the "Column A" row, then 1 otherwise 0

I have scoured Google looking for code answering a question similar to mine so I can test it out and backward engineer a solution.  Unfortunately, I have not been able to find anything.

Otherwise I would post some code that I attempted to solve this problem but I literally have no clue.

答:
You can use a list comprehension to create the desire data based on the columns and rows:

```<code>In [39]: row =['2C 1B D2 6F ABC', '2C 1248 Bulers']

In [40]: columns=['2C', 'GAD', 'D2', '6F',  'ABCDE']

In [41]: df = pd.DataFrame([[int(k in r) for k in columns] for r in row], index = ['2C 1B D2 6F ABC','2C 1248 Bulers'], columns=['2C', 'GAD', 'D2', '6F',  'ABCDE'])

In [42]: df
Out[42]:
                 2C  GAD  D2  6F  ABCDE
2C 1B D2 6F ABC   1    0   1   1      0
2C 1248 Bulers    1    0   0   0      0
</code>```

If you want a pure Pandas approach you can use pd.Series() instead of list for preserving the columns and rows then use Series.apply and Series.str.contains to get the desire result:

```<code>In [73]: data = columns.apply(row.str.contains).astype(int).transpose()

In [74]: df = pd.DataFrame(data.values, index = ['2C 1B D2 6F ABC','2C 1248 Bulers'], columns=['2C', 'GAD', 'D2', '6F',  'ABCDE'])

In [75]: df
Out[75]:
                 2C  GAD  D2  6F  ABCDE
2C 1B D2 6F ABC   1    0   1   1      0
2C 1248 Bulers    1    0   0   0      0
</code>```

Body:
Column A          2C GAD D2 6F  ABCDE
2C 1B D2 6F ABC   1   0  1  1   0
2C 1248 Bulers    1   0  0  0   0

Above is the dataframe I want to create.

The first row represents the field names.  The logic I want to employ is as follows:
If the column name is in the "Column A" row, then 1 otherwise 0

I have scoured Google looking for code answering a question similar to mine so I can test it out and backward engineer a solution.  Unfortunately, I have not been able to find anything.

Otherwise I would post some code that I attempted to solve this problem but I literally have no clue.

Body:
You can use a list comprehension to create the desire data based on the columns and rows:

In [39]: row =['2C 1B D2 6F ABC', '2C 1248 Bulers']

In [40]: columns=['2C', 'GAD', 'D2', '6F',  'ABCDE']

In [41]: df = pd.DataFrame([[int(k in r) for k in columns] for r in row], index = ['2C 1B D2 6F ABC','2C 1248 Bulers'], columns=['2C', 'GAD', 'D2', '6F',  'ABCDE'])

In [42]: df
Out[42]:
                 2C  GAD  D2  6F  ABCDE
2C 1B D2 6F ABC   1    0   1   1      0
2C 1248 Bulers    1    0   0   0      0

If you want a pure Pandas approach you can use pd.Series() instead of list for preserving the columns and rows then use Series.apply and Series.str.contains to get the desire result:

In [73]: data = columns.apply(row.str.contains).astype(int).transpose()

In [74]: df = pd.DataFrame(data.values, index = ['2C 1B D2 6F ABC','2C 1248 Bulers'], columns=['2C', 'GAD', 'D2', '6F',  'ABCDE'])

In [75]: df
Out[75]:
                 2C  GAD  D2  6F  ABCDE
2C 1B D2 6F ABC   1    0   1   1      0
2C 1248 Bulers    1    0   0   0      0


问:
on blur in react is not closing my nav menu
I am new to React and have a nav menu (.mega-menu-overlay) built in React that I am changing to be clickable instead showing/hiding via on mouseover and on mouseout. The function that previously worked to close the menu, when using onmouseover, is called handleMenuLeave(). Any insight as to what I am doing wrong would be great. My code is below:</p>

```<code>componentDidMount() {
    document.addEventListener('scroll', () => {
      if (this.state.megaMenuContent) {
        if (window.scrollY >= 50) {
          window.requestAnimationFrame(() => {
            this.handleMenuLeave();
          });
        }
      }
      });
    if(document.querySelector('.mega-menu-overlay')){
        document.querySelector('.mega-menu-overlay').addEventListener('blur', () => {
            this.handleMenuLeave();
            alert('clicked');
        });
    }
  }
</code>```

答:
on blur in react is not closing my nav menu

If .mega-menu-overlay is not a form element, button, or link, the blur event will not be triggered.

document.querySelector('div').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})
document.querySelector('input').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})

document.querySelector('a').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})
document.querySelector('button').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
  border:1px solid black;
  padding:15px 0;
}
div:nth-child(odd){
  background:green;
}</code>```

hello world

<input type="text" />
Click me
<button>
Click me
</button>```
</div>
</div>
</p>

<blockquote>
  <p>Do you know how I can make it close using clicks on every other
  element?</p>
</blockquote>

<p>You can get every other element using a CSS selector such as <code>div:nth-child(odd)</code> and then attach an event listener to each element.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelectorAll('div:nth-child(odd)').forEach(function(div){
 div.addEventListener('click',function(e){
  this.style.display = "none"
 })
})</code>```

div{
  border:1px solid black;
  padding:15px 0;
}
div:nth-child(odd){
  background:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
First
</div>
<div>
Second
</div>
<div>
Third
</div>
<div>
Fourth
</div></code>```

Body:
I am new to React and have a nav menu (.mega-menu-overlay) built in React that I am changing to be clickable instead showing/hiding via on mouseover and on mouseout. The function that previously worked to close the menu, when using onmouseover, is called handleMenuLeave(). Any insight as to what I am doing wrong would be great. My code is below:

componentDidMount() {
    document.addEventListener('scroll', () => {
      if (this.state.megaMenuContent) {
        if (window.scrollY >= 50) {
          window.requestAnimationFrame(() => {
            this.handleMenuLeave();
          });
        }
      }
      });
    if(document.querySelector('.mega-menu-overlay')){
        document.querySelector('.mega-menu-overlay').addEventListener('blur', () => {
            this.handleMenuLeave();
            alert('clicked');
        });
    }
  }

Body:
on blur in react is not closing my nav menu

If .mega-menu-overlay is not a form element, button, or link, the blur event will not be triggered.

document.querySelector('div').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})
document.querySelector('input').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})

document.querySelector('a').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})
document.querySelector('button').addEventListener('blur', function(e){
 console.log(e.target.tagName)
})

div{
  border:1px solid black;
  padding:15px 0;
}
div:nth-child(odd){
  background:green;
}

<div>
hello world
</div>
<input type="text" />
<a href="#">Click me</a>
<button>
Click me
</button>

Do you know how I can make it close using clicks on every other
  element?

You can get every other element using a CSS selector such as div:nth-child(odd) and then attach an event listener to each element.

document.querySelectorAll('div:nth-child(odd)').forEach(function(div){
 div.addEventListener('click',function(e){
  this.style.display = "none"
 })
})

div{
  border:1px solid black;
  padding:15px 0;
}
div:nth-child(odd){
  background:green;
}

<div>
First
</div>
<div>
Second
</div>
<div>
Third
</div>
<div>
Fourth
</div>


问:
How to effectively check if a string contains one of a few sub strings?
How can I effectively check if a string contains one of a few sub strings?
Suppose I have a string:

```<code>`Hi there, <B>my</B> name is Joe <DIV>.</DIV> Hello world.  `
</code>```

How can I check if the string contains either  OR
 OR  ?

I could do a simple:

```<code>Result := (Pos('<B>', S) > 0) or
          (Pos('<DIV>', S) > 0) or
          (Pos(' ', S) > 0);
</code>```

But this seems to be very inefficient since it make N (at worst) passes and my strings are considerably large.

答:
Slightly better version:

```<code>function StringContainsAny(const S: string; const AnyOf: array of string): Boolean;
var
  CurrChr, C: PChar;
  i, j, Ln: Integer;
begin
  for i := 1 to Length(S) do
  begin
    CurrChr := @S[i];
    for j := 0 to High(AnyOf) do
    begin
      C := @AnyOf[j][1]; // assume that no empty strings
      if C^ <> CurrChr^ then
        Continue;

      Ln := Length(AnyOf[j]);
      if (Length(S) + 1 - i) < Ln then // check bounds
        Continue;

      if CompareMem(C, CurrChr, Ln * SizeOf(C^)) then
        Exit(True);
    end;
  end;

  Exit(False);
end;
</code>```

You can also build some table of stop-symbols and improve speed. It's kinda complex topic, so I can just suggest you to read, for example, book Bill Smyth "Computing Patterns in Strings".

Body:
How can I effectively check if a string contains one of a few sub strings?
Suppose I have a string:

`Hi there, <B>my</B> name is Joe <DIV>.</DIV> Hello world.  `

How can I check if the string contains either  OR
 OR  ?

I could do a simple:

Result := (Pos('', S) > 0) or
          (Pos('
', S) > 0) or
          (Pos(' ', S) > 0);

But this seems to be very inefficient since it make N (at worst) passes and my strings are considerably large.

Body:
Slightly better version:

function StringContainsAny(const S: string; const AnyOf: array of string): Boolean;
var
  CurrChr, C: PChar;
  i, j, Ln: Integer;
begin
  for i := 1 to Length(S) do
  begin
    CurrChr := @S[i];
    for j := 0 to High(AnyOf) do
    begin
      C := @AnyOf[j][1]; // assume that no empty strings
      if C^ <> CurrChr^ then
        Continue;

      Ln := Length(AnyOf[j]);
      if (Length(S) + 1 - i) < Ln then // check bounds
        Continue;

      if CompareMem(C, CurrChr, Ln * SizeOf(C^)) then
        Exit(True);
    end;
  end;

  Exit(False);
end;

You can also build some table of stop-symbols and improve speed. It's kinda complex topic, so I can just suggest you to read, for example, book Bill Smyth "Computing Patterns in Strings".


问:
Standart rowwise vector matrix operations
I am searching for rowwise vector matrix operations( I think that should be  BLAS level 2 routines). For example to substruct a vector from a matrix rowwise, or to normalize matrix by it rows sum. Are there such optimized standard routines?</p>

答:
Unfortunately, there is no such operation in BLAS. All the available subroutines are listed here: http://www.netlib.org/lapack/lug/node145.html

You can write your own subroutines and call BLAS level 1 for jobs like norm, axpy, etc... However, the gain in performance is generally modest.

-> BLAS is really important for matrix-matrix (or matrix-vector) products where cache management, data locality and access pattern make a really big difference (in perfs).


问:
How to translate qt key press event to osg event?
In my osg Eventhandler, I have the following code

```<code>if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT){
   do something
}
</code>```

ea is the osgGA::GUIEventAdapter. In the osgwidget the keypress event is handled by

```<code>void OSGWidget::keyPressEvent(QKeyEvent *event)
{
QString keyString = event->text();
const char *keyData = keyString.toLocal8Bit().data();
this->getEventQueue()->keyPress(osgGA::GUIEventAdapter::KeySymbol(*keyData));
}
</code>```

However, when I run my code, it seems the osgGA::GUIEventAdapter can't capture the shift key press event. What should I do to make it work?

答:
"SHIFT" key is a modifier key.

And your event->text() returns an empty string, when you ask for SHIFT key press.

Try below said way to handle SHIFT key...

```<code>if (event->modifiers() == Qt::ShiftModifier)
{
    //SET SHIFT KEY TO OPENSCENEGRAPH
}
</code>```

Body:
In my osg Eventhandler, I have the following code

if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT){
   do something
}

ea is the osgGA::GUIEventAdapter. In the osgwidget the keypress event is handled by

void OSGWidget::keyPressEvent(QKeyEvent *event)
{
QString keyString = event->text();
const char *keyData = keyString.toLocal8Bit().data();
this->getEventQueue()->keyPress(osgGA::GUIEventAdapter::KeySymbol(*keyData));
}

However, when I run my code, it seems the osgGA::GUIEventAdapter can't capture the shift key press event. What should I do to make it work?

Body:
"SHIFT" key is a modifier key.

And your event->text() returns an empty string, when you ask for SHIFT key press.

Try below said way to handle SHIFT key...

if (event->modifiers() == Qt::ShiftModifier)
{
    //SET SHIFT KEY TO OPENSCENEGRAPH
}


问:
If a function creates and returns an object, should it be in the autorelease pool
I'm still pretty new to objective-c.

As far as I can understand, any object I do not get from alloc, new, copy, or mutableCopy should be assumed to be in the autorelease pool.

I assume that also means that if I create a function that creates and returns a new instance of an object, I should place that in the autorelease pool before returning.

For example, I have a function that parses xml, and returns an object representing the data in the xml, that object should be in the autorelease pool before returning.

My primary concern is iPhone development, but a general answer would be appreciated.

答:
Yep, your right. If you allocated memory in your function you are also responsible for releasing it. Because you are returning the allocated object, the only way for you to release it, in this situation, is by placing it in the autorelease pool, e.g.

```<code>return [newObject autorelease];
</code>```

(edit)

Body:
Yep, your right. If you allocated memory in your function you are also responsible for releasing it. Because you are returning the allocated object, the only way for you to release it, in this situation, is by placing it in the autorelease pool, e.g.

return [newObject autorelease];

(edit)


问:
How to use tf_remap?
I have a rosbag in which a /tf topic is recorded.

I need to remap all tf frames in that bag which refer to the frame named /world to refer to a new frame named /vision. I tried the following but it's unfortunately not working:

```<code>rosrun tf tf_remap _mappings:='[{old: /world, new: /vision}]'
</code>```

Am I missing something?

I have also tried to do it from a launch file:

    <launch>
      <node pkg="tf" type="tf_remap" name="tf_remapper" output="screen">
        <rosparam param="mappings">
          - {old: "/world",
             new: "/vision"}
        </rosparam>
      </node>
    </launch>
```
<p>Same result...</p>
<p>I found people saying that, in addition to running the <code>tf_remap</code> node, <code>rosbag</code> should be run as follows:</p>
```rosbag play x.bag /tf:=/tf_old
```

Also did that... still not working.

The tf_frames are still referring to /world rather than /vision.

Any help would be highly appreciated!

Edit

This is to clarify more what I am trying to achieve:

What I want is to remap all the frames recorded in the bag and referring to /world, and make them refer to /vision instead. There should be no /world frame in the remapped output of the bag. Somewhere else in the code, I will define the frame named /world and its relation to /vision.

答:
You could edit the contents of the bag file using the rosbag python/c++ API. Here is an example with python that would just replace any instance of /world with /vision in your bag's recorded /tf msgs.

import rosbag
from copy import deepcopy
import tf

bagInName = '___.bag'
bagIn = rosbag.Bag(bagInName)
bagOutName = '___fixed.bag'
bagOut = rosbag.Bag(bagOutName,'w')
with bagOut as outbag:
    for topic, msg, t in bagIn.read_messages():
        if topic == '/tf':
            new_msg = deepcopy(msg)
            for i,m in enumerate(msg.transforms): # go through each frame->frame tf within the msg.transforms
                if m.header.frame_id == "/world":
                    m.header.frame_id = "/vision"
                    new_msg.transforms[i] = m
                if m.child_frame_id == "/world":
                    m.child_frame_id = "/vision"
                    new_msg.transforms[i] = m

            outbag.write(topic, new_msg, t)
        else:
            outbag.write(topic, msg, t)

bagIn.close()
bagOut.close()
```

ContentLicense: CC BY-SA 4.0

Title: How to use tf_remap?

Body:
I have a rosbag in which a /tf topic is recorded.

I need to remap all tf frames in that bag which refer to the frame named /world to refer to a new frame named /vision. I tried the following but it's unfortunately not working:

rosrun tf tf_remap _mappings:='[{old: /world, new: /vision}]'

Am I missing something?

I have also tried to do it from a launch file:

    <launch>
      <node pkg="tf" type="tf_remap" name="tf_remapper" output="screen">
        <rosparam param="mappings">
          - {old: "/world",
             new: "/vision"}
        </rosparam>
      </node>
    </launch>

Same result...

I found people saying that, in addition to running the tf_remap node, rosbag should be run as follows:

rosbag play x.bag /tf:=/tf_old

Also did that... still not working.

The tf_frames are still referring to /world rather than /vision.

Any help would be highly appreciated!

Edit

This is to clarify more what I am trying to achieve:

What I want is to remap all the frames recorded in the bag and referring to /world, and make them refer to /vision instead. There should be no /world frame in the remapped output of the bag. Somewhere else in the code, I will define the frame named /world and its relation to /vision.


问:
PrtScn Button in the IE not behaving as other browsers using java script
I've been using the following javascript code that blocks Normal users (not professionals of course) from using print screen & Ctrl+A &  Ctrl+C on the browser.
it does work as expected on Firefox & Chrome but it sometimes works on IE and some other times it fails. Please review the code if you can a little help of maybe what's going wrong on IE. and why it fails?</p>

```<code>function disableselect(e) {
    return false;
}
function reEnable() {
    return true;
}
document.onselectstart = new Function("return false");
if (window.sidebar) {
    document.onmousedown = disableselect;
    document.onclick = reEnable;
}
function copyToClipboard() {
  // Create a "hidden" input
  var aux = document.createElement("input");
  // Assign it the value of the specified element
  aux.setAttribute("value", "You can no longer give print-screen. This is part of the new system security measure");
  // Append it to the body
  document.body.appendChild(aux);
  // Highlight its content
  aux.select();
  // Copy the highlighted text
  document.execCommand("copy");
  // Remove it from the body
  document.body.removeChild(aux);
  alert("You can no longer give print-screen. This is part of the new system security measure.");
}
$(window).keyup(function(e){
  if(e.keyCode == 44){
    copyToClipboard();
  }
});
$(window).focus(function() {
  $("body").show();
}).blur(function() {
  $("body").hide();
});
</code>```

答:
I have tested it and it works for me using Chrome, Firefox, IE11.

But, if someone use Inspect Element to disable CSS restriction, then he will disable it :)

Body:
I've been using the following javascript code that blocks Normal users (not professionals of course) from using print screen & Ctrl+A &  Ctrl+C on the browser.
it does work as expected on Firefox & Chrome but it sometimes works on IE and some other times it fails. Please review the code if you can a little help of maybe what's going wrong on IE. and why it fails?

function disableselect(e) {
    return false;
}
function reEnable() {
    return true;
}
document.onselectstart = new Function("return false");
if (window.sidebar) {
    document.onmousedown = disableselect;
    document.onclick = reEnable;
}
function copyToClipboard() {
  // Create a "hidden" input
  var aux = document.createElement("input");
  // Assign it the value of the specified element
  aux.setAttribute("value", "You can no longer give print-screen. This is part of the new system security measure");
  // Append it to the body
  document.body.appendChild(aux);
  // Highlight its content
  aux.select();
  // Copy the highlighted text
  document.execCommand("copy");
  // Remove it from the body
  document.body.removeChild(aux);
  alert("You can no longer give print-screen. This is part of the new system security measure.");
}
$(window).keyup(function(e){
  if(e.keyCode == 44){
    copyToClipboard();
  }
});
$(window).focus(function() {
  $("body").show();
}).blur(function() {
  $("body").hide();
});


问:
TypeError: Cannot read property 'splice' of undefined
I've created a fixture file to handle my JSON datas used to write tests.

Before each test, I want my data to be filled with seed data.
After each test, I want my data to be empty

Courses.json :

```<code>[
  {
    "id": 1,
    "title": "Ma course"
  }
]
</code>```

CoursesFixture.js :

```<code>const { courseList } = require('./courses')

mockData = [
  {
    "id": 1,
    "title": "Ma course"
  }
]

module.exports = {
  up: () => {
    courseList.splice(0)
    courseList.push.apply(courseList, mockData)
  },

  down: () => {
    courseList.splice(0)
  }
}
</code>```

CoursesTest.js :

```<code>const request = require("supertest")
require('chai').should()
const bodyParser = require("body-parser")

const app = require('./../../app')
app.use(bodyParser.json())

const listeDeCourses = require("../fixtures/courses")
const listeDeCoursesFixture = require("../fixtures/coursesFixture")

describe('Courses', () =>{

    beforeEach(() => { listeDeCoursesFixture.up() })
    afterEach(() => { listeDeCoursesFixture.down() })

    describe('Delete course list', ()=>{
        it("Should delete a list of course", ()=>{
           return  request(app).get('/course')
                        .then((res) => {
                           res.body.should.have.lengthOf(1)
                           request(app).delete('/course').send({"id":"1"})
                           .then((res) => {
                                res.body.should.have.lengthOf(0)
                           })

                        }).catch((err)  =>{
                            throw new Error(err);
                         })
                    })
                })
    describe('Create course list', () =>{
        it("Should create a list of courses", () =>{
            return request(app).post('/course').send({"id":3,"title":"Première course"}).then((res) => {
                res.status.should.be.eq(200)
                const listCourses = res.body
                const lastCourse = res.body[1]
                listCourses.should.be.a('array')
                lastCourse.id.should.be.eq(3)
                lastCourse.title.should.be.eq("Première course")
                listCourses[listCourses.length - 1].should.be.eq(lastCourse)
            }).catch((err) => {
                throw new Error(err)
            })
        })
    })

    describe('Get course list', ()=>{
        it("Should get a list of all courses", ()=>{
           return  request(app).get('/course')
                        .then((res) => {
                           res.body.should.have.lengthOf(1)
                        }).catch((err)  =>{
                           console.log(err)
                            throw new Error(err);
                         })
        })
    })
})
</code>```

My problem is that when I launch my test I have an error :

```<code>TypeError: Cannot read property 'splice' of undefined
</code>```

I think the problem is in CoursesFixture.js and surely a syntax error somewhere but I can't find where it is.

答: const { courseList } = require('./courses') should be const courseList = require('./courses')?

Body:
I've created a fixture file to handle my JSON datas used to write tests.

Before each test, I want my data to be filled with seed data.
After each test, I want my data to be empty

Courses.json :

[
  {
    "id": 1,
    "title": "Ma course"
  }
]

CoursesFixture.js :

const { courseList } = require('./courses')

mockData = [
  {
    "id": 1,
    "title": "Ma course"
  }
]

module.exports = {
  up: () => {
    courseList.splice(0)
    courseList.push.apply(courseList, mockData)
  },

  down: () => {
    courseList.splice(0)
  }
}

CoursesTest.js :

const request = require("supertest")
require('chai').should()
const bodyParser = require("body-parser")

const app = require('./../../app')
app.use(bodyParser.json())

const listeDeCourses = require("../fixtures/courses")
const listeDeCoursesFixture = require("../fixtures/coursesFixture")

describe('Courses', () =>{

    beforeEach(() => { listeDeCoursesFixture.up() })
    afterEach(() => { listeDeCoursesFixture.down() })

    describe('Delete course list', ()=>{
        it("Should delete a list of course", ()=>{
           return  request(app).get('/course')
                        .then((res) => {
                           res.body.should.have.lengthOf(1)
                           request(app).delete('/course').send({"id":"1"})
                           .then((res) => {
                                res.body.should.have.lengthOf(0)
                           })

                        }).catch((err)  =>{
                            throw new Error(err);
                         })
                    })
                })
    describe('Create course list', () =>{
        it("Should create a list of courses", () =>{
            return request(app).post('/course').send({"id":3,"title":"Première course"}).then((res) => {
                res.status.should.be.eq(200)
                const listCourses = res.body
                const lastCourse = res.body[1]
                listCourses.should.be.a('array')
                lastCourse.id.should.be.eq(3)
                lastCourse.title.should.be.eq("Première course")
                listCourses[listCourses.length - 1].should.be.eq(lastCourse)
            }).catch((err) => {
                throw new Error(err)
            })
        })
    })

    describe('Get course list', ()=>{
        it("Should get a list of all courses", ()=>{
           return  request(app).get('/course')
                        .then((res) => {
                           res.body.should.have.lengthOf(1)
                        }).catch((err)  =>{
                           console.log(err)
                            throw new Error(err);
                         })
        })
    })
})

My problem is that when I launch my test I have an error :

TypeError: Cannot read property 'splice' of undefined

I think the problem is in CoursesFixture.js and surely a syntax error somewhere but I can't find where it is.


问:
Neater way to write huge lists for creating named tuples with default values
I have a named tuple object defined with 63 different items in it. I use the _make function. I think this approach will work but need 4x63 more rows for the try except statements. There has to be a better way:

```<code>AssetRow = collections.namedtuple('AssetRow', [
    "status",
    "computer_name",
    .
    .
    .
    61 more

def create_asset_row(Object):
    try:
        Object.status
    except
        Object.status = ""
    try:
        Object.computer_name
    except
        Object.computer_name= ""
    values = [
        Object.status,
        Object.computer_name,
        .
        .
        .
        61 more
    ]
    row = AssetRow._make(values)
</code>```

basically I want to make sure the named tuple is set to "" if I don't have a value to put in it.... but I don't want to write 500 lines to do it... I want to write about 67 lines

答:
Would something like this work? I'm not too familiar with the namedtuple class.

```<code>names = ["status", "computer_name"]
AssetRow = collections.namedtuple('AssetRow', names)

def create_asset_row(Object):
    values = [getattr(Object, name, "") for name in names]
    row = AssetRow._make(values)
</code>```

Body:
I have a named tuple object defined with 63 different items in it. I use the _make function. I think this approach will work but need 4x63 more rows for the try except statements. There has to be a better way:

AssetRow = collections.namedtuple('AssetRow', [
    "status",
    "computer_name",
    .
    .
    .
    61 more

def create_asset_row(Object):
    try:
        Object.status
    except
        Object.status = ""
    try:
        Object.computer_name
    except
        Object.computer_name= ""
    values = [
        Object.status,
        Object.computer_name,
        .
        .
        .
        61 more
    ]
    row = AssetRow._make(values)

basically I want to make sure the named tuple is set to "" if I don't have a value to put in it.... but I don't want to write 500 lines to do it... I want to write about 67 lines

Body:
Would something like this work? I'm not too familiar with the namedtuple class.

names = ["status", "computer_name"]
AssetRow = collections.namedtuple('AssetRow', names)

def create_asset_row(Object):
    values = [getattr(Object, name, "") for name in names]
    row = AssetRow._make(values)


问:
SQL Union on the Join subsets
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

```<code>create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID
</code>```

This gives out the response:

```<code>aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00
</code>```

But what is required is:

```<code>aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
</code>```

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

```<code>with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;
</code>```

答:
This is a pretty simple way to do it using your existing code and just wrapping it in a CTE. I've used a table variable so I can run it as a prototype locally without the drop statement, otherwise the code is all yours except the CTE wrapper.</p>

```<code>DECLARE @test AS TABLE
  (
       [id]               VARCHAR(10)
       , [cv_modstamp]    DATETIMEOFFSET
       , [sf_deleteddate] DATETIMEOFFSET
  );

INSERT INTO @test
VALUES      ('aaa','2017-10-27 18:45:44 +00:00',NULL),
            ('bbb','2017-10-27 18:45:44 +00:00',NULL),
            ('eee','2017-10-27 18:45:44 +00:00',NULL),
            ('aaa','2017-10-28 22:45:44 +00:00',NULL),
            ('bbb','2017-10-28 22:45:44 +00:00','2017-10-28 22:45:44 +00:00'),
            ('ccc','2017-10-28 22:45:44 +00:00',NULL),
            ('ddd','2017-10-28 22:45:44 +00:00','2017-10-28 22:45:44 +00:00');

SELECT *
FROM   @test;

WITH [builder]
     AS (SELECT [D1].[id]            AS [d1_id]
                , [D1].[cv_modstamp] AS [d1_cv_modstamp]
                , [D2].[id]          AS [d2_id]
                , [D2].[cv_modstamp] AS [d2_cv_modstamp]
         FROM   (SELECT [A].*
                 FROM   @test [A]
                        , (SELECT [id]                 AS [T_ALIAS_ID]
                                  , MAX([CV_Modstamp]) AS [T_ALIAS_lastModTime]
                           FROM   @test
                           WHERE  [CV_Modstamp] <= '2017-11-14 18:45:44 +00:00'
                           GROUP  BY [id]) [T]
                 WHERE  [A].[id] = [T].[T_ALIAS_ID]
                        AND [A].[CV_Modstamp] = [T].[T_ALIAS_lastModTime]
                        AND [A].[SF_Deleteddate] IS NULL) [D1]
                INNER JOIN (SELECT [A].*
                            FROM   @test [A]
                                   , (SELECT [id]                 AS [T_ALIAS_ID]
                                             , MAX([CV_Modstamp]) AS [T_ALIAS_lastModTime]
                                      FROM   @test
                                      WHERE  [CV_Modstamp] <= '2017-10-27 18:45:44 +00:00'
                                      GROUP  BY [id]) [T]
                            WHERE  [A].[id] = [T].[T_ALIAS_ID]
                                   AND [A].[CV_Modstamp] = [T].[T_ALIAS_lastModTime]
                                   AND [A].[SF_Deleteddate] IS NULL) [D2]
                        ON [D1].[ID] = [D2].[ID]) SELECT [d1_id]
       , [d1_cv_modstamp]
FROM   [builder]
UNION ALL
SELECT [d2_id]
       , [d2_cv_modstamp]
FROM   [builder];
</code>```

Title: SQL Union on the Join subsets

Body:
I've got a specific requirement where the backend is supposed to send records that match on a certain criteria from a table. There is a version table that basically contains
[id, ..., modstamp, deleted]
The requirement is to get the records that match between timestamp t1 and t2.
I think I could explain with respect to the sql script:

create table test (id varchar(10), cv_modstamp DATETIMEOFFSET, sf_deleteddate DATETIMEOFFSET);
insert into test values ('aaa', '2017-10-27 18:45:44 +00:00', null);
insert into test values ('bbb', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('eee', '2017-10-27 18:45:44 +00:00', NULL);
insert into test values ('aaa', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('bbb', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
insert into test values ('ccc', '2017-10-28 22:45:44 +00:00', NULL);
insert into test values ('ddd', '2017-10-28 22:45:44 +00:00', '2017-10-28 22:45:44 +00:00');
select * from test;

select D1.*, D2.* from
(
select A.*
FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
                  GROUP BY id) T
WHERE A.id = T.T_ALIAS_ID
 AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
 AND   A.SF_Deleteddate IS NULL
) D1
INNER JOIN
 (
    select A.*
    FROM TEST A, (SELECT id AS T_ALIAS_ID, MAX(CV_Modstamp) AS T_ALIAS_lastModTime
                  FROM TEST
                  WHERE CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
                  GROUP BY id) T
    WHERE A.id = T.T_ALIAS_ID
    AND   A.CV_Modstamp = T.T_ALIAS_lastModTime
    AND   A.SF_Deleteddate IS NULL
 )
D2 ON D1.ID = D2.ID

This gives out the response:

aaa 2017-10-28 22:45:44 +00:00      aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00      eee 2017-10-27 18:45:44 +00:00

But what is required is:

aaa 2017-10-28 22:45:44 +00:00
aaa 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00
eee 2017-10-27 18:45:44 +00:00

Is there a way to display the joined sets on union?

Edit:
Thanks all for the solutions. Each one is good enough for SQL Server. I wanted this to be achieved in a single query. Might be porting similar queries to other database flavors too.

Edit2:
What if the entire columnset have to be selected?

This can be achieved with CTE queries

with subset1 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp <= '2017-10-27 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)
, subset2 as
(
    select A.* FROM TEST A,
    (
        SELECT
            id AS T_ALIAS_ID,
            MAX( CV_Modstamp ) AS T_ALIAS_lastModTime
        FROM
            TEST
        WHERE
            CV_Modstamp > '2017-10-27 18:45:44 +00:00'
            AND CV_Modstamp <= '2017-11-14 18:45:44 +00:00'
        GROUP BY
            id
    ) T
    WHERE
        A.id = T.T_ALIAS_ID
        AND A.CV_Modstamp = T.T_ALIAS_lastModTime
        AND A.SF_Deleteddate IS NULL
)

select subset1.* from subset1, subset2 where subset1.id = subset2.id
union all
select subset2.* from subset1, subset2 where subset1.id = subset2.id
order by id, cv_modstamp;

Body:
This is a pretty simple way to do it using your existing code and just wrapping it in a CTE. I've used a table variable so I can run it as a prototype locally without the drop statement, otherwise the code is all yours except the CTE wrapper.

DECLARE @test AS TABLE
  (
       [id]               VARCHAR(10)
       , [cv_modstamp]    DATETIMEOFFSET
       , [sf_deleteddate] DATETIMEOFFSET
  );

INSERT INTO @test
VALUES      ('aaa','2017-10-27 18:45:44 +00:00',NULL),
            ('bbb','2017-10-27 18:45:44 +00:00',NULL),
            ('eee','2017-10-27 18:45:44 +00:00',NULL),
            ('aaa','2017-10-28 22:45:44 +00:00',NULL),
            ('bbb','2017-10-28 22:45:44 +00:00','2017-10-28 22:45:44 +00:00'),
            ('ccc','2017-10-28 22:45:44 +00:00',NULL),
            ('ddd','2017-10-28 22:45:44 +00:00','2017-10-28 22:45:44 +00:00');

SELECT *
FROM   @test;

WITH [builder]
     AS (SELECT [D1].[id]            AS [d1_id]
                , [D1].[cv_modstamp] AS [d1_cv_modstamp]
                , [D2].[id]          AS [d2_id]
                , [D2].[cv_modstamp] AS [d2_cv_modstamp]
         FROM   (SELECT [A].*
                 FROM   @test [A]
                        , (SELECT [id]                 AS [T_ALIAS_ID]
                                  , MAX([CV_Modstamp]) AS [T_ALIAS_lastModTime]
                           FROM   @test
                           WHERE  [CV_Modstamp] <= '2017-11-14 18:45:44 +00:00'
                           GROUP  BY [id]) [T]
                 WHERE  [A].[id] = [T].[T_ALIAS_ID]
                        AND [A].[CV_Modstamp] = [T].[T_ALIAS_lastModTime]
                        AND [A].[SF_Deleteddate] IS NULL) [D1]
                INNER JOIN (SELECT [A].*
                            FROM   @test [A]
                                   , (SELECT [id]                 AS [T_ALIAS_ID]
                                             , MAX([CV_Modstamp]) AS [T_ALIAS_lastModTime]
                                      FROM   @test
                                      WHERE  [CV_Modstamp] <= '2017-10-27 18:45:44 +00:00'
                                      GROUP  BY [id]) [T]
                            WHERE  [A].[id] = [T].[T_ALIAS_ID]
                                   AND [A].[CV_Modstamp] = [T].[T_ALIAS_lastModTime]
                                   AND [A].[SF_Deleteddate] IS NULL) [D2]
                        ON [D1].[ID] = [D2].[ID]) SELECT [d1_id]
       , [d1_cv_modstamp]
FROM   [builder]
UNION ALL
SELECT [d2_id]
       , [d2_cv_modstamp]
FROM   [builder];


问:
How to make multiplyList work? Haskell ref: https://en.wikibooks.org/wiki/Haskell/Lists_II
I am exercising the multiplyList function that uses applyToIntegers in GHCi.  I want it to multiply a list by 2. Below is what I tried and the error I got. Below that, for convenience, is an excerpt from Lists II.

The code in Lists II compiles OK. My problem is: where do I put the multiplier in the code?

I can use applyToIntegers by itself OK, and I can duplicate what it does using map. I just can't make the connection from multiplyList to applyToIntgers.

This is my first post as I am learning Haskell (which I had never heard of before last month!) from the excellent Haskell wikibook, and I must say that Haskell is the most beautiful high-level programming language I've ever encountered.

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
-- E.g., applyToIntegers (2*) [1..5] = [2,4,6,8,10], also
-–  map (2*) [1..5] = [2,4,6,8,10]

-- Unable to come up with a working example:
multiplyList :: Integer -> [Integer] -> [Integer]
--multiplyList m = applyToIntegers ((*) m) -- Compiles OK.
-- If I try:
multiplyList m = applyToIntegers ((2*) m)
</code>```

I get the following:

```<code>*Main> :l ods.hs
[1 of 1] Compiling Main             ( ods.hs, interpreted )

ods.hs:15:35: error:
    • Couldn't match expected type ‘Integer -> Integer’
                  with actual type ‘Integer’
    • Possible cause: ‘2 *’ is applied to too many arguments
      In the first argument of ‘applyToIntegers’, namely ‘((2 *) m)’
      In the expression: applyToIntegers ((2 *) m)
      In an equation for ‘multiplyList’:
      multiplyList m = applyToIntegers ((2 *) m)
Failed, modules loaded: none.
Prelude>
</code>```

https://en.wikibooks.org/w/index.php?title=Haskell/Lists_II&oldid=3242682

We need a function that takes any other appropriate function and applies the

      given function to the elements of a list:

```<code>applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
</code>```

With applyToIntegers, we can take any Integer -> Integer function and apply
      it to the elements of a list of Integers. We can thus use this generalized
      function to redefine multiplyList:```<code>multiplyList :: Integer -> [Integer] -> [Integer]
multiplyList m = applyToIntegers ((*) m)</code>```

That uses the (*) function with a single initial argument to create a new
      function which is ready to take one more argument (which, in this use case,
      will come from the numbers in a given list).

答:
The type signature of multiplyList:

Integer -> [Integer] -> [Integer]

says it takes an integer, a list of integers, and it returns a list of integers.

Therefore, multiplyList is intended to take the parameter to multiply the list by.

If we want to multiply by 2, using the definition of multiplyList:

multiplyList m = applyToIntegers ((*) m)

we can just call multiplyList 2 [1..3] == [2,4,6].

It's a bit easier to demonstrate how multiplyList works if we simply the definition to

multiplyList n xs = applyToIntegers (\x -> x * n) xs.

This is exactly the same as the previous definition, just written in a way which you might find easier to understand.

This says that multiplyList takes an integer n, and a list xs, and passes a function which multiplies by n, and the list xs to applyToIntegers.

applyToIntegers then applies that multiply function to every item in the list.

In conclusion, you simply need to call multiplyList with the value to multiply by. We could separate this into a separate function, if you like:

multiplyListByTwo xs = multiplyList 2 xs

which can be eta reduced to multiplyListByTwo = multiplyList 2

We can then use this function on any list, and the values will be multiplied by 2.

multiplyListByTwo [1..3] would give [2,4,6].

Body:
I am exercising the multiplyList function that uses applyToIntegers in GHCi.  I want it to multiply a list by 2. Below is what I tried and the error I got. Below that, for convenience, is an excerpt from Lists II.

The code in Lists II compiles OK. My problem is: where do I put the multiplier in the code?

I can use applyToIntegers by itself OK, and I can duplicate what it does using map. I just can't make the connection from multiplyList to applyToIntgers.

This is my first post as I am learning Haskell (which I had never heard of before last month!) from the excellent Haskell wikibook, and I must say that Haskell is the most beautiful high-level programming language I've ever encountered.

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns
-- E.g., applyToIntegers (2*) [1..5] = [2,4,6,8,10], also
-–  map (2*) [1..5] = [2,4,6,8,10]

-- Unable to come up with a working example:
multiplyList :: Integer -> [Integer] -> [Integer]
--multiplyList m = applyToIntegers ((*) m) -- Compiles OK.
-- If I try:
multiplyList m = applyToIntegers ((2*) m)

I get the following:

*Main> :l ods.hs
[1 of 1] Compiling Main             ( ods.hs, interpreted )

ods.hs:15:35: error:
    • Couldn't match expected type ‘Integer -> Integer’
                  with actual type ‘Integer’
    • Possible cause: ‘2 *’ is applied to too many arguments
      In the first argument of ‘applyToIntegers’, namely ‘((2 *) m)’
      In the expression: applyToIntegers ((2 *) m)
      In an equation for ‘multiplyList’:
      multiplyList m = applyToIntegers ((2 *) m)
Failed, modules loaded: none.
Prelude>

https://en.wikibooks.org/w/index.php?title=Haskell/Lists_II&oldid=3242682

We need a function that takes any other appropriate function and applies the

      given function to the elements of a list:

applyToIntegers :: (Integer -> Integer) -> [Integer] -> [Integer]
applyToIntegers _ [] = []
applyToIntegers f (n:ns) = (f n) : applyToIntegers f ns

With applyToIntegers, we can take any Integer -> Integer function and apply
      it to the elements of a list of Integers. We can thus use this generalized
      function to redefine multiplyList:
multiplyList :: Integer -> [Integer] -> [Integer]
multiplyList m = applyToIntegers ((*) m)

That uses the (*) function with a single initial argument to create a new
      function which is ready to take one more argument (which, in this use case,
      will come from the numbers in a given list).


问:
How does the Entity.DbSet.Find() method work in MVC3 context?
I'm following the MVC3 Music Store tutorial and this line of code kind of confuses me.

```<code>public ActionResult Details(int id)
{
    var album = storeDb.Albums.Find(id);
    return View(album);
}
</code>```

Here is the Album.cs model:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcMusicStore.ViewModels
{
    public class Album
    {
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string AlbumArtUrl { get; set; }
        public Genre Genre { get; set; }
    }
}
</code>```

When I visit the /Details/5 URL, how does it know to map the 'id' parameter to the Album's AlbumId attribute?

Thanks for the help.

答: There is no find method in Linq. There is no relation between linq and Mvc that makes linq work in a different way. It is a method of the member storeDb. So the easiest way to get to know how the find method works is inspecting the type of storeDb.

OwnerDisplayName: delete

LastEditorDisplayName: delete

Body:
I'm following the MVC3 Music Store tutorial and this line of code kind of confuses me.

public ActionResult Details(int id)
{
    var album = storeDb.Albums.Find(id);
    return View(album);
}

Here is the Album.cs model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcMusicStore.ViewModels
{
    public class Album
    {
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string AlbumArtUrl { get; set; }
        public Genre Genre { get; set; }
    }
}

When I visit the /Details/5 URL, how does it know to map the 'id' parameter to the Album's AlbumId attribute?

Thanks for the help.


问:
How to create a list of all ticked/non-ticked filter in an excel pivot table
This, I hope, is a really simple question but it might not be possible.

In excel, I have used multiple filters in a pivot table, I now want to create a list of the options ticked from the various filters.

How can I create a list/copy all the ticked (or un-ticked) boxes. I have around 800 filters with about 250 boxes ticked.

答:
The Manual approach:

Select a cell in the PivotTable. Then from the PivotTable Tools>Analyze tab use the Select icon to select the entire PivotTable. Copy it and paste it somewhere else. Drag every field out of it, leaving just the Customers field in it as a Rows field. There's your list.

If you add a slicer, and connect it to both PivotTables, then any changes to the Customer field in your original Pivot will flow through to this new one.

The VBA Approach:

See my UDF at https://superuser.com/questions/1254703/add-slicer-selections-to-sheet-in-a-list-excel-vba/1255885#1255885

And if you want a way to 'recall' a filter, then check out my answer here:
Pivotfields multiple filter


问:
Can Android Pay be disabled in-app?
I am looking for a way to suppress Android Pay app for one activity. iOS has requestAutomaticPassPresentationSuppressionWithResponseHandler method, which allows exactly this - suppressing Apple Pay while the app is in the foreground - I am trying to achieve this on Android.

I have implemented foreground dispatch. This works fine for most NFC tags - tag gets detected in the activity and then is ignored. However, when contactless payment machine is detected, Android Pay app gets triggered instead and I never get onNewIntent call in my activity.

Other than implementing the app to do card emulation and ignoring these requests, which is not really an option for a few reasons, is there anything else I could do to suppress Android Pay? (and other similar payment apps with focus on Android Pay as most popular)

答:
On Android 4.4 and above, you could use the reader-mode API to explicitly switch the device into reader/writer mode for a specific tag technology. This would disable the other NFC modes (peer-to-peer mode ("Android Beam") and card emulation mode).

```<code>nfcAdapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
    public void onTagDiscovered(Tag tag) { }
}, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK, null);
</code>```

Since you also want to ignore discovered tags, you could then simply drop (ignore) the tag handle received through the onTagDiscovered().

Title: Can Android Pay be disabled in-app?

Body:
On Android 4.4 and above, you could use the reader-mode API to explicitly switch the device into reader/writer mode for a specific tag technology. This would disable the other NFC modes (peer-to-peer mode ("Android Beam") and card emulation mode).

nfcAdapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
    public void onTagDiscovered(Tag tag) { }
}, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK, null);

Since you also want to ignore discovered tags, you could then simply drop (ignore) the tag handle received through the onTagDiscovered().


问:
Use cases of methods of QueryByExampleExecutor<T> interface in Spring data JPA
What are the use cases of the methods of this interface QueryByExampleExecutor<T> in Spring data JPA. I have googled and found nothing more than the official documentation.

Perhaps someone can point me to the right resource with examples.

In particular, is findAll(Example<S> example, Pagable pageable) of that interface a simpler way to search, paginate, and sort?

答:
The Spring Data JPA query-by-example technique uses Examples and ExampleMatchers to convert entity instances into the underlying query. The current official documentation has several useful examples. Here is my example inspired by documentation:

Person.java

```<code>public class Person {

  @Id
  private String id;
  private String firstname;
  private String lastname;
  private Address address;

  // … getters and setters omitted
}
</code>```

PersonResource.java:

```<code>@RestController
@RequestMapping("/api")
public class PersonResource {

@GetMapping("/persons/{name}")
@Timed
public ResponseEntity<List<Person>> getPersons(@ApiParam Pageable pageable, @PathVariable String  name) {
    log.debug("REST request to get Person by : {}", name);
    Person person = new Person();
    person.setFirstname(name);
    Page<Person> page = personRepository.findAll(Example.of(person), pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/persons");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
</code>```

Body:
The Spring Data JPA query-by-example technique uses Examples and ExampleMatchers to convert entity instances into the underlying query. The current official documentation has several useful examples. Here is my example inspired by documentation:

Person.java

public class Person {

  @Id
  private String id;
  private String firstname;
  private String lastname;
  private Address address;

  // … getters and setters omitted
}

PersonResource.java:

@RestController
@RequestMapping("/api")
public class PersonResource {

@GetMapping("/persons/{name}")
@Timed
public ResponseEntity<List<Person>> getPersons(@ApiParam Pageable pageable, @PathVariable String  name) {
    log.debug("REST request to get Person by : {}", name);
    Person person = new Person();
    person.setFirstname(name);
    Page<Person> page = personRepository.findAll(Example.of(person), pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/persons");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}


问:
How to make a buffer have a read-only in Sublime Text 2
This is not about those files that have their read-only flag set at the OS level, but about every file that users don't intend to modify.

I want Sublime Text to ignore any changes and prevent saving anything to such files. One example for this scenario is when the user is reading source code that shouldn't be altered in anyway.

"Just be really careful, and don't press any buttons" is undoubtedly a good advice, but if I were to "accidentally" delete that octothorpe in front of a comment, or add new lines to a file that is sensitive to such things (some config files in Linux) and then accidently hit save....

I found "toggle-readonly" at GitHub, but it is actually toggling the file permissions ("Read Only", "Write"), which is not quite what I wanted.

答:
The plugin "Toggle the View Read-Only" will do it. It basically does what MattDMo said: when you set the view as read-only, the file can still be changed by another program (or another user), and Sublime Text will pick up those changes. It also has the context menu item you asked for. I like the "Readonly" indicator in status bar.

I didn't test it on Sublime Text 2, but in Sublime Text 3 it works great, and it claims to work on Sublime Text 2 as well.


问:
For Loops, Application Hanging
Well I'm creating an application, I'm using for loops to basically read every pixel of an image looking for patterns in pixel color (simple stuff) Anyway for some reason my application simply locks up and never reverts back to normal. I've loop through the code time and time again without seeing any real problems.

The only thing I've noticed, is the for loop in ScanPixelsLater may be exiting early. I've commented the code as much as possible,

```<code>private Point topLeftc, bottomLeftc, topRightc, bottomRightc;

/// <summary>
/// Starts the initial looping process, designed only to loop through ONCE, ScanPixelsLater takes over
/// </summary>
/// <param name="img">Image to scan</param>
public void ScanPixels(Bitmap img)
{
    int whitePixel = 0;

    for (int y = 100; y < img.Height; y++)
    {

        for (int x = 100; x < img.Width; x++)
        {

            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                // img.SetPixel(x, y, Color.Green);
                whitePixel++;

            }
            else { whitePixel = 0; }

            if (whitePixel == 18)
            {
                whitePixel = 0;
                topLeftc = new Point(x - 18, y);
                DetectNextWhiteLine(topLeftc, img);

            }
        }
    }

}

/// <summary>
/// First creates the TopRight value via using the last pixel in x range, and using the current Y value
/// Then a Y loop is started 10 pixels down, within this loop is another X loop which scans the X range
/// If 10 consecutive white pixels are found, the TopLeft X value and the current Y value are used to map the
/// BottomLeft and BottomRight coordinates. Finally a new Point is created which starts (x = 1) and (y = currentYValue + 2)
/// The ScanPixelsLater method is then called, passing the new Point (newLocation).
///
/// </summary>
/// <param name="p">The x and y value of where the pixels were found</param>
/// <param name="img">Image being used</param>
private void DetectNextWhiteLine(Point p, Bitmap img)
{

    int whitePixel = 0;
    topRightc = new Point(img.Width, topLeftc.Y);

    for (int y = p.Y + 10; y < img.Height; y++)
    {

        for (int x = p.X - 5; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 10)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                bottomRightc = new Point(img.Width, y);
                Cords.Add(new Coordinates(topLeftc, topRightc, bottomLeftc, bottomRightc));

                Point newLocation = new Point(1, y + 2);
                calls++;
                ScanPixelsLater(newLocation, img); //rescan the image from new y axis
            }
        }
    }

}

/// <summary>
/// Loops through the pixels based on the p parameter, if 15 white pixels are found, the location (x & y) is
/// passed to the DetectNextWhiteLine method which fixes the next line with a similar number of white pixels.
/// </summary>
/// <param name="p">The Point(x,y) at which to start scanning</param>
/// <param name="img"></param>
private void ScanPixelsLater(Point p, Bitmap img)
{

    int whitePixel = 0;

    for (int y = p.Y; y < img.Height; y++)
    {

        for (int x = p.X; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 15)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                topLeftc = new Point(x - 15, y);
                calls++;
                DetectNextWhiteLine(topLeftc, img);
            }

        }
    }

    // only want this to execute after all the pixels within the entire img have been read
    // possibly executing early.

    DrawWhiteLines(img);
    AppArgs aa = new AppArgs(true);
    Change(this, aa); // custom event handler, fired behind form to update GUI

}
</code>```

答:
So, to understand why your application is hanging you need to know a little bit about how WinForm applications work.

The thread that your UI is running on also has what is called a message pump.  This message pump contains messages that get passed from the operating system (and other sources) to all of the UI elements.  They tell them when to change state, when to redraw themselves, etc.  When you have a long running loop like yours the message pump cannot process messages.  The get queued up, but never processed, and this is what it means for an application to 'hang'.

It is unlikely that your application will never recover.  Your loop will eventually end and your UI will become responsive again (assuming I didn't miss an infinite loop somewhere, but I don't think that I did).  However, the GDI+ GetPixel method is really very slow, and if your image is large at all that set of loops is going to take a long time to complete.  You will likely have to delve into an unsafe context and obtain a pointer to the image's memory using LockBits.  There are many examples of how to do that floating around here.

EDIT: After looking at your code a bit more closely it is also apparent that it is relatively inefficient.  You have at least 6 levels of nested for loops going on there, so you are essentially scanning the image multiple times when only a single scan is needed.

Image processing is a resource intensive process.  You need to be careful to do all of your performance intensive work as efficiently as possible.

Title: For Loops, Application Hanging

Body:
Well I'm creating an application, I'm using for loops to basically read every pixel of an image looking for patterns in pixel color (simple stuff) Anyway for some reason my application simply locks up and never reverts back to normal. I've loop through the code time and time again without seeing any real problems.

The only thing I've noticed, is the for loop in ScanPixelsLater may be exiting early. I've commented the code as much as possible,

private Point topLeftc, bottomLeftc, topRightc, bottomRightc;

///
/// Starts the initial looping process, designed only to loop through ONCE, ScanPixelsLater takes over
///
/// <param name="img">Image to scan</param>
public void ScanPixels(Bitmap img)
{
    int whitePixel = 0;

    for (int y = 100; y < img.Height; y++)
    {

        for (int x = 100; x < img.Width; x++)
        {

            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                // img.SetPixel(x, y, Color.Green);
                whitePixel++;

            }
            else { whitePixel = 0; }

            if (whitePixel == 18)
            {
                whitePixel = 0;
                topLeftc = new Point(x - 18, y);
                DetectNextWhiteLine(topLeftc, img);

            }
        }
    }

}

///
/// First creates the TopRight value via using the last pixel in x range, and using the current Y value
/// Then a Y loop is started 10 pixels down, within this loop is another X loop which scans the X range
/// If 10 consecutive white pixels are found, the TopLeft X value and the current Y value are used to map the
/// BottomLeft and BottomRight coordinates. Finally a new Point is created which starts (x = 1) and (y = currentYValue + 2)
/// The ScanPixelsLater method is then called, passing the new Point (newLocation).
///
///
/// <param name="p">The x and y value of where the pixels were found</param>
/// <param name="img">Image being used</param>
private void DetectNextWhiteLine(Point p, Bitmap img)
{

    int whitePixel = 0;
    topRightc = new Point(img.Width, topLeftc.Y);

    for (int y = p.Y + 10; y < img.Height; y++)
    {

        for (int x = p.X - 5; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 10)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                bottomRightc = new Point(img.Width, y);
                Cords.Add(new Coordinates(topLeftc, topRightc, bottomLeftc, bottomRightc));

                Point newLocation = new Point(1, y + 2);
                calls++;
                ScanPixelsLater(newLocation, img); //rescan the image from new y axis
            }
        }
    }

}

///
/// Loops through the pixels based on the p parameter, if 15 white pixels are found, the location (x & y) is
/// passed to the DetectNextWhiteLine method which fixes the next line with a similar number of white pixels.
///
/// <param name="p">The Point(x,y) at which to start scanning</param>
/// <param name="img"></param>
private void ScanPixelsLater(Point p, Bitmap img)
{

    int whitePixel = 0;

    for (int y = p.Y; y < img.Height; y++)
    {

        for (int x = p.X; x < img.Width; x++)
        {
            if (img.GetPixel(x, y) == Color.FromArgb(255, 255, 255, 255))
            {
                whitePixel++;
            }
            else
            {
                whitePixel = 0;
            }

            if (whitePixel == 15)
            {
                bottomLeftc = new Point(topLeftc.X, y);
                topLeftc = new Point(x - 15, y);
                calls++;
                DetectNextWhiteLine(topLeftc, img);
            }

        }
    }

    // only want this to execute after all the pixels within the entire img have been read
    // possibly executing early.

    DrawWhiteLines(img);
    AppArgs aa = new AppArgs(true);
    Change(this, aa); // custom event handler, fired behind form to update GUI

}


问:
heading not extending to the end of the div
I have a heading banner that overlays across a background image for a tile. To make it responsive, I set the width to auto and it looks great on a collapsed screen (see capture below). Also, I'm using Bootstrap 4.

However, on full screen resolution, the heading background doesn't extend to the end of the div. I've tried to eliminate any padding, but I can't seem to get it to go to the end. See image.

Here's my HTML:

```<code><!--browse by category section-->
    <section id="category">
        <div class="card-header text-center">
            <h4 class="card-title">Browse Workouts by Category</h1>
        </div>
        <div class="row btn-warning">
            <div class="col-sm-2 bg-primary" id="cardio">
                <h1 class="text-center">Cardio</h1>
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
            <div class="col-sm-2 bg-primary">
                Hi
            </div>
        </div>
    </section>
</code>```

and my CSS:

```<code>/*--------------*/
/*---CATEGORIES-----*/
/*--------------*/

#cardio {
    background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.7)), url('../img/users/pexels-photo-460520.jpeg') no-repeat;
    background-size: cover;
    height: 300px;
}

#cardio h1 {
    margin-top: 100px;
    height: 100px;
    width: auto;
    padding-top: 25px;
    color: #fff;
    background: linear-gradient(rgba(93,139,229,0.7), rgba(93,139,229,0.7));
}
</code>```

答:
This should do it:

```<code> .row, .col {
  padding: 0;
  margin: 0;
}

#cardio {
   padding: 0;
}

#cardio h1 {
   width: 100%;
}
</code>```

Keep the rest as is

Body:
I have a heading banner that overlays across a background image for a tile. To make it responsive, I set the width to auto and it looks great on a collapsed screen (see capture below). Also, I'm using Bootstrap 4.

However, on full screen resolution, the heading background doesn't extend to the end of the div. I've tried to eliminate any padding, but I can't seem to get it to go to the end. See image.

Here's my HTML:

Browse Workouts by Category

Cardio

                Hi

                Hi

                Hi

                Hi

                Hi

and my CSS:

/*--------------*/
/*---CATEGORIES-----*/
/*--------------*/

#cardio {
    background: linear-gradient(rgba(0,0,0,0.7), rgba(0,0,0,0.7)), url('../img/users/pexels-photo-460520.jpeg') no-repeat;
    background-size: cover;
    height: 300px;
}

#cardio h1 {
    margin-top: 100px;
    height: 100px;
    width: auto;
    padding-top: 25px;
    color: #fff;
    background: linear-gradient(rgba(93,139,229,0.7), rgba(93,139,229,0.7));
}

Body:
This should do it:

 .row, .col {
  padding: 0;
  margin: 0;
}

#cardio {
   padding: 0;
}

#cardio h1 {
   width: 100%;
}

Keep the rest as is


问:
Creating a multidimensional list in python3 and assign values in a loop
I'm trying to create and fill in a multidimensional list in python 3.4 like this:

```<code>ret_array = []
</code>```

then in a while list:

```<code>ret_array[k] = [track_name,t_num,disc_num,artist]
</code>```

but this way I'm getting the error:

```<code>IndexError: list assignment index out of range
</code>```

I know how many elements there will be but I'd prefer to do that more dynamically.

Any idea how I should do this the right way?

答:
you can not assign a value to an index which doesn't exist but you can append it to the bottom of the list

```<code>ret_array.append([track_name,t_num,disc_num,artist])
</code>```

or if you want to insert your element in a specific index you can use the insert function

```<code>ret_array.insert(k,[track_name,t_num,disc_num,artist])
</code>```

you can also use dictionary like this

```<code>ret_array = {}
ret_array[k] = [track_name,t_num,disc_num,artist]
</code>```

Body:
I'm trying to create and fill in a multidimensional list in python 3.4 like this:

ret_array = []

then in a while list:

ret_array[k] = [track_name,t_num,disc_num,artist]

but this way I'm getting the error:

IndexError: list assignment index out of range

I know how many elements there will be but I'd prefer to do that more dynamically.

Any idea how I should do this the right way?

Body:
you can not assign a value to an index which doesn't exist but you can append it to the bottom of the list

ret_array.append([track_name,t_num,disc_num,artist])

or if you want to insert your element in a specific index you can use the insert function

ret_array.insert(k,[track_name,t_num,disc_num,artist])

you can also use dictionary like this

ret_array = {}
ret_array[k] = [track_name,t_num,disc_num,artist]


问:
I have a list of excel filenames in the column A of my worksheet and I would like to remove the .xls and .xlsm tags from the filenames using VBA. How?
I want to remove the .xls and .xlsm tags using the "." in the VBA
    logic, but I am a beginner in VBA and I am wondering how I can
    accomplish the objective ?</p>

答:
This should do it... Just pass in the range that you want to extract from

```<code>Sub RemoveExtension(rng As Range)
   ' Declare your variables
   Dim LR As Long
   Dim i As Long
   Dim str() As String

   With rng
      ' Find the last row
      LR = .Cells(.Rows.Count, 1).End(xlUp).Row
      ' Enter loop
      For i = LR To 1 Step -1
         If Not (IsEmpty(.Cells(i))) Then
            ' Extract and split text using "." as a delimiter
            str() = Split(.Cells(i).Value, ".")
            ' Rewrite text in cell from first array variable in str()
            .Cells(i).Value = str(0)
         End If
      Next i
   End With
End Sub
</code>```

You can call this function with another Sub function... Example below:

```<code>Sub Macro1()

    ' Change Range() to what every range you need
    Call RemoveExtension(Range("A2:A10"))

End Sub
</code>```

Bare in mind this only works on columns, so you cannot pass in Range("A1:C3")

Body:
This should do it... Just pass in the range that you want to extract from

Sub RemoveExtension(rng As Range)
   ' Declare your variables
   Dim LR As Long
   Dim i As Long
   Dim str() As String

   With rng
      ' Find the last row
      LR = .Cells(.Rows.Count, 1).End(xlUp).Row
      ' Enter loop
      For i = LR To 1 Step -1
         If Not (IsEmpty(.Cells(i))) Then
            ' Extract and split text using "." as a delimiter
            str() = Split(.Cells(i).Value, ".")
            ' Rewrite text in cell from first array variable in str()
            .Cells(i).Value = str(0)
         End If
      Next i
   End With
End Sub

You can call this function with another Sub function... Example below:

Sub Macro1()

    ' Change Range() to what every range you need
    Call RemoveExtension(Range("A2:A10"))

End Sub

Bare in mind this only works on columns, so you cannot pass in Range("A1:C3")


问:
Why does Go think that this structure does not adhere to this interface?
Let's say I set up two Go interfaces and implement them as follows:

```<code>type fooInterface interface {
    buildBar() barInterface
}

type barInterface interface {
    stuff()
}

type fooStruct struct{}
type barStruct struct{}

func (*fooStruct) buildBar() *barStruct {
    return &barStruct{}
}

func (*barStruct) stuff() {}
</code>```

As soon as I try to assign fooStruct to a fooInterface variable, I get the following error:

```<code>cannot use fooStruct literal (type *fooStruct) as type fooInterface in assignment:
*fooStruct does not implement fooInterface (wrong type for buildBar method)
    have buildBar() *barStruct
    want buildBar() barInterface
</code>```

Naturally, I can modify buildBar() in fooStruct to return a barInterface and it will work. However, I'm curious as to why Go does not notice that *barStruct adheres to barInterface in this case, especially since this would work in a language like Java (likely because Java interfaces are explicitly implemented).

Go playground example: https://play.golang.org/p/84zymo-YnM

答:
Function type in go is not covariant, and not contravariant.

So to be assignable the signature must match exactly.

References:

https://golang.org/ref/spec#Assignability

Body:
Let's say I set up two Go interfaces and implement them as follows:

type fooInterface interface {
    buildBar() barInterface
}

type barInterface interface {
    stuff()
}

type fooStruct struct{}
type barStruct struct{}

func (*fooStruct) buildBar() *barStruct {
    return &barStruct{}
}

func (*barStruct) stuff() {}

As soon as I try to assign fooStruct to a fooInterface variable, I get the following error:

cannot use fooStruct literal (type *fooStruct) as type fooInterface in assignment:
*fooStruct does not implement fooInterface (wrong type for buildBar method)
    have buildBar() *barStruct
    want buildBar() barInterface

Naturally, I can modify buildBar() in fooStruct to return a barInterface and it will work. However, I'm curious as to why Go does not notice that *barStruct adheres to barInterface in this case, especially since this would work in a language like Java (likely because Java interfaces are explicitly implemented).

Go playground example: https://play.golang.org/p/84zymo-YnM


问:
Compile error Argument not optional
I have a code I ran before on a temporary computer and ran perfectly but it seems I can't get it to run on this machine even if I reference suggested by the author

I get

Compile error Argument not optional

on Sub kl()

```<code>Sub kl()
Dim ie As InternetExplorer
Dim htlm As HTMLDocument
Dim link As Object
Dim links As Object
Dim erow As Long
Application.ScreenUpdating = False
Set ie = New InternetExplorer
ie.Visible = False
ie.navigate = "http://www.google.com"

Do While ie.ReadyState <> READYSTATE_COMPLETE
    Application.StatusBar = "loading website"
    DoEvents
Loop

Set Html = ie.document
Set links = Html.getElementsByTagName("a")
For Each link In links
    erow = Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    Cells(erow, 1).Value = link
    Cells(erow, 1).Columns.AutoFit
Next

Set.ie = Nothing
Application.StatusBar = ""
Application.screenupdate = True

End Sub
</code>```

Any help on why it's causing error? Ive referenced MSXML, ActiveX Library, MSHTML and MS Internet Controls

I get error for ie.navigate = "http://www.google.com"

Working code :

```<code>Sub kl()
Dim ie As Object
Dim htlm As HTMLDocument
Dim link As Object
Dim links As Object
Dim erow As Long

Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate "http://www.google.com"

Do While ie.ReadyState <> READYSTATE_COMPLETE
Application.StatusBar = "loading website"
DoEvents
Loop

 Set HTML = ie.document
 Set links = HTML.getElementsByTagName("a")
For Each link In links
erow = Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Cells(erow, 1).Value = link
Cells(erow, 1).Columns.AutoFit
Next

Set ie = Nothing
Application.StatusBar = ""

End Sub
</code>```

答:
I believe the error is in how you're creating and calling the Internet Explorer application.

Try this instead:

```<code>...
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate "http://www.google.com"  ' This seems to be the main thing, don't use `=`
...
</code>```

Title: Compile error Argument not optional

Body:
I have a code I ran before on a temporary computer and ran perfectly but it seems I can't get it to run on this machine even if I reference suggested by the author

I get

Compile error Argument not optional

on Sub kl()

Sub kl()
Dim ie As InternetExplorer
Dim htlm As HTMLDocument
Dim link As Object
Dim links As Object
Dim erow As Long
Application.ScreenUpdating = False
Set ie = New InternetExplorer
ie.Visible = False
ie.navigate = "http://www.google.com"

Do While ie.ReadyState <> READYSTATE_COMPLETE
    Application.StatusBar = "loading website"
    DoEvents
Loop

Set Html = ie.document
Set links = Html.getElementsByTagName("a")
For Each link In links
    erow = Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
    Cells(erow, 1).Value = link
    Cells(erow, 1).Columns.AutoFit
Next

Set.ie = Nothing
Application.StatusBar = ""
Application.screenupdate = True

End Sub

Any help on why it's causing error? Ive referenced MSXML, ActiveX Library, MSHTML and MS Internet Controls

I get error for ie.navigate = "http://www.google.com"

Working code :

Sub kl()
Dim ie As Object
Dim htlm As HTMLDocument
Dim link As Object
Dim links As Object
Dim erow As Long

Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate "http://www.google.com"

Do While ie.ReadyState <> READYSTATE_COMPLETE
Application.StatusBar = "loading website"
DoEvents
Loop

 Set HTML = ie.document
 Set links = HTML.getElementsByTagName("a")
For Each link In links
erow = Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Cells(erow, 1).Value = link
Cells(erow, 1).Columns.AutoFit
Next

Set ie = Nothing
Application.StatusBar = ""

End Sub

Body:
I believe the error is in how you're creating and calling the Internet Explorer application.

Try this instead:

...
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.navigate "http://www.google.com"  ' This seems to be the main thing, don't use `=`
...