问:
How to set up Android library to work with gradle
I'm trying to write some Android library to reuse in multiple projects. So I want to be able to house the library in a repo and then import it using gradle. An example of what I want to achieve is Picasso lib.
https://github.com/square/picasso

The only thing I need to do to start using this lib is adding this line to my app build.gradle: implementation 'com.squareup.picasso:picasso:2.71828'

Could someone point me to a reference or provide steps to do this?

Thanks in advance

答:
You can follow this step by step to upload an android library.
Click here to check in details.
Then you can add in your build.gradle file to use it.

Follow this.

Step 1: Create an account in Bintray with your GitHub/Google account
Step 2: First create a repository in your GitHub. Then add that repository in Bintray.
Step 3: Open your library project in Android Studio and add this line in your build.gradle file:

```<code>classpath 'com.novoda:bintray-release:{latest_version}'

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha07'

        // Step I: add this line
        classpath 'com.novoda:bintray-release:0.8.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Step 4: Add project details to the build.gradle file under the /app directory

```<code>apply plugin: ‘com.android.library’
publish {

    def groupProjectID = '{package_name}'
    def artifactProjectID = '{name_of_your_library}'
    def publishVersionID = 'library_version_code'

    userOrg = '{username_of_bintray}'
    repoName = 'repository_name'
    groupId = groupProjectID
    artifactId = artifactProjectID
    publishVersion = publishVersionID
    desc = '{library description}'
    website = '{github_url}

}

//Step I: Add the below line

apply plugin: 'com.novoda.bintray-release'
apply plugin: 'com.android.library'

//Step II: Add the below publish details
publish {

    def groupProjectID = 'com.an.optimize'
    def artifactProjectID = 'optimize'
    def publishVersionID = '0.1.0'

    userOrg = 'murthyanitaa'
    repoName = 'Optimize'
    groupId = groupProjectID
    artifactId = artifactProjectID
    publishVersion = publishVersionID
    desc = 'Android library for displaying data based on JSON configuration fetched from server. With this library, you can kiss goodbye to string.xml, dimen.xml, arrays.xml. Keep all your string/integer/array config in one file. The library will automatically fetch the data from the url you provide.'
    website = 'https://github.com/anitaa1990/Optimize'
}

android {
    compileSdkVersion 27
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation "android.arch.work:work-runtime:1.0.0-alpha01"
}
</code>```

Step 5: Upload to Bintray: In the terminal in Android Studio, add the below command to clean, build and upload the library to bintray:

```<code>gradle clean build bintrayUpload -PbintrayUser={userid_bintray} -PbintrayKey={apikey_bintray} -PdryRun=false
</code>```

Step 6: Link to JCenter: Under your project repository in Bintray, you will see your library along with the version details you had specified. Now all you need to do is click on Add to JCenter.

Body:
You can follow this step by step to upload an android library.
Click here to check in details.
Then you can add in your build.gradle file to use it.

Follow this.

Step 1: Create an account in Bintray with your GitHub/Google account
Step 2: First create a repository in your GitHub. Then add that repository in Bintray.
Step 3: Open your library project in Android Studio and add this line in your build.gradle file:

classpath 'com.novoda:bintray-release:{latest_version}'

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0-alpha07'

        // Step I: add this line
        classpath 'com.novoda:bintray-release:0.8.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Step 4: Add project details to the build.gradle file under the /app directory

apply plugin: ‘com.android.library’
publish {

    def groupProjectID = '{package_name}'
    def artifactProjectID = '{name_of_your_library}'
    def publishVersionID = 'library_version_code'

    userOrg = '{username_of_bintray}'
    repoName = 'repository_name'
    groupId = groupProjectID
    artifactId = artifactProjectID
    publishVersion = publishVersionID
    desc = '{library description}'
    website = '{github_url}

}

//Step I: Add the below line

apply plugin: 'com.novoda.bintray-release'
apply plugin: 'com.android.library'

//Step II: Add the below publish details
publish {

    def groupProjectID = 'com.an.optimize'
    def artifactProjectID = 'optimize'
    def publishVersionID = '0.1.0'

    userOrg = 'murthyanitaa'
    repoName = 'Optimize'
    groupId = groupProjectID
    artifactId = artifactProjectID
    publishVersion = publishVersionID
    desc = 'Android library for displaying data based on JSON configuration fetched from server. With this library, you can kiss goodbye to string.xml, dimen.xml, arrays.xml. Keep all your string/integer/array config in one file. The library will automatically fetch the data from the url you provide.'
    website = 'https://github.com/anitaa1990/Optimize'
}

android {
    compileSdkVersion 27
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation "android.arch.work:work-runtime:1.0.0-alpha01"
}

Step 5: Upload to Bintray: In the terminal in Android Studio, add the below command to clean, build and upload the library to bintray:

gradle clean build bintrayUpload -PbintrayUser={userid_bintray} -PbintrayKey={apikey_bintray} -PdryRun=false

Step 6: Link to JCenter: Under your project repository in Bintray, you will see your library along with the version details you had specified. Now all you need to do is click on Add to JCenter.


来源: stackexchange

问:
extern declaration and definition in C
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

```<code>extern int foo; //default
static int bar;
</code>```

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

```<code>static int bar = 5;
</code>```

but casts a complain at

```<code>extern int foo = 4;
</code>```

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?

答:
The extern variable will be defined with a global scope (exported) in the unit where it is defined:

int baz = 5;

ContentLicense: CC BY-SA 3.0

Title: extern declaration and definition in C

Body:
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

extern int foo; //default
static int bar;

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

static int bar = 5;

but casts a complain at

extern int foo = 4;

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?


问:
Why am I getting a syntax error using SQL pivot?
I'm getting a syntax error at 1 JAN.

My SampleStart is in datetime format. Am I aliasing something wrong?

```<code>SELECT * FROM (
  SELECT year(SampleStart) year, month(SampleStart) month, AllowedPopulation
  FROM BIC_AGGREGATE_FINAL
  WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) as s
PIVOT (
  max(AllowedPopulation)
  FOR month in (
    1 JAN, 2 FEB, 3 MAR, 4 APR, 5 MAY, 6 JUN,
    7 JUL, 8 AUG, 9 SEP, 10 OCT, 11 NOV, 12 DEC
  )
)
ORDER BY year DESC
</code>```

I'm expecting the results to show me the allowed population for each month in the year 2018.

答:
You cannot supply your column aliases within the pivot function, you have to do this in the select. Also, when specifying your IN clause within the pivot you must apply similar rules to when selecting columns, if the column is a reserved word, or contains special characters (e.g. space), or starts with a number etc then you must enclose the name in square brackets.

Finally, you have to give the pivot function itself an alias.

e.g.

```<code>SELECT  pvt.[year],
        JAN = pvt.[1],
        FEB = pvt.[2],
        MAR = pvt.[3],
        APR = pvt.[4],
        MAY = pvt.[5],
        JUN = pvt.[6],
        JUL = pvt.[7],
        AUG = pvt.[8],
        SEP = pvt.[9],
        OCT = pvt.[10],
        NOV = pvt.[11],
        DEC = pvt.[12]
FROM (
  SELECT YEAR(SampleStart) AS [year], MONTH(SampleStart) AS [month], AllowedPopulation
  FROM BIC_AGGREGATE_FINAL
  WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) AS s
PIVOT (
  MAX(AllowedPopulation)
  FOR month IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
) AS pvt -- Alias here too
ORDER BY pvt.[year] DESC
</code>```

If, as the question states SampleStart is a DATETIME column, then I would make two changes to your where clause:

Use a exclusive date range instead of BETWEEN - What do BETWEEN and the devil have in common?

Use the unambiguous date literal format yyyyMMdd, depending on your settings 2018-10-01 could either be 10th January, or 1st October.

So you would end up with:

```<code>   WHERE SampleStart >= '20180101'
   AND SampleStart < '20190101'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting a syntax error at 1 JAN.

My SampleStart is in datetime format. Am I aliasing something wrong?

SELECT * FROM (
  SELECT year(SampleStart) year, month(SampleStart) month, AllowedPopulation
  FROM BIC_AGGREGATE_FINAL
  WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) as s
PIVOT (
  max(AllowedPopulation)
  FOR month in (
    1 JAN, 2 FEB, 3 MAR, 4 APR, 5 MAY, 6 JUN,
    7 JUL, 8 AUG, 9 SEP, 10 OCT, 11 NOV, 12 DEC
  )
)
ORDER BY year DESC

I'm expecting the results to show me the allowed population for each month in the year 2018.

Body:
You cannot supply your column aliases within the pivot function, you have to do this in the select. Also, when specifying your IN clause within the pivot you must apply similar rules to when selecting columns, if the column is a reserved word, or contains special characters (e.g. space), or starts with a number etc then you must enclose the name in square brackets.

