问:
Session Validation/management Best Practice?
I am working on IOS app using Swift3. I am getting sessionToken once user is authenticated. I want to check that if user is logged on or not on each time user put application on background and open it again. Where to handle these checks? Should I use AppDelegate.swift overridden methods to verify these things? Or It should be done somewhere else?

Also, I want to know how to handle in-activeness of user. How to logout automatically if user is not active(No touch event detected , both in active and background state of app).

Application Structure:
1. LoginViewController(Default landing screen)
2. HomeScreen->2.1 UserList

答:
You can take look at below two methods,</p>

```<code> func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

 // OR

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
</code>```

Body:
You can take look at below two methods,

 func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

 // OR

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


来源: stackexchange

问:
Calculating average speed from lon/lat and timestamp using distance (geosphere) and difftime
I am trying to figure out the haversine distance between two consecutive instances (rows) using the distm function from geosphere. Ultimately, i would like to calculate the average speed using the distance in meters divided by the time difference in seconds.

This is how I've calculated the time difference in seconds

```<code>df$Timediff_secs <-
  with(df,
       difftime(Timestamp, ave(Timestamp, ID, FUN=lag), units='secs'))
</code>```

A similar question has been asked before and the answer does work but I need to index by ID so that each new ID starts with NA. I would like to create a new column called df$Distance.

This needs to be edited so that it indexes by ID and so that the first row is NA (since there's no difference in distance to be calculated)

```<code>library(geosphere)
metersPerMile <- 1609.34
pts <- df1[c("lon", "lat")]

## Pass in two derived data.frames that are lagged by one point
segDists <- distVincentyEllipsoid(p1 = pts[-nrow(df),],
                                  p2 = pts[-1,])
sum(segDists)/metersPerMile
# [1] 1013.919
</code>```

Here is some sample data I copied from the link

```<code>> df
          Timestamp      ID      lat       lon
2012-11-12 02:08:41      1  76.57169 -110.8070
2012-11-12 02:09:41      1  76.44325 -110.7525
2012-11-12 02:10:41      1  76.90897 -110.8613
2012-11-12 03:18:41      2  76.11152 -110.2037
2012-11-12 03:19:41      2  76.29013 -110.3838
2012-11-12 03:20:41      2  76.15544 -110.4506
</code>```

Feels like I've tried everything, any help is much appreciated!

ContentLicense: CC BY-SA 3.0

Body:
I am trying to figure out the haversine distance between two consecutive instances (rows) using the distm function from geosphere. Ultimately, i would like to calculate the average speed using the distance in meters divided by the time difference in seconds.

This is how I've calculated the time difference in seconds

df$Timediff_secs <-
  with(df,
       difftime(Timestamp, ave(Timestamp, ID, FUN=lag), units='secs'))

A similar question has been asked before and the answer does work but I need to index by ID so that each new ID starts with NA. I would like to create a new column called df$Distance.

This needs to be edited so that it indexes by ID and so that the first row is NA (since there's no difference in distance to be calculated)

library(geosphere)
metersPerMile <- 1609.34
pts <- df1[c("lon", "lat")]

## Pass in two derived data.frames that are lagged by one point
segDists <- distVincentyEllipsoid(p1 = pts[-nrow(df),],
                                  p2 = pts[-1,])
sum(segDists)/metersPerMile
# [1] 1013.919

Here is some sample data I copied from the link

> df
          Timestamp      ID      lat       lon
2012-11-12 02:08:41      1  76.57169 -110.8070
2012-11-12 02:09:41      1  76.44325 -110.7525
2012-11-12 02:10:41      1  76.90897 -110.8613
2012-11-12 03:18:41      2  76.11152 -110.2037
2012-11-12 03:19:41      2  76.29013 -110.3838
2012-11-12 03:20:41      2  76.15544 -110.4506

Feels like I've tried everything, any help is much appreciated!

Body:
dplyr::lag or data.table::shift and grouping is handy for this, though it can be done manually in base with something like c(NA, variable[-length(variable)]) and aggregate:

library(dplyr)

df <- structure(list(Timestamp = structure(c(1352704121, 1352704181, 1352704241, 1352708321, 1352708381, 1352708441),
                                           class = c("POSIXct", "POSIXt"), tzone = ""),
                     ID = c(1L, 1L, 1L, 2L, 2L, 2L),
                     lat = c(76.57169, 76.44325, 76.90897, 76.11152, 76.29013, 76.15544),
                     lon = c(-110.807, -110.7525, -110.8613, -110.2037, -110.3838, -110.4506)),
                class = "data.frame", .Names = c("Timestamp", "ID", "lat", "lon"), row.names = c(NA, -6L))

df <- df %>%
    group_by(ID) %>%
    mutate(dist_m = geosphere::distVincentyEllipsoid(cbind(lon, lat),
                                                     cbind(lag(lon), lag(lat))),
           time_s = difftime(Timestamp, lag(Timestamp), units = 'secs'),
           speed_m_per_s = dist_m / as.integer(time_s))

df
#> # A tibble: 6 x 7
#> # Groups:   ID [2]
#>             Timestamp    ID      lat       lon   dist_m  time_s speed_m_per_s
#>                <dttm> <int>    <dbl>     <dbl>    <dbl>  <time>         <dbl>
#> 1 2012-11-12 02:08:41     1 76.57169 -110.8070       NA NA secs            NA
#> 2 2012-11-12 02:09:41     1 76.44325 -110.7525 14408.23 60 secs      240.1371
#> 3 2012-11-12 02:10:41     1 76.90897 -110.8613 52065.53 60 secs      867.7588
#> 4 2012-11-12 03:18:41     2 76.11152 -110.2037       NA NA secs            NA
#> 5 2012-11-12 03:19:41     2 76.29013 -110.3838 20507.15 60 secs      341.7859
#> 6 2012-11-12 03:20:41     2 76.15544 -110.4506 15140.03 60 secs      252.3338

Since the data.frame is already grouped, aggregation only requires summing:

df_avg <- df %>%
    summarise(dist_m = sum(dist_m, na.rm = TRUE),
              time_s = sum(as.integer(time_s), na.rm = TRUE),
              speed_m_per_s = dist_m / time_s)

df_avg
#> # A tibble: 2 x 4
#>      ID   dist_m time_s speed_m_per_s
#>   <int>    <dbl>  <int>         <dbl>
#> 1     1 66473.76    120      553.9480
#> 2     2 35647.18    120      297.0598

Units are in meters per second; convert as you like.


问:
How to set alias for request parameters in Spring-mvc?
When having a bean object for request params in spring: is there a way to define an alias for a bean properties?

```<code>@RestController
public class MyServlet {
   @GetMapping
   public void test(MyReq req) {
   }
}

public class MyReq {
   @RequestParam("different-name") //this is invalid
   private String name;
   private int age;
}
</code>```

Of course @RequestParam does not work, but is there a similar annotation I could use?

答:
With the following approach it is possible to set custom names using an annotation:

See Bozhos answer:
How to customize parameter names when binding spring mvc command objects

As I'm using spring 4, the custom resolver can be added as follows.

```<code>@Configuration
public class AdapterConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new AnnotationServletModelAttributeResolver(false));
    }
}
</code>```

It then can be used on the get query bean as follows:

```<code>@SupportsCustomizedBinding
public class MyReq {
   @CommandParameter("different-name") //this is valid now!
   private String name;
}
</code>```

Further, as I also like to match the get query parameters case insensitive, I'm using the following class:

https://github.com/mdeinum/spring-utils/blob/master/src/main/java/biz/deinum/web/filter/CaseInsensitiveRequestFilter.java

It can be wired as follows:

```<code>@Bean
public CaseInsensitiveRequestFilter caseInsensitiveFilter() {
    return new CaseInsensitiveRequestFilter();
}
</code>```

Body:
When having a bean object for request params in spring: is there a way to define an alias for a bean properties?

@RestController
public class MyServlet {
   @GetMapping
   public void test(MyReq req) {
   }
}

public class MyReq {
   @RequestParam("different-name") //this is invalid
   private String name;
   private int age;
}

Of course @RequestParam does not work, but is there a similar annotation I could use?

Body:
With the following approach it is possible to set custom names using an annotation:

See Bozhos answer:
How to customize parameter names when binding spring mvc command objects

As I'm using spring 4, the custom resolver can be added as follows.

@Configuration
public class AdapterConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new AnnotationServletModelAttributeResolver(false));
    }
}

It then can be used on the get query bean as follows:

@SupportsCustomizedBinding
public class MyReq {
   @CommandParameter("different-name") //this is valid now!
   private String name;
}

Further, as I also like to match the get query parameters case insensitive, I'm using the following class:

https://github.com/mdeinum/spring-utils/blob/master/src/main/java/biz/deinum/web/filter/CaseInsensitiveRequestFilter.java

