问:
Error: Could not find or load main class - Youtube Data API example
I have downloaded the client library from here

And placed all the required .jar files in the libs folder.

I then downloaded Search.java example (mentioned here) and Auth.java

I was able to successfully compile Search.java and Auth.java, but when
I try to run it, I get this error: Error: Could not find or load main class [class name]

I have tried the following:

java com.google.api.services.samples.youtube.cmdline.data.Search

java Search

I still get the same error.

Current directory:

```<code>.
├── Auth.java
├── libs
├── Search.java
└── youtube.properties

1 directory, 3 files
</code>```

After compiling:

```<code>.
├── Auth.class
├── Auth.java
├── libs
├── Search$1.class
├── Search.class
├── Search.java
└── youtube.properties

1 directory, 6 files
</code>```

答:
Where did you compile those files? You need to locate Search.class. If there's package com.google.api.services.samples.youtube.cmdline.data declared in the file, then file iself should live in /com/google/api/services/samples/youtube/cmdline/data/ folder, and same would be true for the .class file once compiled. And you should then invoke java command from the location where such folder path starts.

Or alternatively you use some IDE like Eclipse/IntelliJ/NetBeans or other to import sample as project in there and let IDE take care of resolving all correctly.

Body:
I have downloaded the client library from here

And placed all the required .jar files in the libs folder.

I then downloaded Search.java example (mentioned here) and Auth.java

I was able to successfully compile Search.java and Auth.java, but when
I try to run it, I get this error: Error: Could not find or load main class [class name]

I have tried the following:

java com.google.api.services.samples.youtube.cmdline.data.Search

java Search

I still get the same error.

Current directory:

.
├── Auth.java
├── libs
├── Search.java
└── youtube.properties

1 directory, 3 files

After compiling:

.
├── Auth.class
├── Auth.java
├── libs
├── Search$1.class
├── Search.class
├── Search.java
└── youtube.properties

1 directory, 6 files


来源: stackexchange

问:
How to validate JWT during websocket request. .net core
I am working on a small .net core app that uses JWT authentication and websockets.

I have succesfully implemented generating and validating tokens for standard web api controllers. However I also want to validate the token for a WebSocket request which of course won't work with the [Authorize] attribute.

I have setup my middleware pipeline like this:

```<code>app.UseWebSockets();
app.Use(async (http, next) => {
      if (http.WebSockets.IsWebSocketRequest == false) {
          await next();
          return;
      }
      /// Handle websocket request here. How to check if token is valid?
});

// secretKey contains a secret passphrase only your server knows
var secretKey = .....;
var signKey = new SigningCredentials (
    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
    SecurityAlgorithms.HmacSha256
);

var tokenValidationParameters = new TokenValidationParameters {
    ValidateIssuer = false,
    ValidateAudience = false,

    // The signing key must match!
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = signKey.Key,

    // Validate the token expiry
    ValidateLifetime = true,

    // If you want to allow a certain amount of clock drift, set that here:
    ClockSkew = TimeSpan.FromMinutes(1),
};

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = tokenValidationParameters
});
</code>```

答:
I hope this can help someone, even though the post is kind of old.

I found out the answer, not after Googling, but Binging ! I inspired myself from this official code.

You can write your own class that handles authorization very simply, using the magic of JwtBearerOptions. This class (hopefully) contains everything you need to validate the JWTs by yourself.

So, you have to inject it as a Service, as well as using it to configure your Authentication. Something like that in your Startup.ConfigureServices:

```<code>this.JwtOptions = new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            TokenValidationParameters = yourTokenValidationParameters
        };
services.AddSingleton<JwtBearerOptions>(this.JwtOptions);
</code>```

Then, you have to create a class that is gonna Validate your Token (This is where my code was inspired). Let's call it a Backer, because it's got your back !:

```<code>public class JwtBearerBacker
{
    public JwtBearerOptions Options { get; private set; }

    public JwtBearerBacker(JwtBearerOptions options)
    {
        this.Options = options;
    }

    public bool IsJwtValid(string token)
    {
        List<Exception> validationFailures = null;
        SecurityToken validatedToken;
        foreach (var validator in Options.SecurityTokenValidators)
        {
            if (validator.CanReadToken(token))
            {
                ClaimsPrincipal principal;
                try
                {
                    principal = validator.ValidateToken(token, Options.TokenValidationParameters, out validatedToken);
                }
                catch (Exception ex)
                {
                    // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
                    if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null
                        && ex is SecurityTokenSignatureKeyNotFoundException)
                    {
                        Options.ConfigurationManager.RequestRefresh();
                    }

                    if (validationFailures == null)
                        validationFailures = new List<Exception>(1);
                    validationFailures.Add(ex);
                    continue;
                }
                return true;
            }
        }
        return false;
    }
}
</code>```

Then, in your Middleware, just access the request header, the JwtOptions dependency and call the Backer:

```<code> protected string ObtainAppTokenFromHeader(string authHeader)
    {
        if (string.IsNullOrWhiteSpace(authHeader) || !authHeader.Contains(" "))
            return null;
        string[] authSchemeAndJwt = authHeader.Split(' ');
        string authScheme = authSchemeAndJwt[0];
        if (authScheme != "Bearer")
            return null;
        string jwt = authSchemeAndJwt[1];
        return jwt;
    }

    protected async Task<bool> AuthorizeUserFromHttpContext(HttpContext context)
    {
        var jwtBearerOptions = context.RequestServices.GetRequiredService<JwtBearerOptions>() as JwtBearerOptions;
        string jwt = this.ObtainAppTokenFromHeader(context.Request.Headers["Authorization"]);
        if (jwt == null)
            return false;
        var jwtBacker = new JwtBearerBacker(jwtBearerOptions);
        return jwtBacker.IsJwtValid(jwt);
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.WebSockets.IsWebSocketRequest)
            return;
        if (!await this.AuthorizeUserFromHttpContext(context))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("The door is locked, dude. You're not authorized !");
            return;
        }
//... Whatever else you're doing in your middleware
       }
</code>```

Also, the AuthenticationTicket and any other information about the auth has been already handled by the framework's JwtBearerMiddleware, and will be returned anyway.

Finally, the client side. I advise you using a client library that actually supports additional HTTP Headers. For example, as far as I know, the W3C Javascript client does not provide this functionality.

Here you are! Thanks to Microsoft for its Open Source codebase.

ContentLicense: CC BY-SA 3.0

Body:
I am working on a small .net core app that uses JWT authentication and websockets.

I have succesfully implemented generating and validating tokens for standard web api controllers. However I also want to validate the token for a WebSocket request which of course won't work with the [Authorize] attribute.

I have setup my middleware pipeline like this:

app.UseWebSockets();
app.Use(async (http, next) => {
      if (http.WebSockets.IsWebSocketRequest == false) {
          await next();
          return;
      }
      /// Handle websocket request here. How to check if token is valid?
});

// secretKey contains a secret passphrase only your server knows
var secretKey = .....;
var signKey = new SigningCredentials (
    new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
    SecurityAlgorithms.HmacSha256
);

var tokenValidationParameters = new TokenValidationParameters {
    ValidateIssuer = false,
    ValidateAudience = false,

    // The signing key must match!
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = signKey.Key,

    // Validate the token expiry
    ValidateLifetime = true,

    // If you want to allow a certain amount of clock drift, set that here:
    ClockSkew = TimeSpan.FromMinutes(1),
};

app.UseJwtBearerAuthentication(new JwtBearerOptions {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = tokenValidationParameters
});

Body:
I hope this can help someone, even though the post is kind of old.

I found out the answer, not after Googling, but Binging ! I inspired myself from this official code.

You can write your own class that handles authorization very simply, using the magic of JwtBearerOptions. This class (hopefully) contains everything you need to validate the JWTs by yourself.

So, you have to inject it as a Service, as well as using it to configure your Authentication. Something like that in your Startup.ConfigureServices:

this.JwtOptions = new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            TokenValidationParameters = yourTokenValidationParameters
        };
services.AddSingleton<JwtBearerOptions>(this.JwtOptions);

Then, you have to create a class that is gonna Validate your Token (This is where my code was inspired). Let's call it a Backer, because it's got your back !:

public class JwtBearerBacker
{
    public JwtBearerOptions Options { get; private set; }

    public JwtBearerBacker(JwtBearerOptions options)
    {
        this.Options = options;
    }

    public bool IsJwtValid(string token)
    {
        List<Exception> validationFailures = null;
        SecurityToken validatedToken;
        foreach (var validator in Options.SecurityTokenValidators)
        {
            if (validator.CanReadToken(token))
            {
                ClaimsPrincipal principal;
                try
                {
                    principal = validator.ValidateToken(token, Options.TokenValidationParameters, out validatedToken);
                }
                catch (Exception ex)
                {
                    // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
                    if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null
                        && ex is SecurityTokenSignatureKeyNotFoundException)
                    {
                        Options.ConfigurationManager.RequestRefresh();
                    }

                    if (validationFailures == null)
                        validationFailures = new List<Exception>(1);
                    validationFailures.Add(ex);
                    continue;
                }
                return true;
            }
        }
        return false;
    }
}

Then, in your Middleware, just access the request header, the JwtOptions dependency and call the Backer:

 protected string ObtainAppTokenFromHeader(string authHeader)
    {
        if (string.IsNullOrWhiteSpace(authHeader) || !authHeader.Contains(" "))
            return null;
        string[] authSchemeAndJwt = authHeader.Split(' ');
        string authScheme = authSchemeAndJwt[0];
        if (authScheme != "Bearer")
            return null;
        string jwt = authSchemeAndJwt[1];
        return jwt;
    }

    protected async Task<bool> AuthorizeUserFromHttpContext(HttpContext context)
    {
        var jwtBearerOptions = context.RequestServices.GetRequiredService<JwtBearerOptions>() as JwtBearerOptions;
        string jwt = this.ObtainAppTokenFromHeader(context.Request.Headers["Authorization"]);
        if (jwt == null)
            return false;
        var jwtBacker = new JwtBearerBacker(jwtBearerOptions);
        return jwtBacker.IsJwtValid(jwt);
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.WebSockets.IsWebSocketRequest)
            return;
        if (!await this.AuthorizeUserFromHttpContext(context))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("The door is locked, dude. You're not authorized !");
            return;
        }
//... Whatever else you're doing in your middleware
       }

Also, the AuthenticationTicket and any other information about the auth has been already handled by the framework's JwtBearerMiddleware, and will be returned anyway.

Finally, the client side. I advise you using a client library that actually supports additional HTTP Headers. For example, as far as I know, the W3C Javascript client does not provide this functionality.

Here you are! Thanks to Microsoft for its Open Source codebase.

ContentLicense: CC BY-SA 4.0


问:
How can I convert float to int?
```<code>cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
</code>```

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

