问:
How to implode image file names into mysql database
I am uploading multiple images to my sql database but my implode method isn't working...</p>

```<code>if(isset($_POST['submit'])) {
    $id     = $_POST['id'];
    for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
      $filetmp  = $_FILES['file_upload']['tmp_name'][$i];
      $filename = basename($_FILES['file_upload']['name'][$i]);
      $filetype = $_FILES['file_upload']['type'][$i];
      $filepath = "../images/".$filename;
      move_uploaded_file($filetmp,$filepath);
    }
      $mainfiles = implode(", ", $filename);

      $sql  = "INSERT INTO pictures2 (";
      $sql .= "image, photograph_id";
      $sql .= ") VALUES ('";
      $sql .= $database->escape_character($mainfiles) ."', '";
      $sql .= $id ."')";
      $result = $database->query($sql);
        if($result){
        $session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
        }

}
</code>```

答:
$filename should be an array. You are passing string into implode function. Do something like this.

```<code> if(isset($_POST['submit'])) {
    $id     = $_POST['id'];
    $filename= [];
    for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
      $filetmp  = $_FILES['file_upload']['tmp_name'][$i];
      $filename[] = basename($_FILES['file_upload']['name'][$i]);
      $filetype = $_FILES['file_upload']['type'][$i];
      $filepath = "../images/".$filename[$i];
      move_uploaded_file($filetmp,$filepath);
    }
      $mainfiles = implode(", ", $filename);

      $sql  = "INSERT INTO pictures2 (";
      $sql .= "image, photograph_id";
      $sql .= ") VALUES ('";
      $sql .= $database->escape_character($mainfiles) ."', '";
      $sql .= $id ."')";
      $result = $database->query($sql);
        if($result){
        $session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
        }

}
</code>```

Hope this helps.

Body:
I am uploading multiple images to my sql database but my implode method isn't working...

if(isset($_POST['submit'])) {
    $id     = $_POST['id'];
    for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
      $filetmp  = $_FILES['file_upload']['tmp_name'][$i];
      $filename = basename($_FILES['file_upload']['name'][$i]);
      $filetype = $_FILES['file_upload']['type'][$i];
      $filepath = "../images/".$filename;
      move_uploaded_file($filetmp,$filepath);
    }
      $mainfiles = implode(", ", $filename);

      $sql  = "INSERT INTO pictures2 (";
      $sql .= "image, photograph_id";
      $sql .= ") VALUES ('";
      $sql .= $database->escape_character($mainfiles) ."', '";
      $sql .= $id ."')";
      $result = $database->query($sql);
        if($result){
        $session->message('
Pictures uploaded sucessfully.
');
        }

}

Body:
$filename should be an array. You are passing string into implode function. Do something like this.

 if(isset($_POST['submit'])) {
    $id     = $_POST['id'];
    $filename= [];
    for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
      $filetmp  = $_FILES['file_upload']['tmp_name'][$i];
      $filename[] = basename($_FILES['file_upload']['name'][$i]);
      $filetype = $_FILES['file_upload']['type'][$i];
      $filepath = "../images/".$filename[$i];
      move_uploaded_file($filetmp,$filepath);
    }
      $mainfiles = implode(", ", $filename);

      $sql  = "INSERT INTO pictures2 (";
      $sql .= "image, photograph_id";
      $sql .= ") VALUES ('";
      $sql .= $database->escape_character($mainfiles) ."', '";
      $sql .= $id ."')";
      $result = $database->query($sql);
        if($result){
        $session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
        }

}

Hope this helps.


来源: stackexchange

问:
Angular "Cannot read property 'subscribe' of undefined"
Before I start my question, I'd like to let you know that I already did a big research, and I cannot find a solution ( explanation ) why I get this error.

Please also note, that I am totally new on Angular, and I just started to learn how it works.

So, the problem I have is what I have entered in the title of this question.

What I try to do, is to build a login system using the Firebase, based on a course I purchase on Udemy.

The code I use is the following:

auth.service.ts

```<code>import {Injectable} from '@angular/core';
import * as firebase from 'firebase';

@Injectable ()
export class AuthService {
    token: string;

    // ...

    singInUser ( email: string, password: string ) {
        // login process here ...
    }

    // Responsible to retrieve the authenticated user token
    getToken () {
        return firebase
            .auth ()
            .currentUser
            .getIdToken ();
    }
}
</code>```

data-storage.service.ts

```<code>// ... Dependencies here
@Injectable ()
export class DataStorageService {
    private recipeEndPoint: string = 'https://my-unique-id.firebaseio.com/recipes.json';
    private recipeSubscription: Observable<any> = new Observable();

    constructor ( private http: Http,
                  private recipes: RecipeService,
                  private authService: AuthService ) {}

    // other functionality ...

    getRecipes () {
        const token = this.authService.getToken ();

        token.then (
            ( token: string ) => {
                this.recipeSubscription = this.http.get ( this.recipeEndPoint + '?auth=' + token ).map (
                    ( data: Response ) => {
                        return data.json ();
                    }
                );

                // THIS PARTICULAR CODE WORKS AS EXPECTED
                // WITH NO ISSUES
                this.recipeSubscription.subscribe (
                    ( data: Response ) => {
                        console.log ( 'Data response: ', data );
                    },
                    ( error ) => {
                        console.log ( 'Error: ' + error );
                    }
                )
            }
        );

        // This is supposed to return an Observable to the caller
        return this.recipeSubscription;
    }
}
</code>```

header.component.ts

```<code>// Dependencies here ...

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  constructor(private dataStorage: DataStorageService, private recipeService: RecipeService) { }

  // Other Code Here ...

  onFetchData() {
    let recipeSubscription = this.dataStorage.getRecipes();

    // THIS RETURNS TRUE
    console.log(recipeSubscription instanceof Observable);

    // THIS LINE THEN RETURNS THE MESSAGE:
    // ERROR TypeError: Cannot read property 'subscribe' of undefined
    recipeSubscription.subscribe();

    // IF I COMMENT OUT THE PREVIOUS LINE
    setTimeout(
      () => {
        // THIS RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      500
    );

    setTimeout(
      () => {
        // AS WELL THIS ONE RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      1000
    );

    setTimeout(
      () => {
        // AS WELL THIS ONE RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      1500
    );
  }
}
</code>```

So, unfortunately, I cannot see what could be wrong with this code. Can anyone spot anything I did wrong?

Note: I have removed parts of my code just for make the snippets more readable. If you need any other part, please feel free to ask me, and I will provide it here.

UPDATE #1

This is how it looks like the header.component.html

```<code><nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header">Logo Here</div>

        <div class="navbar-default">
            <ul class="nav navbar-nav">
                <!-- Left Navigation Options -->
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <!-- Right Navigation Options -->
                <li class="dropdown" appDropdown>
                    <a routerLink="/" class="dropdown-toggle" role="button">Manage <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li>
                            <a style="cursor: pointer;" (click)="onSaveData()">Save Data</a>
                        </li>
                        <li>
                            <!-- Here is where I call the onFetchData method -->
                            <a style="cursor: pointer;" (click)="onFetchData()">Fetch Data</a>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>
</code>```

答:
Ionic 4.

I had a method that subscribes to an observable, calling that method within ngOnInit, raised this error. Moving the method call to constructor solved my problem.

ContentLicense: CC BY-SA 3.0

Body:
Before I start my question, I'd like to let you know that I already did a big research, and I cannot find a solution ( explanation ) why I get this error.

Please also note, that I am totally new on Angular, and I just started to learn how it works.

So, the problem I have is what I have entered in the title of this question.

What I try to do, is to build a login system using the Firebase, based on a course I purchase on Udemy.

The code I use is the following:

auth.service.ts

import {Injectable} from '@angular/core';
import * as firebase from 'firebase';

@Injectable ()
export class AuthService {
    token: string;

    // ...

    singInUser ( email: string, password: string ) {
        // login process here ...
    }

    // Responsible to retrieve the authenticated user token
    getToken () {
        return firebase
            .auth ()
            .currentUser
            .getIdToken ();
    }
}

data-storage.service.ts

// ... Dependencies here
@Injectable ()
export class DataStorageService {
    private recipeEndPoint: string = 'https://my-unique-id.firebaseio.com/recipes.json';
    private recipeSubscription: Observable<any> = new Observable();

    constructor ( private http: Http,
                  private recipes: RecipeService,
                  private authService: AuthService ) {}

    // other functionality ...

    getRecipes () {
        const token = this.authService.getToken ();

        token.then (
            ( token: string ) => {
                this.recipeSubscription = this.http.get ( this.recipeEndPoint + '?auth=' + token ).map (
                    ( data: Response ) => {
                        return data.json ();
                    }
                );

                // THIS PARTICULAR CODE WORKS AS EXPECTED
                // WITH NO ISSUES
                this.recipeSubscription.subscribe (
                    ( data: Response ) => {
                        console.log ( 'Data response: ', data );
                    },
                    ( error ) => {
                        console.log ( 'Error: ' + error );
                    }
                )
            }
        );

        // This is supposed to return an Observable to the caller
        return this.recipeSubscription;
    }
}

header.component.ts

