问:
MONGODB Simple query too long to be executed why?
My query takes a lot of time ....

130,000 documents -> 70ms (local)

11,000 documents -> 80ms (local)

1,600 documents -> 2ms (local) (other base, more complex query)

Why do the first two put so much time compared to the third much more complex?

Query with 130.000 documents (60-69ms)

```<code>{
    "_id" : ObjectId("58e669e81a5696098804e0ae"),
    "target" : "mysuperlogin",
    "type" : "auth",
    "key" : "try",
    "useragent" : "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27",
    "ip" : "X.X.X.X",
    "creation_date" : ISODate("2017-04-06T16:16:40.584Z"),
    "__v" : 0
}

db.collection.aggregate(
[
    {
        $match:
        {
            'type':          'auth',
            'target':        params.authlogin,
            'ip':            'X.X.X.X',
            'creation_date': { $gte: date }
        },
        { $group: { _id: '$key', total: { $sum: 1 } } },
        { $sort:   { _id: -1 }}
    }
])
</code>```

Query with 11.000 documents (77-90ms)

```<code>{
    "_id" : ObjectId("5a2a6b17aafee9dcf4000422"),
    "target" : "mysuperlogin",
    "type" : "auth",
    "key" : "try",
    "useragent" : "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27",
    "events" : [
        {
            "creation_date" : ISODate("2017-12-05T08:45:37.217Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:37.010Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:37.111Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:39.759Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:40.054Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:47:36.471Z"),
            "ip" : "X.X.X.X"
        }
    ]
}

db.collection.aggregate(
[
    {
        $match:
        {
            'type':                 'auth',
            'target':               'mysuperlogin',
            'events.ip':            'X.X.X.X',
            'events.creation_date': { $gte: new Date('2017-12-05T08:30:00.471Z') }
        }
    },
    { $unwind: '$events' },
    { $match:  { 'events.creation_date': { $gte: new Date('2017-12-05T08:30:00.471Z') } } },
    { $group:  { _id: '$key', total: { $sum: 1 } } },
    { $sort:   { _id: -1 }}
])
</code>```

Query with 1.600 documents (3-4ms)

```<code>{
    "_id" : ObjectId("58f0ce79e07b3e6c24c5a453"),
    "groups" : [
        {
            "name" : "defaut",
            "company_id" : ObjectId("58e4f31cf8eca22e06167736"),
            "apikey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "level" : 1,
            "expire_date" : ISODate("2018-12-31T00:00:00Z"),
            "creation_date" : ISODate("2017-04-14T13:28:25.122Z")
        }
    ],
    "sessions" : [
        {
            "apikey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "token" : "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
            "ip" : "X.X.X.X",
            "expire_date" : ISODate("2017-05-14T13:35:13.533Z"),
            "_id" : ObjectId("58f0d0113675136beb64c5a1")
        },
        {
            "apikey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "tokenassets" : "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
            "ip" : "X.X.X.X",
            "expire_date" : ISODate("2017-05-14T13:35:13.533Z"),
            "_id" : ObjectId("58f0d0113675136beb64c5a1")
        }
    ],
    "infos" : {
        "login" : "mysuperlogin",
        "mail" : "mysuperlogin@mymail.com",
        "password" : "CRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTED",
        "firstname" : "my",
        "lastname" : "superlogin",
        "creation_date" : ISODate("2017-04-14T13:28:25.124Z")
    },
    "__v" : 0
}

db.collection.aggregate(
[
    {
        $match:
        {
            $and:
            [
                {$or:
                [
                    {'infos.login': 'XXXXXXX'},
                    {'infos.mail':  'XXXXXXX'.toLowerCase()}
                ]},
                {$or:
                [
                    {'infos.password': 'XXXXXXX'},
                    {
                        sessions:
                        {
                            $elemMatch:
                            {
                                'apikey': 'XXXXXXX',
                                'token':  'XXXXXXX'
                            }
                        }
                    },
                    {
                        sessions:
                        {
                            $elemMatch:
                            {
                                'apikey': 'XXXXXXX',
                                'tokenassets':  'XXXXXXX'
                            }
                        }
                    }
                ]}
            ]
        }
    },
    {
        $lookup:
        {
            from: 'othercollection',
            localField: '_id',
            foreignField: 'user_id',
            as: 'othercollection'
        }
    },
    { $unwind: '$othercollection' },
    {
        $project: { 'groups._id': 0, 'othercollection.groups._id': 0 }
    }
])
</code>```

Schemas (create with mongoose nodejs) :

```<code>// Collection 1 (130.000 docs)
const historiesSchema = new mongoose.Schema(
{
    user_id:    mongoose.Schema.Types.ObjectId,
    apikey:     String,
    ip:         String,
    target:     String,
    type:       String,
    key:        String,
    value:      String,
    level:      Number,
    useragent:  String,
    creation_date:
    {
        type:    Date,
        default: Date.now
    }
});

// Collection 2 (11.000 docs)
const eventsSchema = new mongoose.Schema(
{
    ip: String,
    creation_date:
    {
        type:    Date,
        default: Date.now
    }
},
{
    _id : false
});
const histories2Schema = new mongoose.Schema(
{
    user_id:   mongoose.Schema.Types.ObjectId,
    apikey:    String,
    ip:        String,
    target:    String,
    type:      String,
    key:       String,
    value:     String,
    level:     Number,
    useragent: String,
    events:    [eventsSchema]
});

// Collection 3 (1.600 docs)
const sessionSchema = new mongoose.Schema(
{
    apikey:      String,
    token:       String,
    tokenassets: String,
    ip:          String,
    expire_date: Date
},
{
    _id : false
});
const userSchema = new mongoose.Schema(
{
    infos:
    {
        login:       String,
        mail:        String,
        nomail:      Boolean,
        password:    String,
        firstname:   String,
        lastname:    String,
        suspend:     Boolean,
        creation_date:
        {
            type:    Date,
            default: Date.now
        }
    },
    lostpass:
    {
        token:         String,
        creation_date: Date
    },
    sessions: [sessionSchema]
});
</code>```

答:
Well it's obvious from your Schemata that you don't use any index.
Check this page out on how to create indexes with Mongoose. Here is an example as shown on that page:

```<code>var animalSchema = new Schema({
  name: String,
  type: String,
  tags: { type: [String], index: true } // field level
});

animalSchema.index({ name: 1, type: -1 }); // schema level
</code>```

Also when you run the .explain() you should be able to see that it is doing a complete collection scan. You would find it under queryPlanner then winningPlan then you will see the field stage: "COLLSCAN". This is killing the performance of you database.
Create indexes on fields that you will regularly use to search for. Don't overdo it with indexes but don't be stingy either.

I also suggest you read the documentation on indexes of MongoDB.

Body:
My query takes a lot of time ....

130,000 documents -> 70ms (local)

11,000 documents -> 80ms (local)

1,600 documents -> 2ms (local) (other base, more complex query)

Why do the first two put so much time compared to the third much more complex?

Query with 130.000 documents (60-69ms)

{
    "_id" : ObjectId("58e669e81a5696098804e0ae"),
    "target" : "mysuperlogin",
    "type" : "auth",
    "key" : "try",
    "useragent" : "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27",
    "ip" : "X.X.X.X",
    "creation_date" : ISODate("2017-04-06T16:16:40.584Z"),
    "__v" : 0
}

db.collection.aggregate(
[
    {
        $match:
        {
            'type':          'auth',
            'target':        params.authlogin,
            'ip':            'X.X.X.X',
            'creation_date': { $gte: date }
        },
        { $group: { _id: '$key', total: { $sum: 1 } } },
        { $sort:   { _id: -1 }}
    }
])

Query with 11.000 documents (77-90ms)

{
    "_id" : ObjectId("5a2a6b17aafee9dcf4000422"),
    "target" : "mysuperlogin",
    "type" : "auth",
    "key" : "try",
    "useragent" : "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27",
    "events" : [
        {
            "creation_date" : ISODate("2017-12-05T08:45:37.217Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:37.010Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:37.111Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:39.759Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:45:40.054Z"),
            "ip" : "X.X.X.X"
        },
        {
            "creation_date" : ISODate("2017-12-05T08:47:36.471Z"),
            "ip" : "X.X.X.X"
        }
    ]
}

db.collection.aggregate(
[
    {
        $match:
        {
            'type':                 'auth',
            'target':               'mysuperlogin',
            'events.ip':            'X.X.X.X',
            'events.creation_date': { $gte: new Date('2017-12-05T08:30:00.471Z') }
        }
    },
    { $unwind: '$events' },
    { $match:  { 'events.creation_date': { $gte: new Date('2017-12-05T08:30:00.471Z') } } },
    { $group:  { _id: '$key', total: { $sum: 1 } } },
    { $sort:   { _id: -1 }}
])

Query with 1.600 documents (3-4ms)

{
    "_id" : ObjectId("58f0ce79e07b3e6c24c5a453"),
    "groups" : [
        {
            "name" : "defaut",
            "company_id" : ObjectId("58e4f31cf8eca22e06167736"),
            "apikey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "level" : 1,
            "expire_date" : ISODate("2018-12-31T00:00:00Z"),
            "creation_date" : ISODate("2017-04-14T13:28:25.122Z")
        }
    ],
    "sessions" : [
        {
            "apikey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "token" : "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
            "ip" : "X.X.X.X",
            "expire_date" : ISODate("2017-05-14T13:35:13.533Z"),
            "_id" : ObjectId("58f0d0113675136beb64c5a1")
        },
        {
            "apikey" : "XXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "tokenassets" : "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
            "ip" : "X.X.X.X",
            "expire_date" : ISODate("2017-05-14T13:35:13.533Z"),
            "_id" : ObjectId("58f0d0113675136beb64c5a1")
        }
    ],
    "infos" : {
        "login" : "mysuperlogin",
        "mail" : "mysuperlogin@mymail.com",
        "password" : "CRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTEDCRYPTED",
        "firstname" : "my",
        "lastname" : "superlogin",
        "creation_date" : ISODate("2017-04-14T13:28:25.124Z")
    },
    "__v" : 0
}