答:
you need to cast both as int since now you are adding an int with a float which of course results to  float. Try:

```<code>cube1.name = string.Format("Terrain_{0}_{1}", (int)(Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x), (int)(Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y))
</code>```

Title: How can I convert float to int?

Body:
cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

Body:
you need to cast both as int since now you are adding an int with a float which of course results to  float. Try:

cube1.name = string.Format("Terrain_{0}_{1}", (int)(Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x), (int)(Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y))


问:
printing on screen and a text file
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

```
1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >
```

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

```<code>printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
</code>```

Is there an easiest way to implement this to cut down the number of lines of code?

答:
```<code>#define ARRAY_LEN(x) (sizeof(x) / sizeof(x[0]))

FILE *f = fopen("somefile.txt", "a+");
FILE *fp[] = { stdout, f };
int i = 0;

for (i = 0; i < ARRAY_LEN(fp); i++) {
    fprintf(fp[i], "Starting serial number [%ld]\n", serial_info_p->start_int_idx);
    fprintf(fp[i], "Current serial number [%ld]\n", serial_info_p->start_int_idx);
}

fclose(f);
</code>```

OwnerDisplayName: Thi

Title: printing on screen and a text file

Body:
I need to dump the certain things into a text file and same has needs to be displayed on screen. (I'm telling about a C program utiltiy)
The menu option looks like following,

1. display AA parameters
2. display BB parameters
3. display CC parameters
4. dump all
5. Exit
Select option >

If they select 1/2/3, it just needs to displayed on screen only or if they select option #4,it need to display all the parameters one by one and same needs to dumped in a .txt file.

I know, we can use the printf and fprintf functions to display on screen and write it to text file respectively. The thing is that I've display more that 20 parameters and each have at least 20 sub-parameters.

I'm currently implemented as below,

printf (        "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx);
fprintf(file_p, "Starting serial number       [%ld]\n",
        serial_info_p->start_int_idx)
printf (        "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);
fprintf(file_p, "Current Serial number         [%d]\n",
        serial_info_p->current_int_idx);

Is there an easiest way to implement this to cut down the number of lines of code?

LastEditorDisplayName: Jonathan Leffler

ContentLicense: CC BY-SA 2.5


问:
CakePHP Method Will Not Process Data AT ALL
I have a problem my code below will not process at all. It will not save or delete. I get a success message but nothing will save nor will nothing delete. I thought the method was a reserved keyword but then I tried to rename it and it still didn't work. Any insight would be enormously appreciated as this has stumped me.</p>

```<code>function approve() {
    $this->set('title', 'Approve Article');
    if ($this->RequestHandler->isPost() || $this->RequestHandler->isPut()) {
        if (empty($this->data['Article']['id'])) {
            $this->Session->setFlash('No article was passed.', 'message_error');
        } else {
            $this->Article->set($this->data);
            if ($this->Article->validates()) {
                if ($this->data['Article']['approved']) {
                    $this->data['Article']['content'] = $this->Safe->filter($this->data['Article']['content']);
                    $role = $this->Auth->user('role');
                    if ($role == 'Admin')
                        $this->Article->set('updated', strtotime($this->data['Article']['updated']));
                    else
                        $this->Article->set('updated', time());
                    $this->Article->set('updated', time());
                    $this->Article->save();
                    // Status
                    $status['Status']['type'] = 'Gain';
                    $status['Status']['amount'] = 20;
                    $status['Status']['created'] = time();
                    $this->Status->add($this->data['Article']['account_id'], $status);
                    $this->Session->setFlash('The article was approved and status was added.', 'message_success');
                } else {
                    $this->Article->delete($this->data['Article']['id']);
                    $this->Session->setFlash('The article was unapproved and deleted.', 'message_error');
                }
            } else {
                $this->Session->setFlash('Form Errors', 'message_error');
            }
        }
    }
    $unapproved_articles = $this->Article->find('count', array('conditions' => array('Article.approved =' => 0)));
    if ($unapproved_articles == 0) {
        $this->Session->setFlash('There are no unapproved articles.', 'message_success');
    } else {
        $article = $this->Article->find('first', array('order' => array('Article.created DESC')));
        $article['Article']['updated'] = date('d M Y', $article['Article']['updated']);
        $this->set('article', $article);
        $this->set('categories', $this->Category->dropdown());
        $this->set('accounts', $this->Account->dropdown());
    }
}
</code>```

答:
The save will try to validate unless you give $this->Article->save($this->data,array('validate' => false))

You can try out these tips

try this too

```<code>            if ($this->data['Article']['approved']) {
                $this->data['Article']['content'] = $this->Safe->filter($this->data['Article']['content']);
                $role = $this->Auth->user('role');
                if ($role == 'Admin')
                    $this->data['Article']['updated']=strtotime($this->data['Article']['updated']);
                else
                    $this->data['Article']['updated']=time();
                if($this->Article->save($this->data)){
                // Status
                    $status['Status']['type'] = 'Gain';
                    $status['Status']['amount'] = 20;
                    $status['Status']['created'] = time();
                    $this->Status->add($this->data['Article']['account_id'], $status);
                    $this->Session->setFlash('The article was approved and status was added.', 'message_success');
                }
                else{
                    $this->Session->setFlash('Form Errors', 'message_error');
                }
            } else {
                $this->Article->delete($this->data['Article']['id']);
                $this->Session->setFlash('The article was unapproved and deleted.', 'message_error');
            }
</code>```

Body:
I have a problem my code below will not process at all. It will not save or delete. I get a success message but nothing will save nor will nothing delete. I thought the method was a reserved keyword but then I tried to rename it and it still didn't work. Any insight would be enormously appreciated as this has stumped me.

function approve() {
    $this->set('title', 'Approve Article');
    if ($this->RequestHandler->isPost() || $this->RequestHandler->isPut()) {
        if (empty($this->data['Article']['id'])) {
            $this->Session->setFlash('No article was passed.', 'message_error');
        } else {
            $this->Article->set($this->data);
            if ($this->Article->validates()) {
                if ($this->data['Article']['approved']) {
                    $this->data['Article']['content'] = $this->Safe->filter($this->data['Article']['content']);
                    $role = $this->Auth->user('role');
                    if ($role == 'Admin')
                        $this->Article->set('updated', strtotime($this->data['Article']['updated']));
                    else
                        $this->Article->set('updated', time());
                    $this->Article->set('updated', time());
                    $this->Article->save();
                    // Status
                    $status['Status']['type'] = 'Gain';
                    $status['Status']['amount'] = 20;
                    $status['Status']['created'] = time();
                    $this->Status->add($this->data['Article']['account_id'], $status);
                    $this->Session->setFlash('The article was approved and status was added.', 'message_success');
                } else {
                    $this->Article->delete($this->data['Article']['id']);
                    $this->Session->setFlash('The article was unapproved and deleted.', 'message_error');
                }
            } else {
                $this->Session->setFlash('Form Errors', 'message_error');
            }
        }
    }
    $unapproved_articles = $this->Article->find('count', array('conditions' => array('Article.approved =' => 0)));
    if ($unapproved_articles == 0) {
        $this->Session->setFlash('There are no unapproved articles.', 'message_success');
    } else {
        $article = $this->Article->find('first', array('order' => array('Article.created DESC')));
        $article['Article']['updated'] = date('d M Y', $article['Article']['updated']);
        $this->set('article', $article);
        $this->set('categories', $this->Category->dropdown());
        $this->set('accounts', $this->Account->dropdown());
    }
}

Body:
The save will try to validate unless you give $this->Article->save($this->data,array('validate' => false))

You can try out these tips

try this too

            if ($this->data['Article']['approved']) {
                $this->data['Article']['content'] = $this->Safe->filter($this->data['Article']['content']);
                $role = $this->Auth->user('role');
                if ($role == 'Admin')
                    $this->data['Article']['updated']=strtotime($this->data['Article']['updated']);
                else
                    $this->data['Article']['updated']=time();
                if($this->Article->save($this->data)){
                // Status
                    $status['Status']['type'] = 'Gain';
                    $status['Status']['amount'] = 20;
                    $status['Status']['created'] = time();
                    $this->Status->add($this->data['Article']['account_id'], $status);
                    $this->Session->setFlash('The article was approved and status was added.', 'message_success');
                }
                else{
                    $this->Session->setFlash('Form Errors', 'message_error');
                }
            } else {
                $this->Article->delete($this->data['Article']['id']);
                $this->Session->setFlash('The article was unapproved and deleted.', 'message_error');
            }


问:
Access from parent component to child component when the child form is dirty
I have created a pending changes guard which alerts my users, if there has been changes made to the form and warns them before navigating away.

This all works fine but I have a child component on the page which is rendered using a selector, this component has a form on also.

How can I access this form from my guard to check if the form is dirty?

Guard:

```<code>import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { DialogService } from "ng2-bootstrap-modal";
import { ConfirmComponent } from '../components/confirm/confirm.component';
import { Inject } from '@angular/core';

export interface FormComponent {
    form: FormGroup;
}

export class PreventUnsavedChangesGuard implements CanDeactivate<FormComponent> {

constructor(@Inject(DialogService) private dialogService: DialogService) { }

canDeactivate(component: FormComponent): Promise<boolean> {

    if (component.form.dirty) {
        return new Promise<boolean>((resolve, reject) => {

            this.dialogService.addDialog(ConfirmComponent, {
                title: 'Unsaved Changes',
                message: 'You have unsaved changes. Are you sure you want to navigate away?'
            })
                .subscribe((isConfirmed) => {
                    return resolve(isConfirmed);
                });
        });
    }

    return Promise.resolve(true);
    }
}
</code>```

答:
Pass the parent form as input to child component. Then child component needs to bind the input field to that form. If child's input fields becomes dirty, then parent form will become dirty. So in that you do not need to access child form in your guard. For example,

Parent Component ts

```<code>import {FormBuilder, FormGroup} from "@angular/forms";
private addEmailItemForm : FormGroup;
export class ParentComponent implements OnInit, OnDestroy {

    constructor(private _fb: FormBuilder) {}

    ngOnInit() {
        this.parentComponentForm = this._fb.group({});
    }
}
</code>```

Parent Component's HTML

```<code><child-component
   [parentForm]="parentComponentForm"
</child-component>
</code>```

Child Component ts

```<code>export class ChildComponent implements OnInit {
   @Input() parentForm: FormGroup;
   let inputFieldControl = new FormControl('', Validators.required);
   this.parentForm.addControl(this.inputFieldControlName, inputFieldControl);
}
</code>```

Child Component's HTML

```<code><input type="text" class="form-control" [formControl]="parentForm.controls[inputFieldControlName]">
</code>```

Body:
I have created a pending changes guard which alerts my users, if there has been changes made to the form and warns them before navigating away.

This all works fine but I have a child component on the page which is rendered using a selector, this component has a form on also.

How can I access this form from my guard to check if the form is dirty?

Guard:

import { CanDeactivate } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { DialogService } from "ng2-bootstrap-modal";
import { ConfirmComponent } from '../components/confirm/confirm.component';
import { Inject } from '@angular/core';

export interface FormComponent {
    form: FormGroup;
}

export class PreventUnsavedChangesGuard implements CanDeactivate<FormComponent> {

constructor(@Inject(DialogService) private dialogService: DialogService) { }

canDeactivate(component: FormComponent): Promise<boolean> {

    if (component.form.dirty) {
        return new Promise<boolean>((resolve, reject) => {

            this.dialogService.addDialog(ConfirmComponent, {
                title: 'Unsaved Changes',
                message: 'You have unsaved changes. Are you sure you want to navigate away?'
            })
                .subscribe((isConfirmed) => {
                    return resolve(isConfirmed);
                });
        });
    }

    return Promise.resolve(true);
    }
}

Body:
Pass the parent form as input to child component. Then child component needs to bind the input field to that form. If child's input fields becomes dirty, then parent form will become dirty. So in that you do not need to access child form in your guard. For example,

Parent Component ts

import {FormBuilder, FormGroup} from "@angular/forms";
private addEmailItemForm : FormGroup;
export class ParentComponent implements OnInit, OnDestroy {

    constructor(private _fb: FormBuilder) {}

    ngOnInit() {
        this.parentComponentForm = this._fb.group({});
    }
}

Parent Component's HTML

<child-component
   [parentForm]="parentComponentForm"
</child-component>

Child Component ts

export class ChildComponent implements OnInit {
   @Input() parentForm: FormGroup;
   let inputFieldControl = new FormControl('', Validators.required);
   this.parentForm.addControl(this.inputFieldControlName, inputFieldControl);
}

Child Component's HTML

<input type="text" class="form-control" [formControl]="parentForm.controls[inputFieldControlName]">


问:
Convert xml ntext in mssql to csv (ucomponents migration)
I have lots of rows in an mssql table which are in xml format and I want to convert them to csv. The column is an ntext and the values are like.

```<code><MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>
</code>```

and I would like to convert them in 5713,6817,5424,1888,6128,6339
Any ideas how to achieve this with sql command?

** Probably this seems to be the way to go https://social.msdn.microsoft.com/Forums/sqlserver/en-US/780e80b2-f898-4451-b19f-332289fb1c8d/sql-xml-get-xml-values-into-csv?forum=sqlxml , save it in a function and then loop through all the rows and update the values. At the moment it is failing at x.y.value.

I tried also to use replace but it failed because it is xml and it doesnt get the space between the xml nodes.

I also used

```<code>set dataNvarchar = substring(CAST(dataNtext as nvarchar(500)), patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))), 1+patindex('%[0-9][^0-9]%', CAST(dataNtext as nvarchar(500))+'x')-patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))))
</code>```

but it gets only the first numeric.

******* Additional Solution *********
These values come from uComponent plugin for Umbraco. I couldn't find a way to read it as xml - even though the solution to this as proper xml is correct.
Instead I wrote this function which solved my problem

```<code>Create Function [dbo].[ParseXml](@text ntext)
returns nvarchar(500) as
Begin
declare @strnvar nvarchar(MAX) -- main string to subtruct
declare @numberstr nvarchar(500) -- extracted number
declare @csvstr nvarchar(500) -- constructed csv string
-- Convert text to nvarchar
set @strnvar = CAST(@text as nvarchar(MAX))
set @csvstr = ''
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))

while(DATALENGTH(@numberstr) > 0)
BEGIN
set @csvstr = @csvstr + @numberstr + ','
set @strnvar = REPLACE(@strnvar, @numberstr, '')
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))
END

IF RIGHT(@csvstr,1) = ','
    set @csvstr =  LEFT(@csvstr, LEN(@csvstr) - 1)
return @csvstr
end
GO
</code>```

答:
If you convert ntext to xml then you can build comma separated as below

```<code>declare @x xml = '<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>'

Select Stuff(( Select ','+ y.value(N'text()[1]', N'nvarchar(MAX)')
FROM @x.nodes(N'MultiNodePicker/nodeId') as x(y) for xml path('') ),1,1,'')
</code>```

Output as below:

```<code>5713,6817,5424,1888,6128,6339
</code>```

I created function as below and it is working fine:

```<code>Create Function [dbo].[ParseXml](@text ntext) returns nvarchar(500) as
Begin declare @x xml = @text
return
Stuff(( Select ',' + y.value(N'text()[1]',N'nvarchar(MAX)') FROM @x.nodes(N'MultiNodePicker/nodeId') as x(y) for xml path('')),1,1,'')
end

declare @x nvarchar(500) = '<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>'

select  dbo.ParseXml(@x)
</code>```

Output : Same as above

Body:
I have lots of rows in an mssql table which are in xml format and I want to convert them to csv. The column is an ntext and the values are like.

<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>

and I would like to convert them in 5713,6817,5424,1888,6128,6339
Any ideas how to achieve this with sql command?

** Probably this seems to be the way to go https://social.msdn.microsoft.com/Forums/sqlserver/en-US/780e80b2-f898-4451-b19f-332289fb1c8d/sql-xml-get-xml-values-into-csv?forum=sqlxml , save it in a function and then loop through all the rows and update the values. At the moment it is failing at x.y.value.

I tried also to use replace but it failed because it is xml and it doesnt get the space between the xml nodes.

I also used

set dataNvarchar = substring(CAST(dataNtext as nvarchar(500)), patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))), 1+patindex('%[0-9][^0-9]%', CAST(dataNtext as nvarchar(500))+'x')-patindex('%[0-9]%', CAST(dataNtext as nvarchar(500))))