Finally, you have to give the pivot function itself an alias.

e.g.

SELECT  pvt.[year],
        JAN = pvt.[1],
        FEB = pvt.[2],
        MAR = pvt.[3],
        APR = pvt.[4],
        MAY = pvt.[5],
        JUN = pvt.[6],
        JUL = pvt.[7],
        AUG = pvt.[8],
        SEP = pvt.[9],
        OCT = pvt.[10],
        NOV = pvt.[11],
        DEC = pvt.[12]
FROM (
  SELECT YEAR(SampleStart) AS [year], MONTH(SampleStart) AS [month], AllowedPopulation
  FROM BIC_AGGREGATE_FINAL
  WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) AS s
PIVOT (
  MAX(AllowedPopulation)
  FOR month IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
) AS pvt -- Alias here too
ORDER BY pvt.[year] DESC

If, as the question states SampleStart is a DATETIME column, then I would make two changes to your where clause:

Use a exclusive date range instead of BETWEEN - What do BETWEEN and the devil have in common?

Use the unambiguous date literal format yyyyMMdd, depending on your settings 2018-10-01 could either be 10th January, or 1st October.

So you would end up with:

   WHERE SampleStart >= '20180101'
   AND SampleStart < '20190101'


问:
Create writable combobox with vba
I want to create a combobox on the cell the user click, and permit the user to write and/or choose (an autocompletion similar to google), set it to the cell and close combobox.

I have this code which create the box :

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim lst
If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then
        Me.DropDowns.Delete
        With Worksheets("Listing")
            lst = "'" & .Name & "'!" & _
              .Range(.Range("a1"), _
              .Cells(.Rows.Count, 1).End(xlUp)).Address()
         End With
        With Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left, _
                                  Top:=Target.Top, Width:=60, Height:=15)
             .Name = "CB"
            .OnAction = "CB_Change"
            .ControlFormat.ListFillRange = lst

        End With
    End If
End Sub
</code>```

The problem is that the Comboboxes created only allow user to select and not to write into

答:
ActiveX controls are easier to configure than Form Controls. MSForm.ComboBox controls have a Style property that, when set to fmStyleDropDownCombo, makes the textbox area editable; when the style is fmStyleDropDownList, user input is restricted to what's in the dropdown list.

...with that said, Data Validation is probably a better option (less bug-prone, better integrated with the worksheet/Excel, no MSForm dependency), if you can live with "circle invalid data" making red circles around "invalid data" that is allowed to be entered, but not in the dropdown list:

Title: Create writable combobox with vba

Body:
I want to create a combobox on the cell the user click, and permit the user to write and/or choose (an autocompletion similar to google), set it to the cell and close combobox.

I have this code which create the box :

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim lst
If Not Intersect([4:7], Target) Is Nothing And Target.Count = 1 Then
        Me.DropDowns.Delete
        With Worksheets("Listing")
            lst = "'" & .Name & "'!" & _
              .Range(.Range("a1"), _
              .Cells(.Rows.Count, 1).End(xlUp)).Address()
         End With
        With Me.Shapes.AddFormControl(xlDropDown, Left:=Target.Left, _
                                  Top:=Target.Top, Width:=60, Height:=15)
             .Name = "CB"
            .OnAction = "CB_Change"
            .ControlFormat.ListFillRange = lst

        End With
    End If
End Sub

The problem is that the Comboboxes created only allow user to select and not to write into


问:
Python: 'ValueError: too many values to unpack (expected 2)' for a username password system
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

```<code>database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse
</code>```

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

答:
Using pythons function eval, you can parse the string read from the file to a dictionary. Then you can write it to your dictionary

```<code>with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        entry = eval(line)
        database[entry["name"]] = entry["man"]
</code>```

Body:
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

Body:
Using pythons function eval, you can parse the string read from the file to a dictionary. Then you can write it to your dictionary

with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        entry = eval(line)
        database[entry["name"]] = entry["man"]


答:
Try with-</p>

```<code>SELECT  year,
[1] AS JAN,
[2] AS FEB,
[3] AS MAR,
[4] AS APR,
[5] AS MAY,
[6] AS JUN,
[7] AS JUL,
[8] AS AUG,
[9] AS SEP,
[10] AS OCT,
[11] AS NOV,
[12] AS DEC

FROM
(
    SELECT year(SampleStart) year,
    month(SampleStart) month,
    AllowedPopulation
    FROM BIC_AGGREGATE_FINAL
    WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) as s
PIVOT
(
max(AllowedPopulation)
FOR month in (
    [1], [2], [3], [4], [5], [6],
    [7], [8], [9], [10], [11], [12]
)
)AS PVT
ORDER BY year DESC
</code>```

Title: Why am I getting a syntax error using SQL pivot?

Body:
Try with-

SELECT  year,
[1] AS JAN,
[2] AS FEB,
[3] AS MAR,
[4] AS APR,
[5] AS MAY,
[6] AS JUN,
[7] AS JUL,
[8] AS AUG,
[9] AS SEP,
[10] AS OCT,
[11] AS NOV,
[12] AS DEC

FROM
(
    SELECT year(SampleStart) year,
    month(SampleStart) month,
    AllowedPopulation
    FROM BIC_AGGREGATE_FINAL
    WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) as s
PIVOT
(
max(AllowedPopulation)
FOR month in (
    [1], [2], [3], [4], [5], [6],
    [7], [8], [9], [10], [11], [12]
)
)AS PVT
ORDER BY year DESC


问:
Spacy Named Entity Recognition Issue
I am trying to tag ORG's from a bunch of text I am parsing through

What I have so far is as follows:

```<code>import spacy
import en_core_web_sm
nlp = en_core_web_sm.load()

file = open("C:\\sample.txt")

doc = nlp(file.read())
print([(X.text, X.label_) for X in doc.ents])
</code>```

Now, my result prints all possible tags, I just want it to print ORGs instead. Any suggestions on how to do that?

答:
X.label_ holds the name of the entity, so all you need is add a condition to only return those tuples where X.label_ equals ORG:

```<code>print([(X.text, X.label_) for X in doc.ents if X.label_ == "ORG"])
#                                           ^------------------^
</code>```

Title: Spacy Named Entity Recognition Issue

Body:
I am trying to tag ORG's from a bunch of text I am parsing through

What I have so far is as follows:

import spacy
import en_core_web_sm
nlp = en_core_web_sm.load()

file = open("C:\\sample.txt")

doc = nlp(file.read())
print([(X.text, X.label_) for X in doc.ents])

Now, my result prints all possible tags, I just want it to print ORGs instead. Any suggestions on how to do that?

Body:
X.label_ holds the name of the entity, so all you need is add a condition to only return those tuples where X.label_ equals ORG:

print([(X.text, X.label_) for X in doc.ents if X.label_ == "ORG"])
#                                           ^------------------^


问:
create google contact without duplicating them
I am trying to create a google contact using google contact API and got success in it by using this link https://developers.google.com/contacts/v3/#creating_contacts
But when I again creating the same contact it is not checking that it already exists and it is, therefore, creating duplicate contact in Gmail.i do not want to create duplicate contact if email id already exists in Gmail contacts.</p>

答: Unfortunately, upon checking the documentation, there's no information regarding the duplication of contacts using Google Contacts API. There are two options you can use: first is to use Google Apps Script - Duplicate check while creating Google Contact with Google Apps Script or by manually removing the contacts in the UI.</p>


问:
Execute a function after Flask returns response
I have some code that needs to execute after Flask returns a response. I don't think it's complex enough to set up a task queue like Celery for it. The key requirement is that Flask must return the response to the client before running this function. It can't wait for the function to execute.

There are some existing questions about this, but none of the answers seem to address running a task after the response is sent to the client, they still execute synchronously and then the response is returned.

Python Flask sending response immediately

Need to execute a function after returning the response in Flask

Flask end response and continue processing

答:
Middleware Solution for Flask Blueprints

This is the same solution proposed by Matthew Story (which is the perfect solution IMHO - thanks Matthew), adapted for Flask Blueprints.  The secret sauce here is to get hold of the app context using the current_app proxy.  Read up here for more information (http://flask.pocoo.org/docs/1.0/appcontext/)

Let's assume the AfterThisResponse & AfterThisResponseMiddleware classes are placed in a module at .utils.after_this_response.py

Then where the Flask object creation occurs, you might have, eg...

__init__.py

```<code>from api.routes import my_blueprint
from .utils.after_this_response import AfterThisResponse

app = Flask( __name__ )
AfterThisResponse( app )
app.register_blueprint( my_blueprint.mod )
</code>```

And then in your blueprint module...

a_blueprint.py

```<code>from flask import Blueprint, current_app