It can be wired as follows:

@Bean
public CaseInsensitiveRequestFilter caseInsensitiveFilter() {
    return new CaseInsensitiveRequestFilter();
}


问:
SPARQL equivalent of a SQL select query?
If I have a SQL table that can be queried like this:

```<code>Select empname from mytable
Where empid=1;
</code>```

What would an equivalent SPARQL query be?

答:
As a few people have mentioned here and on your similar, previous question, you probably need to do some more reading about the nature of RDF-modeled data.

For Stack Overflow, you definitely need to get into the habit of showing your input data and whatever code you have written so far, even if it isn't working perfectly.  In that case, you need to include the error message in your question.

Here's a self contained example in which I

guessed what your table looks like

modeled it as RDF

wrote a SPARQL query that does what you asked

The example is written in R, my strongest language.  To be clear:  you don't need to know anything about R to be good at RDF, SPARQL and other semantic technologies.  If I were better at Java or Python, I would have written the example in one of those languages.

The relational (SQL) data must be converted to RDF before it can be queried with RDF.  In the code below, I have done that by hand.  See the end of the message for the nuts and bolts.

```<code>library(rrdf)
library(sqldf)

mytable.table.string <- 'empid,empname
1,Arthur
2,Kevin
3,Joey'

mytable <- read.csv(textConnection(mytable.table.string))

print(mytable)

>  empid empname
> 1     1  Arthur
> 2     2  Kevin
> 3     3  Joey

sqldf('select empname from mytable where empid = 1')

>   empname
> 1  Arthur

# R2RML conversion goes here
# I did it by hand

table.rdf.string <- 'prefix mytable: <http://mytable/>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
mytable:1 a mytable:employee .
mytable:1 mytable:empid "1" .
mytable:1 rdfs:label "Arthur" .
mytable:2 a mytable:employee .
mytable:2 mytable:empid "2" .
mytable:2 rdfs:label "Kevin" .
mytable:3 a mytable:employee .
mytable:3 mytable:empid "3" .
mytable:3 rdfs:label "Joey" . '

mytable.rdf <- fromString.rdf(table.rdf.string, format = "TURTLE")

query.as.sparql <- 'prefix mytable: <http://mytable/>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
select ?empname
where
{?emp a mytable:employee .
?emp mytable:empid "1" .
?emp rdfs:label ?empname . }'

sparql.rdf(model = mytable.rdf, sparql = query.as.sparql)

>     empname
> [1,] "Arthur"
</code>```

To review:  this R code above demonstrates a SAPRQL query that is equivalent to the OP's SQL query.  SQL queries are typically run against SQL databases, but I made this self-contained by running it against a dataframe.

SPARQL queries are run against RDF data, frequently in the form of a triplestore database.  In my example, a string containing RDF triples is converted into an in-memory RDF model, and the SPARQL query is sent to that model.

So the question becomes, if you have data in a SQL database, how do you query the database's contents with SPARQL?  As of Summer, 2017, this is an evolving topic.  There are a variety of commercial and open-source tools that can help solve this problem, usually in one of two ways:

by creating an interface that appears to send the SPARQL query
directly to the SQL database, in real time

by transforming and dumping the SQL database contents as a static
RDF file, which can then be loaded into a naively SPARQL-compliant
triplestore

In either case, somebody will need to create a mapping from the SQL data into RDF format.  This is required because SQL tables don't intrinsically have explicit semantics.  Rows typically model individuals of some category, and columns typically represent properties or relationships of the individuals.  RDF triples must have explicit subject-verb-object semantics.

Here are my recommended first steps for SQL-RDF mapping with Karma, which has a nice graphical interface.  Similar results could be achieved with another R2RML mapper like D2RQ (works, but un-maintained for 3 years), ontop, or the R2RML parser.

Watch the Karma videos and read the user's guide,
especially steps 1 though 5 plus 7.

Install Karma according to the posted directions.

Launch Karma.  A web interface to Karma should appear in your web browser

Paste the ontology below into a text editor and save as
44403425.owl Open the attached ontology in Karma (import -> from file)

Likewise, save & import mytable.csv, which is intended to represent
a dump from a SQL database.  If you want to work with a live
database, you will be responsible for making sure the right database
drivers are installed.  In that case, use import -> Database Table
instead.

Again, save the model as mytable-model.ttl. Click on the pull-down
on the left of the gray bar near the top of the Karma web page.
Choose Apply R2RML model -> from file and load mytable_model.ttl

Click on the pull-down again and select Publish -> RDF.  Accept the suggested settings.

Look for OpenRDF at the right of the top black bar.  Right click
that link to open it in a new browser window/tab.

On the OpenRDF Workbench page, select the karma_data repository.
You can now use any of the Explore links on the left, including
the (SPARQL) Query link

The OpenRDF Workbench page will become inaccessible when you close
 Karma. You can export your new triples from the OpenRDF
 Workbench, or you can do it from the gray bar in Karma.  You
 can also export the modelling file, if you have made any changes to
 it.  At that point, the RDF data triples can be loaded into any other triplestore, or explored with command line tools like ARQ from Jena.

Finally, if you want to use an R2RML mapper other than Karma, you can use a mapping file similar to (but not identical to) mytable-model.ttl.  Karma does some data manipulations with snippets of Python, which get embedded in JSON.  That JSON becomes the huge object of a km-dev:hasWorksheetHistory triple. I don't believe that all R2RML parsers would recognize the Python/JSON.

44403425.owl

```<code><?xml version="1.0"?>
<rdf:RDF xmlns="https://stackoverflow.com/questions/44403425.owl/"
     xml:base="https://stackoverflow.com/questions/44403425.owl/"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:mytable="https://stackoverflow.com/questions/44403425.owl/"
     xmlns:owl="http://www.w3.org/2002/07/owl#"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
    <owl:Ontology rdf:about="https://stackoverflow.com/questions/44403425.owl"/>

    <owl:DatatypeProperty rdf:about="https://stackoverflow.com/questions/44403425.owl/empid">
        <rdfs:domain rdf:resource="https://stackoverflow.com/questions/44403425.owl/employee"/>
        <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/>
        <rdfs:label>employee identifier</rdfs:label>
    </owl:DatatypeProperty>

    <owl:Class rdf:about="https://stackoverflow.com/questions/44403425.owl/employee">
        <owl:equivalentClass>
            <owl:Restriction>
                <owl:onProperty rdf:resource="https://stackoverflow.com/questions/44403425.owl/empid"/>
                <owl:cardinality rdf:datatype="http://www.w3.org/2001/XMLSchema#nonNegativeInteger">1</owl:cardinality>
            </owl:Restriction>
        </owl:equivalentClass>
        <rdfs:label>employee class</rdfs:label>
    </owl:Class>
</rdf:RDF>
</code>```

mytable.csv

```<code>"empid","empname"
1,"Arthur"
2,"Kevin"
3,"Joey"
</code>```

mytable-model.ttl

