问:
Executing C program in BASH with 2 arguments
I have a C program executable which required two arguments. The first argument is a abc.dat file and the second argument is abc.csv file. The program inputs the .dat file and converts it to a .csv file. The .dat exists when running the program and it creates the .csv which was the second argument.

I am trying to convert all the files in a folder using a bash script.

Here is my bash script:

```<code>#!/bin/sh

for file in /home/labadmin/Desktop/6122017/1252017
do
    ./my_read_bfee *.dat *.csv
done
</code>```

When I execute the bash script I get:

```<code>usage: read_bfee in.dat out.csv
</code>```

Please help.
Thanks in advance.

答:
maybe you wanted

```<code>#!/bin/sh

for file in /home/labadmin/Desktop/6122017/1252017/*.dat
do
    ./my_read_bfee "$file" "${file%.dat}.csv"
done
</code>```

otherwise the *.dat inside the for loop is expanded to all files matching in current directory for each iteration

Body:
I have a C program executable which required two arguments. The first argument is a abc.dat file and the second argument is abc.csv file. The program inputs the .dat file and converts it to a .csv file. The .dat exists when running the program and it creates the .csv which was the second argument.

I am trying to convert all the files in a folder using a bash script.

Here is my bash script:

#!/bin/sh

for file in /home/labadmin/Desktop/6122017/1252017
do
    ./my_read_bfee *.dat *.csv
done

When I execute the bash script I get:

usage: read_bfee in.dat out.csv

Please help.
Thanks in advance.

Body:
maybe you wanted

#!/bin/sh