mod = Blueprint( 'a_blueprint', __name__, url_prefix=URL_PREFIX )

@mod.route( "/some_resource", methods=['GET', 'POST'] )
def some_resource():
    # do some stuff here if you want

    @current_app.after_this_response
    def post_process():
        # this will occur after you finish processing the route & return (below):
        time.sleep(2)
        print("after_response")

    # do more stuff here if you like & then return like so:
    return "Success!\n"
</code>```

Body:
Middleware Solution for Flask Blueprints

This is the same solution proposed by Matthew Story (which is the perfect solution IMHO - thanks Matthew), adapted for Flask Blueprints.  The secret sauce here is to get hold of the app context using the current_app proxy.  Read up here for more information (http://flask.pocoo.org/docs/1.0/appcontext/)

Let's assume the AfterThisResponse & AfterThisResponseMiddleware classes are placed in a module at .utils.after_this_response.py

Then where the Flask object creation occurs, you might have, eg...

__init__.py

from api.routes import my_blueprint
from .utils.after_this_response import AfterThisResponse

app = Flask( __name__ )
AfterThisResponse( app )
app.register_blueprint( my_blueprint.mod )

And then in your blueprint module...

a_blueprint.py

from flask import Blueprint, current_app

mod = Blueprint( 'a_blueprint', __name__, url_prefix=URL_PREFIX )

@mod.route( "/some_resource", methods=['GET', 'POST'] )
def some_resource():
    # do some stuff here if you want

    @current_app.after_this_response
    def post_process():
        # this will occur after you finish processing the route & return (below):
        time.sleep(2)
        print("after_response")

    # do more stuff here if you like & then return like so:
    return "Success!\n"


问:
"cannot query field 'id' on type CreateUser" with official Graphql tutorial
I am following the graphql-python tutorial on https://www.howtographql.com/graphql-python/4-authentication/. However, I get 3 errors saying "Cannot query field \"id\" on type \"CreateUser\"." I basically copied all source code in the tutorial and I double-checked my Python code before posting here. And I used the same versions of Django, Graphene and other packages. I use Windows 10 and Python3.7. How can I pass the error?

Mutation:

```<code>mutation {
  createUser (
    username: "abc",
    email: "abc@example.com",
    password: "123456"
  ){
    id
    username
    password
  }
}
</code>```

Response:

```<code>{
  "errors": [
    {
      "message": "Cannot query field \"id\" on type \"CreateUser\".",
      "locations": [
        {
          "line": 7,
          "column": 5
        }
      ]
    },
    {
      "message": "Cannot query field \"username\" on type \"CreateUser\". Did you mean \"user\"?",
      "locations": [
        {
          "line": 8,
          "column": 5
        }
      ]
    },
    {
      "message": "Cannot query field \"password\" on type \"CreateUser\".",
      "locations": [
        {
          "line": 9,
          "column": 5
        }
      ]
    }
  ]
}
</code>```

答:
You are missing a level in your query:</p>

```<code>mutation {
  createUser (
    username: "abc",
    email: "abc@example.com",
    password: "123456"
  ){
    user {
      id
      username
      password
    }
  }
}
</code>```

Body:
I am following the graphql-python tutorial on https://www.howtographql.com/graphql-python/4-authentication/. However, I get 3 errors saying "Cannot query field \"id\" on type \"CreateUser\"." I basically copied all source code in the tutorial and I double-checked my Python code before posting here. And I used the same versions of Django, Graphene and other packages. I use Windows 10 and Python3.7. How can I pass the error?

Mutation:

mutation {
  createUser (
    username: "abc",
    email: "abc@example.com",
    password: "123456"
  ){
    id
    username
    password
  }
}

Response:

{
  "errors": [
    {
      "message": "Cannot query field \"id\" on type \"CreateUser\".",
      "locations": [
        {
          "line": 7,
          "column": 5
        }
      ]
    },
    {
      "message": "Cannot query field \"username\" on type \"CreateUser\". Did you mean \"user\"?",
      "locations": [
        {
          "line": 8,
          "column": 5
        }
      ]
    },
    {
      "message": "Cannot query field \"password\" on type \"CreateUser\".",
      "locations": [
        {
          "line": 9,
          "column": 5
        }
      ]
    }
  ]
}

Body:
You are missing a level in your query:

mutation {
  createUser (
    username: "abc",
    email: "abc@example.com",
    password: "123456"
  ){
    user {
      id
      username
      password
    }
  }
}


问:
LINQ query joining two tables together to return values that are false
I have a linq query that joins two tables together by matching method names. Within the table I need to look for a 'global' value and if found compare the children elements in methods called 'parameters' against each other assuring that both the tables has an equal counterpart and if one methods parameters does not match any of the others then returns false.

Below is an example of the results. We can see that seqEquals has found a 'method' that does not equal any of the others, however, the LINQ query returns all values and I'd like to only extract on false of 'seqEquals' I have tried putting the string compare within the 'where' clause however the results did not compare all against each other as expected.

```<code>{ mOneName = GetItemsJSON, seqEqual = False, mOneParm = [
  {
    "name": "itemTypes",
    "type": "List"
  },
  {
    "name": "textSearch",
    "type": "String"
  }
], mTwoParm = [
  {
    "name": "propertyId",
    "type": "String"
  },
  {
    "name": "revClassIds",
    "type": "List"
  },
  {
    "name": "itemTypes",
    "type": "List"
  },
  {
    "name": "textSearch",
    "type": "String"
  },
  {
    "name": "eventId",
    "type": "String"
  }
] }
</code>```

The C# code

```<code>        var ST1 = firstOrgST["records"][0]["SymbolTable"]["methods"];
        var ST2 = secondOrgST["records"][0]["SymbolTable"]["methods"];

        // joins both tables and pulls the methods containing global from the joins
        var STDiff =
            from one in ST1
            join two in ST2
                on one.Value<String>("name") equals two.Value<string>("name")
            where one["modifiers"].Values().Contains("global")
            select new
            {
                mOneName = one["name"],
                seqEqual = one["parameters"].ToString() == two["parameters"].ToString(),
                mOneParm = one["parameters"],
                mTwoParm = two["parameters"]
            };

        var errorFound = false;
        var errorMethod = "";

        foreach (var i in STDiff)
        {    Console.WriteLine(i);
            if (!i.seqEqual)
            {
                errorFound = true;
                errorMethod = i.mOneName.ToString();
                break;
            }
        }

        // if error is found prints to console the class name as well as the method name
        if (errorFound)
        {
            Console.WriteLine(Path.GetFileNameWithoutExtension(symbolTable) + " on method: " + errorMethod + " has different parameters.\n");
            isDifferent = true;
        }
</code>```

Example of data: This is table one. Table two may have different params

```<code>{
  "SymbolTable": {
    "methods": [
      {
        "annotations": [
          {
            "name": "TestVisible"
          }
        ],
        "location": {
          "column": 20,
          "line": 1056
        },
        "modifiers": [
          "private"
        ],
        "name": "GetItemsJSON",
        "parameters": [
          {
            "name": "propertyId",
            "type": "String"
          },
          {
            "name": "revClassIds",
            "type": "List"
          },
          {
            "name": "itemTypes",
            "type": "List"
          },
          {
            "name": "itemCategories",
            "type": "List"
          },
          {
            "name": "textSearch",
            "type": "String"
          },
          {
            "name": "eventId",
            "type": "String"
          }
        ],
        "references": [],
        "returnType": "String",
        "type": null
      },
      {
        "annotations": [],
        "location": {
          "column": 26,
          "line": 4313
        },
        "modifiers": [
          "static",
          "global"
        ],
        "name": "GetItemsJSON",
        "parameters": [
          {
            "name": "itemTypes",
            "type": "List"
          },
          {
            "name": "textSearch",
            "type": "String"
          }
        ],
        "references": [],
        "returnType": "String",
        "type": null
      },
      {
        "annotations": [],
        "location": {
          "column": 26,
          "line": 4316
        },
        "modifiers": [
          "static",
          "global"
        ],
        "name": "GetItemsJSON",
        "parameters": [
          {
            "name": "propertyId",
            "type": "String"
          },
          {
            "name": "revClassIds",
            "type": "List"
          },
          {
            "name": "itemTypes",
            "type": "List"
          },
          {
            "name": "textSearch",
            "type": "String"
          },
          {
            "name": "eventId",
            "type": "String"
          }
        ]
      }
    ]
  }
}
</code>```

答:
I'd recommend you convert your datatable into a list of objects and then run your linq query.

1) Use a generic method like this for conversion of DataTable to list of objects

```<code>private static List<T> ConvertDataTable<T>(DataTable dt)
{
    List<T> data = new List<T>();
    foreach (DataRow row in dt.Rows)
    {
        T item = GetItem<T>(row);
        data.Add(item);
    }
    return data;
}