db.collection.aggregate(
[
    {
        $match:
        {
            $and:
            [
                {$or:
                [
                    {'infos.login': 'XXXXXXX'},
                    {'infos.mail':  'XXXXXXX'.toLowerCase()}
                ]},
                {$or:
                [
                    {'infos.password': 'XXXXXXX'},
                    {
                        sessions:
                        {
                            $elemMatch:
                            {
                                'apikey': 'XXXXXXX',
                                'token':  'XXXXXXX'
                            }
                        }
                    },
                    {
                        sessions:
                        {
                            $elemMatch:
                            {
                                'apikey': 'XXXXXXX',
                                'tokenassets':  'XXXXXXX'
                            }
                        }
                    }
                ]}
            ]
        }
    },
    {
        $lookup:
        {
            from: 'othercollection',
            localField: '_id',
            foreignField: 'user_id',
            as: 'othercollection'
        }
    },
    { $unwind: '$othercollection' },
    {
        $project: { 'groups._id': 0, 'othercollection.groups._id': 0 }
    }
])

Schemas (create with mongoose nodejs) :

// Collection 1 (130.000 docs)
const historiesSchema = new mongoose.Schema(
{
    user_id:    mongoose.Schema.Types.ObjectId,
    apikey:     String,
    ip:         String,
    target:     String,
    type:       String,
    key:        String,
    value:      String,
    level:      Number,
    useragent:  String,
    creation_date:
    {
        type:    Date,
        default: Date.now
    }
});

// Collection 2 (11.000 docs)
const eventsSchema = new mongoose.Schema(
{
    ip: String,
    creation_date:
    {
        type:    Date,
        default: Date.now
    }
},
{
    _id : false
});
const histories2Schema = new mongoose.Schema(
{
    user_id:   mongoose.Schema.Types.ObjectId,
    apikey:    String,
    ip:        String,
    target:    String,
    type:      String,
    key:       String,
    value:     String,
    level:     Number,
    useragent: String,
    events:    [eventsSchema]
});

// Collection 3 (1.600 docs)
const sessionSchema = new mongoose.Schema(
{
    apikey:      String,
    token:       String,
    tokenassets: String,
    ip:          String,
    expire_date: Date
},
{
    _id : false
});
const userSchema = new mongoose.Schema(
{
    infos:
    {
        login:       String,
        mail:        String,
        nomail:      Boolean,
        password:    String,
        firstname:   String,
        lastname:    String,
        suspend:     Boolean,
        creation_date:
        {
            type:    Date,
            default: Date.now
        }
    },
    lostpass:
    {
        token:         String,
        creation_date: Date
    },
    sessions: [sessionSchema]
});

Body:
Well it's obvious from your Schemata that you don't use any index.
Check this page out on how to create indexes with Mongoose. Here is an example as shown on that page:

var animalSchema = new Schema({
  name: String,
  type: String,
  tags: { type: [String], index: true } // field level
});

animalSchema.index({ name: 1, type: -1 }); // schema level

Also when you run the .explain() you should be able to see that it is doing a complete collection scan. You would find it under queryPlanner then winningPlan then you will see the field stage: "COLLSCAN". This is killing the performance of you database.
Create indexes on fields that you will regularly use to search for. Don't overdo it with indexes but don't be stingy either.

I also suggest you read the documentation on indexes of MongoDB.


来源: stackexchange

问:
Worksheet code across multiple sheets
I have a navigation bar at the top of some of my worksheets and want to apply the navigation code across the whole workbook rather than having to paste the code in every worksheet. It works by clicking a cell which would then call a navigation macro. I have the following code (snippet) which is functional but there surely has to be a more efficient way of doing this rather than pasting in every sheet:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'Navigation bar
    If Not Intersect(Target, Range("E2:I3")) Is Nothing Then
        Call goto_Introduction
    End If

    If Not Intersect(Target, Range("J2:N3")) Is Nothing Then
        Call goto_OverviewInputs
    End If

    If Not Intersect(Target, Range("O2:S3")) Is Nothing Then
        Call goto_PopulationSize
    End If
</code>```

Apologies if this has been asked before, but haven't found any solutions thus far...

答:
You could transfer the logic into a module:

```<code>'put this within a module
Option Explicit

Public Sub NavigationBar(ByVal Target As Range)
    If Not Intersect(Target, Target.Parent.Range("E2:I3")) Is Nothing Then
        goto_Introduction 'note that the call statement is deprecated
                          'and not needed to call a procedure!
    End If

    If Not Intersect(Target, Target.Parent.Range("J2:N3")) Is Nothing Then
        goto_OverviewInputs
    End If

    If Not Intersect(Target, Target.Parent.Range("O2:S3")) Is Nothing Then
        goto_PopulationSize
    End If
End Sub
</code>```

so you only need to insert a call to that logic into every worksheet

```<code>'put this within the worksheets you need it
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    NavigationBar Target
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: Worksheet code across multiple sheets

Body:
I have a navigation bar at the top of some of my worksheets and want to apply the navigation code across the whole workbook rather than having to paste the code in every worksheet. It works by clicking a cell which would then call a navigation macro. I have the following code (snippet) which is functional but there surely has to be a more efficient way of doing this rather than pasting in every sheet:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'Navigation bar
    If Not Intersect(Target, Range("E2:I3")) Is Nothing Then
        Call goto_Introduction
    End If

    If Not Intersect(Target, Range("J2:N3")) Is Nothing Then
        Call goto_OverviewInputs
    End If

    If Not Intersect(Target, Range("O2:S3")) Is Nothing Then
        Call goto_PopulationSize
    End If

Apologies if this has been asked before, but haven't found any solutions thus far...

Body:
You could transfer the logic into a module:

'put this within a module
Option Explicit

Public Sub NavigationBar(ByVal Target As Range)
    If Not Intersect(Target, Target.Parent.Range("E2:I3")) Is Nothing Then
        goto_Introduction 'note that the call statement is deprecated
                          'and not needed to call a procedure!
    End If

    If Not Intersect(Target, Target.Parent.Range("J2:N3")) Is Nothing Then
        goto_OverviewInputs
    End If

    If Not Intersect(Target, Target.Parent.Range("O2:S3")) Is Nothing Then
        goto_PopulationSize
    End If
End Sub

so you only need to insert a call to that logic into every worksheet

'put this within the worksheets you need it
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    NavigationBar Target
End Sub


问:
Allow anonymous users to create unpublished nodes in Drupal?
I'm creating a site for a client based on drupal, and the client wants an anonymous user (not logged in) to be able to create a new node, but only an unpublished one. Then an admin can review the node and alter it before publishing himself.

I have looked at using triggers and actions, but writing a custom trigger module seems a bit daunting, as I'm not very fluent with the Drupal API currently. Any ideas are appreciated.

答:
Thanks goes to @mirzu. For anyone interested, I used the following code:</p>

