问:
Neo4j service not starting
I have been using Neo4j for more than 3 months on this server. Not sure what changed, but today morning I am unable to start Neo4j server.

Till today everything was fine and there were not changes that I know of were made to Neo4j or anything else.
I am currently using neo4j 3.1.0.

The following is the error log.

```<code>    xxx@dataserver:~$ sudo neo4j console
Starting Neo4j.
WARNING: Max 1024 open files allowed, minimum of 40000 recommended. See the Neo4j manual.
2017-05-01 03:09:17.948+0000 INFO  Starting...
2017-05-01 03:09:18.616+0000 INFO  Bolt enabled on 0.0.0.0:7687.
2017-05-01 03:09:20.766+0000 ERROR Failed to start Neo4j: Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception. Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception.
org.neo4j.server.ServerStartupException: Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception.
        at org.neo4j.server.exception.ServerStartupErrors.translateToServerStartupError(ServerStartupErrors.java:68)
        at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:227)
        at org.neo4j.server.ServerBootstrapper.start(ServerBootstrapper.java:91)
        at org.neo4j.server.ServerBootstrapper.start(ServerBootstrapper.java:68)
        at org.neo4j.server.CommunityEntryPoint.main(CommunityEntryPoint.java:28)
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception.
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:443)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
        at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:199)
        ... 3 more
Caused by: java.lang.RuntimeException: Error starting org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory, /var/lib/neo4j/data/databases/default.graphdb
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.initFacade(GraphDatabaseFacadeFactory.java:193)
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:124)
        at org.neo4j.server.CommunityNeoServer.lambda$static$0(CommunityNeoServer.java:57)
        at org.neo4j.server.database.LifecycleManagingDatabase.start(LifecycleManagingDatabase.java:89)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:433)
        ... 5 more
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.recovery.Recovery@4b1ec7fa' failed to initialize. Please see attached cause exception.
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:415)
        at org.neo4j.kernel.lifecycle.LifeSupport.init(LifeSupport.java:62)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:98)
        at org.neo4j.kernel.NeoStoreDataSource.start(NeoStoreDataSource.java:517)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:433)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
        at org.neo4j.kernel.impl.transaction.state.DataSourceManager.start(DataSourceManager.java:100)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:433)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.initFacade(GraphDatabaseFacadeFactory.java:189)
        ... 9 more
Caused by: java.lang.IllegalArgumentException: Unknown entry type -1 for version -1. At position LogPosition{logVersion=94, byteOffset=157773910} and entry version V2_1
        at org.neo4j.kernel.impl.transaction.log.entry.LogEntryVersion.entryParser(LogEntryVersion.java:141)
        at org.neo4j.kernel.impl.transaction.log.entry.VersionAwareLogEntryReader.readLogEntry(VersionAwareLogEntryReader.java:84)
        at org.neo4j.kernel.impl.transaction.log.LogEntryCursor.next(LogEntryCursor.java:54)
        at org.neo4j.kernel.recovery.LatestCheckPointFinder.find(LatestCheckPointFinder.java:78)
        at org.neo4j.kernel.recovery.PositionToRecoverFrom.apply(PositionToRecoverFrom.java:53)
        at org.neo4j.kernel.recovery.DefaultRecoverySPI.getPositionToRecoverFrom(DefaultRecoverySPI.java:80)
        at org.neo4j.kernel.recovery.Recovery.init(Recovery.java:80)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:405)
        ... 18 more
</code>```

答:
Stop service

Change dbms.allow_upgrade to true in neo4j config file

Start service again

I had the same problem, and upgrading the db fixed it. I would also suggest changing the password if you are still using default password. Once you start the service it should upgrade the database, once upgraded, you can change the dbms.allow_upgrade to false again if you dont want neo4j to update automatically.

Title: Neo4j service not starting

Body:
I have been using Neo4j for more than 3 months on this server. Not sure what changed, but today morning I am unable to start Neo4j server.

Till today everything was fine and there were not changes that I know of were made to Neo4j or anything else.
I am currently using neo4j 3.1.0.

The following is the error log.

    xxx@dataserver:~$ sudo neo4j console
Starting Neo4j.
WARNING: Max 1024 open files allowed, minimum of 40000 recommended. See the Neo4j manual.
2017-05-01 03:09:17.948+0000 INFO  Starting...
2017-05-01 03:09:18.616+0000 INFO  Bolt enabled on 0.0.0.0:7687.
2017-05-01 03:09:20.766+0000 ERROR Failed to start Neo4j: Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception. Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception.
org.neo4j.server.ServerStartupException: Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception.
        at org.neo4j.server.exception.ServerStartupErrors.translateToServerStartupError(ServerStartupErrors.java:68)
        at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:227)
        at org.neo4j.server.ServerBootstrapper.start(ServerBootstrapper.java:91)
        at org.neo4j.server.ServerBootstrapper.start(ServerBootstrapper.java:68)
        at org.neo4j.server.CommunityEntryPoint.main(CommunityEntryPoint.java:28)
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2241b683' was successfully initialized, but failed to start. Please see attached cause exception.
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:443)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
        at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:199)
        ... 3 more
Caused by: java.lang.RuntimeException: Error starting org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory, /var/lib/neo4j/data/databases/default.graphdb
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.initFacade(GraphDatabaseFacadeFactory.java:193)
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.newFacade(GraphDatabaseFacadeFactory.java:124)
        at org.neo4j.server.CommunityNeoServer.lambda$static$0(CommunityNeoServer.java:57)
        at org.neo4j.server.database.LifecycleManagingDatabase.start(LifecycleManagingDatabase.java:89)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:433)
        ... 5 more
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.recovery.Recovery@4b1ec7fa' failed to initialize. Please see attached cause exception.
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:415)
        at org.neo4j.kernel.lifecycle.LifeSupport.init(LifeSupport.java:62)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:98)
        at org.neo4j.kernel.NeoStoreDataSource.start(NeoStoreDataSource.java:517)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:433)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
        at org.neo4j.kernel.impl.transaction.state.DataSourceManager.start(DataSourceManager.java:100)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:433)
        at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:107)
        at org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory.initFacade(GraphDatabaseFacadeFactory.java:189)
        ... 9 more
Caused by: java.lang.IllegalArgumentException: Unknown entry type -1 for version -1. At position LogPosition{logVersion=94, byteOffset=157773910} and entry version V2_1
        at org.neo4j.kernel.impl.transaction.log.entry.LogEntryVersion.entryParser(LogEntryVersion.java:141)
        at org.neo4j.kernel.impl.transaction.log.entry.VersionAwareLogEntryReader.readLogEntry(VersionAwareLogEntryReader.java:84)
        at org.neo4j.kernel.impl.transaction.log.LogEntryCursor.next(LogEntryCursor.java:54)
        at org.neo4j.kernel.recovery.LatestCheckPointFinder.find(LatestCheckPointFinder.java:78)
        at org.neo4j.kernel.recovery.PositionToRecoverFrom.apply(PositionToRecoverFrom.java:53)
        at org.neo4j.kernel.recovery.DefaultRecoverySPI.getPositionToRecoverFrom(DefaultRecoverySPI.java:80)
        at org.neo4j.kernel.recovery.Recovery.init(Recovery.java:80)
        at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:405)
        ... 18 more


来源: stackexchange

问:
In Room drop an Entity and recreate with updated changes
I'm using Room database in my application. I've some changes in columns of the Entity , so in DB Migration I want to drop the old table and recreate it with the updated Entity. But after Drop Table query instead of writing a long query to create the table again, can we just pass the entity model somehow or tell the DB to recreate the entity? Because my Entity has a number of columns,relations and onDelete rule in it so query would be complex.

Following is the Entity:

```<code>@Entity(tableName = MediaTags.TABLE_NAME_UPLOAD_MEDIA,
        foreignKeys =
        @ForeignKey(
                entity = PostUpload.class,
                parentColumns = PostTags.COLUMN_UPLOAD_POST_LOCAL_ID,
                childColumns = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID,
                onDelete = CASCADE),
        indices = {@Index(MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)})
public class MediaUpload {
    @Ignore
    public final static int MEDIA_TYPE_IMAGE = 1;
    @Ignore
    public final static int MEDIA_TYPE_VIDEO = 2;

    @PrimaryKey
    @NonNull
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_KEY)
    public String mediaKey; // unique key
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_HASH_MD5)
    public String hashMd5;   // hashMd5 of file, for now we are sending it empty, in future will be used
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_TYPE)
    public int mediaType;  // picture or video
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_STATUS)
    public int status = UploadStatus.NOT_COMPRESSED; // upload and edit statues
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_FILE_PATH)
    public String filePath;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)
    public String postId;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_THUMBNAIL)
    public String thumbnail;  // thumbnail in case of videos
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_OVERLAY_PATH)
    public String overlayPath;  // overlay image containing all the editing

}
</code>```

答:
Assuming your previous version was 1 and now you want to update to version 2

