问:
Find all rows with the same exact relations as provided in another table
Given these tables:

Table: Test

Columns:

testID int PK

name nvarchar(128) UNIQUE NOT NULL

Table: [Test-Inputs]

Columns

inputsTableName nvarchar(128) UNIQUE PK

testID int PK FK

Temporary Table: ##TestSearchParams

Columns:

inputsTableName nvarchar(128) UNIQUE NOT NULL

I need to find Tests that have entries in Test-Inputs with inputsTableNames matching EXACTLY ALL of the entries in ##TestSearchParams; the resulting tests relationships must be exactly the ones listed in ##TestSearchParams.

Essentially I am finding tests with ONLY the given relationships, no more, no less. I am matching names with LIKE and wildcards, but that is a sidenote that I believe I can solve after the core logic is there for exact matching.

This is my current query:

```<code>Select *
From   Tests As B
Where  B.testID In (
                       Select ti
                       From   (
                                  Select   (
                                               Select Count(inputsTableName)
                                               From   [Test-Inputs]
                                               Where  [Test-Inputs].testID = B.testID
                                           ) - Count(Distinct i1) As delta,
                                           ti
                                  From     (
                                               Select [Test-Inputs].inputsTableName As i1,
                                                      [Test-Inputs].testID As ti
                                               From   ##TableSearchParams
                                               Join   [Test-Inputs]
                                                   On [Test-Inputs].inputsTableName Like ##TableSearchParams.inputsTableName
                                                      And B.testID = [Test-Inputs].testID
                                           ) As A
                                  Group By ti
                              ) As D
                       Where  D.delta = 0
                   );
</code>```

The current problem is that his seems to retrieve Tests with a match to ANY of the entries in ##TableSearchParams. I have tried several other queries before this, to varying levels of success. I have working queries for find tests that match any of the parameters, all of the paramters, and none of the parameters -- I just cant get this query working.

Here are some sample table values:

Tests

1, Test1

2, Test2

3, Test3

[Test-Inputs]

Table1, 1

Table2, 2

Table1, 3

Table2, 3

TestSearchParams

Table1

Table2

The given values should only return (3, Test3)

答:
Here's a possible solution that works by getting the complete set of TestInputs for each record in Tests, left-joining to the set of search parameters, and then aggregating the results by test and making two observations:

First, if a record from Tests includes a TestInput that is not among the search parameters, then that record must be excluded from the result set. We can check this by seeing if there is any case in which the left-join described above did not produce a match in the search parameters table.

Second, if a record from Tests satisfies the first condition, then we know that it doesn't have any superfluous TestInput records, so the only problem it could have is if there exists a search parameter that is not among its TestInputs. If that is so, then the number of records we've aggregated for that Test will be less than the total number of search parameters.

I have made the assumption here that you don't have Tests records with duplicate TestInputs, and that you likewise don't use duplicate search parameters. If those assumptions are not valid then this becomes more complicated. But if they are, then this ought to work:

```<code>declare @Tests table (testID int, [name] nvarchar(128));
declare @TestInputs table (testID int, inputsTableName nvarchar(128));
declare @TestSearchParams table (inputsTableName nvarchar(128));

-- Sample data.
--
-- testID 1 has only a subset of the search parameters.
-- testID 2 matches the search parameters exactly.
-- testID 3 has a superset of the search parameters.
--
-- Therefore the result set should include testID 2 only.
insert @Tests values
    (1, 'Table A'),
    (2, 'Table B'),
    (3, 'Table C');
insert @TestInputs values
    (1, 'X'),
    (2, 'X'),
    (2, 'Y'),
    (3, 'X'),
    (3, 'Y'),
    (3, 'Z');
insert @TestSearchParams values
    ('X'),
    ('Y');

declare @ParamCount int;
select @ParamCount = count(1) from @TestSearchParams;

select
    Tests.testID,
    Tests.[name]
from
    @Tests Tests
    inner join @TestInputs Inputs on Tests.testID = Inputs.testID
    left join @TestSearchParams Search on Inputs.inputsTableName = Search.inputsTableName
group by
    Tests.testID,
    Tests.[name]
having
    -- If a group includes any record where Search.inputsTableName is null, it means that
    -- the record in Tests has a TestInput that is not among the search parameters.
    sum(case when Search.inputsTableName is null then 1 else 0 end) = 0 and

    -- If a group includes fewer records than there are search parameters, it means that
    -- there exists some parameter that was not found among the Tests record's TestInputs.
    count(1) = @ParamCount;
</code>```

Body:
Given these tables:

Table: Test

Columns:

testID int PK

name nvarchar(128) UNIQUE NOT NULL

Table: [Test-Inputs]

Columns

inputsTableName nvarchar(128) UNIQUE PK

testID int PK FK

Temporary Table: ##TestSearchParams

Columns:

inputsTableName nvarchar(128) UNIQUE NOT NULL

I need to find Tests that have entries in Test-Inputs with inputsTableNames matching EXACTLY ALL of the entries in ##TestSearchParams; the resulting tests relationships must be exactly the ones listed in ##TestSearchParams.

Essentially I am finding tests with ONLY the given relationships, no more, no less. I am matching names with LIKE and wildcards, but that is a sidenote that I believe I can solve after the core logic is there for exact matching.

This is my current query:

Select *
From   Tests As B
Where  B.testID In (
                       Select ti
                       From   (
                                  Select   (
                                               Select Count(inputsTableName)
                                               From   [Test-Inputs]
                                               Where  [Test-Inputs].testID = B.testID
                                           ) - Count(Distinct i1) As delta,
                                           ti
                                  From     (
                                               Select [Test-Inputs].inputsTableName As i1,
                                                      [Test-Inputs].testID As ti
                                               From   ##TableSearchParams
                                               Join   [Test-Inputs]
                                                   On [Test-Inputs].inputsTableName Like ##TableSearchParams.inputsTableName
                                                      And B.testID = [Test-Inputs].testID
                                           ) As A
                                  Group By ti
                              ) As D
                       Where  D.delta = 0
                   );

The current problem is that his seems to retrieve Tests with a match to ANY of the entries in ##TableSearchParams. I have tried several other queries before this, to varying levels of success. I have working queries for find tests that match any of the parameters, all of the paramters, and none of the parameters -- I just cant get this query working.

Here are some sample table values:

Tests

1, Test1

2, Test2

3, Test3

[Test-Inputs]

Table1, 1

Table2, 2

Table1, 3

Table2, 3

TestSearchParams

Table1

Table2

The given values should only return (3, Test3)

Body:
Here's a possible solution that works by getting the complete set of TestInputs for each record in Tests, left-joining to the set of search parameters, and then aggregating the results by test and making two observations:

First, if a record from Tests includes a TestInput that is not among the search parameters, then that record must be excluded from the result set. We can check this by seeing if there is any case in which the left-join described above did not produce a match in the search parameters table.

Second, if a record from Tests satisfies the first condition, then we know that it doesn't have any superfluous TestInput records, so the only problem it could have is if there exists a search parameter that is not among its TestInputs. If that is so, then the number of records we've aggregated for that Test will be less than the total number of search parameters.

I have made the assumption here that you don't have Tests records with duplicate TestInputs, and that you likewise don't use duplicate search parameters. If those assumptions are not valid then this becomes more complicated. But if they are, then this ought to work:

declare @Tests table (testID int, [name] nvarchar(128));
declare @TestInputs table (testID int, inputsTableName nvarchar(128));
declare @TestSearchParams table (inputsTableName nvarchar(128));

-- Sample data.
--
-- testID 1 has only a subset of the search parameters.
-- testID 2 matches the search parameters exactly.
-- testID 3 has a superset of the search parameters.
--
-- Therefore the result set should include testID 2 only.
insert @Tests values
    (1, 'Table A'),
    (2, 'Table B'),
    (3, 'Table C');
insert @TestInputs values
    (1, 'X'),
    (2, 'X'),
    (2, 'Y'),
    (3, 'X'),
    (3, 'Y'),
    (3, 'Z');
insert @TestSearchParams values
    ('X'),
    ('Y');

declare @ParamCount int;
select @ParamCount = count(1) from @TestSearchParams;

select
    Tests.testID,
    Tests.[name]
from
    @Tests Tests
    inner join @TestInputs Inputs on Tests.testID = Inputs.testID
    left join @TestSearchParams Search on Inputs.inputsTableName = Search.inputsTableName
group by
    Tests.testID,
    Tests.[name]
having
    -- If a group includes any record where Search.inputsTableName is null, it means that
    -- the record in Tests has a TestInput that is not among the search parameters.
    sum(case when Search.inputsTableName is null then 1 else 0 end) = 0 and

    -- If a group includes fewer records than there are search parameters, it means that
    -- there exists some parameter that was not found among the Tests record's TestInputs.
    count(1) = @ParamCount;


来源: stackexchange

问:
Fetch child entities when finding by a normal field in Spring Data JPA
I am using Spring Data JpaRepository to find List of entities matching a particular field. Consider the following code snippet:

Entity:

```<code>@Entity
@Table(name = "master")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Master implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id", nullable = false)
    private Long Id;

@NotNull
    @Column(name = "user_id", nullable = false)
    private String userId;

@OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="id", referencedColumnName="id", insertable=false, updatable=false)
    private Details Details;
</code>```

Spring Data Custom JpaRepository:

```<code>public interface MasterRepository extends JpaRepository<Master,Long> {

    List<Master> findMasterByUserId(String userId);

}
</code>```