for file in /home/labadmin/Desktop/6122017/1252017/*.dat
do
    ./my_read_bfee "$file" "${file%.dat}.csv"
done

otherwise the *.dat inside the for loop is expanded to all files matching in current directory for each iteration


来源: stackexchange

问:
asp.net Validation: ZIP from Germany, Switzerland and Austria
I have a TextBox for the ZIP and a ComboBox for the country (selectable: germany, switzerland and austria).

I am not much familiar with RegEx, I get it to build a simple one for ZIP of germany, but how to build one for allowed ZIPs of germany, switzerland and austria?

答:
Look in to Globalization, you can put the regex in a resource file and tell the validator to use it for the current culture. This way if the user is German it will use the German Resource File that uses the German way of validating Zip Code.

Check this tutorial out on Building Multilingual Web Sites, there are examples of how you localize validation.

Edit

I might have missunderstood the question a bit, if you want a regex that will pass on all the different zip-codes from German, Austria and Swizz, you can do what Ward Muylaert said. But it's better if you split the validation up so that you validate against the correct culture.

ContentLicense: CC BY-SA 2.5


问:
Use same object instance(log) in diffrent files
I use logrus logger and I init it inside my main function like following

```<code>main.go file content

import "github.com/sirupsen/logrus"

var logger                *logrus.Logger

func init() {

    logger = utils.InitLogs()
}

func main(){

    logger.Info("bla bla")

   }
</code>```

And I was able to use it  e.g.logger.info(“test”) in the main file, now I don’t want to create the init file in each
other file which need to use the logger , I want to use in other project file the same instance which I’ve created in the main.go file
How should I do it in golfing ?

Im not asking about sharing it on the same package

答:
There are some points here:

Go groups files in package concept for example if you have some .go files in a directory with the package main that means that all files are sharing the package scope, in this case the func init() inits the var logger that is present in the main package.

I prefer to not use package scope variables, but this depends on your implementation
https://dave.cheney.net/2017/06/11/go-without-package-scoped-variables

Maybe you wanted to use logger in different package for example github.com/youruser/work

I prefer to pass the object log to the functions or methods you wanted to use it (as parameters or receiver)

```<code>package main

import (
    "github.com/user/utils"
    "github.com/user/work"
)

func main() {
    logger := utils.InitLogs()
    work.Do(logger)
}
</code>```

or using as receiver

```<code>package main

import (
    "github.com/user/utils"
    "github.com/user/work"
)

func main() {
    logger := utils.InitLogs()
    w := work.New()
    w.Log = logger
    w.Do()
}
</code>```

then in Do() you can log using the receiver

in the work package you should add it as filed

```<code>type Worker struct {
    Log *logrus.Logger
}
</code>```

I really hope you can find it useful.

update:
An example of work package

```<code>package work

import "github.com/sirupsen/logrus"

type Worker struct {
    Log *logrus.Logger
}

func New() *Worker {
    return new(Worker)
}

func (w *Worker) Do() {
    // some work
    // Here you are passing as receiver parameter
    w.Log.Info("bla bla")
}

func AnotherFunc(log *logrus.Logger) {
    // Here you are passing as method parameter
   log.Info("bla bla")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use logrus logger and I init it inside my main function like following

main.go file content

import "github.com/sirupsen/logrus"

var logger                *logrus.Logger

func init() {

    logger = utils.InitLogs()
}

func main(){

    logger.Info("bla bla")

   }

And I was able to use it  e.g.logger.info(“test”) in the main file, now I don’t want to create the init file in each
other file which need to use the logger , I want to use in other project file the same instance which I’ve created in the main.go file
How should I do it in golfing ?

Im not asking about sharing it on the same package

Body:
There are some points here:

Go groups files in package concept for example if you have some .go files in a directory with the package main that means that all files are sharing the package scope, in this case the func init() inits the var logger that is present in the main package.

I prefer to not use package scope variables, but this depends on your implementation
https://dave.cheney.net/2017/06/11/go-without-package-scoped-variables

Maybe you wanted to use logger in different package for example github.com/youruser/work

I prefer to pass the object log to the functions or methods you wanted to use it (as parameters or receiver)

package main

import (
    "github.com/user/utils"
    "github.com/user/work"
)

func main() {
    logger := utils.InitLogs()
    work.Do(logger)
}

or using as receiver

package main

import (
    "github.com/user/utils"
    "github.com/user/work"
)

func main() {
    logger := utils.InitLogs()
    w := work.New()
    w.Log = logger
    w.Do()
}

then in Do() you can log using the receiver

in the work package you should add it as filed

type Worker struct {
    Log *logrus.Logger
}

I really hope you can find it useful.

update:
An example of work package

package work

import "github.com/sirupsen/logrus"

type Worker struct {
    Log *logrus.Logger
}

func New() *Worker {
    return new(Worker)
}

func (w *Worker) Do() {
    // some work
    // Here you are passing as receiver parameter
    w.Log.Info("bla bla")
}

func AnotherFunc(log *logrus.Logger) {
    // Here you are passing as method parameter
   log.Info("bla bla")
}


问:
c++11: Array bound is not an integer constant before a token
I have seen this question, but the solution provided there doesn't solve the issue.

```<code>static int num_instances;
std::vector<SomeClass::FunctionWithinTheClass> *mem[num_instances];
</code>```

SomeClass::FunctionWithinTheClass *mem[num_instances]; //Even this raises an error

the value num_instances is obtained by reading a configuration file.

The error I get is :
array bound is not an integer constant before ‘]’ token

This is strange because the value num_instances is fixed at compile time.

答:
Perhaps it is fixed at compile time but “integer constant” is a technical term and a static int variable does not meet these requirements.

Use a static const int instead. This works:

```<code>static const int num_instances = 5;
</code>```

However, you mention that num_instances is read from a configuration file… this does not sound remotely like a constant to me. In this case, you must use a std::vector or other dynamically sized array instead.

Body:
I have seen this question, but the solution provided there doesn't solve the issue.

static int num_instances;
std::vector<SomeClass::FunctionWithinTheClass> *mem[num_instances];

SomeClass::FunctionWithinTheClass *mem[num_instances]; //Even this raises an error

the value num_instances is obtained by reading a configuration file.

The error I get is :
array bound is not an integer constant before ‘]’ token

This is strange because the value num_instances is fixed at compile time.

Body:
Perhaps it is fixed at compile time but “integer constant” is a technical term and a static int variable does not meet these requirements.

Use a static const int instead. This works:

static const int num_instances = 5;

However, you mention that num_instances is read from a configuration file… this does not sound remotely like a constant to me. In this case, you must use a std::vector or other dynamically sized array instead.


问:
nth-child formula for hover state - all elements except the first one
I want to select all elements except the first one for a hover state. I'm doing this using nth-child() selector.

I'm following this guide: https://css-tricks.com/useful-nth-child-recipies/

It gives a formula for selecting all but the first 5 - the example they give is below:

```<code>li:nth-child(n+6) {
    color: green;
}
</code>```

I want to take this and apply it so that it selects all but the first element. My approach to do that is so:

```<code>li:nth-child(n+1) {
    color: green;
}
</code>```

Is this not correct?

I need to try to apply this to a hover state situation, where it only performs the :hover action all all but the first li. See the embed below:

  li {
    display: inline-block;
  }

  a {
    margin-right: 1.8rem;
      padding-bottom: 23px;
  }

  #login-signup li:nth-child(n+1):hover {
    text-decoration: none;
    border-bottom: 3px solid #292c2e;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="login-signup">
      <li> No Underline</li>
      <li>Log In</li>
      <li>Sign Up</li>
    </ul></code>```

How do you apply the formula for selecting anything but the first element with nth-child? Does :hover not work with nth-child? I can't find any sources that say otherwise.

答:
:nth-child() works with :hover just fine. :hover is not the problem here.

Look closely at the n+6 example. As you mentioned, that's for the first 5. However notice that the expression says 6, not 5.

So to match all but the first element, you need to start from 2. Hence, n+2.

li {
  display: inline-block;
}

a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}

#login-signup li:nth-child(n+2):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="login-signup">
  <li>No Underline</li>
  <li>Log In</li>
  <li>Sign Up</li>
</ul></code>```

Body:
I want to select all elements except the first one for a hover state. I'm doing this using nth-child() selector.

I'm following this guide: https://css-tricks.com/useful-nth-child-recipies/

It gives a formula for selecting all but the first 5 - the example they give is below:

li:nth-child(n+6) {
    color: green;
}

I want to take this and apply it so that it selects all but the first element. My approach to do that is so:

li:nth-child(n+1) {
    color: green;
}

Is this not correct?

I need to try to apply this to a hover state situation, where it only performs the :hover action all all but the first li. See the embed below:

  li {
    display: inline-block;
  }

  a {
    margin-right: 1.8rem;
      padding-bottom: 23px;
  }

  #login-signup li:nth-child(n+1):hover {
    text-decoration: none;
    border-bottom: 3px solid #292c2e;
  }

 No Underline

Log In

Sign Up

How do you apply the formula for selecting anything but the first element with nth-child? Does :hover not work with nth-child? I can't find any sources that say otherwise.

Body:
:nth-child() works with :hover just fine. :hover is not the problem here.

Look closely at the n+6 example. As you mentioned, that's for the first 5. However notice that the expression says 6, not 5.

So to match all but the first element, you need to start from 2. Hence, n+2.

li {
  display: inline-block;
}

a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}

#login-signup li:nth-child(n+2):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}

<ul id="login-signup">
  <li><a href="#">No Underline</a></li>
  <li><a href="#">Log In</a></li>
  <li><a href="#">Sign Up</a></li>
</ul>


问:
Maintain offset when reloadRowsAtIndexPaths
I'm trying to reload a single tableViewCell but it scrolls to the top every time I do it... I'm not adding nor deleting cells, I just want to change the color of the selected cells.

This is what I do in the cellForRowAtIndexPath:

```<code>SMPChoiceViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChoiceCell" forIndexPath:indexPath];
SMPChoice *choice = self.choices[indexPath.row - 1];
cell.choiceTextLabel.text = choice.text;

if ([self.selectedChoices indexOfObject:choice] != NSNotFound) {
  cell.choiceTextLabel.textColor = [UIColor purpleColor];
} else {
  cell.choiceTextLabel.textColor = [UIColor blackColor];
}
</code>```

And this is what I do in the didSelectRowAtIndexPath

```<code>if ([self.selectedChoices indexOfObject:choice] != NSNotFound) {
  [self.selectedChoices removeObject:choice];
} else {
  [self.selectedChoices addObject:choice];
}

CGPoint offSet = [tableView contentOffset];

[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView setContentOffset:offSet animated:NO];
</code>```

But it just jumps, any suggestion?

P.S
I followed this thread but it didn't solved my question Calling reloadRowsAtIndexPaths removes tableView contentOffset

答:
OBJ-C version of Daniel's answer:</p>

```<code>//rowHeightForIndexPath is an NSMutableDictionary
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.rowHeightForIndexPath setObject:@(cell.frame.size.height) forKey:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *cachedHeight = [self.rowHeightForIndexPath objectForKey:indexPath];

    return cachedHeight ? cachedHeight.floatValue : UITableViewAutomaticDimension;
}
</code>```

Body:
I'm trying to reload a single tableViewCell but it scrolls to the top every time I do it... I'm not adding nor deleting cells, I just want to change the color of the selected cells.

This is what I do in the cellForRowAtIndexPath:

SMPChoiceViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChoiceCell" forIndexPath:indexPath];
SMPChoice *choice = self.choices[indexPath.row - 1];
cell.choiceTextLabel.text = choice.text;

if ([self.selectedChoices indexOfObject:choice] != NSNotFound) {
  cell.choiceTextLabel.textColor = [UIColor purpleColor];
} else {
  cell.choiceTextLabel.textColor = [UIColor blackColor];
}

And this is what I do in the didSelectRowAtIndexPath

if ([self.selectedChoices indexOfObject:choice] != NSNotFound) {
  [self.selectedChoices removeObject:choice];
} else {
  [self.selectedChoices addObject:choice];
}

CGPoint offSet = [tableView contentOffset];

[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView setContentOffset:offSet animated:NO];

But it just jumps, any suggestion?

P.S
I followed this thread but it didn't solved my question Calling reloadRowsAtIndexPaths removes tableView contentOffset

Body:
OBJ-C version of Daniel's answer:

//rowHeightForIndexPath is an NSMutableDictionary
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.rowHeightForIndexPath setObject:@(cell.frame.size.height) forKey:indexPath];
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *cachedHeight = [self.rowHeightForIndexPath objectForKey:indexPath];

    return cachedHeight ? cachedHeight.floatValue : UITableViewAutomaticDimension;
}


问:
where I am going wrong in this MySQL query for wordpress Mysql?
```<code>SELECT * FROM wp_posts
   INNER JOIN wp_term_relationships
           ON ( wp_posts.ID = wp_term_relationships.object_id)
   INNER JOIN wp_term_relationships
           ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id
        WHERE term_id = 1 AND taxonomy  = 'category';
</code>```

I want to get the list of posts through this query. Can anyone can solve this query?

答:
Hi @steven spielberg:

Your error was that you specified wp_term_relationships twice instead of specifying wp_term_relationships once and wp_term_taxonomy once. Here is a working query:

```<code>SELECT * FROM wp_posts
   INNER JOIN wp_term_relationships
           ON wp_posts.ID = wp_term_relationships.object_id
   INNER JOIN wp_term_taxonomy
           ON wp_term_taxonomy.term_taxonomy_id =
              wp_term_relationships.term_taxonomy_id
        WHERE term_id = 1 AND taxonomy  = 'category';
</code>```

However, if you are planning to use that within a .php file for use with WordPress I would recommend you use a different approach, such as using WP_Query and starting with this:

```<code>$term = get_term_by('id',1);
$query = new WP_Query(array(
  'taxonomy'=>'category',
  'term'=>$term->slug,
));
print_r($query->posts);
</code>```

You can find other arguments for WP_Query on the query_posts() Codex page (the arguments are the same.)  There are several other arguments you'll probably want to use to fine-tune your query.

Of course if you must use direct SQL for some reason then at least use the $wpdb object so you don't have to worry about prefixes, like this:

```<code>  global $wpdb;
  $sql = <<<SQL
SELECT * FROM {$wpdb->posts}
   INNER JOIN {$wpdb->term_relationships}
           ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id
   INNER JOIN {$wpdb->term_taxonomy}
           ON {$wpdb->term_taxonomy}.term_taxonomy_id =
              {$wpdb->term_relationships}.term_taxonomy_id
        WHERE 1=1
          AND {$wpdb->term_taxonomy}.term_id = 1
          AND {$wpdb->term_taxonomy}.taxonomy  = 'category'
SQL;
  $posts = $wpdb->get_results($sql);
</code>```

Hope this helps.

-Mike

OwnerDisplayName: Steven Spielberg

Body:
SELECT * FROM wp_posts
   INNER JOIN wp_term_relationships
           ON ( wp_posts.ID = wp_term_relationships.object_id)
   INNER JOIN wp_term_relationships
           ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id
        WHERE term_id = 1 AND taxonomy  = 'category';

I want to get the list of posts through this query. Can anyone can solve this query?

Body:
Hi @steven spielberg:

Your error was that you specified wp_term_relationships twice instead of specifying wp_term_relationships once and wp_term_taxonomy once. Here is a working query:

SELECT * FROM wp_posts
   INNER JOIN wp_term_relationships
           ON wp_posts.ID = wp_term_relationships.object_id
   INNER JOIN wp_term_taxonomy
           ON wp_term_taxonomy.term_taxonomy_id =
              wp_term_relationships.term_taxonomy_id
        WHERE term_id = 1 AND taxonomy  = 'category';

However, if you are planning to use that within a .php file for use with WordPress I would recommend you use a different approach, such as using WP_Query and starting with this:

$term = get_term_by('id',1);
$query = new WP_Query(array(
  'taxonomy'=>'category',
  'term'=>$term->slug,
));
print_r($query->posts);

You can find other arguments for WP_Query on the query_posts() Codex page (the arguments are the same.)  There are several other arguments you'll probably want to use to fine-tune your query.

Of course if you must use direct SQL for some reason then at least use the $wpdb object so you don't have to worry about prefixes, like this:

  global $wpdb;
  $sql = <<<SQL
SELECT * FROM {$wpdb->posts}
   INNER JOIN {$wpdb->term_relationships}
           ON {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id
   INNER JOIN {$wpdb->term_taxonomy}
           ON {$wpdb->term_taxonomy}.term_taxonomy_id =
              {$wpdb->term_relationships}.term_taxonomy_id
        WHERE 1=1
          AND {$wpdb->term_taxonomy}.term_id = 1
          AND {$wpdb->term_taxonomy}.taxonomy  = 'category'
SQL;
  $posts = $wpdb->get_results($sql);

Hope this helps.

-Mike


问:
Selenium UrlContains in C#
I'm trying to wait for a specific URL to load. However I don´t know the full URL, a dynamic value will be added at the end. Lets say the URL is www.test.com/accepted/?12345, but I only know www.test.com/accepted/

I´m trying to do something like this:

```<code>WebDriverWait wait = new WebDriverWait(Generic.driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.UrlContains("www.test.com/accepted/"));
</code>```

Is there a way to just check for the part that I know?

答:
```<code>wait.Until(ExpectedConditions.UrlContains("accepted"));
</code>```

Is exactly what you need. If it doesn't work, debug the code and check the actual url and the expected url. If you get an error, please share it with us so we can help you further.

Update 2018-04-11

ExpectedConditions is now marked obsolete, the Selenium changelog now states that you should use the lambda functions directly

Example for UrlContains:

```<code>public static Func<IWebDriver, bool> UrlContains(string fraction)
{
    return (driver) => { return driver.Url.ToLowerInvariant().Contains(fraction.ToLowerInvariant()); };
}
</code>```

They also created a new repository on github which might help:
https://github.com/DotNetSeleniumTools/DotNetSeleniumExtras

Title: Selenium UrlContains in C#

Body:
I'm trying to wait for a specific URL to load. However I don´t know the full URL, a dynamic value will be added at the end. Lets say the URL is www.test.com/accepted/?12345, but I only know www.test.com/accepted/

I´m trying to do something like this:

WebDriverWait wait = new WebDriverWait(Generic.driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.UrlContains("www.test.com/accepted/"));

Is there a way to just check for the part that I know?

Body:
wait.Until(ExpectedConditions.UrlContains("accepted"));

Is exactly what you need. If it doesn't work, debug the code and check the actual url and the expected url. If you get an error, please share it with us so we can help you further.

Update 2018-04-11

ExpectedConditions is now marked obsolete, the Selenium changelog now states that you should use the lambda functions directly

Example for UrlContains:

public static Func<IWebDriver, bool> UrlContains(string fraction)
{
    return (driver) => { return driver.Url.ToLowerInvariant().Contains(fraction.ToLowerInvariant()); };
}

They also created a new repository on github which might help:
https://github.com/DotNetSeleniumTools/DotNetSeleniumExtras


问:
Is there a way to execute JavaScript in Perl?
I've worked some years now in Perl building Web scrapers, and given the problem that spam represents, and how scraping Web pages would turn out to be much more easier to those folks if, for example, Perl's LWP::UserAgent could handle its cup of JavaScript, I'm amazed no one has built a JS engine for it yet.

What am I missing here?

Thanks in advance. Regards.

PS: I'm not a spammer. Just curious.

答:
TMTOWTDI.
Another option is WWW::Scripter, with the Javascript or AJAX plugin.</p>


问:
How to copy/paste selected columns from one xls to another
I would like to copy/paste some columns (always the same) from one Workbook to another. I can't make my code to do this between workbooks.
And one more small thing I want paste values to the 4th row in target sheet and all I could do by myself is to paste it into second one :/

Something like this code but this one works only pasting values from one sheet to another in the same xls file:

EDIT: code with my attempt of copy/paste between xls files. What do I do wrong, because it doesn't work.

```<code>    Sub Paste_columns()

Dim x As Worksheet, r As Long, y As Worksheet

Set x = Workbooks("Bench.xlsm").Worksheets("Test-Sheet")
Set y = Workbooks("Pres.xls").Worksheets("Paste_tab")
With y
   For r = 2 To y.Range("B" & Rows.Count).End(xlUp).Row
        If y.Cells(r, 2).Value > 0 Then
        x.Range("B" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 2)
        x.Range("C" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 3)
        x.Range("D" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 4)
        x.Range("E" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 5)
        x.Range("H" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 8)
        x.Range("I" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 9)
        x.Range("M" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 13)
        x.Range("O" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 15)
        x.Range("Q" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 17)
        x.Range("S" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 19)
        x.Range("V" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 22)
        x.Range("W" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 23)
            Else: End
        End If

    Next r

End With
End Sub
</code>```

答:
Use meaningful variable names - particularly when you are learning:</p>

```<code>Sub Example()
Dim wbSource As Workbook
Dim wbDestination As Workbook
Dim wsSource As Worksheet
Dim wsDestination As Worksheet
Dim rSource As Range
Dim rDestination As Range
Set wbSource = Workbooks("Pres.xls")
Set wsSource = wbSource.Worksheets("Paste_tab")

Set wbDestination = Workbooks("Bench.xlsm")
Set wsDestination = wbDestination.Worksheets("Test-Sheet")

Set rSource = wsSource.Range("b2:b" & wsSource.Range("b" & wsSource.Rows.Count).End(xlUp).Row)
For Each rDestination In wsDestination.Range("B4:W4")
    If InStr("BCDEHIMOQSVW", Left(rDestination.AddressLocal(False, False), 1)) > 0 Then

       ' rSource.Copy rDestination
  '=============if only values wanted ===========
        rsource.copy
        rdestination.pastespecial xlpastevalues
'==================
    End If
Next rDestination
End Sub
</code>```

Body:
I would like to copy/paste some columns (always the same) from one Workbook to another. I can't make my code to do this between workbooks.
And one more small thing I want paste values to the 4th row in target sheet and all I could do by myself is to paste it into second one :/

Something like this code but this one works only pasting values from one sheet to another in the same xls file:

EDIT: code with my attempt of copy/paste between xls files. What do I do wrong, because it doesn't work.

    Sub Paste_columns()

Dim x As Worksheet, r As Long, y As Worksheet

Set x = Workbooks("Bench.xlsm").Worksheets("Test-Sheet")
Set y = Workbooks("Pres.xls").Worksheets("Paste_tab")
With y
   For r = 2 To y.Range("B" & Rows.Count).End(xlUp).Row
        If y.Cells(r, 2).Value > 0 Then
        x.Range("B" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 2)
        x.Range("C" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 3)
        x.Range("D" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 4)
        x.Range("E" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 5)
        x.Range("H" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 8)
        x.Range("I" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 9)
        x.Range("M" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 13)
        x.Range("O" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 15)
        x.Range("Q" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 17)
        x.Range("S" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 19)
        x.Range("V" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 22)
        x.Range("W" & Rows.Count).End(xlUp)(2).Value = .Cells(r, 23)
            Else: End
        End If

    Next r

End With
End Sub

Body:
Use meaningful variable names - particularly when you are learning:

Sub Example()
Dim wbSource As Workbook
Dim wbDestination As Workbook
Dim wsSource As Worksheet
Dim wsDestination As Worksheet
Dim rSource As Range
Dim rDestination As Range
Set wbSource = Workbooks("Pres.xls")
Set wsSource = wbSource.Worksheets("Paste_tab")

Set wbDestination = Workbooks("Bench.xlsm")
Set wsDestination = wbDestination.Worksheets("Test-Sheet")

Set rSource = wsSource.Range("b2:b" & wsSource.Range("b" & wsSource.Rows.Count).End(xlUp).Row)
For Each rDestination In wsDestination.Range("B4:W4")
    If InStr("BCDEHIMOQSVW", Left(rDestination.AddressLocal(False, False), 1)) > 0 Then

       ' rSource.Copy rDestination
  '=============if only values wanted ===========
        rsource.copy
        rdestination.pastespecial xlpastevalues
'==================
    End If
Next rDestination
End Sub


问:
how to work with hybrid mobile application using appium?
Can anybody help me,

I have been try to test hybrid application (developed in kony ide) using appiumbut the coding not executed .then using UIautomator viewer I didn't get "resource id " so im using by.name method. is der any possibility to get resource id?? then how to make work with hybrid application .

My coding

```<code>package com.appium.testcase;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver
public class AppiumTest
{
WebDriver driver=null;

@BeforeClass
public void setup()
{
File appDir = new File("E:/Automation/adt-bundle-windows-x86_64-20130514/sdk");
File app = new File(appDir, "WatsCooking.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("device","Android");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability(CapabilityType.VERSION, "5.1");// motoe
//capabilities.setCapability(CapabilityType.VERSION, "4.2.1");//lava
capabilities.setCapability(CapabilityType.PLATFORM, "WINDOWS");

capabilities.setCapability("app-Package","com.truetech.watcooking");
//Here we mention the activity name, which is invoked initially as app's first page.
capabilities.setCapability("app-Activity","com.truetech.watscooking.SplashActivity");

capabilities.setCapability("deviceName", "ZX1B328HPW");//motoe
//capabilities.setCapability("deviceName", "0123456789ABCDEF");//lava
capabilities.setCapability("app", app.getAbsolutePath());

try {
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);

     }

     @Test
public void loginTest() throws Exception {

    try{
        System.out.println("call");
        List <WebElement> loginbt =driver.findElements(By.id("btnlogin" ));
        loginbt.get(1).click();
  }

          catch(NullPointerException ex1)
    {

              //System.out.println( "Value not found in Dropdown to Select");

    }

     }
@AfterMethod
public void tearDown() {
           driver.quit();
    }
}
</code>```

答:
You need to expose widget IDs. Do the following:

On the File menu, click Settings. The Project Settings dialog box displays.

Click the Native tab.

On the Common sub-tab, click Expose Widget IDs for Test Automation, and then click Finish.

For the Android platform, when you select to expose widget IDs, an xml file is generated during the build containing the widget IDs of the app. This is explained in detail under Android Limitations.

See the docs for more information.

Body:
Can anybody help me,

I have been try to test hybrid application (developed in kony ide) using appiumbut the coding not executed .then using UIautomator viewer I didn't get "resource id " so im using by.name method. is der any possibility to get resource id?? then how to make work with hybrid application .

My coding

package com.appium.testcase;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver
public class AppiumTest
{
WebDriver driver=null;

@BeforeClass
public void setup()
{
File appDir = new File("E:/Automation/adt-bundle-windows-x86_64-20130514/sdk");
File app = new File(appDir, "WatsCooking.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("device","Android");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability(CapabilityType.VERSION, "5.1");// motoe
//capabilities.setCapability(CapabilityType.VERSION, "4.2.1");//lava
capabilities.setCapability(CapabilityType.PLATFORM, "WINDOWS");

capabilities.setCapability("app-Package","com.truetech.watcooking");
//Here we mention the activity name, which is invoked initially as app's first page.
capabilities.setCapability("app-Activity","com.truetech.watscooking.SplashActivity");

capabilities.setCapability("deviceName", "ZX1B328HPW");//motoe
//capabilities.setCapability("deviceName", "0123456789ABCDEF");//lava
capabilities.setCapability("app", app.getAbsolutePath());

try {
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);

     }

     @Test
public void loginTest() throws Exception {

    try{
        System.out.println("call");
        List <WebElement> loginbt =driver.findElements(By.id("btnlogin" ));
        loginbt.get(1).click();
  }

          catch(NullPointerException ex1)
    {

              //System.out.println( "Value not found in Dropdown to Select");

    }

     }
@AfterMethod
public void tearDown() {
           driver.quit();
    }
}


问:
Can not reach 100% Pester Code Coverage due to Script block

Hi All,

I have been struggling a long time because of my pester not reaching 100% code coverage due to a scriptblock. I have been researching and reading articles to no success and I have decided to ask some help from you guys. :)

Part of the code I want to describe contains a scriptblock and would later be fed to a cmdlet Invoke-Command. Sample code below:

```<code>function Get-Function {
.....
Set-Alias Start-PowerShell32 $env:computername\WindowsPowerShell\v1.0\powershell.exe"
$ScriptBlock = {
    Start-PowerShell32 -noprofile {
        $sample = Get-Content -Path "C:\sample.txt
        Import-Module "C:\Program Files (x86)\Software"

        @($sample) | Get-Service | Where-Object { $_.Status -eq 'Stopped' }
        }
    }
Invoke-Command -ScriptBlock $ScriptBlock
}

Describe Get-Function {
....
function Get-Statistics {

    Start-PowerShell32 -noprofile {
        $sample = Get-Content -Path "C:\sample.txt
        Import-Module "C:\Program Files (x86)\Software"

        @($sample) | Get-Service | Where-Object { $_.Status -eq 'Stopped' }
        }
}
Context '1st Context'{
mock Set-Alias {'Setting alias for Powershell 32 bit'} -Verifiable
mock Get-Statistics {'Getting Statistics ....'} -Verifiable
mock Invoke-Command {Get-Statistics} -Verifiable
$result = Get-Function

    it 'should return etting alias for Powershell 32 bit'{
        $result[0] | should be "Setting alias for Powershell 32 bit"
        }
    it 'should return Getting Mailbox Statistics ....'{
        $result[1] | should be "Getting Statistics ...."
        }
    it 'should call all verifiable mocks'{
        Assert-VerifiableMocks
        }
    }
}
</code>```

What I did on my Pester is that I made a custom function inside my Describe block(Get-Statistics) which is basically the inside of the script block for it to be called whenever I mock Invoke-Command to be Get-Statistics. My Pester succeeds but code coverage does not give me 100%.

Can you guys enlighten me on how to do this? do I need to change my tests?

Thank You

答:
At the head of your Describe { block, include a mock for Invoke-Command:

```<code>Describe '..' {
    Mock Invoke-Command { Param($SB) . $SB }

    ...
}
</code>```

Body:
Hi All,

I have been struggling a long time because of my pester not reaching 100% code coverage due to a scriptblock. I have been researching and reading articles to no success and I have decided to ask some help from you guys. :)

Part of the code I want to describe contains a scriptblock and would later be fed to a cmdlet Invoke-Command. Sample code below:

function Get-Function {
.....
Set-Alias Start-PowerShell32 $env:computername\WindowsPowerShell\v1.0\powershell.exe"
$ScriptBlock = {
    Start-PowerShell32 -noprofile {
        $sample = Get-Content -Path "C:\sample.txt
        Import-Module "C:\Program Files (x86)\Software"

        @($sample) | Get-Service | Where-Object { $_.Status -eq 'Stopped' }
        }
    }
Invoke-Command -ScriptBlock $ScriptBlock
}

Describe Get-Function {
....
function Get-Statistics {

    Start-PowerShell32 -noprofile {
        $sample = Get-Content -Path "C:\sample.txt
        Import-Module "C:\Program Files (x86)\Software"

        @($sample) | Get-Service | Where-Object { $_.Status -eq 'Stopped' }
        }
}
Context '1st Context'{
mock Set-Alias {'Setting alias for Powershell 32 bit'} -Verifiable
mock Get-Statistics {'Getting Statistics ....'} -Verifiable
mock Invoke-Command {Get-Statistics} -Verifiable
$result = Get-Function

    it 'should return etting alias for Powershell 32 bit'{
        $result[0] | should be "Setting alias for Powershell 32 bit"
        }
    it 'should return Getting Mailbox Statistics ....'{
        $result[1] | should be "Getting Statistics ...."
        }
    it 'should call all verifiable mocks'{
        Assert-VerifiableMocks
        }
    }
}

What I did on my Pester is that I made a custom function inside my Describe block(Get-Statistics) which is basically the inside of the script block for it to be called whenever I mock Invoke-Command to be Get-Statistics. My Pester succeeds but code coverage does not give me 100%.

Can you guys enlighten me on how to do this? do I need to change my tests?

Thank You

Body:
At the head of your Describe { block, include a mock for Invoke-Command:

Describe '..' {
    Mock Invoke-Command { Param($SB) . $SB }

    ...
}


问:
Padded text padding overflow not affecting word break
Word "under" should go to next line, but it doesn't cause of inline padding i think.

Is there anyway i can get text to break to next line when white padding touches edge of container.

Text needs to stay as inline cause i need that blank space between text lines. Tho if you have solution which requires to change that and result looks same as mine only the problem is fixed, than that will work too.

P.S. My container in real situation is 100% 100% so width,height is not fixed for the block.

It seems like it's not possible cause inline padding doesnt affect wrapping in any way and is completely ignored.

body {
  background: #111111;
}
.container {
  width: 338px;
  height: 600px;
  background-color: #000;
  font-family: Arial;
  text-align: center;
}
h1 {
  font-weight: bold;
  font-size: 48px;
  background-color: #fff;
  display: inline;
  line-height: 95px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
  padding: 10px 20px 10px 20px;
}
.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>Heading title</h1>
  <br/>
  <span class="sub">Some random text under heading title</span>
</div></code>```

答:
```<code>.sub {
  display: block;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}
</code>```

Change the display to block/inline-block and remove line-height. I hope it would help.

Body:
Word "under" should go to next line, but it doesn't cause of inline padding i think.

Is there anyway i can get text to break to next line when white padding touches edge of container.

Text needs to stay as inline cause i need that blank space between text lines. Tho if you have solution which requires to change that and result looks same as mine only the problem is fixed, than that will work too.

P.S. My container in real situation is 100% 100% so width,height is not fixed for the block.

It seems like it's not possible cause inline padding doesnt affect wrapping in any way and is completely ignored.

body {
  background: #111111;
}
.container {
  width: 338px;
  height: 600px;
  background-color: #000;
  font-family: Arial;
  text-align: center;
}
h1 {
  font-weight: bold;
  font-size: 48px;
  background-color: #fff;
  display: inline;
  line-height: 95px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
  padding: 10px 20px 10px 20px;
}
.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

Heading title

  Some random text under heading title

Body:
.sub {
  display: block;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

Change the display to block/inline-block and remove line-height. I hope it would help.


问:
Is it possible to read sub URL as query string in PHP?

    This is my LOCAL URL:

http://localhost/wbdrupal/?url=http://werkbad-konfigurator.de/datahub/searchObjectByID?table=furniture&column=wbid&search=

when I echo this variable $_GET['url'];

then the output is http://werkbad-konfigurator.de/datahub/searchObjectByID?table=furniture

but I need output as http://werkbad-konfigurator.de/datahub/searchObjectByID?table=furniture&column=wbid&search=

I need full query string when I write this command: echo $_GET['url'];

答:
Your URL is malformed and can't be parsed.  The system has no way of knowing which key/value pairs belong to the actual URL or to the url value you're trying to submit.

You need to URL-encode your values so the system can know what the key/value pairs are:

```<code>http://localhost/wbdrupal/?url=http%3A%2F%2Fwerkbad-konfigurator.de%2Fdatahub%2FsearchObjectByID%3Ftable%3Dfurniture%26column%3Dwbid%26search%3D
</code>```

Body:
Your URL is malformed and can't be parsed.  The system has no way of knowing which key/value pairs belong to the actual URL or to the url value you're trying to submit.

You need to URL-encode your values so the system can know what the key/value pairs are:

http://localhost/wbdrupal/?url=http%3A%2F%2Fwerkbad-konfigurator.de%2Fdatahub%2FsearchObjectByID%3Ftable%3Dfurniture%26column%3Dwbid%26search%3D


问:
ASP.NET Database Connection Issues with Azure Database
I followed the WingtipToys tutorial on the Microsoft website, which is basically a tutorial for ASP.NET and shows off numerous features it can do, and so on.

I made my own database to use during the tutorial, and had it working flawlessly on my local machine. Then, I decided to publish it to Azure to see it working online properly, which is where my issues began.

Firstly, I made a SQL database in Azure and moved my database across. I can connect to this Azure database in Visual Studio, and can verify that all the right tables are there, each filled with data;

The next step was to update my connection string, which is currently;

```<code>  <connectionStrings>
    <add name="WingtipTpys" providerName="System.Data.SqlClient" connectionString="Server=tcp:xxxx.database.windows.net,1433;Database=xxxx;Integrated Security=False;User Id=xxx;Password=xxxx;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" />
  </connectionStrings>
</code>```

Now, I was under the impression at this stage that the database and the website could now communicate with each other, so I published the website to see how it looks, which is where the really confusing part (for me) occurs.

When I visit the website URL that I published (http://completebusiness2017.azurewebsites.net/) it uses the right master page, and the about and contact pages are both how they should be. But, it is pulling in data from the;

ProductDatabaseInitializer

Class, which contains code such as;

```<code> private static List<Product> GetProducts()
    {
      var products = new List<Product> {
                new Product
                {
                    ProductID = 1,
                    ProductName = "TEST",
                    Description = "This convertible car is fast! The engine is powered by a neutrino based battery (not included)." +
                                  "Power it up and let it go!",
                    ImagePath="",
                    UnitPrice = 39.50,
                    CategoryID = 1
               },
                new Product
                {
                    ProductID = 2,
                    ProductName = "Silly Car",
                    Description = "There's nothing old about this toy car, except it's looks. Compatible with other old toy cars.",
                    ImagePath="",
                    UnitPrice = 15.95,
                     CategoryID = 1
               },
</code>```

This class has been there all along, but on my local machine, it was never used. The data came straight from the database I created. I don't understand how now I have updated the connection string, it is pulling data from this class, and not my database. Another strange element, is that when I update this class, so for example I changed;

Convertible Car Price from 22.50 to 39.50
  and
  Old-time Car name to Silly Car

These do not update when the website is published again. So I have no idea where or why it is using the old data.

So I guess my first question is, when I update the ProductDatabaseInitializer class, why aren't these changes reflected when the website is published again? I think I should understand why that is happening before I query why my database isn't working properly.

Any help at all would be very much appreciated.

Thank you, happy holidays.

答:
I am not 100% convinced that you're pulling data from where you think you are. Can you verify your database connection strings?

You'll need to look in a couple of places. First, in the Azure Portal, navigate to your Web App, then choose the "Application Settings" menu option. Check to see if you have anything listed under your "Connection Strings" section.

Second, log into your SCM site at the address http://completebusiness2017.scm.azurewebsites.net. Once logged in, choose Debug Console -> CMD. Then browse to your /wwwroot folder and examine the web.config file contents. Check to make sure that the connection string listed there is also what you expect.

Note that the App Settings Connection String listed in the portal will take precedence over what's in your web.config file. See if the database you expect to connect to is actually listed in these two places.

Also, log into your SCM site and browse to the /App_Data directory. See if there is a database there that you didn't expect to see.

Body:
I followed the WingtipToys tutorial on the Microsoft website, which is basically a tutorial for ASP.NET and shows off numerous features it can do, and so on.

I made my own database to use during the tutorial, and had it working flawlessly on my local machine. Then, I decided to publish it to Azure to see it working online properly, which is where my issues began.

Firstly, I made a SQL database in Azure and moved my database across. I can connect to this Azure database in Visual Studio, and can verify that all the right tables are there, each filled with data;

The next step was to update my connection string, which is currently;

  <connectionStrings>
    <add name="WingtipTpys" providerName="System.Data.SqlClient" connectionString="Server=tcp:xxxx.database.windows.net,1433;Database=xxxx;Integrated Security=False;User Id=xxx;Password=xxxx;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" />
  </connectionStrings>

Now, I was under the impression at this stage that the database and the website could now communicate with each other, so I published the website to see how it looks, which is where the really confusing part (for me) occurs.

When I visit the website URL that I published (http://completebusiness2017.azurewebsites.net/) it uses the right master page, and the about and contact pages are both how they should be. But, it is pulling in data from the;

ProductDatabaseInitializer

Class, which contains code such as;

 private static List<Product> GetProducts()
    {
      var products = new List<Product> {
                new Product
                {
                    ProductID = 1,
                    ProductName = "TEST",
                    Description = "This convertible car is fast! The engine is powered by a neutrino based battery (not included)." +
                                  "Power it up and let it go!",
                    ImagePath="",
                    UnitPrice = 39.50,
                    CategoryID = 1
               },
                new Product
                {
                    ProductID = 2,
                    ProductName = "Silly Car",
                    Description = "There's nothing old about this toy car, except it's looks. Compatible with other old toy cars.",
                    ImagePath="",
                    UnitPrice = 15.95,
                     CategoryID = 1
               },

This class has been there all along, but on my local machine, it was never used. The data came straight from the database I created. I don't understand how now I have updated the connection string, it is pulling data from this class, and not my database. Another strange element, is that when I update this class, so for example I changed;

Convertible Car Price from 22.50 to 39.50
  and
  Old-time Car name to Silly Car

These do not update when the website is published again. So I have no idea where or why it is using the old data.

So I guess my first question is, when I update the ProductDatabaseInitializer class, why aren't these changes reflected when the website is published again? I think I should understand why that is happening before I query why my database isn't working properly.

Any help at all would be very much appreciated.

Thank you, happy holidays.


问:
JQuery position do not have information when showing an element after being hidden
I'm trying to get the position of an element when the ajax success callback is executed which inside a call to html() function has added the content to a bootstrap dialog.  It returns 0

Here's the modal:

```<code><div id="ShipmentModal" class="modal fade">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">@Resource.ShipmentDialogTitle...</h4>
            </div>
            <div id="ShipmentText" class="modal-body">
            </div>
            <div class="modal-footer">
                <a data-dismiss="modal" class="btn btn-primary" onclick="SaveOrder($('#ShipmentForm').serialize())">@Resource.Save</a>
                <a class="btn btn-primary" onclick="GetShipmentPrices($('#ShipmentForm').serialize())">@Resource.Execute</a>
                <button id="DismissShipmentModal" type="button" class="btn btn-default" data-dismiss="modal">@Resource.Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

Here's the ajax call:

```<code>$.ajax({
    url: '/Shipments/GetShipmentPrices',
    type: 'POST',
    data: Model,
    success: function (Result) {
        if (Result.Success) {
            $('#BusyIndicator').fadeOut(function () {
                            $('#DismissShipmentModal').click();
                            $('#PricesText').html(Result.View);
                            $('#PricesModal').modal('show');
                        });
        }
        else {
            $('#BusyIndicator').fadeOut(function () {
                if (Result.Exception != "") {
                    $('#DismissShipmentModal').click();
                    $('#ResultText').html(Result.Exception);
                    $('#ResultModal').modal('show');
                }
                else {
                    $('#ShipmentText').html(Result.View).promise().done(function () {
                        var Element = $(this).find(".field-validation-error:first").closest('.form-group');
                        $('.modal-body').animate({ scrollTop: Element.position().top - 150 }, 1300, function () {
                            var ControlName = $(".field-validation-error:first").data("valmsg-for");
                            var Control = $("input[name='" + ControlName + "']");
                            $(Control).focus();
                        });
                    });
                }
            });
        }
    },
    error: function (jqXHR, textStatus, errorThrown) {
        $('#BusyIndicator').fadeOut(function () {
                        $('#DismissShipmentModal').click();
                        $('#ResultText').html(GetResponseText(jqXHR.responseText));
                        $('#ResultModal').modal('show');
                    });
    }
});
</code>```

I expect to be able to get the position of the element

When the dialog appears the element is hidden then if the user clicks a certain property the element is rendered to the user and then a call to the controller go validate the form and return and I should be able to get the element position since the element was shown to the user and the position should be available with jquery position()

答:
I solved my problem with a class I do remove and add accordinly and just making the section disabled rather then hidden however it's a workaround and the problem still exists.  Why an element that we make visible after being hidden doesn't have position information.</p>

```<code><style>
    .disableSection {
        pointer-events: none;
        background-color: lightgray;
        opacity: .3;
        padding-bottom: 5px;
    }
</style>
</code>```

Body:
I'm trying to get the position of an element when the ajax success callback is executed which inside a call to html() function has added the content to a bootstrap dialog.  It returns 0

Here's the modal:

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

@Resource.ShipmentDialogTitle...

                @Resource.Save
                @Resource.Execute
                <button id="DismissShipmentModal" type="button" class="btn btn-default" data-dismiss="modal">@Resource.Close</button>

Here's the ajax call:

$.ajax({
    url: '/Shipments/GetShipmentPrices',
    type: 'POST',
    data: Model,
    success: function (Result) {
        if (Result.Success) {
            $('#BusyIndicator').fadeOut(function () {
                            $('#DismissShipmentModal').click();
                            $('#PricesText').html(Result.View);
                            $('#PricesModal').modal('show');
                        });
        }
        else {
            $('#BusyIndicator').fadeOut(function () {
                if (Result.Exception != "") {
                    $('#DismissShipmentModal').click();
                    $('#ResultText').html(Result.Exception);
                    $('#ResultModal').modal('show');
                }
                else {
                    $('#ShipmentText').html(Result.View).promise().done(function () {
                        var Element = $(this).find(".field-validation-error:first").closest('.form-group');
                        $('.modal-body').animate({ scrollTop: Element.position().top - 150 }, 1300, function () {
                            var ControlName = $(".field-validation-error:first").data("valmsg-for");
                            var Control = $("input[name='" + ControlName + "']");
                            $(Control).focus();
                        });
                    });
                }
            });
        }
    },
    error: function (jqXHR, textStatus, errorThrown) {
        $('#BusyIndicator').fadeOut(function () {
                        $('#DismissShipmentModal').click();
                        $('#ResultText').html(GetResponseText(jqXHR.responseText));
                        $('#ResultModal').modal('show');
                    });
    }
});

I expect to be able to get the position of the element

When the dialog appears the element is hidden then if the user clicks a certain property the element is rendered to the user and then a call to the controller go validate the form and return and I should be able to get the element position since the element was shown to the user and the position should be available with jquery position()

Body:
I solved my problem with a class I do remove and add accordinly and just making the section disabled rather then hidden however it's a workaround and the problem still exists.  Why an element that we make visible after being hidden doesn't have position information.

<style>
    .disableSection {
        pointer-events: none;
        background-color: lightgray;
        opacity: .3;
        padding-bottom: 5px;
    }
</style>


问:
MFMailComposer Email Results From Core Data
Core data functions nicely.  What might be a code snippet to reference the results of the core data and insert into MFMailComposeViewController directly inline (not as an attachment) using isHTML = Yes...

Currently I use code similar to this style (from one of my other apps) (and works)... not sure how to call the core data results to do similar...

```<code>NSString *emailBody = [NSString stringWithFormat:@"<p>Stats...</p>
<p><b>Laps Completed: %@</b></p><p>Goal: %@ laps</p>
<p>Time To Complete: %@ (h:m:s)</p>
<p>%f&#37 completion ratio</p>",
self.lapLabel.text, self.goal.text, self.timeLabel.text,
(self.percentageDoughnut.percentage)*100];

    [mail setMessageBody:emailBody isHTML:YES];
</code>```

答:
You can use UIActivityViewController with attaching file data from local storage, check below code</p>

```<code> let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
 activityVC.popoverPresentationController?.sourceView = self.view .
 activityVC.popoverPresentationController?.sourceRect = sender.frame
 self.present(activityVC, animated: true, completion: nil)
</code>```

Body:
Core data functions nicely.  What might be a code snippet to reference the results of the core data and insert into MFMailComposeViewController directly inline (not as an attachment) using isHTML = Yes...

Currently I use code similar to this style (from one of my other apps) (and works)... not sure how to call the core data results to do similar...

NSString *emailBody = [NSString stringWithFormat:@"
Stats...

Laps Completed: %@

Goal: %@ laps

Time To Complete: %@ (h:m:s)

%f&#37 completion ratio
",
self.lapLabel.text, self.goal.text, self.timeLabel.text,
(self.percentageDoughnut.percentage)*100];

    [mail setMessageBody:emailBody isHTML:YES];

Body:
You can use UIActivityViewController with attaching file data from local storage, check below code

 let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
 activityVC.popoverPresentationController?.sourceView = self.view .
 activityVC.popoverPresentationController?.sourceRect = sender.frame
 self.present(activityVC, animated: true, completion: nil)


问:
iOS: TapGestureRecognizer in UIView not fired
I have create an date component and have problems with the GestureRecognizer.

First line is a StackView with labels. If I attach a TapGestureRecognizer it is fired on touch. The following Lines are subviews in a Stackview consisting of a label and an image view. I can add the Recognizer to the subview, to the label or the image view. It never gets fired and I made sure that userInteraction is enabled.

What could be the problem?

Here an example how I add the recognizer:

```<code>func addTap(){
        dayLabel.isUserInteractionEnabled = true
        imageView.isUserInteractionEnabled = true
        isUserInteractionEnabled = true

        tap1 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap2 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap3 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))

    dayLabel.addGestureRecognizer(tap1!)
    imageView.addGestureRecognizer(tap2!)
    addGestureRecognizer(tap3!)
    }

    @objc func handleTap(recognizer: UITapGestureRecognizer){
        logger.debug("tap")
        changeSelection()
    }
</code>```

You can find a little demo project boiled down to the problem here: https://github.com/ogezue/datedemo

答: For every view (Label/Imageview) you should create a tap object not the same one added to both . . .

Body:
I have create an date component and have problems with the GestureRecognizer.

First line is a StackView with labels. If I attach a TapGestureRecognizer it is fired on touch. The following Lines are subviews in a Stackview consisting of a label and an image view. I can add the Recognizer to the subview, to the label or the image view. It never gets fired and I made sure that userInteraction is enabled.

What could be the problem?

Here an example how I add the recognizer:

func addTap(){
        dayLabel.isUserInteractionEnabled = true
        imageView.isUserInteractionEnabled = true
        isUserInteractionEnabled = true

        tap1 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap2 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap3 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))

    dayLabel.addGestureRecognizer(tap1!)
    imageView.addGestureRecognizer(tap2!)
    addGestureRecognizer(tap3!)
    }

    @objc func handleTap(recognizer: UITapGestureRecognizer){
        logger.debug("tap")
        changeSelection()
    }

You can find a little demo project boiled down to the problem here: https://github.com/ogezue/datedemo


问:
My ethereum balance seems to be 0 when checked via geth
I created an ethereum address

```<code>geth account new
</code>```

and sent some ethers to it. Then I ran the server:

```<code>geth
</code>```

and the JavaScript console:

```<code>geth attach
</code>```

I checked the balance, but it was 0:

```<code>> eth.getBalance('0xB97168a67AB66E55B98B1439222Ee665E657fFc0')
0
</code>```

When I checked the balance via etherchain, there were some ethers.

What am I doing wrong?

答: It may be that your node has not downloaded the latest blocks in the blockchain, one of which contains your transaction. See: My ethereum balance returns 0 when checked via geth, but according to etherchain it has a value for more details.</p>

Body:
I created an ethereum address

geth account new

and sent some ethers to it. Then I ran the server:

geth

and the JavaScript console:

geth attach

I checked the balance, but it was 0:

> eth.getBalance('0xB97168a67AB66E55B98B1439222Ee665E657fFc0')
0

When I checked the balance via etherchain, there were some ethers.

What am I doing wrong?


问:
python ignore blank values csv loop
I am looping through an excel file and I am making two columns a dictionary then into a list. I when looping though the list if the 2nd column has a blank it errors out. How can i get the 2nd column to ignore blanks and keep the loop going.

```<code>mydict = df1.groupby(['first'])['second'].apply(list).to_dict()
qry =list(' '.join(value) for key, value in mydict.items() if 'exampleword' in key)
qryCounted =Counter(" ".join(qry).split(" ")).items()
print(sorted(qryCounted,key=lambda x:(-x[1],x[0])))
</code>```

The error i get is

```<code>TypeError: sequence item 3: expected string or Unicode, float found
</code>```

答:
try to convert the element to string first.

```<code> qry =list(' '.join(str(value)) for key, value in mydict.items() if 'exampleword' in key)
</code>```

--- update ---

it the value is list

```<code> qry =list(' '.join(map(str,value))) for key, value in mydict.items() if 'exampleword' in key)
</code>```

Title: python ignore blank values csv loop

Body:
I am looping through an excel file and I am making two columns a dictionary then into a list. I when looping though the list if the 2nd column has a blank it errors out. How can i get the 2nd column to ignore blanks and keep the loop going.

mydict = df1.groupby(['first'])['second'].apply(list).to_dict()
qry =list(' '.join(value) for key, value in mydict.items() if 'exampleword' in key)
qryCounted =Counter(" ".join(qry).split(" ")).items()
print(sorted(qryCounted,key=lambda x:(-x[1],x[0])))

The error i get is

TypeError: sequence item 3: expected string or Unicode, float found

Body:
try to convert the element to string first.

 qry =list(' '.join(str(value)) for key, value in mydict.items() if 'exampleword' in key)

--- update ---

it the value is list

 qry =list(' '.join(map(str,value))) for key, value in mydict.items() if 'exampleword' in key)


问:
Null reference '#as(test, 0)' that comes from line 28 will be dereferenced at line 28
I have below classes,

```<code>public class Test1
{
    public Test2 Test2 { get; set; }
}

public class Test2 { }
</code>```

Now I have below method,

```<code>private void Test()
    {
        var test = ConfigurationManager.GetSection("Test");

        if (test != null)
        {
            var a= (test as Test1).Test2;
        }
    }
</code>```

Now I am getting Klockwork error saying,

Null reference '#as(test, 0)' that comes from line 28 will be dereferenced at line 28

What this error mean and how to resolve it?

Note that this is Klockwork error, however C# compiling will not have any error.

Error at below line of code,

var a= (test as Test1).Test2;

答:
It will compile but theres a chance with as that the resulting value could be null. You can ensure that it won't throw this way:

```<code>    var test = ConfigurationManager.GetSection("Test") as Test1;

    if (test != null)
    {
        var a = test.Test2;
    }
</code>```

Body:
I have below classes,

public class Test1
{
    public Test2 Test2 { get; set; }
}

public class Test2 { }

Now I have below method,

private void Test()
    {
        var test = ConfigurationManager.GetSection("Test");

        if (test != null)
        {
            var a= (test as Test1).Test2;
        }
    }

Now I am getting Klockwork error saying,

Null reference '#as(test, 0)' that comes from line 28 will be dereferenced at line 28

What this error mean and how to resolve it?

Note that this is Klockwork error, however C# compiling will not have any error.

Error at below line of code,

var a= (test as Test1).Test2;

Body:
It will compile but theres a chance with as that the resulting value could be null. You can ensure that it won't throw this way:

    var test = ConfigurationManager.GetSection("Test") as Test1;

    if (test != null)
    {
        var a = test.Test2;
    }


问:
How to calculate what the sum of these Strings is?
```<code>import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Num2 = "2"
print ("som:", Num1 , Operator , Num2, "= ")
</code>```

I created some variables, one of which is an operator, I printed but now I have to calculate it...
I tried using eval(), but I could not get this to work.

How would I calculate this sum?

答:
eval() does not support operator ^, but you could get around with it.

```<code>import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Operator = "*"
    Num2 = Num1
result = eval(Num1+Operator+Num2)
print ("som:", Num1 , Operator , Num2, "= ", result)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Num2 = "2"
print ("som:", Num1 , Operator , Num2, "= ")

I created some variables, one of which is an operator, I printed but now I have to calculate it...
I tried using eval(), but I could not get this to work.

How would I calculate this sum?

Body:
eval() does not support operator ^, but you could get around with it.

import sys
import random
Num1 = str(random.randint(1,109))
Num2 = str(random.randint(1,109))
Opp = ["+", "-", "*", "^", "/"]

secure_random = random.SystemRandom()

Operator = secure_random.choice(Opp)
if Operator == "^":
    Operator = "*"
    Num2 = Num1
result = eval(Num1+Operator+Num2)
print ("som:", Num1 , Operator , Num2, "= ", result)


问:
traefik: passTLSCert -> Failed to create TLSClientConfig
Isn't this configuration suppose to work?

```<code>#logLevel = "DEBUG"

defaultEntryPoints = ["https"]

[entryPoints]
  [entryPoints.https]
  address = ":443"

[file]

# rules
[backends]
  [backends.backend2]
    [backends.backend2.servers.server1]
    url = "https://google.de:443"
    weight = 1

[frontends]
  [frontends.frontend1]
  backend = "backend2"
  passHostHeader = true
  passTLSCert=true
    [frontends.frontend1.routes.default]
    rule = "Host:search.dev"

[web]
  address = ":8080"
</code>```

I would expect to visit https://search.dev in my browser and see google.com (given that search.dev resolves to 127.0.0.1).
But instead I see this:

```<code>$ docker run -p 8080:8080 -p 443:443 -v $PWD/traefik.toml:/etc/traefik/traefik.toml traefik
time="2017-12-05T20:39:54Z" level=info msg="Using TOML configuration file /etc/traefik/traefik.toml"
time="2017-12-05T20:39:54Z" level=error msg="Failed to create TLSClientConfig: no TLS provided"
time="2017-12-05T20:39:54Z" level=error msg="Failed to create RoundTripper for frontend frontend1: no TLS provided"
time="2017-12-05T20:39:54Z" level=error msg="Skipping frontend frontend1..."
</code>```

I specifically asked traefik not to do the SSL termination: passTLSCert=true

Some more details:

```<code>Version:      v1.4.4
Codename:     roquefort
Go version:   go1.9.2
Built:        2017-11-23_10:53:58AM
OS/Arch:      linux/amd64
</code>```

答:
One thing worth noting is that passTLSCert tells Traefik to forward TLS Client certificates to the backend.  It does not disable SSL termination on Traefik as you are hoping it would.

In order for your configuration to work you will need to specify the certificates for Traefik to use.

If you are using local certificates an example would be:

```<code>#logLevel = "DEBUG"

defaultEntryPoints = ["https"]

[entryPoints]
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]
      [[entryPoints.https.tls.certificates]]
      certFile = "example.crt"
      keyFile = "example.key"

[file]

# rules
[backends]
  [backends.backend2]
    [backends.backend2.servers.server1]
    url = "https://google.de:443"
    weight = 1

[frontends]
  [frontends.frontend1]
  backend = "backend2"
  passHostHeader = true
  passTLSCert=true
    [frontends.frontend1.routes.default]
    rule = "Host:search.dev"

[web]
  address = ":8080"
</code>```

Body:
Isn't this configuration suppose to work?

#logLevel = "DEBUG"

defaultEntryPoints = ["https"]

[entryPoints]
  [entryPoints.https]
  address = ":443"

[file]

# rules
[backends]
  [backends.backend2]
    [backends.backend2.servers.server1]
    url = "https://google.de:443"
    weight = 1

[frontends]
  [frontends.frontend1]
  backend = "backend2"
  passHostHeader = true
  passTLSCert=true
    [frontends.frontend1.routes.default]
    rule = "Host:search.dev"

[web]
  address = ":8080"

I would expect to visit https://search.dev in my browser and see google.com (given that search.dev resolves to 127.0.0.1).
But instead I see this:

$ docker run -p 8080:8080 -p 443:443 -v $PWD/traefik.toml:/etc/traefik/traefik.toml traefik
time="2017-12-05T20:39:54Z" level=info msg="Using TOML configuration file /etc/traefik/traefik.toml"
time="2017-12-05T20:39:54Z" level=error msg="Failed to create TLSClientConfig: no TLS provided"
time="2017-12-05T20:39:54Z" level=error msg="Failed to create RoundTripper for frontend frontend1: no TLS provided"
time="2017-12-05T20:39:54Z" level=error msg="Skipping frontend frontend1..."

I specifically asked traefik not to do the SSL termination: passTLSCert=true

Some more details:

Version:      v1.4.4
Codename:     roquefort
Go version:   go1.9.2
Built:        2017-11-23_10:53:58AM
OS/Arch:      linux/amd64

Body:
One thing worth noting is that passTLSCert tells Traefik to forward TLS Client certificates to the backend.  It does not disable SSL termination on Traefik as you are hoping it would.

In order for your configuration to work you will need to specify the certificates for Traefik to use.

If you are using local certificates an example would be:

#logLevel = "DEBUG"

defaultEntryPoints = ["https"]

[entryPoints]
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]
      [[entryPoints.https.tls.certificates]]
      certFile = "example.crt"
      keyFile = "example.key"

[file]

# rules
[backends]
  [backends.backend2]
    [backends.backend2.servers.server1]
    url = "https://google.de:443"
    weight = 1

[frontends]
  [frontends.frontend1]
  backend = "backend2"
  passHostHeader = true
  passTLSCert=true
    [frontends.frontend1.routes.default]
    rule = "Host:search.dev"

[web]
  address = ":8080"


问:
Remove strange characters from .mdb field names
I have a large number of .mdb-files (as in Microsoft Access db-files). The first field (or column) is supposed be named say MyField1. However the files are corrupted so that the actual field name is \ufeffMyField1 or in other words there is 0xFEFFprepended to the actual field name.

I'm trying to copy the field in question from \ufeffMyField1 to NewField using the pyodbc-command

```<code>cursor.execute("UPDATE MyTable SET NewField=" + colname + ";")
</code>```

where colnameis the errouneous field name (assume that NewFieldalready exists)

The value of colname is fetched with pyodbc using something like

```<code>rows = cur.columns(table='MyTable')
for row in rows:
   if("MyField1" in row.column_name):
      colname=row.column_name
</code>```

Executing the UPDATE... command yields a driver error that the MaxLocksPerFile Ms Access parameter is too low, as described here https://support.microsoft.com/en-us/help/815281/-file-sharing-lock-count-exceeded-error-message-during-large-transacti.
However I've increased the MaxLocksPerFile parameter with several orders of magnitude while opening only a single file in the program, so it seems it is not the actual problem.

Note that without problem I can open the file in MS Access and rename the field in the gui. I have not found a way to see in the gui that the field is incorrectly named, supposedly since the extra bits doesn't match common encodings.

Finally this leads me to my question: how can I pass raw bytes as pyodbc-commands?

Alternatively please suggest in comments if you have other ways to solve the real-world problem of removing the extra characters? (as in clean out all non-ASCII characters from the field names)

答:
If you want to use DAO, then it is pretty simple.  You can modify the following code to find and loop thru a folder of all databases.</p>

```<code>Sub Rename_First_Field()
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field

    Set dbs = OpenDatabase("C:\....\SomeDB.mdb")
    For Each tdf In dbs.TableDefs           ' Spin thru all tables in this database
        Set fld = tdf.Fields(0)             ' Grab the first field
        Debug.Print tdf.Name & vbTab & "|" & vbTab & fld.Name
        fld.Name = "MyField1"               ' Rename to 'MyField1'
    Next tdf                                'Move to next table
    Set tdf = Nothing
    Set dbs = Nothing
End Sub
</code>```

Body:
I have a large number of .mdb-files (as in Microsoft Access db-files). The first field (or column) is supposed be named say MyField1. However the files are corrupted so that the actual field name is \ufeffMyField1 or in other words there is 0xFEFFprepended to the actual field name.

I'm trying to copy the field in question from \ufeffMyField1 to NewField using the pyodbc-command

cursor.execute("UPDATE MyTable SET NewField=" + colname + ";")

where colnameis the errouneous field name (assume that NewFieldalready exists)

The value of colname is fetched with pyodbc using something like

rows = cur.columns(table='MyTable')
for row in rows:
   if("MyField1" in row.column_name):
      colname=row.column_name

Executing the UPDATE... command yields a driver error that the MaxLocksPerFile Ms Access parameter is too low, as described here https://support.microsoft.com/en-us/help/815281/-file-sharing-lock-count-exceeded-error-message-during-large-transacti.
However I've increased the MaxLocksPerFile parameter with several orders of magnitude while opening only a single file in the program, so it seems it is not the actual problem.

Note that without problem I can open the file in MS Access and rename the field in the gui. I have not found a way to see in the gui that the field is incorrectly named, supposedly since the extra bits doesn't match common encodings.

Finally this leads me to my question: how can I pass raw bytes as pyodbc-commands?

Alternatively please suggest in comments if you have other ways to solve the real-world problem of removing the extra characters? (as in clean out all non-ASCII characters from the field names)

Body:
If you want to use DAO, then it is pretty simple.  You can modify the following code to find and loop thru a folder of all databases.

Sub Rename_First_Field()
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field

    Set dbs = OpenDatabase("C:\....\SomeDB.mdb")
    For Each tdf In dbs.TableDefs           ' Spin thru all tables in this database
        Set fld = tdf.Fields(0)             ' Grab the first field
        Debug.Print tdf.Name & vbTab & "|" & vbTab & fld.Name
        fld.Name = "MyField1"               ' Rename to 'MyField1'
    Next tdf                                'Move to next table
    Set tdf = Nothing
    Set dbs = Nothing
End Sub


问:
How to use Where operator in Linq
```<code>SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported
</code>```

but why when I use number instead of parameter it works fine ?

```<code>SomeObject.Where(p => FunctionOn(1));
</code>```

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .

答:
```<code>SomeObject.Where(p => FunctionOn(p.I));
</code>```

You said that SomeObject is an IQueryable. This makes me suspect that you aren't querying an in-memory collection (LINQ-to-Objects), where your query should succeed without any problems, but you're possibly querying something more "dynamic". For the sake of demonstrating the problem, I will assume that we're dealing with LINQ-to-SQL here... but that assumption doesn't have to be necessarily true for what I would like to explain below:

Update: You've just said in a comment that you're using LINQ-to-MongoDB, so the below should apply to your issue.

With something like LINQ-to-SQL, the problem with your query isn't that something's wrong with the FunctionOn predicate method, or with the way you're combining it with the Where operator. The problem at hand is that LINQ-to-SQL (or whatever LINQ provider you're using) doesn't recognise your method. It's trying to convert your LINQ expression into an SQL query at runtime (that's exactly what IQueryable is good for, after all!), but it doesn't know how to convert your FunctionOn to SQL.

If LINQ-to-SQL were to achieve this, it would have to figure out what your method is doing, and then find a way to express that as valid SQL. That would take a lot of sophistication and intelligence. For example, it would have to inspect your method e.g. by decompiling it, and then re-compiling it as SQL. This clearly cannot work for any arbitrarily complex method. Imagine that your FunctionOn method contained a call to Debug.WriteLine. There's no way that this could be translated into an SQL query.

Thus LINQ-to-SQL is restricted to a few cases and expressions that it knows how to handle. If it encounters anything else in a LINQ expression, it'll let you know that it doesn't know how to handle FunctionOn (ie. how to convert it to SQL) by saying something like, "The method FunctionOn is not supported."

Once you write your query as:

```<code>SomeObject.Where(p => p.I == 1);
</code>```

everything should work fine, since LINQ-to-SQL knows how to translate your p.I == 1 to a corresponding equality test in a SQL WHERE clause.

Title: How to use Where operator in Linq

Body:
SomeObject.Where(p => FunctionOn(p.I));
<<>>
public bool FunctionOn(int i){
    return (i == 1);}
<<>>
error message : The method FunctionOn is not supported

but why when I use number instead of parameter it works fine ?

SomeObject.Where(p => FunctionOn(1));

I was wondering if there is a way to implement this code in Linq , because it gives me an error .
 Thank you .

Body:
SomeObject.Where(p => FunctionOn(p.I));

You said that SomeObject is an IQueryable. This makes me suspect that you aren't querying an in-memory collection (LINQ-to-Objects), where your query should succeed without any problems, but you're possibly querying something more "dynamic". For the sake of demonstrating the problem, I will assume that we're dealing with LINQ-to-SQL here... but that assumption doesn't have to be necessarily true for what I would like to explain below:

Update: You've just said in a comment that you're using LINQ-to-MongoDB, so the below should apply to your issue.

With something like LINQ-to-SQL, the problem with your query isn't that something's wrong with the FunctionOn predicate method, or with the way you're combining it with the Where operator. The problem at hand is that LINQ-to-SQL (or whatever LINQ provider you're using) doesn't recognise your method. It's trying to convert your LINQ expression into an SQL query at runtime (that's exactly what IQueryable is good for, after all!), but it doesn't know how to convert your FunctionOn to SQL.

If LINQ-to-SQL were to achieve this, it would have to figure out what your method is doing, and then find a way to express that as valid SQL. That would take a lot of sophistication and intelligence. For example, it would have to inspect your method e.g. by decompiling it, and then re-compiling it as SQL. This clearly cannot work for any arbitrarily complex method. Imagine that your FunctionOn method contained a call to Debug.WriteLine. There's no way that this could be translated into an SQL query.

Thus LINQ-to-SQL is restricted to a few cases and expressions that it knows how to handle. If it encounters anything else in a LINQ expression, it'll let you know that it doesn't know how to handle FunctionOn (ie. how to convert it to SQL) by saying something like, "The method FunctionOn is not supported."

Once you write your query as:

SomeObject.Where(p => p.I == 1);

everything should work fine, since LINQ-to-SQL knows how to translate your p.I == 1 to a corresponding equality test in a SQL WHERE clause.


问:
disabling spring security in spring boot app
I have a spring boot web app with spring security configured. I want to disable authentication for a while (until needed).

I add this to the application.properties:

```<code>security.basic.enable: false
management.security.enabled: false
</code>```

Here is some part of my

But I still have a basic security included : There is a default security password generated at startup and I am still getting HTTP Authentication prompt box.

My pom.xml :

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>fr.test.sample</groupId>
    <artifactId>navigo</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <jsoup.version>1.8.3</jsoup.version>
        <guava.version>18.0</guava.version>
        <postgresql.version>9.3-1103-jdbc41</postgresql.version>
    </properties>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>${jsoup.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            </dependency>
    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <!-- Add Spring repositories -->
    <!-- (you don't need this if you are using a .RELEASE version) -->
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

The security is configured in WebSecurityConfig.java (I have commented the annotation to disable it) :

```<code>//@Configuration
//@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
//@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    UserService userService;

    @Autowired
    private DataSource datasource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // http.authorizeRequests().antMatchers("/bus/topologie", "/home")
        // http.authorizeRequests().anyRequest().authenticated()
        // .antMatchers("/admin/**").access("hasRole('ADMIN')").and()
        // .formLogin().failureUrl("/login?error")
        // .defaultSuccessUrl("/bus/topologie").loginPage("/login")
        // .permitAll().and().logout()
        // .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        // .logoutSuccessUrl("/login").permitAll().and().rememberMe()
        // .rememberMeParameter("remember-me")
        // .tokenRepository(persistentTokenRepository())
        // .tokenValiditySeconds(86400).and().csrf();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
        tokenRepositoryImpl.setDataSource(datasource);
        return tokenRepositoryImpl;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        PasswordEncoder encoder = new BCryptPasswordEncoder();

        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
        auth.jdbcAuthentication().dataSource(datasource);

        if (!userService.userExists("user")) {
            User userAdmin = new User("user", encoder.encode("password"), true);
            Set<Authorities> authorities = new HashSet<Authorities>();
            authorities.add(new Authorities(userAdmin,"ADMIN"));
            authorities.add(new Authorities(userAdmin,"CRIP"));
            authorities.add(new Authorities(userAdmin,"USER"));
            userAdmin.setAuthorities(authorities);

            userService.createUser(userAdmin);
        }
    }

}
</code>```

答:
Use @profile("whatever-name-profile-to-activate-if-needed") on your security configuration class that extends WebSecurityConfigurerAdapter

```<code>security.ignored=/**

security.basic.enable: false
</code>```

NB. I need to debug to know why why exclude auto configuration did not work for me. But the profile is sot so bad as you can still re-activate it via configuration properties if needed

Body:
I have a spring boot web app with spring security configured. I want to disable authentication for a while (until needed).

I add this to the application.properties:

security.basic.enable: false
management.security.enabled: false

Here is some part of my

But I still have a basic security included : There is a default security password generated at startup and I am still getting HTTP Authentication prompt box.

My pom.xml :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>fr.test.sample</groupId>
    <artifactId>navigo</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.1.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.7</java.version>
        <jsoup.version>1.8.3</jsoup.version>
        <guava.version>18.0</guava.version>
        <postgresql.version>9.3-1103-jdbc41</postgresql.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>${jsoup.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>http://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>http://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

</project>

The security is configured in WebSecurityConfig.java (I have commented the annotation to disable it) :

//@Configuration
//@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
//@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    UserService userService;

    @Autowired
    private DataSource datasource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // http.authorizeRequests().antMatchers("/bus/topologie", "/home")
        // http.authorizeRequests().anyRequest().authenticated()
        // .antMatchers("/admin/**").access("hasRole('ADMIN')").and()
        // .formLogin().failureUrl("/login?error")
        // .defaultSuccessUrl("/bus/topologie").loginPage("/login")
        // .permitAll().and().logout()
        // .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        // .logoutSuccessUrl("/login").permitAll().and().rememberMe()
        // .rememberMeParameter("remember-me")
        // .tokenRepository(persistentTokenRepository())
        // .tokenValiditySeconds(86400).and().csrf();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
        tokenRepositoryImpl.setDataSource(datasource);
        return tokenRepositoryImpl;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        PasswordEncoder encoder = new BCryptPasswordEncoder();

        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
        auth.jdbcAuthentication().dataSource(datasource);

        if (!userService.userExists("user")) {
            User userAdmin = new User("user", encoder.encode("password"), true);
            Set<Authorities> authorities = new HashSet<Authorities>();
            authorities.add(new Authorities(userAdmin,"ADMIN"));
            authorities.add(new Authorities(userAdmin,"CRIP"));
            authorities.add(new Authorities(userAdmin,"USER"));
            userAdmin.setAuthorities(authorities);

            userService.createUser(userAdmin);
        }
    }

}

Body:
Use @profile("whatever-name-profile-to-activate-if-needed") on your security configuration class that extends WebSecurityConfigurerAdapter

security.ignored=/**

security.basic.enable: false

NB. I need to debug to know why why exclude auto configuration did not work for me. But the profile is sot so bad as you can still re-activate it via configuration properties if needed