```<code>   INSTANCE = Room.databaseBuilder(context.getApplicationContext(), RoomDatabase.class, databaseName).addMigrations(MIGRATION_1_2).build;
</code>```

To add a column

```<code>private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        // to delete a column
        database.execSQL("ALTER TABLE atable DROP COLUMN acolumn");
        // to add a new column
        database.execSQL("ALTER TABLE atable ADD COLUMN anewcolumn INTEGER NOT NULL default 0");
    }
};
</code>```

Of course, you need to use your new column type, INTEGER, TEXT, etc.

The table contents will remain unchanged with a new column initialized with the default value.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Room database in my application. I've some changes in columns of the Entity , so in DB Migration I want to drop the old table and recreate it with the updated Entity. But after Drop Table query instead of writing a long query to create the table again, can we just pass the entity model somehow or tell the DB to recreate the entity? Because my Entity has a number of columns,relations and onDelete rule in it so query would be complex.

Following is the Entity:

@Entity(tableName = MediaTags.TABLE_NAME_UPLOAD_MEDIA,
        foreignKeys =
        @ForeignKey(
                entity = PostUpload.class,
                parentColumns = PostTags.COLUMN_UPLOAD_POST_LOCAL_ID,
                childColumns = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID,
                onDelete = CASCADE),
        indices = {@Index(MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)})
public class MediaUpload {
    @Ignore
    public final static int MEDIA_TYPE_IMAGE = 1;
    @Ignore
    public final static int MEDIA_TYPE_VIDEO = 2;

    @PrimaryKey
    @NonNull
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_KEY)
    public String mediaKey; // unique key
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_HASH_MD5)
    public String hashMd5;   // hashMd5 of file, for now we are sending it empty, in future will be used
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_TYPE)
    public int mediaType;  // picture or video
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_STATUS)
    public int status = UploadStatus.NOT_COMPRESSED; // upload and edit statues
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_FILE_PATH)
    public String filePath;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)
    public String postId;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_THUMBNAIL)
    public String thumbnail;  // thumbnail in case of videos
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_OVERLAY_PATH)
    public String overlayPath;  // overlay image containing all the editing

}

Body:
Assuming your previous version was 1 and now you want to update to version 2

   INSTANCE = Room.databaseBuilder(context.getApplicationContext(), RoomDatabase.class, databaseName).addMigrations(MIGRATION_1_2).build;

To add a column

private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        // to delete a column
        database.execSQL("ALTER TABLE atable DROP COLUMN acolumn");
        // to add a new column
        database.execSQL("ALTER TABLE atable ADD COLUMN anewcolumn INTEGER NOT NULL default 0");
    }
};

Of course, you need to use your new column type, INTEGER, TEXT, etc.

The table contents will remain unchanged with a new column initialized with the default value.


问:
Compare multiple Lists only one time each in python
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
```

<p>This prints :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2
```

<p>And i would like this result :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2
```

Thanks you for your help !

答:
You can utilize set.intersection to compare the lists:

```<code>resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

s = set()
for list1 in resultList:
    for list2 in resultList:
        i = tuple(sorted([list1[0], list2[0]]))
        if i in s:
            continue
        s.add(i)
        print(list1[0], list2[0], len(set(list1[1]).intersection(list2[1])))
</code>```

Prints:

```<code>Student1 Student1 2
Student1 Student2 0
Student1 Student3 1
Student1 Student4 1
Student2 Student2 2
Student2 Student3 0
Student2 Student4 0
Student3 Student3 2
Student3 Student4 0
Student4 Student4 2
</code>```

Body:
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))

This prints :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2

And i would like this result :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2

Thanks you for your help !

Body:
You can utilize set.intersection to compare the lists:

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

s = set()
for list1 in resultList:
    for list2 in resultList:
        i = tuple(sorted([list1[0], list2[0]]))
        if i in s:
            continue
        s.add(i)
        print(list1[0], list2[0], len(set(list1[1]).intersection(list2[1])))

Prints:

Student1 Student1 2
Student1 Student2 0
Student1 Student3 1
Student1 Student4 1
Student2 Student2 2
Student2 Student3 0
Student2 Student4 0
Student3 Student3 2
Student3 Student4 0
Student4 Student4 2


问:
JavaScript memory loss with Prototype's Ajax.Updater?
I'm not sure this is a Prototype specific issue, but since I don't have the problem when not using Prototype I guess it is.

I'm using Ajax.Updater to append some external HTML to my DOM tree. In the external file there are some script elements. Since I have set the evalScripts options to true, they are all evaluated. But when I later try to access objects that have been set in the script elements, they no longer exists. For example:

```<code><script type="text/javascript">
    var test = true;
    console.log(test); // Works fine, obviously.
</script>

<input type="text" onkeydown="console.log(test)"> <!-- Throws an ReferenceError exception (test is not defined) when the event is fired. -->
</code>```

If I request this with Ajax.Updater the script element will run as expected, but after the evaluation the test variable seems to be deleted. Anyone who knows what's going on?

答:
You can solve the issue with

```<code><script type="text/javascript">
    window.test = true; // global on window
    console.log(test); // Works fine, obviously.
</script>
</code>```

Ajax.Updater will eventually call this on your scripts:

```<code>function evalScripts() {
    return this.extractScripts().map(function(script) { return eval(script) });
}
</code>```

since eval works locally you find that var test is actually a local variables of function(script) { ... }

This is your issue. It's an issue with prototype not doing global evals like jQuery does.

You can either look hard for it or bump this ticket.

ContentLicense: CC BY-SA 3.0

Body:
I'm not sure this is a Prototype specific issue, but since I don't have the problem when not using Prototype I guess it is.

I'm using Ajax.Updater to append some external HTML to my DOM tree. In the external file there are some script elements. Since I have set the evalScripts options to true, they are all evaluated. But when I later try to access objects that have been set in the script elements, they no longer exists. For example:

<input type="text" onkeydown="console.log(test)">

If I request this with Ajax.Updater the script element will run as expected, but after the evaluation the test variable seems to be deleted. Anyone who knows what's going on?

Body:
You can solve the issue with

<script type="text/javascript">
    window.test = true; // global on window
    console.log(test); // Works fine, obviously.
</script>

Ajax.Updater will eventually call this on your scripts:

function evalScripts() {
    return this.extractScripts().map(function(script) { return eval(script) });
}

since eval works locally you find that var test is actually a local variables of function(script) { ... }

This is your issue. It's an issue with prototype not doing global evals like jQuery does.

You can either look hard for it or bump this ticket.


答:
The idea is similar to @yatu's answer, but rather than manually keep count, you can use enumerate, and iterate over only the part of list2 after the current index in list1. If you want to avoid 1-1 2-2 pairs, just use resultList[idx+1:] instead of resultList[idx:].

```<code>resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for idx, list1 in enumerate(resultList):
    for list2 in resultList[idx:]:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
</code>```

Title: Compare multiple Lists only one time each in python

Body:
The idea is similar to @yatu's answer, but rather than manually keep count, you can use enumerate, and iterate over only the part of list2 after the current index in list1. If you want to avoid 1-1 2-2 pairs, just use resultList[idx+1:] instead of resultList[idx:].

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for idx, list1 in enumerate(resultList):
    for list2 in resultList[idx:]:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))


问:
extract an element from an html declaration
I am using scrapy selectors and I am trying to extract the element "1" in from the HTML declaration below:

```<code><li aria-label="Pagina" class="page active"><a href="#">1</a></li>
</code>```

I have two equal declarations in the whole HTML source content.

```<code><div class="row paging-bar">
    <ul class="sync-pagination pagination pull-right">
       <li aria-label="Pagina" class="prev"><a href="#"><</a></li>
       <li aria-label="Pagina" class="page active"><a href="#">1</a></li>
       <li aria-label="Pagina" class="page"><a href="#">2</a></li>
       <li aria-label="Pagina" class="page"><a href="#">3</a></li>
       <li aria-label="Pagina" class="page"><a href="#">4</a></li>
       <li aria-label="Pagina" class="page"><a href="#">5</a></li>
       <li aria-label="Pagina" class="page"><a href="#">6</a></li>
       <li><span>...</span></li>
       <li aria-label="Pagina" class="page"><a href="#">1405</a></li>
      <li aria-label="Pagina" class="next"><a href="#">></a></li>
    </ul>
</div>
</code>```

```<code><div class="row paging-bar">
    <ul class="sync-pagination pagination pull-right">
       <li aria-label="Pagina" class="prev"><a href="#"><</a></li>
       <li aria-label="Pagina" class="page active"><a href="#">1</a></li>
       <li aria-label="Pagina" class="page"><a href="#">2</a></li>
       <li aria-label="Pagina" class="page"><a href="#">3</a></li>
       <li aria-label="Pagina" class="page"><a href="#">4</a></li>
       <li aria-label="Pagina" class="page"><a href="#">5</a></li>
       <li aria-label="Pagina" class="page"><a href="#">6</a></li>
       <li><span>...</span></li>
       <li aria-label="Pagina" class="page"><a href="#">1405</a></li>
       <li aria-label="Pagina" class="next"><a href="#">></a></li>
    </ul>