but it gets only the first numeric.

******* Additional Solution *********
These values come from uComponent plugin for Umbraco. I couldn't find a way to read it as xml - even though the solution to this as proper xml is correct.
Instead I wrote this function which solved my problem

Create Function [dbo].[ParseXml](@text ntext)
returns nvarchar(500) as
Begin
declare @strnvar nvarchar(MAX) -- main string to subtruct
declare @numberstr nvarchar(500) -- extracted number
declare @csvstr nvarchar(500) -- constructed csv string
-- Convert text to nvarchar
set @strnvar = CAST(@text as nvarchar(MAX))
set @csvstr = ''
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))

while(DATALENGTH(@numberstr) > 0)
BEGIN
set @csvstr = @csvstr + @numberstr + ','
set @strnvar = REPLACE(@strnvar, @numberstr, '')
set @numberstr = substring(@strnvar, patindex('%[0-9]%', @strnvar), 1 + patindex('%[0-9][^0-9]%', @strnvar+'x') - patindex('%[0-9]%', @strnvar))
END

IF RIGHT(@csvstr,1) = ','
    set @csvstr =  LEFT(@csvstr, LEN(@csvstr) - 1)
return @csvstr
end
GO

Body:
If you convert ntext to xml then you can build comma separated as below

declare @x xml = '<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>'

Select Stuff(( Select ','+ y.value(N'text()[1]', N'nvarchar(MAX)')
FROM @x.nodes(N'MultiNodePicker/nodeId') as x(y) for xml path('') ),1,1,'')

Output as below:

5713,6817,5424,1888,6128,6339

I created function as below and it is working fine:

Create Function [dbo].[ParseXml](@text ntext) returns nvarchar(500) as
Begin declare @x xml = @text
return
Stuff(( Select ',' + y.value(N'text()[1]',N'nvarchar(MAX)') FROM @x.nodes(N'MultiNodePicker/nodeId') as x(y) for xml path('')),1,1,'')
end

declare @x nvarchar(500) = '<MultiNodePicker type="content">
  <nodeId>5713</nodeId>
  <nodeId>6817</nodeId>
  <nodeId>5424</nodeId>
  <nodeId>1888</nodeId>
  <nodeId>6128</nodeId>
  <nodeId>6339</nodeId>
</MultiNodePicker>'

select  dbo.ParseXml(@x)

Output : Same as above


问:
JavaScript change style of a specific child div from another child div
Let's say that we have a loop which result 3 divs with other 4 divs inside each, like this:

```<code><div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>
</code>```

Now, I want to change the style css with javascript. How can I make something like this in javascript and work?

document.getElementsByClassName('one')[2].document.getElementsByClassName('two')[3].style.cssText {...};

I want to change the style css of the class .two from child [3] which is inside class .one from child [2]

答:
You were very close. A HTMLElement has - like document - a .getElementsByClassName method to select some of the child elements:

document.getElementsByClassName('one')[2].getElementsByClassName('two')[3].style.cssText = 'background-color: red';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div></code>```

MDN: document.getElementsByClassName and Element.getElementsByClassName.

Body:
Let's say that we have a loop which result 3 divs with other 4 divs inside each, like this:

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

Now, I want to change the style css with javascript. How can I make something like this in javascript and work?

document.getElementsByClassName('one')[2].document.getElementsByClassName('two')[3].style.cssText {...};

I want to change the style css of the class .two from child [3] which is inside class .one from child [2]

Body:
You were very close. A HTMLElement has - like document - a .getElementsByClassName method to select some of the child elements:

document.getElementsByClassName('one')[2].getElementsByClassName('two')[3].style.cssText = 'background-color: red';

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

MDN: document.getElementsByClassName and Element.getElementsByClassName.


问:
Firefox display=block problem
I have a the following HTML

```<code> <a id="rptQuestions_ctl01_hlQuestion" onclick="rptQuestions_ctl01_pnlAnswer.style.display = rptQuestions_ctl01_pnlAnswer.style.display == 'none'? 'block' : 'none';" href="javascript:">Header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">

            My Text to display

</div>
</code>```

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

```<code>        <a id="rptQuestions_ctl01_hlQuestion" onclick="jasvascript:document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='block';" href="#">My header Link</a>

            <div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">
My Text

</div>
</code>```

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?

答:
The same code without the ternary operator:

```<code><a id="rptQuestions_ctl01_hlQuestion" onclick="javascript:if(document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display == 'none'){document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='block'}else{document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='none'};return false" href="#">My header Link</a>
<div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">
    My Text