When i am using findBookingMasterByUserId repository method to find all records with specific user id, I am getting the List of Master entity but I am not getting the Details entity that has id as foreign key in it.

However, I get all the dependent entities when I use out of the box findAll method of JpaRepository but with custom findMasterByUserId repository method, child entities are not being fetched eagerly.

Any type of help would be highly appreciated. Thanks!

答:
You can use @EntityGraph in your repo to eagerly get associated data:

```<code>@EntityGraph(attributePaths = {"details"})
List<Master> findBookingMasterByUserId(String userId);
</code>```

P.S. Don't forget to change 'Details' field to details;

ContentLicense: CC BY-SA 3.0

Body:
I am using Spring Data JpaRepository to find List of entities matching a particular field. Consider the following code snippet:

Entity:

@Entity
@Table(name = "master")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Master implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    @Column(name = "id", nullable = false)
    private Long Id;

@NotNull
    @Column(name = "user_id", nullable = false)
    private String userId;

@OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="id", referencedColumnName="id", insertable=false, updatable=false)
    private Details Details;

Spring Data Custom JpaRepository:

public interface MasterRepository extends JpaRepository<Master,Long> {

    List<Master> findMasterByUserId(String userId);

}

When i am using findBookingMasterByUserId repository method to find all records with specific user id, I am getting the List of Master entity but I am not getting the Details entity that has id as foreign key in it.

However, I get all the dependent entities when I use out of the box findAll method of JpaRepository but with custom findMasterByUserId repository method, child entities are not being fetched eagerly.

Any type of help would be highly appreciated. Thanks!

Body:
You can use @EntityGraph in your repo to eagerly get associated data:

@EntityGraph(attributePaths = {"details"})
List<Master> findBookingMasterByUserId(String userId);

P.S. Don't forget to change 'Details' field to details;


问:
Why Flow still complains about null values for document.getElementById
Why even with an IF check, Flow still complains about a possibly null value

```<code>if(document && document.getElementById("myID") && document.getElementById("myID").offsetWidth){
 console.log(document.getElementById("myID").offsetWidth);
}
</code>```

Gives this error

```<code>   ^ property `offsetWidth`. Property cannot be accessed on possibly null value
</code>```

答:
Flow has no way to know that the success of first call to getElementById means that the later ones will also succeed. For all it knows, reading the offsetWidth property could cause getElementById to start returning null the next time it is called.

You'll need to store the value, e.g.

```<code>const myIdEl = document && document.getElementById("myID");

if(myIdEl && myIdEl.offsetWidth) {
   console.log(myIdEl.offsetWidth);
}
</code>```

this way there is no way for myIdEl to become null after it has been referenced.

Body:
Why even with an IF check, Flow still complains about a possibly null value

if(document && document.getElementById("myID") && document.getElementById("myID").offsetWidth){
 console.log(document.getElementById("myID").offsetWidth);
}

Gives this error

   ^ property `offsetWidth`. Property cannot be accessed on possibly null value

Body:
Flow has no way to know that the success of first call to getElementById means that the later ones will also succeed. For all it knows, reading the offsetWidth property could cause getElementById to start returning null the next time it is called.

You'll need to store the value, e.g.

const myIdEl = document && document.getElementById("myID");

if(myIdEl && myIdEl.offsetWidth) {
   console.log(myIdEl.offsetWidth);
}

this way there is no way for myIdEl to become null after it has been referenced.


问:
Error : Database is locked in sqlite3
I'm working on a python script where I'm connecting database of multiple server and executing the same query on all.
Now, the issue is the database on some servers are locked, so need to understand how to unlock the same or if we can use timeout to skip few of the servers and run the query uninterrupted on remaining servers.</p>

答:
sqlite3.connect() has a timeout parameter (in seconds).

But I recommend to change database to a client-server solution. SQLite is ok to handle large database for single program, but it's not very good at handling concurrent access from multiple programs. MySQL or Postgres will suite you much better.

Title: Error : Database is locked in sqlite3


问:
What does "Your bundle is locked to addressable " mean?
I'm trying to bundle exec jekyll serve

but I get this error:

```<code>Your bundle is locked to addressable (2.5.0), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of addressable (2.5.0) has removed it. You'll need to update your bundle to a different version of addressable (2.5.0) that hasn't been removed in order to install.
Run `bundle install` to install missing gems.
</code>```

bundle install gives me

```<code>Warning: the running version of Bundler (1.13.6) is older than the version that created the lockfile (1.13.7). We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.
</code>```

This works, but it gives me the wrong version I think:

```<code>Successfully installed bundler-1.15.1
Parsing documentation for bundler-1.15.1
Done installing documentation for bundler after 4 seconds
1 gem installed
</code>```

Where is the bundle locked to adressable and what does this mean? I checked my gemfile, it's nothing in there. Can I unlock it? I'm trying to run a boilerplate for jekyll and installed ruby using brew.

答:
The "Your bundle is locked to addressable..." error just means that you have a version of addressable specified in your Gemfile.lock, but it's not installed on your machine (yet). Running bundle install fixes that.

As such, if you run the following, your app should run just fine:

```<code>$ bundle install
$ bundle exec jekyll serve
</code>```