</div></div>
</code>```

I have tried the command:

```<code>response.xpath("normalize-space(//li[@class='page active']/a[@href]/text())").extract_first()
</code>```

but it returned an empty string.

Body:
I am using scrapy selectors and I am trying to extract the element "1" in from the HTML declaration below:

1

I have two equal declarations in the whole HTML source content.

<

1

2

3

4

5

6

...

1405

>

<

1

2

3

4

5

6

...

1405

>

I have tried the command:

response.xpath("normalize-space(//li[@class='page active']/a[@href]/text())").extract_first()

but it returned an empty string.

Body:
It works.

>>> html = """
... <div class="row paging-bar">
...     <ul class="sync-pagination pagination pull-right">
...        <li aria-label="Pagina" class="prev"><a href="#">&lt;</a></li>
...        <li aria-label="Pagina" class="page active"><a href="#">1</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">2</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">3</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">4</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">5</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">6</a></li>
...        <li><span>...</span></li>
...        <li aria-label="Pagina" class="page"><a href="#">1405</a></li>
...       <li aria-label="Pagina" class="next"><a href="#">&gt;</a></li>
...     </ul>
... </div>
... """
>>> from parsel import Selector
>>> selector = Selector(text=html)
>>> selector.xpath("normalize-space(//li[@class='page active']/a[@href]/text())").extract_first()
'1'
>>> html = """
... <div class="row paging-bar">
...     <ul class="sync-pagination pagination pull-right">
...        <li aria-label="Pagina" class="prev"><a href="#">&lt;</a></li>
...        <li aria-label="Pagina" class="page active"><a href="#">1</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">2</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">3</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">4</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">5</a></li>
...        <li aria-label="Pagina" class="page"><a href="#">6</a></li>
...        <li><span>...</span></li>
...        <li aria-label="Pagina" class="page"><a href="#">1405</a></li>
...        <li aria-label="Pagina" class="next"><a href="#">&gt;</a></li>
...     </ul>
... </div></div>
... """
>>> selector = Selector(text=html)
>>> selector.xpath("normalize-space(//li[@class='page active']/a[@href]/text())").extract_first()
'1'


问:
Check if any of the files within a folder contain a pattern then return filename
I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this:

I have a nginx sites-enabled folder which contain some reverses proxied sites.
I need to:

check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/"

return the name of the file containing $var1 as $var2

Many thanks for your attention and help!

I have found some lines but none try any files in a folder

```<code>if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then
  echo "found"
fi
</code>```

答:
find and grep can be used to produce a list of matching files:

```<code>find /volume1/nginx/sites-enabled/ -type f -exec grep -le "${var1}" {} +
</code>```

The ‘trick’ is using find’s -exec and grep’s -l.

If you only want the filenames you could use:

```<code>find /volume1/nginx/sites-enabled/ -type f -exec grep -qe "${var1}" {} \; -exec basename {} \;
</code>```

If you want to assign the result to a variable use command substitution ($()):

```<code>var2="$(find …)"
</code>```

Don’t forget to quote your variables!

Body:
I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this:

I have a nginx sites-enabled folder which contain some reverses proxied sites.
I need to:

check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/"

return the name of the file containing $var1 as $var2

Many thanks for your attention and help!

I have found some lines but none try any files in a folder

if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then
  echo "found"
fi

Body:
find and grep can be used to produce a list of matching files:

find /volume1/nginx/sites-enabled/ -type f -exec grep -le "${var1}" {} +

The ‘trick’ is using find’s -exec and grep’s -l.

If you only want the filenames you could use:

find /volume1/nginx/sites-enabled/ -type f -exec grep -qe "${var1}" {} \; -exec basename {} \;

If you want to assign the result to a variable use command substitution ($()):

var2="$(find …)"

Don’t forget to quote your variables!


问:
Running Python Azure Functions on Windows 10 using VSCode
I am trying to develop Azure Functions in Python on Windows 10 PC. Every time I try to debug it I get this error: "AttributeError: module 'azure.functions_worker' has no attribute 'start_async' "

I am running Python 3.6.8,
Azure Function Core Tools (2.7.1158)
And Function Run time: 2.0.12438.0
VSCode latest

Tried to remove and re-install the Azure CLI

答: I had exactly this problem on Win10 when I was using Python 3.6-32bit. Installing Python 3.6-64bit made the error go away, so it is worth giving that a try if you haven't already.


问:
Composer Fatal error: Declaration of Fxp... must be compatible with ...AbstractAssetsRepository.php on line 334
I updated composer

```<code>composer self-update
</code>```

I installed the newer version of the plugin

```<code>composer global require "fxp/composer-asset-plugin:*"
</code>```

I try to install Laravel

composer global require "laravel/installer"

```<code>Changed current directory to C:/Users/Arthur/AppData/Roaming/Composer
Fatal error: Declaration of Fxp\Composer\AssetPlugin\Repository\AbstractAssetsRe
    pository::search() must be compatible with Composer\Repository\RepositoryInterfa
    ce::search($query, $mode = 0, $type = NULL) in C:\Users\Arthur\AppData\Roaming\C
    omposer\vendor\fxp\composer-asset-plugin\Repository\AbstractAssetsRepository.php
     on line 334
</code>```

Now all commands in composer not working

```<code>composer <any command>
</code>```

Please help me to resolve it

答:
To solve the above error while installing composer asset plugin please do the following

delete fxp folder in the path C:\Users\UserName\AppData\Roaming\Composer\vendor

remove "fxp/composer-asset-plugin": "^1.4"  from composer.json file in composer folder

run this command
composer global remove fxp/composer-asset-plugin --no-plugins
to make sure no fxp folder is left and json data

composer global require fxp/composer-asset-plugin --no-plugins
Run this command to install composer asset plugin and it will be installed easily

If you want to update existing plugin, run this command

composer global update fxp/composer-asset-plugin --no-plugins

Body:
I updated composer

composer self-update

I installed the newer version of the plugin

composer global require "fxp/composer-asset-plugin:*"

I try to install Laravel

composer global require "laravel/installer"

Changed current directory to C:/Users/Arthur/AppData/Roaming/Composer
Fatal error: Declaration of Fxp\Composer\AssetPlugin\Repository\AbstractAssetsRe
    pository::search() must be compatible with Composer\Repository\RepositoryInterfa
    ce::search($query, $mode = 0, $type = NULL) in C:\Users\Arthur\AppData\Roaming\C
    omposer\vendor\fxp\composer-asset-plugin\Repository\AbstractAssetsRepository.php
     on line 334

Now all commands in composer not working

composer <any command>

Please help me to resolve it


问:
Parsing input to get specific values
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

```<code>my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}
</code>```

Maybe I should be using a different approach.  Could someone help me, please?

答:
split() is the Right Tool when you know what you want to throw away. Capturing or m//g is the Right Tool when you know what you want to keep. (paraphrased from a Randal Schwartz quote).

You want to specify what to keep (between square brackets) rather than what to throw away (nothing!).

Luckily, your data is "hash shaped" (ie. alternating keys and values), so load it into a hash, sort the keys, and output the value for the highest key:

```<code>my %data = $data =~ /\[
                       (\d+)      # digits are the keys
                       ([^]]+)    # rest are the values
                     \]/gx;
