问:
XML validation failing in java with schemaLocation a local file
I'm attempting to validate some XML against a relative XSD file in java

input file temp.xml:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tagname:b
        xmlns:tagname="http://my_namespace.org/v1"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://my_namespace.org/v1 ./local_xsd_file.xsd">
</tagname>
</code>```

java source:

```<code>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(new FileInputStream(filename)));

public static class RaiseOnErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
  public void error(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
}
</code>```

The local file local_xsd_file.xsd exists and appears to be not being read.

error message

```<code>java.lang.RuntimeException: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 85; schema_reference.4: Failed to read schema document './local_xsd_file.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at org.XX$RaiseOnErrorHandler.warning(DigitalFileWriterTest.java:1114)
    at org.apache.xerces.util.ErrorHandlerWrapper.warning(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.reportSchemaWarning(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.getSchemaDocument(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.findSchemaGrammar(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    ... 50 more
</code>```

I have also tried using file://local_xsd_file.xsd and file://./local_xsd_file.xsd (which should be possible) as the schemaLocation, all with the same results.  If I use an "absolute path" like file:///full/path/to/local_xsd_file.xsd then it works.  If I use a URL for the schema's location it reads them off that server and works fine.

Changing my current working directory to be one where a local_xsd_file.xsd exists will make it work, so apparently this works but only relative to your current working directory?

Is it possible to use a relative path with validation in java?  It feels like an implementation detail perhaps?

答:
When you build a document like this:

```<code>DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(new FileInputStream(filename)));
</code>```

the base URI of the document is not known (because the builder only sees an InputStream, and has no way of finding out that this is reading a particular file). Try using one of the parse() methods from which a base URI can be established, e.g. parse(file.toString()) or saxParser.parse(file, (DefaultHandler) null);.

Without a base URI, there is no sensible way to resolve a relative URI. The system might use the current directory (which seems to be happening here) or it might report an error.

Body:
I'm attempting to validate some XML against a relative XSD file in java

input file temp.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tagname:b
        xmlns:tagname="http://my_namespace.org/v1"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://my_namespace.org/v1 ./local_xsd_file.xsd">
</tagname>

java source:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(new FileInputStream(filename)));

public static class RaiseOnErrorHandler implements ErrorHandler {
  public void warning(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
  public void error(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
  public void fatalError(SAXParseException e) throws SAXException {
    throw new RuntimeException(e);
  }
}

The local file local_xsd_file.xsd exists and appears to be not being read.

error message

java.lang.RuntimeException: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 85; schema_reference.4: Failed to read schema document './local_xsd_file.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
    at org.XX$RaiseOnErrorHandler.warning(DigitalFileWriterTest.java:1114)
    at org.apache.xerces.util.ErrorHandlerWrapper.warning(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.reportSchemaWarning(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.getSchemaDocument(Unknown Source)
    at org.apache.xerces.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.findSchemaGrammar(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
    at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
    at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
    at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
    at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    ... 50 more

I have also tried using file://local_xsd_file.xsd and file://./local_xsd_file.xsd (which should be possible) as the schemaLocation, all with the same results.  If I use an "absolute path" like file:///full/path/to/local_xsd_file.xsd then it works.  If I use a URL for the schema's location it reads them off that server and works fine.

Changing my current working directory to be one where a local_xsd_file.xsd exists will make it work, so apparently this works but only relative to your current working directory?

Is it possible to use a relative path with validation in java?  It feels like an implementation detail perhaps?

Body:
When you build a document like this:

DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(new FileInputStream(filename)));

the base URI of the document is not known (because the builder only sees an InputStream, and has no way of finding out that this is reading a particular file). Try using one of the parse() methods from which a base URI can be established, e.g. parse(file.toString()) or saxParser.parse(file, (DefaultHandler) null);.

Without a base URI, there is no sensible way to resolve a relative URI. The system might use the current directory (which seems to be happening here) or it might report an error.


来源: stackexchange

问:
React Native Set State not a function, in a for each loop not sure about binding?
I have the following code, on my component mount but I'm getting set state is not a function error which I know is a binding issue but I'm not where I should be doing the binding?   </p>

```<code>const selectedTag = this.props.tag;

        // Checks to see if this should be selected
        let checkSelected = function(arr, val) {
            _(arr).each(function(value) {
                if (value == val) {
                    this.setState({checked: true})
                }
            });
        };
        checkSelected(this.props.selectedTags, selectedTag)
        console.log(this.state.checked)
</code>```

答:
Use arrow function to keep the scope of this intact :

```<code> let checkSelected =(arr, val) =>  {
        _(arr).each((value) =>  {
            if (value == val) {
                this.setState({checked: true})
            }
        });
    };
</code>```

and NOT  :

```<code> let checkSelected = function(arr, val) {
        _(arr).each(function(value) {
            if (value == val) {
                this.setState({checked: true})
            }
        });
    };
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code, on my component mount but I'm getting set state is not a function error which I know is a binding issue but I'm not where I should be doing the binding?

const selectedTag = this.props.tag;

        // Checks to see if this should be selected
        let checkSelected = function(arr, val) {
            _(arr).each(function(value) {
                if (value == val) {
                    this.setState({checked: true})
                }
            });
        };
        checkSelected(this.props.selectedTags, selectedTag)
        console.log(this.state.checked)

Body:
Use arrow function to keep the scope of this intact :

 let checkSelected =(arr, val) =>  {
        _(arr).each((value) =>  {
            if (value == val) {
                this.setState({checked: true})
            }
        });
    };

and NOT  :

 let checkSelected = function(arr, val) {
        _(arr).each(function(value) {
            if (value == val) {
                this.setState({checked: true})
            }
        });
    };


问:
WordPress Anonymous Postings?
My client wants to create a form on his new WP site that when filled out and submitted will be submitted to his admin post queue to approve and if he approves gets posted on his site in the "blog" (which is actually a bunch of guitar like tabs). The form would be custom and have custom fields. Below is the form, but in the old design before I did a refresh on it.

So, how hard would this be? He does not want it in the WP admin panel which i began to do, but outside in a page like /contribute

答: The Anonymous Posting plugin appears to do what you're looking for.</p>

ContentLicense: CC BY-SA 2.5

Title: WordPress Anonymous Postings?


问:
Units of time calculation in R
This is a sample of the data I have.I have columns with the read dates.I converted the readdate column into date format using the function as.POSIXct().

```<code>data$readdate=as.POSIXct(data$readdate,format="%Y-%m-%d %H:%M:%S")

ID   readdate                   tdiff
A    2016-06-01 06:00:06          0
B    2016-06-01 06:01:06          1
C    2016-06-01 06:03:06          2
D    2016-06-01 06:04:06          1
E    2016-06-01 06:04:56          50
F    2016-06-01 08:04:56          2
</code>```

I need the third column tdiff to show the time elapsed between two ID's.I used a loop and

```<code>for(i in 1:nrow(data)){
tdiff=data$readdate[i+1]-data$readdate[i]}
</code>```

The problem with using this method is R rounds up the units of the time.I want the tdiff column to consist of a single type of units(such as seconds or mins) similar to this

```<code>ID   readdate                   tdiff(seconds)  or tdiff(mins)
A    2016-06-01 06:00:06          0                    0
B    2016-06-01 06:01:06          60                   1
C    2016-06-01 06:03:06          120                  2
D    2016-06-01 06:04:06          60                   1
E    2016-06-01 06:04:56          50                   0.5
F    2016-06-01 08:04:56          7200                 120
</code>```

I need all of them to be similar, because later I have to extract all IDs which have a tdiff of greater than 30 mins.

答:
I think the easiest is to use difftime with the unit you want from c("auto", "secs", "mins", "hours", " days", "weeks")

For seconds use:

```<code>difftime(data$readdate[i+1], data$readdate[i], units="secs")
</code>```

Title: Units of time calculation in R

Body:
This is a sample of the data I have.I have columns with the read dates.I converted the readdate column into date format using the function as.POSIXct().

data$readdate=as.POSIXct(data$readdate,format="%Y-%m-%d %H:%M:%S")

ID   readdate                   tdiff
A    2016-06-01 06:00:06          0
B    2016-06-01 06:01:06          1
C    2016-06-01 06:03:06          2
D    2016-06-01 06:04:06          1
E    2016-06-01 06:04:56          50
F    2016-06-01 08:04:56          2

I need the third column tdiff to show the time elapsed between two ID's.I used a loop and

for(i in 1:nrow(data)){
tdiff=data$readdate[i+1]-data$readdate[i]}

The problem with using this method is R rounds up the units of the time.I want the tdiff column to consist of a single type of units(such as seconds or mins) similar to this

ID   readdate                   tdiff(seconds)  or tdiff(mins)
A    2016-06-01 06:00:06          0                    0
B    2016-06-01 06:01:06          60                   1
C    2016-06-01 06:03:06          120                  2
D    2016-06-01 06:04:06          60                   1
E    2016-06-01 06:04:56          50                   0.5
F    2016-06-01 08:04:56          7200                 120

I need all of them to be similar, because later I have to extract all IDs which have a tdiff of greater than 30 mins.

Body:
I think the easiest is to use difftime with the unit you want from c("auto", "secs", "mins", "hours", " days", "weeks")

For seconds use:

difftime(data$readdate[i+1], data$readdate[i], units="secs")


问:
Ignoring rows within daterange
I have the following data:

```<code>CREATE TABLE SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO SampleData
VALUES
(1, 'a', '2017-01-01'),
(2, 'a', '2017-01-05'),
(3, 'a', '2017-02-01'),
(4, 'a', '2017-04-01'),
(5, 'a', '2017-10-01'),
(6, 'b', '2017-04-01');
</code>```

I need to retrieve each new order according to the following rules:

The first date for a name is the 'current order' for that name

Orders with the same name, but less than 3 months difference with the 'current order' is considered the same order and needs to be ignored

3 months or more difference with the 'current' order is considered a new order and is now the 'current order' (in the SampleData orderid 1 and 4 need to be compared instead of 3 and 4, because 3 is not the current order)

If the name and date are the same, then the row with the lowest orderid is the superior order

So with the sample data I need the following result:

```<code>id name, date
1  a     2017-01-01
4  a     2017-04-01
5  a     2017-10-01
6  b     2017-04-01
</code>```

I tried several approaches, but without success. Any idea's on how I can achieve this?

答:
Below is a quick fix solution that can be built upon if your code scales beyond the sample data provided. I will state beforehand that this isn't the prettiest solution but it does return the result set you indicated you were after.

If anything, you may want to consider looking into T-SQL Window Functions as well as Analytic Functions. I will advice that that they don't play well with all datatypes.

My goal with the solution below was to rank the rows while partitioning by name and order by the date field. Thus you have something similar to your order id but the rank is specific to the customer who placed the order.

I'll do my best to answer any questions:

```<code>if object_id('tempdb..#tmp_SampleData','u') is not null
    drop table #tmp_SampleData

CREATE TABLE #tmp_SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO #tmp_SampleData
VALUES
(1, 'a', '2017-01-01'),
(2, 'a', '2017-01-05'),
(3, 'a', '2017-02-01'),
(4, 'a', '2017-04-01'),
(5, 'a', '2017-10-01'),
(6, 'b', '2017-04-01');

if object_id('tempdb..#tmp_iter','u') is not null
    drop table #tmp_iter

select
 orderid
,name
,date
,rank() over (partition by name order by date) [Rank]
,lag(orderid,1,0) over (partition by name order by date) [LagRank]
--,rank() over (partition by name order by date desc) [ReverseRank]
into #tmp_Iter
from #tmp_SampleData

if object_id('tempdb..#tmp_final','u') is not null
    drop table #tmp_final

select
 i.orderid
,i.name
,i.date
,datediff(month,i.date,i2.date) [MonthsPassed]
into #tmp_final
from #tmp_Iter i
    left join #tmp_Iter i2
        on i.Rank = i2.LagRank

select *
from #tmp_final
where 1=1
and MonthsPassed > 3
or MonthsPassed = 0
or MonthsPassed < 0
or MonthsPassed is null
</code>```

Title: Ignoring rows within daterange

Body:
I have the following data:

CREATE TABLE SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO SampleData
VALUES
(1, 'a', '2017-01-01'),
(2, 'a', '2017-01-05'),
(3, 'a', '2017-02-01'),
(4, 'a', '2017-04-01'),
(5, 'a', '2017-10-01'),
(6, 'b', '2017-04-01');

I need to retrieve each new order according to the following rules:

The first date for a name is the 'current order' for that name

Orders with the same name, but less than 3 months difference with the 'current order' is considered the same order and needs to be ignored

3 months or more difference with the 'current' order is considered a new order and is now the 'current order' (in the SampleData orderid 1 and 4 need to be compared instead of 3 and 4, because 3 is not the current order)

If the name and date are the same, then the row with the lowest orderid is the superior order

So with the sample data I need the following result:

id name, date
1  a     2017-01-01
4  a     2017-04-01
5  a     2017-10-01
6  b     2017-04-01

I tried several approaches, but without success. Any idea's on how I can achieve this?

Body:
Below is a quick fix solution that can be built upon if your code scales beyond the sample data provided. I will state beforehand that this isn't the prettiest solution but it does return the result set you indicated you were after.

If anything, you may want to consider looking into T-SQL Window Functions as well as Analytic Functions. I will advice that that they don't play well with all datatypes.

My goal with the solution below was to rank the rows while partitioning by name and order by the date field. Thus you have something similar to your order id but the rank is specific to the customer who placed the order.

I'll do my best to answer any questions:

if object_id('tempdb..#tmp_SampleData','u') is not null
    drop table #tmp_SampleData

CREATE TABLE #tmp_SampleData
(
    orderid int,
    [name] nvarchar(1),
    [date] date
);
INSERT INTO #tmp_SampleData
VALUES
(1, 'a', '2017-01-01'),
(2, 'a', '2017-01-05'),
(3, 'a', '2017-02-01'),
(4, 'a', '2017-04-01'),
(5, 'a', '2017-10-01'),
(6, 'b', '2017-04-01');

if object_id('tempdb..#tmp_iter','u') is not null
    drop table #tmp_iter

select
 orderid
,name
,date
,rank() over (partition by name order by date) [Rank]
,lag(orderid,1,0) over (partition by name order by date) [LagRank]
--,rank() over (partition by name order by date desc) [ReverseRank]
into #tmp_Iter
from #tmp_SampleData

if object_id('tempdb..#tmp_final','u') is not null
    drop table #tmp_final

select
 i.orderid
,i.name
,i.date
,datediff(month,i.date,i2.date) [MonthsPassed]
into #tmp_final
from #tmp_Iter i
    left join #tmp_Iter i2
        on i.Rank = i2.LagRank

select *
from #tmp_final
where 1=1
and MonthsPassed > 3
or MonthsPassed = 0
or MonthsPassed < 0
or MonthsPassed is null


问:
Form built with FormBuilder is not updated after Service subscribe
My form is displayed correctly, although the data from the Service is not being applied to the form controls when this.getUser(+id); is executed and there are no errors on Development Tools console. I can see the successful HTTP request/response via Development Tool, but can't see the update in my form.

What is wrong with my code?

Component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NotificationsService } from 'angular2-notifications';

import { UsersService } from '../../core/services/users.service';

import { User } from '../../shared/interfaces/user';

@Component({
  templateUrl: './users-form.component.html',
  styleUrls: ['./users-form.component.scss'],
    providers: [UsersService]
})
export class UsersFormComponent implements OnInit {

  userForm: FormGroup;
  user: User = {
    name: '',
    username: '',
    roleId: 3
  };

  formMode = 'Cadastro';

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private usersService: UsersService,
    private formBuilder: FormBuilder,
    private notification: NotificationsService) { }

  ngOnInit() {
    const id = this.route.snapshot.params['id'];
    this.buildForm();
    if (id) {
      this.formMode = 'Edição';
      this.getUser(+id);
    }
  }

  getUser(id: number) {
    this.usersService.getUserById(id)
      .subscribe((user: User) => {
        this.user = user;
      },
      (err) => console.log(err));
  }

  buildForm() {
    this.userForm = this.formBuilder.group({
      name: [this.user.name, Validators.required],
      username: [this.user.username, Validators.required],
      roleId: [this.user.roleId, Validators.required]
    });
  }

  submit({ value, valid }: { value: User, valid: boolean }) {

    value.id = this.user.id;

    if (value.id) {
      this.usersService.update(value)
        .subscribe((res: User) => {
          if (res) {
            this.router.navigate(['/users']);
            this.notification.success('Sucesso!', 'Registro atualizado.');
          } else {
            this.notification.error('Erro!', 'Registro não atualizado.');
          }
        },
        (err) => console.log(err));
    } else {
      this.usersService.insert(value)
        .subscribe((res: User) => {
          if (res) {
            this.router.navigate(['/users']);
            this.notification.success('Sucesso!', 'Cadastro realizado.');
          } else {
            this.notification.error('Erro!', 'Cadastro não realizado.');
          }
        },
        (err) => console.log(err));
    }
  }
}
</code>```

Component.html

```<code><div class="animated fadeIn">
  <div class="row">
    <div class="col-sm-12">
      <div class="card">
        <div class="card-header">
          <strong>Usuário</strong>
          <small>{{formMode}}</small>
        </div>
        <div class="card-block">
          <form [formGroup]="userForm" (ngSubmit)="submit(userForm)" novalidate>
            <div class="form-group">
              <label for="name">Nome</label>
              <input type="text" class="form-control" id="name" placeholder="Informe o nome" formControlName="name">
              <div class="alert alert-danger" [hidden]="userForm.controls.name">Campo Nome requerido</div>
            </div>
            <div class="form-group">
              <label for="login">Login</label>
              <input type="text" class="form-control" id="username" placeholder="Informe o login" formControlName="username">
              <div class="alert alert-danger" [hidden]="userForm.controls.username">Campo Login requerido</div>
            </div>
            <div class="form-group">
              <label for="role">Perfil</label>
              <select class="form-control" id="role" formControlName="roleId">
                <option value="1">Supervisor</option>
                <option value="2">Analista</option>
                <option value="3">Inspetor</option>
              </select>
              <div class="alert alert-danger" [hidden]="userForm.controls.roleId">Campo Perfil requerido</div>
            </div>
            <div class="form-group">
              <button class="btn btn-primary" type="submit" [disabled]="!userForm.valid">Salvar</button>
              <button [routerLink]="['/users']" class="btn btn-secondary" type="button">Cancelar</button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <!--/.col-->
  </div>
  <!--/.row-->
</div>
</code>```

答:
You're close. But you'll need to update the form using the new values when they become available. When you instantiate the form using the following:

name: [this.user.name, Validators.required],

You are only telling the form to pre-populate the name property with the value of this.user.name, which hasn't yet resolved (I'm guessing). Its not a binding, just an initial value. And in this case, your form is being instantiated faster than your getUser() function is retrieving the user data.

The easiest thing you can do is wait to build the form until your API call has resolved.

getUser(id: number) {
    this.usersService.getUserById(id)
      .subscribe((user: User) => {
        this.user = user;

        // Now your form will have access to the correct data
        this.buildForm();
      },
      (err) => console.log(err));
  }
```

<p>In more complex scenarios, you may need to loop through data and merge multiple subscriptions. In those situations you can instantiate the form with blank values and then update the values as your API calls come in.</p>

<pre class="lang-js prettyprint-override"><code>getUser(id: number) {
    this.usersService.getUserById(id)
      .subscribe((user: User) => {
        this.user = user

                // Update the Form Values
                if (this.userForm) {
                    this.userForm.get('name').setValue(this.user.name);
                    this.userForm.get('username').setValue(this.user.username);
                    this.userForm.get('roleID').setValue(this.user.roleID);
                }
      },
      (err) => console.log(err));
  }
</code>```

Body:
My form is displayed correctly, although the data from the Service is not being applied to the form controls when this.getUser(+id); is executed and there are no errors on Development Tools console. I can see the successful HTTP request/response via Development Tool, but can't see the update in my form.

What is wrong with my code?

Component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NotificationsService } from 'angular2-notifications';

import { UsersService } from '../../core/services/users.service';

import { User } from '../../shared/interfaces/user';

@Component({
  templateUrl: './users-form.component.html',
  styleUrls: ['./users-form.component.scss'],
    providers: [UsersService]
})
export class UsersFormComponent implements OnInit {

  userForm: FormGroup;
  user: User = {
    name: '',
    username: '',
    roleId: 3
  };

  formMode = 'Cadastro';

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private usersService: UsersService,
    private formBuilder: FormBuilder,
    private notification: NotificationsService) { }

  ngOnInit() {
    const id = this.route.snapshot.params['id'];
    this.buildForm();
    if (id) {
      this.formMode = 'Edição';
      this.getUser(+id);
    }
  }

  getUser(id: number) {
    this.usersService.getUserById(id)
      .subscribe((user: User) => {
        this.user = user;
      },
      (err) => console.log(err));
  }

  buildForm() {
    this.userForm = this.formBuilder.group({
      name: [this.user.name, Validators.required],
      username: [this.user.username, Validators.required],
      roleId: [this.user.roleId, Validators.required]
    });
  }

  submit({ value, valid }: { value: User, valid: boolean }) {

    value.id = this.user.id;

    if (value.id) {
      this.usersService.update(value)
        .subscribe((res: User) => {
          if (res) {
            this.router.navigate(['/users']);
            this.notification.success('Sucesso!', 'Registro atualizado.');
          } else {
            this.notification.error('Erro!', 'Registro não atualizado.');
          }
        },
        (err) => console.log(err));
    } else {
      this.usersService.insert(value)
        .subscribe((res: User) => {
          if (res) {
            this.router.navigate(['/users']);
            this.notification.success('Sucesso!', 'Cadastro realizado.');
          } else {
            this.notification.error('Erro!', 'Cadastro não realizado.');
          }
        },
        (err) => console.log(err));
    }
  }
}

Component.html

          Usuário
          {{formMode}}

          <form [formGroup]="userForm" (ngSubmit)="submit(userForm)" novalidate>

              Nome
              <input type="text" class="form-control" id="name" placeholder="Informe o nome" formControlName="name">

Campo Nome requerido

              Login
              <input type="text" class="form-control" id="username" placeholder="Informe o login" formControlName="username">

Campo Login requerido

              Perfil
              <select class="form-control" id="role" formControlName="roleId">
                <option value="1">Supervisor</option>
                <option value="2">Analista</option>
                <option value="3">Inspetor</option>
              </select>

Campo Perfil requerido

              <button class="btn btn-primary" type="submit" [disabled]="!userForm.valid">Salvar</button>
              <button [routerLink]="['/users']" class="btn btn-secondary" type="button">Cancelar</button>

          </form>

Body:
You're close. But you'll need to update the form using the new values when they become available. When you instantiate the form using the following:

name: [this.user.name, Validators.required],

You are only telling the form to pre-populate the name property with the value of this.user.name, which hasn't yet resolved (I'm guessing). Its not a binding, just an initial value. And in this case, your form is being instantiated faster than your getUser() function is retrieving the user data.

The easiest thing you can do is wait to build the form until your API call has resolved.

getUser(id: number) {
    this.usersService.getUserById(id)
      .subscribe((user: User) => {
        this.user = user;

        // Now your form will have access to the correct data
        this.buildForm();
      },
      (err) => console.log(err));
  }

In more complex scenarios, you may need to loop through data and merge multiple subscriptions. In those situations you can instantiate the form with blank values and then update the values as your API calls come in.

getUser(id: number) {
    this.usersService.getUserById(id)
      .subscribe((user: User) => {
        this.user = user

                // Update the Form Values
                if (this.userForm) {
                    this.userForm.get('name').setValue(this.user.name);
                    this.userForm.get('username').setValue(this.user.username);
                    this.userForm.get('roleID').setValue(this.user.roleID);
                }
      },
      (err) => console.log(err));
  }


问:
Dart's http server throws exception
This simple dart program starts and runs for a while, but after some interactions it throws an exception:

```<code>import 'dart:io';
import 'package:http_server/http_server.dart';

main() async {

  //files
  var staticFiles = new VirtualDirectory("/path ....");
  staticFiles.allowDirectoryListing = true;
  staticFiles.directoryHandler = (dir, request) {
    var indexUri = new Uri.file(dir.path).resolve('index.html');
    staticFiles.serveFile(new File(indexUri.toFilePath()), request);
  };

  //http
  HttpServer
    .bind(InternetAddress.ANY_IP_V6, 80)
    .then((server) {
      server.forEach(staticFiles.serveRequest);
    }
  );

  //https
  SecurityContext context = new SecurityContext();
  var chain =   Platform.script.resolve('file.pem').toFilePath();
  var key =    Platform.script.resolve('file.pem').toFilePath();
  context.useCertificateChain(chain);
  context.usePrivateKey(key, password: 'pwd');
  HttpServer
    .bindSecure(InternetAddress.ANY_IP_V6, 443, context)
    .then((server) {
      server.forEach(staticFiles.serveRequest);
    }
  );
}
</code>```

After some time it crashes. The Exception is:

```<code>Unhandled exception:
SocketException: OS Error: Broken pipe, errno = 32, address = ::, port = 443
#0      _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:1108)
#1      _microtaskLoop (dart:async/schedule_microtask.dart:41)
#2      _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
#3      _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:99)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:152)
</code>```

Is it a bug?

How can I solve the problem?

And ... a different topic ... why can I start the https server without providing an appropriate password? I expect the server to check if the password is correct?!

I tried to solve it catching exceptions

```<code>import 'dart:io';
import 'package:http_server/http_server.dart';

main() async {

  //files
  var staticFiles = new VirtualDirectory("file");
  staticFiles.allowDirectoryListing = true;
  staticFiles.directoryHandler = (dir, request) {
    try{
      var indexUri = new Uri.file(dir.path).resolve('index.html');
      staticFiles.serveFile(new File(indexUri.toFilePath()), request);
    } catch(a,b) {
      print(a);
      print(b);
    }
  };

  //http
  HttpServer
    .bind(InternetAddress.ANY_IP_V6, 80)
    .then((server) {
      try{
        server.forEach(staticFiles.serveRequest);
      } catch(a,b)
      {
        print(a);
        print(b);
      }
    }
  );

  //https
  SecurityContext context = new SecurityContext();
  var chain =   Platform.script.resolve('file.pem').toFilePath();
  var key =    Platform.script.resolve('file.pem').toFilePath();
  context.useCertificateChain(chain);
  context.usePrivateKey(key, password: 'pwd');
  HttpServer
    .bindSecure(InternetAddress.ANY_IP_V6, 443, context)
    .then((server) {
        try {
          server.forEach(staticFiles.serveRequest);
        } catch(a, b){
          print(a);
          print(b);
        }
      }
  );
</code>```

But it didn't help ...

答:
http_server (and Dart's HTTP support in general) do not support password-based authentication.

You can build such a thing on top of the core support, but that's it.

If you're looking for a static file solution, I'd look at https://pub.dartlang.org/packages/shelf_static

It'll be much easier to get started.

Title: Dart's http server throws exception

Body:
This simple dart program starts and runs for a while, but after some interactions it throws an exception:

import 'dart:io';
import 'package:http_server/http_server.dart';

main() async {

  //files
  var staticFiles = new VirtualDirectory("/path ....");
  staticFiles.allowDirectoryListing = true;
  staticFiles.directoryHandler = (dir, request) {
    var indexUri = new Uri.file(dir.path).resolve('index.html');
    staticFiles.serveFile(new File(indexUri.toFilePath()), request);
  };

  //http
  HttpServer
    .bind(InternetAddress.ANY_IP_V6, 80)
    .then((server) {
      server.forEach(staticFiles.serveRequest);
    }
  );

  //https
  SecurityContext context = new SecurityContext();
  var chain =   Platform.script.resolve('file.pem').toFilePath();
  var key =    Platform.script.resolve('file.pem').toFilePath();
  context.useCertificateChain(chain);
  context.usePrivateKey(key, password: 'pwd');
  HttpServer
    .bindSecure(InternetAddress.ANY_IP_V6, 443, context)
    .then((server) {
      server.forEach(staticFiles.serveRequest);
    }
  );
}

After some time it crashes. The Exception is:

Unhandled exception:
SocketException: OS Error: Broken pipe, errno = 32, address = ::, port = 443
#0      _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:1108)
#1      _microtaskLoop (dart:async/schedule_microtask.dart:41)
#2      _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
#3      _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:99)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:152)

Is it a bug?

How can I solve the problem?

And ... a different topic ... why can I start the https server without providing an appropriate password? I expect the server to check if the password is correct?!

I tried to solve it catching exceptions

import 'dart:io';
import 'package:http_server/http_server.dart';

main() async {

  //files
  var staticFiles = new VirtualDirectory("file");
  staticFiles.allowDirectoryListing = true;
  staticFiles.directoryHandler = (dir, request) {
    try{
      var indexUri = new Uri.file(dir.path).resolve('index.html');
      staticFiles.serveFile(new File(indexUri.toFilePath()), request);
    } catch(a,b) {
      print(a);
      print(b);
    }
  };

  //http
  HttpServer
    .bind(InternetAddress.ANY_IP_V6, 80)
    .then((server) {
      try{
        server.forEach(staticFiles.serveRequest);
      } catch(a,b)
      {
        print(a);
        print(b);
      }
    }
  );

  //https
  SecurityContext context = new SecurityContext();
  var chain =   Platform.script.resolve('file.pem').toFilePath();
  var key =    Platform.script.resolve('file.pem').toFilePath();
  context.useCertificateChain(chain);
  context.usePrivateKey(key, password: 'pwd');
  HttpServer
    .bindSecure(InternetAddress.ANY_IP_V6, 443, context)
    .then((server) {
        try {
          server.forEach(staticFiles.serveRequest);
        } catch(a, b){
          print(a);
          print(b);
        }
      }
  );

But it didn't help ...


问:
List all git commits that have no files changed
I'm working with an open source repository that seems to have been copied over from either a combined git repo or some other kind of VCS. There are an enormous amount of commits in the repo, most of them with zero files changed:

What would be the best way to list all the commits with no files changed, count them, and potentially remove them from the local git repo?

Edit: I'm specifically looking for a way to assess the extent of the issue before running a time consuming, destructive command like filter-branch as referenced in Remove empty commits in git

答:
So it turns out the keyword I was missing in Google was "empty" (was searching for "remove commits with no files changes", etc)

List commits that have no changes (empty commits):

```<code>git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -eq 0 ]; then
        echo $commitHash
    fi;
done
</code>```

List commits that have changes, and files changed (non empty commits):

```<code>git rev-list HEAD | while read commitHash; do
    git diff-tree --name-status $commitHash
done
</code>```

Count empty commits

```<code>git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -eq 0 ]; then
        echo '1'
    fi;
