问:
How to get the JSON from the Body of a Request on Go
I'm a newbie with Go, but so far I'm liking it very much.

I have a problem I can't figure out. I'm migrating an API from Node to Go and there is this log where I have to capture the Body of a POST AS IT IS and save it to a jsonb type column in a Postgresql database.

This means I can't use a struct or anything predetermined.

The POST is made with body raw Content-Type: application/json like so:

```<code>{
    "debug": false,
    "order_id_gea": 326064,
    "increment_id_gea": 200436102,
    "date": "2017-05-18T01:44:44+00:00",
    "total_amount": 10000.00,
    "currency": "MXN",
    "payment_method": "Referencia bancaria",
    "reference": "857374",
    "buyer": {
        "buyer_id_gea": 1234,
        "full_name": "Juan Perez Martinez",
        "email": "juanperez@gmail.com",
        "phone": "5512341234"
    },
    "products": [
        {
            "sku":"PEP16114",
            "price": 10000.00,
            "currency": "MXN",
            "student": {
                "school_id_gea": 172,
                "grade_id_gea": 119,
                "level_id_gea": 36,
                "name": "Benancio",
                "last_name": "Perez",
                "second_last_name": "Garcia",
                "email": "benancio@gmail.com"
            }
        }
    ]
}
</code>```

On Node + Hapi is quite simple:

```<code>const payload = request.payload
</code>```

and then I can access the JSON from payload.

I am using Go with Echo, so context is a wrapper where I can find Request() *http.Request.

I have tried the following, but everytime the result is empty or an error because it is empty:

```<code>var v interface{}
err := json.NewDecoder(context.Request().Body).Decode(&v)
if err != nil {
    return result, err
}
fmt.Println(v)
</code>```

Result: EOF

--

```<code>m := echo.Map{}
if err := context.Bind(&m); err != nil {
    return result, err
}
fmt.Println(m)
</code>```

Result code 400, message EOF

--

```<code>body, error := ioutil.ReadAll(context.Request().Body)
if error != nil {
    return result, error
}
fmt.Println(body)
</code>```

Result []

--

What am I missing and/or doing wrong? Thanks!

答:
TIL that http.Response.Body is a buffer, which means that once it has been read, it cannot be read again.

It's like a stream of water, you can see it and measure it as it passes but once it's gone, it's gone.

However, knowing this, there is a workaround, you need to "catch" the body and restore it:

```<code>// Read the Body content
var bodyBytes []byte
if context.Request().Body != nil {
    bodyBytes, _ = ioutil.ReadAll(context.Request().Body)
}

// Restore the io.ReadCloser to its original state
context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

// Continue to use the Body, like Binding it to a struct:
order := new(models.GeaOrder)
error := context.Bind(order)
</code>```

Now, you can use context.Request().Body somewhere else.

Sources:

http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or-any-reader

https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361

Body:
I'm a newbie with Go, but so far I'm liking it very much.

I have a problem I can't figure out. I'm migrating an API from Node to Go and there is this log where I have to capture the Body of a POST AS IT IS and save it to a jsonb type column in a Postgresql database.

This means I can't use a struct or anything predetermined.

The POST is made with body raw Content-Type: application/json like so:

{
    "debug": false,
    "order_id_gea": 326064,
    "increment_id_gea": 200436102,
    "date": "2017-05-18T01:44:44+00:00",
    "total_amount": 10000.00,
    "currency": "MXN",
    "payment_method": "Referencia bancaria",
    "reference": "857374",
    "buyer": {
        "buyer_id_gea": 1234,
        "full_name": "Juan Perez Martinez",
        "email": "juanperez@gmail.com",
        "phone": "5512341234"
    },
    "products": [
        {
            "sku":"PEP16114",
            "price": 10000.00,
            "currency": "MXN",
            "student": {
                "school_id_gea": 172,
                "grade_id_gea": 119,
                "level_id_gea": 36,
                "name": "Benancio",
                "last_name": "Perez",
                "second_last_name": "Garcia",
                "email": "benancio@gmail.com"
            }
        }
    ]
}

On Node + Hapi is quite simple:

const payload = request.payload

and then I can access the JSON from payload.

I am using Go with Echo, so context is a wrapper where I can find Request() *http.Request.

I have tried the following, but everytime the result is empty or an error because it is empty:

var v interface{}
err := json.NewDecoder(context.Request().Body).Decode(&v)
if err != nil {
    return result, err
}
fmt.Println(v)

Result: EOF

--

m := echo.Map{}
if err := context.Bind(&m); err != nil {
    return result, err
}
fmt.Println(m)

Result code 400, message EOF

--

body, error := ioutil.ReadAll(context.Request().Body)
if error != nil {
    return result, error
}
fmt.Println(body)

Result []

--

What am I missing and/or doing wrong? Thanks!

Body:
TIL that http.Response.Body is a buffer, which means that once it has been read, it cannot be read again.

It's like a stream of water, you can see it and measure it as it passes but once it's gone, it's gone.

However, knowing this, there is a workaround, you need to "catch" the body and restore it:

// Read the Body content
var bodyBytes []byte
if context.Request().Body != nil {
    bodyBytes, _ = ioutil.ReadAll(context.Request().Body)
}

// Restore the io.ReadCloser to its original state
context.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

// Continue to use the Body, like Binding it to a struct:
order := new(models.GeaOrder)
error := context.Bind(order)

Now, you can use context.Request().Body somewhere else.

Sources:

http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-response-body-or-any-reader

https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361


来源: stackexchange

问:
Error installing tizen studio on windows 10
No matter which of the three tizen studio 2.0 installers I try they all don't work as they won't accept any path. The CLI installer gives the most detailed description:

** The directory you specify is not allowed to install the Tizen Studio. Some tools of the Tizen Studio will not properly work in the directory with administrator privilege or read-only access rights for your account.=> path

I have tried starting the installer with admin rights and owning the destination folders. Additionally, I switched from JDK 9 to 8.

Still, there seems no way to get the installer running. Any ideas what the reason could be? Thanks!

答:
@Henry was almost correct and his scenario works on CLI/IDE installers.

And here are actual restrictions on Win10x64 tizen-studio 2.0 installation I've found:

pointed SDK location needs to be in your user directory. For example:

C:\Users\MrSmith\Tizen\tizen-studio

Data location could be anywhere, but in case of CLI installation, it will be near SDK folder.

CLI installation actually does unzip only and all further system configuration needs to be done manually. So, if you need only CLI, you could unzip "web-cli_Tizen_Studio_2.0_windows-64.exe" with 7zip or any other proper archiver where you want and do further manual configuration. (See here https://developer.tizen.org/development/tizen-studio/web-tools/cli)

Probably, if you login under Administrator you will be able to install SDK anywhere. Just "Run as administrator" doesn't work, at least for me.

My system params:

Win10 Pro x64

Oracle JDK 1.8.0_152

Have a fan ;)

ContentLicense: CC BY-SA 3.0


问:
Testing ASP Net Core Application with SQLite throws unknown function: newid()
I am testing my service layer which contains some calls to repositories by using the SQLite database provider. My test class has been written according to the following introduction:
https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite

For the entity which is written to the database in this test case, the Guid is generated on database:

```<code>entity.Property(e => e.Guid).HasDefaultValueSql("newid()");
</code>```

Now when trying to add a new entity (without explicitely setting the Guid), I get following exception:

```<code>SQLite Error 1: 'unknown function: newid()'.
</code>```

Is there a way around this issue?
It seems like this function is simply not supported. As the database I am working with is quite old I am afraid to find more places like this which may not work.

My hope was to get better unit tests with SQLite than using the InMemoryDatabase provider which does not really suits for testing "relational database functionalities". But if this problem cannot be solved, I am stuck and probably need to stick to integration tests (at least for the data access part of my services)

答:
I guess you would have this issue for MySql uuid() or any other DB because there is a direct dependency to MSSQL with newid(). My first suggestion would be to generate the GUID on the application side and pass it to the DB but you have probably already thought of that and cannot.  As a workaround you can create a extension method like the following:

```<code>public static class Extensions
{
    private static readonly Dictionary<Type, string> NewIdDictionary = new Dictionary<Type, string>
    {
        { typeof(SqlServerOptionsExtension), "newid()" }
    };

    public static PropertyBuilder<TProperty> HasDefaultValueForSql<TProperty>(this PropertyBuilder<TProperty> propertyBuilder,
        DbContextOptions contextOptions)
    {
        var result = contextOptions.Extensions.Select(extension =>
        {
            if (!(extension is RelationalOptionsExtension item)) return string.Empty;
            return NewIdDictionary.TryGetValue(item.GetType(), out var sql) ? sql : string.Empty;
        }).SingleOrDefault(s => !string.IsNullOrEmpty(s));

        return propertyBuilder.HasDefaultValueSql(result);
    }
}
</code>```

Although there isn't an equvalient for SQLite it seems to work when passing null to .HasDefaultValueSql. And then you can add other extension types if needed.

Body:
I am testing my service layer which contains some calls to repositories by using the SQLite database provider. My test class has been written according to the following introduction:
https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite

For the entity which is written to the database in this test case, the Guid is generated on database:

entity.Property(e => e.Guid).HasDefaultValueSql("newid()");

Now when trying to add a new entity (without explicitely setting the Guid), I get following exception:

SQLite Error 1: 'unknown function: newid()'.

Is there a way around this issue?
It seems like this function is simply not supported. As the database I am working with is quite old I am afraid to find more places like this which may not work.

My hope was to get better unit tests with SQLite than using the InMemoryDatabase provider which does not really suits for testing "relational database functionalities". But if this problem cannot be solved, I am stuck and probably need to stick to integration tests (at least for the data access part of my services)

Body:
I guess you would have this issue for MySql uuid() or any other DB because there is a direct dependency to MSSQL with newid(). My first suggestion would be to generate the GUID on the application side and pass it to the DB but you have probably already thought of that and cannot.  As a workaround you can create a extension method like the following:

public static class Extensions
{
    private static readonly Dictionary<Type, string> NewIdDictionary = new Dictionary<Type, string>
    {
        { typeof(SqlServerOptionsExtension), "newid()" }
    };