// Dependencies here ...

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  constructor(private dataStorage: DataStorageService, private recipeService: RecipeService) { }

  // Other Code Here ...

  onFetchData() {
    let recipeSubscription = this.dataStorage.getRecipes();

    // THIS RETURNS TRUE
    console.log(recipeSubscription instanceof Observable);

    // THIS LINE THEN RETURNS THE MESSAGE:
    // ERROR TypeError: Cannot read property 'subscribe' of undefined
    recipeSubscription.subscribe();

    // IF I COMMENT OUT THE PREVIOUS LINE
    setTimeout(
      () => {
        // THIS RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      500
    );

    setTimeout(
      () => {
        // AS WELL THIS ONE RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      1000
    );

    setTimeout(
      () => {
        // AS WELL THIS ONE RETURNS TRUE
        console.log(recipeSubscription instanceof Observable);
      },
      1500
    );
  }
}

So, unfortunately, I cannot see what could be wrong with this code. Can anyone spot anything I did wrong?

Note: I have removed parts of my code just for make the snippets more readable. If you need any other part, please feel free to ask me, and I will provide it here.

UPDATE #1

This is how it looks like the header.component.html

Logo Here

                    Manage

                            Save Data

                            Fetch Data

ContentLicense: CC BY-SA 4.0


问:
SQL Retrieve data from first table based on search criteria in second table
i Have 2 tables i want to get data from the first table based on where condition applied on the second table.

```<code>PHARMASTOCK(1)      Pharma Products(2)
ID                  ProductID
ProductID           GenericName
TradeName           TradeName
MRP                 Supplier
Rate                Manufacturer
Stock               PurchasePTR
Batch               UnitRate
Expiry              MRP
StockSection
</code>```

This is the SQL stored procedure that i have written but it is not working
as expected!

```<code>@StockSupplier varchar(50), @StockManufacturer Varchar(50)
AS

SELECT  PharmaStock.ProductID,PharmaStock.TradeName,PharmaStock.MRP,Rate,Batch,Expiry,StockSection,Stock,Supplier,Manufacturer
from PharmaStock
    Full JOIN PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID
where Supplier  like + @StockSupplier + '%' and Manufacturer  like + @StockManufacturer + '%'
order by Manufacturer asc
</code>```

答:
```<code>    SELECT  PharmaStock.ProductID,
PharmaStock.TradeName,
PharmaStock.MRP,
PharmaStock.Rate,
PharmaStock.Batch,
PharmaStock.Expiry,
PharmaStock.StockSection,
PharmaProducts.Supplier,
PharmaProducts.Manufacturer
FROM PharmaStock
        INNER JOIN  PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID WHERE PharmaProducts.Supplier  LIKE  '%%' and PharmaProducts.Manufacturer  LIKE  '%%'
ORDER BY PharmaProducts.Manufacturer asc
</code>```

pass strings for supplier and Manufacturer to further filter join result.

Body:
i Have 2 tables i want to get data from the first table based on where condition applied on the second table.

PHARMASTOCK(1)      Pharma Products(2)
ID                  ProductID
ProductID           GenericName
TradeName           TradeName
MRP                 Supplier
Rate                Manufacturer
Stock               PurchasePTR
Batch               UnitRate
Expiry              MRP
StockSection

This is the SQL stored procedure that i have written but it is not working
as expected!

@StockSupplier varchar(50), @StockManufacturer Varchar(50)
AS

SELECT  PharmaStock.ProductID,PharmaStock.TradeName,PharmaStock.MRP,Rate,Batch,Expiry,StockSection,Stock,Supplier,Manufacturer
from PharmaStock
    Full JOIN PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID
where Supplier  like + @StockSupplier + '%' and Manufacturer  like + @StockManufacturer + '%'
order by Manufacturer asc

Body:
    SELECT  PharmaStock.ProductID,
PharmaStock.TradeName,
PharmaStock.MRP,
PharmaStock.Rate,
PharmaStock.Batch,
PharmaStock.Expiry,
PharmaStock.StockSection,
PharmaProducts.Supplier,
PharmaProducts.Manufacturer
FROM PharmaStock
        INNER JOIN  PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID WHERE PharmaProducts.Supplier  LIKE  '%%' and PharmaProducts.Manufacturer  LIKE  '%%'
ORDER BY PharmaProducts.Manufacturer asc

pass strings for supplier and Manufacturer to further filter join result.


问:
changing a key name in NSDictionary
I have a method which returns me a nsdictionary with certain keys and values. i need to change the key names from the dictionary to a new key name but the values need to be same for that key,but i am stuck here.need help</p>

答:
You can't change anything in an NSDictionary, since it is read only.

How about loop through the dictionary and create a new NSMutableDictionary with the new key names ?

Title: changing a key name in NSDictionary


问:
how to preserve attributes for ufunc and operator xarray operations?
Given

```<code>da = xr.DataArray([0], attrs={"foo": 42})
</code>```

I can calculate (for example) the sum while preserving coordinates using

```<code>da.sum(keep_attrs=True)
</code>```

however, how can I keep the attributes when applying a ufunc such as np.sin(da) or using operator overloading such as 1-da?  Of course, I can simply reassign the attributes at the end of my operations, but is there any way to preserve them in the first place?

答:
As of xarray 0.11 (released 2018-11-07), you can set</p>

```<code>xarray.set_options(keep_attrs=True)
</code>```

Body:
Given

da = xr.DataArray([0], attrs={"foo": 42})

I can calculate (for example) the sum while preserving coordinates using

da.sum(keep_attrs=True)

however, how can I keep the attributes when applying a ufunc such as np.sin(da) or using operator overloading such as 1-da?  Of course, I can simply reassign the attributes at the end of my operations, but is there any way to preserve them in the first place?

Body:
As of xarray 0.11 (released 2018-11-07), you can set

xarray.set_options(keep_attrs=True)


答:
Simply add a condition to the loop:

```<code>while (counter < Data_string.Length && Data_string[counter] !=  'x' )
{
       //some code
}
</code>```

Of course, you could use a for loop:

```<code>for(var i = 0; i < Data_string.Length && Data_string[i] != x; i++)
{
    // some code
}
</code>```

Title: How to get out of while loop at the end of String in c#

Body:
I have a String which is mentioned below i am extracting a 2D array from this string (which i am doing successfully) The problem is that I dont know how to exit the while loop.

00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000,
00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000,
00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000,
00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000,
00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,

I tried to put "x" at the end of string  and ran my while loop like this and it works but Its not feasible for me beacuase I have to read this string from like hundreds of files.

while (Data_string[counter] !=  'x' )
{
    while (Data_string[counter] != ',')
    {
        if (Data_string[counter] != '\n')
            SubString += Data_string[counter];

        counter++;
    }
    // here I use Substring to covert to int and then set Substring to empty string
}

So I am looking for an efficient solution so i dont have to alter the string,

Thanks..

Body:
Simply add a condition to the loop:

while (counter < Data_string.Length && Data_string[counter] !=  'x' )
{
       //some code
}

Of course, you could use a for loop:

for(var i = 0; i < Data_string.Length && Data_string[i] != x; i++)
{
    // some code
}


问:
getClass.getResource return null
when i run this line:

URL myurl = getClass().getResource("/bla.xml");
```

I got myurl is null

if I try to debug in runtime this value "getClass().getResource("/bla.xml")"
I got the right value.
it seems that something went wrong with placement.
what it can be?
using eclipse oxygen

答:
If maven directory structure is used you can put the XML file in the resources folder. If resources folder is not available in the maven directory structure , you can create a one.
The path of the resources folder are src/main/resources and src/test/resources. The XML file needs to be in the classpath. If you are running the jar, the XML file needs to be embedded in the jar file.</p>

Title: getClass.getResource return null

Body:
when i run this line:

URL myurl = getClass().getResource("/bla.xml");

I got myurl is null

if I try to debug in runtime this value "getClass().getResource("/bla.xml")"
I got the right value.
it seems that something went wrong with placement.
what it can be?
using eclipse oxygen


问:
Rewrite Mathematica output in Python
I want to convert the piecewise-function output of a calculation in Mathematica into Python. Taking inspiration from this page for the Mathematica->Python conversion and this page for writing piecewise functions, I have

```<code>from numpy import linspace, vectorize, array
from numpy import arctan, log
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import parse

def fun(x,a,b,c):
    # string inside parse('') is my mathematica output
    if a == 0:
        out = parse('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = parse('4 c a^2 Log[c^2 + (x - a)^2]')
    return out

a = 0.17
b = 0.44
c = 0.29
x = linspace(0,50,int(1e3))

vfun = vectorize(fun)
y = vfun(x,a,b,c)
yp = 4*c*a**2*log(c**2 + (x - a)**2)

plt.figure()
plt.plot(x,y,'.-')
plt.title('mathematica -> python conversion')

plt.figure()
plt.plot(x,yp,'.-')
plt.title('expected')

plt.show()
</code>```

The plot looks like:

whereas it should be:

Have I done something wrong when converting Mathematica to Python? Or is there a problem when assigning numerical values to a, b, and c? (Note that this is a MWE, and the Mathematica code that I want to convert is much longer and complicated than what is shown above.)

答:
A much easier solution is using eval. Now I know eval is very dangerous but most of the time when it takes input from user, but here the input is already defined for us.

Now onto the answer.

You are not getting the expected output because your vectorized array does not contain any floats but only contains output from mathematica's parser which return unevaluated string, so we can use .evalf() as answer given by @David, lambdify() which uses eval() internally or we can directly use eval().

Here is the documentation of the methods used : https://docs.sympy.org/latest/tutorial/basic_operations.html

```<code>from numpy import linspace, vectorize, array
from numpy import arctan, log
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import MathematicaParser

def fun(x,a,b,c):
    obj = MathematicaParser()
    if a == 0:
        out = obj.parse('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = obj.parse('4 c a^2 Log[c^2 + (x - a)^2]')

    return out

a = 0.17
b = 0.44
c = 0.29
x = linspace(0,50,int(1e3))
yp = 4*c*a**2*log(c**2 + (x - a)**2)
vfun = vectorize(fun)
y = vfun(x,a,b,c)
#Here y is a type <class 'numpy.ndarray'> containing 1000 <class 'numpy.str_'>
#['4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#'4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#'4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#'4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#....
y = eval(y[0]) #y[0] is '4*c*a**2*log(c**2+(x-a)**2)'
#When we evaluate y[0] we again get y as <class 'numpy.ndarray'> conatining 1000 <class 'numpy.float64'>
#Because x is <class 'numpy.ndarray'> it evaluates the first string over
#all the points in x.
#[-0.07309464 -0.07770262 -0.08110382 -0.0828403  -0.08263539 -0.08052339
#-0.07683235 -0.07203573 -0.06659307 -0.06086366 -0.05509179 -0.04942739
#-0.04395413 -0.03871304 -0.03371924 -0.0289728  -0.02446552 -0.02018495
#.....
plt.figure()
plt.plot(x, y,'.-')
plt.title('mathematica -> python conversion')

plt.figure()
plt.plot(x,yp,'.-')
plt.title('expected')

plt.show()
</code>```

Output :

Title: Rewrite Mathematica output in Python

Body:
I want to convert the piecewise-function output of a calculation in Mathematica into Python. Taking inspiration from this page for the Mathematica->Python conversion and this page for writing piecewise functions, I have

from numpy import linspace, vectorize, array
from numpy import arctan, log
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import parse

def fun(x,a,b,c):
    # string inside parse('') is my mathematica output
    if a == 0:
        out = parse('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = parse('4 c a^2 Log[c^2 + (x - a)^2]')
    return out

a = 0.17
b = 0.44
c = 0.29
x = linspace(0,50,int(1e3))

vfun = vectorize(fun)
y = vfun(x,a,b,c)
yp = 4*c*a**2*log(c**2 + (x - a)**2)

plt.figure()
plt.plot(x,y,'.-')
plt.title('mathematica -> python conversion')

plt.figure()
plt.plot(x,yp,'.-')
plt.title('expected')

plt.show()

The plot looks like:

whereas it should be:

Have I done something wrong when converting Mathematica to Python? Or is there a problem when assigning numerical values to a, b, and c? (Note that this is a MWE, and the Mathematica code that I want to convert is much longer and complicated than what is shown above.)

Body:
A much easier solution is using eval. Now I know eval is very dangerous but most of the time when it takes input from user, but here the input is already defined for us.

Now onto the answer.

You are not getting the expected output because your vectorized array does not contain any floats but only contains output from mathematica's parser which return unevaluated string, so we can use .evalf() as answer given by @David, lambdify() which uses eval() internally or we can directly use eval().

Here is the documentation of the methods used : https://docs.sympy.org/latest/tutorial/basic_operations.html

from numpy import linspace, vectorize, array
from numpy import arctan, log
import matplotlib.pyplot as plt
from sympy.parsing.mathematica import MathematicaParser

def fun(x,a,b,c):
    obj = MathematicaParser()
    if a == 0:
        out = obj.parse('a (-I b + x) ArcTan[(b - a)/c]')
    else:
        out = obj.parse('4 c a^2 Log[c^2 + (x - a)^2]')

    return out

a = 0.17
b = 0.44
c = 0.29
x = linspace(0,50,int(1e3))
yp = 4*c*a**2*log(c**2 + (x - a)**2)
vfun = vectorize(fun)
y = vfun(x,a,b,c)
#Here y is a type <class 'numpy.ndarray'> containing 1000 <class 'numpy.str_'>
#['4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#'4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#'4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#'4*c*a**2*log(c**2+(x-a)**2)' '4*c*a**2*log(c**2+(x-a)**2)'
#....
y = eval(y[0]) #y[0] is '4*c*a**2*log(c**2+(x-a)**2)'
#When we evaluate y[0] we again get y as <class 'numpy.ndarray'> conatining 1000 <class 'numpy.float64'>
#Because x is <class 'numpy.ndarray'> it evaluates the first string over
#all the points in x.
#[-0.07309464 -0.07770262 -0.08110382 -0.0828403  -0.08263539 -0.08052339
#-0.07683235 -0.07203573 -0.06659307 -0.06086366 -0.05509179 -0.04942739
#-0.04395413 -0.03871304 -0.03371924 -0.0289728  -0.02446552 -0.02018495
#.....
plt.figure()
plt.plot(x, y,'.-')
plt.title('mathematica -> python conversion')

plt.figure()
plt.plot(x,yp,'.-')
plt.title('expected')

plt.show()

Output :


问:
Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on in window form
I have 2 form in my window form application

frmDashboad and  frmCompany.

There is a button on frmDashboad form, and on click of that button I'm showing frmCompany as a Dialog.

This is my code.

```<code>private void btnCompany_Click(object sender, EventArgs e)
     {
       new frmCompany().ShowDialog();
     }
</code>```

My frmCompany form.

```<code>public partial class frmCompany : SfForm
    {
        public frmCompany()
        {
            InitializeComponent();
        }
    }
</code>```

Now When I close the frmCompany and again click on button to show frmCompany dialog again, if I repeat this process 5-6 times continiously then an exception is thrown.

```<code>'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'
</code>```

This is complete stack trace.

```<code>at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_InternalHandle()
at System.Windows.Forms.Control.DestroyHandle()
at System.Windows.Forms.Control.Dispose(Boolean disposing)
at System.Windows.Forms.Form.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at Syncfusion.Windows.Forms.SfToolTip.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at Syncfusion.WinForms.Controls.SfForm.Dispose(Boolean disposing)
at InventorySystem.UI.frmCompany.Dispose(Boolean disposing) in D:\Test\Code Sample\inventory-system\InventorySystem\InventorySystem.UI\frmCompany.Designer.cs:line 20
at System.ComponentModel.Component.Finalize()
</code>```

If I replace SfForm with Form then there is no exception occured.

答:
You just need to set following property false for Form or sfDatagrid.

ShowValidationErrorToolTip

Body:
I have 2 form in my window form application

frmDashboad and  frmCompany.

There is a button on frmDashboad form, and on click of that button I'm showing frmCompany as a Dialog.

This is my code.

private void btnCompany_Click(object sender, EventArgs e)
     {
       new frmCompany().ShowDialog();
     }

My frmCompany form.

public partial class frmCompany : SfForm
    {
        public frmCompany()
        {
            InitializeComponent();
        }
    }

Now When I close the frmCompany and again click on button to show frmCompany dialog again, if I repeat this process 5-6 times continiously then an exception is thrown.

'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'

This is complete stack trace.

at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.get_InternalHandle()
at System.Windows.Forms.Control.DestroyHandle()
at System.Windows.Forms.Control.Dispose(Boolean disposing)
at System.Windows.Forms.Form.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at Syncfusion.Windows.Forms.SfToolTip.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at Syncfusion.WinForms.Controls.SfForm.Dispose(Boolean disposing)
at InventorySystem.UI.frmCompany.Dispose(Boolean disposing) in D:\Test\Code Sample\inventory-system\InventorySystem\InventorySystem.UI\frmCompany.Designer.cs:line 20
at System.ComponentModel.Component.Finalize()

If I replace SfForm with Form then there is no exception occured.


问:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.?
i have a problem with My dataGridVew

i am trying to export data from my DB to excel fie

it's a small page where there are only data grid view and button to export like this :

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="SID" DataSourceID="SqlDataSource1" EnableModelValidation="True">
    <Columns>
        <asp:BoundField DataField="SID" HeaderText="SID" InsertVisible="False"
            ReadOnly="True" SortExpression="SID" />
        <asp:BoundField DataField="G1Q1" HeaderText="G1Q1" SortExpression="G1Q1" />
        <asp:BoundField DataField="G1Q2" HeaderText="G1Q2" SortExpression="G1Q2" />
        <asp:BoundField DataField="G1Q3" HeaderText="G1Q3" SortExpression="G1Q3" />
        <asp:BoundField DataField="G1Q4" HeaderText="G1Q4" SortExpression="G1Q4" />
        <asp:BoundField DataField="G1Q5" HeaderText="G1Q5" SortExpression="G1Q5" />
        <asp:BoundField DataField="G1Q6" HeaderText="G1Q6" SortExpression="G1Q6" />
        <asp:BoundField DataField="G1Q7" HeaderText="G1Q7" SortExpression="G1Q7" />
        <asp:BoundField DataField="G1Q8" HeaderText="G1Q8" SortExpression="G1Q8" />
        <asp:BoundField DataField="G1Q9" HeaderText="G1Q9" SortExpression="G1Q9" />
        <asp:BoundField DataField="G1Q10" HeaderText="G1Q10" SortExpression="G1Q10" />
        <asp:BoundField DataField="G1Q11" HeaderText="G1Q11" SortExpression="G1Q11" />
        <asp:BoundField DataField="G1Q12" HeaderText="G1Q12" SortExpression="G1Q12" />
        <asp:BoundField DataField="G1Q13" HeaderText="G1Q13" SortExpression="G1Q13" />
        <asp:BoundField DataField="G2Q1" HeaderText="G2Q1" SortExpression="G2Q1" />
        <asp:BoundField DataField="G2Q2" HeaderText="G2Q2" SortExpression="G2Q2" />
        <asp:BoundField DataField="G2Q3" HeaderText="G2Q3" SortExpression="G2Q3" />
        <asp:BoundField DataField="G2Q4" HeaderText="G2Q4" SortExpression="G2Q4" />
        <asp:BoundField DataField="G2Q5" HeaderText="G2Q5" SortExpression="G2Q5" />
        <asp:BoundField DataField="G2Q6" HeaderText="G2Q6" SortExpression="G2Q6" />
        <asp:BoundField DataField="G2Q7" HeaderText="G2Q7" SortExpression="G2Q7" />
        <asp:BoundField DataField="G2Q8" HeaderText="G2Q8" SortExpression="G2Q8" />
        <asp:BoundField DataField="G2Q9" HeaderText="G2Q9" SortExpression="G2Q9" />
        <asp:BoundField DataField="G2Q10" HeaderText="G2Q10" SortExpression="G2Q10" />
        <asp:BoundField DataField="G2Q11" HeaderText="G2Q11" SortExpression="G2Q11" />
        <asp:BoundField DataField="G3P1Q1" HeaderText="G3P1Q1"
            SortExpression="G3P1Q1" />
        <asp:BoundField DataField="G3P1Q2" HeaderText="G3P1Q2"
            SortExpression="G3P1Q2" />
        <asp:BoundField DataField="G3P1Q3" HeaderText="G3P1Q3"
            SortExpression="G3P1Q3" />
        <asp:BoundField DataField="G3P1Q4" HeaderText="G3P1Q4"
            SortExpression="G3P1Q4" />
        <asp:BoundField DataField="G3P1Q5" HeaderText="G3P1Q5"
            SortExpression="G3P1Q5" />
        <asp:BoundField DataField="G3P1Q6" HeaderText="G3P1Q6"
            SortExpression="G3P1Q6" />
        <asp:BoundField DataField="G3P1Q7" HeaderText="G3P1Q7"
            SortExpression="G3P1Q7" />
        <asp:BoundField DataField="G3P1Q8" HeaderText="G3P1Q8"
            SortExpression="G3P1Q8" />
        <asp:BoundField DataField="G3P1Q9" HeaderText="G3P1Q9"
            SortExpression="G3P1Q9" />
        <asp:BoundField DataField="G3P1Q10" HeaderText="G3P1Q10"
            SortExpression="G3P1Q10" />
        <asp:BoundField DataField="G3P2Q1" HeaderText="G3P2Q1"
            SortExpression="G3P2Q1" />
        <asp:BoundField DataField="G3P2Q2" HeaderText="G3P2Q2"
            SortExpression="G3P2Q2" />
        <asp:BoundField DataField="G3P2Q3" HeaderText="G3P2Q3"
            SortExpression="G3P2Q3" />
        <asp:BoundField DataField="G3P2Q4" HeaderText="G3P2Q4"
            SortExpression="G3P2Q4" />
        <asp:BoundField DataField="G3P2Q5" HeaderText="G3P2Q5"
            SortExpression="G3P2Q5" />
        <asp:BoundField DataField="G3P2Q6" HeaderText="G3P2Q6"
            SortExpression="G3P2Q6" />
        <asp:BoundField DataField="G3P2Q7" HeaderText="G3P2Q7"
            SortExpression="G3P2Q7" />
        <asp:BoundField DataField="G3P2Q8" HeaderText="G3P2Q8"
            SortExpression="G3P2Q8" />
        <asp:BoundField DataField="G3P2Q9" HeaderText="G3P2Q9"
            SortExpression="G3P2Q9" />
        <asp:BoundField DataField="G3P2Q10" HeaderText="G3P2Q10"
            SortExpression="G3P2Q10" />
        <asp:BoundField DataField="G3P2Q11" HeaderText="G3P2Q11"
            SortExpression="G3P2Q11" />
        <asp:BoundField DataField="G3P3Q1" HeaderText="G3P3Q1"
            SortExpression="G3P3Q1" />
        <asp:BoundField DataField="G3P3Q2" HeaderText="G3P3Q2"
            SortExpression="G3P3Q2" />
        <asp:BoundField DataField="G3P3Q3" HeaderText="G3P3Q3"
            SortExpression="G3P3Q3" />
        <asp:BoundField DataField="G3P3Q4" HeaderText="G3P3Q4"
            SortExpression="G3P3Q4" />
        <asp:BoundField DataField="G3P3Q5" HeaderText="G3P3Q5"
            SortExpression="G3P3Q5" />
        <asp:BoundField DataField="G3P3Q6" HeaderText="G3P3Q6"
            SortExpression="G3P3Q6" />
        <asp:BoundField DataField="G3P3Q7" HeaderText="G3P3Q7"
            SortExpression="G3P3Q7" />
        <asp:BoundField DataField="G3P3Q8" HeaderText="G3P3Q8"
            SortExpression="G3P3Q8" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
       ConnectionString="<%$ ConnectionStrings:HaronSurveyConnectionString %>"SelectCommand="SELECT * FROM [Results]"></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</code>```

```<code>Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "application/vnd.ms-excel"
    Response.Charset = ""

    Me.EnableViewState = False
    Dim oStringWriter As New System.IO.StringWriter()

    Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)

    'render html content to textwriter
    GridView1.RenderControl(oHtmlTextWriter)
    Response.Write(oStringWriter.ToString())
    Response.[End]()

End Sub
</code>```

when i click on the button error message is coming : "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.???" even i have placed it in form ???

答:
```<code> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim ad As New results()
    Dim dt As results.ResultsDataTable
    dt = ad.Read()

    Dim attachment As String = "attachment; filename=USurvey.xls"
    Response.ClearContent()
    Response.AddHeader("content-disposition", attachment)
    Response.ContentType = "application/vnd.ms-excel"
    Dim tab As String = ""
    For Each dc As DataColumn In dt.Columns
        Response.Write(tab + dc.ColumnName)
        tab = vbTab
    Next
    Response.Write(vbLf)

    Dim i As Integer
    For Each dr As DataRow In dt.Rows
        tab = ""
        For i = 0 To dt.Columns.Count - 1
            Response.Write(tab & dr(i).ToString())
            tab = vbTab
        Next
        Response.Write(vbLf)
    Next
    Response.[End]()
    'export to excel
End Sub
</code>```

Body:
i have a problem with My dataGridVew

i am trying to export data from my DB to excel fie

it's a small page where there are only data grid view and button to export like this :

<title></title>

<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    DataKeyNames="SID" DataSourceID="SqlDataSource1" EnableModelValidation="True">
    <Columns>
        <asp:BoundField DataField="SID" HeaderText="SID" InsertVisible="False"
            ReadOnly="True" SortExpression="SID" />
        <asp:BoundField DataField="G1Q1" HeaderText="G1Q1" SortExpression="G1Q1" />
        <asp:BoundField DataField="G1Q2" HeaderText="G1Q2" SortExpression="G1Q2" />
        <asp:BoundField DataField="G1Q3" HeaderText="G1Q3" SortExpression="G1Q3" />
        <asp:BoundField DataField="G1Q4" HeaderText="G1Q4" SortExpression="G1Q4" />
        <asp:BoundField DataField="G1Q5" HeaderText="G1Q5" SortExpression="G1Q5" />
        <asp:BoundField DataField="G1Q6" HeaderText="G1Q6" SortExpression="G1Q6" />
        <asp:BoundField DataField="G1Q7" HeaderText="G1Q7" SortExpression="G1Q7" />
        <asp:BoundField DataField="G1Q8" HeaderText="G1Q8" SortExpression="G1Q8" />
        <asp:BoundField DataField="G1Q9" HeaderText="G1Q9" SortExpression="G1Q9" />
        <asp:BoundField DataField="G1Q10" HeaderText="G1Q10" SortExpression="G1Q10" />
        <asp:BoundField DataField="G1Q11" HeaderText="G1Q11" SortExpression="G1Q11" />
        <asp:BoundField DataField="G1Q12" HeaderText="G1Q12" SortExpression="G1Q12" />
        <asp:BoundField DataField="G1Q13" HeaderText="G1Q13" SortExpression="G1Q13" />
        <asp:BoundField DataField="G2Q1" HeaderText="G2Q1" SortExpression="G2Q1" />
        <asp:BoundField DataField="G2Q2" HeaderText="G2Q2" SortExpression="G2Q2" />
        <asp:BoundField DataField="G2Q3" HeaderText="G2Q3" SortExpression="G2Q3" />
        <asp:BoundField DataField="G2Q4" HeaderText="G2Q4" SortExpression="G2Q4" />
        <asp:BoundField DataField="G2Q5" HeaderText="G2Q5" SortExpression="G2Q5" />
        <asp:BoundField DataField="G2Q6" HeaderText="G2Q6" SortExpression="G2Q6" />
        <asp:BoundField DataField="G2Q7" HeaderText="G2Q7" SortExpression="G2Q7" />
        <asp:BoundField DataField="G2Q8" HeaderText="G2Q8" SortExpression="G2Q8" />
        <asp:BoundField DataField="G2Q9" HeaderText="G2Q9" SortExpression="G2Q9" />
        <asp:BoundField DataField="G2Q10" HeaderText="G2Q10" SortExpression="G2Q10" />
        <asp:BoundField DataField="G2Q11" HeaderText="G2Q11" SortExpression="G2Q11" />
        <asp:BoundField DataField="G3P1Q1" HeaderText="G3P1Q1"
            SortExpression="G3P1Q1" />
        <asp:BoundField DataField="G3P1Q2" HeaderText="G3P1Q2"
            SortExpression="G3P1Q2" />
        <asp:BoundField DataField="G3P1Q3" HeaderText="G3P1Q3"
            SortExpression="G3P1Q3" />
        <asp:BoundField DataField="G3P1Q4" HeaderText="G3P1Q4"
            SortExpression="G3P1Q4" />
        <asp:BoundField DataField="G3P1Q5" HeaderText="G3P1Q5"
            SortExpression="G3P1Q5" />
        <asp:BoundField DataField="G3P1Q6" HeaderText="G3P1Q6"
            SortExpression="G3P1Q6" />
        <asp:BoundField DataField="G3P1Q7" HeaderText="G3P1Q7"
            SortExpression="G3P1Q7" />
        <asp:BoundField DataField="G3P1Q8" HeaderText="G3P1Q8"
            SortExpression="G3P1Q8" />
        <asp:BoundField DataField="G3P1Q9" HeaderText="G3P1Q9"
            SortExpression="G3P1Q9" />
        <asp:BoundField DataField="G3P1Q10" HeaderText="G3P1Q10"
            SortExpression="G3P1Q10" />
        <asp:BoundField DataField="G3P2Q1" HeaderText="G3P2Q1"
            SortExpression="G3P2Q1" />
        <asp:BoundField DataField="G3P2Q2" HeaderText="G3P2Q2"
            SortExpression="G3P2Q2" />
        <asp:BoundField DataField="G3P2Q3" HeaderText="G3P2Q3"
            SortExpression="G3P2Q3" />
        <asp:BoundField DataField="G3P2Q4" HeaderText="G3P2Q4"
            SortExpression="G3P2Q4" />
        <asp:BoundField DataField="G3P2Q5" HeaderText="G3P2Q5"
            SortExpression="G3P2Q5" />
        <asp:BoundField DataField="G3P2Q6" HeaderText="G3P2Q6"
            SortExpression="G3P2Q6" />
        <asp:BoundField DataField="G3P2Q7" HeaderText="G3P2Q7"
            SortExpression="G3P2Q7" />
        <asp:BoundField DataField="G3P2Q8" HeaderText="G3P2Q8"
            SortExpression="G3P2Q8" />
        <asp:BoundField DataField="G3P2Q9" HeaderText="G3P2Q9"
            SortExpression="G3P2Q9" />
        <asp:BoundField DataField="G3P2Q10" HeaderText="G3P2Q10"
            SortExpression="G3P2Q10" />
        <asp:BoundField DataField="G3P2Q11" HeaderText="G3P2Q11"
            SortExpression="G3P2Q11" />
        <asp:BoundField DataField="G3P3Q1" HeaderText="G3P3Q1"
            SortExpression="G3P3Q1" />
        <asp:BoundField DataField="G3P3Q2" HeaderText="G3P3Q2"
            SortExpression="G3P3Q2" />
        <asp:BoundField DataField="G3P3Q3" HeaderText="G3P3Q3"
            SortExpression="G3P3Q3" />
        <asp:BoundField DataField="G3P3Q4" HeaderText="G3P3Q4"
            SortExpression="G3P3Q4" />
        <asp:BoundField DataField="G3P3Q5" HeaderText="G3P3Q5"
            SortExpression="G3P3Q5" />
        <asp:BoundField DataField="G3P3Q6" HeaderText="G3P3Q6"
            SortExpression="G3P3Q6" />
        <asp:BoundField DataField="G3P3Q7" HeaderText="G3P3Q7"
            SortExpression="G3P3Q7" />
        <asp:BoundField DataField="G3P3Q8" HeaderText="G3P3Q8"
            SortExpression="G3P3Q8" />
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
       ConnectionString="<%$ ConnectionStrings:HaronSurveyConnectionString %>"SelectCommand="SELECT * FROM [Results]"></asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "application/vnd.ms-excel"
    Response.Charset = ""

    Me.EnableViewState = False
    Dim oStringWriter As New System.IO.StringWriter()

    Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)

    'render html content to textwriter
    GridView1.RenderControl(oHtmlTextWriter)
    Response.Write(oStringWriter.ToString())
    Response.[End]()

End Sub

when i click on the button error message is coming : "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.???" even i have placed it in form ???


问:
read csv with escape characters
I have a csv file with some text, among others. I want to tokenize (split into a list of words) this text and am having problems with how pd.read_csv interprets escape characters.

My csv file looks like this:

```<code>text, number
one line\nother line, 12
</code>```

and the code is like follows:

```<code>df = pd.read_csv('test.csv')
word_tokenize(df.iloc[0,0])
</code>```

output is:

```<code>['one', 'line\\nother', 'line']
</code>```

while what I want is:

```<code>['one', 'line', 'other', 'line']
</code>```

The problem is pd.read_csv() is not interpreting the \n as a newline character but as two characters (\ and n).

I've tried setting the escapechar argument to '\' and to '\\' but both just remove the slash from the string without doing any interpretation of a newline character, i.e. the string becomes on one linenon other line.

If I explicitly set df.iloc[0,0] = 'one line\nother line', word_tokenize works just fine, because \n is actually interpreted as a newline character this time.

Ideally I would do this simply changing the way pd.read_csv() interprets the file, but other solutions are also ok.

答:
In you case simply use:</p>

```<code>data = pd.read_csv('test.csv', sep='\\,', names=['c1', 'c2', 'c3', 'c4'], engine='python')
</code>```

Title: read csv with escape characters

Body:
I have a csv file with some text, among others. I want to tokenize (split into a list of words) this text and am having problems with how pd.read_csv interprets escape characters.

My csv file looks like this:

text, number
one line\nother line, 12

and the code is like follows:

df = pd.read_csv('test.csv')
word_tokenize(df.iloc[0,0])

output is:

['one', 'line\\nother', 'line']

while what I want is:

['one', 'line', 'other', 'line']

The problem is pd.read_csv() is not interpreting the \n as a newline character but as two characters (\ and n).

I've tried setting the escapechar argument to '\' and to '\\' but both just remove the slash from the string without doing any interpretation of a newline character, i.e. the string becomes on one linenon other line.

If I explicitly set df.iloc[0,0] = 'one line\nother line', word_tokenize works just fine, because \n is actually interpreted as a newline character this time.

Ideally I would do this simply changing the way pd.read_csv() interprets the file, but other solutions are also ok.

Body:
In you case simply use:

data = pd.read_csv('test.csv', sep='\\,', names=['c1', 'c2', 'c3', 'c4'], engine='python')


问:
Teamcity + Octopus and umbraco packages
Currently we are deploying our Umbraco site with teamcity and octopus deploy, having uSync installed to synchronize datatypes, document types etc. between enviroments.

Now im facing our first problem with our CI setup: How do i automatically install/uninstall any installed umbraco packages? If i install a package through the Umbraco interface, locally, and then deploy to our test environment, then i get an error until i install the package manually. This I have to do every time I deploy.

What is the correct way of managing/synchronizing packages between environments when using CI?

答:
The solution to this issue is to either:

1. Install all packages via Nuget

If you install all packages via. Nuget, then teamcity will take care of everything for you when building the solution.

2. Reference the package .dll

If the package is not available as a Nuget package, then download if via Umbraco, find the .dll and move it to another folder in your solution and reference the .dll from there instead.

Title: Teamcity + Octopus and umbraco packages


答: Have ever tried foreach? It will dynamically loop your collection based on its size as long as it is inheritting the IEnumerable interface.


问:
Change CodePage in CMD permanently?
My Windows cmd CodePage is now under 65001.
Since I was doing some Android stuff and need to use console log, but forget how changing it now.

When using chcp 437 to change the CodePage back, it works. But if I start a new cmd window, it goes back.

How to do the chcp thing to make it pernament?

答:
Setting the default CMD/shell Codepage can be neatly done using the following command:

```<code>REG ADD HKCU\Console\%SystemRoot^%_system32_cmd.exe /v CodePage /t REG_DWORD /d 437
</code>```

This will make the codepage 437 your default, but ONLY in the cmd/shell, meaning the rest of the OS is safe and the boot environment ist untouched.
Instead of always changing the codepage whenever the cmd opens, the cmd will open in the specified codepage from start.

If you wish to edit it manually using regedit.exe, beware that you have to set the codepage value in 'decimal' (use the radio-buttons for selecting decimal or hex input).

Title: Change CodePage in CMD permanently?

Body:
Setting the default CMD/shell Codepage can be neatly done using the following command:

REG ADD HKCU\Console\%SystemRoot^%_system32_cmd.exe /v CodePage /t REG_DWORD /d 437

This will make the codepage 437 your default, but ONLY in the cmd/shell, meaning the rest of the OS is safe and the boot environment ist untouched.
Instead of always changing the codepage whenever the cmd opens, the cmd will open in the specified codepage from start.

If you wish to edit it manually using regedit.exe, beware that you have to set the codepage value in 'decimal' (use the radio-buttons for selecting decimal or hex input).


问:
How can I plus file's info?
I'm making a new game and I wanna make a coins collector to, later, buy things with those coins. I'm using eclipse.

```<code>    void save() {
    try {
        PrintWriter out = new PrintWriter("coins.txt");
        out.write(Integer.toString(nmonedas));
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

void load() {
     StringBuffer texto=new StringBuffer();
     try {
     int c;
     @SuppressWarnings("resource")
    FileReader entrada=new FileReader("coins.txt");
     while((c=entrada.read())!=-1){
     texto.append((char)c);
      }
     }
     catch (IOException ex) {}
     labelshow.setText(texto.toString());

}
</code>```

I have this code but i cant plus the info. NEED HELP PLS

Well, the thing is, I'm doing a game in eclipse and I want you to collect coins and keep them in a file.
They are collected perfectly and stored in the file, but when I start the game again I want them to be collected but they add up with the previous ones

答:
I assume you are referring to appending text to a .TXT file. If so, you can use something like this:

```<code>Files.write(Paths.get("Path to text file here"), "Content".getBytes(), StandardOpenOption.APPEND);
</code>```

I would put the above in a TRY CATCH block.  Also look into PrintWriter as this may be more appopriate to what you need it for as it allows you to continuously write to the file.

Title: How can I plus file's info?

Body:
I'm making a new game and I wanna make a coins collector to, later, buy things with those coins. I'm using eclipse.

    void save() {
    try {
        PrintWriter out = new PrintWriter("coins.txt");
        out.write(Integer.toString(nmonedas));
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

void load() {
     StringBuffer texto=new StringBuffer();
     try {
     int c;
     @SuppressWarnings("resource")
    FileReader entrada=new FileReader("coins.txt");
     while((c=entrada.read())!=-1){
     texto.append((char)c);
      }
     }
     catch (IOException ex) {}
     labelshow.setText(texto.toString());

}

I have this code but i cant plus the info. NEED HELP PLS

Well, the thing is, I'm doing a game in eclipse and I want you to collect coins and keep them in a file.
They are collected perfectly and stored in the file, but when I start the game again I want them to be collected but they add up with the previous ones

Body:
I assume you are referring to appending text to a .TXT file. If so, you can use something like this:

Files.write(Paths.get("Path to text file here"), "Content".getBytes(), StandardOpenOption.APPEND);

I would put the above in a TRY CATCH block.  Also look into PrintWriter as this may be more appopriate to what you need it for as it allows you to continuously write to the file.


问:
Use @RequestBody with optional body in latest Spring v4
How do I make body optional in REST API calls when using @RequestBody annotation in Spring?

With Spring's latest version, if you use @RequestBody annotation, it makes client to send body all the time without making it optional.

I tried @RequestBody (required=false) but that didn't work & still my request comes as null.

How do I manage to get request converted to proper required object without making body mandatory?

For eg:

```<code>@RequestMapping(value="/add/employee", method=RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
    // ...
}
</code>```

Here, I want to add employee using POST but without body. How do I do that? Spring latest version throws error "body missing" if I send empty body...

答:
You can use java.util.Optional:

```<code>@RequestMapping(value="/add/employee", method=RequestMethod.POST)
public void addEmployee(@RequestBody Optional<Employee> employee){
    // ...
}
</code>```

Body:
How do I make body optional in REST API calls when using @RequestBody annotation in Spring?

With Spring's latest version, if you use @RequestBody annotation, it makes client to send body all the time without making it optional.

I tried @RequestBody (required=false) but that didn't work & still my request comes as null.

How do I manage to get request converted to proper required object without making body mandatory?

For eg:

@RequestMapping(value="/add/employee", method=RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
    // ...
}

Here, I want to add employee using POST but without body. How do I do that? Spring latest version throws error "body missing" if I send empty body...

Body:
You can use java.util.Optional:

@RequestMapping(value="/add/employee", method=RequestMethod.POST)
public void addEmployee(@RequestBody Optional<Employee> employee){
    // ...
}


问:
Retrieve all items from DynamoDB using query?
I am trying to retrieve all items in a dynamodb table using a query. Below is my code:

```<code>import boto.dynamodb2
from boto.dynamodb2.table import Table
from time import sleep

c    = boto.dynamodb2.connect_to_region(aws_access_key_id="XXX",aws_secret_access_key="XXX",region_name="us-west-2")

tab  = Table("rip.irc",connection=c)

x    = tab.query()

for i in x:
    print i
    sleep(1)
</code>```

However, I recieve the following error:

```<code>ValidationException: ValidationException: 400 Bad Request
{'message': 'Conditions can be of length 1 or 2 only', '__type': 'com.amazon.coral.validate#ValidationException'}
</code>```

The code I have is pretty straightforward and out of the boto dynamodb2 docs, so I am not sure why I am getting the above error. Any insights would be appreciated (new to this and a bit lost). Thanks

EDIT: I have both an hash key and a range key. I am able to query by specific hash keys. For example,

```<code>x = tab.query(hash__eq="2014-01-20 05:06:29")
</code>```

How can I retrieve all items though?

答:
I ran into this error when I was misusing KeyConditionExpression instead of FilterExpression when querying a dynamodb table.

KeyConditionExpression should only be used with partition key or sort key values.
FilterExpression should be used when you want filter your results even more.

However do note, using FilterExpression uses the same reads as it would without, because it performs the query based on the keyConditionExpression. It then removes items from the results based on your FilterExpression.

Source
Working with Queries

Body:
I am trying to retrieve all items in a dynamodb table using a query. Below is my code:

import boto.dynamodb2
from boto.dynamodb2.table import Table
from time import sleep

c    = boto.dynamodb2.connect_to_region(aws_access_key_id="XXX",aws_secret_access_key="XXX",region_name="us-west-2")

tab  = Table("rip.irc",connection=c)

x    = tab.query()

for i in x:
    print i
    sleep(1)

However, I recieve the following error:

ValidationException: ValidationException: 400 Bad Request
{'message': 'Conditions can be of length 1 or 2 only', '__type': 'com.amazon.coral.validate#ValidationException'}

The code I have is pretty straightforward and out of the boto dynamodb2 docs, so I am not sure why I am getting the above error. Any insights would be appreciated (new to this and a bit lost). Thanks

EDIT: I have both an hash key and a range key. I am able to query by specific hash keys. For example,

x = tab.query(hash__eq="2014-01-20 05:06:29")

How can I retrieve all items though?


问:
How can I load data that comes from a query from the database to get all tags into selectize?
So these past days I've been trying to load data into the selectize.js input, which I've tried many ways and it does not work.

I tried the tags[{}]; way but in only works with strings inside.

```<code>Example: tags = [
            {text: "science"},
            {text: "biology"},
            {text: "chemistry"},
            {text: "physics"}
         ];
</code>```

```<code>
    <!------ Hidden Input with the tags queried from the database ------>

    <?php

        $alltags="";

        foreach ($tags as $tag ) {

            $alltags.=$tag['name'].".";

        }

    ?>

    <input type="text" style="display:none" value="<?php echo $alltags; ?>" id="hiddeninput_tags">

    <!----------------------------------------------------------------->

</code>```

```<code>
    <!------ JavaScript Function ------>

    function sendtags()
    {

        var rawtags = $('#hiddeninput_tags').val();
        var res = rawtags.split(".");

        res.forEach(function(entry) {

            //alert(tags); If I remove this from comment, when I load the page it will alert all the tags inside the hidden input.

        });

    }

    <!--------------------------------->

</code>```

```<code>
    <!------ Selectize Function ------>

    $('#input-tags').selectize({

        plugins: ['restore_on_backspace', 'remove_button'],
        delimiter: ',',
        persist: false,
        options: tags,
        valueField: 'text',
        create: function(input) {
            return {
                value: input,
                text: input
            }
        },
        render: {

            option_create: function(data, escape) {

                var addString = 'Adicionar';

                return '<div class="create">' + addString + ' <strong>' + escape(data.input) + '</strong>…</div>';

            }

        }

    });

    <!-------------------------------->

</code>```

I expect the input from selectize to have all the values queried from the database inserted into the value of that "selectize input" so it can suggest the tags that already exist in the database.

答:
Hi @NeonSilver instead of using "" in your string use '' single quotes to make your input value.

Your provide code is displaying like -

```<code><input type="text" style="display:block" value="[{text: " science"},{text:="" "biology"},{text:="" "chemistry"},{text:="" "physics"}]" id="hiddeninput_tags">
</code>```

but it should be like this -

```<code><input type="text" style="display:block" value='[{text: " science"},{text:="" "biology"},{text:="" "chemistry"},{text:="" "physics"}]' id="hiddeninput_tags">
</code>```

now you can easily get the tag value.

Body:
So these past days I've been trying to load data into the selectize.js input, which I've tried many ways and it does not work.

I tried the tags[{}]; way but in only works with strings inside.

Example: tags = [
            {text: "science"},
            {text: "biology"},
            {text: "chemistry"},
            {text: "physics"}
         ];

    <?php

        $alltags="";

        foreach ($tags as $tag ) {

            $alltags.=$tag['name'].".";

        }

    ?>

    <input type="text" style="display:none" value="<?php echo $alltags; ?>" id="hiddeninput_tags">

    function sendtags()
    {

        var rawtags = $('#hiddeninput_tags').val();
        var res = rawtags.split(".");

        res.forEach(function(entry) {

            //alert(tags); If I remove this from comment, when I load the page it will alert all the tags inside the hidden input.

        });

    }

    $('#input-tags').selectize({

        plugins: ['restore_on_backspace', 'remove_button'],
        delimiter: ',',
        persist: false,
        options: tags,
        valueField: 'text',
        create: function(input) {
            return {
                value: input,
                text: input
            }
        },
        render: {

            option_create: function(data, escape) {

                var addString = 'Adicionar';

                return '
' + addString + ' ' + escape(data.input) + '…
';

            }

        }

    });

I expect the input from selectize to have all the values queried from the database inserted into the value of that "selectize input" so it can suggest the tags that already exist in the database.

Body:
Hi @NeonSilver instead of using "" in your string use '' single quotes to make your input value.

Your provide code is displaying like -

<input type="text" style="display:block" value="[{text: " science"},{text:="" "biology"},{text:="" "chemistry"},{text:="" "physics"}]" id="hiddeninput_tags">

but it should be like this -

<input type="text" style="display:block" value='[{text: " science"},{text:="" "biology"},{text:="" "chemistry"},{text:="" "physics"}]' id="hiddeninput_tags">

now you can easily get the tag value.


问:
Using refs with react-redux 6.0.0 and decorators
I have the following component:

export default
@connect(null, dispatch => ({ dispatch }))
class MyComponent extends React.PureComponent {

}
```

<p>And I have a component wrapping it:</p>

<pre class="lang-js prettyprint-override"><code>export default class MyWrapper extends React.PureComponent {
  comp = React.createRef();

  render() {
    return <MyComponent ref={this.comp}/>
  }
}
</code>```

How do I access MyComponent using refs?

I tried {withRef: true}, then tried {forwardRef: true} and got all sorts of errors.

答: The problem is with "react-redux": "7.0.0". The connect function has been implemented as a functional react component, so @decorators is not working anymore.

Body:
I have the following component:

export default
@connect(null, dispatch => ({ dispatch }))
class MyComponent extends React.PureComponent {

}

And I have a component wrapping it:

export default class MyWrapper extends React.PureComponent {
  comp = React.createRef();

  render() {
    return <MyComponent ref={this.comp}/>
  }
}

How do I access MyComponent using refs?

I tried {withRef: true}, then tried {forwardRef: true} and got all sorts of errors.


问:
Storing generated files in Git
We have a reasonably large, and far too messy code base that we wish to migrate to using Git. At the moment, it's a big monolithic chunk that can't easily be split into smaller independent components. The code builds a large number of shared libraries, but their source code is so interleaved that it can't be cleanly separated into separate repositories at the moment.

I'm not too concerned with whether Git can cope with having all the code in a single repository, but a problem is that we need to version both the source code and many of the libraries built from it. Building everything from scratch takes hours, so when checking out the code, developers should also get precompiled versions of these libraries to save time.

And this is where I could use some advice. The libraries don't need to be 100% up to date (as they generally maintain binary compatibility, and can always be rebuilt by the individual developer if necessary), so I'm looking for ways to to avoid cluttering up our source code repository with countless marginally different versions of binary files which can be regenerated from the source anyway, while still making the libraries easily accessible to developers so they don't have to rebuild everything from scratch.

So I'd like some way to achieve something like the following.

the libraries are generated by our build server on a regular basis, which could then commit them to the Git repository. The developers should then treat these files as read-only (pull the latest version, and when necessary, rebuild in place, but don't commit new versions), and ideally, Git should enforce this. (In particular, a developer running a quick git commit -a shouldn't end up accidentally polluting the repository with a new revision of all these generated files)

keep these files in a separate repository, so the source code won't have to carry around all these generated binary files perpetually (since they're a convenience to cut down on compilation time, but they're not actually necessary).

Of course, at the same time, the process of using these should be as smooth as possible. When checking out the source, the libraries built from it should follow (or at least, be easy to get). And when committing, it shouldn't be possible to accidentally commit new versions of these libraries, just because they were recompiled and now have a different timestamp embedded.

I've been looking at the option of using git's submodules, creating the "super" repository containing the source code, and then one or more submodules for the generated libraries, but so far, it seems a bit too clumsy and fragile for my taste. It seems that they don't actually prevent the developer from committing changes directly to the submodule, it just causes things to break further down the line (while playing around with submodules, I've ended up with more detached HEADs than I care to count).

Considering virtually all our developers are new to Git, that may end up wasting more time than it saves us.

So what are our options? Does the submodule approach sound sensible to you Git gurus out there? And how do I "tame" it, so it's as easy to use (and hard to mess up) as possible for our developers?

Or is there an entirely different solution we haven't considered?

I should mention that I've only used Git for a couple of days, so I'm pretty much a newbie myself.

答:
I would keep these in a separate repository to the source files. You can use 'git submodules' to keep a reference between the two; so the 'compiled libs' becomes the parent and the source becomes the submodule. That way, when you commit the libs you commit a reference to the exact point of the source code at the time.

Further, since developers don't need the full history, you can use git clone --depth 1 libs.git which gives you only the latest version of the libs. It doesn't pull further history, and doesn't allow you to commit (which is OK since the server should be doing that for you) and you'll give them access to the latest versions (or whatever branch you specify on the clone command with -b).

Ideally you don't want the main git repository containing, or pointing to, the binary repository.

Title: Storing generated files in Git


问:
RabbitMQ Java API queuePurge() method called on Qpid returns PurgeOK response with zero message count
I am integration testing a component that uses RabbitMQ client (amqp-client version 5.7.0) with an embedded Apache Qpid server object.

When calling the Channel.queuePurge() method, the queue is purged. I can verify that with the getMessageCount() method. But the queuePurge() method returns a PurgeOk object, which always has 0 message count. The documentation says the PurgeOK returns the message count that was purged.

```<code>   //The queue has 1 message.
   int f = getMessageCount();
   //verify message count
   assertEquals(f, 1);
   //purge
   com.rabbitmq.client.AMQP.Queue.PurgeOk purgeOK= channel.queuePurge(queueName);
   //the next test fails.
   //Shouldn't the purgeOK have count 1, to denote that one message was purged?
   assertEquals(purgeOK.getMessageCount(), 1);
</code>```

This happens only when testing with embedded Qpid server. The same test case with an actual running instance of Rabbit MQ is giving the expected.

Is this a known issue? Is there a better way to unit test the purge feature?

答: It wasn't a known issue, I have raised an issue for this defect in Qpid Broker-J.  Thank you for your help in discovering this.

Body:
I am integration testing a component that uses RabbitMQ client (amqp-client version 5.7.0) with an embedded Apache Qpid server object.

When calling the Channel.queuePurge() method, the queue is purged. I can verify that with the getMessageCount() method. But the queuePurge() method returns a PurgeOk object, which always has 0 message count. The documentation says the PurgeOK returns the message count that was purged.

   //The queue has 1 message.
   int f = getMessageCount();
   //verify message count
   assertEquals(f, 1);
   //purge
   com.rabbitmq.client.AMQP.Queue.PurgeOk purgeOK= channel.queuePurge(queueName);
   //the next test fails.
   //Shouldn't the purgeOK have count 1, to denote that one message was purged?
   assertEquals(purgeOK.getMessageCount(), 1);

This happens only when testing with embedded Qpid server. The same test case with an actual running instance of Rabbit MQ is giving the expected.

Is this a known issue? Is there a better way to unit test the purge feature?


问:
How to unit-test a AWS Lambda use lambda-local with mocha?
Background

I am working on a project that is build with Serverless framework with  serverless-appsync-plugin. I implemented a single endpoint(AWS Lambda) to handle all the requests generate from Appsync through graphQL. The endpoint will route the request to the corresponding function to perform the operation.

Problem

Now that I have developed around 10+ operations, I want to automate the process of unit-testing. For simplicity, I decided to run that single endpoint as a lambda locally for all the testing (against running appsync-offline).

So, I used lambda-local with mocha. However, I am not able to get a test-case to fail, based on the response I got from the lambda.

```<code>it('db should have a user of uId: 123',  async function () {
  lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath,
    callback: function(err, data) {
      if(err) {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
      } else {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here too
      }
    }
  });
  console.log(3)
})
</code>```

In both of the situation I want it to fail, it is not failing the test cases for either callback('failed', null) or callback(null, 'success').

So, what is the right way to make the lambda-local to fail a test case?

答:
In your code the test finishes without mocha registering that the assertions in lambdaLocal.execute failed. So it will always pass.

Instead of using the callback parameter you could return a promise, or await the lambdalocal.execute and then do your assertions.

For example (using Promises):

```<code>it('db should have a user of uId: 123',  function () {
  return lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath })
 .then(
    (data) => {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here
    },
    (err) => {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
    })
}
</code>```

Alternatively change signature of the function that is passed to it to take an additional parameter (usually called done) which will then be used by mocha to pass a function that can be used to signalise that the test finished. See the mocha documentation for more info.

Body:
Background

I am working on a project that is build with Serverless framework with  serverless-appsync-plugin. I implemented a single endpoint(AWS Lambda) to handle all the requests generate from Appsync through graphQL. The endpoint will route the request to the corresponding function to perform the operation.

Problem

Now that I have developed around 10+ operations, I want to automate the process of unit-testing. For simplicity, I decided to run that single endpoint as a lambda locally for all the testing (against running appsync-offline).

So, I used lambda-local with mocha. However, I am not able to get a test-case to fail, based on the response I got from the lambda.

it('db should have a user of uId: 123',  async function () {
  lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath,
    callback: function(err, data) {
      if(err) {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
      } else {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here too
      }
    }
  });
  console.log(3)
})

In both of the situation I want it to fail, it is not failing the test cases for either callback('failed', null) or callback(null, 'success').

So, what is the right way to make the lambda-local to fail a test case?

Body:
In your code the test finishes without mocha registering that the assertions in lambdaLocal.execute failed. So it will always pass.

Instead of using the callback parameter you could return a promise, or await the lambdalocal.execute and then do your assertions.

For example (using Promises):

it('db should have a user of uId: 123',  function () {
  return lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath })
 .then(
    (data) => {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here
    },
    (err) => {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
    })
}