done | wc -l
</code>```

Count non empty commits

```<code>git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -gt 0 ]; then
        echo '1'
    fi;
done | wc -l
</code>```

And finally, as per @JKillian's suggestion, remove all empty commits from the repo using git filter-branch:

```<code>git filter-branch --tag-name-filter cat --commit-filter 'git_commit_non_empty_tree "$@"' -- --all
</code>```

Documentation on filter-branch, specifically --commit-filter:

https://git-scm.com/docs/git-filter-branch#git-filter-branch---commit-filterltcommandgt

Body:
So it turns out the keyword I was missing in Google was "empty" (was searching for "remove commits with no files changes", etc)

List commits that have no changes (empty commits):

git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -eq 0 ]; then
        echo $commitHash
    fi;
done

List commits that have changes, and files changed (non empty commits):

git rev-list HEAD | while read commitHash; do
    git diff-tree --name-status $commitHash
done

Count empty commits

git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -eq 0 ]; then
        echo '1'
    fi;
done | wc -l

Count non empty commits

git rev-list HEAD | while read commitHash; do
    if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -gt 0 ]; then
        echo '1'
    fi;
done | wc -l

And finally, as per @JKillian's suggestion, remove all empty commits from the repo using git filter-branch:

git filter-branch --tag-name-filter cat --commit-filter 'git_commit_non_empty_tree "$@"' -- --all

Documentation on filter-branch, specifically --commit-filter:

https://git-scm.com/docs/git-filter-branch#git-filter-branch---commit-filterltcommandgt


答:
This should just be a diff operation, which will dispatch to diff.POSIXt:

```<code>dif <- diff(dat$readdate)
dif
#Time differences in secs
#[1]   60  120   60   50 7200
c(0, dif)
#[1]    0   60  120   60   50 7200
</code>```

If you need to change the units of measurement, just do so using units<-

```<code>units(dif) <- "mins"
c(0, dif)
#[1]   0.0000000   1.0000000   2.0000000   1.0000000   0.8333333 120.0000000
</code>```

You can also do this in-line if you are tricky:

```<code>c(0, `units<-`(diff(dat$readdate), "mins"))
#[1]   0.0000000   1.0000000   2.0000000   1.0000000   0.8333333 120.0000000
</code>```

Title: Units of time calculation in R

Body:
This should just be a diff operation, which will dispatch to diff.POSIXt:

dif <- diff(dat$readdate)
dif
#Time differences in secs
#[1]   60  120   60   50 7200
c(0, dif)
#[1]    0   60  120   60   50 7200

If you need to change the units of measurement, just do so using units<-

units(dif) <- "mins"
c(0, dif)
#[1]   0.0000000   1.0000000   2.0000000   1.0000000   0.8333333 120.0000000

You can also do this in-line if you are tricky:

c(0, `units<-`(diff(dat$readdate), "mins"))
#[1]   0.0000000   1.0000000   2.0000000   1.0000000   0.8333333 120.0000000


问:
pandas python replace column values
Suppose that I have a data frame with a column a: 1, 2, 3, 4, 5, .... How can I replace the values so that every number is 1 less (new a is 0, 1, 2, 3, 4). Thank you all.

答:
This should do it:

```<code>>>> data['col_name']=data['col_name'].apply(lambda row:row-1)
</code>```

You can add any other operation or functionality as well in this manner

Title: pandas python replace column values

Body:
This should do it:

>>> data['col_name']=data['col_name'].apply(lambda row:row-1)

You can add any other operation or functionality as well in this manner


问:
Thorough use of 'if' statements or 'try/catch' blocks?
Give me some of your thoughts on which is a better coding practice/makes more efficient code/looks prettier/whatever:  Increasing and improving your ability to use if statements to anticipate and catch potential problems?  Or simply making good use of try/catch in general?

Let's say this is for Java (if it matters).

Edit:  I'm presently transitioning myself away from some admittedly out-dated and constrained current coding practices, but I'm a little torn on the necessity of doing so on a few points (such as this).  I'm simply asking for some perspectives on this.  Not a debate.

答:
Using exceptions is universal method to notify other part of code that something wrong happened in loosely coupled way. Let imagine that if you would like to handle some exceptional condition by using if.. nad else.. you need to insert into different part of your code some arbitrary variables and other stuff which probably would easily led to have spaghetti code soon after.

Let next imagine that you are using any external library/package and it's author decided to put in his/her code other arbitrary way to handle wrong states - it would force you to adjust to its way of dealing with it - for example you would need to check if particular methods returns true or false or whatever.

Using exceptions makes handling errors much more easy - you just assume that if something goes wrong - the other code will throw exception, so you just wrap the code in try block and handle possible exception on your own way.

OwnerDisplayName: Daddy Warbox

LastEditorDisplayName: Daddy Warbox


问:
Bluetooth only Connection with Nearby-Communication
I'm wondering if it's possible to have a Bluetooth connection only in Googles Nearby-Connections API.

The problem is, if i have a running hotspot for my notebook, google Nearby will cut off the connection.

If I use the connections-activity from github, it will raise a hotspot after the acceptConnection() function.

答:
Change from 'Strategy.P2P_STAR' to 'Strategy.P2P_CLUSTER'.

STAR uses hotspots and is generally more disruptive but has higher bandwidth as a result. CLUSTER will only ever use non-disruptive mediums.


问:
Need to design a table with loads of attributes which must all be searchable by SQL
I'm in a fix here. I'm building a home reservation site and the client requires a filter search facility to allow visitors to search and filter through properties based upon criteria. The thing is that his list of criteria is exceedingly long, largely boolean values and calculable values stuff like:

Attached bathroom, balcony, smoking, alcoholic, maximum number of occupants, cable TV, Internet, carpeted, airconditioning, central heating, room service, etc., etc., etc...

I'm thinking of having to create a field for each of these, but there's a very strong chance that the number of preferences might even go up. I dished out the idea of storing everying in a serialised object as a string as then it would be impossible to search using an SQL query. Do I have any options apart from setting up individual fields for each preference here?

Thanks. I'm using PHP MySQL.

答:
Could you have a many-to-many table that ties the ID of the property to a reference table that has Attributes?  The lookup table would contain a row for every attribute that the property has?

Main Table

ID PropertyName OtherCols

10 CottageA     Stuff

 20 CottageB     OtherStuff

Attributes

100 Smoking

200 AirConditioning

300 Room Service

400 TV

500 Internet

Lookup Table

ID AttributeID

10 100

10 200

10 300

20 100

20 400

20 500


问:
Comparing NSDates without time component
In a swift playground, I have been using

```<code>NSDate.date()
</code>```

But, this always appears with the time element appended. For my app I need to ignore the time element. Is this possible in Swift? How can it be done? Even if I could set the time element to be the same time on every date that would work too.

Also, I am trying to compare two dates and at the moment I am using the following code:

```<code>var earlierDate:NSDate = firstDate.earlierDate(secondDate)
</code>```

Is this the only way or can I do this in a way that ignores the time element? For instance I don't want a result if they are the same day, but different times.

答:
In Swift 4:</p>

```<code>func compareDate(date1:Date, date2:Date) -> Bool {
    let order = NSCalendar.current.compare(date1, to: date2, toGranularity: .day)
    switch order {
    case .orderedSame:
        return true
    default:
        return false
    }
}
</code>```

Body:
In a swift playground, I have been using

NSDate.date()

But, this always appears with the time element appended. For my app I need to ignore the time element. Is this possible in Swift? How can it be done? Even if I could set the time element to be the same time on every date that would work too.

Also, I am trying to compare two dates and at the moment I am using the following code:

var earlierDate:NSDate = firstDate.earlierDate(secondDate)

Is this the only way or can I do this in a way that ignores the time element? For instance I don't want a result if they are the same day, but different times.

Body:
In Swift 4:

func compareDate(date1:Date, date2:Date) -> Bool {
    let order = NSCalendar.current.compare(date1, to: date2, toGranularity: .day)
    switch order {
    case .orderedSame:
        return true
    default:
        return false
    }
}


问:
How to change the position of an array element?
I have a question on how I can change the index of a array element, so that it doesn't come at the 7. position but at position 2 instead...

Is there a function to handle this?

答:
If you don't care about the position of the other elements in the array you can use the .rotate! (note that the ! at the end of this method changes the actual array) method.

```<code>arr = [1, 2, 3, 4, 5, 6, 7, 8]
arr.rotate! -3
arr = [6, 7, 8, 1, 2, 3, 4, 5]
</code>```

This takes the element 8 which is at index 7, and rotates it to an index of 2.

Body:
If you don't care about the position of the other elements in the array you can use the .rotate! (note that the ! at the end of this method changes the actual array) method.

arr = [1, 2, 3, 4, 5, 6, 7, 8]
arr.rotate! -3
arr = [6, 7, 8, 1, 2, 3, 4, 5]

This takes the element 8 which is at index 7, and rotates it to an index of 2.


问:
Alternative for Garbage Collector
I'd like to know the best alternative for a garbage collector, with its pros and cons. My priority is speed, memory is less important. If there is garbage collector which doesn't make any pause, let me know.

I'm working on a safe language (i.e. a language with no dangling pointers, checking bounds, etc), and garbage collection or its alternative has to be used.

答:
If you truly want no pauses at all, disallow all memory allocation except for stack allocation, region-based buffers, and static allocation. Despite what you may have been told, malloc() can actually cause severe pauses if the free list becomes fragmented, and if you often find yourself building massive object graphs, naive manual free can and will lose to stop-and-copy; the only way to really avoid this is to amortize over preallocated pages, such as the stack or a bump-allocated pool that's freed all at once. I don't know how useful this is, but I know that the proprietary graphical programming language LabVIEW by default allocates a static region of memory for each subroutine-equivalent, requiring programmers to manually enable stack allocation; this is the kind of thing that's useful in a hard-real-time environment where you need absolute guarantees on memory usage.

If what you want is to make it easy to reason about pauses and give your developers control over allocation and placement, then there is already a language called Rust that has the same stated goals as your language; while not a completely safe language, it does have a safe subset, allowing you to create safe abstractions for raw bit-twiddling. It uses pointer type annotations to eliminate use-after-free bugs. It also doesn't have null pointers in safe code, because null pointers cost a billion dollars at least.

If bounded pauses are enough, though, there are a wide variety of algorithms that will work. If you really have a small working set compared to available memory, then I would recommend the MOS collector (aka the Train Algorithm), which collects incrementally and provably always makes progress toward freeing unreferenced objects.

Title: Alternative for Garbage Collector


问:
Is it possible to capture a window with windows 7 DWM thumbnail in it?
I am starting to believe that you can do nothing with Windows API.

I have two windows. One has a DWM thumbnail in it. What I want to do is, I want to be able to capture the screen of the window with the thumbnail into the other one.
When I do this, using bitblt, everything is copied except the thumbnail. It just isn't there in the bitmap.

So how does the DWM rendering work? I mean, if DWM renders thumbnails directly onto the DC of the registered window, then my approach should work. I'm confused.

Thanks a bunch.

答:
You cannot expect a thumbnail to be place in a window's device context, because the thumbnail is not placed in a window's device context. So your approach will not work.

But if you're trying to steal the thumbnail of an application, just ask the Dwm to give you it's thumbnail. That will allow you to present to the user the exact thumbnail you want.

If, on the other hand, you want to access the pixels in the thumbnail of another process, then you have a problem.


问:
How to Download PDF files from Netsuite File Cabinet to Local drive without any click?

I have one script customization, which creates multiple PDF files on daily basis and store it in File Cabinet.

Now i need to download all new created PDF files on daily basis.

I can download PDF by click on download button. Is there any idea or script to download all PDF files on my local drive at a time ?

答:
If you have an sftp server you can build a scheduled SuiteScript 2.0 map/reduce script to push all the files to a specific folder on this server and then process them as you need.

If you want to push all of those files to your a folder on you local pc, it's not possible via script.


问:
User input not reflected properly in AJAX URL call
Trying to use user's city input (ex. Los Angeles) and include in Ajax URL parameters, however when I console.log(searchURL). It doesn't add a '+' between "los angels" thus breaking the URL. What can be done to make the URL include the + between cities with two words.

```<code>var apiKey = "&client_id=OTU3MDMwMHwxNTEwMjUwNDQ0LjI3"
var baseQueryURL = "https://api.seatgeek.com/2/events?" + apiKey;
console.log(baseQueryURL);