    public static PropertyBuilder<TProperty> HasDefaultValueForSql<TProperty>(this PropertyBuilder<TProperty> propertyBuilder,
        DbContextOptions contextOptions)
    {
        var result = contextOptions.Extensions.Select(extension =>
        {
            if (!(extension is RelationalOptionsExtension item)) return string.Empty;
            return NewIdDictionary.TryGetValue(item.GetType(), out var sql) ? sql : string.Empty;
        }).SingleOrDefault(s => !string.IsNullOrEmpty(s));

        return propertyBuilder.HasDefaultValueSql(result);
    }
}

Although there isn't an equvalient for SQLite it seems to work when passing null to .HasDefaultValueSql. And then you can add other extension types if needed.


问:
Flask google authentification offline keep
I followed this tutorial for the authentification with google account in the flask.

As was written in this tutorial the response as the JSON is:

```<code>{
  "family_name": "Doe",
  "name": "John Doe",
  "picture": "https://lh3.googleusercontent.com/-asdasdas/asdasdad/asdasd/daadsas/photo.jpg",
  "locale": "en",
  "gender": "male",
  "email": "john@gmail.com",
  "link": "https://plus.google.com/+JohnDoe",
  "given_name": "John",
  "id": "1109367330250025112153346",
  "verified_email": true
}
</code>```

I fetch this JSON response to my database and trying to login in offline mode. In other words, I added one more "group" column to the response and base that column redirect users to the different pages. When I try to log in again with this credentials after login page it opens a blank page without any error. My question how can I keep google user credentials in the flask at offline mode. Thank you for reading

答: You can't keep it by this way because oath token will update each time. But you can update user data, at the base of the email. Read this guide</p>

Body:
I followed this tutorial for the authentification with google account in the flask.

As was written in this tutorial the response as the JSON is:

{
  "family_name": "Doe",
  "name": "John Doe",
  "picture": "https://lh3.googleusercontent.com/-asdasdas/asdasdad/asdasd/daadsas/photo.jpg",
  "locale": "en",
  "gender": "male",
  "email": "john@gmail.com",
  "link": "https://plus.google.com/+JohnDoe",
  "given_name": "John",
  "id": "1109367330250025112153346",
  "verified_email": true
}

I fetch this JSON response to my database and trying to login in offline mode. In other words, I added one more "group" column to the response and base that column redirect users to the different pages. When I try to log in again with this credentials after login page it opens a blank page without any error. My question how can I keep google user credentials in the flask at offline mode. Thank you for reading


问:
Invalid conversion from void* to int*
I have a global variable:

```<code>static int *avgg;
</code>```

In main function:

```<code>avgg = mmap(NULL, sizeof *avgg, PROT_READ | PROT_WRITE,
                MAP_SHARED | MAP_ANONYMOUS, -1, 0);

pid_t  pid, wpid;
int status;

 pid = fork();
 if (pid == 0) {
      avg(argc,argv);
      print_avg();

  }
 else{
     while ((wpid = wait(&status)) > 0) {

     }
 cout<<"Parent process";
     print_avg();
</code>```

By using mmap Im trying to share memory between parent and child process but Im getting error:

```<code>invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
                 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
</code>```

答:
Hi you can fix this problem with this code segment :

```<code> int file_descriptor = shm_open("/test_shared_memory", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
 void *address = mmap ( NULL, size, PROT_READ | PROT_WRITE , MAP_SHARED, file_descriptor, 0);
 // For checking that the address mapped correctly or not.
 if (address == MAP_FAILED) {
    printf("Memory map failed. :(");
    return (EXIT_FAILURE);
 }
</code>```

Thanks.

Title: Invalid conversion from void* to int*

Body:
I have a global variable:

static int *avgg;

In main function:

avgg = mmap(NULL, sizeof *avgg, PROT_READ | PROT_WRITE,
                MAP_SHARED | MAP_ANONYMOUS, -1, 0);

pid_t  pid, wpid;
int status;

 pid = fork();
 if (pid == 0) {
      avg(argc,argv);
      print_avg();

  }
 else{
     while ((wpid = wait(&status)) > 0) {

     }
 cout<<"Parent process";
     print_avg();

By using mmap Im trying to share memory between parent and child process but Im getting error:

invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
                 MAP_SHARED | MAP_ANONYMOUS, -1, 0);

Body:
Hi you can fix this problem with this code segment :

 int file_descriptor = shm_open("/test_shared_memory", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
 void *address = mmap ( NULL, size, PROT_READ | PROT_WRITE , MAP_SHARED, file_descriptor, 0);
 // For checking that the address mapped correctly or not.
 if (address == MAP_FAILED) {
    printf("Memory map failed. :(");
    return (EXIT_FAILURE);
 }

Thanks.


问:
Open URL in intent
In my application I receive a URL inserted by the user.  This URL can be - for example - xx.sd.  Using any web browser, this URL is a valid URL, but when try to open it by intent, a crash happens: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=xx.sd }.

I check this URL is valid URL by using this

```<code>Patterns.WEB_URL.matcher(model.getTarget().getUrl()).matches()
</code>```

and open intent by using this code

```<code>  Intent i = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(model.getTarget().getUrl()));
  itemView.getContext().startActivity(i);
</code>```

I know i can solve this issue by append http or https before URL if not exist but if my URL start with another protocol like ftp or file and other protocols. Can any one help me to handle this issue.

答:
Add un try-catch and call-again, such as:</p>

```<code>public boolean startOpenWebPage(String url) {
    boolean result = false;
    if (!url.startsWith("http://") && !url.startsWith("https://"))
        url = "http://" + url;

    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);

    try {
        startActivity(intent);
        result = true;
    }catch (Exception e){
        if (url.startsWith("http://")){
            startOpenWebPage(url.replace("http://","https://"));
        }
    }
    return result;
}
</code>```

Title: Open URL in intent

Body:
In my application I receive a URL inserted by the user.  This URL can be - for example - xx.sd.  Using any web browser, this URL is a valid URL, but when try to open it by intent, a crash happens: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=xx.sd }.

I check this URL is valid URL by using this

Patterns.WEB_URL.matcher(model.getTarget().getUrl()).matches()

and open intent by using this code

  Intent i = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(model.getTarget().getUrl()));
  itemView.getContext().startActivity(i);

I know i can solve this issue by append http or https before URL if not exist but if my URL start with another protocol like ftp or file and other protocols. Can any one help me to handle this issue.

Body:
Add un try-catch and call-again, such as:

public boolean startOpenWebPage(String url) {
    boolean result = false;
    if (!url.startsWith("http://") && !url.startsWith("https://"))
        url = "http://" + url;

    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);

    try {
        startActivity(intent);
        result = true;
    }catch (Exception e){
        if (url.startsWith("http://")){
            startOpenWebPage(url.replace("http://","https://"));
        }
    }
    return result;
}


问:
Subversion - Async development cycle... two trunks?
Currently in our enterprise we have a situation that i think it's not very common, or at least i haven't found a similar case in Internet. My problem is that we have software that can evolve by more than one requirement, and both not necessarily will coincide in their release date.

We have a development cycle where all software is developed in a "DEV" environment, and then it's handled to SQA so it can be tested on "LAB" environment; if all works OK then this software is moved to "PROD" environment. The problem i am facing here is that i cant use a single trunk and i don't see how a single branch could work either.

For example, lets say i have requirements A and B, one to be released today and the other a week from today. Both have reached LAB environment but today's release to PROD environment only has to contain A, since B is not yet needed by our business users (and it cannot be released early because it would introduce some error's to others systems). Both requirements where developed in different branches (they respond to different needs). In this case my problem is that i can't have a single trunk where developers can merge to see both changes in "DEV" environment, and then use the same trunk to feed "LAB" environment since it would have source code not yet scheduled for release.

I think i should also mention that having a separate development environment for each branch is not possible because this software is based on PL/SQL (Oracle) and our current test database is about 350Mb in size, so having a different one for each requirement would be quite expensive and hard to manage.

Any suggestion or similar experience would be appreciated.

Regards