```<code>function hook_nodeapi($node, $op, $a3 = NULL, $a4 = NULL)
{
    global $user;
    if( $op == 'presave' && !$user->uid)
    {
        db_query('UPDATE node SET status="0" WHERE nid="' . $node->nid . '"');
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Thanks goes to @mirzu. For anyone interested, I used the following code:

function hook_nodeapi($node, $op, $a3 = NULL, $a4 = NULL)
{
    global $user;
    if( $op == 'presave' && !$user->uid)
    {
        db_query('UPDATE node SET status="0" WHERE nid="' . $node->nid . '"');
    }
}


问:
GraphQL resolver middleware for auth check
I have a GraphQL API with mixed public and private queries and mutation. I'm looking for a way to check whether an operation requires the user to be authenticated and also a permission checker, so that the user can only modify his own data.

I noticed that the resolver function has a fourth argument, info that includes path.key which returns the name of the operation (documented here).

My solution was to add a checker function inside every resolver, like so:

```<code>// modify user details
resolve: async (parent, args, { mongo: { User }, loggedUser }, info) => {
    // auth check
    authChecker(info.path.key, loggedUser, args.id);

  // continue resolving
},
</code>```

And in another file:

```<code>function authChecker(operationName, loggedUser, userId) {
  if (PUBLIC_OPERATIONS.includes(operationName) {
    // public operation
    return true;
  } else {
    // private operation
    if (args.id) {
      // private operation that requires a permission check
      ...
    } else {
      // private operation that only requires user to be logged in
      ...
    }
  }
}
</code>```

The function either returns true or throws an error if conditions are not met.

I was wondering if this was an ok solution or if there was a way that this could be done with a middleware somehow so that I wouldn't have to repeat the code in every resolver. The problem is that I wouldn't have access to the operation name if I'd use a middleware. Any suggestions?

答:
Utilizing middleware should be possible, but would be painful because you would have to parse the query yourself. I think the cleanest way is to utilize a schema-level resolver, which is available with graphql-tools.

```<code>const {makeExecutableSchema, addSchemaLevelResolveFunction} = require('graphql-tools')

const schema = makeExecutableSchema({typeDefs, resolvers})
addSchemaLevelResolveFunction(schema, (root, args, context, info) => {
  // check info to see if query is private and throw if user isn't authenticated
})
// use the schema like normal
app.use('/graphql', graphqlHTTP({schema}))
</code>```

The resolver doesn't need to return anything; it just needs to throw or return a rejected Promise when authentication fails. For more info about generating a schema with graphql-tools, check the docs here.

Body:
I have a GraphQL API with mixed public and private queries and mutation. I'm looking for a way to check whether an operation requires the user to be authenticated and also a permission checker, so that the user can only modify his own data.

I noticed that the resolver function has a fourth argument, info that includes path.key which returns the name of the operation (documented here).

My solution was to add a checker function inside every resolver, like so:

// modify user details
resolve: async (parent, args, { mongo: { User }, loggedUser }, info) => {
    // auth check
    authChecker(info.path.key, loggedUser, args.id);

  // continue resolving
},

And in another file:

function authChecker(operationName, loggedUser, userId) {
  if (PUBLIC_OPERATIONS.includes(operationName) {
    // public operation
    return true;
  } else {
    // private operation
    if (args.id) {
      // private operation that requires a permission check
      ...
    } else {
      // private operation that only requires user to be logged in
      ...
    }
  }
}

The function either returns true or throws an error if conditions are not met.

I was wondering if this was an ok solution or if there was a way that this could be done with a middleware somehow so that I wouldn't have to repeat the code in every resolver. The problem is that I wouldn't have access to the operation name if I'd use a middleware. Any suggestions?

Body:
Utilizing middleware should be possible, but would be painful because you would have to parse the query yourself. I think the cleanest way is to utilize a schema-level resolver, which is available with graphql-tools.

const {makeExecutableSchema, addSchemaLevelResolveFunction} = require('graphql-tools')

const schema = makeExecutableSchema({typeDefs, resolvers})
addSchemaLevelResolveFunction(schema, (root, args, context, info) => {
  // check info to see if query is private and throw if user isn't authenticated
})
// use the schema like normal
app.use('/graphql', graphqlHTTP({schema}))

The resolver doesn't need to return anything; it just needs to throw or return a rejected Promise when authentication fails. For more info about generating a schema with graphql-tools, check the docs here.


问:
IOS (Swift 3) How to trigger broadcast receiver when gps is turn on/off?

Hello Friends

I am android(java/kotlin) and IOS(Swift) Developer. So I can easily get broadcast of GPS Enable/Disable in Android. But the problem is in IOS platform.

If user Enable or Disable GPS from phone settings. Is any way to get a callback to detect enabling/disabling GPS from my app.

答:
If user updates location services permission in settings and then enters the app (that was still loaded in memory), your CLLocationManagerDelegate implementation should receive authorization status update in function:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus)

If you want to make action after first authorization positive change, just persist previou state somehow into user defaults or other persisting options


问:
BigQuery - Delete rows from Partitioned Table
I have a Day-Partitioned Table on BigQuery. When I try to delete some rows from the table using a query like:

```<code>DELETE FROM `MY_DATASET.partitioned_table` WHERE id = 2374180
</code>```

I get the following error:

Error: DML statements are not yet supported over partitioned tables.

A quick Google search leads me to: https://cloud.google.com/bigquery/docs/loading-data-sql-dml where it also says: "DML statements that modify partitioned tables are not yet supported."

So for now, is there a workaround that we can use in deleting rows from a partitioned table?

答:
I've already done it without temporary table, steps:

1) prepare query which selects all the rows from particular partition which should be kept:

```<code>SELECT * FROM `your_data_set.tablename` WHERE
_PARTITIONTIME = timestamp('2017-12-07')
AND condition_to_keep_rows_which_shouldn't_be_deleted = 'condition'
</code>```

if necessary run this for other partitions

2) choose Destination table for result of your query where you point TO THE PARTICULAR PARTITION, you need to provide table name like this:

```<code>tablename$20171207
</code>```

3) Check option "Overwrite table" -> it will overwrite only particular partition

4) Run Query, as a result from pointed partition redundant rows will be deleted!

//remember that you could need run this for other partitions, where you rows to deleted are spread across more than one partition

Body:
I have a Day-Partitioned Table on BigQuery. When I try to delete some rows from the table using a query like:

DELETE FROM `MY_DATASET.partitioned_table` WHERE id = 2374180

I get the following error:

Error: DML statements are not yet supported over partitioned tables.

A quick Google search leads me to: https://cloud.google.com/bigquery/docs/loading-data-sql-dml where it also says: "DML statements that modify partitioned tables are not yet supported."

So for now, is there a workaround that we can use in deleting rows from a partitioned table?

Body:
I've already done it without temporary table, steps:

1) prepare query which selects all the rows from particular partition which should be kept:

SELECT * FROM `your_data_set.tablename` WHERE
_PARTITIONTIME = timestamp('2017-12-07')
AND condition_to_keep_rows_which_shouldn't_be_deleted = 'condition'

if necessary run this for other partitions

2) choose Destination table for result of your query where you point TO THE PARTICULAR PARTITION, you need to provide table name like this:

tablename$20171207

3) Check option "Overwrite table" -> it will overwrite only particular partition

4) Run Query, as a result from pointed partition redundant rows will be deleted!

//remember that you could need run this for other partitions, where you rows to deleted are spread across more than one partition


问:
How to pass a vector to execvp
I want to pass a vector in as the second argument to execvp. Is it possible?</p>

答:
Yes, it can be done pretty cleanly by taking advantage of the internal array that vectors use.

This will work, since the standard guarantees its elements are stored contiguously (see https://stackoverflow.com/a/2923290/383983)

```<code>#include <vector>

using std::vector;

int main() {
  vector<char*> commandVector;

  // do a push_back for the command, then each of the arguments
  commandVector.push_back(const_cast<char*>("echo"));
  commandVector.push_back(const_cast<char*>("testing"));
  commandVector.push_back(const_cast<char*>("1"));
  commandVector.push_back(const_cast<char*>("2"));
  commandVector.push_back(const_cast<char*>("3"));

  // push NULL to the end of the vector (execvp expects NULL as last element)
  commandVector.push_back(NULL);

  int status = execvp(command[0], &command[0]);
  return 0;
}
</code>```

Do a const_cast to avoid the "deprecated conversion from string constant to 'char*'". String literals are implemented as 'const char*' in C++. const_cast is the safest form of cast here, as it only removes the const and does not do any other funny business. execvp will not edit the values anyway.

If you want to avoid all casts, you have to complicate this code by copying all the values to 'char*' types not really worth it.

Title: How to pass a vector to execvp

Body:
Yes, it can be done pretty cleanly by taking advantage of the internal array that vectors use.

This will work, since the standard guarantees its elements are stored contiguously (see https://stackoverflow.com/a/2923290/383983)

#include <vector>

using std::vector;

int main() {
  vector<char*> commandVector;

  // do a push_back for the command, then each of the arguments
  commandVector.push_back(const_cast<char*>("echo"));
  commandVector.push_back(const_cast<char*>("testing"));
  commandVector.push_back(const_cast<char*>("1"));
  commandVector.push_back(const_cast<char*>("2"));
  commandVector.push_back(const_cast<char*>("3"));

  // push NULL to the end of the vector (execvp expects NULL as last element)
  commandVector.push_back(NULL);

  int status = execvp(command[0], &command[0]);
  return 0;
}

Do a const_cast to avoid the "deprecated conversion from string constant to 'char*'". String literals are implemented as 'const char*' in C++. const_cast is the safest form of cast here, as it only removes the const and does not do any other funny business. execvp will not edit the values anyway.

If you want to avoid all casts, you have to complicate this code by copying all the values to 'char*' types not really worth it.

ContentLicense: CC BY-SA 4.0


问:
Apache VirtualHost confusion when using alias
So I have a setup that looks as follows:

www.mydomain.com - runs a complex multisite Wordpress install
www.mydomain.com/othersite - for various reasons this needs to run a totally separate install of Wordpress, but the URL must be in this format for historic reasons.

I'd like the "othersite" install of WP not to have to sit in the directory of the main multisite install, eg
/var/www/main-multisite
/var/www/othersite and NOT /var/www/main-multisite/othersite

My understanding is that I couldn't create a separate virtualhost for othersite, so I created an alias in the main virutalhost:

```<code>Alias /othersite /var/www/othersite
</code>```

However when doing that, it seems the .htaccess file in /var/www/othersite is being ignored - I first noticed this as the permalinks in Wordpress don't work.  I tried adding other directives into .htaccess but none work...so I then put gibberish into .htaccess to try and induce an error...but that didn't happen.  So taht confirms my thinking that .htaccess is being ignored.

However, if I remove the alias from the Virtual host, and move things so we have

```<code>/var/www/main-multisite/other
</code>```

everything works fine, and the .htaccess in the folder works ok! But this is not how I want things.

Can anyone help me shed any light on what I'm missing here?

Thanks in advance.

答:
After you have set the Alias, you should set the group of directives to apply to the directory. You should add the <Directory> directive in apache config. The default config AllowOverride None will completely ignore .htaccess on the directory. You should also check the documentation about the <Directory> directive.

```<code><Directory "/var/www/othersite">
    Options FollowSymLinks Includes
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>
</code>```

Body:
So I have a setup that looks as follows:

www.mydomain.com - runs a complex multisite Wordpress install
www.mydomain.com/othersite - for various reasons this needs to run a totally separate install of Wordpress, but the URL must be in this format for historic reasons.

I'd like the "othersite" install of WP not to have to sit in the directory of the main multisite install, eg
/var/www/main-multisite
/var/www/othersite and NOT /var/www/main-multisite/othersite

My understanding is that I couldn't create a separate virtualhost for othersite, so I created an alias in the main virutalhost:

Alias /othersite /var/www/othersite

However when doing that, it seems the .htaccess file in /var/www/othersite is being ignored - I first noticed this as the permalinks in Wordpress don't work.  I tried adding other directives into .htaccess but none work...so I then put gibberish into .htaccess to try and induce an error...but that didn't happen.  So taht confirms my thinking that .htaccess is being ignored.

However, if I remove the alias from the Virtual host, and move things so we have

/var/www/main-multisite/other

everything works fine, and the .htaccess in the folder works ok! But this is not how I want things.

Can anyone help me shed any light on what I'm missing here?

Thanks in advance.

Body:
After you have set the Alias, you should set the group of directives to apply to the directory. You should add the <Directory> directive in apache config. The default config AllowOverride None will completely ignore .htaccess on the directory. You should also check the documentation about the <Directory> directive.

<Directory "/var/www/othersite">
    Options FollowSymLinks Includes
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>


问:
Is the problem of finding the chromatic number of this modified interval graph NP-Complete?
Few days ago I was working on interval graphs to solve the known problem of resource allocation, as we know there is a greedy approach that solves this problem (chromatic number) in polynomial time and gives us the colors of each vertex in the interval graph (the problem of finding the chromatic number in general graphs is NP-Complete (3-satisfiability reduction by Karp)).

I was wondering: if had a graph that is not an interval graph but it is because it has one and only one chordless cycle of length > 3 (there is an edge that, when you remove it, the graph becomes an interval graph), does it makes the problem of finding the chromatic number on this kind of graph NP-Complete?

答:
Kind of hand-wavey, if there's just a single edge which prevents the interval graph coloring algorithm from working, then remove it.  Run the interval graph algorithm.  If the two endpoints of the removed edge have different colors, you're done.  Otherwise, Let C be the number of colors that the algorithm used.  Try all (C choose 2) fixed colors for the two endpoints, and try the interval graph algorithm again.  If it succeeds with C colors, you're done.  Otherwise, you'll need C+1 colors so just pick one of the endpoints and give it a unique color.

I'm assuming you can find the removable edge in poly time.


问:
How to use different google analytics code for different pages in wordpress
I am already using one analytics code for my website. But now I want to separately use one more analytics code for specific pages.
I am using Plugin named "Google Analytics" for integrating analytics code in my website.
So is there any way to implement this.
Thanks in advance...</p>

答:
So you're probably referring to https://support.google.com/analytics/answer/1032400?hl=en correct?

In this case the plugin you're using won't help. You'll need something like Head & Footer Code plugin and insert codes manually on per post/page basis.

With that, in Tools → Head & Footer Code you'll put your global GA code, but then you can override it with a different code via post/page metabox for individual posts/pages/CPTs.


问:
How to transform into database and label according to the interval with R
I'm trying to transform mass data into database but it seems too cumbersome to make it ordered.

it is example data.

```<code>structure(list(V1 = structure(c(2L, 1L, 1L, 3L, 1L, 4L, 1L, 1L,
1L, 5L), .Label = c("", "01.01 ? 01.06                          ",
"02.01 ? 02.10                          ", "03.01 ? 03.07                          ",
"Chapter 4 (04.01~04.10)"), class = "factor"), V2 = structure(c(2L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 3L), .Label = c("", "CTH", "WO"
), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-10L))
</code>```

the result I want to show is like this

```<code>structure(list(V1 = c(1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 2.01,
2.02, 2.03, 2.04, 2.05, 2.06, 2.07, 2.08, 2.09, 2.1, 3.01, 3.02,
3.03, 3.04, 3.05, 3.06, 3.07, 4.01, 4.02, 4.03, 4.04, 4.05, 4.06,
4.07, 4.08, 4.09, 4.1), V2 = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("CTH",
"WO"), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-33L))
</code>```

you can find out each cell of row A is comprised kinda interval value. it would be an abbreviation of several cells in database I want to make.

I should labeling those cells as same code of row C - for example, cell of 01.01 - CTH, cell of 01.02 - CTH, cell of 01.03 - CTH, so on till 0.06 is done.

But there are several problems.

how to divide a cell of interval value into 2 variables?

and labeling same code according to the value of the first data of the interval.

the classification indicators of data are chapter, heading and subheading.

And I'd like to if the cell of the interval value just says chapter I, I'd like to label all sub-category data as the code corresponding to interval value.
and organizing a dataframe on the new csv.

Let me know how to deal those problems with R.

thanks for you all

Body:
I'm trying to transform mass data into database but it seems too cumbersome to make it ordered.

it is example data.

structure(list(V1 = structure(c(2L, 1L, 1L, 3L, 1L, 4L, 1L, 1L,
1L, 5L), .Label = c("", "01.01 ? 01.06                          ",
"02.01 ? 02.10                          ", "03.01 ? 03.07                          ",
"Chapter 4 (04.01~04.10)"), class = "factor"), V2 = structure(c(2L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 3L), .Label = c("", "CTH", "WO"
), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-10L))

the result I want to show is like this

structure(list(V1 = c(1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 2.01,
2.02, 2.03, 2.04, 2.05, 2.06, 2.07, 2.08, 2.09, 2.1, 3.01, 3.02,
3.03, 3.04, 3.05, 3.06, 3.07, 4.01, 4.02, 4.03, 4.04, 4.05, 4.06,
4.07, 4.08, 4.09, 4.1), V2 = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("CTH",
"WO"), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-33L))

you can find out each cell of row A is comprised kinda interval value. it would be an abbreviation of several cells in database I want to make.

I should labeling those cells as same code of row C - for example, cell of 01.01 - CTH, cell of 01.02 - CTH, cell of 01.03 - CTH, so on till 0.06 is done.

But there are several problems.

how to divide a cell of interval value into 2 variables?

and labeling same code according to the value of the first data of the interval.

the classification indicators of data are chapter, heading and subheading.

And I'd like to if the cell of the interval value just says chapter I, I'd like to label all sub-category data as the code corresponding to interval value.
and organizing a dataframe on the new csv.

Let me know how to deal those problems with R.

thanks for you all

Body:
structure(list(V1 = structure(c(2L, 1L, 1L, 3L, 1L, 4L, 1L, 1L,
1L, 5L), .Label = c("", "01.01 ? 01.06                          ",
"02.01 ? 02.10                          ", "03.01 ? 03.07                          ",
"Chapter 4 (04.01~04.10)"), class = "factor"), V2 = structure(c(2L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 3L), .Label = c("", "CTH", "WO"
), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, -10L)) -> df1

structure(list(V1 = c(1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 2.01,
2.02, 2.03, 2.04, 2.05, 2.06, 2.07, 2.08, 2.09, 2.1, 3.01, 3.02,
3.03, 3.04, 3.05, 3.06, 3.07, 4.01, 4.02, 4.03, 4.04, 4.05, 4.06,
4.07, 4.08, 4.09, 4.1), V2 = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("CTH",
"WO"), class = "factor")), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, -33L)) -> df2

library(dplyr)
library(stringr)
library(purrr)
library(tidyr)

df1 %>%
  filter(V1 != "") %>%
  mutate(lim = str_extract_all(V1, "\\d{2}\\.\\d{2}"),
         lim = map_chr(lim, paste0, collapse = ",")) %>%
  separate(lim, into = c("low", "high"), sep = ",", convert = T) %>%
  mutate(value = map2(low, high, ~paste0(seq(.x,.y, by=0.01), collapse = ","))) %>%
  select(V2, value) %>%
  separate_rows(value, convert = T)


答:
This also accounts for the case when you have a single number... named your data df:

```<code>library(tidyverse)
as.character(df$V1) %>%
  # extract all matching, ie 12.34
  str_extract_all(pattern = "\\d{2}\\.\\d{2}") %>%
  # convert to matrix
  map(as.matrix) %>%
  # transpose, such that it is only one column
  map(t) %>%
  # convert to tibble (or data frame)
  map(as_tibble) %>%
  # bind rows together, regardless of single or double rows
  reduce(bind_rows) %>%
  # name columns
  set_names(nm = c("from", "to")) %>%
  # if single values occur...
  mutate(to = ifelse(is.na(to), from, to),
         # add info of second column
         second = as.character(df$V2)) %>%
  # drop missing rows
  drop_na() %>%
  # convert to double for seq
  mutate_at(.vars = vars(from, to), as.double) %>%
  group_by_all() %>%
  # create list of individual length using seq
  mutate(first = list(seq(from = from, to = to, by = .01))) %>%
  unnest() %>% ungroup() %>%
  select(first, second)
</code>```

Title: How to transform into database and label according to the interval with R

Body:
This also accounts for the case when you have a single number... named your data df:

library(tidyverse)
as.character(df$V1) %>%
  # extract all matching, ie 12.34
  str_extract_all(pattern = "\\d{2}\\.\\d{2}") %>%
  # convert to matrix
  map(as.matrix) %>%
  # transpose, such that it is only one column
  map(t) %>%
  # convert to tibble (or data frame)
  map(as_tibble) %>%
  # bind rows together, regardless of single or double rows
  reduce(bind_rows) %>%
  # name columns
  set_names(nm = c("from", "to")) %>%
  # if single values occur...
  mutate(to = ifelse(is.na(to), from, to),
         # add info of second column
         second = as.character(df$V2)) %>%
  # drop missing rows
  drop_na() %>%
  # convert to double for seq
  mutate_at(.vars = vars(from, to), as.double) %>%
  group_by_all() %>%
  # create list of individual length using seq
  mutate(first = list(seq(from = from, to = to, by = .01))) %>%
  unnest() %>% ungroup() %>%
  select(first, second)


问:
Promise.then() executing before the promise is resolved
I'm having a problem with promises. I have this code:

```<code>let line = hey.fetchBans().then(() => {
  myStuff();
  console.log(line);
});
</code>```

The problem is that myStuff() executes before fetchBans() is resolved. I tried to see if that was the real problem logging line, and it prints Promise { <pending> }

What am I doing wrong?

答: line is not the promise that hey.fetchBans() returned (and which did fulfill before your callback is called), it is the promise that .then(…) returned (and which will be resolved with the result value of the callback). It will always be pending inside that very callback.

Body:
I'm having a problem with promises. I have this code:

let line = hey.fetchBans().then(() => {
  myStuff();
  console.log(line);
});

The problem is that myStuff() executes before fetchBans() is resolved. I tried to see if that was the real problem logging line, and it prints Promise { <pending> }

What am I doing wrong?


问:
python pandas select both head and tail
For a DataFrame in Pandas, how can I select both the first 5 values and last 5 values?

For example

```<code>In [11]: df
Out[11]:
        A  B  C
2012-11-29  0  0  0
2012-11-30  1  1  1
2012-12-01  2  2  2
2012-12-02  3  3  3
2012-12-03  4  4  4
2012-12-04  5  5  5
2012-12-05  6  6  6
2012-12-06  7  7  7
2012-12-07  8  8  8
2012-12-08  9  9  9
</code>```

How to show the first two and the last two rows?

答:
Small simple function:

```<code>def ends(df, x=5):
    return df.head(x).append(df.tail(x))
</code>```

And use like so:

```<code>df = pd.DataFrame(np.random.rand(15,6))
ends(df,2)
</code>```

I actually use this so much, I think it would be a great feature to add to pandas. (No features are to be added to pandas.DataFrame core API) I add it after import like so:

```<code>import pandas as pd
def ends(df, x=5):
    return df.head(x).append(df.tail(x))
setattr(pd.DataFrame,'ends',ends)
</code>```

Use like so:

```<code>import numpy as np
df = pd.DataFrame(np.random.rand(15,6))
df.ends(2)
</code>```

Title: python pandas select both head and tail

Body:
For a DataFrame in Pandas, how can I select both the first 5 values and last 5 values?

For example

In [11]: df
Out[11]:
        A  B  C
2012-11-29  0  0  0
2012-11-30  1  1  1
2012-12-01  2  2  2
2012-12-02  3  3  3
2012-12-03  4  4  4
2012-12-04  5  5  5
2012-12-05  6  6  6
2012-12-06  7  7  7
2012-12-07  8  8  8
2012-12-08  9  9  9

How to show the first two and the last two rows?

Body:
Small simple function:

def ends(df, x=5):
    return df.head(x).append(df.tail(x))

And use like so:

df = pd.DataFrame(np.random.rand(15,6))
ends(df,2)

I actually use this so much, I think it would be a great feature to add to pandas. (No features are to be added to pandas.DataFrame core API) I add it after import like so:

import pandas as pd
def ends(df, x=5):
    return df.head(x).append(df.tail(x))
setattr(pd.DataFrame,'ends',ends)

Use like so:

import numpy as np
df = pd.DataFrame(np.random.rand(15,6))
df.ends(2)


问:
Add array of objects to PHPExcel template
I'm currently pulling an array of objects from my database with the intention of each object representing a row in a PHPExcel template.
The data is as follows:

```<code>[
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
]
</code>```

The rows in my Excel sheet start at 17 - so the first object would be entered in row 17, the second object in the array would be entered in row 18 and so on. However, the columns I wish to add to are not all next to each other, so its difficult to loop. For example, the name field of the first object should be entered into C17, while the age field should be entered into F17 and the other_info field should be entered into J17 and my_info should be in L17. The second object would then be entered into the same columns but the next row and so on.

I have tried looping through the array but that doesn't allow me to skip the columns, only add to consecutive columns and rows;

```<code>foreach ($array as $rowArray) {
    $columnID = 'C';
    $rowID = 17;
    foreach ($rowArray as $columnValue) {
        $objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
        $rowID++;
    }
}
</code>```

Can anyone give me some guidance on this? Much appreciated!

答:
Try this one:</p>

```<code>$json = '[
            {
                "name": "name1",
                "age":"age1",
                "other_info":"other_info1",
                "my_info":"my_info1"
            },
            {
                "name": "name2",
                "age": "age2",
                "other_info": "other_info2",
                "my_info": "my_info2"
            }
        ]';

$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
$cells = ['name' => 'C', 'age' => 'F', 'other_info' => 'J', 'my_info' => 'L'];
$array = json_decode($json, true);

$rowID = 17;
foreach($array as $rowArray) {
    foreach ($rowArray as $index => $columnValue) {
        $col = $cells[$index].$rowID;
        $phpExcelObject
          ->getActiveSheet()
          ->setCellValue((string)$col, $columnValue);
    }
    $rowID++;
}
</code>```

Body:
I'm currently pulling an array of objects from my database with the intention of each object representing a row in a PHPExcel template.
The data is as follows:

[
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
    {
        name: test,
        age: test,
        other_info: test,
        my_info: test
    },
]

The rows in my Excel sheet start at 17 - so the first object would be entered in row 17, the second object in the array would be entered in row 18 and so on. However, the columns I wish to add to are not all next to each other, so its difficult to loop. For example, the name field of the first object should be entered into C17, while the age field should be entered into F17 and the other_info field should be entered into J17 and my_info should be in L17. The second object would then be entered into the same columns but the next row and so on.

I have tried looping through the array but that doesn't allow me to skip the columns, only add to consecutive columns and rows;

foreach ($array as $rowArray) {
    $columnID = 'C';
    $rowID = 17;
    foreach ($rowArray as $columnValue) {
        $objPHPExcel->getActiveSheet()->setCellValue($columnID.$rowID, $columnValue);
        $rowID++;
    }
}

Can anyone give me some guidance on this? Much appreciated!

Body:
Try this one:

$json = '[
            {
                "name": "name1",
                "age":"age1",
                "other_info":"other_info1",
                "my_info":"my_info1"
            },
            {
                "name": "name2",
                "age": "age2",
                "other_info": "other_info2",
                "my_info": "my_info2"
            }
        ]';

$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject();
$cells = ['name' => 'C', 'age' => 'F', 'other_info' => 'J', 'my_info' => 'L'];
$array = json_decode($json, true);

$rowID = 17;
foreach($array as $rowArray) {
    foreach ($rowArray as $index => $columnValue) {
        $col = $cells[$index].$rowID;
        $phpExcelObject
          ->getActiveSheet()
          ->setCellValue((string)$col, $columnValue);
    }
    $rowID++;
}


问:
TCL tclOODecls.h Functions Not Exported
My compiled TCL library (Tcl8.6.7, win7) didn't export the functions in tclOODecls.h. I exported the functions by putting: #define TCLAPI extern DLLEXPORT in tclOODecls.h before the auto generated section.

I would like to know why the functions were not exported by default and the preferred way of enabling the export.

答:
The symbols have been defined to use MODULE_SCOPE. See issue 3010352 which mentions this a while ago. The idea is that if you want to use these symbols you should be using the Tcl stubs linking mechanism and define the USE_TCLOO_STUBS macro and link with the stubs library (tclstub86). The functions are in there - just not exported on the DLL exports.

From tcl.h:

```<code>/*
 * Include platform specific public function declarations that are accessible
 * via the stubs table. Make all TclOO symbols MODULE_SCOPE (which only
 * has effect on building it as a shared library). See ticket [3010352].
 */
</code>```

Example of static embedding Tcl with TclOO API usage

The following code will build an executable that works like the standard Tcl shell but includes an additional command that accesses the TclOO API as a demonstration.

```<code>/* Demonstrate embedding Tcl and using the TclOO API.
 *
 * Build with MSVC (adjust paths for local setup):
 *
 *   cl -nologo -W3 -MT -Zi -GL -DSTATIC_BUILD -Ic:\opt\tcl\include test_embed_oo.c \
 *      -Fe:test_embed_oo.exe -link -debug -subsystem:console -ltcg -libpath:C:\src\tcl\kitgen\8.6\tcl\win\Release_VC13 \
 *      tcl86ts.lib user32.lib ws2_32.lib netapi32.lib
 *
 * Requires a static libary if Tcl (tcl86ts.lib on windows)
 */
#include <tcl.h>
#include <tclOO.h>
#include <locale.h>

static int
GetObjectNameCmd(ClientData clientData, Tcl_Interp *interp,
                 int objc, Tcl_Obj *const objv[])
{
    int r = TCL_ERROR;
    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "object");
        return r;
    }
    Tcl_Object object = Tcl_GetObjectFromObj(interp, objv[1]);
    if (object != NULL) {
        Tcl_Obj *resultObj = Tcl_GetObjectName(interp, object);
        if (resultObj != NULL) {
            Tcl_SetObjResult(interp, resultObj);
            r = TCL_OK;
        }
    }
    return r;
}