</div>
</code>```

The previous code also worked, so I'm not sure how this would change anything. If you paste this code into a new HTML file it will work. If it doesn't work when you put it in your file, then the problem is probably somewhere else in the file. In that case, you should post more of the surrounding code.

Title: Firefox display=block problem

Body:
I have a the following HTML

 Header Link

            My Text to display

This works as i would expect in IE8, where it displays the div when you click the header link, and then hides it when clicking the header link again. However, in Firefox, nothing happens when i click the header link.
I'm assuming this is to do with IE being forgiving of an error i have made, and Firefox sticking to the rules, but i can't see what i am doing wrong.
Any ideas?

--- EDIT

I've tried this with the following code and it works fine:

        My header Link

My Text

so it seems the problem is the ternary operator not working correctly.
Anyone see the problem?

Body:
The same code without the ternary operator:

<a id="rptQuestions_ctl01_hlQuestion" onclick="javascript:if(document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display == 'none'){document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='block'}else{document.getElementById('rptQuestions_ctl01_pnlAnswer').style.display='none'};return false" href="#">My header Link</a>
<div id="rptQuestions_ctl01_pnlAnswer" style="display:none;">
    My Text
</div>

The previous code also worked, so I'm not sure how this would change anything. If you paste this code into a new HTML file it will work. If it doesn't work when you put it in your file, then the problem is probably somewhere else in the file. In that case, you should post more of the surrounding code.


问:
quantity input box on featured products -Opencart
can you help for  quantity input box on featured products , opencart 2.3.0.2

```<code><input type="text" size="3" id="quantity-<?php echo $product['product_id']; ?>" name="quantity" value="1" placeholder="1" class="form-control my-form-control input-lg qty-input radius-none pull-left" />
</code>```

this code will show input box and default 1 and it adds 1 products to cart but I need any numbers to be added to cart.

答:
You should change the value attribute. Like value="<?php echo $needed_quantity; ?>"

Or delete value attribute but than you need to check if user set the quantity (check if empty) and inform user that he must set the quantity manually

Body:
can you help for  quantity input box on featured products , opencart 2.3.0.2

<input type="text" size="3" id="quantity-<?php echo $product['product_id']; ?>" name="quantity" value="1" placeholder="1" class="form-control my-form-control input-lg qty-input radius-none pull-left" />

this code will show input box and default 1 and it adds 1 products to cart but I need any numbers to be added to cart.


问:
How to pass GraphQLEnumType in mutation as a string value
I have following GraphQLEnumType

```<code>const PackagingUnitType = new GraphQLEnumType({
  name: 'PackagingUnit',
  description: '',
  values: {
    Carton: { value: 'Carton' },
    Stack: { value: 'Stack' },
  },
});
</code>```

On a mutation query if i pass PackagingUnit value as Carton (without quotes) it works.  But If i pass as string 'Carton' it throws following error

```<code>In field "packagingUnit": Expected type "PackagingUnit", found "Carton"
</code>```

Is there a way to pass the enum as a string from client side?

EDIT:
I have a form in my front end, where i collect the PackagingUnit type from user along with other fields. PackagingUnit type is represented as a string in front end (not the graphQL Enum type), Since i am not using Apollo Client or Relay, i had to construct the graphQL query string by myself.
Right now i am collecting the form data as JSON and then do JSON.stringify() and then remove the double Quotes on properties to get the final graphQL compatible query.

eg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat)
my json structure is

```<code>{
  packagingUnitType: "Carton",
  noOfUnits: 10
}
</code>```

convert this to string using JSON.stringify()

```<code>'{"packagingUnitType":"Carton","noOfUnits":10}'
</code>```

And then remove the doubleQuotes on properties

```<code>{packagingUnitType:"Carton",noOfUnits:10}
</code>```

Now this can be passed to the graphQL server like

```<code>newStackMutation(input: {packagingUnitType:"Carton", noOfUnits:10}) {
...
}
</code>```

This works only if the enum value does not have any quotes. like below

```<code>newStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {
...
}
</code>```

Thanks

答:
GraphQL queries can accept variables. This will be easier for you, as you will not have to do some tricky string-concatenation.

I suppose you use GraphQLHttp - or similar. To send your variables along the query, send a JSON body with a query key and a variables key:

```<code>// JSON body
{
  "query": "query MyQuery { ... }",
  "variables": {
    "variable1": ...,
  }
}
</code>```

The query syntax is:

```<code>query MyMutation($input: NewStackMutationInput) {
  newStackMutation(input: $input) {
    ...
  }
}
</code>```

And then, you can pass your variable as:

```<code>{
  "input": {
    "packagingUnitType": "Carton",
    "noOfUnits": 10
  }
}
</code>```

GraphQL will understand packagingUnitType is an Enum type and will do the conversion for you.

Body:
I have following GraphQLEnumType

const PackagingUnitType = new GraphQLEnumType({
  name: 'PackagingUnit',
  description: '',
  values: {
    Carton: { value: 'Carton' },
    Stack: { value: 'Stack' },
  },
});

On a mutation query if i pass PackagingUnit value as Carton (without quotes) it works.  But If i pass as string 'Carton' it throws following error

In field "packagingUnit": Expected type "PackagingUnit", found "Carton"

Is there a way to pass the enum as a string from client side?

EDIT:
I have a form in my front end, where i collect the PackagingUnit type from user along with other fields. PackagingUnit type is represented as a string in front end (not the graphQL Enum type), Since i am not using Apollo Client or Relay, i had to construct the graphQL query string by myself.
Right now i am collecting the form data as JSON and then do JSON.stringify() and then remove the double Quotes on properties to get the final graphQL compatible query.

eg. my form has two fields packagingUnitType (An GraphQLEnumType) and noOfUnits (An GraphQLFloat)
my json structure is

{
  packagingUnitType: "Carton",
  noOfUnits: 10
}

convert this to string using JSON.stringify()

'{"packagingUnitType":"Carton","noOfUnits":10}'

And then remove the doubleQuotes on properties

{packagingUnitType:"Carton",noOfUnits:10}

Now this can be passed to the graphQL server like

newStackMutation(input: {packagingUnitType:"Carton", noOfUnits:10}) {
...
}

This works only if the enum value does not have any quotes. like below

newStackMutation(input: {packagingUnitType:Carton, noOfUnits:10}) {
...
}

Thanks

Body:
GraphQL queries can accept variables. This will be easier for you, as you will not have to do some tricky string-concatenation.

I suppose you use GraphQLHttp - or similar. To send your variables along the query, send a JSON body with a query key and a variables key:

// JSON body
{
  "query": "query MyQuery { ... }",
  "variables": {
    "variable1": ...,
  }
}

The query syntax is:

query MyMutation($input: NewStackMutationInput) {
  newStackMutation(input: $input) {
    ...
  }
}

And then, you can pass your variable as:

{
  "input": {
    "packagingUnitType": "Carton",
    "noOfUnits": 10
  }
}

GraphQL will understand packagingUnitType is an Enum type and will do the conversion for you.


问:
Getting "The path to the driver executable must be set by the webdriver.gecko.driver " while try to run selenium Grid code with Gecko driver
I am running basic selenium code with the help of selenium Grid.

Below are the steps:

Step 1 :- Downloaded the latest version of selenium Standalone server (3.4.0);

Step 2 :- Created HUB by using command java - jar <path of selenium standalone server>\\selenium-server-standalone-3.4.0.jar -role hub -> run successfully;

Step 3 :- Created node using command java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register -> run successfully;

Step 4 :- Created a simple selenium program with below code:

```<code>public class ClassName {

  public static void main(String args[]) throws InterruptedException, MalformedURLException {
    System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
    DesiredCapabilities cap=DesiredCapabilities.firefox();
    cap.setPlatform(Platform.WINDOWS);
    cap.setBrowserName("firefox");
    URL url = new URL("http://localhost:4444/wd/hub");

    WebDriver wd1 = new RemoteWebDriver(url, cap);
    wd1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    wd1.manage().window().maximize();

    wd1.get("http://www.clickindia.com/");
    wd1.findElement(By.linkText("Post Free Ad")).click();
    Thread.sleep(3000);
    wd1.findElement(By.linkText("Select category manually")).click();
    Thread.sleep(3000);
    WebElement country = wd1.findElement(By.id("combo_0"));
    Select sel = new Select(country);
    sel.selectByVisibleText("Jobs");
  }
}
</code>```

While running above code the following exception was thrown:

Note : If I run above code without remoteDriver and as a common WebDriver programm then it is working and running properly.

Location of selenium standalone server and Gecko file is same.

Gecko version is v0.16.0

Thanks in advance

答:
You have registered the node with default configuration as java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register. So your node is unable to process the request.

You can consider registering the node with the following configuration as:

```<code>java -Dwebdriver.gecko.driver=C:\\geckodriver.exe -jar selenium-server-standalone-3.4.0.jar -role node -hub http://localhost:4444/grid/register
</code>```

Your code blocks works fine at my end.

Body:
I am running basic selenium code with the help of selenium Grid.

Below are the steps:

Step 1 :- Downloaded the latest version of selenium Standalone server (3.4.0);

Step 2 :- Created HUB by using command java - jar <path of selenium standalone server>\\selenium-server-standalone-3.4.0.jar -role hub -> run successfully;

Step 3 :- Created node using command java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register -> run successfully;

Step 4 :- Created a simple selenium program with below code:

public class ClassName {

  public static void main(String args[]) throws InterruptedException, MalformedURLException {
    System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
    DesiredCapabilities cap=DesiredCapabilities.firefox();
    cap.setPlatform(Platform.WINDOWS);
    cap.setBrowserName("firefox");
    URL url = new URL("http://localhost:4444/wd/hub");

    WebDriver wd1 = new RemoteWebDriver(url, cap);
    wd1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    wd1.manage().window().maximize();

    wd1.get("http://www.clickindia.com/");
    wd1.findElement(By.linkText("Post Free Ad")).click();
    Thread.sleep(3000);
    wd1.findElement(By.linkText("Select category manually")).click();
    Thread.sleep(3000);
    WebElement country = wd1.findElement(By.id("combo_0"));
    Select sel = new Select(country);
    sel.selectByVisibleText("Jobs");
  }
}

While running above code the following exception was thrown:

Note : If I run above code without remoteDriver and as a common WebDriver programm then it is working and running properly.

Location of selenium standalone server and Gecko file is same.

Gecko version is v0.16.0

Thanks in advance

Body:
You have registered the node with default configuration as java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register. So your node is unable to process the request.

You can consider registering the node with the following configuration as:

java -Dwebdriver.gecko.driver=C:\\geckodriver.exe -jar selenium-server-standalone-3.4.0.jar -role node -hub http://localhost:4444/grid/register

Your code blocks works fine at my end.


问:
What happens if you manually update a .CSS file when a .SCSS/.SASS file is in use?
I've got the below setup:

Brackets IDE

CodeKit for compiling SASS/SCSS into CSS

CloudMounter to mount a live copy of a Wordpress site via FTP (it also auto updates the server's files with any changes I make to the mounted version).

Here's how it works:

Add SCSS styling into .SCSS file

Save SCSS file

CodeKit auto compiles into CSS file, and stores on Local/mounted drive.

CloudMounter picks up the change and auto uploads it to server where Wordpress site is hosted.

Probably not the most efficient workflow but I'm quite impressed with what I've managed to pull off.

My question is: What happens if one of the other people in my office directly FTPs onto the server and makes an edit to the .CSS file instead of using the above method to add SCSS instead?

Will this break the compiler? When I update the SCSS file in the future, will this overwrite/ignore the new custom CSS?

I'd rather like to keep myself as the only developer who uses SCSS instead of having to train the other people in the office.

答:
DON'T! It will be very hard to maintain what you edited and when you reload the Wordpress site you will lose the edits to the compiled CSS file (pure assumption). If you ABSOLUTELY have to just put the extra CSS you want to add or want your coworkers to add in separate CSS files that AREN'T SCSS/SASS.

SCSS compiles to CSS, that would be like writing software in C++ and then editing the compiled object files or writing software in Java and then editing the byte code. It is just very backwards and not ideal.

By doing what you said you wanted to do you are doing something that is not not advised. SCSS is neat because it allows you to short hand a bunch of stuff and saves you typing and annoying syntax and lets you use variables which plain CSS doesn't allow. Adding plain CSS to a mainly SCSS styled app isn't bad, but I suggest you put all your additional CSS in a separate file so that it is clear what the compiled CSS from SCSS is and what the new CSS you used is.

For the most part SCSS can almost be used Exactly like CSS as far as I know and its worth learning.


问:
How to use TSQL for generating Json
I'm trying to design source document for mongodb from data already existing in tabular database sqlserver/mysql.

For practicing i've prepared three table customer,product & order transaction, with schema as below

```<code>USE scratch
GO