my($highest) = sort {$b <=> $a} keys %data; # inefficent if $data is big
print $highest, $data{$highest}, "\n";
</code>```

Title: Parsing input to get specific values

Body:
I have input like this:

"[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=17}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,D=14}|phone";

It appears as a continuous line, there are no line breaks.  I need the
largest value out of the values between [ and the first occurrence of
|.  In this case, for example, the largest value is 204.  Once
that is obtained, I want to print the contents of that element
between [].  In this case, it would be "204|0|{A=9,B=201,C=61,D=11}|Calculator".

I've tried something like this, but it is not going anywhere:

my @array1;

my $data =  "[0|0|{A=145,B=2,C=12,D=18}|!][0|0|{A=167,B=2,C=67,D=1
+7}|.1iit][196|0|{A=244,B=6,C=67,D=12}|10:48AM][204|0|{A=9,B=201,C=61,
+D=11}|Calculator][66|0|{A=145,B=450,C=49,D=14}|phone]0|0|{A=145,B=2,C
+=12,D=18}|!0|0|{A=167,B=2,C=67,D=17}|.1iit196|0|{A=244,B=6,C=67,D=12}
+|10:48AM204|0|{A=9,B=201,C=61,D=11}|Calculator66|0|{A=145,B=450,C=49,
+D=14}|phone";

my $high = 0;
my @values = split(/\[([^\]]+)\]/,$data) ;
print "Values is @values \n";

foreach (@values) {
    # I want the value that preceeds the first occurence of | in each array
    # element, i.e. 0,0,196,204, etc.
    my ($conf,$rest)= split(/\|/,$_);
    print "Conf is $conf \n";
    print "Rest is $rest \n";
    push(@array1, $conf);
    push (@array2, $rest);
    print "Array 1 is @array1 \n";
    print "Array 2 is @array2 \n";
}

$conf = highest(@array1);
my $i=0;

# I want the index value of the element that contains the highest conf value,
# in this case 204.

for (@myarray1) { last if $conf eq $_; $i++; };
print "$conf=$i\n";

# I want to print the rest of the string that was split in  the same index
# position.

$rest = @array2[$i];
print "Rest is $rest \n";

# To get the highest conf value

sub highest {
    my  @data = @_;
    my $high = 0;
    for(@data) {
        $high = $_ if $_ > $high;
    }
    $high;
}

Maybe I should be using a different approach.  Could someone help me, please?

Body:
split() is the Right Tool when you know what you want to throw away. Capturing or m//g is the Right Tool when you know what you want to keep. (paraphrased from a Randal Schwartz quote).

You want to specify what to keep (between square brackets) rather than what to throw away (nothing!).

Luckily, your data is "hash shaped" (ie. alternating keys and values), so load it into a hash, sort the keys, and output the value for the highest key:

my %data = $data =~ /\[
                       (\d+)      # digits are the keys
                       ([^]]+)    # rest are the values
                     \]/gx;
my($highest) = sort {$b <=> $a} keys %data; # inefficent if $data is big
print $highest, $data{$highest}, "\n";


问:
GTM fires tags perfectly but Google Analytics does not reflect any Real Time/ regular click events
I am trying to track click events in my website using GTM and Google Analytics. GTM fires tags fine but GA does not show any events in real time or after 24 hours in Behavior -> Events.

I have installed Google Tag Manager as mentioned in several websites and created variable, triggers, tags as needed.

On my website, I can see that GTM fires the tags to send the information to GA but GA doesn't show any real time click events or events for that matter. Even after 24 hours, I don't see any events being tracked under Behaviour -> Events.

Note: My website is being tracked by both Google Analytics and GTM. I have not created pageviews tracking through GTM to avoid data being sent to GA twice.

I have done everything as mentioned, Created Trigger which triggers only when a click URL has certain text buttonNext. Created a Tag by providing Category, Action, Label, value and Google tracking id (tried both ways by using a GA tracking constant and direct value). In the website, when a the button with Click URL contains buttonNext is clicked, I can see the tag being fired in the GTM preview/debugger. Also, Google Tag assistant confirms that event is being sent to the provided GA Tracking id. I have made sure the tracking id provided is mapped to my website. After all this, Google Analytics is not tracking the click events. I waited for 24 hours still no data logged in the events and I modified the non interaction hit to true and false to see if that matters. Nothing did the trick.

I expect GA to track events as GTM fires tags in preview mode and GA Tag Assistant confirms the event is triggerred but GA does not track any events.

答:
First of all, I would recommend you to decide on either implementing all Google Analytics tracking through GTM OR implementing all tracking natively. This will lead to a cleaner "tracking environment". There are different pros and cons that you should take into considerations when deciding on which way you want to go.

If it's a "minor website" where you have access to the source code, page speed is important and you will not do a lot of updates on the tracking I would recommend you to implement the tracking natively. Otherwise, implement all Google Analytics tracking using GTM.

However, regarding your issue, it's hard to say what is causing the issue since you didn't attach any code, screenshots, etc. My recommendation is that you open dev tools in your browser -> go to the network tab -> the filter on "collect". There you will be able to see all HTTP request that is sent to Google Analytics. If you don't see any network call being sent once triggering your event = something is wrong. You can also inspect the network call by clicking on it and under "Headers" see what values that are sent to Google Analytics.


答:
I think, you should do it just more clearly :).

Maybe try this way, using OOP:

```<code>import itertools.combinations

class Student:
    def __init__(self, name, subjects):
        self.name = name
        self.subjects = subjects

    def compare_to(self, another_student):
        result = 0
        for subject_my in self.subjects:
            for subject_he in another_student.subjects:
                if self.subjects.index(subject_my) >= \
                        another_student.subjects.index(subject_he):
                    result+=1
                else:
                    result+=2
       return result

resultList = [
    Student('Student1', ['Sport', 'History']),
    Student('Student2', ['Math', 'Spanish']),
    Student('Student3', ['French', 'History']),
    Student('Student4', ['English', 'Sport'])
    ]

for first, secound in itertools.combinations(resultList):
    print("{} - {} : {}".format(first.name, secound.name, first.compare_to(secound)))