```<code>@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix pato: <http://purl.obolibrary.org/obo/pato#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix obo: <http://purl.obolibrary.org/obo/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#> .
@prefix protege: <http://protege.stanford.edu/plugins/owl/protege#> .
@prefix turbo: <http://turbo.org/> .
@prefix subsets: <http://purl.obolibrary.org/obo/ro/subsets#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix km-dev: <http://isi.edu/integration/karma/dev#> .

_:node1bi2073ftx1 a km-dev:R2RMLMapping ;
    km-dev:sourceName "mytable.csv" ;
    km-dev:modelPublicationTime "1496863444477"^^xsd:long ;
    km-dev:modelVersion "1.7" ;
    km-dev:hasInputColumns "[[{\"columnName\":\"empname\"}],[{\"columnName\":\"empid\"}]]" ;
    km-dev:hasOutputColumns "[[{\"columnName\":\"empname\"}],[{\"columnName\":\"empid\"}],[{\"columnName\":\"empid_val\"}]]" ;
    km-dev:hasModelLabel "mytable" ;
    km-dev:hasBaseURI "https://stackoverflow.com/questions/44403425.owl/" ;
    km-dev:hasWorksheetHistory """[
    {
        \"commandName\": \"SubmitPythonTransformationCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empid\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"newColumnName\",
                \"type\": \"other\",
                \"value\": \"empid_val\"
            },
            {
                \"name\": \"transformationCode\",
                \"type\": \"other\",
                \"value\": \"return getValue(\\\"empid\\\")\"
            },
            {
                \"name\": \"errorDefaultValue\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"isJSONOutput\",
                \"type\": \"other\",
                \"value\": \"false\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid_val\\\"}]}]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetWorksheetPropertiesCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"properties\",
                \"type\": \"other\",
                \"value\": {
                    \"graphLabel\": \"\",
                    \"hasBaseURI\": false,
                    \"prefix\": \"mytable\",
                    \"hasPrefix\": true,
                    \"hasServiceProperties\": false
                }
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetWorksheetPropertiesCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"properties\",
                \"type\": \"other\",
                \"value\": {
                    \"graphLabel\": \"\",
                    \"hasBaseURI\": true,
                    \"baseURI\": \"https://stackoverflow.com/questions/44403425.owl/\",
                    \"hasPrefix\": false,
                    \"hasServiceProperties\": false
                }
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetWorksheetPropertiesCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"properties\",
                \"type\": \"other\",
                \"value\": {
                    \"graphLabel\": \"mytable\",
                    \"hasBaseURI\": false,
                    \"hasPrefix\": false,
                    \"hasServiceProperties\": false
                }
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetMetaPropertyCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empid\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"metaPropertyName\",
                \"type\": \"other\",
                \"value\": \"isUriOfClass\"
            },
            {
                \"name\": \"metaPropertyUri\",
                \"type\": \"other\",
                \"value\": \"https://stackoverflow.com/questions/44403425.owl/employee\"
            },
            {
                \"name\": \"metaPropertyId\",
                \"type\": \"other\",
                \"value\": \"https://stackoverflow.com/questions/44403425.owl/employee1\"
            },
            {
                \"name\": \"SemanticTypesArray\",
                \"type\": \"other\",
                \"value\": [{
                    \"DomainUri\": \"https://stackoverflow.com/questions/44403425.owl/employee\",
                    \"DomainId\": \"https://stackoverflow.com/questions/44403425.owl/employee1\",
                    \"isPrimary\": true,
                    \"isProvenance\": false,
                    \"FullType\": \"http://isi.edu/integration/karma/dev#classLink\",
                    \"DomainLabel\": \"https://stackoverflow.com/questions/44403425.owl/employee/employee1 (add)\"
                }]
            },
            {
                \"name\": \"trainAndShowUpdates\",
                \"type\": \"other\",
                \"value\": true
            },
            {
                \"name\": \"rdfLiteralType\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"language\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid\\\"}]}]\"
            }
        ],
        \"tags\": [\"SemanticType\"]
    },
    {
        \"commandName\": \"SetSemanticTypeCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empid_val\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"SemanticTypesArray\",
                \"type\": \"other\",
                \"value\": [{
                    \"DomainUri\": \"https://stackoverflow.com/questions/44403425.owl/employee\",
                    \"DomainId\": \"https://stackoverflow.com/questions/44403425.owl/employee1\",
                    \"isPrimary\": true,
                    \"isProvenance\": false,
                    \"FullType\": \"https://stackoverflow.com/questions/44403425.owl/empid\",
                    \"DomainLabel\": \"https://stackoverflow.com/questions/44403425.owl/employee/employee1\"
                }]
            },
            {
                \"name\": \"trainAndShowUpdates\",
                \"type\": \"other\",
                \"value\": true
            },
            {
                \"name\": \"rdfLiteralType\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"language\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid_val\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid_val\\\"}]}]\"
            }
        ],
        \"tags\": [\"SemanticType\"]
    },
    {
        \"commandName\": \"SetSemanticTypeCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empname\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"SemanticTypesArray\",
                \"type\": \"other\",
                \"value\": [{
                    \"DomainUri\": \"https://stackoverflow.com/questions/44403425.owl/employee\",
                    \"DomainId\": \"https://stackoverflow.com/questions/44403425.owl/employee1\",
                    \"isPrimary\": true,
                    \"isProvenance\": false,
                    \"FullType\": \"http://www.w3.org/2000/01/rdf-schema#label\",
                    \"DomainLabel\": \"https://stackoverflow.com/questions/44403425.owl/employee/employee1\"
                }]
            },
            {
                \"name\": \"trainAndShowUpdates\",
                \"type\": \"other\",
                \"value\": true
            },
            {
                \"name\": \"rdfLiteralType\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"language\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empname\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empname\\\"}]}]\"
            }
        ],
        \"tags\": [\"SemanticType\"]
    }
]""" .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 a rr:TriplesMap .

_:node1bi2073ftx1 km-dev:hasTriplesMap km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx2 rr:tableName "mytable.csv" ;
    a rr:LogicalTable ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasLogicalTable _:node1bi2073ftx2 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 rr:logicalTable _:node1bi2073ftx2 ;
    rr:subjectMap _:node1bi2073ftx3 .

_:node1bi2073ftx1 km-dev:hasSubjectMap _:node1bi2073ftx3 .

_:node1bi2073ftx3 km-dev:isPartOfMapping _:node1bi2073ftx1 ;
    a rr:SubjectMap ;
    km-dev:alignmentNodeId "https://stackoverflow.com/questions/44403425.owl/employee1" ;
    rr:class <https://stackoverflow.com/questions/44403425.owl/employee> ;
    rr:template "{empid}" ;
    a km-dev:steinerTreeRootNode .

km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 rr:predicate <https://stackoverflow.com/questions/44403425.owl/empid> .

_:node1bi2073ftx4 rr:column "empid" ;
    a rr:ObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasObjectMap _:node1bi2073ftx4 .

km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 rr:objectMap _:node1bi2073ftx4 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 rr:predicateObjectMap km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 .

km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 a rr:PredicateObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasPredicateObjectMap km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 .

km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b rr:predicate rdfs:label .

_:node1bi2073ftx5 rr:column "empname" ;
    a rr:ObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasObjectMap _:node1bi2073ftx5 .

km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b rr:objectMap _:node1bi2073ftx5 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 rr:predicateObjectMap km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b .

km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b a rr:PredicateObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasPredicateObjectMap km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b .
</code>```

Body:
If I have a SQL table that can be queried like this:

Select empname from mytable
Where empid=1;

What would an equivalent SPARQL query be?

Body:
As a few people have mentioned here and on your similar, previous question, you probably need to do some more reading about the nature of RDF-modeled data.

For Stack Overflow, you definitely need to get into the habit of showing your input data and whatever code you have written so far, even if it isn't working perfectly.  In that case, you need to include the error message in your question.

Here's a self contained example in which I

guessed what your table looks like

modeled it as RDF

wrote a SPARQL query that does what you asked

The example is written in R, my strongest language.  To be clear:  you don't need to know anything about R to be good at RDF, SPARQL and other semantic technologies.  If I were better at Java or Python, I would have written the example in one of those languages.

The relational (SQL) data must be converted to RDF before it can be queried with RDF.  In the code below, I have done that by hand.  See the end of the message for the nuts and bolts.

library(rrdf)
library(sqldf)

mytable.table.string <- 'empid,empname
1,Arthur
2,Kevin
3,Joey'

mytable <- read.csv(textConnection(mytable.table.string))

print(mytable)

>  empid empname
> 1     1  Arthur
> 2     2  Kevin
> 3     3  Joey

sqldf('select empname from mytable where empid = 1')

>   empname
> 1  Arthur

# R2RML conversion goes here
# I did it by hand

table.rdf.string <- 'prefix mytable: <http://mytable/>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
mytable:1 a mytable:employee .
mytable:1 mytable:empid "1" .
mytable:1 rdfs:label "Arthur" .
mytable:2 a mytable:employee .
mytable:2 mytable:empid "2" .
mytable:2 rdfs:label "Kevin" .
mytable:3 a mytable:employee .
mytable:3 mytable:empid "3" .
mytable:3 rdfs:label "Joey" . '

mytable.rdf <- fromString.rdf(table.rdf.string, format = "TURTLE")

query.as.sparql <- 'prefix mytable: <http://mytable/>
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
select ?empname
where
{?emp a mytable:employee .
?emp mytable:empid "1" .
?emp rdfs:label ?empname . }'

sparql.rdf(model = mytable.rdf, sparql = query.as.sparql)

>     empname
> [1,] "Arthur"

To review:  this R code above demonstrates a SAPRQL query that is equivalent to the OP's SQL query.  SQL queries are typically run against SQL databases, but I made this self-contained by running it against a dataframe.

SPARQL queries are run against RDF data, frequently in the form of a triplestore database.  In my example, a string containing RDF triples is converted into an in-memory RDF model, and the SPARQL query is sent to that model.

So the question becomes, if you have data in a SQL database, how do you query the database's contents with SPARQL?  As of Summer, 2017, this is an evolving topic.  There are a variety of commercial and open-source tools that can help solve this problem, usually in one of two ways:

by creating an interface that appears to send the SPARQL query
directly to the SQL database, in real time

by transforming and dumping the SQL database contents as a static
RDF file, which can then be loaded into a naively SPARQL-compliant
triplestore

In either case, somebody will need to create a mapping from the SQL data into RDF format.  This is required because SQL tables don't intrinsically have explicit semantics.  Rows typically model individuals of some category, and columns typically represent properties or relationships of the individuals.  RDF triples must have explicit subject-verb-object semantics.