CREATE TABLE Customer(customer_id int identity(1,1), FirstName varchar(100),LastName varchar(100));

Create TAble Product(Product_id int identity(1,1), Name varchar(100), Price numeric(18,2), Unit varchar(10));

CREATE TABLE OrderTransaction(Tr_id int identity(1,1), customer_id int, Product_id int ,Quantity int, TotalCost numeric, trdate datetime, weigh int , weighunit varchar(100));

INSERT INTO Customer(FirstName,LastName)

SELECT 'Harry','G'
UNION ALL
SELECT 'Jenne','G'
UNION ALL
SELECT 'Gill','G'
UNION ALL
SELECT 'Tom','G'
UNION ALL
SELECT 'Bai','G'

INSERT INTO Product(Name,Price, Unit )
SELECT 'Sugar',100,'kg'
UNION ALL
SELECT 'Olive Oil',500,'litre'
UNION ALL
SELECT 'Loreal Face Wash',200,NULL
UNION ALL
SELECT 'FLour',400,'kg'
UNION ALL
SELECT 'Onion',20,'kg'
UNION ALL
SELECT 'Potato',10,'kg'

INSERT INTO OrderTransaction(customer_id,Product_id,Quantity,TotalCost,trdate,weigh,weighunit)
SELECT 1,1,5,500,GETDATE()-40,5,'kg'
UNION ALL
SELECT 1,2,1,2500,GETDATE()-40,5,'litre'
UNION ALL
SELECT 1,3,5,500,GETDATE()-30,5,'kg'
UNION ALL
SELECT 1,4,1,200,GETDATE()-30,NULL,NULL
UNION ALL
SELECT 1,5,5,100,GETDATE(),5,'kg'
UNION ALL
SELECT 1,6,5,50,GETDATE(),5,'kg'

UNION ALL
SELECT 2,1,5,500,GETDATE()-40,5,'kg'
UNION ALL
SELECT 2,2,1,2500,GETDATE()-40,5,'litre'
UNION ALL
SELECT 2,3,5,500,GETDATE()-30,5,'kg'
UNION ALL
SELECT 2,4,1,200,GETDATE()-30,NULL,NULL
UNION ALL
SELECT 2,5,5,100,GETDATE(),5,'kg'
UNION ALL
SELECT 2,6,5,50,GETDATE(),5,'kg'
</code>```

I've tried Json Path in sql server 2016 but didn't find any documentation
to group transaction on basis of customer, it create each transaction as a document.

```<code>select a.customer_id as 'Customer.customer_id'
,FirstName as 'Customer.FirstName'
,LastName as 'Customer.LastName'
,Tr_id as 'Customer.AllTransaction.Tr_id'
,b.Product_id as 'Customer.AllTransaction.Product_id'
,Quantity as 'Customer.AllTransaction.Quantity'
,TotalCost as 'Customer.AllTransaction.TotalCost'
,p.Name as 'Customer.AllTransaction.ProductName'

from Customer a
inner join OrderTransaction b
on a.customer_id=b.customer_id
inner join Product p
on b.Product_id=p.Product_id
FOR JSON PATH
</code>```

I would like write a query to prepare json like:

```<code>[
  {
    "customer_id": 1,
    "FirstName": "Harry",
    "LastName": "G",
    "totalsales": 3850.0,
    "LastTransactionDate": "2014-12-1208: 42: 00.000Z",
    "AllTransctionList": [
      {
        "Tr_id": 1,
        "Product_id": 1,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Sugar"
      },
      {
        "Tr_id": 2,
        "Product_id": 2,
        "Quantity": 1,
        "TotalCost": 2500,
        "ProductName": "Olive Oil"
      },
      {
        "Tr_id": 3,
        "Product_id": 3,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Loreal Face Wash"
      },
      {
        "Tr_id": 4,
        "Product_id": 4,
        "Quantity": 1,
        "TotalCost": 200,
        "ProductName": "FLour"
      },
      {
        "Tr_id": 5,
        "Product_id": 5,
        "Quantity": 5,
        "TotalCost": 100,
        "ProductName": "Onion"
      },
      {
        "Tr_id": 6,
        "Product_id": 6,
        "Quantity": 5,
        "TotalCost": 50,
        "ProductName": "Potato"
      }
    ]
  },
  {
    "customer_id": 2,
    "FirstName": "Jenne",
    "LastName": "G",
    "totalsales": 3850.0,
    "LastTransactionDate": "2014-12-1208: 42: 00.000Z",
    "AllTransctionList": [
      {
        "Tr_id": 1,
        "Product_id": 1,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Sugar"
      },
      {
        "Tr_id": 2,
        "Product_id": 2,
        "Quantity": 1,
        "TotalCost": 2500,
        "ProductName": "Olive Oil"
      },
      {
        "Tr_id": 3,
        "Product_id": 3,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Loreal Face Wash"
      },
      {
        "Tr_id": 4,
        "Product_id": 4,
        "Quantity": 1,
        "TotalCost": 200,
        "ProductName": "FLour"
      },
      {
        "Tr_id": 5,
        "Product_id": 5,
        "Quantity": 5,
        "TotalCost": 100,
        "ProductName": "Onion"
      },
      {
        "Tr_id": 6,
        "Product_id": 6,
        "Quantity": 5,
        "TotalCost": 50,
        "ProductName": "Potato"
      }
    ]
  }
]
</code>```

答:
To get you started you might use something like

```<code>SELECT a.customer_id as 'customer_id'
,FirstName as 'FirstName'
,LastName as 'LastName'
,Tr_id as 'Tr_id'
,Quantity as 'Quantity'
,TotalCost as 'TotalCost'
from Customer a
inner join OrderTransaction AllTransactionList
on a.customer_id=AllTransactionList.customer_id
FOR JSON AUTO
</code>```

Instead of joining OrderTransaction you might get your product data first or use a subselect in the select list like in this example (Query3).

Like:

```<code>USE scratch
GO

SELECT a.customer_id     AS 'customer_id'
,FirstName               AS 'FirstName'
,LastName                AS 'LastName'
,LastTransactionDate
,totalsales
,Tr_id                   AS 'Tr_id'
,ProductName
,Quantity                AS 'Quantity'
,TotalCost               AS 'TotalCost'
FROM
(SELECT c.customer_id
,FirstName
,LastName
,MAX(trdate) LastTransactionDate
,SUM(TotalCost)totalsales

FROM Customer c
INNER JOIN OrderTransaction o
ON c.customer_id=o.customer_id
GROUP BY
c.customer_id
,FirstName
,LastName )a

INNER JOIN
    (SELECT
    o.Tr_id
    ,o.customer_id
    ,p.Name AS ProductName
    ,o.Quantity
    ,o.TotalCost
    ,o.trdate
    ,o.weigh
    ,o.weighunit
    FROM OrderTransaction o
    INNER JOIN Product p
    ON o.Product_id=p.Product_id)AllTransactionList

ON a.customer_id=AllTransactionList.customer_id