function runSearch(queryURL) {
  $.ajax({
      url: queryURL,
      method: 'GET'
    }).done(function(response) {
        console.log(response);
      };

      $("#submitSearch").on("click", function(event) {
        //prevents default event from occuring
        event.preventDefault();

        userCity = $("#userCity").val();
        console.log(userCity);
        //create variable queryCity to hold city queried with URL parameters
        var queryCity = "&venue.city=" + userCity;
        //create searchURL to pass in as queryURL in AJAX call
        searchURL = searchURL + queryCity;
        console.log(searchURL);
        runSearch(searchURL);
      });
</code>```

答:
URL-encode the value:</p>

```<code>userCity = encodeURIComponent($("#userCity").val());
</code>```

Body:
Trying to use user's city input (ex. Los Angeles) and include in Ajax URL parameters, however when I console.log(searchURL). It doesn't add a '+' between "los angels" thus breaking the URL. What can be done to make the URL include the + between cities with two words.

var apiKey = "&client_id=OTU3MDMwMHwxNTEwMjUwNDQ0LjI3"
var baseQueryURL = "https://api.seatgeek.com/2/events?" + apiKey;
console.log(baseQueryURL);

function runSearch(queryURL) {
  $.ajax({
      url: queryURL,
      method: 'GET'
    }).done(function(response) {
        console.log(response);
      };

      $("#submitSearch").on("click", function(event) {
        //prevents default event from occuring
        event.preventDefault();

        userCity = $("#userCity").val();
        console.log(userCity);
        //create variable queryCity to hold city queried with URL parameters
        var queryCity = "&venue.city=" + userCity;
        //create searchURL to pass in as queryURL in AJAX call
        searchURL = searchURL + queryCity;
        console.log(searchURL);
        runSearch(searchURL);
      });

Body:
URL-encode the value:

userCity = encodeURIComponent($("#userCity").val());


问:
Having trouble getting my nopcommerce task to run
Ok so I have created a task I would like to run every hour:

```<code>using Nop.Core.Domain.Stores;
using Nop.Core.Plugins;
using Nop.Services.Common;
using Nop.Services.Configuration;
using Nop.Services.Customers;
using Nop.Services.Logging;
using Nop.Services.Stores;
using Nop.Services.Tasks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;

namespace Nop.Plugin.Feed.Froogle.Tasks
{
    public partial class CreateAmazonInventoryUpdateTask : ITask
    {
        private readonly ISettingService _settingService;
        private readonly IScheduleTaskService _scheduleTaskService;
        private readonly ILogger _logger;
        private readonly IPluginFinder _pluginFinder;
        private readonly IStoreService _storeService;
        private readonly FroogleSettings _froogleSettings;
        private readonly ICustomerService _customerService;
        private readonly IGenericAttributeService _genericAttributeService;

        //Constructor
        public CreateAmazonInventoryUpdateTask(
            ISettingService settingService,
            IScheduleTaskService scheduleTaskService,
            ILogger logger,
            IPluginFinder pluginFinder,
            IStoreService storeService,
            FroogleSettings froogleSettings,
            ICustomerService customerService,
            IGenericAttributeService genericAttributeService)
        {
            _settingService = settingService;
            _scheduleTaskService = scheduleTaskService;
            _logger = logger;
            _pluginFinder = pluginFinder;
            _storeService = storeService;
            _froogleSettings = froogleSettings;
            _customerService = customerService;
            _genericAttributeService = genericAttributeService;
        }

        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            Debug.WriteLine("CreateAmazonInventoryUpdateTask started");
            // Only runs on first server, or test server, or local
            var runHour = new System.Timers.Timer(60000); //60 * 60 * 1000 one hour in milliseconds
            runHour.Elapsed += new ElapsedEventHandler(CreateAmazonInventoryUpdateFeed);
        }

        public void CreateAmazonInventoryUpdateFeed(object src, ElapsedEventArgs e)
        {
            Debug.WriteLine("CreateAmazonInventoryUpdateFeed task starting");
            _logger.Information("CreateAmazonInventoryUpdateFeed task starting");

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            try
            {
                var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName("PromotionFeed.Froogle");
                if (pluginDescriptor == null)
                    throw new Exception("Cannot load the plugin");

                //plugin
                var plugin = pluginDescriptor.Instance() as FroogleService;
                if (plugin == null)
                    throw new Exception("Cannot load the plugin");

                var stores = new List<Store>();
                var storeById = _storeService.GetStoreById(_froogleSettings.StoreId);
                if (storeById != null)
                    stores.Add(storeById);
                else
                    stores.AddRange(_storeService.GetAllStores());

                foreach (var store in stores.Where(x => x.Id != 2)) // Added store 2 is admin
                {
                    _logger.Information($"CreateAmazonInventoryUpdateFeed, storeId = {store.Id}, machine name = {Environment.MachineName}");
                    plugin.AmazonProductHourlyInventoryUpdateTask(store);

                }
            }
            catch (Exception exc)
            {
                _logger.Error(exc.Message, exc);
            }

            var time = string.Format("{0} mins {1} seconds", Math.Floor(stopwatch.Elapsed.TotalMinutes), (int)stopwatch.Elapsed.TotalSeconds % 60);
            _logger.Information("CreateAmazonInventoryUpdateFeed scheduled task completed in " + time);
        }
    }
}
</code>```

Now inside the froogle service I have added the task when the plugin is installed:

```<code>/// <summary>
    /// Install plugin
    /// </summary>
    public override void Install()
    {
        //settings
        var settings = new FroogleSettings
        {
            PricesConsiderPromotions = false,
            ProductPictureSize = 125,
            PassShippingInfoWeight = false,
            PassShippingInfoDimensions = false,
            StaticFileName = string.Format("froogle_{0}.xml", CommonHelper.GenerateRandomDigitCode(10)),
            ExpirationNumberOfDays = 28
        };
        _settingService.SaveSetting(settings);

        //data
        _objectContext.Install();

        //locales
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Store", "Store");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Store.Hint", "Select the store that will be used to generate the feed.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Currency", "Currency");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Currency.Hint", "Select the default currency that will be used to generate the feed.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.DefaultGoogleCategory", "Default Google category");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.DefaultGoogleCategory.Hint", "The default Google category to use if one is not specified.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.General", "General");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Generate", "Generate feed");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Override", "Override product settings");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoWeight", "Pass shipping info (weight)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoWeight.Hint", "Check if you want to include shipping information (weight) in generated XML file.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoDimensions", "Pass shipping info (dimensions)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoDimensions.Hint", "Check if you want to include shipping information (dimensions) in generated XML file.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PricesConsiderPromotions", "Prices consider promotions");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PricesConsiderPromotions.Hint", "Check if you want prices to be calculated with promotions (tier prices, discounts, special prices, tax, etc). But please note that it can significantly reduce time required to generate the feed file.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.ProductPictureSize", "Product thumbnail image size");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.ProductPictureSize.Hint", "The default size (pixels) for product thumbnail images.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.ProductName", "Product");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.GoogleCategory", "Google Category");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.Gender", "Gender");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.AgeGroup", "Age group");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.Color", "Color");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.Size", "Size");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.CustomGoods", "Custom goods (no identifier exists)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.SuccessResult", "Froogle feed has been successfully generated.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.StaticFilePath", "Generated file path (static)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.StaticFilePath.Hint", "A file path of the generated Froogle file. It's static for your store and can be shared with the Froogle service.");

        var task = FindScheduledTask();
        if (task == null)
        {
            DateTime now = DateTime.Now;
            task = new ScheduleTask
            {
                Name = "Amazon Inventory Update Sync",
                // Every hour
                Seconds = 60,
                Type = "Nop.Plugin.Feed.Froogle.Tasks.CreateAmazonInventoryUpdateTask, Nop.Plugin.Feed.Froogle",
                StopOnError = false,
                Enabled = true,
            };

            _scheduleTaskService.InsertTask(task);
        }

        base.Install();
    }

    private ScheduleTask FindScheduledTask()
    {
        return _scheduleTaskService.GetTaskByType("Nop.Plugin.Feed.Froogle.Tasks.CreateAmazonInventoryUpdateTask, Nop.Plugin.Feed.Froogle");
    }