Here are my recommended first steps for SQL-RDF mapping with Karma, which has a nice graphical interface.  Similar results could be achieved with another R2RML mapper like D2RQ (works, but un-maintained for 3 years), ontop, or the R2RML parser.

Watch the Karma videos and read the user's guide,
especially steps 1 though 5 plus 7.

Install Karma according to the posted directions.

Launch Karma.  A web interface to Karma should appear in your web browser

Paste the ontology below into a text editor and save as
44403425.owl Open the attached ontology in Karma (import -> from file)

Likewise, save & import mytable.csv, which is intended to represent
a dump from a SQL database.  If you want to work with a live
database, you will be responsible for making sure the right database
drivers are installed.  In that case, use import -> Database Table
instead.

Again, save the model as mytable-model.ttl. Click on the pull-down
on the left of the gray bar near the top of the Karma web page.
Choose Apply R2RML model -> from file and load mytable_model.ttl

Click on the pull-down again and select Publish -> RDF.  Accept the suggested settings.

Look for OpenRDF at the right of the top black bar.  Right click
that link to open it in a new browser window/tab.

On the OpenRDF Workbench page, select the karma_data repository.
You can now use any of the Explore links on the left, including
the (SPARQL) Query link

The OpenRDF Workbench page will become inaccessible when you close
 Karma. You can export your new triples from the OpenRDF
 Workbench, or you can do it from the gray bar in Karma.  You
 can also export the modelling file, if you have made any changes to
 it.  At that point, the RDF data triples can be loaded into any other triplestore, or explored with command line tools like ARQ from Jena.

Finally, if you want to use an R2RML mapper other than Karma, you can use a mapping file similar to (but not identical to) mytable-model.ttl.  Karma does some data manipulations with snippets of Python, which get embedded in JSON.  That JSON becomes the huge object of a km-dev:hasWorksheetHistory triple. I don't believe that all R2RML parsers would recognize the Python/JSON.

44403425.owl

<?xml version="1.0"?>
<rdf:RDF xmlns="https://stackoverflow.com/questions/44403425.owl/"
     xml:base="https://stackoverflow.com/questions/44403425.owl/"
     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:mytable="https://stackoverflow.com/questions/44403425.owl/"
     xmlns:owl="http://www.w3.org/2002/07/owl#"
     xmlns:xml="http://www.w3.org/XML/1998/namespace"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
    <owl:Ontology rdf:about="https://stackoverflow.com/questions/44403425.owl"/>

    <owl:DatatypeProperty rdf:about="https://stackoverflow.com/questions/44403425.owl/empid">
        <rdfs:domain rdf:resource="https://stackoverflow.com/questions/44403425.owl/employee"/>
        <rdfs:range rdf:resource="http://www.w3.org/2000/01/rdf-schema#Literal"/>
        <rdfs:label>employee identifier</rdfs:label>
    </owl:DatatypeProperty>

    <owl:Class rdf:about="https://stackoverflow.com/questions/44403425.owl/employee">
        <owl:equivalentClass>
            <owl:Restriction>
                <owl:onProperty rdf:resource="https://stackoverflow.com/questions/44403425.owl/empid"/>
                <owl:cardinality rdf:datatype="http://www.w3.org/2001/XMLSchema#nonNegativeInteger">1</owl:cardinality>
            </owl:Restriction>
        </owl:equivalentClass>
        <rdfs:label>employee class</rdfs:label>
    </owl:Class>
</rdf:RDF>

mytable.csv

"empid","empname"
1,"Arthur"
2,"Kevin"
3,"Joey"

mytable-model.ttl

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix pato: <http://purl.obolibrary.org/obo/pato#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix obo: <http://purl.obolibrary.org/obo/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#> .
@prefix protege: <http://protege.stanford.edu/plugins/owl/protege#> .
@prefix turbo: <http://turbo.org/> .
@prefix subsets: <http://purl.obolibrary.org/obo/ro/subsets#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rr: <http://www.w3.org/ns/r2rml#> .
@prefix km-dev: <http://isi.edu/integration/karma/dev#> .

_:node1bi2073ftx1 a km-dev:R2RMLMapping ;
    km-dev:sourceName "mytable.csv" ;
    km-dev:modelPublicationTime "1496863444477"^^xsd:long ;
    km-dev:modelVersion "1.7" ;
    km-dev:hasInputColumns "[[{\"columnName\":\"empname\"}],[{\"columnName\":\"empid\"}]]" ;
    km-dev:hasOutputColumns "[[{\"columnName\":\"empname\"}],[{\"columnName\":\"empid\"}],[{\"columnName\":\"empid_val\"}]]" ;
    km-dev:hasModelLabel "mytable" ;
    km-dev:hasBaseURI "https://stackoverflow.com/questions/44403425.owl/" ;
    km-dev:hasWorksheetHistory """[
    {
        \"commandName\": \"SubmitPythonTransformationCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empid\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"newColumnName\",
                \"type\": \"other\",
                \"value\": \"empid_val\"
            },
            {
                \"name\": \"transformationCode\",
                \"type\": \"other\",
                \"value\": \"return getValue(\\\"empid\\\")\"
            },
            {
                \"name\": \"errorDefaultValue\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"isJSONOutput\",
                \"type\": \"other\",
                \"value\": \"false\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid_val\\\"}]}]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetWorksheetPropertiesCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"properties\",
                \"type\": \"other\",
                \"value\": {
                    \"graphLabel\": \"\",
                    \"hasBaseURI\": false,
                    \"prefix\": \"mytable\",
                    \"hasPrefix\": true,
                    \"hasServiceProperties\": false
                }
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetWorksheetPropertiesCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"properties\",
                \"type\": \"other\",
                \"value\": {
                    \"graphLabel\": \"\",
                    \"hasBaseURI\": true,
                    \"baseURI\": \"https://stackoverflow.com/questions/44403425.owl/\",
                    \"hasPrefix\": false,
                    \"hasServiceProperties\": false
                }
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetWorksheetPropertiesCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"properties\",
                \"type\": \"other\",
                \"value\": {
                    \"graphLabel\": \"mytable\",
                    \"hasBaseURI\": false,
                    \"hasPrefix\": false,
                    \"hasServiceProperties\": false
                }
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[]\"
            }
        ],
        \"tags\": [\"Transformation\"]
    },
    {
        \"commandName\": \"SetMetaPropertyCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empid\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"metaPropertyName\",
                \"type\": \"other\",
                \"value\": \"isUriOfClass\"
            },
            {
                \"name\": \"metaPropertyUri\",
                \"type\": \"other\",
                \"value\": \"https://stackoverflow.com/questions/44403425.owl/employee\"
            },
            {
                \"name\": \"metaPropertyId\",
                \"type\": \"other\",
                \"value\": \"https://stackoverflow.com/questions/44403425.owl/employee1\"
            },
            {
                \"name\": \"SemanticTypesArray\",
                \"type\": \"other\",
                \"value\": [{
                    \"DomainUri\": \"https://stackoverflow.com/questions/44403425.owl/employee\",
                    \"DomainId\": \"https://stackoverflow.com/questions/44403425.owl/employee1\",
                    \"isPrimary\": true,
                    \"isProvenance\": false,
                    \"FullType\": \"http://isi.edu/integration/karma/dev#classLink\",
                    \"DomainLabel\": \"https://stackoverflow.com/questions/44403425.owl/employee/employee1 (add)\"
                }]
            },
            {
                \"name\": \"trainAndShowUpdates\",
                \"type\": \"other\",
                \"value\": true
            },
            {
                \"name\": \"rdfLiteralType\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"language\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid\\\"}]}]\"
            }
        ],
        \"tags\": [\"SemanticType\"]
    },
    {
        \"commandName\": \"SetSemanticTypeCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empid_val\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"SemanticTypesArray\",
                \"type\": \"other\",
                \"value\": [{
                    \"DomainUri\": \"https://stackoverflow.com/questions/44403425.owl/employee\",
                    \"DomainId\": \"https://stackoverflow.com/questions/44403425.owl/employee1\",
                    \"isPrimary\": true,
                    \"isProvenance\": false,
                    \"FullType\": \"https://stackoverflow.com/questions/44403425.owl/empid\",
                    \"DomainLabel\": \"https://stackoverflow.com/questions/44403425.owl/employee/employee1\"
                }]
            },
            {
                \"name\": \"trainAndShowUpdates\",
                \"type\": \"other\",
                \"value\": true
            },
            {
                \"name\": \"rdfLiteralType\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"language\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid_val\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empid_val\\\"}]}]\"
            }
        ],
        \"tags\": [\"SemanticType\"]
    },
    {
        \"commandName\": \"SetSemanticTypeCommand\",
        \"model\": \"new\",
        \"inputParameters\": [
            {
                \"name\": \"hNodeId\",
                \"type\": \"hNodeId\",
                \"value\": [{\"columnName\": \"empname\"}]
            },
            {
                \"name\": \"worksheetId\",
                \"type\": \"worksheetId\",
                \"value\": \"W\"
            },
            {
                \"name\": \"selectionName\",
                \"type\": \"other\",
                \"value\": \"DEFAULT_TEST\"
            },
            {
                \"name\": \"SemanticTypesArray\",
                \"type\": \"other\",
                \"value\": [{
                    \"DomainUri\": \"https://stackoverflow.com/questions/44403425.owl/employee\",
                    \"DomainId\": \"https://stackoverflow.com/questions/44403425.owl/employee1\",
                    \"isPrimary\": true,
                    \"isProvenance\": false,
                    \"FullType\": \"http://www.w3.org/2000/01/rdf-schema#label\",
                    \"DomainLabel\": \"https://stackoverflow.com/questions/44403425.owl/employee/employee1\"
                }]
            },
            {
                \"name\": \"trainAndShowUpdates\",
                \"type\": \"other\",
                \"value\": true
            },
            {
                \"name\": \"rdfLiteralType\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"language\",
                \"type\": \"other\",
                \"value\": \"\"
            },
            {
                \"name\": \"inputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empname\\\"}]}]\"
            },
            {
                \"name\": \"outputColumns\",
                \"type\": \"hNodeIdList\",
                \"value\": \"[{\\\"value\\\":[{\\\"columnName\\\":\\\"empname\\\"}]}]\"
            }
        ],
        \"tags\": [\"SemanticType\"]
    }
]""" .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 a rr:TriplesMap .