FOR JSON AUTO
</code>```

Title: How to use TSQL for generating Json

Body:
I'm trying to design source document for mongodb from data already existing in tabular database sqlserver/mysql.

For practicing i've prepared three table customer,product & order transaction, with schema as below

USE scratch
GO

CREATE TABLE Customer(customer_id int identity(1,1), FirstName varchar(100),LastName varchar(100));

Create TAble Product(Product_id int identity(1,1), Name varchar(100), Price numeric(18,2), Unit varchar(10));

CREATE TABLE OrderTransaction(Tr_id int identity(1,1), customer_id int, Product_id int ,Quantity int, TotalCost numeric, trdate datetime, weigh int , weighunit varchar(100));

INSERT INTO Customer(FirstName,LastName)

SELECT 'Harry','G'
UNION ALL
SELECT 'Jenne','G'
UNION ALL
SELECT 'Gill','G'
UNION ALL
SELECT 'Tom','G'
UNION ALL
SELECT 'Bai','G'

INSERT INTO Product(Name,Price, Unit )
SELECT 'Sugar',100,'kg'
UNION ALL
SELECT 'Olive Oil',500,'litre'
UNION ALL
SELECT 'Loreal Face Wash',200,NULL
UNION ALL
SELECT 'FLour',400,'kg'
UNION ALL
SELECT 'Onion',20,'kg'
UNION ALL
SELECT 'Potato',10,'kg'

INSERT INTO OrderTransaction(customer_id,Product_id,Quantity,TotalCost,trdate,weigh,weighunit)
SELECT 1,1,5,500,GETDATE()-40,5,'kg'
UNION ALL
SELECT 1,2,1,2500,GETDATE()-40,5,'litre'
UNION ALL
SELECT 1,3,5,500,GETDATE()-30,5,'kg'
UNION ALL
SELECT 1,4,1,200,GETDATE()-30,NULL,NULL
UNION ALL
SELECT 1,5,5,100,GETDATE(),5,'kg'
UNION ALL
SELECT 1,6,5,50,GETDATE(),5,'kg'

UNION ALL
SELECT 2,1,5,500,GETDATE()-40,5,'kg'
UNION ALL
SELECT 2,2,1,2500,GETDATE()-40,5,'litre'
UNION ALL
SELECT 2,3,5,500,GETDATE()-30,5,'kg'
UNION ALL
SELECT 2,4,1,200,GETDATE()-30,NULL,NULL
UNION ALL
SELECT 2,5,5,100,GETDATE(),5,'kg'
UNION ALL
SELECT 2,6,5,50,GETDATE(),5,'kg'

I've tried Json Path in sql server 2016 but didn't find any documentation
to group transaction on basis of customer, it create each transaction as a document.

select a.customer_id as 'Customer.customer_id'
,FirstName as 'Customer.FirstName'
,LastName as 'Customer.LastName'
,Tr_id as 'Customer.AllTransaction.Tr_id'
,b.Product_id as 'Customer.AllTransaction.Product_id'
,Quantity as 'Customer.AllTransaction.Quantity'
,TotalCost as 'Customer.AllTransaction.TotalCost'
,p.Name as 'Customer.AllTransaction.ProductName'

from Customer a
inner join OrderTransaction b
on a.customer_id=b.customer_id
inner join Product p
on b.Product_id=p.Product_id
FOR JSON PATH

I would like write a query to prepare json like:

[
  {
    "customer_id": 1,
    "FirstName": "Harry",
    "LastName": "G",
    "totalsales": 3850.0,
    "LastTransactionDate": "2014-12-1208: 42: 00.000Z",
    "AllTransctionList": [
      {
        "Tr_id": 1,
        "Product_id": 1,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Sugar"
      },
      {
        "Tr_id": 2,
        "Product_id": 2,
        "Quantity": 1,
        "TotalCost": 2500,
        "ProductName": "Olive Oil"
      },
      {
        "Tr_id": 3,
        "Product_id": 3,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Loreal Face Wash"
      },
      {
        "Tr_id": 4,
        "Product_id": 4,
        "Quantity": 1,
        "TotalCost": 200,
        "ProductName": "FLour"
      },
      {
        "Tr_id": 5,
        "Product_id": 5,
        "Quantity": 5,
        "TotalCost": 100,
        "ProductName": "Onion"
      },
      {
        "Tr_id": 6,
        "Product_id": 6,
        "Quantity": 5,
        "TotalCost": 50,
        "ProductName": "Potato"
      }
    ]
  },
  {
    "customer_id": 2,
    "FirstName": "Jenne",
    "LastName": "G",
    "totalsales": 3850.0,
    "LastTransactionDate": "2014-12-1208: 42: 00.000Z",
    "AllTransctionList": [
      {
        "Tr_id": 1,
        "Product_id": 1,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Sugar"
      },
      {
        "Tr_id": 2,
        "Product_id": 2,
        "Quantity": 1,
        "TotalCost": 2500,
        "ProductName": "Olive Oil"
      },
      {
        "Tr_id": 3,
        "Product_id": 3,
        "Quantity": 5,
        "TotalCost": 500,
        "ProductName": "Loreal Face Wash"
      },
      {
        "Tr_id": 4,
        "Product_id": 4,
        "Quantity": 1,
        "TotalCost": 200,
        "ProductName": "FLour"
      },
      {
        "Tr_id": 5,
        "Product_id": 5,
        "Quantity": 5,
        "TotalCost": 100,
        "ProductName": "Onion"
      },
      {
        "Tr_id": 6,
        "Product_id": 6,
        "Quantity": 5,
        "TotalCost": 50,
        "ProductName": "Potato"
      }
    ]
  }
]

Body:
To get you started you might use something like

SELECT a.customer_id as 'customer_id'
,FirstName as 'FirstName'
,LastName as 'LastName'
,Tr_id as 'Tr_id'
,Quantity as 'Quantity'
,TotalCost as 'TotalCost'
from Customer a
inner join OrderTransaction AllTransactionList
on a.customer_id=AllTransactionList.customer_id
FOR JSON AUTO

Instead of joining OrderTransaction you might get your product data first or use a subselect in the select list like in this example (Query3).

Like:

USE scratch
GO

SELECT a.customer_id     AS 'customer_id'
,FirstName               AS 'FirstName'
,LastName                AS 'LastName'
,LastTransactionDate
,totalsales
,Tr_id                   AS 'Tr_id'
,ProductName
,Quantity                AS 'Quantity'
,TotalCost               AS 'TotalCost'
FROM
(SELECT c.customer_id
,FirstName
,LastName
,MAX(trdate) LastTransactionDate
,SUM(TotalCost)totalsales

FROM Customer c
INNER JOIN OrderTransaction o
ON c.customer_id=o.customer_id
GROUP BY
c.customer_id
,FirstName
,LastName )a

INNER JOIN
    (SELECT
    o.Tr_id
    ,o.customer_id
    ,p.Name AS ProductName
    ,o.Quantity
    ,o.TotalCost
    ,o.trdate
    ,o.weigh
    ,o.weighunit
    FROM OrderTransaction o
    INNER JOIN Product p
    ON o.Product_id=p.Product_id)AllTransactionList

ON a.customer_id=AllTransactionList.customer_id

FOR JSON AUTO


答:
You've just got a precedence problem. You've got:

```<code>(int) x + y
</code>```

which is equivalent to

```<code>((int) x) + y
</code>```

... which will then promote the result of the cast back to a float in order to perform floating point addition. Just make the cast apply to the whole result instead:

```<code>(int) (x + y)
</code>```

Where x and y are the rather long expressions in your original code, of course. For the sake of readability, I'd extract the two values to separate local variables, so you'd have:

```<code>int sumX = (int) (Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x);
int sumY = (int) (Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
cube1.name = string.Format("Terrain_{0}_{1}", sumX, sumY);
</code>```

Or better still:

```<code>var position = Terrain.activeTerrain.transform.position;
int sumX = (int) (position.x + tilePositionInLocalSpace.x);
int sumY = (int) (position.z + tilePositionInLocalSpace.y);
cube1.name = string.Format("Terrain_{0}_{1}", sumX, sumY);
</code>```

Title: How can I convert float to int?

Body:
cube1.name = string.Format("Terrain_{0}_{1}",
    (int)Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x,
    (int)Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);

Tried to cast it for int but it didn't change much.
The name of each cube is still for example: Terrain_6.5_5.5. But I want the name to be Terrain_6_5.

tilePositionInLocalSpace is vector3 type and both x are float type.

Body:
You've just got a precedence problem. You've got:

(int) x + y

which is equivalent to

((int) x) + y

... which will then promote the result of the cast back to a float in order to perform floating point addition. Just make the cast apply to the whole result instead:

(int) (x + y)

Where x and y are the rather long expressions in your original code, of course. For the sake of readability, I'd extract the two values to separate local variables, so you'd have:

int sumX = (int) (Terrain.activeTerrain.transform.position.x + tilePositionInLocalSpace.x);
int sumY = (int) (Terrain.activeTerrain.transform.position.z + tilePositionInLocalSpace.y);
cube1.name = string.Format("Terrain_{0}_{1}", sumX, sumY);

Or better still:

var position = Terrain.activeTerrain.transform.position;
int sumX = (int) (position.x + tilePositionInLocalSpace.x);
int sumY = (int) (position.z + tilePositionInLocalSpace.y);
cube1.name = string.Format("Terrain_{0}_{1}", sumX, sumY);


问:
Breadcrumbs in Highcharts large treemap
I have a requirement to show breadcrumbs in High charts large tree map as we drill down the level.

As we drill down, need to show the name in the breadcrumbs and user should be able to navigate.

Something similar to the Breadcrumbs in highchart-treemap
But I could not find any solution. Let me know how to achieve this

答:
Drilldown events are not available for a treemap series. Instead you can use point click event for displaying/destroying breadcrumb element - a label.

Disable drill up button:

```<code>Highcharts.seriesTypes.treemap.prototype.showDrillUpButton = function () {
  this.drillUpButton = {
    destroy: function () {}
  }
}
</code>```

Function for creating a breadcrumb element can look like this:

```<code>function makeNode(id, name, series, prev) {
  const chart = series.chart
  const node = {
    id,
    name
  }
  let x = chart.plotLeft

  if (prev) {
    const { width, height, y } = prev.element.getBBox()
    x = width + prev.x + 10
    node.prev = prev
    prev.next = node

        prev.element.attr({
      anchorX: x,
      anchorY: chart.plotTop - 20 + height / 2
    })
  }

  node.destroyNext = function () {
    const next = this.next
    if (next) {
      next.destroyNext()
      next.element.destroy()
      delete this.next
      delete chart.bread[next.id]
    }
  }

  const element = node.element = chart.renderer.label(name, x, chart.plotTop - 20, 'callout').attr({
    fill: '#FFFFEF',
    stroke: 'gray',
    'stroke-width': 2,
    padding: 5,
    r: 5,
    zIndex: 10
  }).add()

  element.on('click', () => {
    node.destroyNext()
    node.element.attr({
      anchorX: undefined,
      anchorY: undefined
    })
    if (chart.series[0].rootNode !== '') series.drillToNode(id)
  })

  node.x = x
  return node
}
</code>```

Call that function on chart load:

```<code>chart: {
  events: {
    load: function() {
      this.bread = {
        '': makeNode('', this.series[0].name, this.series[0])
      }
    }
  }
},
</code>```

and on point click event:

```<code>  plotOptions: {
   series: {
      point: {
        events: {
          click: function(e) {
            const hasChildren = !!this.node.childrenTotal

            if (hasChildren) {
              const bread = this.series.chart.bread
              bread[this.id] = makeNode(this.id, this.name, this.series, bread[this.node.parent])
            }
          }
        }
      }
    }
  },
</code>```

Example and output

http://jsfiddle.net/z0zc1btk/

Title: Breadcrumbs in Highcharts large treemap

Body:
Drilldown events are not available for a treemap series. Instead you can use point click event for displaying/destroying breadcrumb element - a label.

Disable drill up button:

Highcharts.seriesTypes.treemap.prototype.showDrillUpButton = function () {
  this.drillUpButton = {
    destroy: function () {}
  }
}

Function for creating a breadcrumb element can look like this:

function makeNode(id, name, series, prev) {
  const chart = series.chart
  const node = {
    id,
    name
  }
  let x = chart.plotLeft

  if (prev) {
    const { width, height, y } = prev.element.getBBox()
    x = width + prev.x + 10
    node.prev = prev
    prev.next = node

        prev.element.attr({
      anchorX: x,
      anchorY: chart.plotTop - 20 + height / 2
    })
  }

  node.destroyNext = function () {
    const next = this.next
    if (next) {
      next.destroyNext()
      next.element.destroy()
      delete this.next
      delete chart.bread[next.id]
    }
  }

  const element = node.element = chart.renderer.label(name, x, chart.plotTop - 20, 'callout').attr({
    fill: '#FFFFEF',
    stroke: 'gray',
    'stroke-width': 2,
    padding: 5,
    r: 5,
    zIndex: 10
  }).add()

  element.on('click', () => {
    node.destroyNext()
    node.element.attr({
      anchorX: undefined,
      anchorY: undefined
    })
    if (chart.series[0].rootNode !== '') series.drillToNode(id)
  })

  node.x = x
  return node
}

Call that function on chart load:

chart: {
  events: {
    load: function() {
      this.bread = {
        '': makeNode('', this.series[0].name, this.series[0])
      }
    }
  }
},

and on point click event:

  plotOptions: {
   series: {
      point: {
        events: {
          click: function(e) {
            const hasChildren = !!this.node.childrenTotal

            if (hasChildren) {
              const bread = this.series.chart.bread
              bread[this.id] = makeNode(this.id, this.name, this.series, bread[this.node.parent])
            }
          }
        }
      }
    }
  },

Example and output

http://jsfiddle.net/z0zc1btk/


问:
Accessing MySQL from PHP and another process at the same time
I'm writing a program that runs (24/7) on a Linux server and adds entries to a MySQL database.
The contents of the database are presented on a web interface with PHP and the user should be able to delete entries using the web interface.
Is it possible to access the database from multiple processes at the same time?</p>

答: Unless you're doing something like accessing the DB using a singleton, the max number of simultaneous mysql connections php will use is limited in your php.ini.  I believe it defaults to 100.</p>


问:
Property include/exclude on Kotlin data classes
Suppose I only want one or two fields to be included in the generated equals and hashCode implementations (or perhaps exclude one or more fields).  For a simple class, e.g.:

```<code>data class Person(val id: String, val name: String)
</code>```

Groovy has this:

```<code>@EqualsAndHashCode(includes = 'id')
</code>```

Lombok has this:

```<code>@EqualsAndHashCode(of = "id")
</code>```

What is the idiomatic way of doing this in Kotlin?

My approach so far

```<code>data class Person(val id: String) {
   // at least we can guarantee it is present at access time
   var name: String by Delegates.notNull()

   constructor(id: String, name: String): this(id) {
      this.name = name
   }
}
</code>```

Just feels wrong though... I don't really want name to be mutable, and the extra constructor definition is ugly.

答:
I also don't know "the idomatic way" in Kotlin (1.1) to do this...

I ended up overriding equals and hashCode:

```<code>data class Person(val id: String,
                  val name: String) {

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other?.javaClass != javaClass) return false

        other as Person

        if (id != other.id) return false

        return true
    }

    override fun hashCode(): Int {
        return id.hashCode()
    }
}
</code>```

Isn't there a "better" way?

Body:
Suppose I only want one or two fields to be included in the generated equals and hashCode implementations (or perhaps exclude one or more fields).  For a simple class, e.g.:

data class Person(val id: String, val name: String)

Groovy has this:

@EqualsAndHashCode(includes = 'id')

Lombok has this:

@EqualsAndHashCode(of = "id")

What is the idiomatic way of doing this in Kotlin?

My approach so far

data class Person(val id: String) {
   // at least we can guarantee it is present at access time
   var name: String by Delegates.notNull()

   constructor(id: String, name: String): this(id) {
      this.name = name
   }
}

Just feels wrong though... I don't really want name to be mutable, and the extra constructor definition is ugly.

Body:
I also don't know "the idomatic way" in Kotlin (1.1) to do this...

I ended up overriding equals and hashCode:

data class Person(val id: String,
                  val name: String) {

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other?.javaClass != javaClass) return false

        other as Person

        if (id != other.id) return false

        return true
    }

    override fun hashCode(): Int {
        return id.hashCode()
    }
}

Isn't there a "better" way?


问:
how to add complementary intervals in pandas dataframe
Lets say that I have a signal of 100 samples L=100

In this signal I found some intervals that I label as "OK". The intervals are stored in a Pandas DataFrame that looks like this:

```<code>c = pd.DataFrame(np.array([[10,26],[50,84]]),columns=['Start','End'])
c['Value']='OK'
</code>```

How can I add the complementary intervals in another dataframe in order to have something like this

```<code> d = pd.DataFrame(np.array([[0,9],[10,26],[27,49],[50,84],[85,100]]),columns=['Start','End'])
 d['Value']=['Check','OK','Check','OK','Check']