</code>```

The task will generate a feed to submit to google. But the problem is the task won't run.

From what I googled everything looks right, not sure what I'm missing.

Also yes this is 1 min new System.Timers.Timer(60000); :)

答:
Ok so was going about this wrong.
I removed the task creation from the froogleservice install() method.

Now in my CreateAmazonInventoryUpdateTask class I needed to use:

```<code>public void InsertTask(Core.Domain.Tasks.ScheduleTask task)
    {
        task.Enabled = true;
        task.Name = "Amazon Inventory Update Sync";
        task.Type = "Nop.Plugin.Feed.Froogle.Tasks.CreateAmazonInventoryUpdateTask, Nop.Plugin.Feed.Froogle";
        task.Seconds = 60;
        task.StopOnError = false;
    }
</code>```

Also inside the database there is a table dbo.ScheduleTask
I needed to add my task in here manually as well as in the code.

Works now :)

Body:
Ok so I have created a task I would like to run every hour:

using Nop.Core.Domain.Stores;
using Nop.Core.Plugins;
using Nop.Services.Common;
using Nop.Services.Configuration;
using Nop.Services.Customers;
using Nop.Services.Logging;
using Nop.Services.Stores;
using Nop.Services.Tasks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;

namespace Nop.Plugin.Feed.Froogle.Tasks
{
    public partial class CreateAmazonInventoryUpdateTask : ITask
    {
        private readonly ISettingService _settingService;
        private readonly IScheduleTaskService _scheduleTaskService;
        private readonly ILogger _logger;
        private readonly IPluginFinder _pluginFinder;
        private readonly IStoreService _storeService;
        private readonly FroogleSettings _froogleSettings;
        private readonly ICustomerService _customerService;
        private readonly IGenericAttributeService _genericAttributeService;

        //Constructor
        public CreateAmazonInventoryUpdateTask(
            ISettingService settingService,
            IScheduleTaskService scheduleTaskService,
            ILogger logger,
            IPluginFinder pluginFinder,
            IStoreService storeService,
            FroogleSettings froogleSettings,
            ICustomerService customerService,
            IGenericAttributeService genericAttributeService)
        {
            _settingService = settingService;
            _scheduleTaskService = scheduleTaskService;
            _logger = logger;
            _pluginFinder = pluginFinder;
            _storeService = storeService;
            _froogleSettings = froogleSettings;
            _customerService = customerService;
            _genericAttributeService = genericAttributeService;
        }

        ///
        /// Executes a task
        ///
        public void Execute()
        {
            Debug.WriteLine("CreateAmazonInventoryUpdateTask started");
            // Only runs on first server, or test server, or local
            var runHour = new System.Timers.Timer(60000); //60 * 60 * 1000 one hour in milliseconds
            runHour.Elapsed += new ElapsedEventHandler(CreateAmazonInventoryUpdateFeed);
        }

        public void CreateAmazonInventoryUpdateFeed(object src, ElapsedEventArgs e)
        {
            Debug.WriteLine("CreateAmazonInventoryUpdateFeed task starting");
            _logger.Information("CreateAmazonInventoryUpdateFeed task starting");

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            try
            {
                var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName("PromotionFeed.Froogle");
                if (pluginDescriptor == null)
                    throw new Exception("Cannot load the plugin");

                //plugin
                var plugin = pluginDescriptor.Instance() as FroogleService;
                if (plugin == null)
                    throw new Exception("Cannot load the plugin");

                var stores = new List<Store>();
                var storeById = _storeService.GetStoreById(_froogleSettings.StoreId);
                if (storeById != null)
                    stores.Add(storeById);
                else
                    stores.AddRange(_storeService.GetAllStores());

                foreach (var store in stores.Where(x => x.Id != 2)) // Added store 2 is admin
                {
                    _logger.Information($"CreateAmazonInventoryUpdateFeed, storeId = {store.Id}, machine name = {Environment.MachineName}");
                    plugin.AmazonProductHourlyInventoryUpdateTask(store);

                }
            }
            catch (Exception exc)
            {
                _logger.Error(exc.Message, exc);
            }

            var time = string.Format("{0} mins {1} seconds", Math.Floor(stopwatch.Elapsed.TotalMinutes), (int)stopwatch.Elapsed.TotalSeconds % 60);
            _logger.Information("CreateAmazonInventoryUpdateFeed scheduled task completed in " + time);
        }
    }
}

Now inside the froogle service I have added the task when the plugin is installed:

///
    /// Install plugin
    ///
    public override void Install()
    {
        //settings
        var settings = new FroogleSettings
        {
            PricesConsiderPromotions = false,
            ProductPictureSize = 125,
            PassShippingInfoWeight = false,
            PassShippingInfoDimensions = false,
            StaticFileName = string.Format("froogle_{0}.xml", CommonHelper.GenerateRandomDigitCode(10)),
            ExpirationNumberOfDays = 28
        };
        _settingService.SaveSetting(settings);

        //data
        _objectContext.Install();

        //locales
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Store", "Store");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Store.Hint", "Select the store that will be used to generate the feed.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Currency", "Currency");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Currency.Hint", "Select the default currency that will be used to generate the feed.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.DefaultGoogleCategory", "Default Google category");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.DefaultGoogleCategory.Hint", "The default Google category to use if one is not specified.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.General", "General");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Generate", "Generate feed");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Override", "Override product settings");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoWeight", "Pass shipping info (weight)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoWeight.Hint", "Check if you want to include shipping information (weight) in generated XML file.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoDimensions", "Pass shipping info (dimensions)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PassShippingInfoDimensions.Hint", "Check if you want to include shipping information (dimensions) in generated XML file.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PricesConsiderPromotions", "Prices consider promotions");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.PricesConsiderPromotions.Hint", "Check if you want prices to be calculated with promotions (tier prices, discounts, special prices, tax, etc). But please note that it can significantly reduce time required to generate the feed file.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.ProductPictureSize", "Product thumbnail image size");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.ProductPictureSize.Hint", "The default size (pixels) for product thumbnail images.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.ProductName", "Product");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.GoogleCategory", "Google Category");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.Gender", "Gender");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.AgeGroup", "Age group");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.Color", "Color");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.Size", "Size");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.Products.CustomGoods", "Custom goods (no identifier exists)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.SuccessResult", "Froogle feed has been successfully generated.");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.StaticFilePath", "Generated file path (static)");
        this.AddOrUpdatePluginLocaleResource("Plugins.Feed.Froogle.StaticFilePath.Hint", "A file path of the generated Froogle file. It's static for your store and can be shared with the Froogle service.");

        var task = FindScheduledTask();
        if (task == null)
        {
            DateTime now = DateTime.Now;
            task = new ScheduleTask
            {
                Name = "Amazon Inventory Update Sync",
                // Every hour
                Seconds = 60,
                Type = "Nop.Plugin.Feed.Froogle.Tasks.CreateAmazonInventoryUpdateTask, Nop.Plugin.Feed.Froogle",
                StopOnError = false,
                Enabled = true,
            };

            _scheduleTaskService.InsertTask(task);
        }

        base.Install();
    }

    private ScheduleTask FindScheduledTask()
    {
        return _scheduleTaskService.GetTaskByType("Nop.Plugin.Feed.Froogle.Tasks.CreateAmazonInventoryUpdateTask, Nop.Plugin.Feed.Froogle");
    }

The task will generate a feed to submit to google. But the problem is the task won't run.

From what I googled everything looks right, not sure what I'm missing.

Also yes this is 1 min new System.Timers.Timer(60000); :)

Body:
Ok so was going about this wrong.
I removed the task creation from the froogleservice install() method.

Now in my CreateAmazonInventoryUpdateTask class I needed to use:

public void InsertTask(Core.Domain.Tasks.ScheduleTask task)
    {
        task.Enabled = true;
        task.Name = "Amazon Inventory Update Sync";
        task.Type = "Nop.Plugin.Feed.Froogle.Tasks.CreateAmazonInventoryUpdateTask, Nop.Plugin.Feed.Froogle";
        task.Seconds = 60;
        task.StopOnError = false;
    }

Also inside the database there is a table dbo.ScheduleTask
I needed to add my task in here manually as well as in the code.

Works now :)


问:
What's the best practice way to convert enum to string?
I have enum like this:

```<code>public enum ObectTypes
{
    TypeOne,
    TypeTwo,
    TypeThree,
    ...
    TypeTwenty
 }