#define TCL_LOCAL_APPINIT Custom_AppInit
int
Custom_AppInit(Tcl_Interp *interp)
{
    Tcl_CreateObjCommand(interp, "getobjectname", GetObjectNameCmd, NULL, NULL);
    return Tcl_Eval(interp, "source test_embed_oo.tcl");
}

#include "c:/src/tcl/kitgen/8.6/tcl/win/tclAppInit.c"
</code>```

Embed Tcl using dynamic loading

Tcl can be linked to an application dynamically using the Tcl stubs linkage mechanism. This requires loading two functions from the DLL and then initializing the stubs table. The following shows this with TclOO access enabled.

```<code>/* Demonstrate embedding Tcl and using the TclOO API via stubs
 *
 * Build with MSVC (adjust paths for local setup):
 *
 *   cl -nologo -W3 -MD -Zi -GL -Ic:\opt\tcl\include test_embed_oo_ex.c \
 *      -Fe:test_embed_oo_ex.exe -link -debug -ltcg -subsystem:console \
 *      -libpath:C:\opt\tcl\lib tclstub86.lib user32.lib
 *
 * Dynamically loads Tcl and then uses stubs for API access.
 */

#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <windows.h>
#include <locale.h>

#define USE_TCL_STUBS
#define USE_TCLOO_STUBS
#include <tcl.h>
#include <tclOO.h>