private static T GetItem<T>(DataRow dr)
{
    Type temp = typeof(T);
    T obj = Activator.CreateInstance<T>();

    foreach (DataColumn column in dr.Table.Columns)
    {
        foreach (PropertyInfo pro in temp.GetProperties())
        {
            if (pro.Name == column.ColumnName)
                pro.SetValue(obj, dr[column.ColumnName], null);
            else
                continue;
        }
    }
    return obj;
}
</code>```

2) Use Linq query like this on the list of objects

```<code>    var ST1 = myTableData.ToList();
    var ST2 = myTableData.ToList();

    var STDiff = from one in ST1
                 join two in ST2
                 on one.name equals two.name
                 where one.modifiers.Contains("global")
            select new
            {
                mOneName = one.name,
                seqEqual = CompareParamsAndGetMatchingIndex(one.parameters, two.parameters),
                mOneParm = one.parameters,
                mTwoParm = two.parameters
            };

private int CompareParamsAndGetMatchingIndex(Parameter[] items1, Parameter[] items2)
{
    if (items1.Length > items2.Length)
    {
        return items2.Select((Parameter p, int i) => p.Equals(items1[i]) ? 1 : 0).Sum();
    }
    else
    {
        return items1.Select((Parameter p, int i) => p.Equals(items2[i]) ? 1 : 0).Sum();
    }
}

public class SymbolTableRoot
{
    public Symboltable SymbolTable { get; set; }
}

public class Symboltable
{
    public Method[] methods { get; set; }
}

public class Method
{
    public Annotation[] annotations { get; set; }
    public Location location { get; set; }
    public string[] modifiers { get; set; }
    public string name { get; set; }
    public Parameter[] parameters { get; set; }
    public object[] references { get; set; }
    public string returnType { get; set; }
    public object type { get; set; }
}

public class Location
{
    public int column { get; set; }
    public int line { get; set; }
}

public class Annotation
{
    public string name { get; set; }
}

public class Parameter : IEquatable<Parameter>
{
    public string name { get; set; }
    public string type { get; set; }

    public bool Equals(Parameter other)
    {
        return other?.name == name && other?.type == type;
    }
}
</code>```

Body:
I have a linq query that joins two tables together by matching method names. Within the table I need to look for a 'global' value and if found compare the children elements in methods called 'parameters' against each other assuring that both the tables has an equal counterpart and if one methods parameters does not match any of the others then returns false.

Below is an example of the results. We can see that seqEquals has found a 'method' that does not equal any of the others, however, the LINQ query returns all values and I'd like to only extract on false of 'seqEquals' I have tried putting the string compare within the 'where' clause however the results did not compare all against each other as expected.

{ mOneName = GetItemsJSON, seqEqual = False, mOneParm = [
  {
    "name": "itemTypes",
    "type": "List"
  },
  {
    "name": "textSearch",
    "type": "String"
  }
], mTwoParm = [
  {
    "name": "propertyId",
    "type": "String"
  },
  {
    "name": "revClassIds",
    "type": "List"
  },
  {
    "name": "itemTypes",
    "type": "List"
  },
  {
    "name": "textSearch",
    "type": "String"
  },
  {
    "name": "eventId",
    "type": "String"
  }
] }

The C# code

        var ST1 = firstOrgST["records"][0]["SymbolTable"]["methods"];
        var ST2 = secondOrgST["records"][0]["SymbolTable"]["methods"];

        // joins both tables and pulls the methods containing global from the joins
        var STDiff =
            from one in ST1
            join two in ST2
                on one.Value<String>("name") equals two.Value<string>("name")
            where one["modifiers"].Values().Contains("global")
            select new
            {
                mOneName = one["name"],
                seqEqual = one["parameters"].ToString() == two["parameters"].ToString(),
                mOneParm = one["parameters"],
                mTwoParm = two["parameters"]
            };

        var errorFound = false;
        var errorMethod = "";

        foreach (var i in STDiff)
        {    Console.WriteLine(i);
            if (!i.seqEqual)
            {
                errorFound = true;
                errorMethod = i.mOneName.ToString();
                break;
            }
        }

        // if error is found prints to console the class name as well as the method name
        if (errorFound)
        {
            Console.WriteLine(Path.GetFileNameWithoutExtension(symbolTable) + " on method: " + errorMethod + " has different parameters.\n");
            isDifferent = true;
        }

Example of data: This is table one. Table two may have different params

{
  "SymbolTable": {
    "methods": [
      {
        "annotations": [
          {
            "name": "TestVisible"
          }
        ],
        "location": {
          "column": 20,
          "line": 1056
        },
        "modifiers": [
          "private"
        ],
        "name": "GetItemsJSON",
        "parameters": [
          {
            "name": "propertyId",
            "type": "String"
          },
          {
            "name": "revClassIds",
            "type": "List"
          },
          {
            "name": "itemTypes",
            "type": "List"
          },
          {
            "name": "itemCategories",
            "type": "List"
          },
          {
            "name": "textSearch",
            "type": "String"
          },
          {
            "name": "eventId",
            "type": "String"
          }
        ],
        "references": [],
        "returnType": "String",
        "type": null
      },
      {
        "annotations": [],
        "location": {
          "column": 26,
          "line": 4313
        },
        "modifiers": [
          "static",
          "global"
        ],
        "name": "GetItemsJSON",
        "parameters": [
          {
            "name": "itemTypes",
            "type": "List"
          },
          {
            "name": "textSearch",
            "type": "String"
          }
        ],
        "references": [],
        "returnType": "String",
        "type": null
      },
      {
        "annotations": [],
        "location": {
          "column": 26,
          "line": 4316
        },
        "modifiers": [
          "static",
          "global"
        ],
        "name": "GetItemsJSON",
        "parameters": [
          {
            "name": "propertyId",
            "type": "String"
          },
          {
            "name": "revClassIds",
            "type": "List"
          },
          {
            "name": "itemTypes",
            "type": "List"
          },
          {
            "name": "textSearch",
            "type": "String"
          },
          {
            "name": "eventId",
            "type": "String"
          }
        ]
      }
    ]
  }
}

Body:
I'd recommend you convert your datatable into a list of objects and then run your linq query.

1) Use a generic method like this for conversion of DataTable to list of objects

private static List<T> ConvertDataTable<T>(DataTable dt)
{
    List<T> data = new List<T>();
    foreach (DataRow row in dt.Rows)
    {
        T item = GetItem<T>(row);
        data.Add(item);
    }
    return data;
}

private static T GetItem<T>(DataRow dr)
{
    Type temp = typeof(T);
    T obj = Activator.CreateInstance<T>();

    foreach (DataColumn column in dr.Table.Columns)
    {
        foreach (PropertyInfo pro in temp.GetProperties())
        {
            if (pro.Name == column.ColumnName)
                pro.SetValue(obj, dr[column.ColumnName], null);
            else
                continue;
        }
    }
    return obj;
}

2) Use Linq query like this on the list of objects

    var ST1 = myTableData.ToList();
    var ST2 = myTableData.ToList();

    var STDiff = from one in ST1
                 join two in ST2
                 on one.name equals two.name
                 where one.modifiers.Contains("global")
            select new
            {
                mOneName = one.name,
                seqEqual = CompareParamsAndGetMatchingIndex(one.parameters, two.parameters),
                mOneParm = one.parameters,
                mTwoParm = two.parameters
            };

private int CompareParamsAndGetMatchingIndex(Parameter[] items1, Parameter[] items2)
{
    if (items1.Length > items2.Length)
    {
        return items2.Select((Parameter p, int i) => p.Equals(items1[i]) ? 1 : 0).Sum();
    }
    else
    {
        return items1.Select((Parameter p, int i) => p.Equals(items2[i]) ? 1 : 0).Sum();
    }
}

public class SymbolTableRoot
{
    public Symboltable SymbolTable { get; set; }
}

public class Symboltable
{
    public Method[] methods { get; set; }
}

public class Method
{
    public Annotation[] annotations { get; set; }
    public Location location { get; set; }
    public string[] modifiers { get; set; }
    public string name { get; set; }
    public Parameter[] parameters { get; set; }
    public object[] references { get; set; }
    public string returnType { get; set; }
    public object type { get; set; }
}

public class Location
{
    public int column { get; set; }
    public int line { get; set; }
}

public class Annotation
{
    public string name { get; set; }
}

public class Parameter : IEquatable<Parameter>
{
    public string name { get; set; }
    public string type { get; set; }

    public bool Equals(Parameter other)
    {
        return other?.name == name && other?.type == type;
    }
}


问:
How to create android service to check if user open another app
I want to know if its possible do that, for example an app that you press in a button and the service is on, and when you are using your device and press in Youtube app , the service can know about this.

Im trying with a service of an instant message app but i dont know how to use this with the other function.

For example:

'' startService();
'' minimize app

User click on Youtube app.

'' The service now know that user open youtube 1 time.

And i want to know too if is possible use this service when the user turn on the device... I dont know if its possible on Android

答:
To obtain app usage statistics you can use UsageStats class from android.app.usage package.

The new App usage statistics API allows app developers to collect statistics related to usage of the applications. This API provides more detailed usage information than the deprecated getRecentTasks() method.

To use this API, you must first declare the android.permission.PACKAGE_USAGE_STATS permission in your manifest. The user must also enable access for this app through Settings > Security > Apps with usage access.

Here is a basic app example showing how to use App usage statistics API to let users collect statistics related to usage of the applications.


问:
Error while adding a new remote repository in JFrog's Artifactory
I have requested for a trial version of JFrog Artifactory and trying to a new remote repository via the admin UI.

For example, I am adding the https://jcenter.bintray.com/ but I am getting an error saying "Error parsing json body" in UI.

```<code>2019-05-28 15:03:28,714 [http-nio-8081-exec-10] [ERROR] (o.a.r.c.e.JsonMappingExceptionMapper:23) - Error parsing json body
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.lang.Integer from String value 'admin': not a valid Integer value
 at [Source: org.apache.catalina.connector.CoyoteInputStream@133a043d; line: 1, column: 400] (through reference chain: org.artifactory.ui.rest.model.admin.configuration.repository.remote.RemoteRepositoryConfigModel["typeSpecific"]->org.artifactory.ui.rest.model.admin.configuration.repository.typespecific.MavenTypeSpecificConfigModel["maxUniqueSnapshots"])
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.weirdStringException(StdDeserializationContext.java:243)
    at org.codehaus.jackson.map.deser.std.StdDeserializer._parseInteger(StdDeserializer.java:321)
    at org.codehaus.jackson.map.deser.std.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:818)
    at org.codehaus.jackson.map.deser.std.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:805)
    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
    at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:600)
    at org.codehaus.jackson.map.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:92)
    at org.codehaus.jackson.map.deser.AbstractDeserializer.deserializeWithType(AbstractDeserializer.java:52)
    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:297)
    at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:600)
    at org.codehaus.jackson.map.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:92)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeWithType(BeanDeserializer.java:664)
    at org.codehaus.jackson.map.deser.StdDeserializerProvider$WrappedDeserializer.deserialize(StdDeserializerProvider.java:461)
    at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2704)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1315)
    at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:419)
    at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
    at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
    at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:86)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.RepoFilter.execute(RepoFilter.java:183)
    at org.artifactory.webapp.servlet.RepoFilter.doFilter(RepoFilter.java:93)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.AccessFilter.useAuthentication(AccessFilter.java:433)
    at org.artifactory.webapp.servlet.AccessFilter.doFilterInternal(AccessFilter.java:215)
    at org.artifactory.webapp.servlet.AccessFilter.doFilter(AccessFilter.java:168)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.RequestFilter.doFilter(RequestFilter.java:78)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.ArtifactoryCsrfFilter.doFilter(ArtifactoryCsrfFilter.java:66)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:164)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.artifactory.webapp.servlet.SessionFilter.doFilter(SessionFilter.java:62)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.ArtifactoryFilter.doFilter(ArtifactoryFilter.java:124)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    at org.apache.catalina.valves.rewrite.RewriteValve.invoke(RewriteValve.java:279)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Please let me know what I am doing wrong here and is authentication required inorder to connect to any remote repo?