The "Bundler (1.13.6) is older..." warning is just an FYI from the good people at Bundler, encouraging you to upgrade. You can safely ignore it without it affecting your app (but it's good practice to stay up-to-date).

Body:
I'm trying to bundle exec jekyll serve

but I get this error:

Your bundle is locked to addressable (2.5.0), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of addressable (2.5.0) has removed it. You'll need to update your bundle to a different version of addressable (2.5.0) that hasn't been removed in order to install.
Run `bundle install` to install missing gems.

bundle install gives me

Warning: the running version of Bundler (1.13.6) is older than the version that created the lockfile (1.13.7). We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.

This works, but it gives me the wrong version I think:

Successfully installed bundler-1.15.1
Parsing documentation for bundler-1.15.1
Done installing documentation for bundler after 4 seconds
1 gem installed

Where is the bundle locked to adressable and what does this mean? I checked my gemfile, it's nothing in there. Can I unlock it? I'm trying to run a boilerplate for jekyll and installed ruby using brew.

Body:
The "Your bundle is locked to addressable..." error just means that you have a version of addressable specified in your Gemfile.lock, but it's not installed on your machine (yet). Running bundle install fixes that.

As such, if you run the following, your app should run just fine:

$ bundle install
$ bundle exec jekyll serve

The "Bundler (1.13.6) is older..." warning is just an FYI from the good people at Bundler, encouraging you to upgrade. You can safely ignore it without it affecting your app (but it's good practice to stay up-to-date).


问:
Simple Injector instance is requested outside the context of an active (async scope) scope
I'm trying to inject my IAuthorizationRepository into my VB Web App using SimpleInjector.

```<code>Public Class IdentityPackage
    Implements IPackage
    Public Sub RegisterServices(container As Container) Implements IPackage.RegisterServices
        container.Register(Of IUserStore(Of User, Integer), UserStore)(Lifestyle.Scoped)
        container.Register(Of IAuthorizationRepository, AuthorizationRepository)(Lifestyle.Scoped)
        container.Register(Of ISession, Session)()
    End Sub
End Class
</code>```

Here's my startup.

```<code>Public Partial Class Startup
    Public Sub Configuration(app As IAppBuilder)
        Dim container = ConfigureSimpleInjector(app)
        Dim config = New HttpConfiguration() With {
            .DependencyResolver = New SimpleInjectorWebApiDependencyResolver(container)
        }

        ConfigureOAuth(app, container)

        WebApiConfig.Register(config)
        app.UseCors(CorsOptions.AllowAll)
        app.UseWebApi(config)
    End Sub
End Class
</code>```

And here's my ConfigureOAuth.

```<code>Public Sub ConfigureOAuth(app As IAppBuilder, container As Container)
    Dim authRepositoryFactory As Func(Of IAuthorizationRepository) = container.GetInstance(Of IAuthorizationRepository)

    Dim authorizationOptions = New OAuthAuthorizationServerOptions() With {
        .AllowInsecureHttp = True,
        .TokenEndpointPath = New PathString("/api/token"),
        .AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
        .Provider = New AuthorizationServerProvider(authRepositoryFactory)
    }

    ' Token Generation
    app.UseOAuthAuthorizationServer(authorizationOptions)
    app.UseOAuthBearerAuthentication(New OAuthBearerAuthenticationOptions())
End Sub
</code>```

When it gets to the first line under ConfigureOAuth, it throws the error The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.

The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem. This makes me feel like the issue lies in how VB handles the code, as opposed to C#, but I don't see how that could be the case with this example. Can anyone tell me what's going wrong?

The following is my stack trace:

```<code>[ActivationException: The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.]
   SimpleInjector.Scope.GetScopelessInstance(ScopedRegistration`1 registration) +168
   SimpleInjector.Scope.GetInstance(ScopedRegistration`1 registration, Scope scope) +52
   SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope) +158
   lambda_method(Closure ) +223
   SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance() +32
   SimpleInjector.InstanceProducer.GetInstance() +235
   SimpleInjector.Container.GetInstanceForRootType() +154
   SimpleInjector.Container.GetInstance() +146
   ClientWebAppVB.Api.Startup.ConfigureOAuth(IAppBuilder app, Container container) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\App_Start\OAuthConfig.vb:10
   ClientWebAppVB.Api.Startup.Configuration(IAppBuilder app) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\Startup.vb:15

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +160
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
   Owin.Loader.<>c__DisplayClass12.<MakeDelegate>b__b(IAppBuilder builder) +66
   Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +123
   Microsoft.Owin.Host.SystemWeb.<>c__DisplayClass2.<InitializeBlueprint>b__0(IAppBuilder builder) +71
   Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +462
   Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +536
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10044576
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254
</code>```

答:
The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem

Well this is actually not the equivalent of the c# version. And unless you changed Option Explicit and Option Strict settings I'm pretty sure the code you show does not even compile. Or in your real code you omitted the As Func(Of IAuthorizationRepository) clause.

In c# this two lines are 2 totally different things:

// create a delegate
Func<IAuthorizationRepository> authRepositoryFactory =
                        container.GetInstance<IAuthorizationRepository>;
// and directly call a delegate or method
Func<IAuthorizationRepository> authRepositoryFactory =
                        container.GetInstance<IAuthorizationRepository>();
```

<p>And here the second line does not compile. This line returns <code>IAuthorizationRepository</code> and therefore is not assignable to <code>Func<IAuthorizationRepository></code>.</p>

<p>In Vb.Net however the following lines are exactly the same. The braces of a method call are totally optional. </p>

<pre class="lang-vb prettyprint-override"><code>' Directly call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)
' And directy call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)()
</code>```

If you hover over authRepositoryFactory you'll see that the inferred type is IAuthorizationRepository for both lines.

To create a delegate instead of directly invoking it in VB you need to use the AddressOf Operator

Dim authRepositoryFactory = New Func(Of IAuthorizationRepository)(
              AddressOf container.GetInstance(Of IAuthorizationRepository))

'or
Dim authRepositoryFactory As Func(Of IAuthorizationRepository) =
              AddressOf container.GetInstance(Of IAuthorizationRepository)
```

If you would hover over authRepositoryFactory you'll see this is actually a Func (Of IAuthorizationRepository)

Body:
I'm trying to inject my IAuthorizationRepository into my VB Web App using SimpleInjector.

Public Class IdentityPackage
    Implements IPackage
    Public Sub RegisterServices(container As Container) Implements IPackage.RegisterServices
        container.Register(Of IUserStore(Of User, Integer), UserStore)(Lifestyle.Scoped)
        container.Register(Of IAuthorizationRepository, AuthorizationRepository)(Lifestyle.Scoped)
        container.Register(Of ISession, Session)()
    End Sub
End Class

Here's my startup.

Public Partial Class Startup
    Public Sub Configuration(app As IAppBuilder)
        Dim container = ConfigureSimpleInjector(app)
        Dim config = New HttpConfiguration() With {
            .DependencyResolver = New SimpleInjectorWebApiDependencyResolver(container)
        }

        ConfigureOAuth(app, container)

        WebApiConfig.Register(config)
        app.UseCors(CorsOptions.AllowAll)
        app.UseWebApi(config)
    End Sub
End Class

And here's my ConfigureOAuth.

Public Sub ConfigureOAuth(app As IAppBuilder, container As Container)
    Dim authRepositoryFactory As Func(Of IAuthorizationRepository) = container.GetInstance(Of IAuthorizationRepository)

    Dim authorizationOptions = New OAuthAuthorizationServerOptions() With {
        .AllowInsecureHttp = True,
        .TokenEndpointPath = New PathString("/api/token"),
        .AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
        .Provider = New AuthorizationServerProvider(authRepositoryFactory)
    }

    ' Token Generation
    app.UseOAuthAuthorizationServer(authorizationOptions)
    app.UseOAuthBearerAuthentication(New OAuthBearerAuthenticationOptions())
End Sub

When it gets to the first line under ConfigureOAuth, it throws the error The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.

The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem. This makes me feel like the issue lies in how VB handles the code, as opposed to C#, but I don't see how that could be the case with this example. Can anyone tell me what's going wrong?

The following is my stack trace:

[ActivationException: The AuthorizationRepository is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.]
   SimpleInjector.Scope.GetScopelessInstance(ScopedRegistration`1 registration) +168
   SimpleInjector.Scope.GetInstance(ScopedRegistration`1 registration, Scope scope) +52
   SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope) +158
   lambda_method(Closure ) +223
   SimpleInjector.InstanceProducer.BuildAndReplaceInstanceCreatorAndCreateFirstInstance() +32
   SimpleInjector.InstanceProducer.GetInstance() +235
   SimpleInjector.Container.GetInstanceForRootType() +154
   SimpleInjector.Container.GetInstance() +146
   ClientWebAppVB.Api.Startup.ConfigureOAuth(IAppBuilder app, Container container) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\App_Start\OAuthConfig.vb:10
   ClientWebAppVB.Api.Startup.Configuration(IAppBuilder app) in C:\Projects\TEST\ClientWebAppVB\ClientWebAppVB.Api\Startup.vb:15

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +160
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
   Owin.Loader.<>c__DisplayClass12.<MakeDelegate>b__b(IAppBuilder builder) +66
   Owin.Loader.<>c__DisplayClass1.<LoadImplementation>b__0(IAppBuilder builder) +123
   Microsoft.Owin.Host.SystemWeb.<>c__DisplayClass2.<InitializeBlueprint>b__0(IAppBuilder builder) +71
   Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +462
   Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
   System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
   Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +536
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10044576
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Body:
The strange thing is that I'm converting an existing, and fully functional C# project into VB, and this is the VB equivalent of the codebase in C#, but the C# code does not have this problem

Well this is actually not the equivalent of the c# version. And unless you changed Option Explicit and Option Strict settings I'm pretty sure the code you show does not even compile. Or in your real code you omitted the As Func(Of IAuthorizationRepository) clause.

In c# this two lines are 2 totally different things:

// create a delegate
Func<IAuthorizationRepository> authRepositoryFactory =
                        container.GetInstance<IAuthorizationRepository>;
// and directly call a delegate or method
Func<IAuthorizationRepository> authRepositoryFactory =
                        container.GetInstance<IAuthorizationRepository>();

And here the second line does not compile. This line returns IAuthorizationRepository and therefore is not assignable to Func<IAuthorizationRepository>.

In Vb.Net however the following lines are exactly the same. The braces of a method call are totally optional.

' Directly call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)
' And directy call the method
Dim authRepositoryFactory = container.GetInstance(Of IAuthorizationRepository)()

If you hover over authRepositoryFactory you'll see that the inferred type is IAuthorizationRepository for both lines.

To create a delegate instead of directly invoking it in VB you need to use the AddressOf Operator

Dim authRepositoryFactory = New Func(Of IAuthorizationRepository)(
              AddressOf container.GetInstance(Of IAuthorizationRepository))

'or
Dim authRepositoryFactory As Func(Of IAuthorizationRepository) =
              AddressOf container.GetInstance(Of IAuthorizationRepository)

If you would hover over authRepositoryFactory you'll see this is actually a Func (Of IAuthorizationRepository)


问:
Pattern search over various bitstrings
I have the following problem:
Given 15 bit strings of 1024 bit each, what is the best way to find patterns in different strings on the same position? How the pattern looks like doesn't matter to me (length > 1 of course), I just want to find parts (as long as possible) where at least two of the strings match.
An example:

10010...

00011...

00101...

Here i would like to get 001 from the first two strings (position 2 to 4, frequency 2 would also be great...) and 00 from the second and third string (position 1 to 2).

I hope, the problem is clear now... Anybody an idea?
Thanks!

答:
I would try to solve your problem in a two-step approach. Since you only have 15 bitstrings, it should be sufficient to compare all pairs of bitstrings (105 comparisons á 16 QWORDS should be doable)

For now, I'll also consider patterns of length 1 valid, we'll see how to get rid of this later. Since you don't mention a programming language, I'll try to keep it general and use C syntax for bit operations. Let a and b be two bitstrings.

Identify the possible patterns: The ith bit is part of a pattern if and only if a[i] == b[i]. We can mark these bits efficiently by computing the bitwise xor (which corresponds to !=) and negating: patterns = ~(a ^ b)

Identify longest pattern: After the transformation above has been computed, common patterns between a and b are consecutive 1s in pattern. Finding such long patterns can e.g. be solved by repeated shifting and AND operations, see this question for details. If you expect really long sequences, I would try to use some dedicated instructions to find non-pattern bits, I'll extend the answer if necessary.

If this is really high-throughput code, you could try doing multiple comparisons simultaneously, i.e. using SIMD instructions, but that's a topic for another question.

Title: Pattern search over various bitstrings


问:
elasticsearch not receiving from localhost
I run logstash(192.168.56.100) and elasticsearch(192.168.56.100) on same host, but elasticsearch just create index and not receiving data. And I try run logstash(192.168.56.101) on different host, and  elasticsearch(192.168.56.100) can receiving data. this my elasticsearch and logstash config

example data : 12345~78904

```<code>input {
  file {
    path => "/tmp/tmp.log"
  }
}

filter {
    grok {
     match => ["message" , '%{INT:shopID}~%{INT:userID}']
   }
}

output {
  elasticsearch {
    hosts => "127.0.0.1:9200"
    index => "shop"
  }
}

# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: 0.0.0.0
#
# Set a custom port for HTTP:
#
http.port: 9200
</code>```

elasticsearch version 5.1.1 -
logstash version 2.4.0

答: Do you have any errors in logstash log? Try instead 0.0.0.0 set in elasticsearch.yml _local_ or 127.0.0.1. https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-network.html#network-interface-values

Body:
I run logstash(192.168.56.100) and elasticsearch(192.168.56.100) on same host, but elasticsearch just create index and not receiving data. And I try run logstash(192.168.56.101) on different host, and  elasticsearch(192.168.56.100) can receiving data. this my elasticsearch and logstash config

example data : 12345~78904

input {
  file {
    path => "/tmp/tmp.log"
  }
}

filter {
    grok {
     match => ["message" , '%{INT:shopID}~%{INT:userID}']
   }
}

output {
  elasticsearch {
    hosts => "127.0.0.1:9200"
    index => "shop"
  }
}

# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: 0.0.0.0
#
# Set a custom port for HTTP:
#
http.port: 9200

elasticsearch version 5.1.1 -
logstash version 2.4.0


问:
C# Mysql move row to another table and get max value of cell
I have a method that moves a row from one table to another. That itself works fine. What I am trying to do now is to select the highest value of a cell inside the table Callbacks. This is what I have tried:

```<code>public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            string query = "BEGIN;  select max(UniqueID) from Callbacks;     INSERT INTO Callbacks select * from " + Table + " where UniqueID = " + UniqueID + "; DELETE FROM " + Table + " where UniqueID = " + UniqueID + "; COMMIT;";
            cn.Open();
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();

                Console.WriteLine("query" + Convert.ToInt32(cmd.ExecuteScalar()));
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
</code>```

Thanks in advance

答:
Have you tried just changing your code a bit?

```<code>public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            cn.Open();

            string query = "select max(UniqueID) from Callbacks;";
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                // Notice I removed the command text, you are already setting the command text in the constructor for the MySqlCommand
                int UID = Int32.Parse(cmd.ExecuteScalar());

                Console.WriteLine("query" + UID);
            }

            query = "BEGIN;  INSERT INTO Callbacks select * from " + Table + " where UniqueID = ?UniqueID; DELETE FROM " + Table + " where UniqueID = ?UniqueID; COMMIT;";
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                // Use parameters to sanitize input. There are very rare circumstances where you would want to do a direct concatenation to a query as its susceptible to sql injection
                cmd.Parameters.Add(new MySqlParameter("UniqueID", UniqueID))
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}
</code>```

Also, I would highly recommend you read up on SQL injections. The way you are building your queries are scary depending on where "Table" and "UniqueID" are coming from. Seeing the Table variable cant be parameterized, you will need to be extra careful on where that value is being populated from.
Check out https://stackoverflow.com/a/652999/5947241 & https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html

Body:
I have a method that moves a row from one table to another. That itself works fine. What I am trying to do now is to select the highest value of a cell inside the table Callbacks. This is what I have tried:

public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            string query = "BEGIN;  select max(UniqueID) from Callbacks;     INSERT INTO Callbacks select * from " + Table + " where UniqueID = " + UniqueID + "; DELETE FROM " + Table + " where UniqueID = " + UniqueID + "; COMMIT;";
            cn.Open();
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                cmd.CommandText = query;
                cmd.ExecuteNonQuery();

                Console.WriteLine("query" + Convert.ToInt32(cmd.ExecuteScalar()));
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Thanks in advance

Body:
Have you tried just changing your code a bit?

public static void MoveLead(RadGridView Gridview, RadDropDownList SegmentDropdown, string UniqueID)
{
    try
    {
        string Table = SegmentDropdown.Text;
        using (MySqlConnection cn = new MySqlConnection(Varribles.ConString))
        {
            cn.Open();

            string query = "select max(UniqueID) from Callbacks;";
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                // Notice I removed the command text, you are already setting the command text in the constructor for the MySqlCommand
                int UID = Int32.Parse(cmd.ExecuteScalar());

                Console.WriteLine("query" + UID);
            }

            query = "BEGIN;  INSERT INTO Callbacks select * from " + Table + " where UniqueID = ?UniqueID; DELETE FROM " + Table + " where UniqueID = ?UniqueID; COMMIT;";
            using (MySqlCommand cmd = new MySqlCommand(query, cn))
            {
                // Use parameters to sanitize input. There are very rare circumstances where you would want to do a direct concatenation to a query as its susceptible to sql injection
                cmd.Parameters.Add(new MySqlParameter("UniqueID", UniqueID))
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Also, I would highly recommend you read up on SQL injections. The way you are building your queries are scary depending on where "Table" and "UniqueID" are coming from. Seeing the Table variable cant be parameterized, you will need to be extra careful on where that value is being populated from.
Check out https://stackoverflow.com/a/652999/5947241 & https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html


问:
Can dagger provide different implementations of the interface, depending on requested type?
I just started to learn Dagger and I wonder: Can it provide different implementations of the interface, depending on the request?
For example, I have an interface Api and I have 2 implementations of this interface - TwitterApi and FacebookApi. Can I write something like the following?

```<code>@Provides
Api provideApi(ApiType type) {
    switch (type){
        case TWITTER_API:
            return new TwitterApi();
        case FACEBOOK_API:
            return new FacebookApi();
    }
}
</code>```

Maybe @Named() can help somehow?

答:
This really depends on what you are trying to accomplish. You have 2 basic setups, whether you want to access your different implementations at once, or just want to supply one.

Access them at the same time / within the same scope

This is where you want to use a @Qualifier, e.g. @Named. It lets you define 2 qualified objects of the same type, so you could request / use both at the same time within the same module.

Here you just put a qualifier on both your implementations, and can provide & request both at the same time.

```<code>@Binds
@Qualifier("twitter")
Api provideApi(TwitterApi api);
</code>```

And request with

```<code>@Inject @Qualifier("twitter") Api api;
</code>```

Use a single one within a scope

In case that you have some ApiDependentThing that takes one of your Api implementations and you want to either provide TwitterApi or FacebookApi, you can just bind one of the implementations to your component. You can achieve this by using a @Component.Builder, or @Binds in a module, or some other way.

With this approach you would not use a qualifier, as you will only have one Api on your graph that will be used within your component.

E.g. just bind one instance in your builder.

```<code>@Component
interface ApiComponent {
  Api api();