static int
GetObjectNameCmd(ClientData clientData, Tcl_Interp *interp,
                 int objc, Tcl_Obj *const objv[])
{
    int r = TCL_ERROR;
    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "object");
        return r;
    }
    Tcl_Object object = Tcl_GetObjectFromObj(interp, objv[1]);
    if (object != NULL) {
        Tcl_Obj *resultObj = Tcl_GetObjectName(interp, object);
        if (resultObj != NULL) {
            Tcl_SetObjResult(interp, resultObj);
            r = TCL_OK;
        }
    }
    return r;
}

typedef Tcl_Interp *(*LPFNTCLCREATEINTERP)();
typedef void *(*LPFNTCLFINDEXECUTABLE)(const char *);

static Tcl_Interp *
InitializeTcl(int argc, char *argv[])
{
    Tcl_Interp *interp = NULL;
    //Tcl_DString dString;
    char szLibrary[16];
    int nMinor;
    HINSTANCE hTcl = NULL;

    for (nMinor = 6; hTcl == NULL && nMinor > 4; nMinor--) {
        wsprintfA(szLibrary, "tcl8%d.dll", nMinor);
        hTcl = LoadLibraryA(szLibrary);
    }

    if (hTcl != NULL) {
        LPFNTCLCREATEINTERP lpfnTcl_CreateInterp;
        LPFNTCLFINDEXECUTABLE lpfnTcl_FindExecutable;
        lpfnTcl_CreateInterp = (LPFNTCLCREATEINTERP)
            GetProcAddress(hTcl, "Tcl_CreateInterp");
        lpfnTcl_FindExecutable = (LPFNTCLFINDEXECUTABLE)
            GetProcAddress(hTcl, "Tcl_FindExecutable");
        if (lpfnTcl_CreateInterp != NULL) {
            interp = lpfnTcl_CreateInterp();
            if (interp != NULL) {
                Tcl_InitStubs(interp, "8.6", 0);
#ifdef USE_TCLOO_STUBS
                Tcl_OOInitStubs(interp);
#endif
                lpfnTcl_FindExecutable(argv[0]);
                Tcl_InitMemory(interp);
                Tcl_Init(interp);
            }
        }
    }
    return interp;
}
/*
 * Embed tcl interpreter into a C program.
 */