答:
In the field Max Unique Snapshot (righthand side of the screenshot you pasted), you've entered an incorrect value. Right now it shows the value admin and it should be either an integer or a blank value.

To answer your second question, authentication isn't required to set up JCenter as a remote repository.

Body:
I have requested for a trial version of JFrog Artifactory and trying to a new remote repository via the admin UI.

For example, I am adding the https://jcenter.bintray.com/ but I am getting an error saying "Error parsing json body" in UI.

2019-05-28 15:03:28,714 [http-nio-8081-exec-10] [ERROR] (o.a.r.c.e.JsonMappingExceptionMapper:23) - Error parsing json body
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.lang.Integer from String value 'admin': not a valid Integer value
 at [Source: org.apache.catalina.connector.CoyoteInputStream@133a043d; line: 1, column: 400] (through reference chain: org.artifactory.ui.rest.model.admin.configuration.repository.remote.RemoteRepositoryConfigModel["typeSpecific"]->org.artifactory.ui.rest.model.admin.configuration.repository.typespecific.MavenTypeSpecificConfigModel["maxUniqueSnapshots"])
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.weirdStringException(StdDeserializationContext.java:243)
    at org.codehaus.jackson.map.deser.std.StdDeserializer._parseInteger(StdDeserializer.java:321)
    at org.codehaus.jackson.map.deser.std.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:818)
    at org.codehaus.jackson.map.deser.std.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:805)
    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
    at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:600)
    at org.codehaus.jackson.map.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:92)
    at org.codehaus.jackson.map.deser.AbstractDeserializer.deserializeWithType(AbstractDeserializer.java:52)
    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:297)
    at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:600)
    at org.codehaus.jackson.map.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:92)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeWithType(BeanDeserializer.java:664)
    at org.codehaus.jackson.map.deser.StdDeserializerProvider$WrappedDeserializer.deserialize(StdDeserializerProvider.java:461)
    at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2704)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1315)
    at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:419)
    at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
    at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
    at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:86)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.RepoFilter.execute(RepoFilter.java:183)
    at org.artifactory.webapp.servlet.RepoFilter.doFilter(RepoFilter.java:93)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.AccessFilter.useAuthentication(AccessFilter.java:433)
    at org.artifactory.webapp.servlet.AccessFilter.doFilterInternal(AccessFilter.java:215)
    at org.artifactory.webapp.servlet.AccessFilter.doFilter(AccessFilter.java:168)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.RequestFilter.doFilter(RequestFilter.java:78)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.ArtifactoryCsrfFilter.doFilter(ArtifactoryCsrfFilter.java:66)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:164)
    at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
    at org.artifactory.webapp.servlet.SessionFilter.doFilter(SessionFilter.java:62)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.artifactory.webapp.servlet.ArtifactoryFilter.doFilter(ArtifactoryFilter.java:124)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
    at org.apache.catalina.valves.rewrite.RewriteValve.invoke(RewriteValve.java:279)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Please let me know what I am doing wrong here and is authentication required inorder to connect to any remote repo?


问:
Error when creation data source for neo4j in websphere application server
Im trying to create data source for neo4j in websphere application server but its failing to connect. Any pointers on this would be helpful.

JDBC Driver Created with the following parameters:

Name : neo4j Driver

Class path : path of the neo4j jdbc jar/neo4j-jdbc-driver-3.3.1.jar

Implementation class name : org.neo4j.jdbc.Driver

Data source created with the following :

jndi Name: jdbc/neo4j

Custom Properties:

auth : container

type: javax.sql.DataSource

username: neo4j

password: password

url:jdbc:neo4j:bolt://localhost:port

removeAbandonedOnBorrow : true

closeMethod : close

The properties are added based on the pointers provided in https://github.com/neo4j-contrib/neo4j-jdbc

Here is the error from logs:

java.lang.Exception: DSRA8101E: DataSource class cannot be used as
  one-phase: ClassCastException: org.neo4j.jdbc.bolt.BoltDriver
  incompatible with javax.sql.ConnectionPoolDataSource [5/27/19
  13:12:41:533 UTC] 00000111 SystemErr     R     at
  com.ibm.ws.rsadapter.AdapterUtil.createDataStoreAdapterException(AdapterUtil.java:441)
  [5/27/19 13:12:41:533 UTC] 00000111 SystemErr     R     at
  com.ibm.ws.rsadapter.DSConfigHelper.getPooledConnection(DSConfigHelper.java:1340)

答:
To clarify for others who may find this post in the future - whether or not it is possible to directly configure to java.sql.Driver depends on whether WebSphere Application Server traditional vs Liberty is being used.

A more indirect approach is possible in WebSphere Application Server traditional, which involves mocking up a ConnectionPoolDataSource class around the driver.  It is discussed under a related stack overflow post.

With Liberty 18.0.0.3 and above, it is possible to directly configure a dataSource specifying only the URL, with examples given under this knowledge center document.

Here is an example dataSource configuration in Liberty,