_:node1bi2073ftx1 km-dev:hasTriplesMap km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx2 rr:tableName "mytable.csv" ;
    a rr:LogicalTable ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasLogicalTable _:node1bi2073ftx2 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 rr:logicalTable _:node1bi2073ftx2 ;
    rr:subjectMap _:node1bi2073ftx3 .

_:node1bi2073ftx1 km-dev:hasSubjectMap _:node1bi2073ftx3 .

_:node1bi2073ftx3 km-dev:isPartOfMapping _:node1bi2073ftx1 ;
    a rr:SubjectMap ;
    km-dev:alignmentNodeId "https://stackoverflow.com/questions/44403425.owl/employee1" ;
    rr:class <https://stackoverflow.com/questions/44403425.owl/employee> ;
    rr:template "{empid}" ;
    a km-dev:steinerTreeRootNode .

km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 rr:predicate <https://stackoverflow.com/questions/44403425.owl/empid> .

_:node1bi2073ftx4 rr:column "empid" ;
    a rr:ObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasObjectMap _:node1bi2073ftx4 .

km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 rr:objectMap _:node1bi2073ftx4 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 rr:predicateObjectMap km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 .

km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 a rr:PredicateObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasPredicateObjectMap km-dev:PredicateObjectMap_5a63b356-1bbb-4b1f-b64a-514c19f83d28 .

km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b rr:predicate rdfs:label .

_:node1bi2073ftx5 rr:column "empname" ;
    a rr:ObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasObjectMap _:node1bi2073ftx5 .

km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b rr:objectMap _:node1bi2073ftx5 .

km-dev:TriplesMap_d397eb02-1069-4e93-a544-0f2c4d1f8970 rr:predicateObjectMap km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b .

km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b a rr:PredicateObjectMap ;
    km-dev:isPartOfMapping _:node1bi2073ftx1 .

_:node1bi2073ftx1 km-dev:hasPredicateObjectMap km-dev:PredicateObjectMap_028e84af-9ed2-406c-81d0-9add2ed2ca2b .


问:
Wait Firebase async retrieve data in Android
I need to store the result of FireBase getValue method that is async by his own. I can't use something like "onPostExecute()" and, for my purpose, i can't execute all my operation "into onDataChange()" because i need some references in future time in other activities.

Here my snippet to retrieve data:

```<code>    List<Village> villages = new LinkedList<>();
    Firebase ref = new Firebase("MYFIREBASEURL").child("village");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            spinnerArray.clear();
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                Village v = postSnapshot.getValue(Village.class);
                villages.add(v);
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });
</code>```

If i try to read villages out of "onDataChange" i have, naturally for his async life, null value. There is a way to ensure that onDataChange was called?.

答:
Just to add to Manh's answer, one would call onStart() just before

```<code> FirebaseDatabase.getInstance().getReference().child(child).addListenerForSingleValueEvent(new ValueEventListener() {
</code>```

And in onStart(), typically you would show a progressDialog:

```<code>    if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setMessage(getString(R.string.loading));
        mProgressDialog.setIndeterminate(true);
    }

    mProgressDialog.show();
</code>```

And in onSuccess() dismiss the dialog and load the data onto GUI (or whatever you want to do)

```<code>    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to store the result of FireBase getValue method that is async by his own. I can't use something like "onPostExecute()" and, for my purpose, i can't execute all my operation "into onDataChange()" because i need some references in future time in other activities.

Here my snippet to retrieve data:

    List<Village> villages = new LinkedList<>();
    Firebase ref = new Firebase("MYFIREBASEURL").child("village");
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            spinnerArray.clear();
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                Village v = postSnapshot.getValue(Village.class);
                villages.add(v);
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });

If i try to read villages out of "onDataChange" i have, naturally for his async life, null value. There is a way to ensure that onDataChange was called?.

Body:
Just to add to Manh's answer, one would call onStart() just before

 FirebaseDatabase.getInstance().getReference().child(child).addListenerForSingleValueEvent(new ValueEventListener() {

And in onStart(), typically you would show a progressDialog:

    if (mProgressDialog == null) {
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setMessage(getString(R.string.loading));
        mProgressDialog.setIndeterminate(true);
    }

    mProgressDialog.show();

And in onSuccess() dismiss the dialog and load the data onto GUI (or whatever you want to do)

    if (mProgressDialog != null && mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
    }


问:
spring data jpa repository inject fails using @Autowired in spring boot
spring boot entry class

```<code>package com.test;

@SpringBootApplication(exclude={
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class})
public class AssetManagementDigital2Application {

    public static void main(String[] args) {
        SpringApplication.run(AssetManagementDigital2Application.class, args);
    }
}
</code>```

Controller class

```<code>package com.test.assetmanagementdigital.controller;

 @RestController

public class ShopController {

    @Autowired
    private ShopServiceImpl shopServiceImpl;

    @RequestMapping(value="/shops",method=RequestMethod.POST)
    public void shopDetails(Shop shop){
        shopServiceImpl.addShopDetails(shop);

    }

}
</code>```

Entity

```<code>package com.test.assetmanagementdigital.model;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="ShopDetails")
public class Shop {

    private String shopName;
    private Address address;

    public String getShopName() {
        return shopName;
    }

    public void setShopName(String shopName) {
        this.shopName = shopName;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

}
</code>```

data jpa repository interface

```<code>package com.test.assetmanagementdigital.repository;
    @Repository
    public interface ShopRepository extends CrudRepository<Shop,Long>{

    }
</code>```

Service class

```<code>package com.test.assetmanagementdigital.service;
@Service
public class ShopServiceImpl {

    @Autowired
    private ShopRepository shopRepository;

    public void addShopDetails(Shop shop) {
        shopRepository.save(shop);
    }

}
</code>```

gradle file

```<code> buildscript {
        ext {
            springBootVersion = '2.0.0.BUILD-SNAPSHOT'
        }
        repositories {
            mavenCentral()
            maven { url "https://repo.spring.io/snapshot" }
            maven { url "https://repo.spring.io/milestone" }
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        }
    }

    apply plugin: 'java'
    apply plugin: 'eclipse-wtp'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'
    apply plugin: 'war'

    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = 1.8

    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }

    configurations {
        providedRuntime
    }

    dependencies {
        compile('org.springframework.boot:spring-boot-starter-data-jpa')
        compile('org.springframework.boot:spring-boot-starter-web')
        compile("com.h2database:h2")
        compile group: 'org.hibernate', name: 'hibernate-core', version: '4.2.2.Final'
        providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }
</code>```

I am getting following error

```<code>Description:

Field shopRepository in com.test.assetmanagementdigital.service.ShopServiceImpl required a bean of type 'com.test.assetmanagementdigital.repository.ShopRepository' that could not be found.

Action:

Consider defining a bean of type 'com.test.assetmanagementdigital.repository.ShopRepository' in your configuration.
</code>```

if i remove the @Autowired annotation from ShopRepository then it will throw `NullPointerException