Alternatively change signature of the function that is passed to it to take an additional parameter (usually called done) which will then be used by mocha to pass a function that can be used to signalise that the test finished. See the mocha documentation for more info.


问:
How to delete duplicate from this result
How to delete duplicate from this result

```<code>select *,
       row_number() over (order by (select null)) as seqnum
from [elo].[dbo].[objkeys]
where parentid in (select parentid
                   from [elo].[dbo].[objekte]
                   inner join [elo].[dbo].[objkeys] on objid = parentid
                   where objmask like 26 and okeydata like 'yes'
                   )
</code>```

output is

```<code>parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1        yes_no   yes
  2          name   a
  2      number     1
  2        yes_no   yes
  3          name   a
  3      number     1
  3        yes_no   no
  4          name   a
  4      number     2
  4          yes_no no
  5          name   b
  5      number     3
  5          yes_no yes
  6          name   b
  6      number     3
  6          yes_no yes
  7          name   b
  7      number     3
  7          yes_no no
  8          name   b
  8      number     3
  8          yes_no no

</code>```

need to be like this

```<code>parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1          yes_no yes

  3          name   a
  3      number     1
  3          yes_no no

  5          name   b
  5      number     3
  5          yes_no yes

  7          name   b
  7      number     3
  7          yes_no no
</code>```