</code>```

答:
I think you need:

```<code>d = pd.merge(d, c, how='left')
d['Value'] = d['Value'].fillna('Check')
print (d)
   Start  End  Value
0      0    9  Check
1     10   26     OK
2     27   49  Check
3     50   84     OK
4     85  100  Check
</code>```

EDIT:

You can use numpy.concatenate with numpy.sort, numpy.column_stack and DataFrame constructor for new df. Last need   merge with fillna by dict for column for replace:

```<code>s = np.sort(np.concatenate([[0], c['Start'].values, c['End'].values + 1]))
e = np.sort(np.concatenate([c['Start'].values - 1, c['End'].values, [100]]))
d =  pd.DataFrame(np.column_stack([s,e]), columns=['Start','End'])
d = pd.merge(d, c, how='left').fillna({'Value':'Check'})
print (d)
   Start  End  Value
0      0    9  Check
1     10   26     OK
2     27   49  Check
3     50   84     OK
4     85  100  Check
</code>```

EDIT1 :

For d was added new values by loc, rehape to Series by stack and shift. Last create df back by unstack:

```<code>b = c.copy()
max_val = 100
min_val = 0
c.loc[-1, 'Start'] = max_val + 1
a = c[['Start','End']].stack(dropna=False).shift().fillna(min_val - 1).astype(int).unstack()
a['Start'] = a['Start'] + 1
a['End'] = a['End'] - 1
a['Value'] = 'Check'
print (a)
    Start  End  Value
 0      0    9  Check
 1     27   49  Check
-1     85  100  Check

d = pd.concat([b, a]).sort_values('Start').reset_index(drop=True)
print (d)
   Start  End  Value