</code>```

then I need to convert this enum to string. Now Im doing this that way:

```<code>public string ConvertToCustomTypeName(ObjectTypes typeObj)
{
    string result = string.Empty;
    switch (typeObj)
    {
        case ObjectTypes.TypeOne: result = "This is type T123"; break;
        case ObjectTypes.TypeTwo: result = "Oh man! This is type T234"; break;
        ...
        case ObjectTypes.TypeTwenty: result = "This is type last"; break;
    }

    return result;
}
</code>```

Im quite sure that there is better way do do this, Im looking for some good practice solution.

EDIT: There is no one pattern in result string.

Thanks in advance.

答:
What you were already using isn't a bad pattern. Almost every other option has its own problems. If you were using F# for this type, you could do something like:

```<code>type ObjectTypes =
| TypeOne
| TypeTwo
| TypeThree
...
| TypeTwenty
with override this.ToString() =
    match this with
    | TypeOne -> "This is type T123"
    | TypeTwo -> "Oh man! This is type T234"
    ...
    | TypeTwenty -> "This is type last"
    | _ -> "This is any other type that wasn't explicitly specified"
</code>```

Of course, with F# pattern matching, you have a lot more control than you would with a simple C# switch statement.

Body:
I have enum like this:

public enum ObectTypes
{
    TypeOne,
    TypeTwo,
    TypeThree,
    ...
    TypeTwenty
 }

then I need to convert this enum to string. Now Im doing this that way:

public string ConvertToCustomTypeName(ObjectTypes typeObj)
{
    string result = string.Empty;
    switch (typeObj)
    {
        case ObjectTypes.TypeOne: result = "This is type T123"; break;
        case ObjectTypes.TypeTwo: result = "Oh man! This is type T234"; break;
        ...
        case ObjectTypes.TypeTwenty: result = "This is type last"; break;
    }

    return result;
}

Im quite sure that there is better way do do this, Im looking for some good practice solution.

EDIT: There is no one pattern in result string.

Thanks in advance.

Body:
What you were already using isn't a bad pattern. Almost every other option has its own problems. If you were using F# for this type, you could do something like:

type ObjectTypes =
| TypeOne
| TypeTwo
| TypeThree
...
| TypeTwenty
with override this.ToString() =
    match this with
    | TypeOne -> "This is type T123"
    | TypeTwo -> "Oh man! This is type T234"
    ...
    | TypeTwenty -> "This is type last"
    | _ -> "This is any other type that wasn't explicitly specified"

Of course, with F# pattern matching, you have a lot more control than you would with a simple C# switch statement.


问:
get amazon S3 to send http request upon file upload
I need my nodejs application to receive a http request with a file name, when a file is uploaded in my S3 bucket.

I would like  some recommendations on the most simple/straight forward way to achieve this.

So far I see 3 ways to do this, but I feel Im overthinking this, and there surely exist better options:

1/ file uploaded on s3 -> S3 send a notification to SNS -> SNS sends a http request to my application

2/ file uploaded on s3 -> lambda function is triggered and sends a http request to my application

3/ make my application watch the bucket on regular basis and do something when a file is uploaded

thanks

ps. yes, Im really new to amazon services :)

答:
SNS- If you want to call multiple services on updating S3 then I would suggest SNS. You can create a topic for SNS and there can have multiple subscribers to that topic. Later if you want to add more HTTP then it would be as simple as subscribing the topic.

Lambda - If you need to sent notification to only one HTTP endpoint then I would strongly recommend this.

SQS - You don't need SQL in this scenario. SQS is mainly for decoupling components and would be the best fit for microservices but you can use with other messaging systems as well

You don't need to build something on your on to regularly monitor the bucket for changes as already services there like Lambda, SNS etc.


问:
How to click dynamic id button in selenium IDE?
I am searching it from 2 days but still unable to get satisfying answer..please help
I am using liferay, i want to open dropdown which name is "Add" and then want to click on submit button named as "Blank Site"..and both "Add" and "Blank site" button contains dynamic values/id which changes each time..attaching image for reference..

Image: Add
Image: blanksite

答:
Use Xpath Contains Method:

Based on your 2 attached image, I think the button's text you are looking for is unique in the entire web page.

What you can do to fix the problem:

For the second circumstance(Blank Site):

Xpath: //li/a/span[contains(text(), "Blank Site")]

Suggestions:

Xpath Contains|Start-with Usage


问:
How to convert varchar to datetime in SQL Server
I would like to convert varchar data to datetime format. So, can anyone let me know the way. this is the sample data available in column.

I tried following things

```<code>SELECT
    CASE WHEN [EntryTime] = ''
       THEN NULL
       ELSE CONVERT(datetime2, [EntryTime])
    END [EntryTime]