  @Component.Builder
  interface Builder {
    @BindsInstance Builder api(Api api);
    ApiComponent build();
  }
}
</code>```

Body:
I just started to learn Dagger and I wonder: Can it provide different implementations of the interface, depending on the request?
For example, I have an interface Api and I have 2 implementations of this interface - TwitterApi and FacebookApi. Can I write something like the following?

@Provides
Api provideApi(ApiType type) {
    switch (type){
        case TWITTER_API:
            return new TwitterApi();
        case FACEBOOK_API:
            return new FacebookApi();
    }
}

Maybe @Named() can help somehow?

Body:
This really depends on what you are trying to accomplish. You have 2 basic setups, whether you want to access your different implementations at once, or just want to supply one.

Access them at the same time / within the same scope

This is where you want to use a @Qualifier, e.g. @Named. It lets you define 2 qualified objects of the same type, so you could request / use both at the same time within the same module.

Here you just put a qualifier on both your implementations, and can provide & request both at the same time.

@Binds
@Qualifier("twitter")
Api provideApi(TwitterApi api);

And request with

@Inject @Qualifier("twitter") Api api;

Use a single one within a scope

In case that you have some ApiDependentThing that takes one of your Api implementations and you want to either provide TwitterApi or FacebookApi, you can just bind one of the implementations to your component. You can achieve this by using a @Component.Builder, or @Binds in a module, or some other way.

With this approach you would not use a qualifier, as you will only have one Api on your graph that will be used within your component.

E.g. just bind one instance in your builder.

@Component
interface ApiComponent {
  Api api();

  @Component.Builder
  interface Builder {
    @BindsInstance Builder api(Api api);
    ApiComponent build();
  }
}


问:
How to read BufferedReader faster
I want to optimize this code:

```<code>InputStream is = rp.getEntity().getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String text = "";
String aux = "";

while ((aux = reader.readLine()) != null) {
        text += aux;
      }