int
main(int argc, char *argv[])
{
    Tcl_Interp *interp = NULL;
    int r = TCL_ERROR;

    setlocale(LC_ALL, "C");
    interp = InitializeTcl(argc, argv);
    if (interp == NULL) {
        fprintf(stderr, "error: failed to initialize Tcl runtime\n");
    } else {
        Tcl_CreateObjCommand(interp, "getobjectname", GetObjectNameCmd, NULL, NULL);
        if (argc > 1) {
            r = Tcl_EvalFile(interp, argv[1]);
            printf(Tcl_GetStringResult(interp));
        }
        Tcl_DeleteInterp(interp);
    }
    return r;
}
</code>```

To test this you want a file that contains some tcl code that can call getobjectname and run the executable with the path to this file as the only argument.

Title: TCL tclOODecls.h Functions Not Exported

Body:
The symbols have been defined to use MODULE_SCOPE. See issue 3010352 which mentions this a while ago. The idea is that if you want to use these symbols you should be using the Tcl stubs linking mechanism and define the USE_TCLOO_STUBS macro and link with the stubs library (tclstub86). The functions are in there - just not exported on the DLL exports.

From tcl.h:

/*
 * Include platform specific public function declarations that are accessible
 * via the stubs table. Make all TclOO symbols MODULE_SCOPE (which only
 * has effect on building it as a shared library). See ticket [3010352].
 */

Example of static embedding Tcl with TclOO API usage

The following code will build an executable that works like the standard Tcl shell but includes an additional command that accesses the TclOO API as a demonstration.

/* Demonstrate embedding Tcl and using the TclOO API.
 *
 * Build with MSVC (adjust paths for local setup):
 *
 *   cl -nologo -W3 -MT -Zi -GL -DSTATIC_BUILD -Ic:\opt\tcl\include test_embed_oo.c \
 *      -Fe:test_embed_oo.exe -link -debug -subsystem:console -ltcg -libpath:C:\src\tcl\kitgen\8.6\tcl\win\Release_VC13 \
 *      tcl86ts.lib user32.lib ws2_32.lib netapi32.lib
 *
 * Requires a static libary if Tcl (tcl86ts.lib on windows)
 */
#include <tcl.h>
#include <tclOO.h>
#include <locale.h>

static int
GetObjectNameCmd(ClientData clientData, Tcl_Interp *interp,
                 int objc, Tcl_Obj *const objv[])
{
    int r = TCL_ERROR;
    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "object");
        return r;
    }
    Tcl_Object object = Tcl_GetObjectFromObj(interp, objv[1]);
    if (object != NULL) {
        Tcl_Obj *resultObj = Tcl_GetObjectName(interp, object);
        if (resultObj != NULL) {
            Tcl_SetObjResult(interp, resultObj);
            r = TCL_OK;
        }
    }
    return r;
}

#define TCL_LOCAL_APPINIT Custom_AppInit
int
Custom_AppInit(Tcl_Interp *interp)
{
    Tcl_CreateObjCommand(interp, "getobjectname", GetObjectNameCmd, NULL, NULL);
    return Tcl_Eval(interp, "source test_embed_oo.tcl");
}

#include "c:/src/tcl/kitgen/8.6/tcl/win/tclAppInit.c"

Embed Tcl using dynamic loading

Tcl can be linked to an application dynamically using the Tcl stubs linkage mechanism. This requires loading two functions from the DLL and then initializing the stubs table. The following shows this with TclOO access enabled.

/* Demonstrate embedding Tcl and using the TclOO API via stubs
 *
 * Build with MSVC (adjust paths for local setup):
 *
 *   cl -nologo -W3 -MD -Zi -GL -Ic:\opt\tcl\include test_embed_oo_ex.c \
 *      -Fe:test_embed_oo_ex.exe -link -debug -ltcg -subsystem:console \
 *      -libpath:C:\opt\tcl\lib tclstub86.lib user32.lib
 *
 * Dynamically loads Tcl and then uses stubs for API access.
 */

#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <windows.h>
#include <locale.h>

#define USE_TCL_STUBS
#define USE_TCLOO_STUBS
#include <tcl.h>
#include <tclOO.h>

static int
GetObjectNameCmd(ClientData clientData, Tcl_Interp *interp,
                 int objc, Tcl_Obj *const objv[])
{
    int r = TCL_ERROR;
    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "object");
        return r;
    }
    Tcl_Object object = Tcl_GetObjectFromObj(interp, objv[1]);
    if (object != NULL) {
        Tcl_Obj *resultObj = Tcl_GetObjectName(interp, object);
        if (resultObj != NULL) {
            Tcl_SetObjResult(interp, resultObj);
            r = TCL_OK;
        }
    }
    return r;
}

typedef Tcl_Interp *(*LPFNTCLCREATEINTERP)();
typedef void *(*LPFNTCLFINDEXECUTABLE)(const char *);

static Tcl_Interp *
InitializeTcl(int argc, char *argv[])
{
    Tcl_Interp *interp = NULL;
    //Tcl_DString dString;
    char szLibrary[16];
    int nMinor;
    HINSTANCE hTcl = NULL;

    for (nMinor = 6; hTcl == NULL && nMinor > 4; nMinor--) {
        wsprintfA(szLibrary, "tcl8%d.dll", nMinor);
        hTcl = LoadLibraryA(szLibrary);
    }

    if (hTcl != NULL) {
        LPFNTCLCREATEINTERP lpfnTcl_CreateInterp;
        LPFNTCLFINDEXECUTABLE lpfnTcl_FindExecutable;
        lpfnTcl_CreateInterp = (LPFNTCLCREATEINTERP)
            GetProcAddress(hTcl, "Tcl_CreateInterp");
        lpfnTcl_FindExecutable = (LPFNTCLFINDEXECUTABLE)
            GetProcAddress(hTcl, "Tcl_FindExecutable");
        if (lpfnTcl_CreateInterp != NULL) {
            interp = lpfnTcl_CreateInterp();
            if (interp != NULL) {
                Tcl_InitStubs(interp, "8.6", 0);
#ifdef USE_TCLOO_STUBS
                Tcl_OOInitStubs(interp);
#endif
                lpfnTcl_FindExecutable(argv[0]);
                Tcl_InitMemory(interp);
                Tcl_Init(interp);
            }
        }
    }
    return interp;
}
/*
 * Embed tcl interpreter into a C program.
 */
int
main(int argc, char *argv[])
{
    Tcl_Interp *interp = NULL;
    int r = TCL_ERROR;

    setlocale(LC_ALL, "C");
    interp = InitializeTcl(argc, argv);
    if (interp == NULL) {
        fprintf(stderr, "error: failed to initialize Tcl runtime\n");
    } else {
        Tcl_CreateObjCommand(interp, "getobjectname", GetObjectNameCmd, NULL, NULL);
        if (argc > 1) {
            r = Tcl_EvalFile(interp, argv[1]);
            printf(Tcl_GetStringResult(interp));
        }
        Tcl_DeleteInterp(interp);
    }
    return r;
}

To test this you want a file that contains some tcl code that can call getobjectname and run the executable with the path to this file as the only argument.


问:
Is it possible to make a silent installer for npgsql
We're building a package in LanRev for npgsql.
Is it possible to make a silent installer? If not, we won't be able to proceed.</p>

答:
You might want to look at this link -> packages/Npgsql

It also contains a pakage installer command.


问:
Trace not working in Flash
In have searched the forums and can't find the appropiate answer.  I do not have the "omit traces" option checked in publish settings (I use flash CS5).  Here is my code:

```<code>package
{

 import flash.display.MovieClip;

 public class gr extends MovieClip
 {

  public function gr()
  {
   // constructor code
   var mc:MovieClip = new MovieClip();
   mc.graphics.beginFill(0xFF0000);
   mc.graphics.drawRect(0, 0, 100, 80);
   mc.graphics.endFill();
   mc.x = 200;
   mc.y = 60;
   addChild(mc);
   trace("hi")
  }
 }

}
</code>```

The creation of a movieclip works fine, but the trace doesn't.  This is the main class.

答:
Try quitting your Flash CS5 and start with a fresh Fla document then your main class.

The code above works, so there must be something either in the options or your setup that is preventing the debugging from working.

Depending on which debugger you are using .. you should see the debugger option available in the control menu. Try using the debug option available in the CS5 menu.

Title: Trace not working in Flash

Body:
In have searched the forums and can't find the appropiate answer.  I do not have the "omit traces" option checked in publish settings (I use flash CS5).  Here is my code:

package
{

 import flash.display.MovieClip;

 public class gr extends MovieClip
 {

  public function gr()
  {
   // constructor code
   var mc:MovieClip = new MovieClip();
   mc.graphics.beginFill(0xFF0000);
   mc.graphics.drawRect(0, 0, 100, 80);
   mc.graphics.endFill();
   mc.x = 200;
   mc.y = 60;
   addChild(mc);
   trace("hi")
  }
 }

}

The creation of a movieclip works fine, but the trace doesn't.  This is the main class.


问:
kivy synchronize each Scroll_y
If there are two ScrollView widgets And I want to synchronize each Scroll_y.
In my code, even when scrolling in Scroll_A it does not move itself and Scroll_B does not move in real time.
What kind of code should I write to synchronize Scroll_y with these two ScrollViews in real time?</p>

```<code>python
from kivy.app            import App
from kivy.lang           import Builder
from kivy.uix.scrollview import ScrollView
from kivy.properties     import ObjectProperty

class Scroll_A(ScrollView):
    scroll_b = ObjectProperty(None)
    def on_scroll_move(self, touch):
        self.scroll_b.scroll_y = self.scroll_y

class Scroll_B(ScrollView):
    def on_scroll_move(self, touch):
        pass

Mykv = '''
GridLayout:
    cols: 2
    spacing: 100, 100
    padding: 50, 50, 50, 50
    Scroll_A:
        id: scroll_a
        scroll_b: scroll_b
        do_scroll_y: True
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'X' * 1000
    Scroll_B:
        id: scroll_b
        do_scroll_y: True
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'Y' * 1000
'''

class MyApp(App):

    def build(self):
        return Builder.load_string(Mykv)

if __name__ == '__main__':
    MyApp().run()
</code>```

答:
I solved my problem.</p>

```<code>#python
from kivy.app            import App
from kivy.lang           import Builder
from kivy.uix.scrollview import ScrollView
from kivy.properties     import ObjectProperty

class Scroll_A(ScrollView):
    scroll_b = ObjectProperty(None)
    pass

class Scroll_B(ScrollView):
    pass

Mykv = '''
GridLayout:
    cols: 2
    spacing: 100, 100
    padding: 50, 50, 50, 50
    Scroll_A:
        id: scroll_a
        scroll_b: scroll_b
        do_scroll_y: False
        scroll_y: self.scroll_b.scroll_y
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'X' * 10000
    Scroll_B:
        id: scroll_b
        do_scroll_y: True
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'Y' * 10000
'''

class MyApp(App):

    def build(self):
        return Builder.load_string(Mykv)

if __name__ == '__main__':
    MyApp().run()