</code>```

I think, it should look cleaner and more readable :). Choice is yours of course.
Clear code, will simplify your chance to catch whats going wrong.

Body:
I think, you should do it just more clearly :).

Maybe try this way, using OOP:

import itertools.combinations

class Student:
    def __init__(self, name, subjects):
        self.name = name
        self.subjects = subjects

    def compare_to(self, another_student):
        result = 0
        for subject_my in self.subjects:
            for subject_he in another_student.subjects:
                if self.subjects.index(subject_my) >= \
                        another_student.subjects.index(subject_he):
                    result+=1
                else:
                    result+=2
       return result

resultList = [
    Student('Student1', ['Sport', 'History']),
    Student('Student2', ['Math', 'Spanish']),
    Student('Student3', ['French', 'History']),
    Student('Student4', ['English', 'Sport'])
    ]

for first, secound in itertools.combinations(resultList):
    print("{} - {} : {}".format(first.name, secound.name, first.compare_to(secound)))

I think, it should look cleaner and more readable :). Choice is yours of course.
Clear code, will simplify your chance to catch whats going wrong.


问:
Copying excel worksheet to a different workbook
I'm trying to copy a worksheet to a different workbook into the last worksheet of the target workbook.

My workbooks and worksheets are created like this:

```<code>public Microsoft.Office.Interop.Excel.Workbook xlWorkbookMatrix;
public Microsoft.Office.Interop.Excel._Worksheet xlWorksheetMatrix;
</code>```

I tried using worksheet.copy:

xlWorksheetMatrix.Copy(Type.Missing, xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);

and worksheet.UsedRange.Copy:

xlWorksheetMatrix.UsedRange.Copy(xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);

With both different methods I always get an error.

For worksheet.Copy:

System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the worksheet object can't be assigned

For worksheet.UsedRange.Copy:

System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the Range object can't be assigned

答:
Having a template sheet you want to fill many times, Hope this helps :</p>

```<code>public void test()
{

    Excel.Application excelApp;

    string fileTarget = "C:\target.xlsx";
    string fileTemplate = "C:\template.xlsx";
    excelApp = new Excel.Application();
    Excel.Workbook wbTemp, wbTarget;
    Excel.Worksheet sh;

    //Create target workbook
    wbTarget = excelApp.Workbooks.Open(fileTemplate);

    //Fill target workbook
    //Open the template sheet
    sh = wbTarget.Worksheets["TEMPLATE"];
    //Fill in some data
    sh.Cells[1, 1] = "HELLO WORLD!";
    //Rename sheet
    sh.Name = "1. SHEET";

    //Save file
    wbTarget.SaveAs(fileTarget);

    //Iterate through the rest of the files
    for (int i = 1; i < 3; i++)
    {
        //Open template file in temporary workbook
        wbTemp = excelApp.Workbooks.Open(fileTemplate);

        //Fill temporary workbook
        //Open the template sheet
        sh = wbTemp.Worksheets["TEMPLATE"];
        //Fill in some data
        sh.Cells[1, 1] = "HELLO WORLD! FOR THE " + i + ".TH TIME";
        //Rename sheet
        sh.Name = i + ". SHEET";

        //Copy sheet to target workbook
        sh.Copy(wbTarget.Worksheets[1]);
        //Close temporary workbook without saving
        wbTemp.Close(false);
    }

    //Close and save target workbook
    wbTarget.Close(true);
    //Kill excelapp
    excelApp.Quit();
}
</code>```

Body:
I'm trying to copy a worksheet to a different workbook into the last worksheet of the target workbook.

My workbooks and worksheets are created like this:

public Microsoft.Office.Interop.Excel.Workbook xlWorkbookMatrix;
public Microsoft.Office.Interop.Excel._Worksheet xlWorksheetMatrix;

I tried using worksheet.copy:

xlWorksheetMatrix.Copy(Type.Missing, xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);

and worksheet.UsedRange.Copy:

xlWorksheetMatrix.UsedRange.Copy(xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);

With both different methods I always get an error.

For worksheet.Copy:

System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the worksheet object can't be assigned

For worksheet.UsedRange.Copy:

System.Runtime.InteropServices.COMException occured in System.Dynamic.dll
The Copy-property of the Range object can't be assigned

Body:
Having a template sheet you want to fill many times, Hope this helps :

public void test()
{

    Excel.Application excelApp;

    string fileTarget = "C:\target.xlsx";
    string fileTemplate = "C:\template.xlsx";
    excelApp = new Excel.Application();
    Excel.Workbook wbTemp, wbTarget;
    Excel.Worksheet sh;

    //Create target workbook
    wbTarget = excelApp.Workbooks.Open(fileTemplate);

    //Fill target workbook
    //Open the template sheet
    sh = wbTarget.Worksheets["TEMPLATE"];
    //Fill in some data
    sh.Cells[1, 1] = "HELLO WORLD!";
    //Rename sheet
    sh.Name = "1. SHEET";

    //Save file
    wbTarget.SaveAs(fileTarget);

    //Iterate through the rest of the files
    for (int i = 1; i < 3; i++)
    {
        //Open template file in temporary workbook
        wbTemp = excelApp.Workbooks.Open(fileTemplate);

        //Fill temporary workbook
        //Open the template sheet
        sh = wbTemp.Worksheets["TEMPLATE"];
        //Fill in some data
        sh.Cells[1, 1] = "HELLO WORLD! FOR THE " + i + ".TH TIME";
        //Rename sheet
        sh.Name = i + ". SHEET";

        //Copy sheet to target workbook
        sh.Copy(wbTarget.Worksheets[1]);
        //Close temporary workbook without saving
        wbTemp.Close(false);
    }

    //Close and save target workbook
    wbTarget.Close(true);
    //Kill excelapp
    excelApp.Quit();
}


问:
How to send email from shared serve in laravel 5.7
When my project is run on localhost mail was perfectly send but when I move my project to shared server mail not send i do change in env file but still not working.

My env file:

```<code>MAIL_DRIVER=sendmail
MAIL_HOST=mail.XXXX.com
MAIL_PORT=465
MAIL_USERNAME=areeba.XXXX@gmail.com
MAIL_PASSWORD=XXXX
MAIL_ENCRYPTION=ssl
</code>```

Controller file save data in database and also send mail:

```<code>public function store(Request $request)
{
    $this->validate($request,[
        'name' => 'required',
        'email' => 'required|email',
        'subject' => 'required',
        'phone_number' => 'string',
        'message' =>    'required',
    ]);

    Mail::send('emails.contact-message',[
        'name' => $request->name,
        'email' => $request->email,
        'subject' => $request->subject,
        'phone_number' => $request->phone_number,
        'msg' => $request->message
     ], function($mail) use($request){
         $mail->from($request->email, $request->name);

        $mail->to('areeba.premiotravels@gmail.com')->subject($request-
     >subject);

    });

    ContactUs ::create($request->all());
    return redirect()->back()->with('flash_message', 'Thank you for your
   message.');
 }
</code>```

and my form is

```<code> <form class="ui form" method="post" action="{{ url('contactsubmit') }}">
                {{ csrf_field() }}
                <div class="field">
                    <input type="text" name="name" placeholder="Name">
                </div>
                <div class="field">
                    <input type="text" name="email" placeholder="Email">
                </div>
                <div class="field">
                    <input type="text" name="subject" placeholder="Subject">
                </div>
                <div class="field">
                    <input type="text" name="phone_number" placeholder="Phone Number">
                </div>
                <div class="field">
                    <textarea name="message" cols="40" rows="10">Any Comment (Optional)</textarea>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <button class="ui button" type="submit">Send</button>
                    </div>
                </div>

            </form>
</code>```

My Route is:

```<code>     Route::post('/contactsubmit',[
     'uses' => 'ContactUsController@store',
     'as' => 'contact.store'
     ]);
</code>```

答:
After moved on shared server you neeed clear cache:

```<code>php artisan config:cache
</code>```

then you need start queue if you use it

Body:
When my project is run on localhost mail was perfectly send but when I move my project to shared server mail not send i do change in env file but still not working.

My env file:

MAIL_DRIVER=sendmail
MAIL_HOST=mail.XXXX.com
MAIL_PORT=465
MAIL_USERNAME=areeba.XXXX@gmail.com
MAIL_PASSWORD=XXXX
MAIL_ENCRYPTION=ssl

Controller file save data in database and also send mail:

public function store(Request $request)
{
    $this->validate($request,[
        'name' => 'required',
        'email' => 'required|email',
        'subject' => 'required',
        'phone_number' => 'string',
        'message' =>    'required',
    ]);

    Mail::send('emails.contact-message',[
        'name' => $request->name,
        'email' => $request->email,
        'subject' => $request->subject,
        'phone_number' => $request->phone_number,
        'msg' => $request->message
     ], function($mail) use($request){
         $mail->from($request->email, $request->name);

        $mail->to('areeba.premiotravels@gmail.com')->subject($request-
     >subject);

    });

    ContactUs ::create($request->all());
    return redirect()->back()->with('flash_message', 'Thank you for your
   message.');
 }

and my form is

 <form class="ui form" method="post" action="{{ url('contactsubmit') }}">
                {{ csrf_field() }}

                    <input type="text" name="name" placeholder="Name">

                    <input type="text" name="email" placeholder="Email">

                    <input type="text" name="subject" placeholder="Subject">

                    <input type="text" name="phone_number" placeholder="Phone Number">

                    <textarea name="message" cols="40" rows="10">Any Comment (Optional)</textarea>

                        <button class="ui button" type="submit">Send</button>

            </form>

My Route is:

     Route::post('/contactsubmit',[
     'uses' => 'ContactUsController@store',
     'as' => 'contact.store'
     ]);

Body:
After moved on shared server you neeed clear cache:

php artisan config:cache

then you need start queue if you use it


问:
set value to
 tag and update the prop on:click $event vue.js
I am trying to update props child to parent with on:click $event.

I passed the data and $event to parent to child, like below.
in parent;

```<code><v-filter
    :sortTypePrice="sortTypePrice"
    :sortTypeNewest="sortTypeNewest"
    v-on:updatePrice="sortTypePrice = $event"
    v-on:updateDate="sortTypeNewest = $event"
/>

data(){
    return {
        sortTypePrice: "",
        sortTypeNewest: "",
    }
 }

computed: {
  filterArticles(){

      let filteredStates = this.api.filter((article) => {
          return (this.keyword.length === 0 || article.address.includes(this.keyword))
      });

      if(this.sortTypePrice == "price") {
          filteredStates = filteredStates.sort((prev, curr) => prev.price1 - curr.price1);
      }
      if(this.sortTypeNewest == 'created_at') {
          filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
      }

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

I got the props and set the $event update. But my @click is not working.

in child

```<code><ul>
  <li v-model="sortPrice" @click="updatePrice" :value="price">lowest</li>
  <li v-model="sortDate" @click="updateDate" :value="created_at">newest</li>
</ul>

props:["sortTypePrice", "sortTypeNewest"],
name: "controller",
data(){
    return {
        price: "price",
        created_at: "created_at",
        sortPrice:this.sortTypePrice,
        sortDate:this.sortTypeNewest,
    };
},
methods: {
    updatePrice(e){
        this.$emit("updatePrice", e.target.value)
    },
    updateDate(e){
        this.$emit("updateDate", e.target.value)
    }
}
</code>```

I think, I am using very wrong way to do this. if it so, what is the right way to achieve this?

答:
I find the following the best way to sync a prop between parent and child component:

in parent:

```<code><!-- notice `sync` modifier -->
<child :foo.sync="val" />
</code>```

in child:

```<code><input v-model="foo_" />

props: ['foo'],
computed: {

    // create a local proxy for the `foo` prop
    foo_{
        // its value should be the value of the prop
        get(){
            return this.foo
        },

        // when we try to change it we should update the prop instead
        set(val){
            this.$emit('update:foo', val)
        }
    }
}
</code>```

Now in the child component you can work with the foo_ prop the same way as you would with the foo prop. Whenever you try to change it, it will update the foo prop in the parent and then sync down so that foo_ remains equal to foo. For example this.foo_ = 1 would make foo == 1.

This is the same pattern that is applied with the v-model directive. Check .sync Modifier for better understanding.

Title: set value to <li> tag and update the prop on:click $event vue.js

Body:
I am trying to update props child to parent with on:click $event.

I passed the data and $event to parent to child, like below.
in parent;

<v-filter
    :sortTypePrice="sortTypePrice"
    :sortTypeNewest="sortTypeNewest"
    v-on:updatePrice="sortTypePrice = $event"
    v-on:updateDate="sortTypeNewest = $event"
/>

data(){
    return {
        sortTypePrice: "",
        sortTypeNewest: "",
    }
 }

computed: {
  filterArticles(){

      let filteredStates = this.api.filter((article) => {
          return (this.keyword.length === 0 || article.address.includes(this.keyword))
      });

      if(this.sortTypePrice == "price") {
          filteredStates = filteredStates.sort((prev, curr) => prev.price1 - curr.price1);
      }
      if(this.sortTypeNewest == 'created_at') {
          filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
      }

      return filteredStates;
  },
}

I got the props and set the $event update. But my @click is not working.

in child

lowest

newest

props:["sortTypePrice", "sortTypeNewest"],
name: "controller",
data(){
    return {
        price: "price",
        created_at: "created_at",
        sortPrice:this.sortTypePrice,
        sortDate:this.sortTypeNewest,
    };
},
methods: {
    updatePrice(e){
        this.$emit("updatePrice", e.target.value)
    },
    updateDate(e){
        this.$emit("updateDate", e.target.value)
    }
}

I think, I am using very wrong way to do this. if it so, what is the right way to achieve this?

Body:
I find the following the best way to sync a prop between parent and child component:

in parent:

<!-- notice `sync` modifier -->
<child :foo.sync="val" />

in child:

<input v-model="foo_" />

props: ['foo'],
computed: {

    // create a local proxy for the `foo` prop
    foo_{
        // its value should be the value of the prop
        get(){
            return this.foo
        },

        // when we try to change it we should update the prop instead
        set(val){
            this.$emit('update:foo', val)
        }
    }
}

Now in the child component you can work with the foo_ prop the same way as you would with the foo prop. Whenever you try to change it, it will update the foo prop in the parent and then sync down so that foo_ remains equal to foo. For example this.foo_ = 1 would make foo == 1.

This is the same pattern that is applied with the v-model directive. Check .sync Modifier for better understanding.


问:
Turn OFF self-closing tags in SimpleXML for PHP?
I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:

```<code>$doc->addChild('myToken');
</code>```

This generates (what I know as) a self-closing or single tag:

```<code><myToken/>
</code>```

However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:

```<code><myToken></myToken>
</code>```

The question is, how do I do this, outside of running the generated XML through a preg_replace?

答:
LIBXML_NOEMPTYTAG works but only if you use DOMDocument::save or DOMDocument::saveXML

```<code>$dom = dom_import_simplexml(SimpleXMLElement)->ownerDocument;
$dom->formatOutput = true;
$dom->save($save_path, LIBXML_NOEMPTYTAG);
</code>```

OwnerDisplayName: TimTowdi

ContentLicense: CC BY-SA 2.5

Body:
I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:

$doc->addChild('myToken');

This generates (what I know as) a self-closing or single tag:

<myToken/>

However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:

<myToken></myToken>

The question is, how do I do this, outside of running the generated XML through a preg_replace?

Body:
LIBXML_NOEMPTYTAG works but only if you use DOMDocument::save or DOMDocument::saveXML

$dom = dom_import_simplexml(SimpleXMLElement)->ownerDocument;
$dom->formatOutput = true;
$dom->save($save_path, LIBXML_NOEMPTYTAG);


问:
Why is fprintf causing memory leak and behaving unpredictably when width argument is missing
The following simple program is behaving unpredictably. Sometimes it prints "0.00000", sometimes it prints more "0" than I can count. Some times it uses up all memory on the system, before the system either kills some process, or it fails with bad_alloc.

```<code>#include "stdio.h"

int main() {
  fprintf(stdout, "%.*f", 0.0);
}
</code>```

I'm aware that this is incorrect usage of fprintf. There should be another argument specifying the width of the formatting. It's just surprising that the behavior is so unpredictable. Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

I came over similar usage in some code at work, and spent a lot of time figuring out what was happening. It only seemed to happen with debug builds, but would not happen while debugging with gdb. Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.

I am running Red Hat Enterprise Linux 7, and compiled with gcc 4.8.5.

答:
The format string does not match the parameters, therefore the bahaviour of fprintf is undefined. Google "undefined behaviour C" for more information about "undefined bahaviour".

This would be correct:

```<code>// printf 0.0 with 7 decimals
fprintf(stdout, "%.*f", 7, 0.0);
</code>```

Or maybe you just want this:

```<code>// printf 0.0 with de default format
fprintf(stdout, "%f", 0.0);
</code>```

About this part of your question: Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

There cannot be any default behaviour, fprintf is reading the arguments according to the format string. If the arguments don't match, fprintf ends up with seamingly random values.

About this part of your question: Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.:

This is just another manifestation of undefined behaviour, with valgrind the conditions are quite different and therefore the actual undefined bahaviour can be different.

Body:
The following simple program is behaving unpredictably. Sometimes it prints "0.00000", sometimes it prints more "0" than I can count. Some times it uses up all memory on the system, before the system either kills some process, or it fails with bad_alloc.

#include "stdio.h"

int main() {
  fprintf(stdout, "%.*f", 0.0);
}

I'm aware that this is incorrect usage of fprintf. There should be another argument specifying the width of the formatting. It's just surprising that the behavior is so unpredictable. Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

I came over similar usage in some code at work, and spent a lot of time figuring out what was happening. It only seemed to happen with debug builds, but would not happen while debugging with gdb. Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.

I am running Red Hat Enterprise Linux 7, and compiled with gcc 4.8.5.

Body:
The format string does not match the parameters, therefore the bahaviour of fprintf is undefined. Google "undefined behaviour C" for more information about "undefined bahaviour".

This would be correct:

// printf 0.0 with 7 decimals
fprintf(stdout, "%.*f", 7, 0.0);

Or maybe you just want this:

// printf 0.0 with de default format
fprintf(stdout, "%f", 0.0);

About this part of your question: Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

There cannot be any default behaviour, fprintf is reading the arguments according to the format string. If the arguments don't match, fprintf ends up with seamingly random values.

About this part of your question: Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.:

This is just another manifestation of undefined behaviour, with valgrind the conditions are quite different and therefore the actual undefined bahaviour can be different.


问:
How to analyze only a part of an image?
I want to analyse a specific part of an image, as an example I'd like to focus on the bottom right 200x200 section and count all the black pixels, so far I have:</p>

```<code>im1 = Image.open(path)
rgb_im1 = im1.convert('RGB')
for pixel in rgb_im1.getdata():
</code>```

答:
Whilst you could do this with cropping and a pair of for loops, that is really slow and not ideal.

I would suggest you use Numpy as it is very commonly available, very powerful and very fast.

Here's a 400x300 black rectangle with a 1-pixel red border:

```<code>#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Open the image and make into Numpy array
im = Image.open('image.png')
ni = np.array(im)

# Declare an ROI - Region of Interest as the bottom-right 200x200 pixels
# This is called "Numpy slicing" and is near-instantaneous https://www.tutorialspoint.com/numpy/numpy_indexing_and_slicing.htm
ROI = ni[-200:,-200:]

# Calculate total area of ROI and subtract non-zero pixels to get number of zero pixels
# Numpy.count_nonzero() is highly optimised and extremely fast
black = 200*200 - np.count_nonzero(ROI)
print(f'Black pixel total: {black}')
</code>```

Sample Output

```<code>Black pixel total: 39601
</code>```

Yes, you can make it shorter, for example:

```<code>h, w = 200,200
im = np.array(Image.open('image.png'))
black = h*w - np.count_nonzero(ni[-h:,-w:])
</code>```

If you want to debug it, you can take the ROI and make it into a PIL Image which you can then display. So just use this line anywhere after you make the ROI:

```<code># Display image to check
Image.fromarray(ROI).show()
</code>```

Title: How to analyze only a part of an image?

Body:
I want to analyse a specific part of an image, as an example I'd like to focus on the bottom right 200x200 section and count all the black pixels, so far I have:

im1 = Image.open(path)
rgb_im1 = im1.convert('RGB')
for pixel in rgb_im1.getdata():

Body:
Whilst you could do this with cropping and a pair of for loops, that is really slow and not ideal.

I would suggest you use Numpy as it is very commonly available, very powerful and very fast.

Here's a 400x300 black rectangle with a 1-pixel red border:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Open the image and make into Numpy array
im = Image.open('image.png')
ni = np.array(im)

# Declare an ROI - Region of Interest as the bottom-right 200x200 pixels
# This is called "Numpy slicing" and is near-instantaneous https://www.tutorialspoint.com/numpy/numpy_indexing_and_slicing.htm
ROI = ni[-200:,-200:]

# Calculate total area of ROI and subtract non-zero pixels to get number of zero pixels
# Numpy.count_nonzero() is highly optimised and extremely fast
black = 200*200 - np.count_nonzero(ROI)
print(f'Black pixel total: {black}')

Sample Output

Black pixel total: 39601

Yes, you can make it shorter, for example:

h, w = 200,200
im = np.array(Image.open('image.png'))
black = h*w - np.count_nonzero(ni[-h:,-w:])

If you want to debug it, you can take the ROI and make it into a PIL Image which you can then display. So just use this line anywhere after you make the ROI:

# Display image to check
Image.fromarray(ROI).show()


问:
How to show grecaptcha in a popup on clicking CF7 Submit button?
I'm making a new form in Contact Form 7. I need to display grecaptcha in a popup on submit button click. After the captcha success need to submit Contact Form 7.</p>

答:
As an option you can create your own functionality with JavaScript.
skip_mail -> take CF7 data by DOM Event using wpcf7beforesubmit(added in cf7 4.9) -> then create pop-up with your captcha -> then check it. If captha ok -> sending email by yourself with taken data.</p>


问:
How to split a line to a new line when specific condition meets in a csv file?
I have the below data in my csv file, I want to split each line to a new line when "05/16/2019" text is identified using c#.

Currently in my csv file data format is like below:

05/16/2019,PAPER,190516-TRE-5419,GbK,R0000001,1,05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1,05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

I want to change like below:

05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

I am new to c# programming, Can anyone please help me with the Code?

1st Step:  I am Uploading my csv file

2nd Step: I am trying to change my csv as above requirement

3rd Step: Exporting the modified csv to a new location

```<code>List<string> csvfiles = new List<string>();
private void btnimport_Click(object sender, EventArgs e)
{
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.CheckFileExists = true;
        openFileDialog.AddExtension = true;
        openFileDialog.Multiselect = true;
        openFileDialog.Filter = "CSV files (*.csv)|*.csv";
        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            foreach (string fileName in openFileDialog.FileNames)
            {
                csvfiles.Add(fileName);
            }
        }
    }
public void csvedit()
    {
        String path = @"C:\Users\Sunil\Videos\original\GSK.csv";
        Regex r = new Regex(@",(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4})");   // looks for the comma just before the date
        var newStr = r.Replace(path, "\r\n");
    }
 private void btnexport_Click(object sender, EventArgs e)
    {
        csvedit();
        string installedPath = "C:\\Users\\Sunil\\Videos\\changed";

        //Check whether folder path is exist
        if (!System.IO.Directory.Exists(installedPath))
        {
            // If not create new folder
            System.IO.Directory.CreateDirectory(installedPath);
        }
        //Save pdf files in installedPath ??
        foreach (string sourceFileName in csvfiles)
        {
            string destinationFileName = System.IO.Path.Combine(installedPath, System.IO.Path.GetFileName(sourceFileName));
            System.IO.File.Copy(sourceFileName, destinationFileName);
            MessageBox.Show("File Exported Successfully");
        }
    }
</code>```

答:
Assuming that the current CSV format is available as string in your code, you can use the regular expressions for formatting the way you want. Try with this:

```<code>Regex r = new Regex(@",(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4})");   // looks for the comma just before the date
var newStr = r.Replace(str, "\r\n");         // here 'str' is the input string which contains unformatted csv file content.
</code>```

For your requirement, you need to modify the csvedit() as follows:

```<code>public void csvedit()
{
    string path = @"C:\Users\Sunil\Videos\original\GSK.csv";
    string csvContent = System.IO.File.ReadAllText(path);
    Regex r = new Regex(@"("",""(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4}))");  // looks for the 'double quotes - comma - double quotes' pattern just before the date
    var newStr = r.Replace(csvContent, "\n").Trim("\"".ToArray());
    System.IO.File.WriteAllText(path, newStr);    //this will overwrite the text present in existing file.
}
</code>```

Body:
I have the below data in my csv file, I want to split each line to a new line when "05/16/2019" text is identified using c#.

Currently in my csv file data format is like below:

05/16/2019,PAPER,190516-TRE-5419,GbK,R0000001,1,05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1,05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

I want to change like below:

05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

05/16/2019,PAPER,190516-TRE-5419,GSK,R0000001,1

I am new to c# programming, Can anyone please help me with the Code?

1st Step:  I am Uploading my csv file

2nd Step: I am trying to change my csv as above requirement

3rd Step: Exporting the modified csv to a new location

List<string> csvfiles = new List<string>();
private void btnimport_Click(object sender, EventArgs e)
{
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.CheckFileExists = true;
        openFileDialog.AddExtension = true;
        openFileDialog.Multiselect = true;
        openFileDialog.Filter = "CSV files (*.csv)|*.csv";
        if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            foreach (string fileName in openFileDialog.FileNames)
            {
                csvfiles.Add(fileName);
            }
        }
    }
public void csvedit()
    {
        String path = @"C:\Users\Sunil\Videos\original\GSK.csv";
        Regex r = new Regex(@",(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4})");   // looks for the comma just before the date
        var newStr = r.Replace(path, "\r\n");
    }
 private void btnexport_Click(object sender, EventArgs e)
    {
        csvedit();
        string installedPath = "C:\\Users\\Sunil\\Videos\\changed";

        //Check whether folder path is exist
        if (!System.IO.Directory.Exists(installedPath))
        {
            // If not create new folder
            System.IO.Directory.CreateDirectory(installedPath);
        }
        //Save pdf files in installedPath ??
        foreach (string sourceFileName in csvfiles)
        {
            string destinationFileName = System.IO.Path.Combine(installedPath, System.IO.Path.GetFileName(sourceFileName));
            System.IO.File.Copy(sourceFileName, destinationFileName);
            MessageBox.Show("File Exported Successfully");
        }
    }

Body:
Assuming that the current CSV format is available as string in your code, you can use the regular expressions for formatting the way you want. Try with this:

Regex r = new Regex(@",(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4})");   // looks for the comma just before the date
var newStr = r.Replace(str, "\r\n");         // here 'str' is the input string which contains unformatted csv file content.

For your requirement, you need to modify the csvedit() as follows:

public void csvedit()
{
    string path = @"C:\Users\Sunil\Videos\original\GSK.csv";
    string csvContent = System.IO.File.ReadAllText(path);
    Regex r = new Regex(@"("",""(?=[0-9]{2}\/[0-9]{2}\/[0-9]{4}))");  // looks for the 'double quotes - comma - double quotes' pattern just before the date
    var newStr = r.Replace(csvContent, "\n").Trim("\"".ToArray());
    System.IO.File.WriteAllText(path, newStr);    //this will overwrite the text present in existing file.
}


问:
Char.IsControl method does not recognize some characters as control
I noticed that C# 'Char.IsControl' method doesn't recognize some characters as control. For example, the following code outputs false for both values:

```<code>char pilcrow = '\u00B6';
char softHyphen = '\u00AD';
Console.Write("{0},{1}",char.IsControl(pilcrow), char.IsControl(softHyphen)); // -> 'false,false'
</code>```

Is this an expected behavior? I need to escape such characters in my code.

答:
Those aren't control characters. One is the pilcrow sign ¶ which belongs to the Punctuation, Other [Po] category , the other is the soft hyphen, a non-visible formatting character that affects how texts gets hyphenated.

There's nothing special about them, in fact you probably use the soft hyphen when writing a paragraph in Word and want to control hyphenation of some words. Word uses ¶ as the paragraph mark - a visualization of a paragraph's end. It doesn't affect formatting, it's just the common way to denote the end of paragraph. In that respect it's no different than ², ³, §, ¶, ¤, ¦, °, ±, ½, ¬ (just holding Right Alt and hitting keys)

.NET strings use Unicode so there's no need to escape these characters. You can just type them directly.

There's no problem with printing either - those characters are used in document processing after all. The soft hyphen controls how the UI or the print engine lays out text during rendering to the screen or paper.

If someone doesn't want those characters to be printed, a simple string.Remove will do the job. Removing the hyphen can affect how text is printed though, with long words moving to the next line. I added that hyphen to Removing in the previous sentence to force hyphenation. Without it, Removing would have moved to the next line

Body:
I noticed that C# 'Char.IsControl' method doesn't recognize some characters as control. For example, the following code outputs false for both values:

char pilcrow = '\u00B6';
char softHyphen = '\u00AD';
Console.Write("{0},{1}",char.IsControl(pilcrow), char.IsControl(softHyphen)); // -> 'false,false'

Is this an expected behavior? I need to escape such characters in my code.


问:
How exactly does inspect.signature work with classes?
The inspect.signature doc states that it supports classes as input, but it doesn't go into any sort of detail:

Accepts a wide range of Python callables, from plain functions and classes to functools.partial() objects.

If I call inspect.signature(MyClass), what signature does it return? Does it return the signature of MyClass.__init__? Or MyClass.__new__? Or something else?

答:
It tries pretty much everything it reasonably could. I think the details are probably deliberately undocumented, because they're complicated and likely to get more so as new Python versions add more stuff to try.

For example, as of CPython 3.7.3, the code path tries the following things in order:

If the metaclass has a custom __call__ defined in Python, it uses the signature of the metaclass __call__ with the first argument removed.

Otherwise, if the class has a __new__ method defined in Python, it uses the __new__ signature with the first argument removed.

Otherwise, if the class has an __init__ method defined in Python, it uses the __init__ signature with the first argument removed.

Otherwise, it traverses the MRO looking for a __text_signature__. If it finds one, it parses __text_signature__ to get the signature information.

If it still hasn't found anything, if the type's __init__ is object.__init__ and the type's __new__ is object.__new__, it returns the signature of the object class. (There's a misleading comment and a possible bug involving metaclasses around this point - the comment says it's going to check for type.__init__, but it doesn't do that. I think this commit may have made a mistake here.)

If it still hasn't found anything, it gives up and raises a ValueError saying it couldn't find anything.


问:
CADisplayLink because of remove(from:forMode:) not deallocating view controller
I am facing one strange issue.

So I have created instance and allocated like below

```<code>var displayLink:CADisplayLink?

private func setupDisplayLink () {

    self.displayLink = CADisplayLink(target: self, selector: #selector(displayLinkDidFire(link:)))
    self.displayLink?.preferredFramesPerSecond = 30
    self.displayLink?.add(to: .main, forMode: .common)
}
</code>```

Now to remove display link I have from this Answer

```<code>self.displayLink?.remove(from: .main, forMode: .common) // comment this line and view controller correctly deallocated
self.displayLink?.invalidate()
</code>```

because of line  self.displayLink?.remove(from: .main, forMode: .common) my deinit method not called of view controller

In memory graph I am not able to identify the real problem. I was lucky that I have  tried to comment that line and it works

Why that so ?

答:
Stop displayLink like this:</p>

```<code>displayLink?.invalidate()
displayLink = nil
</code>```

Body:
I am facing one strange issue.

So I have created instance and allocated like below

var displayLink:CADisplayLink?

private func setupDisplayLink () {

    self.displayLink = CADisplayLink(target: self, selector: #selector(displayLinkDidFire(link:)))
    self.displayLink?.preferredFramesPerSecond = 30
    self.displayLink?.add(to: .main, forMode: .common)
}

Now to remove display link I have from this Answer

self.displayLink?.remove(from: .main, forMode: .common) // comment this line and view controller correctly deallocated
self.displayLink?.invalidate()

because of line  self.displayLink?.remove(from: .main, forMode: .common) my deinit method not called of view controller

In memory graph I am not able to identify the real problem. I was lucky that I have  tried to comment that line and it works

Why that so ?

Body:
Stop displayLink like this:

displayLink?.invalidate()
displayLink = nil


问:
Mastering CSS and XHTML with Vim
Please point me to some guides on how to master (X)HTML, CSS with Vim. I preffer to create web pages by hands and I decided to go with Vim.

Any useful plugins, tips & tricks, tutorials, how-tos, books, articles?

Thanks!

答:
I use a lot zencoding, so, if you're used with zen-coding try the zenCoding plugin for Vim find it here

If you want to learn more about zen-coding you could read: zen coding vim tutorial

Title: Mastering CSS and XHTML with Vim


问:
how to stream rtsp url using exoplayer?
I want to stream rtsp video using exoplayer. I am using ExoMedia library which is an An Android ExoPlayer wrapper. I have search on stackoverflow but I didn't find any good answer. After some google search I found that exoplayer does not support rtsp stream issue 55.
Is there any way to stream rtsp url using exoplayer?
  Here is my code.

```<code>public class MainActivity extends AppCompatActivity implements OnPreparedListener{
    EMVideoView emPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        playVideo();
    }

    private void playVideo() {
        emPlayer = (EMVideoView)findViewById(R.id.video_view);
        emPlayer.setOnPreparedListener(this);

        emPlayer.setVideoURI(Uri.parse("rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov"));
    }

    @Override
    public void onPrepared() {
        emPlayer.start();
        Log.v("TAG","video is playing");
    }
}
</code>```

Here is my log

```<code>com.google.android.exoplayer.ExoPlaybackException: com.google.android.exoplayer.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov
           at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:262)
           at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:148)
           at com.google.android.exoplayer.ExoPlayerImplInternal.incrementalPrepareInternal(ExoPlayerImplInternal.java:273)
           at com.google.android.exoplayer.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:203)
           at android.os.Handler.dispatchMessage(Handler.java:98)
           at android.os.Looper.loop(Looper.java:135)
           at android.os.HandlerThread.run(HandlerThread.java:61)
           at com.google.android.exoplayer.util.PriorityHandlerThread.run(PriorityHandlerThread.java:40)
        Caused by: com.google.android.exoplayer.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov
           at com.google.android.exoplayer.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:191)
           at com.google.android.exoplayer.upstream.DefaultUriDataSource.open(DefaultUriDataSource.java:133)
           at com.google.android.exoplayer.extractor.ExtractorSampleSource$ExtractingLoadable.load(ExtractorSampleSource.java:823)
           at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:222)
           at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
           at java.lang.Thread.run(Thread.java:818)
        Caused by: java.net.MalformedURLException: Unknown protocol: rtsp
           at java.net.URL.<init>(URL.java:182)
           at java.net.URL.<init>(URL.java:125)
           at com.google.android.exoplayer.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:330)
           at com.google.android.exoplayer.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:189)
           at com.google.android.exoplayer.upstream.DefaultUriDataSource.open(DefaultUriDataSource.java:133)
           at com.google.android.exoplayer.extractor.ExtractorSampleSource$ExtractingLoadable.load(ExtractorSampleSource.java:823)
           at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:222)
           at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
           at java.lang.Thread.run(Thread.java:818)
</code>```

答:
Actually current version of ExoPlayer doesn't support RTSP. But as indicated in the issue issue 55 there's an active pull request #3854 to add this support.

In the meantime, you can clone the original authors exoplayer fork which does support RTSP (branch dev-v2-rtsp):

```<code>git clone -b dev-v2-rtsp https://github.com/tresvecesseis/ExoPlayer.git
</code>```

I've tested it and it works perfectly. The authors are working actively to fix the issues reported by many users and I hope that RTSP support at some point becomes part of the official exoplayer.

Title: how to stream rtsp url using exoplayer?

Body:
I want to stream rtsp video using exoplayer. I am using ExoMedia library which is an An Android ExoPlayer wrapper. I have search on stackoverflow but I didn't find any good answer. After some google search I found that exoplayer does not support rtsp stream issue 55.
Is there any way to stream rtsp url using exoplayer?
  Here is my code.

public class MainActivity extends AppCompatActivity implements OnPreparedListener{
    EMVideoView emPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        playVideo();
    }

    private void playVideo() {
        emPlayer = (EMVideoView)findViewById(R.id.video_view);
        emPlayer.setOnPreparedListener(this);

        emPlayer.setVideoURI(Uri.parse("rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov"));
    }

    @Override
    public void onPrepared() {
        emPlayer.start();
        Log.v("TAG","video is playing");
    }
}

Here is my log

com.google.android.exoplayer.ExoPlaybackException: com.google.android.exoplayer.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov
           at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:262)
           at com.google.android.exoplayer.SampleSourceTrackRenderer.maybeThrowError(SampleSourceTrackRenderer.java:148)
           at com.google.android.exoplayer.ExoPlayerImplInternal.incrementalPrepareInternal(ExoPlayerImplInternal.java:273)
           at com.google.android.exoplayer.ExoPlayerImplInternal.handleMessage(ExoPlayerImplInternal.java:203)
           at android.os.Handler.dispatchMessage(Handler.java:98)
           at android.os.Looper.loop(Looper.java:135)
           at android.os.HandlerThread.run(HandlerThread.java:61)
           at com.google.android.exoplayer.util.PriorityHandlerThread.run(PriorityHandlerThread.java:40)
        Caused by: com.google.android.exoplayer.upstream.HttpDataSource$HttpDataSourceException: Unable to connect to rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov
           at com.google.android.exoplayer.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:191)
           at com.google.android.exoplayer.upstream.DefaultUriDataSource.open(DefaultUriDataSource.java:133)
           at com.google.android.exoplayer.extractor.ExtractorSampleSource$ExtractingLoadable.load(ExtractorSampleSource.java:823)
           at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:222)
           at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
           at java.lang.Thread.run(Thread.java:818)
        Caused by: java.net.MalformedURLException: Unknown protocol: rtsp
           at java.net.URL.<init>(URL.java:182)
           at java.net.URL.<init>(URL.java:125)
           at com.google.android.exoplayer.upstream.DefaultHttpDataSource.makeConnection(DefaultHttpDataSource.java:330)
           at com.google.android.exoplayer.upstream.DefaultHttpDataSource.open(DefaultHttpDataSource.java:189)
           at com.google.android.exoplayer.upstream.DefaultUriDataSource.open(DefaultUriDataSource.java:133)
           at com.google.android.exoplayer.extractor.ExtractorSampleSource$ExtractingLoadable.load(ExtractorSampleSource.java:823)
           at com.google.android.exoplayer.upstream.Loader$LoadTask.run(Loader.java:222)
           at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
           at java.lang.Thread.run(Thread.java:818)

Body:
Actually current version of ExoPlayer doesn't support RTSP. But as indicated in the issue issue 55 there's an active pull request #3854 to add this support.

In the meantime, you can clone the original authors exoplayer fork which does support RTSP (branch dev-v2-rtsp):

git clone -b dev-v2-rtsp https://github.com/tresvecesseis/ExoPlayer.git

I've tested it and it works perfectly. The authors are working actively to fix the issues reported by many users and I hope that RTSP support at some point becomes part of the official exoplayer.