</code>```

The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above.
I need to spend as little time as possible.
Thank you

答:
I wrote a simple function to do this using StringBuilder and While loop with catching IOException inside.</p>

```<code>public String getString(BufferedReader bufferedReader) {
    StringBuilder stringBuilder = new StringBuilder();
    String line = null;

    do {
        try {
            if ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (line != null);

    return stringBuilder.toString();
}
</code>```

Title: How to read BufferedReader faster

Body:
I want to optimize this code:

InputStream is = rp.getEntity().getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String text = "";
String aux = "";

while ((aux = reader.readLine()) != null) {
        text += aux;
      }

The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above.
I need to spend as little time as possible.
Thank you

Body:
I wrote a simple function to do this using StringBuilder and While loop with catching IOException inside.

public String getString(BufferedReader bufferedReader) {
    StringBuilder stringBuilder = new StringBuilder();
    String line = null;

    do {
        try {
            if ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (line != null);

    return stringBuilder.toString();
}


问:
Matching a result in c#
I have the following string

```<code>background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')
</code>```

and I just want to get the image URL.

My code is:

```<code>image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, @"'([^']*)");
</code>```

Match.Success returns nothing, so I can not get the image URL.

Is there something missing? This used to work but not now.

答:
No need for a regex, just

Split the string with ' substring

Find the element starting with http

Return the first found item.

C# demo:

```<code>var s = "background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')";
var res = s.Split(new[] {"'"}, StringSplitOptions.None)
    .Where(v => v.StartsWith("http"))
    .FirstOrDefault();
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg
</code>```

If you need to use a regex, use the standard regex to match a string between two strings, start(.*?)end where (.*?) captures into Group 1 any 0 or more chars other than a newline, as few as possible as the *? quantifier is lazy:

```<code>var s = "background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')";
var res = Regex.Match(s, @"'(.*?)'").Groups[1].Value ?? string.Empty;
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg
</code>```

See another C# demo

Title: Matching a result in c#

Body:
I have the following string

background-image: url('https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg')

and I just want to get the image URL.

My code is:

image = image.Replace(@"'", "\"");
Match match = Regex.Match(image, @"'([^']*)");

Match.Success returns nothing, so I can not get the image URL.

Is there something missing? This used to work but not now.

Body:
No need for a regex, just

Split the string with &#39; substring

Find the element starting with http

Return the first found item.

C# demo:

var s = "background-image: url(&#39;https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg&#39;)";
var res = s.Split(new[] {"&#39;"}, StringSplitOptions.None)
    .Where(v => v.StartsWith("http"))
    .FirstOrDefault();
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg

If you need to use a regex, use the standard regex to match a string between two strings, start(.*?)end where (.*?) captures into Group 1 any 0 or more chars other than a newline, as few as possible as the *? quantifier is lazy:

var s = "background-image: url(&#39;https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg&#39;)";
var res = Regex.Match(s, @"&#39;(.*?)&#39;").Groups[1].Value ?? string.Empty;
Console.WriteLine(res);
// => https://s3-eu-west-1.amazonaws.com/files.domain.com/uploads/image/file/168726/carousel_IMG_6455.jpg

See another C# demo


问:
Find pair of numbers inside an array is it possible to solve with bitwise operators
Is it possible to solve this problem with bitwise operators?
Given an array of integers, find two same numbers and return one of them, for example in array [7,3,5,6,7] answer is 7. I'm trying to understand when a problem can be solved with bitwise. So far I understand that if I multiply or divide by 2 I would want to use a left shift to multiply by 2, right shift to divide by 2 and if I want to cancel out matching numbers use XOR. I was thinking I could exit a loop on the first matching pair but I now don't think I can. I've tried this.

```<code>function findIt(arr) {
  var dog = 0;
  for (var i = 0; i < arr.length; i++) {
    if ((dog ^= arr[i]) == 0) {
      dog =arr[i];
      break;
    }
  }
  return dog;
}
</code>```

It's not homework, i'm just curiously learning about bitwise operations in javascript. Below solved vanilla solution.

function findIt(arr) {
  var obj = {};
  for (var i = 0; i < arr.length; i++) {
    if (obj[arr[i]] === 1) {
      return arr[i];
    } else {
      obj[arr[i]] = 1;
    }
  }
  return 'no pairs found'
}

console.log(findIt([7,3,5,6,7))```

答:
As @Barmar already suggested in comments you can use nested for loops for solving the problem.

Something like this should do:

```<code>function findIt(arr) {
  var cmpValue, flag = 0;
  for (var i = 0; i < arr.length; i++) {
    cmpValue = arr[i];
    for(var j = i + 1 ; j < arr.length ; j++){
        if(cmpValue^arr[i] == 0){
            flag=1;
            break;
        }
    }
    if(flag == 1){
        break;
    }
  }
  if(flag == 1){
    return cmpValue;
  }
  else{
    return 'no pairs found'
  }

}

console.log(findIt([7,3,5,6,7))
> 7
console.log(findIt([3,3,5,6,7))
> 3
</code>```

Body:
Is it possible to solve this problem with bitwise operators?
Given an array of integers, find two same numbers and return one of them, for example in array [7,3,5,6,7] answer is 7. I'm trying to understand when a problem can be solved with bitwise. So far I understand that if I multiply or divide by 2 I would want to use a left shift to multiply by 2, right shift to divide by 2 and if I want to cancel out matching numbers use XOR. I was thinking I could exit a loop on the first matching pair but I now don't think I can. I've tried this.

function findIt(arr) {
  var dog = 0;
  for (var i = 0; i < arr.length; i++) {
    if ((dog ^= arr[i]) == 0) {
      dog =arr[i];
      break;
    }
  }
  return dog;
}

It's not homework, i'm just curiously learning about bitwise operations in javascript. Below solved vanilla solution.

function findIt(arr) {
  var obj = {};
  for (var i = 0; i < arr.length; i++) {
    if (obj[arr[i]] === 1) {
      return arr[i];
    } else {
      obj[arr[i]] = 1;
    }
  }
  return 'no pairs found'
}

console.log(findIt([7,3,5,6,7))

Body:
As @Barmar already suggested in comments you can use nested for loops for solving the problem.

Something like this should do:

function findIt(arr) {
  var cmpValue, flag = 0;
  for (var i = 0; i < arr.length; i++) {
    cmpValue = arr[i];
    for(var j = i + 1 ; j < arr.length ; j++){
        if(cmpValue^arr[i] == 0){
            flag=1;
            break;
        }
    }
    if(flag == 1){
        break;
    }
  }
  if(flag == 1){
    return cmpValue;
  }
  else{
    return 'no pairs found'
  }

}

console.log(findIt([7,3,5,6,7))
> 7
console.log(findIt([3,3,5,6,7))
> 3


问:
print values of all items in array JAVASCRIPT / d3
Sorry if it's a bit rookie:

I have a csv file turned into array with property-value duos.

```<code>console.log(data);
console.log(data[0].property_name);
console.log(data.property_name);
</code>```

first and second line work perfectly
the third line doesn't work (returns undefined)

答:
After getting your data from your csv using d3 you will get an object prop/val. You can use Object.values to get the values from the props.

var csv = {
  city: "seattle",
  state: "WA",
  population: "652405",
  landarea: "83.9"
};
console.log(Object.values(csv));```
</div>
</div>
</p>

<p>And for an array of Objects </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var csv = [{
  city: "seattle",
  state: "WA",
  population: "652405",
  landarea: "83.9"
}, {
  city: "moSat",
  state: "moWA",
  population: "mo652405",
  landarea: "mo83.9"
}];

var val = csv.map(x => Object.values(x));
console.log(val);</code>```

Body:
Sorry if it's a bit rookie:

I have a csv file turned into array with property-value duos.

console.log(data);
console.log(data[0].property_name);
console.log(data.property_name);

first and second line work perfectly
the third line doesn't work (returns undefined)

Body:
After getting your data from your csv using d3 you will get an object prop/val. You can use Object.values to get the values from the props.

var csv = {
  city: "seattle",
  state: "WA",
  population: "652405",
  landarea: "83.9"
};
console.log(Object.values(csv));

And for an array of Objects

var csv = [{
  city: "seattle",
  state: "WA",
  population: "652405",
  landarea: "83.9"
}, {
  city: "moSat",
  state: "moWA",
  population: "mo652405",
  landarea: "mo83.9"
}];

var val = csv.map(x => Object.values(x));
console.log(val);


问:
jQuery: Get value of url in load() function
I'm using a library which has already defined an onclick event handler on a hyperlink eg:

```<code><a onclick="$('#myDiv').load('/?__=634285190817664832&sort=Id&sortdir=ASC&page=1 #myDiv');" href="#">1</a>
</code>```

How can I get the value of the 'url' parameter?

答:
Updated Answer

...after tobyodavies pointed out (in the nicest of ways) that I was being thick. If you explicitly retrieve the attribute, rather than the reflected property, we'll get back the string from the DOM, not a function, and so don't have to worry about function decompilation (see notes below). The remainder of the below is a bit paranoid (because I originally was working from function decompilation), but still:

```<code>jQuery(function($) {

  var link, onclick, url, index;

  link = $('#theLink')[0];
  // IMPORTANT: Getting the *attribute* here, not the reflected property.
  // jQuery's `attr` function will give you the property, so go direct.
  onclick = link.getAttribute("onclick");
  display("onclick = " + onclick);
  index = onclick.indexOf("load('");
  if (index < 0) {
    url = "(unknown)";
  }
  else {
    url = onclick.substring(index + 6);
    index = url.indexOf("');");
    if (index > 0) {
      url = url.substring(0, index);
    }
  }
  display("url = " + url);

  function display(msg) {
    $("<p/>").html(msg).appendTo(document.body);
  }
});
</code>```

Live example

<s>

Original Answer

Note that here there be dragons. The value of the onclick reflected property by the time you're accessing it in the DOM is a function object on most browsers, and so you'll have to use Function#toString, which has never been standardized and some mobile browsers are known to just return "[object Function]". Most desktop browsers return a decompiled version of the event handler, but that can change at any time.

But now you're aware of the dragons, you can get it that way. Here's a somewhat paranoid approach:

```<code>jQuery(function($) {

  var link, onclick, url, index;

  link = $('#theLink')[0];
  onclick = "" + link.onclick;
  display("onclick = " + onclick);
  index = onclick.indexOf("load('");
  if (index < 0) {
    url = "(unknown)";
  }
  else {
    url = onclick.substring(index + 6);
    index = url.indexOf("');");
    if (index > 0) {
      url = url.substring(0, index);
    }
  }
  display("url = " + url);

  function display(msg) {
    $("<p/>").html(msg).appendTo(document.body);
  }
});
</code>```

Live example
</s>

ContentLicense: CC BY-SA 2.5

Body:
I'm using a library which has already defined an onclick event handler on a hyperlink eg:

1

How can I get the value of the 'url' parameter?

Body:
Updated Answer

...after tobyodavies pointed out (in the nicest of ways) that I was being thick. If you explicitly retrieve the attribute, rather than the reflected property, we'll get back the string from the DOM, not a function, and so don't have to worry about function decompilation (see notes below). The remainder of the below is a bit paranoid (because I originally was working from function decompilation), but still:

jQuery(function($) {

  var link, onclick, url, index;

  link = $('#theLink')[0];
  // IMPORTANT: Getting the *attribute* here, not the reflected property.
  // jQuery's `attr` function will give you the property, so go direct.
  onclick = link.getAttribute("onclick");
  display("onclick = " + onclick);
  index = onclick.indexOf("load('");
  if (index < 0) {
    url = "(unknown)";
  }
  else {
    url = onclick.substring(index + 6);
    index = url.indexOf("');");
    if (index > 0) {
      url = url.substring(0, index);
    }
  }
  display("url = " + url);

  function display(msg) {
    $("<p/>").html(msg).appendTo(document.body);
  }
});

Live example

<s>

Original Answer

Note that here there be dragons. The value of the onclick reflected property by the time you're accessing it in the DOM is a function object on most browsers, and so you'll have to use Function#toString, which has never been standardized and some mobile browsers are known to just return "[object Function]". Most desktop browsers return a decompiled version of the event handler, but that can change at any time.

But now you're aware of the dragons, you can get it that way. Here's a somewhat paranoid approach:

jQuery(function($) {

  var link, onclick, url, index;

  link = $('#theLink')[0];
  onclick = "" + link.onclick;
  display("onclick = " + onclick);
  index = onclick.indexOf("load('");
  if (index < 0) {
    url = "(unknown)";
  }
  else {
    url = onclick.substring(index + 6);
    index = url.indexOf("');");
    if (index > 0) {
      url = url.substring(0, index);
    }
  }
  display("url = " + url);

  function display(msg) {
    $("<p/>").html(msg).appendTo(document.body);
  }
});

Live example
</s>


问:
Nested view pager with child fragment
I want to get nested fragment with a onClick method.I can't get the inner Fragment with his own xml working. After execution I get the following error:
No view found for id 0x7f0d0086 (com.none.myapp:id/menu_fragment) for fragment InnerFragment.
Is there a correct way to retrieve a inner Fragment using Viewpager?

FRAGMENT1 -->Button --->NESTED FRAGMENT

This is my MainActivity:

```<code>public class MainActivity extends AppCompatActivity {

private SectionsPageAdapter mSectionPageAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSectionPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);
    //Assigns the ViePager to TabLayout
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}
//Defines the number of tabs by setting appropriate fragment and tab name.
private void setupViewPager(ViewPager viewPager){
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new ScanFragment(),"TEST1");
    adapter.addFragment(new FilesFragment(),"TEST2");
    adapter.addFragment(new QuizFragment(),"TEST3");
    viewPager.setAdapter(adapter);

}}
</code>```

This is the outer Fragment:

```<code>public class TEST1 extends Fragment{
private Button btnTest1;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.quiz_layout, container, false);
    btnTest1 = (Button) view.findViewById(R.id.btn1);

    btnTest1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            getChildFragmentManager()
                    .beginTransaction()
                    .add(R.id.fragContainer, new InnerFragment())
                    .commit();

        }

    });

    return view;
}

}
</code>```

This is should be the inner Fragment:

```<code>public class InnerFragment extends Fragment{
public InnerFragment(){

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.inner_fragment, container, false);

    return view;
}}
</code>```

}

Outer xml Fragment:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragContainer"
android:orientation="vertical">

<Button
    android:id="@+id/btn1"
    android:layout_width="300dp"
    android:layout_height="60dp"
    android:onClick="buttonOnClick"
    android:text="Quiz"
    android:textColor="#ffffff"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="207dp" />

 <FrameLayout
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     />
 </RelativeLayout>
</code>```

答:
You may try to get you fragment from pager by tag.

View Pager marks fragment with its own tag wich is android:switcher:viewId:index.

Here is simple method to do this.

```<code>private static String getFragmentTag(int viewPagerId, int fragmentIndex) {
      return "android:switcher:" + viewPagerId+ ":" + fragmentIndex;
}
</code>```

Example how to get fragment from viewPager:

```<code>String fragmentTag = getFragmentTag(mViewPager.getViewId(), 0);// 0 - is pos of first fragment
Fragment yourFragment = getSupportFragmentManager().findFragmentByTag(fragmentTag);
</code>```

But as far as I understand you want to get fragment inside fragment.
So basically you need to provide method which return this fragment from TEST1 fragment.

```<code>public class TEST1 extends Fragment{
    private Button btnTest1;

    private InnerFragment innerFragment = new InnerFragment()

            @Nullable
            @Override
            public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.quiz_layout, container, false);
                btnTest1 = (Button) view.findViewById(R.id.btn1);

                btnTest1.setOnClickListener(new View.OnClickListener(){
                    public void onClick(View v) {
                        getChildFragmentManager()
                                .beginTransaction()
                                .add(R.id.fragContainer, innerFragment )
                                .commit();

                    }

                });

                return view;
            }

       public InnerFragment getInnerFragment() {
            return innerFragment;
       }

 }
</code>```

Title: Nested view pager with child fragment

Body:
I want to get nested fragment with a onClick method.I can't get the inner Fragment with his own xml working. After execution I get the following error:
No view found for id 0x7f0d0086 (com.none.myapp:id/menu_fragment) for fragment InnerFragment.
Is there a correct way to retrieve a inner Fragment using Viewpager?

FRAGMENT1 -->Button --->NESTED FRAGMENT

This is my MainActivity:

public class MainActivity extends AppCompatActivity {

private SectionsPageAdapter mSectionPageAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSectionPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    setupViewPager(mViewPager);
    //Assigns the ViePager to TabLayout
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
}
//Defines the number of tabs by setting appropriate fragment and tab name.
private void setupViewPager(ViewPager viewPager){
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new ScanFragment(),"TEST1");
    adapter.addFragment(new FilesFragment(),"TEST2");
    adapter.addFragment(new QuizFragment(),"TEST3");
    viewPager.setAdapter(adapter);

}}

This is the outer Fragment:

public class TEST1 extends Fragment{
private Button btnTest1;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.quiz_layout, container, false);
    btnTest1 = (Button) view.findViewById(R.id.btn1);

    btnTest1.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            getChildFragmentManager()
                    .beginTransaction()
                    .add(R.id.fragContainer, new InnerFragment())
                    .commit();

        }

    });

    return view;
}

}

This is should be the inner Fragment:

public class InnerFragment extends Fragment{
public InnerFragment(){

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.inner_fragment, container, false);

    return view;
}}

}

Outer xml Fragment:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragContainer"
android:orientation="vertical">

<Button
    android:id="@+id/btn1"
    android:layout_width="300dp"
    android:layout_height="60dp"
    android:onClick="buttonOnClick"
    android:text="Quiz"
    android:textColor="#ffffff"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="207dp" />

 <FrameLayout
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     />
 </RelativeLayout>

Body:
You may try to get you fragment from pager by tag.

View Pager marks fragment with its own tag wich is android:switcher:viewId:index.

Here is simple method to do this.

private static String getFragmentTag(int viewPagerId, int fragmentIndex) {
      return "android:switcher:" + viewPagerId+ ":" + fragmentIndex;
}

Example how to get fragment from viewPager:

String fragmentTag = getFragmentTag(mViewPager.getViewId(), 0);// 0 - is pos of first fragment
Fragment yourFragment = getSupportFragmentManager().findFragmentByTag(fragmentTag);

But as far as I understand you want to get fragment inside fragment.
So basically you need to provide method which return this fragment from TEST1 fragment.

public class TEST1 extends Fragment{
    private Button btnTest1;

    private InnerFragment innerFragment = new InnerFragment()

            @Nullable
            @Override
            public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.quiz_layout, container, false);
                btnTest1 = (Button) view.findViewById(R.id.btn1);

                btnTest1.setOnClickListener(new View.OnClickListener(){
                    public void onClick(View v) {
                        getChildFragmentManager()
                                .beginTransaction()
                                .add(R.id.fragContainer, innerFragment )
                                .commit();

                    }

                });

                return view;
            }

       public InnerFragment getInnerFragment() {
            return innerFragment;
       }

 }


问:
Facing issue with Guava Cache
I'm using Google Guava Cache + Spring cache abstraction for caching purpose.
I'm trying to make use of Guava's Loading Cache interface for the same.

I know Spring provides support for Guava Cache, but I was wondering whether I can make use of spring's cacheable annotation alongwith Loading Cache?

Basically I wanted to keep the business layer separate from the Cache.

Kindly help. Thanks.

答:
So you want both butter and jam. Okay. I will help you use loading cache along with keeping caching logic separate.

Consider you have a service class SampleServiceImpl which implements SampleService interface.

Service interface:

```<code>public interface SampleService {
    User getUser(int id);
}
</code>```

Service Implementation:

```<code>@Service
public class SampleServiceImpl implements SampleService {

    public User getUser(int id) {
        // fetch user from database
        return user;
    }
}
</code>```

Create one more class SampleServiceCache

```<code>public class SampleServiceCache extends ServiceCacheImpl {

    @Autowired
    public SampleServiceCache(int expiryTime, int maximumSize) {

        loadingCache =
                CacheBuilder.newBuilder().maximumSize(maximumSize).expireAfterAccess(expiryTime, TimeUnit.HOURS).build(
                        new CacheLoader<Integer, User>() {

                            @Override
                            public User load(@Nonnull Integer userId) {
                                return SampleServiceCache.super.getUser(userId);
                            }
                        });
    }
    @Override
    public User getUser(int userId) {
        return loadingCache.getUnchecked(userId);
    }
}
</code>```

In you bean config:

```<code>@Bean
public SampleService sampleService() {
    return new SampleServiceCache(expiry, maxSize);
}
</code>```

The day you want to remove cache, you have to do two things:

1. Remove the cache class.

2. Change bean config to return actual implementation object rather than cache implementation object.

P.S. You can define multiple loading caches for different behaviors say user retrieval, article retrieval, etc.

Title: Facing issue with Guava Cache

Body:
So you want both butter and jam. Okay. I will help you use loading cache along with keeping caching logic separate.

Consider you have a service class SampleServiceImpl which implements SampleService interface.

Service interface:

public interface SampleService {
    User getUser(int id);
}

Service Implementation:

@Service
public class SampleServiceImpl implements SampleService {

    public User getUser(int id) {
        // fetch user from database
        return user;
    }
}

Create one more class SampleServiceCache

public class SampleServiceCache extends ServiceCacheImpl {

    @Autowired
    public SampleServiceCache(int expiryTime, int maximumSize) {

        loadingCache =
                CacheBuilder.newBuilder().maximumSize(maximumSize).expireAfterAccess(expiryTime, TimeUnit.HOURS).build(
                        new CacheLoader<Integer, User>() {

                            @Override
                            public User load(@Nonnull Integer userId) {
                                return SampleServiceCache.super.getUser(userId);
                            }
                        });
    }
    @Override
    public User getUser(int userId) {
        return loadingCache.getUnchecked(userId);
    }
}

In you bean config:

@Bean
public SampleService sampleService() {
    return new SampleServiceCache(expiry, maxSize);
}

The day you want to remove cache, you have to do two things:

1. Remove the cache class.

2. Change bean config to return actual implementation object rather than cache implementation object.

P.S. You can define multiple loading caches for different behaviors say user retrieval, article retrieval, etc.


问:
How can I pass value out of anonoymous function
I would like to sent response from node server to client instead of greeting the return value of function Stats.calculate(), but I cannot figure out how to do it.

```<code>router.post('/calc', (req, res) => {
    request.get('a secret url api', (err,res,bodyJson) => {
        if(err) console.log('error');
        if(res.statusCode !== 200 ) console.log('error');
        Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);
    });
    res.json({greeting: "ciao"});
});
</code>```

Any suggestions?

答:
You can just call res.json inside the callback:

```<code>router.post('/calc', (req, res) => {
    request.get('a secret url api', (err, response, bodyJson) => {
        if(err) console.log('error');
        if(response.statusCode !== 200 ) console.log('error');
        var statsResult = Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);

        res.json({result: statsResult});
    });

});
</code>```

Body:
I would like to sent response from node server to client instead of greeting the return value of function Stats.calculate(), but I cannot figure out how to do it.

router.post('/calc', (req, res) => {
    request.get('a secret url api', (err,res,bodyJson) => {
        if(err) console.log('error');
        if(res.statusCode !== 200 ) console.log('error');
        Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);
    });
    res.json({greeting: "ciao"});
});

Any suggestions?

Body:
You can just call res.json inside the callback:

router.post('/calc', (req, res) => {
    request.get('a secret url api', (err, response, bodyJson) => {
        if(err) console.log('error');
        if(response.statusCode !== 200 ) console.log('error');
        var statsResult = Stats.calculate(bodyJson, req.body.firstVal, req.body.secondVal);

        res.json({result: statsResult});
    });

});


问:
Unsuccessful team-employs-player property chain
I am intrigued by Using Property Chains to get inferred Knowledge in an OWL Ontology(Protege)

The accepted answer has two solutions: two OWL expressions, or a SWRL rule.  I get the sense that the OP found the all-OWL (property chain) solution confusing but was satisfied with the SWRL answer.

I am trying to implement the all-OWL solution.  So far, I don't see an inference that Steven_Gerrard is employed by England when reasoning with Pellet.

I do see the inference

```<code>Steven_Gerrard R_NationalPlayer Steven_Gerrard
</code>```

Is that an error?

Should I use a different reasoner?  The OP got an error from FaCT++.

Is my substitution of some for values breaking the reasoning?

The answerer suggested a General Class Axiom of

```<code>hasNationalStatus value National_Player EquivalentTo R_NationalPlayer some Self
</code>```

but Protege compalined about my use of vlaue.  It does accept the following:

```<code>hasNationalStatus some ({National_Player}) EquivalentTo R_NationalPlayer some  Self
</code>```

Have I made some mistake in modelling Club, Country and Nationality?

My implementation:

```<code>@prefix : <http://example.com/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