</code>```

Title: kivy synchronize each Scroll_y

Body:
If there are two ScrollView widgets And I want to synchronize each Scroll_y.
In my code, even when scrolling in Scroll_A it does not move itself and Scroll_B does not move in real time.
What kind of code should I write to synchronize Scroll_y with these two ScrollViews in real time?

python
from kivy.app            import App
from kivy.lang           import Builder
from kivy.uix.scrollview import ScrollView
from kivy.properties     import ObjectProperty

class Scroll_A(ScrollView):
    scroll_b = ObjectProperty(None)
    def on_scroll_move(self, touch):
        self.scroll_b.scroll_y = self.scroll_y

class Scroll_B(ScrollView):
    def on_scroll_move(self, touch):
        pass

Mykv = '''
GridLayout:
    cols: 2
    spacing: 100, 100
    padding: 50, 50, 50, 50
    Scroll_A:
        id: scroll_a
        scroll_b: scroll_b
        do_scroll_y: True
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'X' * 1000
    Scroll_B:
        id: scroll_b
        do_scroll_y: True
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'Y' * 1000
'''

class MyApp(App):

    def build(self):
        return Builder.load_string(Mykv)

if __name__ == '__main__':
    MyApp().run()

Body:
I solved my problem.

#python
from kivy.app            import App
from kivy.lang           import Builder
from kivy.uix.scrollview import ScrollView
from kivy.properties     import ObjectProperty

class Scroll_A(ScrollView):
    scroll_b = ObjectProperty(None)
    pass

class Scroll_B(ScrollView):
    pass

Mykv = '''
GridLayout:
    cols: 2
    spacing: 100, 100
    padding: 50, 50, 50, 50
    Scroll_A:
        id: scroll_a
        scroll_b: scroll_b
        do_scroll_y: False
        scroll_y: self.scroll_b.scroll_y
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'X' * 10000
    Scroll_B:
        id: scroll_b
        do_scroll_y: True
        pos_hint: {'top': 1}
        Label:
            size_hint_y: None
            text_size: self.width, None
            color: 1,1,1,1
            height: self.texture_size[1]
            text: 'Y' * 10000
'''

class MyApp(App):

    def build(self):
        return Builder.load_string(Mykv)

if __name__ == '__main__':
    MyApp().run()


问:
How to check if jsonjavaobject is already part of an array?
I am building a simple array of jsonobjects via:

```<code>var jsonObjArr = sessionScope.get("tmpAssessors");

var jsonObj:com.ibm.commons.util.io.json.JsonJavaObject = new com.ibm.commons.util.io.json.JsonJavaObject();

var area = getComponent("inpArea").value;
var person = getComponent("personField").value;

jsonObj.putJsonProperty("area", area);
jsonObj.putJsonProperty("person", person);

jsonObjArr.push(jsonObj);

sessionScope.put("tmpAssessors",jsonObjArr);
</code>```

However I would like to check if a similar jsonobject (same key-pair values) is already in the array so I will not push it in a second time.

How can I check this?

答:
Provided that JsonJavaObject.equals performs a correct equality check, your code should work if you replace jsonObjArr.push(jsonObj); with the following:

```<code>var _doesArrayContainElement=function(a,e){
    var i;
    for (i=0;i<a.length;i++) {
        if (a[i].equals(e)) return true;
    }
    return false;
}

if (!_doesArrayContainElement(jsonObjArr,jsonObj)) jsonObjArr.push(jsonObj);
</code>```

Body:
I am building a simple array of jsonobjects via:

var jsonObjArr = sessionScope.get("tmpAssessors");

var jsonObj:com.ibm.commons.util.io.json.JsonJavaObject = new com.ibm.commons.util.io.json.JsonJavaObject();

var area = getComponent("inpArea").value;
var person = getComponent("personField").value;

jsonObj.putJsonProperty("area", area);
jsonObj.putJsonProperty("person", person);

jsonObjArr.push(jsonObj);

sessionScope.put("tmpAssessors",jsonObjArr);

However I would like to check if a similar jsonobject (same key-pair values) is already in the array so I will not push it in a second time.

How can I check this?

Body:
Provided that JsonJavaObject.equals performs a correct equality check, your code should work if you replace jsonObjArr.push(jsonObj); with the following:

var _doesArrayContainElement=function(a,e){
    var i;
    for (i=0;i<a.length;i++) {
        if (a[i].equals(e)) return true;
    }
    return false;
}

if (!_doesArrayContainElement(jsonObjArr,jsonObj)) jsonObjArr.push(jsonObj);


问:
R code: Plot multiple lines in one graph
I need to produce a line graph with two lines into the graph, one for the return of an asset and the other for a "Compound" factor, on the X axis you will have the days. My current code is the following:

```<code>lines(1:64,dataf[,3])
lines(1:64,data2$Change)
</code>```

This of course gives me two line graphs, but I would like to have one graph with 1:64 (the days) on the X axis and "dataf[,3]" plus "data2$Change" as lines, can someone help me? thanks!!

答:
You should first use plot() to create a new plot. lines() will add your line to the existing plot. Example:

```<code>plot(x = seq(1:10), y = seq(1:10),type = "l",col = "red")
lines(x = seq(1,10), y = seq(1,20,by=2), col = "green")
</code>```

Body:
I need to produce a line graph with two lines into the graph, one for the return of an asset and the other for a "Compound" factor, on the X axis you will have the days. My current code is the following:

lines(1:64,dataf[,3])
lines(1:64,data2$Change)

This of course gives me two line graphs, but I would like to have one graph with 1:64 (the days) on the X axis and "dataf[,3]" plus "data2$Change" as lines, can someone help me? thanks!!

Body:
You should first use plot() to create a new plot. lines() will add your line to the existing plot. Example:

plot(x = seq(1:10), y = seq(1:10),type = "l",col = "red")
lines(x = seq(1,10), y = seq(1,20,by=2), col = "green")


问:
how to countif, if i want to conunt over 100% results in not a consecutive column?
if there are texts and numbers(%) mixed in column(A1:A6), how can I count those numbers which are over 100%? for example

```<code>ex. A B C D E
1 text
2 90%
3 text
4 120%
5 text
6 150%
</code>```

using countif or Suggest me

答:
COUNTIF will ignore the text values if you use a numeric criterion, so you can use just a simple

=COUNTIF(A1:A6,">100%")

Body:
if there are texts and numbers(%) mixed in column(A1:A6), how can I count those numbers which are over 100%? for example

ex. A B C D E
1 text
2 90%
3 text
4 120%
5 text
6 150%

using countif or Suggest me


问:
MySQL performance: raw query vs. stored procedure
As I know there is know significant performance difference between raw queries and stored procedures in MSSQL (for example, query plans are cached in the same way for both). But what about MySQL? </p>

答: First, the value in SP is not in performance, hasn't been for some time. The value in stored procedures has more to do with security and data lifespan. Take a look at the article linked here a couple of years ago - Is this a valid benefit of using embedded SQL over stored procedures?</p>


问:
How to insert data into two tables in rails at the same time?
I am trying from last 2 days to figure out this problem but no avail till now. I am working on omniauth in rails and I have integrated the omniauth authentication in my site but I want to create seperate table for all providers.I have two tables 1: user and other is auth_provider
1: user will contain user data
2: auth_provder will contain user_id with social media provider authentication details.

I have created has_many association from user to auth_providers.

Now I want to insert the data in both tables so that first the would create entry in user table with some fields and then it should take the newly insert record entry and insert this id with other data into auth_providers table. I know this thing is possible but I am unable to find any example or code. I am just searching and trying from last 2 days but still no success. I want to do it using associations and I have also used nested_attributes but still no success.

Here is my code

user model:

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable,
    :omniauthable, :omniauth_providers => [:facebook,:twitter,:linkedin]
  has_many :organizations_users
  has_many :auth_providers
  has_many :organizations, through: :organizations_users
  accepts_nested_attributes_for :auth_providers
    def active_for_authentication?
    # Uncomment the below debug statement to view the properties of the returned self model values.
    super && self.active && self.exp_alert == false
  end

  def self.from_omniauth(auth)
    exist = where(email: auth.info.email).first
    if exist
      existing_user = exist["id"]
      Auth_provider.where(provider: auth.provider, social_uid: auth.uid).first_or_create do |auth_provider|
      auth_provider.provider =  auth.provider
      auth_provider.social_uid = auth.uid
      auth_provider.social_token = auth.credentials.token
      auth_provider.user_id = existing_user
      end
    else
      #@organization.users.create(first_name:params[:first_name])
      names = auth.info.name.strip.split(" ")
      first_name = names[0]
      last_name = names[1]

      params = { user: {
    email: 'abc@abc.com', auth_providers_attributes: [
    { provider: 'facebook' },
    { social_token: 'asfasf2342432' },
    { social_uid: 'asfdaf23242'} # this will be ignored
    ]
  }}
user = User.create(params[:user])

              end
  end

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end

  def self.find_or_create_from_auth_hash(auth_hash)
    user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create do |user|
      user.first_name =  auth_hash.info.nickname
      user.active = 'true'
      user.admin=='false'
      user.exp_alert = 'false'
      user.password = Devise.friendly_token[0,20]
      user.token =  auth_hash.credentials.token
      user.email =  auth_hash.info.email
      user.secret =  auth_hash.credentials.secret
      user.skip_confirmation!
    end
    user
  end

  def self.linkedin_hash(auth_hash)
    user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create do |user|
      user.first_name =  auth_hash.info.first_name
      user.last_name =  auth_hash.info.last_name
      user.active = 'true'
      user.admin = 'false'
      user.exp_alert = 'false'
      user.password = Devise.friendly_token[0,20]
      user.token =  auth_hash.credentials.token
      user.email =  auth_hash.info.email
      user.skip_confirmation!
    end
    user
  end

  def inactive_message
    "Your Account has not been active yet."
  end

  def after_confirmation
    super
    self.update_attribute(:active, true)
  end
end
</code>```

auth_providers model

```<code>class Auth_provider < ApplicationRecord
devise :database_authenticatable
belongs_to :user

 accepts_nested_attributes_for :user
end
</code>```

Response from facebook is this

```<code>#<OmniAuth::AuthHash credentials=#<OmniAuth::AuthHash expires=true expires_at=1517924507 token="EAAdDsC4F0CCLq95eo81qfaMVVs0zeNgqtRqUF9ufZB3gK609NY3aiikJ9AvE8zSB63WFcG0E6NBFNIWf00DjgHNlsQHCd2D26uxJ1ongQ5YBJZCeuZAOas2SEYlRwPYhctfiEVVdbadOyA3QeL50JHIA5dKa3xdfK5Efw9Y"> extra=#<OmniAuth::AuthHash raw_info=#<OmniAuth::AuthHash email="testing@gmail.com" id="35232364989259" name="John">> info=#<OmniAuth::AuthHash::InfoHash email="testing@gmail.com" image="http://graph.facebook.com/v2.6/35489/picture" name="John"> provider="facebook" uid="354814524989259">
</code>```

答:
If I'm understanding you right, could you do something like:

```<code>...
user = User.create(the_user_attributes)
user.auth_providers.create(the_auth_provider_attributes)
...
</code>```

This should work, creating a user, then an auth provider belonging to them.