答:
If you can ignore 'parentid', you can use the code below.</p>

```<code>select distinct okeyname, okeydata,
             row_number() over (order by (select null)) as seqnum
      from [elo].[dbo].[objkeys]
      where parentid in (select parentid
                         from [elo].[dbo].[objekte] inner join
                              [elo].[dbo].[objkeys]
                               on objid = parentid
                         where objmask like 26 and okeydata like 'yes'
                        )
</code>```

Body:
How to delete duplicate from this result

select *,
       row_number() over (order by (select null)) as seqnum
from [elo].[dbo].[objkeys]
where parentid in (select parentid
                   from [elo].[dbo].[objekte]
                   inner join [elo].[dbo].[objkeys] on objid = parentid
                   where objmask like 26 and okeydata like 'yes'
                   )

output is

parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1        yes_no   yes
  2          name   a
  2      number     1
  2        yes_no   yes
  3          name   a
  3      number     1
  3        yes_no   no
  4          name   a
  4      number     2
  4          yes_no no
  5          name   b
  5      number     3
  5          yes_no yes
  6          name   b
  6      number     3
  6          yes_no yes
  7          name   b
  7      number     3
  7          yes_no no
  8          name   b
  8      number     3
  8          yes_no no

need to be like this

parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1          yes_no yes

  3          name   a
  3      number     1
  3          yes_no no

  5          name   b
  5      number     3
  5          yes_no yes

  7          name   b
  7      number     3
  7          yes_no no