<http://example.com/playerEmployment.owl> rdf:type owl:Ontology .

<http://example.com/R_NationalPlayer> rdf:type owl:ObjectProperty .

<http://example.com/employs> rdf:type owl:ObjectProperty ;
                           rdfs:subPropertyOf owl:topObjectProperty ;
                           owl:propertyChainAxiom ( [ owl:inverseOf <http://example.com/hasNationality>
                                                    ]
                                                    <http://example.com/R_NationalPlayer>
                                                  ) .

<http://example.com/hasNationalStatus> rdf:type owl:ObjectProperty .

<http://example.com/hasNationality> rdf:type owl:ObjectProperty .

<http://example.com/Club> rdf:type owl:Class ;
                        owl:equivalentClass [ rdf:type owl:Restriction ;
                                              owl:onProperty <http://example.com/employs> ;
                                              owl:someValuesFrom <http://example.com/Player>
                                            ] .

<http://example.com/NationalStatus> rdf:type owl:Class .

<http://example.com/Nationality> rdf:type owl:Class .

<http://example.com/Player> rdf:type owl:Class ;
                          owl:equivalentClass [ rdf:type owl:Restriction ;
                                                owl:onProperty <http://example.com/hasNationalStatus> ;
                                                owl:someValuesFrom <http://example.com/NationalStatus>
                                              ] ,
                                              [ rdf:type owl:Restriction ;
                                                owl:onProperty <http://example.com/hasNationality> ;
                                                owl:someValuesFrom <http://example.com/Nationality>
                                              ] .