```<code><featureManager>
  <feature>jdbc-4.2</feature>
  <feature>jndi-1.0</feature>
  ... other features
</featureManager>

<dataSource jndiName="jdbc/neo4j" containerAuthDataRef="neo4jAuth">
  <jdbcDriver libraryRef="neo4j"/>
  <properties URL="jdbc:neo4j:bolt://localhost:7687"/>
</dataSource>

<authData id="neo4jAuth" user="neo4j" password="password"/>

<library>
  <file name="C:/drivers/neo4j/neo4j-jdbc-driver-3.3.1.jar"/>
</library>
</code>```

Body:
To clarify for others who may find this post in the future - whether or not it is possible to directly configure to java.sql.Driver depends on whether WebSphere Application Server traditional vs Liberty is being used.

A more indirect approach is possible in WebSphere Application Server traditional, which involves mocking up a ConnectionPoolDataSource class around the driver.  It is discussed under a related stack overflow post.

With Liberty 18.0.0.3 and above, it is possible to directly configure a dataSource specifying only the URL, with examples given under this knowledge center document.

Here is an example dataSource configuration in Liberty,

<featureManager>
  <feature>jdbc-4.2</feature>
  <feature>jndi-1.0</feature>
  ... other features
</featureManager>

<dataSource jndiName="jdbc/neo4j" containerAuthDataRef="neo4jAuth">
  <jdbcDriver libraryRef="neo4j"/>
  <properties URL="jdbc:neo4j:bolt://localhost:7687"/>
</dataSource>

<authData id="neo4jAuth" user="neo4j" password="password"/>

<library>
  <file name="C:/drivers/neo4j/neo4j-jdbc-driver-3.3.1.jar"/>
</library>


问:
How can you not consume messages in a particular environment?
I used spring-cloud-starter-stream-kafka 2.1.2
Consumers for the corresponding topic have been written and deployed to the test environment.
Then I use @conditional to exclude local consumers, and the following error will always appear:

```<code>@Component
@Slf4j
@Conditional(NotWindowsCondition.class)
public class TestListener {
    @StreamListener(TestSink.INPUT)
</code>```

```<code>org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'application-1.input'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=byte[38], headers={deliveryAttempt=3, X-B3-ParentSpanId=41e8fe9d35f75986, kafka_timestampType=CREATE_TIME, kafka_receivedTopic=user_huanxin_register, spanTraceId=1c2878998d138740, spanId=34cbd18294b7858d, spanParentSpanId=41e8fe9d35f75986, nativeHeaders={spanTraceId=[1c2878998d138740], spanId=[8654b6a6c4aa8517], spanParentSpanId=[3df3fa4e69033f5e], spanSampled=[0], X-B3-TraceId=[1c2878998d138740], X-B3-SpanId=[8654b6a6c4aa8517], X-B3-ParentSpanId=[3df3fa4e69033f5e], X-B3-Sampled=[0]}, kafka_offset=74, X-B3-SpanId=34cbd18294b7858d, scst_nativeHeadersPresent=true, kafka_consumer=org.apache.kafka.clients.consumer.KafkaConsumer@16c73ae4, X-B3-Sampled=0, X-B3-TraceId=1c2878998d138740, id=201aaf99-082b-864f-8129-de7961e03972, kafka_receivedPartitionId=0, spanSampled=0, kafka_receivedTimestamp=1559041573040, contentType=application/json, timestamp=1559041580558}]
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:453)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:401)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)
</code>```

I tried to find a configuration to specify consumption or not consumption, but did not find it

Desired results: Enables a specific environment to consume or not consume without error messages

答:
Set the auto-startup property to false.

@SpringBootApplication
@EnableBinding(Sink.class)
public class So56341052Application {

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

}

@Component
@ConditionalOnProperty("is.enabled")
class Listener {

    @StreamListener(Sink.INPUT)
    public void listen(String in) {

    }

}
```

```is.enabled=false