0      0    9  Check
1     10   26     OK
2     27   49  Check
3     50   84     OK
4     85  100  Check
</code>```

Body:
Lets say that I have a signal of 100 samples L=100

In this signal I found some intervals that I label as "OK". The intervals are stored in a Pandas DataFrame that looks like this:

c = pd.DataFrame(np.array([[10,26],[50,84]]),columns=['Start','End'])
c['Value']='OK'

How can I add the complementary intervals in another dataframe in order to have something like this

 d = pd.DataFrame(np.array([[0,9],[10,26],[27,49],[50,84],[85,100]]),columns=['Start','End'])
 d['Value']=['Check','OK','Check','OK','Check']

Body:
I think you need:

d = pd.merge(d, c, how='left')
d['Value'] = d['Value'].fillna('Check')
print (d)
   Start  End  Value
0      0    9  Check
1     10   26     OK
2     27   49  Check
3     50   84     OK
4     85  100  Check

EDIT:

You can use numpy.concatenate with numpy.sort, numpy.column_stack and DataFrame constructor for new df. Last need   merge with fillna by dict for column for replace:

s = np.sort(np.concatenate([[0], c['Start'].values, c['End'].values + 1]))
e = np.sort(np.concatenate([c['Start'].values - 1, c['End'].values, [100]]))
d =  pd.DataFrame(np.column_stack([s,e]), columns=['Start','End'])
d = pd.merge(d, c, how='left').fillna({'Value':'Check'})
print (d)
   Start  End  Value
0      0    9  Check
1     10   26     OK
2     27   49  Check
3     50   84     OK
4     85  100  Check

EDIT1 :

For d was added new values by loc, rehape to Series by stack and shift. Last create df back by unstack:

b = c.copy()
max_val = 100
min_val = 0
c.loc[-1, 'Start'] = max_val + 1
a = c[['Start','End']].stack(dropna=False).shift().fillna(min_val - 1).astype(int).unstack()
a['Start'] = a['Start'] + 1
a['End'] = a['End'] - 1
a['Value'] = 'Check'
print (a)
    Start  End  Value
 0      0    9  Check
 1     27   49  Check
-1     85  100  Check

d = pd.concat([b, a]).sort_values('Start').reset_index(drop=True)
print (d)
   Start  End  Value
0      0    9  Check
1     10   26     OK
2     27   49  Check
3     50   84     OK
4     85  100  Check


问:
How to deepen array by having parent id-s (JavaScript)
The problem is like this. I have a flat array of Comment objects. Every comment object has parent_id in it. Ones without parents have parent_id set to null.
Now I want to have it nested. I mean like you see in HackerNews for example. For example add a field in Comment object, say children and in that field have all comments that are children or grandchildren or whatever of this comment. I did it with heavy way, I want to see much clearer and much more clever algorithm (I think mine is really heavy).
Here is my version.

```<code>find_children(pid = null) => {
  result = comments.filter(pid)
  if(result.length > 0) {
    result.forEach(currentComment => {
      currentComment.children = find_children(currentComment.parent_id)
    }
  }
}
</code>```

EDIT: Well actually I wrote the solution and it's working correctly. I want to get some reviews of it if possible, if it's a acceptable solution, can it be improved and so on.

```<code>export const nest_comments = (comments, parent_id = null) => {
  // defaults to null just to make it easier to call
  const current_children = filter(comments, {'parent_comment': parent_id});
  // first find the children by current parent_id
  if (current_children.length !== 0) { // if it's not empty (termination case)
    // then for each add new field called children which is actually again is
    // chunk of comments, so can be nested, that's why we recurse over
    // array again
    return current_children.map(current_comment => {
      current_comment.children = nest_comments(comments, current_comment.id)
      return current_comment
    })
  }
  else return undefined // undefined as in this case js will ignore the field
    // I think it needs to be other value though
}
</code>```

答:
This may solve your problem

function createCommentsMap(comments) {
  var commentsMap = {};

  for (var i = 0; i < comments.length; i++) {
    commentsMap[comments[i].pid] = comments[i];
  }

  return commentsMap;
}

function createParentChildMap(comments) {
  var parentChildMap = {};

  for (var i = 0; i < comments.length; i++) {
    if (!parentChildMap.hasOwnProperty(comments[i].parent_id)) {
      parentChildMap[comments[i].parent_id] = [];
    }

    parentChildMap[comments[i].parent_id].push(comments[i].pid);
  }

  return parentChildMap;
}

function createNestedStructure(startId, parentArray, commentsMap, parentChildMap) {
  if (!parentChildMap.hasOwnProperty(startId)) {
    return;
  }

  for (var i = 0; i < parentChildMap[startId].length; i++) {
    var comment = commentsMap[parentChildMap[startId][i]];
    if (!comment.hasOwnProperty('children')) {
      comment['children'] = [];
    }

    parentArray.push(comment);
    createNestedStructure(comment.pid, comment.children, commentsMap, parentChildMap);
  }
}

var comments = [{
    pid: 1,
    parent_id: null
  },
  {
    pid: 2,
    parent_id: 1
  },
  {
    pid: 3,
    parent_id: 1
  },
  {
    pid: 4,
    parent_id: 2
  },
  {
    pid: 5,
    parent_id: 4
  },
  {
    pid: 6,
    parent_id: 3
  },
]; // Your comments
var commentsMap = createCommentsMap(comments);
var parentChildMap = createParentChildMap(comments);

var nestedStructure = [];
createNestedStructure('null', nestedStructure, commentsMap, parentChildMap);

// In nestedStructure you will get your desired structure```

Body:
The problem is like this. I have a flat array of Comment objects. Every comment object has parent_id in it. Ones without parents have parent_id set to null.
Now I want to have it nested. I mean like you see in HackerNews for example. For example add a field in Comment object, say children and in that field have all comments that are children or grandchildren or whatever of this comment. I did it with heavy way, I want to see much clearer and much more clever algorithm (I think mine is really heavy).
Here is my version.

find_children(pid = null) => {
  result = comments.filter(pid)
  if(result.length > 0) {
    result.forEach(currentComment => {
      currentComment.children = find_children(currentComment.parent_id)
    }
  }
}

EDIT: Well actually I wrote the solution and it's working correctly. I want to get some reviews of it if possible, if it's a acceptable solution, can it be improved and so on.

export const nest_comments = (comments, parent_id = null) => {
  // defaults to null just to make it easier to call
  const current_children = filter(comments, {'parent_comment': parent_id});
  // first find the children by current parent_id
  if (current_children.length !== 0) { // if it's not empty (termination case)
    // then for each add new field called children which is actually again is
    // chunk of comments, so can be nested, that's why we recurse over
    // array again
    return current_children.map(current_comment => {
      current_comment.children = nest_comments(comments, current_comment.id)
      return current_comment
    })
  }
  else return undefined // undefined as in this case js will ignore the field
    // I think it needs to be other value though
}


问:
How to convert a set of bytes in an array from hexa to decimal (python)?
I have a file which contains in each line a set of bytes for example:

```<code>4655d16c690f2789c2d3e803e388637f
16161b1504137217336d403e2a03c669
fa79c5ffe35d112915f0f3243fc68fb4
87d57d0a63e52b6df869eb5c0aac4328
640c2eefb7829d863f7aa686bc513acc
4024767c463558b7c7cd0ffd4f0aaa6d
18ee0b17f5b5206df0443e658b105990
7b40bf42d2cfc290eed4c4edcb9d3e91
b57dad9833c3e174e05a5ae75cac70ed
</code>```

I want to convert line in an array,then convert byte in decimal, for example:

```<code>4655d16c690f2789c2d3e803e388637f
</code>```

The result is:

```<code>46 55 d1 6c 69 0f 27 89 c2 d3 e8 03 e3 88 63 7f
</code>```

Then convert each byte in decimal:

```<code> [70,85,209,108,105,15,39,137,194,211,232,3,136,227,99,127]
</code>```

I try by using this code ,

```<code>with open(Srcpath, 'r') as f:
        with open(Destpath, 'w') as fp:
            for key in f:
                key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
                rejoined = ' '.join(key_Separated)
                Decimal= [i for i, b in enumerate(rejoined ) if b=='1']
                print(Decimal)
                fp.write(str(Decimal))
</code>```

so it gives this wrong results:

```<code>[43]
[21, 45]
[27, 42]
[13, 31, 37, 42]
[16, 21, 28]
[13, 36]
[12, 43, 46]
[0, 6, 18, 27, 37]
</code>```

How could I correct them please?

Body:
I have a file which contains in each line a set of bytes for example:

4655d16c690f2789c2d3e803e388637f
16161b1504137217336d403e2a03c669
fa79c5ffe35d112915f0f3243fc68fb4
87d57d0a63e52b6df869eb5c0aac4328
640c2eefb7829d863f7aa686bc513acc
4024767c463558b7c7cd0ffd4f0aaa6d
18ee0b17f5b5206df0443e658b105990
7b40bf42d2cfc290eed4c4edcb9d3e91
b57dad9833c3e174e05a5ae75cac70ed

I want to convert line in an array,then convert byte in decimal, for example:

4655d16c690f2789c2d3e803e388637f

The result is:

46 55 d1 6c 69 0f 27 89 c2 d3 e8 03 e3 88 63 7f

Then convert each byte in decimal:

 [70,85,209,108,105,15,39,137,194,211,232,3,136,227,99,127]

I try by using this code ,

with open(Srcpath, 'r') as f:
        with open(Destpath, 'w') as fp:
            for key in f:
                key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
                rejoined = ' '.join(key_Separated)
                Decimal= [i for i, b in enumerate(rejoined ) if b=='1']
                print(Decimal)
                fp.write(str(Decimal))

so it gives this wrong results:

[43]
[21, 45]
[27, 42]
[13, 31, 37, 42]
[16, 21, 28]
[13, 36]
[12, 43, 46]
[0, 6, 18, 27, 37]

How could I correct them please?

Body:
This should do the trick:

import re

data = '''4655d16c690f2789c2d3e803e388637f
16161b1504137217336d403e2a03c669
fa79c5ffe35d112915f0f3243fc68fb4
87d57d0a63e52b6df869eb5c0aac4328
640c2eefb7829d863f7aa686bc513acc
4024767c463558b7c7cd0ffd4f0aaa6d
18ee0b17f5b5206df0443e658b105990
7b40bf42d2cfc290eed4c4edcb9d3e91
b57dad9833c3e174e05a5ae75cac70ed'''

data = [re.findall('..', item) for item in data.split('\n') if item]
result = [[int(x, 16) for x in item] for item in data]


问:
ng-repeat with ng-click not working properly
i got some new issues in my spa with angularjs.

THIS ist my HTML:

                    {{friend.friend_username}} - {{friend.gamename}}
                ```
</div>
</div>
</p>

<p>This is my controller:</p>

```"use strict";

    app.controller("chatCtrl", ["userService", "socket" , "chatService", "$scope", function (userService, socket , chatService, $scope) {
        var self = this;

        self.friendlist = chatService.friendlist;

        chatService.init(userService.username);

        $scope.loadChat = function (username) {
            console.log(username); //console logs {{friend.friend_username}}
            chatService.chatWith(username);
        }

    }]);
```

Everything is working properly except the username within the loadChat function.
The username console logs {{friend.friend_username}} and not the value of friend.friend_username as i want to do. Within the DOM everything looks fine. ng-click="loadChat('USERNAME')" is shown properly but in chat controller the username is set as {{friend.friend_username}}. I´ve no clue why this happens. I hope someone can help me to figure this out.

答:
Directly pass the user name to ngClick, Don't use string interpolation

```<code><a ng-click="loadChat(friend.friend_username)" >
</code>```

Body:
i got some new issues in my spa with angularjs.

THIS ist my HTML:

                    {{friend.friend_username}} - {{friend.gamename}}

This is my controller:

"use strict";

    app.controller("chatCtrl", ["userService", "socket" , "chatService", "$scope", function (userService, socket , chatService, $scope) {
        var self = this;

        self.friendlist = chatService.friendlist;

        chatService.init(userService.username);

        $scope.loadChat = function (username) {
            console.log(username); //console logs {{friend.friend_username}}
            chatService.chatWith(username);
        }

    }]);

Everything is working properly except the username within the loadChat function.
The username console logs {{friend.friend_username}} and not the value of friend.friend_username as i want to do. Within the DOM everything looks fine. ng-click="loadChat('USERNAME')" is shown properly but in chat controller the username is set as {{friend.friend_username}}. I´ve no clue why this happens. I hope someone can help me to figure this out.

Body:
Directly pass the user name to ngClick, Don't use string interpolation

<a ng-click="loadChat(friend.friend_username)" >


问:
How can I write a list of objects to firebase?
I am trying to write multiple nodes at one go in Firebase, my data class

```<code>@IgnoreExtraProperties
public class Data{
    public String desc;
    public double id;
    public data(String desc,double id) {
        this.id=id;
        this.desc=desc;
    }
}
</code>```

And I am trying this

```<code>   .....//firebase auth ok

    ArrayList<Data> mydata= new ArrayList<>();
    mydata.add(new Items("data1",1));
    mydata.add(new Items("data2",2));
    mDatabase.child("DATA").setValue(mydata);
</code>```

But this fails as firebase doesn't support Listarray I guess, as I am getting the error

com.google.firebase.database.DatabaseException: No properties to
  serialize found on class android.support.v4.app.LoaderManagerImpl

答:
First of all your constructor from your model si wrong, needs to be Data in stead of data. You getting such an error because you are using a List in stead of an Map. Change this line of codes:

```<code>ArrayList<Data> mydata= new ArrayList<>();
mydata.add(new Items("data1",1));
mydata.add(new Items("data2",2));
mDatabase.child("DATA").setValue(mydata);
</code>```

with

```<code>DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference pushedKey = mDatabase.child("DATA").push();
Data data = new Data("data1", 1));
pushedKey.setValue(data);
</code>```

In this way you'll have also different keys for every new object.

Hope it helps.

Body:
I am trying to write multiple nodes at one go in Firebase, my data class

@IgnoreExtraProperties
public class Data{
    public String desc;
    public double id;
    public data(String desc,double id) {
        this.id=id;
        this.desc=desc;
    }
}

And I am trying this

   .....//firebase auth ok

    ArrayList<Data> mydata= new ArrayList<>();
    mydata.add(new Items("data1",1));
    mydata.add(new Items("data2",2));
    mDatabase.child("DATA").setValue(mydata);

But this fails as firebase doesn't support Listarray I guess, as I am getting the error

com.google.firebase.database.DatabaseException: No properties to
  serialize found on class android.support.v4.app.LoaderManagerImpl

Body:
First of all your constructor from your model si wrong, needs to be Data in stead of data. You getting such an error because you are using a List in stead of an Map. Change this line of codes:

ArrayList<Data> mydata= new ArrayList<>();
mydata.add(new Items("data1",1));
mydata.add(new Items("data2",2));
mDatabase.child("DATA").setValue(mydata);

with

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
DatabaseReference pushedKey = mDatabase.child("DATA").push();
Data data = new Data("data1", 1));
pushedKey.setValue(data);

In this way you'll have also different keys for every new object.

Hope it helps.


答:
Yes, databases are designed for this purpose quite well.  You'll want to keep a few things in mind in your designs:

Concurrency and race conditions on database writes.

Performance.

Separate database permissions for separate applications.

Title: Accessing MySQL from PHP and another process at the same time

Body:
I'm writing a program that runs (24/7) on a Linux server and adds entries to a MySQL database.
The contents of the database are presented on a web interface with PHP and the user should be able to delete entries using the web interface.
Is it possible to access the database from multiple processes at the same time?