You can also use User.new and user.auth_providers.build if you need to manipulate either a little ahead of saving, and they'll be persisted when you call save on the user.

Update

To split the code into readable chunks, I'd suggest something like the following:

user.rb

```<code># update: you're in the user model, so no need to specify the model again in the line below
user = create(user_attributes_from_auth(auth))
user.auth_providers.create(provider_attributes_from_auth(auth))

private

def user_attributes_from_auth(auth)
  { first_name: auth.info.nickname,
    token: auth_hash.credentials.token,
    etc: etc }
end

def provider_attributes_from_auth(auth)
  { a_similar_approach_as: user_attributes_from_auth }
end
</code>```

So, in a nutshell, you use the first two lines in there ^^ to create a user from a hash of attributes, then do the same for the auth provider.

This is nice and readable, and not actually far off what you're currently doing. Have a go and see how you get on - hope it helps!

Body:
I am trying from last 2 days to figure out this problem but no avail till now. I am working on omniauth in rails and I have integrated the omniauth authentication in my site but I want to create seperate table for all providers.I have two tables 1: user and other is auth_provider
1: user will contain user data
2: auth_provder will contain user_id with social media provider authentication details.

I have created has_many association from user to auth_providers.

Now I want to insert the data in both tables so that first the would create entry in user table with some fields and then it should take the newly insert record entry and insert this id with other data into auth_providers table. I know this thing is possible but I am unable to find any example or code. I am just searching and trying from last 2 days but still no success. I want to do it using associations and I have also used nested_attributes but still no success.

Here is my code

user model:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable,
    :omniauthable, :omniauth_providers => [:facebook,:twitter,:linkedin]
  has_many :organizations_users
  has_many :auth_providers
  has_many :organizations, through: :organizations_users
  accepts_nested_attributes_for :auth_providers
    def active_for_authentication?
    # Uncomment the below debug statement to view the properties of the returned self model values.
    super && self.active && self.exp_alert == false
  end

  def self.from_omniauth(auth)
    exist = where(email: auth.info.email).first
    if exist
      existing_user = exist["id"]
      Auth_provider.where(provider: auth.provider, social_uid: auth.uid).first_or_create do |auth_provider|
      auth_provider.provider =  auth.provider
      auth_provider.social_uid = auth.uid
      auth_provider.social_token = auth.credentials.token
      auth_provider.user_id = existing_user
      end
    else
      #@organization.users.create(first_name:params[:first_name])
      names = auth.info.name.strip.split(" ")
      first_name = names[0]
      last_name = names[1]

      params = { user: {
    email: 'abc@abc.com', auth_providers_attributes: [
    { provider: 'facebook' },
    { social_token: 'asfasf2342432' },
    { social_uid: 'asfdaf23242'} # this will be ignored
    ]
  }}
user = User.create(params[:user])

              end
  end

  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end

  def self.find_or_create_from_auth_hash(auth_hash)
    user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create do |user|
      user.first_name =  auth_hash.info.nickname
      user.active = 'true'
      user.admin=='false'
      user.exp_alert = 'false'
      user.password = Devise.friendly_token[0,20]
      user.token =  auth_hash.credentials.token
      user.email =  auth_hash.info.email
      user.secret =  auth_hash.credentials.secret
      user.skip_confirmation!
    end
    user
  end

  def self.linkedin_hash(auth_hash)
    user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create do |user|
      user.first_name =  auth_hash.info.first_name
      user.last_name =  auth_hash.info.last_name
      user.active = 'true'
      user.admin = 'false'
      user.exp_alert = 'false'
      user.password = Devise.friendly_token[0,20]
      user.token =  auth_hash.credentials.token
      user.email =  auth_hash.info.email
      user.skip_confirmation!
    end
    user
  end

  def inactive_message
    "Your Account has not been active yet."
  end

  def after_confirmation
    super
    self.update_attribute(:active, true)
  end
end

auth_providers model

class Auth_provider < ApplicationRecord
devise :database_authenticatable
belongs_to :user

 accepts_nested_attributes_for :user
end

Response from facebook is this

#<OmniAuth::AuthHash credentials=#<OmniAuth::AuthHash expires=true expires_at=1517924507 token="EAAdDsC4F0CCLq95eo81qfaMVVs0zeNgqtRqUF9ufZB3gK609NY3aiikJ9AvE8zSB63WFcG0E6NBFNIWf00DjgHNlsQHCd2D26uxJ1ongQ5YBJZCeuZAOas2SEYlRwPYhctfiEVVdbadOyA3QeL50JHIA5dKa3xdfK5Efw9Y"> extra=#<OmniAuth::AuthHash raw_info=#<OmniAuth::AuthHash email="testing@gmail.com" id="35232364989259" name="John">> info=#<OmniAuth::AuthHash::InfoHash email="testing@gmail.com" image="http://graph.facebook.com/v2.6/35489/picture" name="John"> provider="facebook" uid="354814524989259">

Body:
If I'm understanding you right, could you do something like:

...
user = User.create(the_user_attributes)
user.auth_providers.create(the_auth_provider_attributes)
...

This should work, creating a user, then an auth provider belonging to them.

You can also use User.new and user.auth_providers.build if you need to manipulate either a little ahead of saving, and they'll be persisted when you call save on the user.

Update

To split the code into readable chunks, I'd suggest something like the following:

user.rb

# update: you're in the user model, so no need to specify the model again in the line below
user = create(user_attributes_from_auth(auth))
user.auth_providers.create(provider_attributes_from_auth(auth))

private

def user_attributes_from_auth(auth)
  { first_name: auth.info.nickname,
    token: auth_hash.credentials.token,
    etc: etc }
end

def provider_attributes_from_auth(auth)
  { a_similar_approach_as: user_attributes_from_auth }
end

So, in a nutshell, you use the first two lines in there ^^ to create a user from a hash of attributes, then do the same for the auth provider.

This is nice and readable, and not actually far off what you're currently doing. Have a go and see how you get on - hope it helps!


问:
Displaying wp post from another WP site
I have two WordPress installations, one is main domain and the other one is sub-domain. Also, both sites use different database. Now I want to automatically post content from subdomain to Main Domain.Is there a way to show the most recent post from the second(sub-domain) site on my first(main domain) sites?
Thanks</p>

答:
I'm Able to solve this.
here is the way:
Step 1: Copy the following code wherever you want to display your original WordPress posts:

```<code><?php
include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed('http://my-subdomain.com/feed/');
if(!empty($rss)):
$maxitems = $rss->get_item_quantity(4);
$rss_items = $rss->get_items(0, $maxitems);
endif;
?>
</code>```

Step 2: Add this to your code (preferably right after the snippet above):

```<code><ul>
<?php if ($maxitems == 0) echo 'No news.';
else
foreach ( $rss_items as $item ) : ?>
<li><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></li>
<?php endforeach; ?>
</ul>
</code>```

Title: Displaying wp post from another WP site

Body:
I'm Able to solve this.
here is the way:
Step 1: Copy the following code wherever you want to display your original WordPress posts:

<?php
include_once(ABSPATH . WPINC . '/feed.php');
$rss = fetch_feed('http://my-subdomain.com/feed/');
if(!empty($rss)):
$maxitems = $rss->get_item_quantity(4);
$rss_items = $rss->get_items(0, $maxitems);
endif;
?>

Step 2: Add this to your code (preferably right after the snippet above):

<ul>
<?php if ($maxitems == 0) echo 'No news.';
else
foreach ( $rss_items as $item ) : ?>
<li><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></li>
<?php endforeach; ?>
</ul>


问:
Google Maps pushing content down?
I have two columns, contact information on the left and a google map on the right. However the Google Map is pushing all of the content in the left column now when I don't want it to. It's probably something simple but I can't seem to get it working. I understand that the google map won't work without the API key, but I have already requested one and that is not needed anyway, as the content is still pushed down on the left column. The columns stack when the screen is at mobile size and that works correctly, it's just for desktop screens where the two columns are shown side by side. Thank you for your help!</p>

答:
```<code>.leftColumn {
    vertical-align: top;
}
</code>```

Will align your left column content back to the top. With elements that sit next to each other, it's often a headache saver to include the vertical-align property.

Title: Google Maps pushing content down?

Body:
.leftColumn {
    vertical-align: top;
}

Will align your left column content back to the top. With elements that sit next to each other, it's often a headache saver to include the vertical-align property.


问:
Is there a way to extract timezone_abbr from snowflake database?
ORACLE Query: select extract(timezone_abbr FROM sysdate at TIME zone 'America/New_York') from dual;

Is there any way to get the timezone_abbr in snowflake database, similar to what we are doing in ORACLE?

答:
There is no direct way to extract timezone abbreviation from snowflake similar to Oracle.
But we can find it by calculating the difference between the 2 time zones.

```<code>SELECT cast(your_column AS TIMESTAMP) yourtimecolumn
    ,decode(
        extract(
           hour FROM
            convert_timezone('America/New_York', 'UTC',
              cast(your_column AS TIMESTAMP)
            )
          ) -
      extract(hour FROM cast(your_column AS TIMESTAMP)
      ),
  4, 'EDT', -20, 'EDT', 5, 'EST', -19, 'EST') timezone
FROM your_table
WHERE cast(your_column AS TIMESTAMP) IS NOT NULL
limit 100
</code>```

The above query assumes your timestamp is in America/Newyork and it tries to convert it to UTC since that is the global time zone.

After the conversion, as the usual way if the difference is 4 then the timezone is in EDT and if the difference is 5 then the timezone is in EST.

EDIT: To include the time that exceeds a day due to the UTC conversion

Body:
There is no direct way to extract timezone abbreviation from snowflake similar to Oracle.
But we can find it by calculating the difference between the 2 time zones.

SELECT cast(your_column AS TIMESTAMP) yourtimecolumn
    ,decode(
        extract(
           hour FROM
            convert_timezone('America/New_York', 'UTC',
              cast(your_column AS TIMESTAMP)
            )
          ) -
      extract(hour FROM cast(your_column AS TIMESTAMP)
      ),
  4, 'EDT', -20, 'EDT', 5, 'EST', -19, 'EST') timezone
FROM your_table
WHERE cast(your_column AS TIMESTAMP) IS NOT NULL
limit 100

The above query assumes your timestamp is in America/Newyork and it tries to convert it to UTC since that is the global time zone.

After the conversion, as the usual way if the difference is 4 then the timezone is in EDT and if the difference is 5 then the timezone is in EST.

EDIT: To include the time that exceeds a day due to the UTC conversion