spring.cloud.stream.bindings.input.consumer.auto-startup=${is.enabled}
```

Body:
I used spring-cloud-starter-stream-kafka 2.1.2
Consumers for the corresponding topic have been written and deployed to the test environment.
Then I use @conditional to exclude local consumers, and the following error will always appear:

@Component
@Slf4j
@Conditional(NotWindowsCondition.class)
public class TestListener {
    @StreamListener(TestSink.INPUT)

org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'application-1.input'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=byte[38], headers={deliveryAttempt=3, X-B3-ParentSpanId=41e8fe9d35f75986, kafka_timestampType=CREATE_TIME, kafka_receivedTopic=user_huanxin_register, spanTraceId=1c2878998d138740, spanId=34cbd18294b7858d, spanParentSpanId=41e8fe9d35f75986, nativeHeaders={spanTraceId=[1c2878998d138740], spanId=[8654b6a6c4aa8517], spanParentSpanId=[3df3fa4e69033f5e], spanSampled=[0], X-B3-TraceId=[1c2878998d138740], X-B3-SpanId=[8654b6a6c4aa8517], X-B3-ParentSpanId=[3df3fa4e69033f5e], X-B3-Sampled=[0]}, kafka_offset=74, X-B3-SpanId=34cbd18294b7858d, scst_nativeHeadersPresent=true, kafka_consumer=org.apache.kafka.clients.consumer.KafkaConsumer@16c73ae4, X-B3-Sampled=0, X-B3-TraceId=1c2878998d138740, id=201aaf99-082b-864f-8129-de7961e03972, kafka_receivedPartitionId=0, spanSampled=0, kafka_receivedTimestamp=1559041573040, contentType=application/json, timestamp=1559041580558}]
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:453)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:401)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:187)
    at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:166)

I tried to find a configuration to specify consumption or not consumption, but did not find it

Desired results: Enables a specific environment to consume or not consume without error messages

Body:
Set the auto-startup property to false.

@SpringBootApplication
@EnableBinding(Sink.class)
public class So56341052Application {

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

}

@Component
@ConditionalOnProperty("is.enabled")
class Listener {

    @StreamListener(Sink.INPUT)
    public void listen(String in) {

    }

}

is.enabled=false

spring.cloud.stream.bindings.input.consumer.auto-startup=${is.enabled}


问:
R - How to create a data frame from a data frame with conditions?
I have a data frame that has many columns, but I want to create another data frame that only has the columns race and spouse. I have this sample of data.

```<code>  gender name    race realm  spouse
1  Female Adanel  Men  Gondor  Not Married
2  Male   Lagduf  Orc  Mordor  Married
2  Male   Boromir Men  Gondor  Married
</code>```

I would like to create another data frame with race and spouse (where the creature is "married") so that I can plot a graph from it showing the marriage variation between races. The only data that should appear in the new data frame would be the following one:

```<code>  race spouse
1 Orc  Married
2 Men  Married
</code>```

I would like to get the columns race and spouse(where the creature is "Married"). I have tried something like this:

```<code>marriedCreatures <- data %>% filter(spouse == "Married" & race)
</code>```

As I've recently started working with R I don't know how I am supposed to create this new data frame from other data frame's columns.

I would appreciate if anyone could help me with that.

Thanks!

答:
An option with base R

```<code>subset(df, spouse == "Married", select = c("race", "spouse"))
</code>```

Body:
I have a data frame that has many columns, but I want to create another data frame that only has the columns race and spouse. I have this sample of data.

  gender name    race realm  spouse
1  Female Adanel  Men  Gondor  Not Married
2  Male   Lagduf  Orc  Mordor  Married
2  Male   Boromir Men  Gondor  Married

I would like to create another data frame with race and spouse (where the creature is "married") so that I can plot a graph from it showing the marriage variation between races. The only data that should appear in the new data frame would be the following one:

  race spouse
1 Orc  Married
2 Men  Married

I would like to get the columns race and spouse(where the creature is "Married"). I have tried something like this:

marriedCreatures <- data %>% filter(spouse == "Married" & race)

As I've recently started working with R I don't know how I am supposed to create this new data frame from other data frame's columns.

I would appreciate if anyone could help me with that.

Thanks!

Body:
An option with base R

subset(df, spouse == "Married", select = c("race", "spouse"))


问:
Dealing with Impedence Mismatch with Linq-to-Sql XML Mapping Source
I am attempting to implement Linq-to-SQL as the data access technology (ORM tool) on a DDD project.  L2S was not my choice, but it is what I have to work with (for now).

Following DDD, I have my domain model already created and it is not going to match my normalized database schema. (Nothing unusual here).  I am trying to implement L2S to use my domain objects as POCOs using the external XML mapping file as the MappingSource for my DataContext.  All of this is well and good until I run into more complex mapping.

In my domain layer I have an Appointment class which has a child property of type Recurrence.  Recurrence is a base class and the actual implementation is provided by various subclasses depending on the type of the recurrence pattern.  From code, I can create the appropriate subclass using the RecurrenceFactory class.  However, in my database, I simply have an Appointment table which has two columns: RecurrenceType and RecurrenceValue.

How do I setup the XML mapping file to use the RecurrenceFactory to create the appropriate subclass using the RecurrenceType and RecurrenceValue columns from the database?

If this is not do-able, then I have to completely change direction for my implementation.  Your thoughts are appreciated!

答:
I hate answering my own questions but since no one else has chimed in, and I hate an unanswered question more, here goes...

Based on the discussion in this post, How to make POCO work with Linq-to-SQL with complex relationships in DDD, it looks like the problem isn't with the XML Mapping file but with Ling-to-SQL itself not supporting anything beyond a class-per-table approach.


问:
Lazy __FILE__ and __LINE__ Population
So I have a function which I want to evaluate a result, and if the result is a failure the function will log the file and line number:

```<code>void foo(const bool is_failure, const char* file = __FILE__, const int line = __LINE__) {
    if(is_failure) cout << "Failure returned at " << file << '#' << line << endl;
}
</code>```

I can call this like foo(func()) and if func returns true then foo will log out failure. The problem is that the file and line parameters are returning the file and line that foo is declared at. Is there a way that I can accomplish this other than using a macro?

答:
Is there a way that I can accomplish this ...

Yes.

You can write a function-like macro that expands into a function call, and passes __FILE__ and __LINE__ as arguments. Since the macro is expanded at call site, that's the line which populates those macros:

```<code>#define FOO(arg) foo((arg), __FILE__, __LINE__);
</code>```

... other than using a macro?

I don't think so. __FILE__ and __LINE__ are pre processor macros. Pre processing always happens before compilation.

Equivalent functionality is not implementable in standard C++ without (those) macros. A non-macro feature std::source_location has been proposed in n4519 as a Technical Specification. When passed as a default argument, it will be populated by the call site. Example from the proposal:

```<code>struct s {
    source_location member = source_location::current();
    int other_member;

    s(source_location loc = source_location::current())
        : member(loc)   // values of member will be from call-site
    {}

    s(int blather)      // values of member should be hereabouts
        : other_member(blather)
    {}

    s(double)           // values of member should be hereabouts
    {}
};
</code>```

Adapted for your function:

```<code>void foo(const bool is_failure, source_location loc = source_location::current());
</code>```

Until (and unless) this feature is incorporated into the standard, you can rely on either a macro, or implementation specific features such as __builtin_LINE and__builtin_FILE in GCC that make it possible to implement std::source_location or equivalent.

Title: Lazy __FILE__ and __LINE__ Population

Body:
So I have a function which I want to evaluate a result, and if the result is a failure the function will log the file and line number:

void foo(const bool is_failure, const char* file = __FILE__, const int line = __LINE__) {
    if(is_failure) cout << "Failure returned at " << file << '#' << line << endl;
}

I can call this like foo(func()) and if func returns true then foo will log out failure. The problem is that the file and line parameters are returning the file and line that foo is declared at. Is there a way that I can accomplish this other than using a macro?

Body:
Is there a way that I can accomplish this ...

Yes.

You can write a function-like macro that expands into a function call, and passes __FILE__ and __LINE__ as arguments. Since the macro is expanded at call site, that's the line which populates those macros:

#define FOO(arg) foo((arg), __FILE__, __LINE__);

... other than using a macro?

I don't think so. __FILE__ and __LINE__ are pre processor macros. Pre processing always happens before compilation.

Equivalent functionality is not implementable in standard C++ without (those) macros. A non-macro feature std::source_location has been proposed in n4519 as a Technical Specification. When passed as a default argument, it will be populated by the call site. Example from the proposal:

struct s {
    source_location member = source_location::current();
    int other_member;

    s(source_location loc = source_location::current())
        : member(loc)   // values of member will be from call-site
    {}

    s(int blather)      // values of member should be hereabouts
        : other_member(blather)
    {}

    s(double)           // values of member should be hereabouts
    {}
};

Adapted for your function:

void foo(const bool is_failure, source_location loc = source_location::current());

Until (and unless) this feature is incorporated into the standard, you can rely on either a macro, or implementation specific features such as __builtin_LINE and__builtin_FILE in GCC that make it possible to implement std::source_location or equivalent.


问:
Embedding dynamic script when page scrolls
I am trying to add an iframe which consist of form . I am inserting this iframe when the page is loaded already and scrolled at some position ,I have used jquery this script is working fine it appending that script tag  under that div but the thing it should load iframe at that place.  please help out

please point out whats wrong in this question

i found that iframe is generated by script its not loaded first itself

$(document).ready(function() {
  var element_position = $('#Banner').offset().top;

  $(window).one('scroll', function() {

    if (y_scroll_pos < 300) {
      //do stuff
      $('#form1').load("http://www.samisite.com/test-csb2nf/ifform/somejsthatgenrateiframe");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="Banner"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-in">
  <script id="form1"></script></code>```

答:
Just see this fiddle https://jsfiddle.net/qmad1uLo

There were follwoing mistakes in your code.

You've used # in the id attribute, which is invalid

You're appending the script tag inside another script tag, which is not allowed.

The main problem is that maybe you're running your main site on https but the frame is loaded on http, so what can you do is that, run your website on http or try to load the iframe on https if possible, then try the above fiddle, it should work like charm.


问:
Custom validator in Template driven forms for Angular 2.4
Can anyone please share an example of how to create a custom validator for template driven forms in Angular 2.4?</p>

答:
You can create a directive for this and here is an example:

Then you can use it in your template like here:

```<code><input myCustomValidation [(ngModel)]="MyValue" #myValue="ngModel">
</code>```

You can also add additional fields to your validation like this:

```<code>validate(formGroup: FormGroup): ValidationErrors {
  const passwordControl = formGroup.controls["password"];
  const emailControl = formGroup.controls["login"];

  // for example check if email and password fields have value
  if (!passwordControl || !emailControl || !passwordControl.value || !emailControl.value) {
    return null;
  }

  // do validation here using passwordControl.value and emailControl.value

  return formGroup;
}
</code>```

Body:
You can create a directive for this and here is an example:

Then you can use it in your template like here:

<input myCustomValidation [(ngModel)]="MyValue" #myValue="ngModel">

You can also add additional fields to your validation like this:

validate(formGroup: FormGroup): ValidationErrors {
  const passwordControl = formGroup.controls["password"];
  const emailControl = formGroup.controls["login"];

  // for example check if email and password fields have value
  if (!passwordControl || !emailControl || !passwordControl.value || !emailControl.value) {
    return null;
  }

  // do validation here using passwordControl.value and emailControl.value

  return formGroup;
}


问:
Error: Required package curl not found. Please run: install.packages('curl') Execution halted on Travis CI
An R package works fine (and passes CRAN checks), but when Travis CI runs unit tests it errors with

```<code>Error: Required package curl not found. Please run: install.packages('curl')
Execution halted
</code>```

This seems to be an issue particular to Ubuntu. I can see here that running sudo apt-get install libcurl4-openssl-dev can fix the issue. The trouble is I don't have access to the Ubuntu console (as Travis CI does everything after I push to git) - can I place this code somewhere? E.g. can it go in .travis.yml somehow, and if so, how?

The current .travis.yml file is just 2 lines and looks like this

```<code>language: R
cache: packages
</code>```

Note

Based on this question/answer, I tried adjusting .travis.yml to

```<code>language: R
cache: packages
before_install:
  - sudo apt-get install libcurl4-openssl-dev
</code>```

I can see from the build logs that sudo apt-get install libcurl4-openssl-dev ran, but the build errored in the same way as before regardless

Also note

I also tried

```<code>language: R
cache: packages
before_install:
    -sudo apt-get update
</code>```

Based on this suggestion, but the same error persisted

答:
The problem went away by adding curl to imports (i.e. in DESCRIPTION)

e.g.

Imports: dplyr, gsubfn, stringr, purrr, jsonlite, stats, lubridate, curl

If you have a helper file in testthat, don't forget to load the package there too i.e. simply library(curl). Then the tests should be able to run as expected

Body:
An R package works fine (and passes CRAN checks), but when Travis CI runs unit tests it errors with

Error: Required package curl not found. Please run: install.packages('curl')
Execution halted

This seems to be an issue particular to Ubuntu. I can see here that running sudo apt-get install libcurl4-openssl-dev can fix the issue. The trouble is I don't have access to the Ubuntu console (as Travis CI does everything after I push to git) - can I place this code somewhere? E.g. can it go in .travis.yml somehow, and if so, how?

The current .travis.yml file is just 2 lines and looks like this

language: R
cache: packages

Note

Based on this question/answer, I tried adjusting .travis.yml to