答: Based on your last paragraph you've got quite a pickle.  I believe the best practice for this is to branch per feature and merge the features into the trunk as they're needed/released.  I don't really know if there's a second best practice for improving your situation (But I'm not that smart)...</p>

OwnerDisplayName: Patricio Téllez

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Adam Lassek

OwnerDisplayName: JPunyon


问:
How to map RestTemplate with multiple response content?
I must consume a REST API with RestTemplate which doesn't follows good patterns, like using HTTP status codes, for example.

I have both below response contents.

Success response:

```<code>{
    "435": {
        "Codigo": "435",
        "Tipo": "",
        "Corretor": "62",
        "Cliente": "48304",
        "DataHora": "2016-04-27 14:18:24",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "",
        "DataHoraInicio": "2016-04-28 12:00:00",
        "DataHoraFinal": "2016-04-28 12:20:00"
    },
    "687": {
        "Codigo": "687",
        "Tipo": "",
        "Corretor": "20",
        "Cliente": "33040",
        "DataHora": "2016-07-18 17:09:28",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "teste",
        "DataHoraInicio": "2016-07-28 08:00:00",
        "DataHoraFinal": "2016-07-28 09:00:00"
    }}
</code>```

We can note a map structure, as follows::

```<code>Map<String, MyObject> myObjects;
</code>```

MyObject Class

```<code>public class MyObject {

    @JsonProperty("Codigo")
    private String codigo;

    @JsonProperty("Tipo")
    private String tipo;

    @JsonProperty("Corretor")
    private String corretor;

    @JsonProperty("Cliente")
    private String cliente;

    @JsonProperty("DataHora")
    private String dataHora;

    @JsonProperty("DataHoraAtualizacao")
    private String dataHoraAtualizacao;

    @JsonProperty("Assunto")
    private String assunto;

    @JsonProperty("Local")
    private String local;

    @JsonProperty("Texto")
    private String texto;

    @JsonProperty("DataHoraInicio")
    private String dataHoraInicio;

    @JsonProperty("DataHoraFinal")
    private String dataHoraFinal;

}
</code>```

Error response (with no objects to return):

```<code>{
    "status": "200",
    "message": "A pesquisa não retornou resultados."
}
</code>```

How I should map a Java class in order to solve both cases?

答:
um... that API is awful, can you ask them to change it? at least to use proper HTTP codes?

If not, you could deserialize first into a Map<String, JsonNode> and then depending on the presence of the status field, deserialize into the appropriate type:

```<code>String json = ...
Map<String, JsonNode> response = mapper.readValue(json, ...);

if (response.get("status") != null) {
    // its an error, deserialize into Error type
    Error error = mapper.readValue(json, Error.class);
else {
    // not an error, deserialize into MyObject
    MyObject obj = mapper.readValue(json, MyObject.class);
}
</code>```

Body:
I must consume a REST API with RestTemplate which doesn't follows good patterns, like using HTTP status codes, for example.

I have both below response contents.

Success response:

{
    "435": {
        "Codigo": "435",
        "Tipo": "",
        "Corretor": "62",
        "Cliente": "48304",
        "DataHora": "2016-04-27 14:18:24",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "",
        "DataHoraInicio": "2016-04-28 12:00:00",
        "DataHoraFinal": "2016-04-28 12:20:00"
    },
    "687": {
        "Codigo": "687",
        "Tipo": "",
        "Corretor": "20",
        "Cliente": "33040",
        "DataHora": "2016-07-18 17:09:28",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "teste",
        "DataHoraInicio": "2016-07-28 08:00:00",
        "DataHoraFinal": "2016-07-28 09:00:00"
    }}

We can note a map structure, as follows::

Map<String, MyObject> myObjects;

MyObject Class

public class MyObject {

    @JsonProperty("Codigo")
    private String codigo;

    @JsonProperty("Tipo")
    private String tipo;

    @JsonProperty("Corretor")
    private String corretor;

    @JsonProperty("Cliente")
    private String cliente;

    @JsonProperty("DataHora")
    private String dataHora;

    @JsonProperty("DataHoraAtualizacao")
    private String dataHoraAtualizacao;

    @JsonProperty("Assunto")
    private String assunto;

    @JsonProperty("Local")
    private String local;

    @JsonProperty("Texto")
    private String texto;

    @JsonProperty("DataHoraInicio")
    private String dataHoraInicio;

    @JsonProperty("DataHoraFinal")
    private String dataHoraFinal;

}

Error response (with no objects to return):

{
    "status": "200",
    "message": "A pesquisa não retornou resultados."
}

How I should map a Java class in order to solve both cases?

Body:
um... that API is awful, can you ask them to change it? at least to use proper HTTP codes?

If not, you could deserialize first into a Map<String, JsonNode> and then depending on the presence of the status field, deserialize into the appropriate type:

String json = ...
Map<String, JsonNode> response = mapper.readValue(json, ...);

if (response.get("status") != null) {
    // its an error, deserialize into Error type
    Error error = mapper.readValue(json, Error.class);
else {
    // not an error, deserialize into MyObject
    MyObject obj = mapper.readValue(json, MyObject.class);
}


问:
Array Length 4 doesn't match Index Length 5 error message
I'm relatively new to pandas and am trying create a moving average crossover trading strategy backtest. It was going well until I tried to retrieve the profitability of long trades by creating a DataFrame. I continue to get the error message "ValueError: array length 4 doesn't match index length 5". Here is the piece of code that is giving me issues. </p>

```<code>Dextera_long_profits = pd.DataFrame({
        "Price": Dextera_signals.loc[(Dextera_signals["Signal"] == "Buy") &
                                  Dextera_signals["Regime"] == 1, "Price"],
        "Profit": pd.Series(Dextera_signals["Price"] - Dextera_signals["Price"].shift(1)).loc[
            Dextera_signals.loc[(Dextera_signals["Signal"].shift(1) == "Buy") & (Dextera_signals["Regime"].shift(1) == 1)].index
        ].tolist(),
        "End Date": Dextera_signals["Price"].loc[
            Dextera_signals.loc[(Dextera_signals["Signal"].shift(1) == "Buy") & (Dextera_signals["Regime"].shift(1) == 1)].index
        ].index
    })
Dextera_long_profits

print(Dextera_long_profits)
</code>```

答: I believe one of the .locs is returning 4 values instead of 5.  Try each of these in isolation and you should be able to determine which is the culprit.</p>

Body:
I'm relatively new to pandas and am trying create a moving average crossover trading strategy backtest. It was going well until I tried to retrieve the profitability of long trades by creating a DataFrame. I continue to get the error message "ValueError: array length 4 doesn't match index length 5". Here is the piece of code that is giving me issues.

Dextera_long_profits = pd.DataFrame({
        "Price": Dextera_signals.loc[(Dextera_signals["Signal"] == "Buy") &
                                  Dextera_signals["Regime"] == 1, "Price"],
        "Profit": pd.Series(Dextera_signals["Price"] - Dextera_signals["Price"].shift(1)).loc[
            Dextera_signals.loc[(Dextera_signals["Signal"].shift(1) == "Buy") & (Dextera_signals["Regime"].shift(1) == 1)].index
        ].tolist(),
        "End Date": Dextera_signals["Price"].loc[
            Dextera_signals.loc[(Dextera_signals["Signal"].shift(1) == "Buy") & (Dextera_signals["Regime"].shift(1) == 1)].index
        ].index
    })
Dextera_long_profits

print(Dextera_long_profits)


问:
How to run UFT script without having UFT installed
I want to know whether is there any way to run script written in UFT without having UFT installed in your PC.
Can we export Script to some .vbs or .exe file? Or is there any alternate way through which we can execute scripts? </p>

答:
You now can with the UFT Runtime Engine. More information can be found at this link.

From that site:

The UFTRuntime Engine enables you to run UFT tests (both GUI and API)
  and business process tests on your computer without installing the
  entire UFT IDE. In addition, you can also install the Runtime Engine
  without the Run Results Viewer, UFT Add-in for ALM, sample
  applications, or Help documentation. This can potentially save you
  valuable disk space on your computer


问:
Can Kafka be provided with custom LoginModule to support LDAP?
Kafka can be configured to use several authentication mechanisms: plaintext username/password, Kerberos or SSL.  The first 2 use SASL, where there is a JAAS config file required.

For the plain text auth method, the config looks like (taken from the documentation):

```<code>KafkaServer {
   org.apache.kafka.common.security.plain.PlainLoginModule required
   username="admin"
   password="admin-secret"
   user_admin="admin-secret"
   user_alice="alice-secret";
};
</code>```

I want to authenticate if possible using LDAP.  My question is this: if I replace the PlainLoginModule with a class that implements LoginModule and place this class in the broker's classpath, can I implement authentication in any manner I wish (i.e. LDAP)?

I cannot use Kerberos in a reasonable fashion because of the way its principals are defined within the organisation where I'm working, hence I wish to use LDAP as I need to support RBAC.

答:
Yes you can provide Kafka with a custom class that implements LoginModule and have the authentication logic you want in it.

Then update the JAAS file with your class name and make sure it's in the classpath.

You'll need to put some boilerplate code to get everything setup correctly but you can use PlainLoginModule, PlainSaslServerProvider, PlainSaslServerFactory and PlainSaslServer as examples.

Your LoginModule class should have the same logic as PlainLoginModule but instead initialize your Provider implementation (in the static block).

Your Provider class should have the same logic as PlainSaslServerProvider but instead reference your SaslServerFactory implementation.

Your SaslFactory class should again have the same logic as PlainSaslServerFactory but create an instance of your SaslServer implementation.

Finally your SaslServer class should implement the necessary LDAP logic in its evaluateResponse() method. Just be sure to set correctly set this.authorizationId as this will become the user principal and set complete to true (like PlainSaslServer.evaluateResponse() does)

Body:
Kafka can be configured to use several authentication mechanisms: plaintext username/password, Kerberos or SSL.  The first 2 use SASL, where there is a JAAS config file required.

For the plain text auth method, the config looks like (taken from the documentation):

KafkaServer {
   org.apache.kafka.common.security.plain.PlainLoginModule required
   username="admin"
   password="admin-secret"
   user_admin="admin-secret"
   user_alice="alice-secret";
};

I want to authenticate if possible using LDAP.  My question is this: if I replace the PlainLoginModule with a class that implements LoginModule and place this class in the broker's classpath, can I implement authentication in any manner I wish (i.e. LDAP)?

I cannot use Kerberos in a reasonable fashion because of the way its principals are defined within the organisation where I'm working, hence I wish to use LDAP as I need to support RBAC.


问:
Jquery validation plugin - TypeError: $(...).validate is not a function
My script throw errors:

TypeError: jQuery.validator is undefined additional-methods.js:20
  TypeError: $(...).validate is not a function index.php:115

Probably, I have mistake in jQuery code.

```<code><head>
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
</head>
<body>
            <form id="registerForm" method="post" action="logrej.php">
            <input name="login" type="text"/>
            <input name="nick" type="text"/>
            <input type="password" id="passw" name="password"/>
            <input type="password" name="retype" />
            <input type="submit" value="Zarejestruj!" />
            </form>
            <script>

                $("#registerForm").validate({
                    rules: {
                        login: {
                            required:true,
                            rangelenght: [4,20],
                            remote:"look.php"
                        },
                        nick : {
                            required:true,
                            rangelenght:[4,20],
                            remote:"look.php"
                        },
                        password: {
                            required:true,
                            rangelenght:[4.20]
                        },
                        retype: {
                            required:true,
                            equalTo:"#passw"
                        }
                    },
                    messages:{
                        login:{
                            required:"To pole jest wymagane!"
                        }
                    }
                })

            </script>
</code>```

答:
For me problem solved by changing http://ajax... into https://ajax... (add an S to http)</p>

```<code>https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js
</code>```

Body:
My script throw errors:

TypeError: jQuery.validator is undefined additional-methods.js:20
  TypeError: $(...).validate is not a function index.php:115

Probably, I have mistake in jQuery code.

            <form id="registerForm" method="post" action="logrej.php">
            <input name="login" type="text"/>
            <input name="nick" type="text"/>
            <input type="password" id="passw" name="password"/>
            <input type="password" name="retype" />
            <input type="submit" value="Zarejestruj!" />
            </form>

Body:
For me problem solved by changing http://ajax... into https://ajax... (add an S to http)

https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js


问:
Kafka log retention time per topic in server.properties
I would like to lower the retention period for one of the Kafka topics. I want the rest of the topics to still use the default retention time (7 days).
I know that we can set this through terminal: bin/kafka-topics.sh --zookeeper XXX --alter --topic XXXX --config retention.ms=86400000.
I was wondering if there is a way to do this so that it is set in server.properties and can be used in the future. For example, for the default retention time, we have log.retention.minutes = XXX.

EDIT: after some research, I noticed that per-topic configurations should better be done this way in ZK (https://issues.apache.org/jira/browse/KAFKA-554). But I'm still wondering if I can do this programmatically rather than using kafka-topics.sh.

答: Using https://kafka.apache.org/0110/javadoc/index.html?org/apache/kafka/clients/admin/AdminClient.html you can create your own programmatic solution but I don't believe there's any sort of Kafka configuration that'd do it for you. You could also use a tool like https://github.com/yahoo/kafka-manager. </p>


问:
Access SQL query to SELECT from one table and INSERT into another
Below is my query.  Access does not like it, giving me the error Syntax error (missing operator) in query expression 'answer WHERE question = 1'.

Hopefully you can see what I am trying to do.  Please pay particular attention to 3rd, 4th, and 5th lines under the SELECT statement.

```<code>INSERT INTO Table2 (respondent,1,2,3-1,3-2,3-3,4,5)
SELECT respondent,
answer WHERE question = 1,
answer WHERE question = 2,
answer WHERE answer = 'text 1' AND question = 3,
answer WHERE answer = 'text 2' AND question = 3,
answer WHERE answer = 'text 3' AND question = 3,
answer WHERE question = 4,
longanswer WHERE question 5 FROM Table1 GROUP BY respondent;
</code>```

UPDATE:

I have made a little progress with this, but I still cannot get my data in the format I really want.  I used several Iif statements to get as far as I am now, but GROUP BY simply isn't working the way I would expect it to.  I have also tried variations on my SELECT statement (like SELECT DISTINCT TOP 100 PERCENT and TRANSFORM) but I guess I am not using them correctly because I always get errors.  Here is what my data looks like now:

All I need to do now is smash all the similar respondent rows together (that is, respondent rows that have the same number) so all the cells that are empty are removed.

答:
Finally got this all sorted out.  I was on the right track for a long time, but just wasn't getting it exactly right.  After removing some unneeded columns and performing some significant formatting I was able to run the following query to produce the results I needed.  Thanks for all your suggestions.</p>

```<code>TRANSFORM Max(Sheet1.[answer]) AS MaxOfanswer
SELECT Sheet1.[respondent], Max(Sheet1.[answer]) AS [Total Of answer]
FROM Sheet1
GROUP BY Sheet1.[respondent]
PIVOT Sheet1.[question];
</code>```

Body:
Below is my query.  Access does not like it, giving me the error Syntax error (missing operator) in query expression 'answer WHERE question = 1'.

Hopefully you can see what I am trying to do.  Please pay particular attention to 3rd, 4th, and 5th lines under the SELECT statement.

INSERT INTO Table2 (respondent,1,2,3-1,3-2,3-3,4,5)
SELECT respondent,
answer WHERE question = 1,
answer WHERE question = 2,
answer WHERE answer = 'text 1' AND question = 3,
answer WHERE answer = 'text 2' AND question = 3,
answer WHERE answer = 'text 3' AND question = 3,
answer WHERE question = 4,
longanswer WHERE question 5 FROM Table1 GROUP BY respondent;

UPDATE:

I have made a little progress with this, but I still cannot get my data in the format I really want.  I used several Iif statements to get as far as I am now, but GROUP BY simply isn't working the way I would expect it to.  I have also tried variations on my SELECT statement (like SELECT DISTINCT TOP 100 PERCENT and TRANSFORM) but I guess I am not using them correctly because I always get errors.  Here is what my data looks like now:

All I need to do now is smash all the similar respondent rows together (that is, respondent rows that have the same number) so all the cells that are empty are removed.

Body:
Finally got this all sorted out.  I was on the right track for a long time, but just wasn't getting it exactly right.  After removing some unneeded columns and performing some significant formatting I was able to run the following query to produce the results I needed.  Thanks for all your suggestions.

TRANSFORM Max(Sheet1.[answer]) AS MaxOfanswer
SELECT Sheet1.[respondent], Max(Sheet1.[answer]) AS [Total Of answer]
FROM Sheet1
GROUP BY Sheet1.[respondent]
PIVOT Sheet1.[question];


问:
Python Reading a text file
I wrote an applescript to generate a text file of all unwatched movies in my itunes library.  Here is the code of that script:

```<code>tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)
        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedTVShows to trackNames as text
        do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if

    set watchedEpisodes to tracks of playlist "Movies" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "Movies" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)

        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedMovies to trackNames as text
        do shell script "echo " & quoted form of unwatchedMovies & " > /Volumes/Data/Media/Kodi/unwatchedMovies.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if
end tell
</code>```

Here is my output file:

```<code>/Volumes/Data/Media/Movies/Thanks For Sharing.m4v
/Volumes/Data/Media/Movies/Thats My Boy.m4v
/Volumes/Data/Media/Movies/Think Like a Man.m4v
/Volumes/Data/Media/Movies/Think Like a Man Too.m4v
/Volumes/Data/Media/Movies/This Means War.m4v
/Volumes/Data/Media/Movies/Top Five.m4v
/Volumes/Data/Media/Movies/Trail of Blood.m4v
</code>```

My problem is reading this file.  I need to open it, and put it in a string so that I can search it wholeistically (ie, if I search for "Think Like a Man" I don't want a false positive on "Think Like a Man Too".

Anyway, here is my current python code (or at least a snippet of that code):

```<code>KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies:
        line = line.strip()
        print line
</code>```

Here is the output:

```<code>/Volumes/Data/Media/Movies/Trail of Blood.m4voo.m4v
</code>```

Clearly, it's opening and reading the file, but I'm not understanding why the snippet isn't providing a full "list" of what's in the text file.  Any thoughts as to what I'm doing wrong?

Here is the final answer.  Not sure exactly what's different than what I had before (mixing tabs and spaces maybe??).  Anyway, for future reference, this code:

```<code>with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as uwmovies:
    for line in uwmovies:
        line = line.replace("\n","")
        unwatchedmovies = line.split('\r')
        print unwatchedmovies
</code>```

Gave the output of this list:

```<code>['/Volumes/Data/Media/Movies/Table 19.m4v', '/Volumes/Data/Media/Movies/Term Life.m4v', '/Volumes/Data/Media/Movies/Thanks For Sharing.m4v', '/Volumes/Data/Media/Movies/Thats My Boy.m4v', '/Volumes/Data/Media/Movies/Think Like a Man.m4v', '/Volumes/Data/Media/Movies/Think Like a Man Too.m4v', '/Volumes/Data/Media/Movies/This Means War.m4v', '/Volumes/Data/Media/Movies/Top Five.m4v', '/Volumes/Data/Media/Movies/Trail of Blood.m4v']
</code>```

which was exactly what I needed.  I list with no "\r" or "\n"'s.  Thanks for the help!

答:
Is this your actual code snippet?

```<code>KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies:
        line = line.strip()
    print line
</code>```

This would only print the last line of your file. Note, print line is only indented one tab.

Title: Python Reading a text file

Body:
I wrote an applescript to generate a text file of all unwatched movies in my itunes library.  Here is the code of that script:

tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)
        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedTVShows to trackNames as text
        do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if

    set watchedEpisodes to tracks of playlist "Movies" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "Movies" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set tmp to location of anEpisode as text
            set posixtmp to POSIX path of tmp
            set end of trackNames to (posixtmp as text)

        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedMovies to trackNames as text
        do shell script "echo " & quoted form of unwatchedMovies & " > /Volumes/Data/Media/Kodi/unwatchedMovies.txt"
        #display dialog trackNames as text
        set AppleScript's text item delimiters to TID
    end if
end tell

Here is my output file:

/Volumes/Data/Media/Movies/Thanks For Sharing.m4v
/Volumes/Data/Media/Movies/Thats My Boy.m4v
/Volumes/Data/Media/Movies/Think Like a Man.m4v
/Volumes/Data/Media/Movies/Think Like a Man Too.m4v
/Volumes/Data/Media/Movies/This Means War.m4v
/Volumes/Data/Media/Movies/Top Five.m4v
/Volumes/Data/Media/Movies/Trail of Blood.m4v

My problem is reading this file.  I need to open it, and put it in a string so that I can search it wholeistically (ie, if I search for "Think Like a Man" I don't want a false positive on "Think Like a Man Too".

Anyway, here is my current python code (or at least a snippet of that code):

KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies:
        line = line.strip()
        print line

Here is the output:

/Volumes/Data/Media/Movies/Trail of Blood.m4voo.m4v

Clearly, it's opening and reading the file, but I'm not understanding why the snippet isn't providing a full "list" of what's in the text file.  Any thoughts as to what I'm doing wrong?

Here is the final answer.  Not sure exactly what's different than what I had before (mixing tabs and spaces maybe??).  Anyway, for future reference, this code:

with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as uwmovies:
    for line in uwmovies:
        line = line.replace("\n","")
        unwatchedmovies = line.split('\r')
        print unwatchedmovies

Gave the output of this list:

['/Volumes/Data/Media/Movies/Table 19.m4v', '/Volumes/Data/Media/Movies/Term Life.m4v', '/Volumes/Data/Media/Movies/Thanks For Sharing.m4v', '/Volumes/Data/Media/Movies/Thats My Boy.m4v', '/Volumes/Data/Media/Movies/Think Like a Man.m4v', '/Volumes/Data/Media/Movies/Think Like a Man Too.m4v', '/Volumes/Data/Media/Movies/This Means War.m4v', '/Volumes/Data/Media/Movies/Top Five.m4v', '/Volumes/Data/Media/Movies/Trail of Blood.m4v']

which was exactly what I needed.  I list with no "\r" or "\n"'s.  Thanks for the help!

Body:
Is this your actual code snippet?

KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies:
        line = line.strip()
    print line

This would only print the last line of your file. Note, print line is only indented one tab.


问:
Writing Spark Dataframe directly to HIVE is taking too much time
I am writing 2 dataframes from Spark directly to Hive using PySpark. The first df has only one row and 7 columns. The second df has 20M rows and 20 columns. It took 10 mins to write the 1 df(1row) and around 30Mins to write 1M rows in the second DF. I dont know how long it will take to write the entire 20M, I killed the code before it can complete.

I have tried two approaches to write the df. I also cached the df to see if it would make the write faster but didn't seem to have any effect:

```<code>df_log.write.mode("append").insertInto("project_alpha.sends_log_test")
</code>```

2nd Method

```<code>#df_log.registerTempTable("temp2")
#df_log.createOrReplaceTempView("temp2")
sqlContext.sql("insert into table project_alpha.sends_log_test select * from temp2")
</code>```

In the 2nd approach I tried using both registerTempTable() as well as createOrReplaceTempView() but there was no difference in the run time.

Is there a way to write it faster or more efficiently. Thanks.

答:
Are you sure the final tables are cached? It might be the issue that before writing the data it calculates the whole pipeline. You can check that in terminal/console where Spark runs.

Also, please check if the table you append to on Hive is not a temporary view - then it could be the issue of recalculating the view before appending new rows.
When I write data to Hive I always use:

```<code>df.write.saveAsTable('schema.table', mode='overwrite')
</code>```

Please try:

```<code>df.write.saveAsTable('schema.table', mode='append')
</code>```

Body:
I am writing 2 dataframes from Spark directly to Hive using PySpark. The first df has only one row and 7 columns. The second df has 20M rows and 20 columns. It took 10 mins to write the 1 df(1row) and around 30Mins to write 1M rows in the second DF. I dont know how long it will take to write the entire 20M, I killed the code before it can complete.

I have tried two approaches to write the df. I also cached the df to see if it would make the write faster but didn't seem to have any effect:

df_log.write.mode("append").insertInto("project_alpha.sends_log_test")

2nd Method

#df_log.registerTempTable("temp2")
#df_log.createOrReplaceTempView("temp2")
sqlContext.sql("insert into table project_alpha.sends_log_test select * from temp2")

In the 2nd approach I tried using both registerTempTable() as well as createOrReplaceTempView() but there was no difference in the run time.

Is there a way to write it faster or more efficiently. Thanks.

Body:
Are you sure the final tables are cached? It might be the issue that before writing the data it calculates the whole pipeline. You can check that in terminal/console where Spark runs.

Also, please check if the table you append to on Hive is not a temporary view - then it could be the issue of recalculating the view before appending new rows.
When I write data to Hive I always use:

df.write.saveAsTable('schema.table', mode='overwrite')

Please try:

df.write.saveAsTable('schema.table', mode='append')


问:
Copy database from one server to another using c#
I'm trying to create a windows application that copies a database from one server to another using the Transfer object
but end up having "The Integration Services component is not installed or you do not have permission to use it" error.
both servers have enterprise edition of sql server 2005 and the integration services component installed, the connection logins have full permissions as well. I really don't know what goes wrong here

```<code>            Server backFromServer = new Server(@"xx.xx.xx.xx");
            Server backToServer = new Server(@"xx.xx.xx.xx");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "username";
            backFromServer.ConnectionContext.Password = "password";

            backToServer.ConnectionContext.LoginSecure = false;
            backToServer.ConnectionContext.Login = "username";
            backToServer.ConnectionContext.Password = "password";

            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["databasesource"];

            Database backToDb = new Database();
            backToDb = backToServer.Databases["databasedest"];

            EventLog.WriteEntry(eventLogSource,"Loading databases successful!", EventLogEntryType.Information);

            Transfer dataTransfer = new Transfer(backFromDb);
            dataTransfer.CopyAllTables = true;
            dataTransfer.CopyAllObjects = false;
            dataTransfer.CopyData = true;
            dataTransfer.CopyAllUserDefinedDataTypes = true;
            dataTransfer.CopyAllStoredProcedures = false;

            dataTransfer.DropDestinationObjectsFirst = true;

            dataTransfer.Options.WithDependencies = false;

            dataTransfer.DestinationServer = backToServer.Name;
            dataTransfer.DestinationDatabase = backToDb.Name;
            dataTransfer.DestinationLoginSecure = false;
            dataTransfer.DestinationLogin = "username";
            dataTransfer.DestinationPassword = "password";

            EventLog.WriteEntry(eventLogSource,"Transfer configuration successful, starting to transfer!", EventLogEntryType.Information);

            dataTransfer.TransferData();//here causes the error

            EventLog.WriteEntry(eventLogSource, "Transfer successful!", EventLogEntryType.Information);
</code>```

I managed to find a solution
so the app does this:
step 1. backup the database into a .bak file by using the Backup class

```<code> Server backFromServer = new Server(@"server");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "un";
            backFromServer.ConnectionContext.Password = "psd";
            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["dbname"];

            Backup bkpDatabase = new Backup();
            bkpDatabase.Action = BackupActionType.Database;
            bkpDatabase.Database = backFromDb.Name;
            bkpDatabase.Incremental = false;
            bkpDatabase.LogTruncation = BackupTruncateLogType.Truncate;
            bkpDatabase.Initialize = true;

            BackupDeviceItem bkpDevice = new BackupDeviceItem(@"c:\backup.bak", DeviceType.File);

            bkpDatabase.Devices.Add(bkpDevice);
            bkpDatabase.SqlBackup(backFromServer);

            EventLog.WriteEntry(eventLogSource, "Create database backup file successful!", EventLogEntryType.Information);
</code>```

step 2. Since the file is in the source server, download the file.
step 3. restore the database by using t-sql.
step 4. fire up a scheduled task that runs the app on daily basis.
  here is the t-sql script:
USE master
ALTER DATABASE [DBName] SET Single_User WITH Rollback Immediate
RESTORE DATABASE [DBName] FROM DISK = N'filepath' WITH REPLACE, FILE = 1,  NOUNLOAD,  STATS = 10
ALTER DATABASE [DBName] SET Multi_User

答: Does the box you're running the application on have IS installed?

Body:
I'm trying to create a windows application that copies a database from one server to another using the Transfer object
but end up having "The Integration Services component is not installed or you do not have permission to use it" error.
both servers have enterprise edition of sql server 2005 and the integration services component installed, the connection logins have full permissions as well. I really don't know what goes wrong here

            Server backFromServer = new Server(@"xx.xx.xx.xx");
            Server backToServer = new Server(@"xx.xx.xx.xx");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "username";
            backFromServer.ConnectionContext.Password = "password";

            backToServer.ConnectionContext.LoginSecure = false;
            backToServer.ConnectionContext.Login = "username";
            backToServer.ConnectionContext.Password = "password";

            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["databasesource"];

            Database backToDb = new Database();
            backToDb = backToServer.Databases["databasedest"];

            EventLog.WriteEntry(eventLogSource,"Loading databases successful!", EventLogEntryType.Information);

            Transfer dataTransfer = new Transfer(backFromDb);
            dataTransfer.CopyAllTables = true;
            dataTransfer.CopyAllObjects = false;
            dataTransfer.CopyData = true;
            dataTransfer.CopyAllUserDefinedDataTypes = true;
            dataTransfer.CopyAllStoredProcedures = false;

            dataTransfer.DropDestinationObjectsFirst = true;

            dataTransfer.Options.WithDependencies = false;

            dataTransfer.DestinationServer = backToServer.Name;
            dataTransfer.DestinationDatabase = backToDb.Name;
            dataTransfer.DestinationLoginSecure = false;
            dataTransfer.DestinationLogin = "username";
            dataTransfer.DestinationPassword = "password";

            EventLog.WriteEntry(eventLogSource,"Transfer configuration successful, starting to transfer!", EventLogEntryType.Information);

            dataTransfer.TransferData();//here causes the error

            EventLog.WriteEntry(eventLogSource, "Transfer successful!", EventLogEntryType.Information);

I managed to find a solution
so the app does this:
step 1. backup the database into a .bak file by using the Backup class

 Server backFromServer = new Server(@"server");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "un";
            backFromServer.ConnectionContext.Password = "psd";
            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["dbname"];

            Backup bkpDatabase = new Backup();
            bkpDatabase.Action = BackupActionType.Database;
            bkpDatabase.Database = backFromDb.Name;
            bkpDatabase.Incremental = false;
            bkpDatabase.LogTruncation = BackupTruncateLogType.Truncate;
            bkpDatabase.Initialize = true;

            BackupDeviceItem bkpDevice = new BackupDeviceItem(@"c:\backup.bak", DeviceType.File);

            bkpDatabase.Devices.Add(bkpDevice);
            bkpDatabase.SqlBackup(backFromServer);

            EventLog.WriteEntry(eventLogSource, "Create database backup file successful!", EventLogEntryType.Information);

step 2. Since the file is in the source server, download the file.
step 3. restore the database by using t-sql.
step 4. fire up a scheduled task that runs the app on daily basis.
  here is the t-sql script:
USE master
ALTER DATABASE [DBName] SET Single_User WITH Rollback Immediate
RESTORE DATABASE [DBName] FROM DISK = N'filepath' WITH REPLACE, FILE = 1,  NOUNLOAD,  STATS = 10
ALTER DATABASE [DBName] SET Multi_User


问:
Bad Request Error on POST request in Javascript
I am trying to do a POST request and I am getting a "Bad Request" error. If anyone could tell me what I am doing wrong here, I would be grateful.

```<code>function mkSentiTopics() {
    dta['n_clusters'] = 3;
    $.ajax({
        type: "POST",
        url: "http://saxonydemoubuntu.southcentralus.cloudapp.azure.com/sentitopic",
        data: JSON.stringify(dta),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(response) {
            alert("success");
        },
        beforeSend: function() {

        },
        error: function(xhr, stats) {
            alert("error");
        }
    });
}
</code>```

"dta" is a dictionary

```<code>// dta["sentis"] is a list of numbers
// dta["texts"] is a list of strings
// dta["n_clusters"] is an int.
</code>```

答:
The error indicates that the structure of the payload you are sending to the server does not match what it expects, so it rejects it. Not knowing the API signature, we can't help with that.

However, I'm going to take a shot in the dark and make the following suggestion based on this part of your post:

```<code>// dta["sentis"] is a list of numbers
// dta["texts"] is a list of strings
// dta["n_clusters"] is an int.
</code>```

When you JSON.stringify(dta), ensure that the output exactly matches what the API expects, noting that JSON only knows about boolean, array, object, string and number, further noting that true !== "true", 1 !== "1" and so on.

Example:

let dta = {                 // Note object wrapper
  sentis: [1, 2, 3, 4],     // Note lack of ""
  texts: ["a", "b", "c"],   // Note presence of ""
  n_clusters: 5             // 'Naked' number
}

console.log(JSON.stringify(dta, 0, 1)); // Note that "dta" is not a root key```

If your API requires that the root key "dta" is present, or that the structure is different, modify your dta object accordingly.

Body:
I am trying to do a POST request and I am getting a "Bad Request" error. If anyone could tell me what I am doing wrong here, I would be grateful.

function mkSentiTopics() {
    dta['n_clusters'] = 3;
    $.ajax({
        type: "POST",
        url: "http://saxonydemoubuntu.southcentralus.cloudapp.azure.com/sentitopic",
        data: JSON.stringify(dta),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(response) {
            alert("success");
        },
        beforeSend: function() {

        },
        error: function(xhr, stats) {
            alert("error");
        }
    });
}

"dta" is a dictionary

// dta["sentis"] is a list of numbers
// dta["texts"] is a list of strings
// dta["n_clusters"] is an int.

Body:
The error indicates that the structure of the payload you are sending to the server does not match what it expects, so it rejects it. Not knowing the API signature, we can't help with that.

However, I'm going to take a shot in the dark and make the following suggestion based on this part of your post:

// dta["sentis"] is a list of numbers
// dta["texts"] is a list of strings
// dta["n_clusters"] is an int.

When you JSON.stringify(dta), ensure that the output exactly matches what the API expects, noting that JSON only knows about boolean, array, object, string and number, further noting that true !== "true", 1 !== "1" and so on.

Example:

let dta = {                 // Note object wrapper
  sentis: [1, 2, 3, 4],     // Note lack of ""
  texts: ["a", "b", "c"],   // Note presence of ""
  n_clusters: 5             // 'Naked' number
}

console.log(JSON.stringify(dta, 0, 1)); // Note that "dta" is not a root key

If your API requires that the root key "dta" is present, or that the structure is different, modify your dta object accordingly.


问:
angular 2 generic click event in child component
There is a child component which is used in many pages of an angular web app. The child component has a (click) event which calls a function. Each page that consist of this child component is calling a different function with different parameters on click event.

How can I make this (click) event generic or dynamic that it calls the different function if the parent is different?

```<code>// In one component
(click)="saveData(types, functions)"

// On another component
(click)="showFunctions(index, areas, types)"
</code>```

Using a single child component in multiple pages with different click event, how we can do this?

Thank you in advance.

答:
Child:

```<code><button type="button" (click)="onMyClick()">Click<button>

@Output() myClick = new EventEmitter();

onMyClick() {
    this.myClick.emit();
}
</code>```

Parent:

```<code><my-child-cmp (myClick)="firstFunction()"></my-child-cmp>

firstFunction() {
   // whatever
}
</code>```

Parent2:

```<code><my-child-cmp (myClick)="secondFunction()"></my-child-cmp>

secondFunction() {
   // whatever
}
</code>```

Hope it helps. Let me know if you need more details.

By the way if you need to send some data from child to your parent you can do smth like this:

Child:

```<code><button type="button" (click)="onMyClick()">Click<button>

@Output() myClick = new EventEmitter();

onMyClick() {
    this.myClick.emit(something);
}
</code>```

Parent:

```<code><my-child-cmp (myClick)="firstFunction($event)"></my-child-cmp>

firstFunction(event: Event) {
   console.log(event); // You will see something here))

}
</code>```

UPDATE:

If we need send data from parent to child

Parent

```<code>data: any;

ngOnInit() {
  this.data = 'hello world';
}

<app-child [settings]="data"></app-child>
</code>```

Child:

```<code>@Input() settings: any;

ngOnInit() {
  console.log(this.settings);
}
</code>```

Body:
There is a child component which is used in many pages of an angular web app. The child component has a (click) event which calls a function. Each page that consist of this child component is calling a different function with different parameters on click event.

How can I make this (click) event generic or dynamic that it calls the different function if the parent is different?

// In one component
(click)="saveData(types, functions)"

// On another component
(click)="showFunctions(index, areas, types)"

Using a single child component in multiple pages with different click event, how we can do this?

Thank you in advance.

Body:
Child:

<button type="button" (click)="onMyClick()">Click<button>

@Output() myClick = new EventEmitter();

onMyClick() {
    this.myClick.emit();
}

Parent:

<my-child-cmp (myClick)="firstFunction()"></my-child-cmp>

firstFunction() {
   // whatever
}

Parent2:

<my-child-cmp (myClick)="secondFunction()"></my-child-cmp>

secondFunction() {
   // whatever
}

Hope it helps. Let me know if you need more details.

By the way if you need to send some data from child to your parent you can do smth like this:

Child:

<button type="button" (click)="onMyClick()">Click<button>

@Output() myClick = new EventEmitter();

onMyClick() {
    this.myClick.emit(something);
}

Parent:

<my-child-cmp (myClick)="firstFunction($event)"></my-child-cmp>

firstFunction(event: Event) {
   console.log(event); // You will see something here))

}

UPDATE:

If we need send data from parent to child

Parent

data: any;

ngOnInit() {
  this.data = 'hello world';
}

<app-child [settings]="data"></app-child>

Child:

@Input() settings: any;

ngOnInit() {
  console.log(this.settings);
}

ContentLicense: CC BY-SA 4.0


答:
Try calling .read() on the file you open and then split the content up on \n (newline)

```<code>KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies.read().split('\n'):
        line = line.strip()
        print line
</code>```

But this is probably enough for your usecase:

```<code>KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    umovies_content = umovies.read()
    print umovies_content
</code>```

Title: Python Reading a text file

Body:
Try calling .read() on the file you open and then split the content up on \n (newline)

KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    for line in umovies.read().split('\n'):
        line = line.strip()
        print line

But this is probably enough for your usecase:

KODIFOLDER="/Volumes/Data/Media/Kodi"
with open(KODIFOLDER + "/unwatchedMovies.txt", 'r') as umovies:
    umovies_content = umovies.read()
    print umovies_content


问:
Ionic App convert JSON to array
I'm pretty new to both Ionic and Angular so please excuse if this question doesn't make much sense.

Platform : Ionic 3.

I have a provider : rest.ts as follows

```<code>getLights() {
  return new Promise(resolve => {
    this.http.get(this.apiUrl+'/lights').subscribe(data => {
      resolve(data);
    }, err => {
      console.log(err);
    });
  });
}
</code>```

This returns the following data (sensitive info removed)

```<code>{
    "1": {
        "state": {
            "on": false,
            "bri": 98,
            "alert": "none",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Dimmable light",
        "name": "Lion",
        "modelid": "LWB010",
        "manufacturername": "Philips",
    },
    "2": {
        "state": {
            "on": true,
            "bri": 100,
            "alert": "none",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Dimmable light",
        "name": "Brutus",
        "modelid": "LWB010",
        "manufacturername": "Philips",
    },
    "3": {
        "state": {
            "on": true,
            "bri": 254,
            "hue": 8418,
            "sat": 140,
            "effect": "none",
            "xy": [
                0.4573,
                0.41
            ],
            "ct": 366,
            "alert": "none",
            "colormode": "ct",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Extended color light",
        "name": "Hue lightstrip plus 1",
        "modelid": "LST002",
        "manufacturername": "Philips"
    }
}
</code>```

An ionic page 'list' made up of : list.ts

```<code>export class ListPage {

  lights: any;
  icons: string[];

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public restProvider: RestProvider) {

    this.getLights();
  }

  getLights() {
    this.restProvider.getLights()
    .then(data => {
      this.lights = data;
      console.log(this.lights);
    });
  }

}
</code>```

and list.html :

```<code><ion-content>
  <ion-list inset>
    <ion-item *ngFor="let light of lights">
      <h2>{{light.name}}</h2>
      <p>{{light.type}}</p>
    </ion-item>
  </ion-list>
</ion-content>
</code>```

Although the console log statement displays the JSON correctly, I can't iterate it using ngFor in list.html due to the following error.

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

I realise I need to convert the JSON into a javascript array, but not sure where or how to do this.  Any pointers would be very much appreciated.

答:
There are a variety of ways you can convert an Array-like object to an Array depending on how it's composed. In this case you could do it pretty easily with:

```<code>data => resolve(Object.keys(data).map(key => data[key]))
</code>```

This will resolve with an array of the objects from the promise and should work with your component.

I'll point out that you don't have to use your own Promise, you can use the Observable method toPromise:

```<code>getLights() {
  return this.http.get(`${this.apiUrl}/lights`).map(data =>
    Object.keys(data).map(key => data[key])
  ).toPromise();
}
</code>```

In fact you don't even need to use a promise and you can just subscribe to getLights instead.

```<code>this.restProvider.getLights().subscribe(data => {
  this.lights = data;
});
</code>```

NOTE:

If this is not using Angular 5 I think you need to do:

```<code>this.http.get(url).map(response => response.json())
</code>```

in the Observable chain as well.

Title: Ionic App convert JSON to array

Body:
I'm pretty new to both Ionic and Angular so please excuse if this question doesn't make much sense.

Platform : Ionic 3.

I have a provider : rest.ts as follows

getLights() {
  return new Promise(resolve => {
    this.http.get(this.apiUrl+'/lights').subscribe(data => {
      resolve(data);
    }, err => {
      console.log(err);
    });
  });
}

This returns the following data (sensitive info removed)

{
    "1": {
        "state": {
            "on": false,
            "bri": 98,
            "alert": "none",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Dimmable light",
        "name": "Lion",
        "modelid": "LWB010",
        "manufacturername": "Philips",
    },
    "2": {
        "state": {
            "on": true,
            "bri": 100,
            "alert": "none",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Dimmable light",
        "name": "Brutus",
        "modelid": "LWB010",
        "manufacturername": "Philips",
    },
    "3": {
        "state": {
            "on": true,
            "bri": 254,
            "hue": 8418,
            "sat": 140,
            "effect": "none",
            "xy": [
                0.4573,
                0.41
            ],
            "ct": 366,
            "alert": "none",
            "colormode": "ct",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Extended color light",
        "name": "Hue lightstrip plus 1",
        "modelid": "LST002",
        "manufacturername": "Philips"
    }
}

An ionic page 'list' made up of : list.ts

export class ListPage {

  lights: any;
  icons: string[];

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public restProvider: RestProvider) {

    this.getLights();
  }

  getLights() {
    this.restProvider.getLights()
    .then(data => {
      this.lights = data;
      console.log(this.lights);
    });
  }

}

and list.html :

<ion-content>
  <ion-list inset>
    <ion-item *ngFor="let light of lights">

{{light.name}}

{{light.type}}

    </ion-item>
  </ion-list>
</ion-content>

Although the console log statement displays the JSON correctly, I can't iterate it using ngFor in list.html due to the following error.

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

I realise I need to convert the JSON into a javascript array, but not sure where or how to do this.  Any pointers would be very much appreciated.

Body:
There are a variety of ways you can convert an Array-like object to an Array depending on how it's composed. In this case you could do it pretty easily with:

data => resolve(Object.keys(data).map(key => data[key]))

This will resolve with an array of the objects from the promise and should work with your component.

I'll point out that you don't have to use your own Promise, you can use the Observable method toPromise:

getLights() {
  return this.http.get(`${this.apiUrl}/lights`).map(data =>
    Object.keys(data).map(key => data[key])
  ).toPromise();
}

In fact you don't even need to use a promise and you can just subscribe to getLights instead.

this.restProvider.getLights().subscribe(data => {
  this.lights = data;
});

NOTE:

If this is not using Angular 5 I think you need to do:

this.http.get(url).map(response => response.json())

in the Observable chain as well.


问:
Amazon login and logout scenario using selenium webdriver
I am new to selenium.
I am trying to automate amazon login and log out.
I am facing couple of problems.

1.In login page the button "continue" appears after username when I try to login for  first time.
But later when I try to login for second time , its does not appear.
How to handle this.
Here is the code I have written so far:

```<code>public void logindetails()
{

        Datafile d=new Datafile("C:\\Users\\kirruPC\\selenium divers\\Data.xlsx",0);

        String uname= d.username(0, 0);
        WebElement u=driver.findElement(useid);
        u.sendKeys(uname);
        u.click();

        if(driver.findElement(By.xpath(".//*[@id='continue']")).isDisplayed()==true)
        {
            driver.findElement(By.id("continue")).click();
            String psw=d.pass(0,1);
            driver.findElement(password).sendKeys(psw);
        }
        else
        {
            String psw=d.pass(0,1);
            driver.findElement(password).sendKeys(psw);
        }
}
</code>```

Unable to locate sign Out element.

Below is the code I have written to move to sign out link and click:

```<code>     public void logout() throws Exception
     {

          Actions a= new Actions(driver);
          WebElement ele=driver.findElement(By.xpath(".//*[@id='nav-link-accountList']"));
          a.moveToElement(ele).build().perform();

          driver.findElement(By.xpath(".//*[@id='nav-al-your-account']"));
          Thread.sleep(3000);
          driver.findElement(By.xpath(".//*[@id='nav-al-your-account']/a[22]")).click();
     }
</code>```

Please help me

Thanks in advance

答:
First of all, there is a high change that the element you are searching for might not exist at all in the page, so first let's check if the element exist (if the element does not exist, an exception is thrown, so let's add a handle for that as well). For all that, create a function like so:

```<code>public bool ElementExists(By locator)
{
    try
    {
        driver.findElement(locator);
        //If no exception is thrown here, element exists, so return true
        return true;
    }
    catch (NoSuchElementException ex)
    {
        return false;
    {
}
</code>```

Now that we have a function that can safely check if an element exists without getting an exception, you can use it to determine if you will run the code handling the element.
Function isDisplayed() already returns a bool, so checking equality with true is not necessary.

```<code>if(ElementExists(By.xpath(...)).isDisplayed())
{
    if(driver.findElement(By.xpath(".//*[@id='continue']")).isDisplayed())
    {
        driver.findElement(By.id("continue")).click();
    }
}
//The code below will run either way, so move it out of the if statement
String psw=d.pass(0,1);
driver.findElement(password).sendKeys(psw);
</code>```

As for the second part of your question, your code can be simplified by just, searching for the element and then clicking it like so:

```<code>driver.findElement(By.xpath(".//*[@id='nav-al-your-account']/a[22]")).click();
</code>```

If you will, double-check the xpath or "catch" the element by an ID.

Body:
I am new to selenium.
I am trying to automate amazon login and log out.
I am facing couple of problems.

1.In login page the button "continue" appears after username when I try to login for  first time.
But later when I try to login for second time , its does not appear.
How to handle this.
Here is the code I have written so far:

public void logindetails()
{

        Datafile d=new Datafile("C:\\Users\\kirruPC\\selenium divers\\Data.xlsx",0);

        String uname= d.username(0, 0);
        WebElement u=driver.findElement(useid);
        u.sendKeys(uname);
        u.click();

        if(driver.findElement(By.xpath(".//*[@id='continue']")).isDisplayed()==true)
        {
            driver.findElement(By.id("continue")).click();
            String psw=d.pass(0,1);
            driver.findElement(password).sendKeys(psw);
        }
        else
        {
            String psw=d.pass(0,1);
            driver.findElement(password).sendKeys(psw);
        }
}

Unable to locate sign Out element.

Below is the code I have written to move to sign out link and click:

     public void logout() throws Exception
     {

          Actions a= new Actions(driver);
          WebElement ele=driver.findElement(By.xpath(".//*[@id='nav-link-accountList']"));
          a.moveToElement(ele).build().perform();

          driver.findElement(By.xpath(".//*[@id='nav-al-your-account']"));
          Thread.sleep(3000);
          driver.findElement(By.xpath(".//*[@id='nav-al-your-account']/a[22]")).click();
     }

Please help me

Thanks in advance

Body:
First of all, there is a high change that the element you are searching for might not exist at all in the page, so first let's check if the element exist (if the element does not exist, an exception is thrown, so let's add a handle for that as well). For all that, create a function like so:

public bool ElementExists(By locator)
{
    try
    {
        driver.findElement(locator);
        //If no exception is thrown here, element exists, so return true
        return true;
    }
    catch (NoSuchElementException ex)
    {
        return false;
    {
}

Now that we have a function that can safely check if an element exists without getting an exception, you can use it to determine if you will run the code handling the element.
Function isDisplayed() already returns a bool, so checking equality with true is not necessary.

if(ElementExists(By.xpath(...)).isDisplayed())
{
    if(driver.findElement(By.xpath(".//*[@id='continue']")).isDisplayed())
    {
        driver.findElement(By.id("continue")).click();
    }
}
//The code below will run either way, so move it out of the if statement
String psw=d.pass(0,1);
driver.findElement(password).sendKeys(psw);

As for the second part of your question, your code can be simplified by just, searching for the element and then clicking it like so:

driver.findElement(By.xpath(".//*[@id='nav-al-your-account']/a[22]")).click();

If you will, double-check the xpath or "catch" the element by an ID.


问:
How to download file from server using nodejs
I want to download file from other website to my pc using expressjs

I tried to use: res.download to download but it seems to be worked on my own server only

Here is my code:

```<code>res.download('http://apkleecher.com/download/dl.php?dl=com.instagram.android', 'folder', function(err){
                if (err) {
                    console.log(err);
                } else {

                }
            });
</code>```

And it return the error:

{ Error: ENOENT: no such file or directory, stat '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android'
    errno: -2,
    code: 'ENOENT',
    syscall: 'stat',
    path: '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android',
    expose: false,
    statusCode: 404,
    status: 404 }

In my guess, the problem is in the path of url.

答:
Turning my comment into an answer since it worked for you...

You can fetch a resource from a remote web server using either http.get() or the request() module in node.  If you like to use promises for your asynchronous operations, then the request-promise module is a promisified version of the request module and works great.

You can also use just plain http.get(), but it's a lot more work because you have to read the stream, rather the results yourself and install appropriate error handling, all of which the request() module does for you in one simple call.

Here's a simple example using the request-promise module:

```<code>const rp = require('request-promise');
rp('http://www.google.com').then(function (htmlString) {
    // Process html...
}).catch(function (err) {
    // process error here
});
</code>```

Body:
I want to download file from other website to my pc using expressjs

I tried to use: res.download to download but it seems to be worked on my own server only

Here is my code:

res.download('http://apkleecher.com/download/dl.php?dl=com.instagram.android', 'folder', function(err){
                if (err) {
                    console.log(err);
                } else {

                }
            });

And it return the error:

{ Error: ENOENT: no such file or directory, stat '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android'
    errno: -2,
    code: 'ENOENT',
    syscall: 'stat',
    path: '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android',
    expose: false,
    statusCode: 404,
    status: 404 }

In my guess, the problem is in the path of url.

Body:
Turning my comment into an answer since it worked for you...

You can fetch a resource from a remote web server using either http.get() or the request() module in node.  If you like to use promises for your asynchronous operations, then the request-promise module is a promisified version of the request module and works great.

You can also use just plain http.get(), but it's a lot more work because you have to read the stream, rather the results yourself and install appropriate error handling, all of which the request() module does for you in one simple call.

Here's a simple example using the request-promise module:

const rp = require('request-promise');
rp('http://www.google.com').then(function (htmlString) {
    // Process html...
}).catch(function (err) {
    // process error here
});


问:
How to figure out what IIS Express instance is using a port?
I want to kill a running IIS Instance programmatically that is occupying a specific port, but it seems there is no way to figure out what IIS Instance is using a specific port.

netstat.exe just shows that the process is having the PID 4, but that's the system process. "netsh http show urlacl" does not display the occupied port at all.

The IIS Express Tray program knows this somehow. When I try to start another IIS Express instance while the port is occupied I get the following error:

"Port '40000' is already being used by process 'IIS Express' (process ID '10632').

Anyone got a clue how I can get this information?

答:
It seems like the PID is 4 (System) because the actual listening socket is under a service called http.

I looked at what iisexpresstray.exe was using to provide a list of all running IISExpress applications. Thankfully it's managed .NET code (all in iisexpresstray.dll) that's easily decompiled.

It appears to have at least three different ways of getting the port number for a process:

Reading /port from the command-line arguments (unreliable as we know)

Running netsh http show servicestate view=requestq and parsing the output

Calling Microsoft.Web.RuntimeStatusClient.GetWorkerProcess(pid) and parsing the site URL

Unfortunately, most of the useful stuff in iisexpresstray.dll like the IisExpressHelper class is declared internal (although I imagine there're tools to generate wrappers or copy the assembly and publicize everything).

I opted to use Microsoft.Web.dll. It was in my GAC, though for some reason wasn't appearing in the list of assemblies available to add as a reference in Visual Studio, so I just copied the file out from my GAC. Once I had Microsoft.Web.dll it was just a matter of using this code:

```<code>    using (var runtimeStatusClient = new RuntimeStatusClient())
    {
      var workerProcess = runtimeStatusClient.GetWorkerProcess(process.Id);
      // Apparently an IISExpress process can run multiple sites/applications?
      var apps = workerProcess.RegisteredUrlsInfo.Select(r => r.Split('|')).Select(u => new { SiteName = u[0], PhysicalPath = u[1], Url = u[2] });
      // If we just assume one app
      return new Uri(apps.FirstOrDefault().Url).Port;
     }
</code>```

You can also call RuntimeClient.GetAllWorkerProcesses to retrieve only actual worker processes.

I looked into RegisteredUrlsInfo (in Microsoft.Web.dll) as well and found that it's using two COM interfaces,

IRsca2_Core (F90F62AB-EE00-4E4F-8EA6-3805B6B25CDD)

IRsca2_WorkerProcess (B1341209-7F09-4ECD-AE5F-3EE40D921870)

Lastly, I read about a version of Microsoft.Web.Administration apparently being able to read IISExpress application info, but information was very scarce, and the one I found on my system wouldn't even let me instantiate ServerManager without admin privileges.

Body:
It seems like the PID is 4 (System) because the actual listening socket is under a service called http.

I looked at what iisexpresstray.exe was using to provide a list of all running IISExpress applications. Thankfully it's managed .NET code (all in iisexpresstray.dll) that's easily decompiled.

It appears to have at least three different ways of getting the port number for a process:

Reading /port from the command-line arguments (unreliable as we know)

Running netsh http show servicestate view=requestq and parsing the output

Calling Microsoft.Web.RuntimeStatusClient.GetWorkerProcess(pid) and parsing the site URL

Unfortunately, most of the useful stuff in iisexpresstray.dll like the IisExpressHelper class is declared internal (although I imagine there're tools to generate wrappers or copy the assembly and publicize everything).

I opted to use Microsoft.Web.dll. It was in my GAC, though for some reason wasn't appearing in the list of assemblies available to add as a reference in Visual Studio, so I just copied the file out from my GAC. Once I had Microsoft.Web.dll it was just a matter of using this code:

    using (var runtimeStatusClient = new RuntimeStatusClient())
    {
      var workerProcess = runtimeStatusClient.GetWorkerProcess(process.Id);
      // Apparently an IISExpress process can run multiple sites/applications?
      var apps = workerProcess.RegisteredUrlsInfo.Select(r => r.Split('|')).Select(u => new { SiteName = u[0], PhysicalPath = u[1], Url = u[2] });
      // If we just assume one app
      return new Uri(apps.FirstOrDefault().Url).Port;
     }

You can also call RuntimeClient.GetAllWorkerProcesses to retrieve only actual worker processes.

I looked into RegisteredUrlsInfo (in Microsoft.Web.dll) as well and found that it's using two COM interfaces,

IRsca2_Core (F90F62AB-EE00-4E4F-8EA6-3805B6B25CDD)

IRsca2_WorkerProcess (B1341209-7F09-4ECD-AE5F-3EE40D921870)

Lastly, I read about a version of Microsoft.Web.Administration apparently being able to read IISExpress application info, but information was very scarce, and the one I found on my system wouldn't even let me instantiate ServerManager without admin privileges.


问:
Your current session has been expired. Magento2
I just migrate my site to localhost and everything working fine. but when i try to logged into  my admin pannel then its through me error like Your current session has been expired.

I removed all the cache from the folder also change the setting from database about session expiration time.

also we have tried each and every possible solution from this thread.

Thanks in advance.

答: Make sure the times on all your servers are in sync.  You do not need to update any tables.</p>


问:
confirm box multiple time after delete item - ajax
I have a menu in side of page, and this menu has many items to navigate.
Well, in a admin page, I have a table to manage those items.
When I delete an item in table (the delete was made in ajax), the item is deleted in table and menu side. I used the function load to load items in menu. But when I remove items two or more times, appears many confirm popup according the quantity of elements removed.

See the image. When I click in delete button, this item is removed in database and the table remove the item. When I delete an item for the first time, it show the confirm pop up one time and remove the item. Until here, thats correct. But when I delete the second, third ou more items, the confirm popup keeps active and appears many times according quantity of elements removed. Where is the mistake?

Menu Code:

```<code>echo '<div id="slide-out" class="side-nav sn-bg-4 fixed mdb-sidenav">
            <ul id="menu_ul" class="custom-scrollbar list-unstyled" style="max-height:100vh;">
                <!-- Side navigation links -->
                <li>
                    <ul id="side-menu" class="collapsible collapsible-accordion">
                    <li id="home" class="menu-item menu-item-type-custom menu-item-object-custom"><a class="collapsible-header waves-effect" href="/admin/view/main.php"><img src="/imgs/icones/ic_home.png">Home</a></li>';

    foreach ($Menu_array as $valor)
    {

        echo '<li id='. $valor->getCategoria()->getCat_id() .' class="menu-item menu-item-type-custom menu-item-object-custom'. $menu_filhos .'"><a class="collapsible-header waves-effect '"><img style="margin-right:10px; vertical-align: text-bottom; text-align:left" src="'.$valor->getCategoria()->getCat_img().'">'. $valor->getCategoria()->getCat_nome().'</a>';

            $array_SCat = [];
            $array_SCat = $valor->getlist_SCat();

            if((count($valor->getlist_SCat())) > 0)
            {
                echo '<div class="collapsible-body">
                        <ul class="sub-menu">';

                foreach($array_SCat as $val)
                {
                    echo '<li class="menu-item menu-item-type-post_type menu-item-object-page '"><a class="collapsible-header waves-effect" id='.$val->getSCat_id().' href="'.$variaveis->getDominio().'/'.$variaveis->getNome_site().'/admin/view/ld.php?id_cat='.$valor->getCategoria()->getCat_id().'&id_subcat='.$val->getSCat_id().'">'.$val->getSCat_nome().'</a></li>';
                }
                    </ul>
                </div>';
            }
        }
    }
        echo '</ul>
        </li>
        <!-- /. Side navigation links -->
        </ul>
    </div>';
</code>```

The table code to delete item:

```<code><table width="100%">
    <tbody>
         <tr>
              <td><a id="deleteItem" name="'.$val->getSCat_id().'">Delete</a></td>
         </tr>
</code>```

ajax code:

```<code>$(document).on("click", "#deleteItem", function(e) {

    e.preventDefault();

    var idItem = $(this).attr('name');
    var $tr = $(this).closest('tr');

    if (confirm('Deseja excluir o item?')) {

        $.ajax({
            url: '/admin/control/ajax/remove.php',
            type: 'POST',
            data: {id: idItem},
            dataType: 'html',
            success: function(response) {

                var result = $.trim(response);

                if(result === "success") {

                    $tr.find('td').fadeOut(800,function(){
                        $tr.remove();
                    });

                    $("body").load('#slide-out');

                } else if(result === "error") {

                    alert("Error.");

                }

            }

        });

    }

});
</code>```

Notice I did this in ajax:

```<code>$("body").load('#slide-out');
</code>```

The body calls the menu id slide-out to load.

答:
Try to change attribute id for "deleteItem" to class.
Here places:

Markup

```<code><td><a class="deleteItem">Delete</a></td>
</code>```

JS

$(document).on("click", ".deleteItem", function(e) {});

Body:
I have a menu in side of page, and this menu has many items to navigate.
Well, in a admin page, I have a table to manage those items.
When I delete an item in table (the delete was made in ajax), the item is deleted in table and menu side. I used the function load to load items in menu. But when I remove items two or more times, appears many confirm popup according the quantity of elements removed.

See the image. When I click in delete button, this item is removed in database and the table remove the item. When I delete an item for the first time, it show the confirm pop up one time and remove the item. Until here, thats correct. But when I delete the second, third ou more items, the confirm popup keeps active and appears many times according quantity of elements removed. Where is the mistake?

Menu Code:

echo '

Home
';

    foreach ($Menu_array as $valor)
    {

        echo '
getCategoria()->getCat_id() .' class="menu-item menu-item-type-custom menu-item-object-custom'. $menu_filhos .'">getCategoria()->getCat_img().'">'. $valor->getCategoria()->getCat_nome().'';

            $array_SCat = [];
            $array_SCat = $valor->getlist_SCat();

            if((count($valor->getlist_SCat())) > 0)
            {
                echo '

';

                foreach($array_SCat as $val)
                {
                    echo '
getSCat_id().' href="'.$variaveis->getDominio().'/'.$variaveis->getNome_site().'/admin/view/ld.php?id_cat='.$valor->getCategoria()->getCat_id().'&id_subcat='.$val->getSCat_id().'">'.$val->getSCat_nome().'
';
                }

';
            }
        }
    }
        echo '

';

The table code to delete item:

              getSCat_id().'">Delete

ajax code:

$(document).on("click", "#deleteItem", function(e) {

    e.preventDefault();

    var idItem = $(this).attr('name');
    var $tr = $(this).closest('tr');

    if (confirm('Deseja excluir o item?')) {

        $.ajax({
            url: '/admin/control/ajax/remove.php',
            type: 'POST',
            data: {id: idItem},
            dataType: 'html',
            success: function(response) {

                var result = $.trim(response);

                if(result === "success") {

                    $tr.find('td').fadeOut(800,function(){
                        $tr.remove();
                    });

                    $("body").load('#slide-out');

                } else if(result === "error") {

                    alert("Error.");

                }

            }

        });

    }

});

Notice I did this in ajax:

$("body").load('#slide-out');

The body calls the menu id slide-out to load.

Body:
Try to change attribute id for "deleteItem" to class.
Here places:

Markup

<td><a class="deleteItem">Delete</a></td>

JS

$(document).on("click", ".deleteItem", function(e) {});