FROM
    table
</code>```

I get this result:

But, I don't need additional milliseconds.

So, can anyone let me know how should I convert it to a datetime format?

For all other tries, I am getting error as

Conversion failed when converting date and/or time from character string

So, can anyone please help me? Thanks.

答:
specify the sub-second width as datetime2(7)

```<code>select
       try_cast(EntryTime as datetime2(7))    by_try_cast
     , try_convert(datetime2(7), EntryTime )  by_try_covert
</code>```

I also suggest you use try_cast() or try_convert() if they are available, if not just remove "try_", The advantage of these is that if a string is an invalid date they return NULL and don't crash the query.

If you really don't want datetime2:

```<code>select cast(try_cast(EntryTime as datetime2(7)) as datetime)
</code>```

see it: http://rextester.com/YWBB31287

Body:
I would like to convert varchar data to datetime format. So, can anyone let me know the way. this is the sample data available in column.

I tried following things

SELECT
    CASE WHEN [EntryTime] = ''
       THEN NULL
       ELSE CONVERT(datetime2, [EntryTime])
    END [EntryTime]
FROM
    table

I get this result:

But, I don't need additional milliseconds.

So, can anyone let me know how should I convert it to a datetime format?

For all other tries, I am getting error as

Conversion failed when converting date and/or time from character string

So, can anyone please help me? Thanks.

Body:
specify the sub-second width as datetime2(7)

select
       try_cast(EntryTime as datetime2(7))    by_try_cast
     , try_convert(datetime2(7), EntryTime )  by_try_covert

I also suggest you use try_cast() or try_convert() if they are available, if not just remove "try_", The advantage of these is that if a string is an invalid date they return NULL and don't crash the query.

If you really don't want datetime2:

select cast(try_cast(EntryTime as datetime2(7)) as datetime)

see it: http://rextester.com/YWBB31287


问:
SVN dump of Apache Lucene’s repository
I want to take SVN dump of Apache Lucene’s repository. How to replicate the above repo to my local machine?</p>

答:
One way to clone an entire Subversion project (with full history) is to use Git's Subversion bridge:

```<code>git svn clone http://svn.apache.org/repos/asf/lucene/dev/trunk lucene
</code>```

By default this will get the entire history of the trunk in Subversion. Be aware that depending on the size, longevity, and complexity of the Subversion repository, this command may take some time to run.

Title: SVN dump of Apache Lucene’s repository

Body:
One way to clone an entire Subversion project (with full history) is to use Git's Subversion bridge:

git svn clone http://svn.apache.org/repos/asf/lucene/dev/trunk lucene

By default this will get the entire history of the trunk in Subversion. Be aware that depending on the size, longevity, and complexity of the Subversion repository, this command may take some time to run.


问:
Executing map function inside string concatenation
Is it possible to use the map() function while concatenating strings? If not, what is another approach?

I tried the following:

```<code>var data = [{ server: "one" }, { server: "two" }];
var output = "start " + data.map(function(i) { i.server}) + " end";
</code>```

I wanted to use Array Comprehension but I'm not running ES7, so I tried map with =>, but it's also not supported by whatever EcmaScript I'm running... So I modified it to be the above, but it still doesn't work with JSHint stating that it wants the map() to be executed independently.

Any approach is fine with me, as long as I can run it inline with the string concatenation.

答:
Try using join() to connect the new array generated by map() into one string.

var data = [{ server: "one" }, { server: "two" }];
var output = "start " + data.map(function(i) { return i.server; }).join(' ') + " end";
console.log(output);```