Body:
If you can ignore 'parentid', you can use the code below.

select distinct okeyname, okeydata,
             row_number() over (order by (select null)) as seqnum
      from [elo].[dbo].[objkeys]
      where parentid in (select parentid
                         from [elo].[dbo].[objekte] inner join
                              [elo].[dbo].[objkeys]
                               on objid = parentid
                         where objmask like 26 and okeydata like 'yes'
                        )


问:
1 pixel grid lines in pcolormesh
When using pcolormesh in matplotlib I can get a grid using the edgecolor parameter. I want this grid to be exactly 1 pixel wide with no antialiasing:

```<code>plt.pcolormesh(x_bin_edges, y_bin_edges, z, edgecolor='k', linewidth=1, antialiased=False)
</code>```

But this code gives me a grid which is 2-3 pixels wide (the tiny red dashes are added as a visual guide):

Reducing the linewidth further (to say 0.1) gives me grid lines that are 1-2 pixels wide:

Reducing the linewidth further doesn't seem to do anything. How can I get all the grid lines down to 1 pixel width?

I'm using the Agg backend for creating png-files in matplotlib 1.4.2 in python 2.7.8.

答:
Since the answer didn't really clarify how to set the linewdith parameter of pcolormesh to get exactly 1 pixel width grid lines, and I spent some effort reverse engineering it,I am posting some code that works for me and hopefully may help others that want to avoid using ax.grid, which is very often misaligned by one pixel compared to the cells shown by imshow.