<http://example.com/England> rdf:type owl:NamedIndividual ,
                                    <http://example.com/Club> ,
                                    <http://example.com/Nationality> .

<http://example.com/National_Player> rdf:type owl:NamedIndividual ,
                                            <http://example.com/NationalStatus> .

<http://example.com/Steven_Gerrard> rdf:type owl:NamedIndividual ,
                                           <http://example.com/Player> ;
                                  <http://example.com/hasNationalStatus> <http://example.com/National_Player> ;
                                  <http://example.com/hasNationality> <http://example.com/England> .

[ rdf:type owl:Restriction ;
  owl:onProperty <http://example.com/hasNationalStatus> ;
  owl:someValuesFrom [ rdf:type owl:Class ;
                       owl:oneOf ( <http://example.com/National_Player>
                                 )
                     ] ;
  owl:equivalentClass [ rdf:type owl:Restriction ;
                        owl:onProperty <http://example.com/R_NationalPlayer> ;
                        owl:hasSelf "true"^^xsd:boolean
                      ]
] .
</code>```

答:
Ugh.  Pellet can make the desired inference from the ontology included in my question.

I was looking on Steven's Individual page.  I should have been looking on England's individual page.

Body:
I am intrigued by Using Property Chains to get inferred Knowledge in an OWL Ontology(Protege)

The accepted answer has two solutions: two OWL expressions, or a SWRL rule.  I get the sense that the OP found the all-OWL (property chain) solution confusing but was satisfied with the SWRL answer.

I am trying to implement the all-OWL solution.  So far, I don't see an inference that Steven_Gerrard is employed by England when reasoning with Pellet.

I do see the inference

Steven_Gerrard R_NationalPlayer Steven_Gerrard

Is that an error?

Should I use a different reasoner?  The OP got an error from FaCT++.

Is my substitution of some for values breaking the reasoning?

The answerer suggested a General Class Axiom of

hasNationalStatus value National_Player EquivalentTo R_NationalPlayer some Self

but Protege compalined about my use of vlaue.  It does accept the following:

hasNationalStatus some ({National_Player}) EquivalentTo R_NationalPlayer some  Self

Have I made some mistake in modelling Club, Country and Nationality?

My implementation:

@prefix : <http://example.com/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

<http://example.com/playerEmployment.owl> rdf:type owl:Ontology .

<http://example.com/R_NationalPlayer> rdf:type owl:ObjectProperty .

<http://example.com/employs> rdf:type owl:ObjectProperty ;
                           rdfs:subPropertyOf owl:topObjectProperty ;
                           owl:propertyChainAxiom ( [ owl:inverseOf <http://example.com/hasNationality>
                                                    ]
                                                    <http://example.com/R_NationalPlayer>
                                                  ) .

<http://example.com/hasNationalStatus> rdf:type owl:ObjectProperty .

<http://example.com/hasNationality> rdf:type owl:ObjectProperty .

<http://example.com/Club> rdf:type owl:Class ;
                        owl:equivalentClass [ rdf:type owl:Restriction ;
                                              owl:onProperty <http://example.com/employs> ;
                                              owl:someValuesFrom <http://example.com/Player>
                                            ] .

<http://example.com/NationalStatus> rdf:type owl:Class .

<http://example.com/Nationality> rdf:type owl:Class .

<http://example.com/Player> rdf:type owl:Class ;
                          owl:equivalentClass [ rdf:type owl:Restriction ;
                                                owl:onProperty <http://example.com/hasNationalStatus> ;
                                                owl:someValuesFrom <http://example.com/NationalStatus>
                                              ] ,
                                              [ rdf:type owl:Restriction ;
                                                owl:onProperty <http://example.com/hasNationality> ;
                                                owl:someValuesFrom <http://example.com/Nationality>
                                              ] .

<http://example.com/England> rdf:type owl:NamedIndividual ,
                                    <http://example.com/Club> ,
                                    <http://example.com/Nationality> .

<http://example.com/National_Player> rdf:type owl:NamedIndividual ,
                                            <http://example.com/NationalStatus> .

<http://example.com/Steven_Gerrard> rdf:type owl:NamedIndividual ,
                                           <http://example.com/Player> ;
                                  <http://example.com/hasNationalStatus> <http://example.com/National_Player> ;
                                  <http://example.com/hasNationality> <http://example.com/England> .

[ rdf:type owl:Restriction ;
  owl:onProperty <http://example.com/hasNationalStatus> ;
  owl:someValuesFrom [ rdf:type owl:Class ;
                       owl:oneOf ( <http://example.com/National_Player>
                                 )
                     ] ;
  owl:equivalentClass [ rdf:type owl:Restriction ;
                        owl:onProperty <http://example.com/R_NationalPlayer> ;
                        owl:hasSelf "true"^^xsd:boolean
                      ]
] .


问:
Compiling and communication with shell application in Android/Java
I have a command line application (also it's source code in C language). I want to use it in my first android application.

Here are my questions:

I have a compiled executable for mac. Should I recompile it for android? If yes, how?

Is it possible to have a two way communication with an executable in shell in Java/Android?

I'm looking for something like:

```<code>Runtime.getRuntime().exec(cmd);
</code>```

After a lot of googling, that line of code was only thing that I found. But I don't want to close the executable after each call (it communicates with a server on the internet). Here is what I want to do:

```<code>1. Open shell executable
2. write AAA
3. read line
4. write BBB
5. read line
6. write CCC
...
98. write XYZ
99. read line
100. close executable
</code>```

Note that there may be nothing to read, and it shouldn't wait for it.

答:
Yes, you need recompile it with NDK. How: you can find more information on official Android site, where examples also present.

Yes its also possible to do that, and there are two ways exist:
a) JNI. You need to write a wrapper for for you function, and compile a shared library
b) You can compile executable file, run it and communicate via input/output stream. Something like:

```<code>     try {
        Process pb = Runtime.getRuntime().exec(cmd);
        String line;
        BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream()));
        while ((line = input.readLine()) != null) {
            System.out.println("Input from your C/C++ app: " + line);
        }
        input.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Body:
I have a command line application (also it's source code in C language). I want to use it in my first android application.

Here are my questions:

I have a compiled executable for mac. Should I recompile it for android? If yes, how?

Is it possible to have a two way communication with an executable in shell in Java/Android?

I'm looking for something like:

Runtime.getRuntime().exec(cmd);

After a lot of googling, that line of code was only thing that I found. But I don't want to close the executable after each call (it communicates with a server on the internet). Here is what I want to do:

1. Open shell executable
2. write AAA
3. read line
4. write BBB
5. read line
6. write CCC
...
98. write XYZ
99. read line
100. close executable

Note that there may be nothing to read, and it shouldn't wait for it.

Body:
Yes, you need recompile it with NDK. How: you can find more information on official Android site, where examples also present.

Yes its also possible to do that, and there are two ways exist:
a) JNI. You need to write a wrapper for for you function, and compile a shared library
b) You can compile executable file, run it and communicate via input/output stream. Something like:

     try {
        Process pb = Runtime.getRuntime().exec(cmd);
        String line;
        BufferedReader input = new BufferedReader(new InputStreamReader(pb.getInputStream()));
        while ((line = input.readLine()) != null) {
            System.out.println("Input from your C/C++ app: " + line);
        }
        input.close();

    } catch (IOException e) {
        e.printStackTrace();
    }


问:
Algorithm to sum/stack values from a time series graph where data points don't match on time
I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?

I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values across the series don't match up, and i really don't want to resort to duplicating values into time bins.

So, given these 2 series:

```<code>S1: (1;100) (5;100) (10;100)
S2: (4;150) (5;100) (18;150)
</code>```

When added together, should result in:

```<code>ST: (1;100) (4;250) (5;200) (10;200) (18;250)
</code>```

Logic:

```<code>x=1 s1=100, s2=None, sum=100
x=4 s1=100, s2=150, sum=250 (note s1 value from previous value)
x=5 s1=100, s2=100, sum=200
x=10 s1=100, s2=100, sum=200
x=18 s1=100, s2=150, sum=250
</code>```

My current thinking is to iterate a sorted list of keys(x), keep the previous value for each series, and query each set if it has a new y for the x.

Any ideas would be appreciated!

答:
Here's another way to do it, putting more of the behaviour on the individual data streams:</p>

```<code>class DataStream(object):
    def __init__(self, iterable):
        self.iterable = iter(iterable)
        self.next_item = (None, 0)
        self.next_x = None
        self.current_y = 0
        self.next()

    def next(self):
        if self.next_item is None:
            raise StopIteration()
        self.current_y = self.next_item[1]
        try:
            self.next_item = self.iterable.next()
            self.next_x = self.next_item[0]
        except StopIteration:
            self.next_item = None
            self.next_x = None
        return self.next_item

    def __iter__(self):
        return self

class MergedDataStream(object):
    def __init__(self, *iterables):
        self.streams = [DataStream(i) for i in iterables]
        self.outseq = []

    def next(self):
        xs = [stream.next_x for stream in self.streams if stream.next_x is not None]
        if not xs:
            raise StopIteration()
        next_x = min(xs)
        current_y = 0
        for stream in self.streams:
            if stream.next_x == next_x:
                stream.next()
            current_y += stream.current_y
        self.outseq.append((next_x, current_y))
        return self.outseq[-1]

    def __iter__(self):
        return self

if __name__ == '__main__':
    seqs = [
        [(1, 100), (5, 100), (10, 100)],
        [(4, 150), (5, 100), (18, 150)],
        ]

    sm = MergedDataStream(*seqs)
    for x, y in sm:
        print "%02s: %s" % (x, y)

    print sm.outseq
</code>```

Body:
I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?

I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values across the series don't match up, and i really don't want to resort to duplicating values into time bins.

So, given these 2 series:

S1: (1;100) (5;100) (10;100)
S2: (4;150) (5;100) (18;150)

When added together, should result in:

ST: (1;100) (4;250) (5;200) (10;200) (18;250)

Logic:

x=1 s1=100, s2=None, sum=100
x=4 s1=100, s2=150, sum=250 (note s1 value from previous value)
x=5 s1=100, s2=100, sum=200
x=10 s1=100, s2=100, sum=200
x=18 s1=100, s2=150, sum=250

My current thinking is to iterate a sorted list of keys(x), keep the previous value for each series, and query each set if it has a new y for the x.

Any ideas would be appreciated!

Body:
Here's another way to do it, putting more of the behaviour on the individual data streams:

class DataStream(object):
    def __init__(self, iterable):
        self.iterable = iter(iterable)
        self.next_item = (None, 0)
        self.next_x = None
        self.current_y = 0
        self.next()

    def next(self):
        if self.next_item is None:
            raise StopIteration()
        self.current_y = self.next_item[1]
        try:
            self.next_item = self.iterable.next()
            self.next_x = self.next_item[0]
        except StopIteration:
            self.next_item = None
            self.next_x = None
        return self.next_item

    def __iter__(self):
        return self

class MergedDataStream(object):
    def __init__(self, *iterables):
        self.streams = [DataStream(i) for i in iterables]
        self.outseq = []

    def next(self):
        xs = [stream.next_x for stream in self.streams if stream.next_x is not None]
        if not xs:
            raise StopIteration()
        next_x = min(xs)
        current_y = 0
        for stream in self.streams:
            if stream.next_x == next_x:
                stream.next()
            current_y += stream.current_y
        self.outseq.append((next_x, current_y))
        return self.outseq[-1]

    def __iter__(self):
        return self

if __name__ == '__main__':
    seqs = [
        [(1, 100), (5, 100), (10, 100)],
        [(4, 150), (5, 100), (18, 150)],
        ]

    sm = MergedDataStream(*seqs)
    for x, y in sm:
        print "%02s: %s" % (x, y)

    print sm.outseq


问:
Understanding the limitations of the bignumber.js library
I have recently found the bignumber.js library:

source: https://github.com/MikeMcl/bignumber.js

What I'm not sure of is if there is a limit to how big the number operations can be? I have been looking into the documentation, trying to find sources online. But nothing as of yet.

答:
I haven't worked with bignumber.js but a small peek into
http://mikemcl.github.io/bignumber.js/#range has shown me that it seems to be configurable.

```<code>BigNumber.config({ RANGE: 500 })
BigNumber.config().RANGE     // [ -500, 500 ]
new BigNumber('9.999e499')   // '9.999e+499'
new BigNumber('1e500')       // 'Infinity'
new BigNumber('1e-499')      // '1e-499'
new BigNumber('1e-500')      // '0'
</code>```

Body:
I haven't worked with bignumber.js but a small peek into
http://mikemcl.github.io/bignumber.js/#range has shown me that it seems to be configurable.

BigNumber.config({ RANGE: 500 })
BigNumber.config().RANGE     // [ -500, 500 ]
new BigNumber('9.999e499')   // '9.999e+499'
new BigNumber('1e500')       // 'Infinity'
new BigNumber('1e-499')      // '1e-499'
new BigNumber('1e-500')      // '0'