language: R
cache: packages
before_install:
  - sudo apt-get install libcurl4-openssl-dev

I can see from the build logs that sudo apt-get install libcurl4-openssl-dev ran, but the build errored in the same way as before regardless

Also note

I also tried

language: R
cache: packages
before_install:
    -sudo apt-get update

Based on this suggestion, but the same error persisted


问:
How to convert an rtf string to text in C#
Is there an easy way to extract text from an Rtf string without using RichTextBox?

Example:

```<code>{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\lang2070\ltrch foo}\li0\ri0\sa0\sb0\fi0\ql\par}
{\f2 {\lang2070\ltrch bar }\li0\ri0\sa0\sb0\fi0\ql\par}
}
}
</code>```

should return:

```<code>foo
bar
</code>```

答:
There's a simple article on MSDN to achieve what you want: http://msdn.microsoft.com/en-us/library/cc488002.aspx</p>

```<code>class ConvertFromRTF
{
    static void Main()
    {

        string path = @"test.rtf";

        //Create the RichTextBox. (Requires a reference to System.Windows.Forms.dll.)
        System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox();

        // Get the contents of the RTF file. Note that when it is
        // stored in the string, it is encoded as UTF-16.
        string s = System.IO.File.ReadAllText(path);

        // Display the RTF text.
        System.Windows.Forms.MessageBox.Show(s);

        // Convert the RTF to plain text.
        rtBox.Rtf = s;
        string plainText = rtBox.Text;

        // Display plain text output in MessageBox because console
        // cannot display Greek letters.
        System.Windows.Forms.MessageBox.Show(plainText);

        // Output plain text to file, encoded as UTF-8.
        System.IO.File.WriteAllText(@"output.txt", plainText);
    }
}
</code>```

Body:
Is there an easy way to extract text from an Rtf string without using RichTextBox?

Example:

{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 {\lang2070\ltrch foo}\li0\ri0\sa0\sb0\fi0\ql\par}
{\f2 {\lang2070\ltrch bar }\li0\ri0\sa0\sb0\fi0\ql\par}
}
}

should return:

foo
bar

Body:
There's a simple article on MSDN to achieve what you want: http://msdn.microsoft.com/en-us/library/cc488002.aspx

class ConvertFromRTF
{
    static void Main()
    {

        string path = @"test.rtf";

        //Create the RichTextBox. (Requires a reference to System.Windows.Forms.dll.)
        System.Windows.Forms.RichTextBox rtBox = new System.Windows.Forms.RichTextBox();

        // Get the contents of the RTF file. Note that when it is
        // stored in the string, it is encoded as UTF-16.
        string s = System.IO.File.ReadAllText(path);

        // Display the RTF text.
        System.Windows.Forms.MessageBox.Show(s);

        // Convert the RTF to plain text.
        rtBox.Rtf = s;
        string plainText = rtBox.Text;

        // Display plain text output in MessageBox because console
        // cannot display Greek letters.
        System.Windows.Forms.MessageBox.Show(plainText);

        // Output plain text to file, encoded as UTF-8.
        System.IO.File.WriteAllText(@"output.txt", plainText);
    }
}


问:
How to rename a CSV file from a value in the CSV file
I have 100 1-line CSV files. The files are currently labeled AAA.txt, AAB.txt, ABB.txt (after I used split -l 1 on them). The first field in each of these files is what I want to rename the file as, so instead of AAA, AAB and ABB it would be the first value.

Input CSV (filename AAA.txt)

```<code>1234ABC, stuff, stuff
</code>```

Desired Output (filename 1234ABC.csv)

```<code>1234ABC, stuff, stuff
</code>```

I don't want to edit the content of the CSV itself, just change the filename

答:
In a terminal, changed directory, e.g. cd /path/to/directory that the files are in and then use the following compound command:

```<code>for f in *.txt; do echo mv -n "$f" "$(awk -F, '{print $1}' "$f").cvs"; done
</code>```

Note: There is an intensional echo command that is there for you to test with, and it will only print out the mv command for you to see that it's the outcome you wish. You can then run it again removing just echo from the compound command to actually rename the files as desired via the mv command.

Body:
I have 100 1-line CSV files. The files are currently labeled AAA.txt, AAB.txt, ABB.txt (after I used split -l 1 on them). The first field in each of these files is what I want to rename the file as, so instead of AAA, AAB and ABB it would be the first value.

Input CSV (filename AAA.txt)

1234ABC, stuff, stuff

Desired Output (filename 1234ABC.csv)

1234ABC, stuff, stuff

I don't want to edit the content of the CSV itself, just change the filename

Body:
In a terminal, changed directory, e.g. cd /path/to/directory that the files are in and then use the following compound command:

for f in *.txt; do echo mv -n "$f" "$(awk -F, '{print $1}' "$f").cvs"; done

Note: There is an intensional echo command that is there for you to test with, and it will only print out the mv command for you to see that it's the outcome you wish. You can then run it again removing just echo from the compound command to actually rename the files as desired via the mv command.


问:
Regex to load integer number of "key value" pairs e.g. 3 key1 "value1" key2 "value2" key3 "value3"
I'm struggling to create a regex to parse a line which contains an integer number of values following an integer, can get it mostly working but not for the case when there the integer is zero and no values following.

e.g.

```<code>..... 2 "value1" "value2" "someother non-related text"
..... 0 "someother non-related text"
</code>```

Also an integer number of space-separated key value pairs following the integer number or

```<code>..... 3 key1 "value1" key2 "value2" key3 "value3"......
</code>```

Happy to stuff them in a single named group but might be useful at a later date to have them in separate named groups.

```<code>3 "value1" "value2" "value3" "someother non-related text"

(?<my_named_group>([0])|[0-9] (?<my_values>(".*"?)?))

my_named_group = 3
my_values = '"value1" "value2" "value3"'
</code>```

and when the integer is zero

```<code>my_named_group = 0
my_values = ""
</code>```

and for the second question/regex

```<code>3 key1 "value1" key2 "value2" key3 "value3" "someother non-related text"

my_named_group = 3
my_values = 'key 1 "value1" key 2 "value2" key3 "value3"'
</code>```

答:
If I understand it right, we are having digits followed by some texts in quotes, and we can likely start solving it using a simple expression:

```<code>([0-9]+).+?(\".*\")
</code>```

where are desired digits are in the first capturing group ([0-9]+) and the other desired substring is in the second one, (\".*\").

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([0-9]+).+?(\".*\")"

test_str = ("2 \"value1\" \"value2\" \"someother non-related text\"\n"
    "0 \"someother non-related text\"\n"
    "3 key1 \"value1\" key2 \"value2\" key3 \"value3\"")

subst = "\\1\\n\\2"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

DEMO

Body:
I'm struggling to create a regex to parse a line which contains an integer number of values following an integer, can get it mostly working but not for the case when there the integer is zero and no values following.

e.g.

..... 2 "value1" "value2" "someother non-related text"
..... 0 "someother non-related text"

Also an integer number of space-separated key value pairs following the integer number or

..... 3 key1 "value1" key2 "value2" key3 "value3"......

Happy to stuff them in a single named group but might be useful at a later date to have them in separate named groups.

3 "value1" "value2" "value3" "someother non-related text"

(?<my_named_group>([0])|[0-9] (?<my_values>(".*"?)?))

my_named_group = 3
my_values = '"value1" "value2" "value3"'

and when the integer is zero

my_named_group = 0
my_values = ""

and for the second question/regex

3 key1 "value1" key2 "value2" key3 "value3" "someother non-related text"

my_named_group = 3
my_values = 'key 1 "value1" key 2 "value2" key3 "value3"'

Body:
If I understand it right, we are having digits followed by some texts in quotes, and we can likely start solving it using a simple expression:

([0-9]+).+?(\".*\")

where are desired digits are in the first capturing group ([0-9]+) and the other desired substring is in the second one, (\".*\").

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([0-9]+).+?(\".*\")"

test_str = ("2 \"value1\" \"value2\" \"someother non-related text\"\n"
    "0 \"someother non-related text\"\n"
    "3 key1 \"value1\" key2 \"value2\" key3 \"value3\"")

subst = "\\1\\n\\2"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

DEMO


问:
RaspberryPi - calling your iPhone from your RaspberryPi
I'm new to using a RaspberryPi but I've seen a large amount of videos which show a Raspberry Pi calling the user's iPhone. I'm interested and I've tried look up tutorials but due to the fact that everything is new to me/my lack of knowledge, I'm getting nowhere.

I was wondering if anyone could give me a hand in understanding what's meant by the different VoIP, PBX, SIP client etc termonology and how I can set it up myself.

答: Try twilio it can make phone calls in python.</p>