Body:
Is it possible to use the map() function while concatenating strings? If not, what is another approach?

I tried the following:

var data = [{ server: "one" }, { server: "two" }];
var output = "start " + data.map(function(i) { i.server}) + " end";

I wanted to use Array Comprehension but I'm not running ES7, so I tried map with =>, but it's also not supported by whatever EcmaScript I'm running... So I modified it to be the above, but it still doesn't work with JSHint stating that it wants the map() to be executed independently.

Any approach is fine with me, as long as I can run it inline with the string concatenation.


问:
React Native Set State not a function, in a for each loop not sure about binding?
I have the following code, on my component mount but I'm getting set state is not a function error which I know is a binding issue but I'm not where I should be doing the binding?   </p>

```<code>const selectedTag = this.props.tag;

        // Checks to see if this should be selected
        let checkSelected = function(arr, val) {
            _(arr).each(function(value) {
                if (value == val) {
                    this.setState({checked: true})
                }
            });
        };
        checkSelected(this.props.selectedTags, selectedTag)
        console.log(this.state.checked)
</code>```

答:
Try declare global this outside the each func and use it</p>

```<code>var _this = this;  // Reference

let checkSelected = function(arr, val) {
        _(arr).each(function(value) {
            if (value == val) {
                _this.setState({checked: true})
            }
        });
  };
</code>```