I have tried @EnableJpaRepositories("com.test.assetmanagementdigital.repository") here I get

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'shopController': Unsatisfied dependency expressed through field 'shopServiceImpl'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shopServiceImpl': Unsatisfied dependency expressed through field 'shopRepository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shopRepository': Post-processing of merged bean definition failed; nested exception is
java.lang.NoSuchMethodError: javax.persistence.PersistenceContext.synchronization()Ljavax/persistence/SynchronizationType;
</code>```

答:
You need to provide the package name to Spring to scan the repositories from, using @EnableJpaRepositories annnotation, e.g.:

```<code>@SpringBootApplication
@EnableJpaRepositories("com.test.assetmanagementdigital.repository")
public class AssetManagementDigital2Application
</code>```

Here's the documentation.

Body:
spring boot entry class

package com.test;

@SpringBootApplication(exclude={
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class})
public class AssetManagementDigital2Application {

    public static void main(String[] args) {
        SpringApplication.run(AssetManagementDigital2Application.class, args);
    }
}

Controller class

package com.test.assetmanagementdigital.controller;

 @RestController

public class ShopController {

    @Autowired
    private ShopServiceImpl shopServiceImpl;

    @RequestMapping(value="/shops",method=RequestMethod.POST)
    public void shopDetails(Shop shop){
        shopServiceImpl.addShopDetails(shop);

    }

}

Entity

package com.test.assetmanagementdigital.model;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="ShopDetails")
public class Shop {

    private String shopName;
    private Address address;

    public String getShopName() {
        return shopName;
    }

    public void setShopName(String shopName) {
        this.shopName = shopName;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

}

data jpa repository interface

package com.test.assetmanagementdigital.repository;
    @Repository
    public interface ShopRepository extends CrudRepository<Shop,Long>{

    }

Service class

package com.test.assetmanagementdigital.service;
@Service
public class ShopServiceImpl {

    @Autowired
    private ShopRepository shopRepository;

    public void addShopDetails(Shop shop) {
        shopRepository.save(shop);
    }

}

gradle file

 buildscript {
        ext {
            springBootVersion = '2.0.0.BUILD-SNAPSHOT'
        }
        repositories {
            mavenCentral()
            maven { url "https://repo.spring.io/snapshot" }
            maven { url "https://repo.spring.io/milestone" }
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        }
    }

    apply plugin: 'java'
    apply plugin: 'eclipse-wtp'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'
    apply plugin: 'war'

    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = 1.8

    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }

    configurations {
        providedRuntime
    }

    dependencies {
        compile('org.springframework.boot:spring-boot-starter-data-jpa')
        compile('org.springframework.boot:spring-boot-starter-web')
        compile("com.h2database:h2")
        compile group: 'org.hibernate', name: 'hibernate-core', version: '4.2.2.Final'
        providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }

I am getting following error

Description:

Field shopRepository in com.test.assetmanagementdigital.service.ShopServiceImpl required a bean of type 'com.test.assetmanagementdigital.repository.ShopRepository' that could not be found.

Action:

Consider defining a bean of type 'com.test.assetmanagementdigital.repository.ShopRepository' in your configuration.

if i remove the @Autowired annotation from ShopRepository then it will throw `NullPointerException

I have tried @EnableJpaRepositories("com.test.assetmanagementdigital.repository") here I get

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'shopController': Unsatisfied dependency expressed through field 'shopServiceImpl'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shopServiceImpl': Unsatisfied dependency expressed through field 'shopRepository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shopRepository': Post-processing of merged bean definition failed; nested exception is
java.lang.NoSuchMethodError: javax.persistence.PersistenceContext.synchronization()Ljavax/persistence/SynchronizationType;

Body:
You need to provide the package name to Spring to scan the repositories from, using @EnableJpaRepositories annnotation, e.g.:

@SpringBootApplication
@EnableJpaRepositories("com.test.assetmanagementdigital.repository")
public class AssetManagementDigital2Application

Here's the documentation.


问:
Is generating components in render efficient?
In a simple component I have an array of child components. In the parent's state (among other things), I hold an array of objects and in the render function I construct the child components as:

```<code>const children = [];
let i = 1;
for(let child of this.state.children){
    children.push(<Decoration key={i++} {...child} />);
}
return (
    <div>{children} {this.state.something_else}</div>
);
</code>```

The problem is that whenever I change some other state values, the render function of the child component gets called which is strange since I don't change anything in the children array. Any ideas? Is this code inefficient?

答:
You might want to move the code out of the render() method and put it into one of the lifecycle methods in this case it would be

componentWillMount and componentWillReceiveProps. You can construct your children array there and simply disply it in the render() e.g.

```<code>render(){
  return (
      <div>{children} {this.state.something_else}</div>
  );
}
</code>```

Body:
In a simple component I have an array of child components. In the parent's state (among other things), I hold an array of objects and in the render function I construct the child components as:

const children = [];
let i = 1;
for(let child of this.state.children){
    children.push(<Decoration key={i++} {...child} />);
}
return (

{children} {this.state.something_else}

);

The problem is that whenever I change some other state values, the render function of the child component gets called which is strange since I don't change anything in the children array. Any ideas? Is this code inefficient?

Body:
You might want to move the code out of the render() method and put it into one of the lifecycle methods in this case it would be

componentWillMount and componentWillReceiveProps. You can construct your children array there and simply disply it in the render() e.g.

render(){
  return (
      <div>{children} {this.state.something_else}</div>
  );
}


问:
How to evaluate this formula right in apache poi?
In Microsoft Office Excel,I set this formula in a cell.=YEAR("2017-01-01").The result is 2017.

In apache-poi,I do the same.

```<code>cell.setCellFormula("YEAR(\"2017-01-01\")");
</code>```

But I get a wrong result.

```<code>#VALUE!
</code>```

How to get the correct result?

Code

```<code>HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfworkbook.createSheet("Sheet1");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellFormula("YEAR(\"2017-01-01\")");
CreationHelper creationHelper = hssfworkbook.getCreationHelper();
FormulaEvaluator evaluator = creationHelper.createFormulaEvaluator();
System.out.println(evaluator.evaluate(cell));
</code>```

Console

```<code>org.apache.poi.ss.usermodel.CellValue [#VALUE!]
</code>```

use apache-poi 3.16

答:
From Interface FormulaEvaluator docs

If cell contains formula, it evaluates the formula, and puts the formula result back into the cell, in place of the old formula. Else if cell does not contain formula, this method leaves the cell unchanged. Note that the same instance of Cell is returned to allow chained calls like:

```<code>int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType();
</code>```

```<code>if (cell.getCellType() == Cell.CELL_TYPE_FORMULA)
{
     cell = evaluator.evaluateInCell(cell);
}
</code>```

Body:
In Microsoft Office Excel,I set this formula in a cell.=YEAR("2017-01-01").The result is 2017.

In apache-poi,I do the same.

cell.setCellFormula("YEAR(\"2017-01-01\")");

But I get a wrong result.

#VALUE!

How to get the correct result?

Code

HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfworkbook.createSheet("Sheet1");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellFormula("YEAR(\"2017-01-01\")");
CreationHelper creationHelper = hssfworkbook.getCreationHelper();
FormulaEvaluator evaluator = creationHelper.createFormulaEvaluator();
System.out.println(evaluator.evaluate(cell));

Console