Set my_dpi to your monitor's dpi values and tell your figure that this is the dpi values you are using, and compute the linewidth with this formula.

my_dpi = 96.0
plt.figure(dpi=my_dpi)

my_linewidth=my_dpi/(1024*32)
```

This seems to work for me in consistently ensuring exactly 1 pixel wide grid lines with pcolormesh.

Title: 1 pixel grid lines in pcolormesh

Body:
When using pcolormesh in matplotlib I can get a grid using the edgecolor parameter. I want this grid to be exactly 1 pixel wide with no antialiasing:

plt.pcolormesh(x_bin_edges, y_bin_edges, z, edgecolor='k', linewidth=1, antialiased=False)

But this code gives me a grid which is 2-3 pixels wide (the tiny red dashes are added as a visual guide):

Reducing the linewidth further (to say 0.1) gives me grid lines that are 1-2 pixels wide:

Reducing the linewidth further doesn't seem to do anything. How can I get all the grid lines down to 1 pixel width?

I'm using the Agg backend for creating png-files in matplotlib 1.4.2 in python 2.7.8.

Body:
Since the answer didn't really clarify how to set the linewdith parameter of pcolormesh to get exactly 1 pixel width grid lines, and I spent some effort reverse engineering it,I am posting some code that works for me and hopefully may help others that want to avoid using ax.grid, which is very often misaligned by one pixel compared to the cells shown by imshow.

Set my_dpi to your monitor's dpi values and tell your figure that this is the dpi values you are using, and compute the linewidth with this formula.

my_dpi = 96.0
plt.figure(dpi=my_dpi)

my_linewidth=my_dpi/(1024*32)

This seems to work for me in consistently ensuring exactly 1 pixel wide grid lines with pcolormesh.


问:
Find better way to see if object has filled fields
I got the filter in Vue.

Template:

```<code><b-button v-if="filterFilled()" @click="clearFilter">
    Clear