Body:
I have the following code, on my component mount but I'm getting set state is not a function error which I know is a binding issue but I'm not where I should be doing the binding?

const selectedTag = this.props.tag;

        // Checks to see if this should be selected
        let checkSelected = function(arr, val) {
            _(arr).each(function(value) {
                if (value == val) {
                    this.setState({checked: true})
                }
            });
        };
        checkSelected(this.props.selectedTags, selectedTag)
        console.log(this.state.checked)

Body:
Try declare global this outside the each func and use it

var _this = this;  // Reference

let checkSelected = function(arr, val) {
        _(arr).each(function(value) {
            if (value == val) {
                _this.setState({checked: true})
            }
        });
  };


答:
You should use a return statement inside the map function and join the result as well, like this:</p>

```<code>var data = [{ server: "one" }, { server: "two" }];
var output = "start " + data.map(function(i) { return i.server; }).join(" ") + " end";
</code>```

Title: Executing map function inside string concatenation

Body:
You should use a return statement inside the map function and join the result as well, like this:

var data = [{ server: "one" }, { server: "two" }];
var output = "start " + data.map(function(i) { return i.server; }).join(" ") + " end";


问:
append has no effect on a form based on Backbone.js
I retrieved a template Javascript / HTML based on Backbone.js. I would need to add a dynamic dropdown list in a field of the following form:

```<code><script type="text/template" id="compose-view-template">
<form id="email-compose" class="form-email-compose" method="get" action="">
    <div class="form-group">
        <select type="email" id="input-to" placeholder="To" class="input-transparent form-control">
        </select>
    </div>
    <div class="form-group">
        <input type="text" id="input-subject" placeholder="Subject" class="input-transparent form-control"
               value="<%= subject %>">
    </div>
    <div class="form-group">
        <textarea rows="10" class="form-control" id="wysiwyg" placeholder="Message"><%- body %></textarea>
    </div>
    <div class="clearfix">
        <div class="btn-toolbar pull-xs-right">
            <button type="reset" id="compose-discard-button" class="btn btn-gray">Annuler</button>
            <button type="submit" id="compose-send-button" onClick="fillEmailDropDown()" class="btn btn-danger">   Envoyer   </button>
        </div>
    </div>
</form>

</script>
</code>```

The Backbone part is the following:

```<code>        var ComposeView = Backbone.View.extend({

        template: _.template($('#compose-view-template').html()),

        attributes: {
            id: 'compose-view',
            class: 'compose-view'
        },

        events: {
            "click #compose-save-button, #compose-send-button, #compose-discard-button": 'backToFolders'
        },

        render: function() {
            $('#widget-email-header').html(
                '<h5>Nouvel <span class="fw-semi-bold">Email</span></h5>'
            );
            $('#folder-stats').addClass('hide');
            $('#back-btn').removeClass('hide');
            this.$el.html(this.template(this.model.toJSON()));
            this._initViewComponents();

            return this;
        },

        backToFolders: function(){
            App.showEmailsView();

        },

        _initViewComponents: function(){
            this.$("textarea").wysihtml5({
                html: true,
                customTemplates: bs3Wysihtml5Templates,
                stylesheets: []
            });

        }

    });
</code>```

The Javascript is the following:

```<code>$(document).ready(function() {
      var listItems = '<option selected="selected" value="0">- Select -</option>';
      console.log("Preparing Auto Fill of DropDown list for email adresses");

      for (var i = 0; i < jsonData.Table.length; i++) {
        listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
      }
      $("#input-to").append(listItems);
});
</code>```

Unfortunately the .append has no effect on the select form, and the Dropdown remains empty.
I also tried to use .html instead of append but same result.

If I'm adding the options manually in the select tag, it works properly but I need to fill it dynamically...

any idea ?

答:
It sounds like the issue is likely that backbone hasn't added the #input-to element to your html before you attempt to append to it. That wouldn't throw any errors, it would just silently fail, then backbone would add the (empty) element after the append attempt.

You only know it is "safe" to append your content after backbone has added the html, and that happens in your render method:

```<code>    render: function() {
        $('#widget-email-header').html(
            '<h5>Nouvel <span class="fw-semi-bold">Email</span></h5>'
        );
        $('#folder-stats').addClass('hide');
        $('#back-btn').removeClass('hide');
        this.$el.html(this.template(this.model.toJSON()));
        // NOW IT IS SAFE TO APPEND CONTENT...

        this._initViewComponents();

        return this;
    },
</code>```

A solution that will definitely work is to add you code that appends to the element directly in the render method. I'd recommend that if the appended content is very intrinsic to the view.

If that doesn't seem coherent, then a lot will depend on how your backbone is set up. It's probably safe to append the content after the line that initializes your view:

```<code>var myView = new ComposeView({});
// NOW APPEND CONTENT
</code>```

However, that will only be safe if:

Your view is instantly rendered when created, and

The render is synchronous (does not fetch external data or templates first).

Hope this helps, good luck.

Body:
I retrieved a template Javascript / HTML based on Backbone.js. I would need to add a dynamic dropdown list in a field of the following form:

The Backbone part is the following:

        var ComposeView = Backbone.View.extend({

        template: _.template($('#compose-view-template').html()),

        attributes: {
            id: 'compose-view',
            class: 'compose-view'
        },

        events: {
            "click #compose-save-button, #compose-send-button, #compose-discard-button": 'backToFolders'
        },

        render: function() {
            $('#widget-email-header').html(
                '
Nouvel Email
'
            );
            $('#folder-stats').addClass('hide');
            $('#back-btn').removeClass('hide');
            this.$el.html(this.template(this.model.toJSON()));
            this._initViewComponents();

            return this;
        },

        backToFolders: function(){
            App.showEmailsView();

        },

        _initViewComponents: function(){
            this.$("textarea").wysihtml5({
                html: true,
                customTemplates: bs3Wysihtml5Templates,
                stylesheets: []
            });

        }

    });

The Javascript is the following:

$(document).ready(function() {
      var listItems = '<option selected="selected" value="0">- Select -</option>';
      console.log("Preparing Auto Fill of DropDown list for email adresses");

      for (var i = 0; i < jsonData.Table.length; i++) {
        listItems += "<option value='" + jsonData.Table[i].stateid + "'>" + jsonData.Table[i].statename + "</option>";
      }
      $("#input-to").append(listItems);
});

Unfortunately the .append has no effect on the select form, and the Dropdown remains empty.
I also tried to use .html instead of append but same result.

If I'm adding the options manually in the select tag, it works properly but I need to fill it dynamically...

any idea ?

Body:
It sounds like the issue is likely that backbone hasn't added the #input-to element to your html before you attempt to append to it. That wouldn't throw any errors, it would just silently fail, then backbone would add the (empty) element after the append attempt.

You only know it is "safe" to append your content after backbone has added the html, and that happens in your render method:

    render: function() {
        $('#widget-email-header').html(
            '<h5>Nouvel <span class="fw-semi-bold">Email</span></h5>'
        );
        $('#folder-stats').addClass('hide');
        $('#back-btn').removeClass('hide');
        this.$el.html(this.template(this.model.toJSON()));
        // NOW IT IS SAFE TO APPEND CONTENT...

        this._initViewComponents();

        return this;
    },

A solution that will definitely work is to add you code that appends to the element directly in the render method. I'd recommend that if the appended content is very intrinsic to the view.

If that doesn't seem coherent, then a lot will depend on how your backbone is set up. It's probably safe to append the content after the line that initializes your view:

var myView = new ComposeView({});
// NOW APPEND CONTENT

However, that will only be safe if:

Your view is instantly rendered when created, and

The render is synchronous (does not fetch external data or templates first).

Hope this helps, good luck.