org.apache.poi.ss.usermodel.CellValue [#VALUE!]

use apache-poi 3.16

Body:
From Interface FormulaEvaluator docs

If cell contains formula, it evaluates the formula, and puts the formula result back into the cell, in place of the old formula. Else if cell does not contain formula, this method leaves the cell unchanged. Note that the same instance of Cell is returned to allow chained calls like:

int evaluatedCellType = evaluator.evaluateInCell(cell).getCellType();

if (cell.getCellType() == Cell.CELL_TYPE_FORMULA)
{
     cell = evaluator.evaluateInCell(cell);
}


问:
How to properly close a JMS connection?
I am trying to use Spring's SingleConnectionFactory, where there are 2 connection factories, and only one of them should be able to connect at a time.

```<code><bean id="connectionFactory1" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>

<bean id="connectionFactory2" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>
</code>```

By using the same client id in both factories(CLIENT_ID), I made sure that when I create connection from one factory, I can't create another connection from the other factory (throws InvalidClientIDException, so this is as expected). But the issue is, when I close the connection I got from first factory, and try to get connection from second factory, I'm still getting the exception.

Using the following Java code:

```<code>Connection connection1 = connectionFactory1.createConnection();
connection1.close();

Connection connection2 = connectionFactory2.createConnection();
</code>```

What is the proper way of closing first connection, so that it allows me to create connection using the second factory?

Also, note that I am not using Queues here. I have to achieve this without queues.

答: Use factory.resetConnection() to actually close the single connection.

Title: How to properly close a JMS connection?

Body:
I am trying to use Spring's SingleConnectionFactory, where there are 2 connection factories, and only one of them should be able to connect at a time.

<bean id="connectionFactory1" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>

<bean id="connectionFactory2" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>

By using the same client id in both factories(CLIENT_ID), I made sure that when I create connection from one factory, I can't create another connection from the other factory (throws InvalidClientIDException, so this is as expected). But the issue is, when I close the connection I got from first factory, and try to get connection from second factory, I'm still getting the exception.

Using the following Java code:

Connection connection1 = connectionFactory1.createConnection();
connection1.close();

Connection connection2 = connectionFactory2.createConnection();

What is the proper way of closing first connection, so that it allows me to create connection using the second factory?

Also, note that I am not using Queues here. I have to achieve this without queues.


问:
MEF - Can I create instances and have them automatically Composed inside MEF?
As I understand, in order for Import/Export attributes to be correctly connected to each other, I have to call compositionContainerInstance.Compose(...) with each new instance that has these attributes.

Is it possible to have this happening automatically, so I don't have to do it whenever I create a new instance of some composable  class?

This would be an example, although lengthly, it abstracts the problem I have.

```<code>public class Worker1
{
    [Import(typeof(IDataProvider))]
    public IDataProvider DataProvider;

    public Worker2 second;
    //use data provider to perform logic
}

public class Worker2
{
    [Import(typeof(IDataProvider))]
    public IDataProvider DataProvider;

    //use data provider to perform logic
}

[Export(typeof(IDataProvider))]
public class GeoDataProvider : IDataProvider
{
    //implements logic
}

public class Container
{
    private Worker1 t1;
    public void Init()
    {
        AggregateCatalog cat = new AggregateCatalog();
        cat.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
        cat.Catalogs.Add(new DirectoryCatalog("."));

        CompositionContainer c = new CompositionContainer(cat);
        c.ComposeParts(new GeoDataProvider(), this);
    }

    public void PerformLogic()
    {
        t1 = new Worker1;
        //here it fails because I need c.ComposeParts(t1):
        t1.DoSomethingWithProvider();
        //but even if I do c.ComposeParts(t1), still the t1.second.DataProvider will be null
        //how to avoid this?
    }
}
</code>```

What I'm hoping for is a way to freely create new instances of Worker1/Worker2 without needing to know that they have to be composed before usage. Is that feasible?

答:
Someone has to know that they need composed.

If you're going to freely create Worker1 and Work2 instances rather than letting MEF create them then you have to also give MEF a chance to satisfy the imports of new instances or as you've discovered, the IDataProvider field is never filled out.

Here's an example where you just let MEF create the classes as needed.  Only one 'ComposeParts' call is needed to get everything setup.

```<code>[Export]
public class Worker1
{
  [Import]
  public IDataProvider DataProvider;

  [Import]
  public Worker2 second;

  //use data provider to perform logic
  public void DoSomethingWithProvider() {
    }
}

[Export]
public class Worker2
{
  [Import]
  public IDataProvider DataProvider;

  //use data provider to perform logic
}

[Export( typeof( IDataProvider ) )]
public class GeoDataProvider : IDataProvider
{
  //implements logic
}

public class Container
{
  [Import]
  private Worker1 t1;

  public void Init()
  {
    AggregateCatalog cat = new AggregateCatalog();
    cat.Catalogs.Add( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );
    cat.Catalogs.Add( new DirectoryCatalog( "." ) );

    CompositionContainer c = new CompositionContainer( cat );
    c.ComposeParts( this );
  }

  public void PerformLogic()
  {
    t1.DoSomethingWithProvider();
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As I understand, in order for Import/Export attributes to be correctly connected to each other, I have to call compositionContainerInstance.Compose(...) with each new instance that has these attributes.

Is it possible to have this happening automatically, so I don't have to do it whenever I create a new instance of some composable  class?

This would be an example, although lengthly, it abstracts the problem I have.

public class Worker1
{
    [Import(typeof(IDataProvider))]
    public IDataProvider DataProvider;

    public Worker2 second;
    //use data provider to perform logic
}

public class Worker2
{
    [Import(typeof(IDataProvider))]
    public IDataProvider DataProvider;

    //use data provider to perform logic
}

[Export(typeof(IDataProvider))]
public class GeoDataProvider : IDataProvider
{
    //implements logic
}

public class Container
{
    private Worker1 t1;
    public void Init()
    {
        AggregateCatalog cat = new AggregateCatalog();
        cat.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
        cat.Catalogs.Add(new DirectoryCatalog("."));

        CompositionContainer c = new CompositionContainer(cat);
        c.ComposeParts(new GeoDataProvider(), this);
    }

    public void PerformLogic()
    {
        t1 = new Worker1;
        //here it fails because I need c.ComposeParts(t1):
        t1.DoSomethingWithProvider();
        //but even if I do c.ComposeParts(t1), still the t1.second.DataProvider will be null
        //how to avoid this?
    }
}

What I'm hoping for is a way to freely create new instances of Worker1/Worker2 without needing to know that they have to be composed before usage. Is that feasible?

Body:
Someone has to know that they need composed.

If you're going to freely create Worker1 and Work2 instances rather than letting MEF create them then you have to also give MEF a chance to satisfy the imports of new instances or as you've discovered, the IDataProvider field is never filled out.

Here's an example where you just let MEF create the classes as needed.  Only one 'ComposeParts' call is needed to get everything setup.

[Export]
public class Worker1
{
  [Import]
  public IDataProvider DataProvider;

  [Import]
  public Worker2 second;

  //use data provider to perform logic
  public void DoSomethingWithProvider() {
    }
}

[Export]
public class Worker2
{
  [Import]
  public IDataProvider DataProvider;

  //use data provider to perform logic
}

[Export( typeof( IDataProvider ) )]
public class GeoDataProvider : IDataProvider
{
  //implements logic
}

public class Container
{
  [Import]
  private Worker1 t1;

  public void Init()
  {
    AggregateCatalog cat = new AggregateCatalog();
    cat.Catalogs.Add( new AssemblyCatalog( Assembly.GetExecutingAssembly() ) );
    cat.Catalogs.Add( new DirectoryCatalog( "." ) );

    CompositionContainer c = new CompositionContainer( cat );
    c.ComposeParts( this );
  }

  public void PerformLogic()
  {
    t1.DoSomethingWithProvider();
  }
}


问:
Find coincidence between item in Firebase List and value provided
Sorry by my question. Maybe it's too evident, but I'm new in Ionic and I would like do the things the best as possible.

I have a barcode scanner that returns a value with the key of a collection in my firebase database. I need to know if the scanned code exists in my database. Up to this point this is what I have:

```<code>export class HomePage {

    constructor(
         private barcode: BarcodeScanner,
         public navCtrl: NavController,
         af: AngularFireDatabase) {

         // Here I get the list of elements where I will search the scanned code.
         this.ocupadas = af.list('/UbicacionesOcupadas', {
             query: {
                 orderByChild: 'evento',
                 equalTo: 28
             }
         });
      }

      // Here I get the QR Code value.
      async scanBarcode() {
          this.results = await this.barcode.scan(this.options);
      }

      // Now, I need to know if the QR Code value is in the firebase list. How would you do?
</code>```

答:
You could try using find to compare between the results.</p>

```<code>public findScanAgainstStoredList(scannedItem){
   // scannedItem being this.results
   let item = this.ocupadas.find(scannedItem);
   if(item != undefined){
       // do something if there is an item
   }else{
       // do something if no item is found
   }
}
</code>```

Body:
Sorry by my question. Maybe it's too evident, but I'm new in Ionic and I would like do the things the best as possible.

I have a barcode scanner that returns a value with the key of a collection in my firebase database. I need to know if the scanned code exists in my database. Up to this point this is what I have:

export class HomePage {

    constructor(
         private barcode: BarcodeScanner,
         public navCtrl: NavController,
         af: AngularFireDatabase) {

         // Here I get the list of elements where I will search the scanned code.
         this.ocupadas = af.list('/UbicacionesOcupadas', {
             query: {
                 orderByChild: 'evento',
                 equalTo: 28
             }
         });
      }

      // Here I get the QR Code value.
      async scanBarcode() {
          this.results = await this.barcode.scan(this.options);
      }

      // Now, I need to know if the QR Code value is in the firebase list. How would you do?

Body:
You could try using find to compare between the results.

public findScanAgainstStoredList(scannedItem){
   // scannedItem being this.results
   let item = this.ocupadas.find(scannedItem);
   if(item != undefined){
       // do something if there is an item
   }else{
       // do something if no item is found
   }
}


问:
R rvest: could not find function "xpath_element"
I am trying to simply replicate the example of rvest::html_nodes(), yet encounter an error:

```<code>library(rvest)
ateam <- read_html("http://www.boxofficemojo.com/movies/?id=ateam.htm")
html_nodes(ateam, "center")
</code>```

Error in do.call(method, list(parsed_selector)) :    could not find
  function "xpath_element"

The same happens if I load packages such as httr, xml2, selectr. I seem to have the latest version of these packages too...

In which packages are functions such as xpath_element, xpath_combinedselector located? How do I get it to work? Note that I am running on Ubuntu 16.04, so that code might work on other platforms...

答:
I understand this issue is rather old but I wanted to post a comment for those who may have similar issues.

I stumbled upon this same error and was unable to find much help. So, I thought instead of targeting CSS I would try to target the xpath instead. I do not know what the best practice is.

My original functions worked fine on Ubuntu 16, R 3.4.0. However, they failed on Debian 8 R 3.3.3 and R 3.4.0.

When I modified my code to target xpaths instead of css they began working as expected. For example, changing this...

```<code>contents <- link %>%
    xml2::read_html() %>%
    rvest::html_nodes(css = "pre") %>%
    rvest::html_text()
</code>```

to this...

```<code>contents <- link %>%
    xml2::read_html() %>%
    rvest::html_nodes(xpath = "//pre") %>%
    rvest::html_text()
</code>```

resolved my issue.

Body:
I am trying to simply replicate the example of rvest::html_nodes(), yet encounter an error:

library(rvest)
ateam <- read_html("http://www.boxofficemojo.com/movies/?id=ateam.htm")
html_nodes(ateam, "center")

Error in do.call(method, list(parsed_selector)) :    could not find
  function "xpath_element"

The same happens if I load packages such as httr, xml2, selectr. I seem to have the latest version of these packages too...

In which packages are functions such as xpath_element, xpath_combinedselector located? How do I get it to work? Note that I am running on Ubuntu 16.04, so that code might work on other platforms...

Body:
I understand this issue is rather old but I wanted to post a comment for those who may have similar issues.

I stumbled upon this same error and was unable to find much help. So, I thought instead of targeting CSS I would try to target the xpath instead. I do not know what the best practice is.

My original functions worked fine on Ubuntu 16, R 3.4.0. However, they failed on Debian 8 R 3.3.3 and R 3.4.0.

When I modified my code to target xpaths instead of css they began working as expected. For example, changing this...

contents <- link %>%
    xml2::read_html() %>%
    rvest::html_nodes(css = "pre") %>%
    rvest::html_text()

to this...

contents <- link %>%
    xml2::read_html() %>%
    rvest::html_nodes(xpath = "//pre") %>%
    rvest::html_text()

resolved my issue.


问:
Unable to log into WeChat Sandbox
Revisiting a project I've not opened for a month or so I've found that the sandbox account I previously set up cant be accessed, visiting;
http://admin.wechat.com/debug/cgi-bin/sandbox?t=sandbox/login

Allows me to log in via. the scanning of the QR code but after (seemingly) managing to log in it then gives the error 'Unable to initialize'

Previously this worked I'm wondering if there's been an unpublicised change to the WeChat platform?

答: Same here! The International sandbox is not letting me in, but the Weixin one works.</p>

Title: Unable to log into WeChat Sandbox


问:
Regex alphanumeric with special characters
I need to validate input string using regex which should met below requirements:

If All Numbers -> Error

If All Special Characters -> Error

If only Numbers + special Characters -> Error

Remaining all should be flagged as non error.

I couldn't get all my test cases passed.

Here is my regex:

```<code>\d*([a-zA-Z,\/().]*[a-zA-Z][\d,\/().]*)[a-zA-Z\d\s]*$
</code>```

For the special characters, I get a specific list ,\/(). to let them in. Can anyone help me to understand this?

答:
You may use the following regex:

```<code>^(?:[\d,\/().]*[a-zA-Z][a-zA-Z\d,\/().]*)?$
</code>```

See the regex demo

Details:

^ - start of string

(?:[\d,\/().]*[a-zA-Z][a-zA-Z\d,\/().]*)? - an optional sequence (it lets the string be empty):

[\d,\/().]* - 0+ digits and special

[a-zA-Z] - one alpha

[a-zA-Z\d,\/().]* - 0+ alpha, digits and special

$ - end of string

Body:
I need to validate input string using regex which should met below requirements:

If All Numbers -> Error

If All Special Characters -> Error

If only Numbers + special Characters -> Error

Remaining all should be flagged as non error.

I couldn't get all my test cases passed.

Here is my regex:

\d*([a-zA-Z,\/().]*[a-zA-Z][\d,\/().]*)[a-zA-Z\d\s]*$

For the special characters, I get a specific list ,\/(). to let them in. Can anyone help me to understand this?

Body:
You may use the following regex:

^(?:[\d,\/().]*[a-zA-Z][a-zA-Z\d,\/().]*)?$

See the regex demo

Details:

^ - start of string

(?:[\d,\/().]*[a-zA-Z][a-zA-Z\d,\/().]*)? - an optional sequence (it lets the string be empty):

[\d,\/().]* - 0+ digits and special

[a-zA-Z] - one alpha

[a-zA-Z\d,\/().]* - 0+ alpha, digits and special

$ - end of string


问:
How to access function key to add focus to a control?
In my web application on my master page I have a search box [<option> </option> list] for searching pages.

something like this

I like to enable this search option on function key press [ f9 ]. How can I do that ?

Design

```<code><form class="form form-search">
                    <select id="select-templating" data-placeholder="Search " onchange="location = this.value;" class="width300">
                        <option value="">Search</option>
                        <option value="Home.aspx">Home</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AuthorizationList.aspx">Authorization List</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AccountClosing.aspx">Account Closing</option>
                        <option value="AccountTransaction.aspx">Account Transaction</option>
                        <option value="CustomerCreation.aspx">Customer Creation</option>
                        <option value="ShareDividendDeclaration.aspx">Share Dividend Declaration</option>
                    </select>
                </form>
</code>```

In the same solution, I used key f2 to redirect to home using jquery
function(which is working) :

```<code> $(function () {
        $(document).keyup(function (e) {
            var key = (e.keyCode ? e.keyCode : e.charCode);
            switch (key) {

                case 113:
                    window.location.replace("Home.aspx");
                    break;

                default:;
            }
        });
        function navigateUrl(jObj) {
            window.location.href = $(jObj).attr("href");
        }
    });
</code>```

but I don't know how to use f9 key for open search <option> control.. Help me please

答:
You can make use of open option of select2 plugin to open select on F9:

```<code>$(document).on('keyup',function(e){
    if(e.which==120){
    $('#select-templating').select2('open');
  }
})
</code>```

Here's the Fiddle DEMO

Updating your code would be as below:

```<code>$(document).keyup(function (e) {
     var key = (e.keyCode ? e.keyCode : e.charCode);
     switch (key) {
            case 113:
                window.location.replace("Home.aspx");
                break;
            case 120:
                $('#select-templating').select2('open');
                break;
            default:;
     }
});
</code>```

Let me know if you face any issue.

Body:
In my web application on my master page I have a search box [<option> </option> list] for searching pages.

something like this

I like to enable this search option on function key press [ f9 ]. How can I do that ?

Design

<form class="form form-search">
                    <select id="select-templating" data-placeholder="Search " onchange="location = this.value;" class="width300">
                        <option value="">Search</option>
                        <option value="Home.aspx">Home</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AuthorizationList.aspx">Authorization List</option>
                        <option value="Modifications.aspx">Modifications</option>
                        <option value="AccountClosing.aspx">Account Closing</option>
                        <option value="AccountTransaction.aspx">Account Transaction</option>
                        <option value="CustomerCreation.aspx">Customer Creation</option>
                        <option value="ShareDividendDeclaration.aspx">Share Dividend Declaration</option>
                    </select>
                </form>

In the same solution, I used key f2 to redirect to home using jquery
function(which is working) :

 $(function () {
        $(document).keyup(function (e) {
            var key = (e.keyCode ? e.keyCode : e.charCode);
            switch (key) {

                case 113:
                    window.location.replace("Home.aspx");
                    break;

                default:;
            }
        });
        function navigateUrl(jObj) {
            window.location.href = $(jObj).attr("href");
        }
    });

but I don't know how to use f9 key for open search <option> control.. Help me please

Body:
You can make use of open option of select2 plugin to open select on F9:

$(document).on('keyup',function(e){
    if(e.which==120){
    $('#select-templating').select2('open');
  }
})

Here's the Fiddle DEMO

Updating your code would be as below:

$(document).keyup(function (e) {
     var key = (e.keyCode ? e.keyCode : e.charCode);
     switch (key) {
            case 113:
                window.location.replace("Home.aspx");
                break;
            case 120:
                $('#select-templating').select2('open');
                break;
            default:;
     }
});

Let me know if you face any issue.