</b-button>
</code>```

Data:

```<code>data () {
      return {
        filter: {
          price_from: '',
          price_to: '',
          surface_from: '',
          surface_to: '',
          floor: '',
          type: '',
          structure: '',
        },
      }
    },
</code>```

And my method where I check is filter dirty:

```<code>filterFilled(){
        return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from ||
          this.filter.floor || this.filter.type || this.filter.structure)
      },
</code>```

This works fine, but my question is, does it exists better way to ask if object has filled props?

答:
Apart from @adiga suggestion, for methods that checks over data in your component, you should generally prefer computed properties over methods, since they are more performant and only called when some of its dependencies change:</p>
```<code>...

data () {
      return {
        filter: {
          price_from: '',
          price_to: '',
          surface_from: '',
          surface_to: '',
          floor: '',
          type: '',
          structure: '',
        },
      }
    },
  computed: {
     filterFilled() {
       // as in @adiga answer, which is great
       return Object.values(this.filter).some(v => v);
     }
  }
</code>```

Body:
I got the filter in Vue.

Template:

    Clear

Data:

data () {
      return {
        filter: {
          price_from: '',
          price_to: '',
          surface_from: '',
          surface_to: '',
          floor: '',
          type: '',
          structure: '',
        },
      }
    },

And my method where I check is filter dirty:

filterFilled(){
        return (this.filter.price_from || this.filter.price_to || this.filter.surface_to || this.filter.surface_from ||
          this.filter.floor || this.filter.type || this.filter.structure)
      },

This works fine, but my question is, does it exists better way to ask if object has filled props?

Body:
Apart from @adiga suggestion, for methods that checks over data in your component, you should generally prefer computed properties over methods, since they are more performant and only called when some of its dependencies change:

...

data () {
      return {
        filter: {
          price_from: '',
          price_to: '',
          surface_from: '',
          surface_to: '',
          floor: '',
          type: '',
          structure: '',
        },
      }
    },
  computed: {
     filterFilled() {
       // as in @adiga answer, which is great
       return Object.values(this.filter).some(v => v);
     }
  }


答:
Just use</p>

```<code>while (counter < Data_string.Length)
{

}
</code>```

Body:
I have a String which is mentioned below i am extracting a 2D array from this string (which i am doing successfully) The problem is that I dont know how to exit the while loop.

00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000,
00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000,
00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000,
00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000,
00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,

I tried to put "x" at the end of string  and ran my while loop like this and it works but Its not feasible for me beacuase I have to read this string from like hundreds of files.

while (Data_string[counter] !=  'x' )
{
    while (Data_string[counter] != ',')
    {
        if (Data_string[counter] != '\n')
            SubString += Data_string[counter];

        counter++;
    }
    // here I use Substring to covert to int and then set Substring to empty string
}

So I am looking for an efficient solution so i dont have to alter the string,

Thanks..

Body:
Just use

while (counter < Data_string.Length)
{

}


问:
How to stop default link click behavior with jQuery
I have a link on a web page.  When a user clicks it, a widget on the page should update.  However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

```<code><a href="store/cart/" class="update-cart">Update Cart</a>
</code>```

This is what the jQuery looks like:

```<code>$('.update-cart').click(function(e) {
  e.stopPropagation();
  updateCartWidget();
});
</code>```

What is the problem?

答:
```<code>$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});
</code>```

The following methods achieve the exact same thing.

Body:
I have a link on a web page.  When a user clicks it, a widget on the page should update.  However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.

This is what the link looks like:

Update Cart

This is what the jQuery looks like:

$('.update-cart').click(function(e) {
  e.stopPropagation();
  updateCartWidget();
});

What is the problem?

Body:
$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});

The following methods achieve the exact same thing.


问:
How to adress variable Columns of SQL query with TWIG
I am trying to address a specific column of a SQL query depending on the value of another row from the query.

The result I am getting from the SQL query is something like this:

```<code>Number | Value1 | Value2 | Value3
1      |      3 |      5 |     4
3      |      5 |      2 |     6
2      |      1 |      3 |     2
</code>```

For each row, I want to get the Value of the Column by the Index of the Number.
So for example in the first row, I want to get the Value of 'Value1', which is 3.
In the second row, I want to get the Value of 'Value3', which is 6, and so on.

Then I am iterating through the list with a TWIG for loop and can access the 'Number' parameter like this:

```<code>{% for key in examplelist|keys %}
   {% set number = examplelist[key].number %}
{% endfor %}
</code>```

Unfortunately, I cannot address the 'Value'-columns using that number.

I have tried things like:

```<code>{{examplelist[key].Value . number }}
</code>```

or

```<code>{{examplelist[key].Value + number }}
</code>```

or

```<code>{{examplelist[key].Value ~ number }}
</code>```

but none of these work...

答:
Okay, I figured it out.

The data gets returned as an object of the type stdClass, not as an array. Therefore you can't access it like an array and it has to be converted using

```<code>$Examplelist = json_decode($Examplelist, true);
return $Examplelist;
</code>```

in the php part.

Afterwards, it can be adressed by using

```<code>{% set value  = examplelist[key]["Value"~number] %}
</code>```

Thank you for the Help anyways :)

Body:
I am trying to address a specific column of a SQL query depending on the value of another row from the query.

The result I am getting from the SQL query is something like this:

Number | Value1 | Value2 | Value3
1      |      3 |      5 |     4
3      |      5 |      2 |     6
2      |      1 |      3 |     2

For each row, I want to get the Value of the Column by the Index of the Number.
So for example in the first row, I want to get the Value of 'Value1', which is 3.
In the second row, I want to get the Value of 'Value3', which is 6, and so on.

Then I am iterating through the list with a TWIG for loop and can access the 'Number' parameter like this:

{% for key in examplelist|keys %}
   {% set number = examplelist[key].number %}
{% endfor %}

Unfortunately, I cannot address the 'Value'-columns using that number.

I have tried things like:

{{examplelist[key].Value . number }}

or

{{examplelist[key].Value + number }}

or

{{examplelist[key].Value ~ number }}

but none of these work...

Body:
Okay, I figured it out.

The data gets returned as an object of the type stdClass, not as an array. Therefore you can't access it like an array and it has to be converted using

$Examplelist = json_decode($Examplelist, true);
return $Examplelist;

in the php part.

Afterwards, it can be adressed by using

{% set value  = examplelist[key]["Value"~number] %}

Thank you for the Help anyways :)


问:
Open a portrait page from Pivot Page Listbox with "LineThree" text in it
As the title says...
If I start my app project with a pivot page(MainPage.xaml) and then choose to click for example the "design two" link in the databinded listbox. Is it possible to bind the "LineThree" text for the "design two" link in to a separate portrait page?

Do I have to make new portrait page for every "LineThree"-link? Or can I just generate the "MainViewModelSampleData.xaml" data to a single portrait page depending on what "LineOne"-link I click in the pivot page in the start?

Hope my question is understandable... :P

答:
If I understand you correctly, you want to have a main page that contains a list of data, and then a details page whose contents are dependent on the item that you clicked in the main page. The answer to your question is then "yes". There are a number of ways to achieve this, some of which include global variables, a custom navigation service, storing a value in isolated storage and so on. My personal preference is to use the context of the NavigationService and to pass an ID or an index in the query string for the target page.

Your call to navigate to the details page then looks like this:

```<code>Application.Current.Navigate(string.Format("/Views/DetailsView.xaml?id={0}", id));</code>```

In the target page, you override the OnNavigatedTo handler to retrieve the value that you passed and then process it accordingly (i.e. look up the value from your database, or retrieve it from a data collection).

```<code>protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (this.NavigationContext.QueryString.ContainsKey("id"))
    {
        var id = this.NavigationContext.QueryString["id"];
        // TODO: Do what you need to with the ID.
    }
    else
    {
        // I use this condition to handle creating new items.
    }
}</code>```

Body:
If I understand you correctly, you want to have a main page that contains a list of data, and then a details page whose contents are dependent on the item that you clicked in the main page. The answer to your question is then "yes". There are a number of ways to achieve this, some of which include global variables, a custom navigation service, storing a value in isolated storage and so on. My personal preference is to use the context of the NavigationService and to pass an ID or an index in the query string for the target page.

Your call to navigate to the details page then looks like this:

Application.Current.Navigate(string.Format("/Views/DetailsView.xaml?id={0}", id));

In the target page, you override the OnNavigatedTo handler to retrieve the value that you passed and then process it accordingly (i.e. look up the value from your database, or retrieve it from a data collection).

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (this.NavigationContext.QueryString.ContainsKey("id"))
    {
        var id = this.NavigationContext.QueryString["id"];
        // TODO: Do what you need to with the ID.
    }
    else
    {
        // I use this condition to handle creating new items.
    }
}


问:
Pagination API good practice
My main function :

```<code>def get_data():
    try:
        response = send_request_to_get_data()

        // will get one dict output looks like :
        {
          "data": ['some datas.....'],
          "next": "api/data?top=100&skip=200",
        }

        if response.status_code == 200:
            if response.json().get("next"):
                first_paginated_response = get_paginated_data(response.json().get("next"))

                if response.status_code == 200:
                    if first_paginated_response.json().get("next"):
                        second_paginated_response = get_paginated_data(response.json().get("next"))

                        if response.status_code == 200:
                           if second_paginated_response.json().get("next"):
                               print('again...again....again....again...again)

def send_request_to_get_data():
    return rq.get('https://example.com')

def get_paginated_data(paginated):
    url = "https://example.com/{next}".format(next=paginated)
    return rq.get(url)
</code>```

If "next" key is in response, i need to send another request for pagination api, but my if statement looks weird.

What is the good approach for this?

答:
You could use while loop and save the data like this:

```<code>response = send_request_to_get_data()
data = response['data']
while response.status_code == 200 and response.json().get("next"):
    response = get_paginated_data(response.json().get("next"))
    data.extend(response['data'])
</code>```

Title: Pagination API good practice

Body:
My main function :

def get_data():
    try:
        response = send_request_to_get_data()

        // will get one dict output looks like :
        {
          "data": ['some datas.....'],
          "next": "api/data?top=100&skip=200",
        }

        if response.status_code == 200:
            if response.json().get("next"):
                first_paginated_response = get_paginated_data(response.json().get("next"))

                if response.status_code == 200:
                    if first_paginated_response.json().get("next"):
                        second_paginated_response = get_paginated_data(response.json().get("next"))

                        if response.status_code == 200:
                           if second_paginated_response.json().get("next"):
                               print('again...again....again....again...again)

def send_request_to_get_data():
    return rq.get('https://example.com')

def get_paginated_data(paginated):
    url = "https://example.com/{next}".format(next=paginated)
    return rq.get(url)

If "next" key is in response, i need to send another request for pagination api, but my if statement looks weird.

What is the good approach for this?

Body:
You could use while loop and save the data like this:

response = send_request_to_get_data()
data = response['data']
while response.status_code == 200 and response.json().get("next"):
    response = get_paginated_data(response.json().get("next"))
    data.extend(response['data'])


答: You can use the file length as your stopping condition</p>


答:
Use string.Length:

```<code>while (counter < Data_string.Length)
    { } // some code
</code>```

Side note: Common code style in C# avoids snake_case. Use UpperCamelCase for properties and lowerCamelCase for local or private variables.

Body:
Use string.Length:

while (counter < Data_string.Length)
    { } // some code

Side note: Common code style in C# avoids snake_case. Use UpperCamelCase for properties and lowerCamelCase for local or private variables.


问:
object junit is not a member of package org
When running

sbt compile

in project root I get error:

```<code>object junit is not a member of package org
[error] import org.junit.Test
</code>```

I have fully defined build.sbt:

```<code>libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test"
testOptions += Tests.Argument(TestFrameworks.JUnit, "-q", "-v")
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0" % "test
libraryDependencies += "junit" % "junit" % "4.12" % "test"
</code>```

File TestSingleLinkedList.scala is also in project root and has:

```<code>import org.junit.Test
</code>```

答:
It seems the only valid to put junit tests in sbt is:

```<code>├── built.sbt
├── src
│   └── test
│       └── scala
│           ├── X.scala
</code>```

Otherwise - sbt will provide very uninformative and confusing error about junit not being included.
I found the answer from
ScalaTest on sbt not running any tests
where someone asked different question about sbt not running the tests.
In my case the sbt - was not compiling at all.

Body:
When running

sbt compile

in project root I get error:

object junit is not a member of package org
[error] import org.junit.Test

I have fully defined build.sbt:

libraryDependencies += "com.novocode" % "junit-interface" % "0.11" % "test"
testOptions += Tests.Argument(TestFrameworks.JUnit, "-q", "-v")
libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0" % "test
libraryDependencies += "junit" % "junit" % "4.12" % "test"

File TestSingleLinkedList.scala is also in project root and has:

import org.junit.Test

Body:
It seems the only valid to put junit tests in sbt is:

├── built.sbt
├── src
│   └── test
│       └── scala
│           ├── X.scala

Otherwise - sbt will provide very uninformative and confusing error about junit not being included.
I found the answer from
ScalaTest on sbt not running any tests
where someone asked different question about sbt not running the tests.
In my case the sbt - was not compiling at all.