text:
Q: RSExecRole missing I have multiple servers and 4 of them have reporting services installed with the ReportServer & ReportServerTempDB databases.
A few days ago I was setting up security for a new login and I found out that the RSExecRole role is missing in my dev server (in the reportserver database). It exists on the ReportServerTempDB, master & msdb databases.
I have found a way to create it on the master & msdb databases on msdn
but it didn't help me creating it on reportserver with all the securibles & properties similar to the other environents I run.
Has anyone encountered this problem before? Can anyone help me with a script and an explanation about this role?

A: Open "Reporting Services Configuration Manager" --> Database, verify the login under [Current Report Server Database Credential] is one of users in RSExecRole or not, if not, click "Change Credentials" button to change to an user in RSExecRole.
You can also use commnadline utility rsconfig as well http://technet.microsoft.com/en-us/library/ms162837.aspx
Since you wanted the code as well, I have scripted it out for you ....
Edit: I have edited, so that below becomes the full code.
    /****** Object: Schema [RSExecRole] ***/

CREATE SCHEMA [RSExecRole] AUTHORIZATION [RSExecRole]
GO
/*** Object: DatabaseRole [RSExecRole] ******

/ CREATE ROLE [RSExecRole] AUTHORIZATION [dbo]
 GO

--Security creation script for role RSExecRole

    --Add Role To Database

    EXEC sp_addrole
        @rolename 'RSExecRole'

    --Set Object Specific Permissions For Role
    GRANT
        EXECUTE
        ON [dbo].[FindItemsByDataSource]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[History]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FindItemsByDataSet]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FindItemsByDataSourceRecursive]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDBVersion]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateRole]
        TO RSExecRole
    GRANT
        SELECT,REFERENCES
        ON [dbo].[ExtendedCatalog]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetRoles]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ConfigurationInfo]
        TO RSExecRole
    GRANT
        SELECT,REFERENCES
        ON [dbo].[ExtendedDataSources]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteRole]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetKeysForInstallation]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ReadRoleProperties]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Catalog]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetAnnouncedKey]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetRoleProperties]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AnnounceOrGetKey]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetPoliciesForRole]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetMachineName]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[SubscriptionsBeingDeleted]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdatePolicy]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListInstallations]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetPolicy]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ModelDrill]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListSubscriptionIDs]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Segment]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetSystemPolicy]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListInfoForReencryption]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetModelItemPolicy]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDatasourceInfoForReencryption]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdatePolicyPrincipal]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetReencryptedDatasourceInfo]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ChunkSegmentMapping]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdatePolicyRole]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ModelPerspective]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSubscriptionInfoForReencryption]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetPolicy]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetReencryptedSubscriptionInfo]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSystemPolicy]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[CachePolicy]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteEncryptedContent]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeletePolicy]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteKey]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[SegmentedChunk]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateSession]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetAllConfigurationInfo]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteModelItemPolicy]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Users]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetOneConfigurationInfo]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteAllModelItemPolicies]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetConfigurationInfo]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ExecutionLogStorage]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetModelItemInfo]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[DataSource]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddEvent]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetModelDefinition]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteEvent]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddModelPerspective]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanEventRecords]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteModelPerspectives]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Policies]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddExecutionLogEntry]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetModelsAndPerspectives]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ExpireExecutionLogEntries]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetModelPerspectives]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetUserIDBySid]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DereferenceSessionSnapshot]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetUserIDByName]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetSessionData]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[SecData]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetUserID]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[WriteLockSession]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetPrincipalID]
        TO RSExecRole
    GRANT
        SELECT,REFERENCES
        ON [dbo].[ExecutionLog2]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CheckSessionLock]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Roles]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSessionData]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeliveryRemovedInactivateSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSnapshotFromHistory]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[PolicyUserRole]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddSubscriptionToBeingDeleted]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanExpiredSessions]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[RemoveSubscriptionFromBeingDeleted]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanExpiredCache]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetSessionCredentials]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetSessionParameters]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListSubscriptionsUsingDataSource]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ClearSessionSnapshot]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateSubscriptionStatus]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[RemoveReportFromSession]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateSubscriptionLastRunInfo]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanBrokenSnapshots]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanOrphanedSnapshots]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[InvalidateSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetCacheOptions]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanNotificationRecords]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetCacheOptions]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateSnapShotNotifications]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddReportToCache]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateDataDrivenNotification]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetExecutionOptions]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Event]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateNewActiveSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetExecutionOptions]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateActiveSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateSnapshot]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteActiveSubscription]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateChunkAndGetPointer]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Subscriptions]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateCacheUpdateNotifications]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[WriteChunkPortion]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetCacheSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetChunkPointerAndLength]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteNotification]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetChunkInformation]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetNotificationAttempt]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ReadChunkPortion]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateTimeBasedSubscriptionNotification]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CopyChunksOfType]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ActiveSubscriptions]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteTimeBasedSubscriptionSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteSnapshotAndChunks]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListUsedDeliveryProviders]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteOneChunk]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddBatchRecord]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateRdlChunk]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[SnapshotData]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetBatchRecords]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeletePersistedStreams]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteBatchRecords]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteExpiredPersistedStreams]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ChunkData]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanBatchRecords]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeletePersistedStream]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanOrphanedPolicies]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddPersistedStream]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[IncreaseTransientSnapshotRefcount]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[LockPersistedStream]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DecreaseTransientSnapshotRefcount]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[WriteFirstPortionPersistedStream]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Notifications]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[MarkSnapshotAsDependentOnUser]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[WriteNextPortionPersistedStream]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetSnapshotProcessingFlags]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetFirstPortionPersistedStream]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetSnapshotChunksVersion]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetPersistedStreamError]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Batch]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[LockSnapshotForUpgrade]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetNextPortionPersistedStream]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Schedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[InsertUnreferencedSnapshot]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSnapshotChunks]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[PromoteSnapshotInfo]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetDrillthroughReports]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateSnapshotPaginationInfo]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteDrillthroughReports]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSnapshotPromotedInfo]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDrillthroughReports]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ReportSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddHistoryRecord]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDrillthroughReport]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetHistoryLimit]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetUpgradeItems]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListHistory]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetUpgradeItemStatus]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanHistoryForReport]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetPolicyRoots]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanAllHistories]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDataSourceForUpgrade]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteHistoryRecord]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSubscriptionsForUpgrade]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteAllHistoryForReport]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[StoreServerParameters]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[RunningJobs]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteHistoriesWithNoPolicy]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetServerParameters]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[Get_sqlagent_job_status]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanExpiredServerParameters]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateTask]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CopyChunks]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateTask]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateNewSnapshotVersion]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateScheduleNextRunTime]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateSnapshotReferences]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListScheduledReports]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[OpenSegmentedChunk]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListTasks]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateSegmentedChunk]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListTasksForMaintenance]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ReadChunkSegment]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ClearScheduleConsistancyFlags]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[WriteChunkSegment]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetAReportsReportAction]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateChunkSegment]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetTimeBasedSubscriptionReportAction]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[IsSegmentedChunk]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetTaskProperties]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ShallowCopyChunk]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteTask]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeepCopySegment]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSchedulesReports]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[RemoveSegmentedMapping]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[EnforceCacheLimits]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[RemoveSegment]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddReportSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[MigrateExecutionLog]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteReportSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[TempChunkExists]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSnapShotSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateEditSession]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateTimeBasedSubscriptionSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetTimeBasedSubscriptionSchedule]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanExpiredEditSessions]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddRunningJob]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetCacheLastUsed]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[RemoveRunningJob]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSharePointPathsForUpgrade]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpdateRunningJob]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetSharePointSchedulePathsForUpgrade]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetMyRunningJobs]
        TO RSExecRole
    GRANT
        SELECT,REFERENCES
        ON [dbo].[ExtendedDataSets]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ListRunningJobs]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpgradeSharePointPaths]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CleanExpiredJobs]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[UpgradeSharePointSchedulePaths]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[CreateObject]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDataSets]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteObject]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddDataSet]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FindObjectsNonRecursive]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteDataSets]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FindObjectsRecursive]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDataSetForExecution]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FindParents]
        TO RSExecRole
    GRANT
        SELECT,REFERENCES
        ON [dbo].[ExecutionLog3]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FindObjectsByLink]
        TO RSExecRole
    GRANT
        SELECT,REFERENCES
        ON [dbo].[ExecutionLog]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetIDPairsByLink]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetChildrenBeforeDelete]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetAllProperties]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetParameters]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetObjectContent]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[LoadForDefinitionCheck]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[LoadForRepublishing]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[RebindDataSource]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[RebindDataSet]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetCompiledDefinition]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetReportForExecution]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetReportParametersForExecution]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[DBUpgradeHistory]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[MoveObject]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ObjectExists]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetAllProperties]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FlushCacheByID]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[FlushReportFromCache]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetParameters]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetObjectContent]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[DataSets]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[SetLastModified]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetNameById]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[AddDataSource]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[GetDataSources]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[DeleteDataSources]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[Keys]
        TO RSExecRole
    GRANT
        SELECT,INSERT,UPDATE,DELETE,REFERENCES
        ON [dbo].[ServerUpgradeHistory]
        TO RSExecRole
    GRANT
        EXECUTE
        ON [dbo].[ChangeStateOfDataSource]
        TO RSExecRole
    GO

A: *

*Can anyone help me with a script?

Sure! Run SQL Profiler, create new ReportServer database using 'Reporting Services Configuration Manager' (you can specify your own name to avoid collisions) and capture all statements. Final script depends on sql version and edition so it's not generic and shouldn't be reused. It's good for education (e.g. RSExecRole dependencies) and nothing else.

*

*Has anyone encountered this problem before?

I've seen attempts of scripting out all ReportServer objects. It can sound good, but it's bad idea - too easy to miss something important (RSExecRole). 3rd party databases (Reporting Services, ASPState etc) should be created and configured with dedicated tools. Another explanation - somebody explicitly dropped that role.


text:
Q: Is it a good practice to always read a value from the object, or store it in a variable and use it? I would like to know If it a good practice to always read an value from the object or store it in a variable and use it(why not a good practice or good practise)
Below piece of code
private void calc(Product product){
   User = new User(product.getCode(), ...)  // Line 2
   ....
   ....
   if(product.getCode() == 2){ //Line 4
    .....
   }
}

At line 2 and 4 , I am getting code from product.getCode(). So is it ok to read it from product object or store it in a variable say String code = product.getCode() and then use code at line 2 and 4

A: What you're asking is whether it is good practice to make a local copy of a value or should you always fetch the value from some source that owns the value.
The answer is, it depends.
What you must always remember is that when you are making a local copy of a value from some source, you own a copy of the value. You do not own the value itself nor do you own what ever mechanism is creating the value. You just own a copy. And that copy is a copy of the value generated at the time the copy was made.
So the underlying question is this, when you make a copy of the value, will the generating mechanism you are getting it from change the value it will provide at some time in the future. Should the generating mechanism change the value it generates, your copy of the value becomes invalid.
To answer this question means that you must (1) have some idea as to how the mechanism that generates the value does so and (2) that the generating mechanism will not change at some time in the future in a way that invalidates what you know now regarding how the mechanism generates the value.
Making a local copy of a value from some generating mechanism such as a function will break encapsulation. The generating mechanism and what ever encapsulating and change isolating measures are in place for the generating mechanism are being bypassed and it is no longer the source of the value, the local copy is.
In my opinion the only time any consideration as to making a local copy of a value should be entertained is when the mechanism to get the value is sufficiently costly, usually in terms of time or in terms of computational resources, that it makes sense to have a local copy. Usually the rationale for a local copy is due to the computational cost or the time cost associated with using the generating mechanism. Time costs may be network latency with a server request or if the value takes significant computations to create.
Making a local copy then requires that you ensure that the local copy properly shadows the value that would be provided by the generating mechanism. If the generating mechanism always provides the same value, for instance a function that always provides the same output for the same input, then a local copy is defensible.
If you have some way of monitoring the generating mechanism which provides various values so that the generating mechanism can tell you if there is a new value, for instance a database trigger or some other kind of event, then you can perform that check before using the local copy to determine if the local copy is still valid. If the local copy is no longer valid then you can fetch a new copy using the generating mechanism.
In some cases the time span for how long a local copy shadows the actual value generated falls within the lifetime of the local copy. In other words, the life time of the local copy is shorter than the lifetime of the value generated. For instance a local cache of the value in order to optimize a loop may be appropriate. What I mean by this is that you fetch a copy of the value from the generating mechanism and store that in a local variable, perform a loop which uses the value in a calculation of some kind, and then discard the local copy. This may make the time taken by the loop much less than if fetching the value each time and due to the short time span taken by the loop processing, any changes to the value provided by the generating mechanism is negligible and can be ignored.
An example of this would be to pull the temperature and humidity from a sensor and then perform a series of calculations using just the single value. The reason for doing so is that the overhead of interacting with the sensor and pulling the data is reasonable once but not multiple times within a loop.
Another reason for making a local copy is if there is some kind of noise in the generating mechanism such that the value provided will vary slightly in some range of error. So a sensor may provide a temperature reading that varies slightly each time it is read due to electrical noise in the circuitry so you read the sensor once and then do a number of calculations or process the temperature value in various ways using just the single value in order to reduce the error that comes from multiple, slightly different temperature readings.

A: I guess it is the same thing. A String in java is an object, thus when you call product.getCode() it will just pass you the reference of that String. But, of course, it depends on what you have behind that method.
BTW, to compare the value of a string you should use:
someString.equals(anotherString)

To compare the reference you should use:
someString == anotherString

A: We can compare those different approaches basing on the following three criteria.

*

*Performance: in this case they should be the same, unless product.getCode() is expensive.

*Cleanness: if you call product.getCode() multiple times, the second approach will be cleaner.

*Space: the second approach has to use auxiliary space.

A: If it is something simple and cheap, then I would keep reading it from the object. I would separate it into its own variable if it makes the code more clear or easier to understand.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding objects by attributes of their last child For example, let's say I have two models: Parent and Child
parent.rb
has_many :children

child.rb
belongs_to :parent

I'd like to find all parents where either parent.children.last.gender == "boy" OR parent.volunteer == "yes"
Thanks in advance.

A: Do you have to have "last child is a boy" or will "has a child who is a boy" work?
This will work a latter:
Parent.includes(:child).where("children.gender = 'boy' or parents.volunteer = 'yes'")

For last child is a boy:
Here is the equivalent of what you need in SQL, you can probably use find_by_sql to get it working or create something similar using rails syntax or Arel.
select p.* from parents p inner join
(select parent_id, gender from children where id in (select max(id) from children group by parent_id)) c
on c.parent_id = p.id where p.volunteer = 'Yes' OR c.gender = 'Boy';

Depending on the size of your database this query might be pretty expensive to run, alternative solution could be to store last child gender on the parent record, and update it every time new child is added if it's a different gender from what parent has currently.


text:
Q: Automatic Cookie clear in Android - Chrome On killing Chrome App in android, i expect the session cookies to be cleared, but they stay intact and affects certain functionalities of my site when the user re-visits the site. The same is not observed in iOS.
Is this the expected behavior ? Clearing cookies explicitly is the only option in Android ?


text:
Q: What is wrong with my convert coordinate code in Python? I'm going to convert coordinates in a gml file. Inside the file says <gml:Envelope srsName="urn:ogc:def:crs:EPSG::3347" srsDimension="2"> so I think the coordinate system is EPSG:3347. (The first lines of file shows in the end of this question)
I tried to convert the first coordinate by a Python code to Google coordinate, but I didn't get the correct coordinate. (my coordinate was 8979444.20611001,2148774.86356001 for St. John's South--Mount Pearl in Canada.)
Python code to convert
>>> from pyproj import Proj, transform
>>> inProj  = Proj("+init=EPSG:3347")
>>> outProj = Proj("+init=EPSG:4326") # I believe google use this coordinate system
>>> x, y = 8979444.20611001, 2148774.86356001
>>> print(transform(inProj,outProj,x,y))

(-52.746286073488385, 47.53880067785412)

I expect the result to be something like 47.525712,-53.0941826 since when I searched google for that area on the map I got this URL and inside the URL Google used those numbers
https://www.google.com/maps/search/St.+John's+South--Mount+Pearl/@47.525712,-53.0941826,10z
==========================================================================
The first lines of gml file which show the coordinate system and first coordinate which I tested by the Python program.
<?xml version="1.0" encoding="UTF-8"?>
<gml:FeatureCollection xmlns:fme="http://www.safe.com/gml/fme" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gml="http://www.opengis.net/gml" xsi:schemaLocation="http://www.safe.com/gml/fme ldb_000b16g_e.xsd">
<gml:boundedBy>
<gml:Envelope srsName="urn:ogc:def:crs:EPSG::3347" srsDimension="2">
<gml:lowerCorner>3689439.01142991 659338.860003093</gml:lowerCorner>
<gml:upperCorner>9015736.63142905 5242179.21714491</gml:upperCorner>
</gml:Envelope>
</gml:boundedBy>
<gml:featureMember>
<fme:ldb_000b16g_e gml:id="id06314a49-5d76-4da4-a503-61389e1de9f2">
<fme:DBUID>10010202002</fme:DBUID>
<fme:DBRPLAMX>8979444.20611001</fme:DBRPLAMX>
<fme:DBRPLAMY>2148774.86356001</fme:DBRPLAMY>
<fme:PRUID>10</fme:PRUID>
<fme:PRNAME>Newfoundland and Labrador / Terre-Neuve-et-Labrador</fme:PRNAME>
<fme:CDUID>1001</fme:CDUID>
<fme:CDNAME>Division No.  1</fme:CDNAME>
<fme:CDTYPE>CDR</fme:CDTYPE>
<fme:CCSUID>1001519</fme:CCSUID>
<fme:CCSNAME>St. John's</fme:CCSNAME>
<fme:CSDUID>1001519</fme:CSDUID>
<fme:CSDNAME>St. John's</fme:CSDNAME>
<fme:CSDTYPE>CY</fme:CSDTYPE>
<fme:ERUID>1010</fme:ERUID>
<fme:ERNAME>Avalon Peninsula</fme:ERNAME>
<fme:FEDUID>10007</fme:FEDUID>
<fme:FEDNAME>St. John's South--Mount Pearl / St. John's-Sud--Mount Pearl</fme:FEDNAME>
<fme:SACCODE>001</fme:SACCODE>
<fme:SACTYPE>1</fme:SACTYPE>
<fme:CMAUID>001</fme:CMAUID>
<fme:CMAPUID>10001</fme:CMAPUID>
<fme:CMANAME>St. John's</fme:CMANAME>
<fme:CMATYPE>B</fme:CMATYPE>
<fme:CTUID>0010003.01</fme:CTUID>
<fme:CTNAME>0003.01</fme:CTNAME>
<fme:ADAUID>10010015</fme:ADAUID>
<fme:DAUID>10010202</fme:DAUID>
<gml:surfaceProperty>
<gml:Surface srsName="urn:ogc:def:crs:EPSG::3347" srsDimension="2">
<gml:patches>
<gml:PolygonPatch>
<gml:exterior>
<gml:LinearRing>
<gml:posList>8979489.93714421 2148660.22857111 8979433.25999921 2148615.68285611 8979342.05142921 2148718.48285611 8979389.55142921 2148774.91428611 8979408.69714421 2148804.85714611 8979410.04856921 2148807.62285612 8979427.40856921 2148833.40285611 8979439.68571422 2148885.92285611 8979440.24285422 2148887.11714611 8979451.08856921 2148909.40571611 8979483.10285421 2148945.63428611 8979539.50285421 2148889.48000111 8979516.25999921 2148862.55714611 8979509.69142921 2148848.88571611 8979487.88856921 2148770.13714611 8979480.16571421 2148756.90285611 8979460.72856921 2148737.50571611 8979455.81999921 2148723.84857111 8979458.11999922 2148705.52285611 8979461.08571421 2148701.36285611 8979461.09999921 2148699.86857111 8979489.93714421 2148660.22857111</gml:posList>
</gml:LinearRing>
</gml:exterior>
</gml:PolygonPatch>
</gml:patches>
</gml:Surface>
</gml:surfaceProperty>
</fme:ldb_000b16g_e>
</gml:featureMember>
<gml:featureMember>
<fme:ldb_000b16g_e gml:id="id

A: With the following code:
from pyproj import Proj, transform, CRS, Transformer
inProj = CRS.from_epsg(3347)
outProj = CRS.from_epsg(4326)
x, y = 8979444.20611001, 2148774.86356001
t = Transformer.from_crs(inProj, outProj)
t.transform(x,y)

I get (47.53880067785412, -52.746286073488385) which is about right for St Johns.


text:
Q: Project file name field using '-tagFile' option, LOAD USING PigStorage '-tagFile', Pig 0.14 Amazon EMR-4.5, Hadoop 2.7.2, Pig 0.14
I would like to project the file name field and selected fields to a new relation after loading using the -tagFile option. The results do not seem to make sense. Examples:
tagfile-test.txt (tab-delimited)
AAA    123    2016
BBB    456    2016
CCC    789    2016

Load-Dump
test = LOAD 'tagfile-test.txt' USING PigStorage('\t','-tagFile') AS (f0, f1, f2, f3);
DUMP test;

(tagfile-test.txt,AAA,123,2016)
(tagfile-test.txt,BBB,456,2016)
(tagfile-test.txt,CCC,789,2016)

Correct - GENERATE f0, f1, f2
test = LOAD 'tagfile-test.txt' USING PigStorage('\t','-tagFile') AS (f0, f1, f2, f3);
project = FOREACH test GENERATE f0, f1, f2;
DUMP project;

(tagfile-test.txt,AAA,123)
(tagfile-test.txt,BBB,456)
(tagfile-test.txt,CCC,789)

Incorrect - GENERATE f0, f1, f3 (result same as above)
test = LOAD 'tagfile-test.txt' USING PigStorage('\t','-tagFile') AS (f0, f1, f2, f3);
project = FOREACH test GENERATE f0, f1, f3;
DUMP project;

(tagfile-test.txt,AAA,123)
(tagfile-test.txt,BBB,456)
(tagfile-test.txt,CCC,789)

Incorrect - GENERATE f0, f2, f3 (confirm)
test = LOAD 'tagfile-test.txt' USING PigStorage('\t','-tagFile') AS (f0, f1, f2, f3);
project = FOREACH test GENERATE f0, f2, f3;
DUMP project;

(tagfile-test.txt,AAA,2016)
(tagfile-test.txt,BBB,2016)
(tagfile-test.txt,CCC,2016)

It seems Pig is not correctly identifying the field names. I have tried using field positions ($0, $1, $2, $3) with the same results.

A: I faced the same issue when used tagFile option with pigstorage and solved the problem by adding below line in pig script:

set pig.optimizer.rules.disabled 'ColumnMapKeyPrune';

ColumnMapKeyPrune is well explained at http://chimera.labs.oreilly.com/books/1234000001811/ch07.html#debugging_tips

A: It looks like the fields are separated by ',' but you are using '\t' as the delimiter in PigStorage.Also specify the datatype for the fields.
Try changing this
test = LOAD 'tagfile-test.txt' USING PigStorage('\t','-tagFile') AS (f0, f1, f2, f3);

To
test = LOAD 'tagfile-test.txt' USING PigStorage(',','-tagFile') AS (f0:chararray, f1:chararray, f2:int, f3:int);


text:
Q: fragmenttabhost on first time could not display data I am trying to use fragmenttabhost that 4 tabs, but when I into first tabs could not display data on first time, however i should click other tabs then back first tab the data would be show.
i will  via API data then  display onlistview and viewpager(picture and text)  in different  tabs , but i don't understand or lose some things should to do...
my activity:
FragmentActivity extends ActionBarActivity

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        tabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        tabHost.addTab(setIndicator(this,tabHost.newTabSpec(TAB_1_TAG),0,"first tab",R.drawable.ic_launcher), firstFragment.class,null);
        ...

my fragment:
1 :use volley and get json data(ex:get a imagm  url )
FirstTabFragment extends Fragment
onAttach(Activity activity)
        @Override
        public void onAttach(Activity activity) {
        ..
        use volley and get json data(ex:get a imagm url)...
        ...}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tabfragment_page1, container, false);
        return rootView;`

2.onActivityCreated:use volley image url show some pictures to pageView widge...
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    //use volley image url show some pictures on pageView widge...
    RequestQueue mQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
    Log.d(tag,"myurl.get(i)"+promotionOneUrl.get(i));
    ImageRequest imageRequest = new ImageRequest(promotionOneUrl.get(i),
            new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
            imageView.setImageBitmap(response);}
            }, 0, 0, Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error){
            R.drawable.default_image);}});
    mQueue.add(imageRequest);

p.s.sorry for poor english


text:
Q: How to capture kobject_uevent using C program? I have created /dev/ttyACM0 port in my target for gps connection. Due to some reason this port is disconnecting in between when target is running. Whenever disconnection happen I will get kobject-uevent and right not I am capturing this event using netlink sample program as follow.
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <sys/socket.h>
    #include <linux/netlink.h>
    #include <unistd.h>
    #include <errno.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <sys/time.h>
    #include <sys/socket.h>
    #include <linux/netlink.h>

#define NETLINK_TEST    17
#define MYGROUP         1

#define MAX_PAYLOAD 1024  /* maximum payload size*/
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
int sock_fd;
struct msghdr msg;

int main()
{
    int ret, fd;
    char *temp;

    fd = open("/dev/ttyACM1", O_RDWR);
    if (fd < 0) {
        printf("Unable to open port\n");
        return -1;
    }
    printf("Creating socket\n");
    sock_fd=socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
    if(sock_fd<0) {
        printf("Socket creating failed\n");
        return -1;
    }

    memset(&src_addr, 0, sizeof(src_addr));
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid();  /* self pid */
    src_addr.nl_groups = MYGROUP;
    /* interested in group 1<<0 */
    ret = bind(sock_fd, (struct sockaddr*)&src_addr,
            sizeof(src_addr));
    if (ret < 0) {
        printf("Bind Failed\n");
        perror("bind:");
        return -1;
    }

    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0;   /* For Linux Kernel */
    dest_addr.nl_groups = 0; /* unicast */

memset(&dest_addr, 0, sizeof(dest_addr));
dest_addr.nl_family = AF_NETLINK;
dest_addr.nl_pid = 0;   /* For Linux Kernel */
dest_addr.nl_groups = 0; /* unicast */

    nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
    nlh->nlmsg_flags = 0;
    iov.iov_base = (void *)nlh;
    iov.iov_len = nlh->nlmsg_len;
    msg.msg_name = (void *)&dest_addr;
    msg.msg_namelen = sizeof(dest_addr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    printf("Waiting for message from kernel\n");
    /* Read message from kernel */
    while (1) {
        recvmsg(sock_fd, &msg, 0);
        temp = strstr(NLMSG_DATA(nlh), "tty/ttyACM1");
        printf("Received message payload: %s\n", temp);
    }
    close(sock_fd);
    return 0;
}

using this program I am getting below output.
Received message payload: 0000:00/0000:00:15.0/usb1/1-4/1-4:1.0/tty/ttyACM1

which is the path of the device for which disconnect happen. But when I check /lib/kobject_uevent.c code I have seen it is sending action_string with device path which is in my case remove.
If I want to capture this action_string how can I capture it?

A: Hi Due to some research and suggestion by Prabhakar in comment I came to know we have to use libudev.so libraries for getting the proper uevent in user space.
But for testing purpose I went through libudev source code and found out libudev also captures uevent using netlink. Only the difference in libudev code is it uses union{} which contain 'struct nlmsghdr' and 'char buf[SIZE]'. So data which is coming in nlmsghdr struct we can print using buf.
So as a Hack I used union instead of "struct nlmsghdr *nlh" and created one raw buffer inside that union along with this structure as below
union {
    struct nlmsghdr nlh;
    char raw[8192];
} buf;

Full working program after this changes is as follow:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <unistd.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <linux/netlink.h>

#define NETLINK_TEST    17
#define MYGROUP         1

#define MAX_PAYLOAD 1024  /* maximum payload size*/
struct sockaddr_nl src_addr, dest_addr;
union {
    struct nlmsghdr nlh;
    char raw[8192];
} buf;
struct iovec iov;
int sock_fd;
struct msghdr msg;

int main()
{
    int ret, fd, i;
    char *event_buf;
    char action[50];
#if 1
    fd = open("/dev/ttyACM1", O_RDWR);
    if (fd < 0) {
        printf("Unable to open port\n");
        return -1;
    }
#endif
    printf("Creating socket\n");
    sock_fd=socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
    if(sock_fd<0) {
        printf("Socket creating failed\n");
        return -1;
    }

    memset(&src_addr, 0, sizeof(src_addr));
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid();  /* self pid */
    src_addr.nl_groups = MYGROUP;
    /* interested in group 1<<0 */
    ret = bind(sock_fd, (struct sockaddr*)&src_addr,
            sizeof(src_addr));
    if (ret < 0) {
        printf("Bind Failed\n");
        perror("bind:");
        return -1;
    }

    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0;   /* For Linux Kernel */
    dest_addr.nl_groups = 0; /* unicast */

    memset(&buf, 0, sizeof(buf));
    iov.iov_base = &buf;
    iov.iov_len = sizeof(buf);
    msg.msg_name = (void *)&dest_addr;
    msg.msg_namelen = sizeof(dest_addr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
#if 1
    /* Read message from kernel */
    while (1) {
        recvmsg(sock_fd, &msg, 0);
        if (strstr(buf.raw, "/tty/ttyACM1") != NULL) {
            event_buf = buf.raw;
            for (i = 0; event_buf[i] != '@'; i++)
                action[i] = event_buf[i];
            action[i] = '\0';
            printf("ACTION = %s\n", action);
            if ((strcmp(action, "remove")) == 0) {
                close(fd);
                printf("ACM port closed\n");
            }
        }
    }
end:
    close(sock_fd);
#endif
    return 0;
}

Here in buf.raw i am getting uevent message with action_string. For Example:
remove@/devices/pci0000:00/0000:00:15.0/usb1/1-3/1-3:1.0/tty/ttyACM2

where "remove" is action string and rest of the string after '@' is device path for that event.


text:
Q: How to I setup a VoIP Server (not connected to telephony) What I need is a VoIP server that allows people use their data bundle to make calls within an app (mobile/PC), but not necessarily app to phone but App to App.
That means, both users have the app running and they don't need to have phone numbers.

*

*What would I need to know (I'm developing the App for Mobile - Android, BB, iOS)?

*What would the configuration of my server be (hardware requirements)?

*What are the software requirements?

A: Do you want to develop the App yourself? I would choose one of the many apps already available.
First you need to decide what protocol you want to use. Users could just use Skype to communcate from Skype to Skype. Downside/Upside is you don't need a server of your own.
If you want to setup your own server you could go for the widely used SIP-protocol.
Here is a list of server-software. You can check out the pages to see the hardware requirements.
Two of the most used VOIP-servers are Asterisk and Freeswitch.
With these servers you can use one of the many (SIP-)apps available.
Another possibility is choosing one of the many VOIP-providers on the internet. You need to choose one who does not charge you for calls between users. For example Voipbuster has free PC to PC (and App to App) calling. The mother-company of Voipbuster has many, many, many sub-companies who all have different rates of calling land-lines per country (which you don't need) but all provide free user to user calling. So you won't need your own server.
Before deciding which one of the options above you want, you need to test (and check) if your cell-provider does not block any of these protocols. Sometimes the provider blocks Skype and/or SIP-protocol via data because it hurts their business. In Europe there are laws (coming) against the blocking of these protocols but it's best to check beforehand.


text:
Q: How do I save to Django's database manually? I'm trying to make a UserProfile model in Django. Half the information for the fields in this model will come directly from the user's input in a form, but the other half I'm importing from a social network that they authenticate when they login. How would I go about implementing this?
if form.is_valid():
    prefs = form.save(commit=False)
    prefs.user = request.user
    prefs.save()
    # if they logged in through social network there are other fields
    if socialacc:
        firstname = socialacc[0].extra_data['firstName']

So now I have the data for 'firstname' as a string. How should I save this to the same model? The model will include a field called firstname, which will be empty unless there is social authentication information available.
Thanks a lot for any help!

A: Since the save method returns an Model object, you can modify it again before definitively save it to the database :
if form.is_valid():
    prefs = form.save(commit=False)
    prefs.user = request.user
    # if they logged in through social network there are other fields
    if socialacc:
        prefs.firstname = socialacc[0].extra_data['firstName']
        ...
    prefs.save()


text:
Q: Display pdf with transparent background with pdf.js I have a pdf with 4 pages, each of the page has a transparent background. I use pdf.js to display them, but I would like to display them with a transparent background on my html page but I can't figure out how I could do that, there is always a white background :

I think it is possible according to this issue, but when I change the line page.render(renderContext); to page.render({renderContext, viewport, backgroundColor: 'rgba(0,0,0,0)' }); (as it said in the issue) I have the following error :

Any idea on how I could manage that ?
I use pdf.js version v1.9.426 and Firefox 55.0.2 (64 bits).
EDIT :
With the following code I have no error in the console but the background of my pdf file is still white. (However, If open the pdf with for example photoshop there is no background)
Link to the PDF file I use : tempPDF.pdf
Here is my javascript file to display the four pages :
var pdfFile;
PDFJS.getDocument('/assets/pdf/tempPDF.pdf').then(function (pdf) {
    pdfFile = pdf;

    for(var i = 1; i <= 5; i++) {
        var canvas = document.getElementById('canvas'+i);
        var context = canvas.getContext('2d');
        PDFJS.disableStream = true;
        openPage(pdf, i, context, 50);
    }
});

function openPage(pdfFile, pageNumber, context, ratio) {
    var scale = 10;
    pdfFile.getPage(pageNumber).then(function (page) {
        viewport = page.getViewport(scale);
        // reference canvas via context
        var canvas = context.canvas;
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        canvas.style.width = ratio+"%";
        canvas.style.height = ratio+"%";
        var renderContext = {
            canvasContext: context
            , viewport: viewport
        };
        page.render({canvasContext: context, viewport: viewport, backgroundColor: 'rgba(0,0,0,0)' });
        //page.render(renderContext);
    });
}

And my html page in case that could be useful :
<!DOCTYPE html>
<html>
<body
        style="background-color:powderblue;">
</body>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="PDF Viewer" />
    <title>My page</title>
</head>
<body>
    <form action="pdf_latex_test.php">
        <input type="submit" value="execute" /> </form>
</body>
<body>
    <canvas id="canvas1" width="300" height="300"></canvas>
    <canvas id="canvas2" width="300" height="300"></canvas>
    <canvas id="canvas3" width="300" height="300"></canvas>
    <canvas id="canvas4" width="300" height="300"></canvas>
<script src="/assets/js/pdf.js"></script>
<script src="/assets/js/pdf.worker.js"></script>
<script src="/assets/js/pdf.latex.main.js"></script>
</body>
</html>

A: The change and API documentation shows that property name must be background:

var url = '//cdn.mozilla.net/pdfjs/helloworld.pdf';

PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

var loadingTask = PDFJS.getDocument(url);
loadingTask.promise.then(function(pdf) {
  var pageNumber = 1;
  pdf.getPage(pageNumber).then(function(page) {
    console.log('Page loaded');

    var scale = 1.5;
    var viewport = page.getViewport(scale);

    // Prepare canvas using PDF page dimensions
    var canvas = document.getElementById('the-canvas');
    var context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    // Render PDF page into canvas context
    var renderContext = {
      canvasContext: context,
      // Use transparent background!
      background: 'rgba(0,0,0,0)',
      viewport: viewport
    };
    var renderTask = page.render(renderContext);
    renderTask.then(function () {
      console.log('Page rendered');
    });
  });
}, function (reason) {
  // PDF loading error
  console.error(reason);
});
#the-canvas {
  border:1px solid black;
  background-image: url(http://image.blingee.com/images19/content/output/000/000/000/7c8/805674825_1628628.gif?6);
}
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<canvas id="the-canvas"></canvas>


text:
Q: How to center navigation bar in Drupal? I'm trying to center the navigation on this page: http://66.147.244.50/~schneie1/
However, the div containing the ul of buttons take up the entire width and thus I can't do "text-align:center;"
Here's the page.tpl.php and the CSS-file:
<nav id="navigation" role="navigation" class="clearfix">
    <?php if ($page['navigation']): ?> <!--if block in navigation region, override $main_menu and $secondary_menu-->
        <?php print render($page['navigation']); ?>
    <?php endif; ?>
    <?php if (!$page['navigation']): ?>
        <?php if ($main_menu): print $main_menu;
        endif; ?>
        <?php if ($secondary_menu): print $secondary_menu;
        endif; ?>
<?php endif; ?>
</nav> <!-- /#navigation -->

#navigation {
    margin: 0 0 1.5em;
    padding: 0;
    width:auto;
    margin-left:auto;
    margin-right:auto;
}

#navigation ul.main-menu {
    margin:0;
    padding: 0;
    display:block;
    width:auto;
}

#navigation ul.main-menu li {
    float: left;
    margin: 0;
    padding: 0;
}

Thanks in advance!

A: Change your width on your #navigation from "auto" to a value. Auto means it will extend the full width of the screen, unless you've already wrapped it in a block level element which has a fixed width. You need something for your "auto" to reference.


text:
Q: Calculating a point in 3D space I am trying to locate a point in 3D space relative to the origin (0,0,0).  I have 3 values to calculate this point with: a rotation in degrees about both the x and y axis as well as a "view distance".  Using these values, how can I locate a point in 3D space relative to the origin?  I have tried using basic trigonometric functions, but the results seem to be random. The image below gives a visual as to what needs to be done.

*

*'vd' being the "view distance"

*'c' being a value holder

*'(x,y,z)' being the coordinate I am trying to find

What I am trying to do is find the point a player is looking at a certain distance away (find a point in the direct line of sight of the player out a certain distance).  Keep in mind, the rotations about the x and y axis are constantly changing, but the view distance remains the same.  If anyone has any suggestions, methods of how to do this, or needs clarification, please comment/answer below.
I am doing this in LWJGL, and the code I am using is as follows:
    float c = (float)(Math.cos(Math.toRadians(A00.rot.y)) * view_distance);
    locate.y = (float)(Math.sin(Math.toRadians(rot.y)) * view_distance);
    locate.x = (float)(Math.cos(Math.toRadians(rot.x)) * c);
    locate.z = (float)(Math.sin(Math.toRadians(rot.x)) * c);

EDIT:
My issue is that this current setup does NOT work for some reason.  The math seems legitimate to me, but I must have something wrong somewhere in the actual setup of the graph..

A: I suggest looking up quaternions. No need to fully understand how they work. You can find ready made classes for java available on the internet as well. Quaternions allow you to represent a rotation in 3D space.
What I would then do, is to start with a vector representing the direction pointing forwards from the origin, and apply the same rotation that the player currently has to it. Now it is pointing in the same direction as the player. Now if you take the player's current point, and the direction vector we now have a ray describing where the player is looking at.
I suggest this link for further information on quaternions. They may look complex but, as I said, you don't need to fully understand how and why they work to be able to use them. Just copy the formulae and learn how they are used. Once you figure out how to use them, they make 3d rotations really easy.
http://content.gpwiki.org/index.php/OpenGL:Tutorials:Using_Quaternions_to_represent_rotation


text:
Q: How to get radio Button values number I am making an application that has list and Radio Buttons. My Layout contains of the following : a list , A button .
The List contains of Radio buttons. Two radio Buttons. After checking the buttons. I want to make a loop that reads the values of how many are in Button one and how many in Button Two.
This is how I have done so far.
        ListViewStudentEditAbsence country ;

            for(int i=0;i<listViewStudentNames.size();i++) {
                country = listViewStudentNames.get(i);
                if (country.getAbsence()==1) {
                    Absence[i] = "1";
                } else {
                    Absence[i] ="0";
                }
            }

But It doesn't seem to work.

A: https://stackoverflow.com/questions/11194515/android-get-value-of-the-selected-radio-button
Android getting value from selected radiobutton
Hope it works. This two links give you proper knowledge about fetching value.

A: In your CustomAdapter getView() method
int value=0; //globally
    RadioGroup radioGroup = (RadioGroup) convertView.findViewById(R.id.yourRadioGroup);
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // checkedId is the RadioButton selected
                  if (checkedId == R.id.rbutton1) {
                    value=10;  //a's value
                } else if (checkedId == R.id.rbutton2) {
                    value=20; //b's value
                }
            }
        });


text:
Q: Как получить оригинальные нативные объекты браузера, если они были изменены? Собственно весь вопрос.
Своего рода анти-манки патчинг.
Как достать оригинальные объекты (Object, Array, Function, String, etc) и их прототипы, если они были  изменены \ расширены \ удалены?
Единственный возможный вариант, который сейчас вижу - это динамическое создание фрейма - вытаскивание из него нативных объектов - удаление фрейма на лету. Возможно тоже самое можно проделать с помощь Web Workers. Но они ie > 9, в них нет классов DOM, и сам по себе путь такой же как динамический фрейм.
Пример.
delete Object.prototype.constructor;
delete Object;

console.log(window.__proto__.__proto__.__proto__.constructor); // undefined
// console.log(Object); // undefined

var frame = document.createElement('frame');
document.all[0].appendChild(frame);

var Object = frames[0].Object;
document.all[0].removeChild(frame);
console.log(Object);

Возможно есть иные пути решения?
Заранее спасибо.
upd.
Относительно - не стоит использовать библиотеки которые лезут в нативы.
Вы можете разрабатывать встраиваемую систему.
Допустим вы пишите библиотеку, которая в последствии будет использоваться кем-то и где-то. Какие еще библиотеки использует этот кто-то и где-то, неизвестно. И тогда становится, имхо, вполне разумно предусмотреть варианты, доступа к нативному окружения, учитывая тот факт, что еще до инициализации Вашей библиотеки, могут быть инициализированы иные, которые способны были бы на все (трудно сейчас привести конкретный пример, но откатившись на несколько лет назад, можно вспомнить prototype).
Тоже самое с песочницами. Ее введение, как средство отбрасывания yet-another-super-cool-class-prefix, сами по себе решают проблемы конфликтов между различными фреймворками\библиотеками.
Да, разумеется, решая конкретную задачу, можно опираться на свой рассудок.
Но при реализации встраиваемых вещей - неизвестно кто, как и куда будет встраивать. Почему бы не рассмотреть возможные варианты, даже с точки зрения просто интереса.
upd.
Вопрос и стоит в том, как попросить выдать движок эти начальные состояния объектов.
Ибо при условии, что наверняка не известно, когда именно будет инициализирована функция, что запишет начальные свойства объектов, нельзя быть уверенным, что они не будут подделаны до ее вызова.
Пути по типу frame\workers очевидны, так как создается чистое новое окружение.
Но нельзя же быть всегда уверенным во всем на сто процентов, и быть может кто-то знает то, чего не знаешь ты. Посему я и интересуюсь у сообщества. Мало ли где то в global-object есть скрытый зарытый в proto или куда-либо объект, в котором сложено аккуратно в ряд, все это самое начальное окружение, да и дополненное свойствами запрета на модификацию\удаление\запись, а я о нем и не знаю. Или же существуют еще способы получения new window без явного создания онного. Например тот же frame по сути инициализируется лишь после добавления в документ, но не при самом создании элемента (createElement), что вызывает лишние телодвижения по его деинициализации после. С workers удобнее, но в них, как я уже описывал, нет нативных объектов браузера для работы с DOM, плюс они не поддерживаются старыми версиями тех же браузеров.

A: Не думаю, что вопрос без предварительной записи(да и там все непросто) как-то решается, дело в том, что в js эти самые native не то чтобы совсем native (а те что менять нельзя уже и так неизменяемые), придти к бессмысленности попыток решения (и к осознанности возможной необходимости без iframe)   можно попытавшись решить сию проблему для серверных движков типа nodejs - c одной стороны для них нет никаких iframe, с другой, понятие "native" становится очень расплывчато. Для ноды решение похожее - тредовая либа.
Второй вариант - запретить менять свойства нативных объектов при инициализации (правда этот запрет будет распространяться и на код самого тюремщика), доступно вроде и для v8 и для spidermonkey, для IE не знаю.
@VladD в той задаче про TopMostWindow есть одно большое упущение - в сети супермаркетов есть администратор и операторы, и если уж компы позволяют всякие извращения, то почему бы просто все программы кроме одной, самой главной, не запихать в виртуальную машину ? И оператор девайса сам в таком случае решает. про задачи @vldmir я примерно так-же думаю, не стоит использовать библиотеки которые лезут в native (кроме может быть полифилов и то...), бить по рукам в общем всех кто ответсвенен. а для песочниц... В общем, не зря jsfiddle сделали отдельный фрейм на отдельном домене, в блоге даж писали.
Кстати, от использования prototype меня как раз оттолкнуло  то, что он вольно обходится с "несвоими" (c) объектами, вряд-ли бы вам понравился фреймворк, который зачем-то умножает все целые  числа на 2 во всех свойствах всех объектов вашего кода :), мне интересно было бы решить эту проблему но я, как уже сказал, не могу решить философскую проблему - какие свойства native, а какие нет. Я понимаю - состояние прототипов до исполнения любого кода можно посчитать native, но тогда и решением будет - тупо записать всё. Мне кажется в свете такого решения попросить движок выдать "нач" состояние - лучше.


text:
Q: How can I make tuple of tuples? I'm trying to make tuple of tuples!
a = ('Oct 27, 2021', 'Oct 24, 2021', 'Oct 20, 2021', 'Oct 20, 2021')
b = ('1',)

>>> h=tuple([a+b])
(('Oct 27, 2021', 'Oct 24, 2021', 'Oct 20, 2021', 'Oct 20, 2021', '1'),)

What I want is this
(('Oct 27, 2021', 'Oct 24, 2021', 'Oct 20, 2021', 'Oct 20, 2021'), ('1'))

I've tried to use the zip but didn't work!
in my opinion it should be easy, but I can't find the answer.
Could I get some help on this?

WOW
I've tried (a+b).... so sorry for that.
It should be (a,b) not (a+b)!

A: Tuples are unchangedable (see: https://www.w3schools.com/python/python_tuples.asp). It means you cannot append, merge or extend them.
The only way to get what you want is to directly write them as:
(b, t)


text:
Q: Can a name used in define be redefined in php? Can a define be redefined in PHP?
e.g.
define("__root__", "/some/path");

Can the name __root__ be redefined?

A: http://php.net/manual/en/function.runkit-constant-redefine.php
It's there, just don't do it.

A: Constant is called constant because it is constant.

A: No, the idea of constants in PHP is that they can't be redefined. If you wan't to do this eventually you could use just variables or the $_GLOBALS array.


text:
Q: Is there a way to load pages/site from specific referring source only? I am trying to create a user manual for our software which would be stored on WordPress.  But I don't want it accessible to just anyone, it should be hidden, at the very least not indexed by search engines.  I know how to set pages not to be indexed so that they are "private".
But is there a way to take it a step further and have the pages ONLY load if they are referred by the software? So let's say a user is in one of our modules and there's a Help button, they click on it and it takes them to the right page on WP.  But WP checks to see where the link came from and if it came from the software it will display, otherwise not.
That would be the best case scenario, any ideas if this is achievable?

A: My preferred option is a quick-and-dirty, though very common, solution. The vendor has a "Support" page that contains limited "public" information. However the page includes a user "sign in" option so that authorised users can access all the "private" data that you have concerning your product.
This page can be accessed via the public website as well as via the  software (such as "Help > On-line Support").
You can be creative with the sign in details. The user name might be the licenced user name (which might be entered when the software is first installed). The password might be a code that is issued at the time of sale, but that is subject to a compulsory password change on first use, or even as part of a post-sales validation process. There are as many  options for sign in details as one's imagination can dream up.


text:
Q: JS regexp to match words, exclude words surrounded by slashes This regexp is working in PHP:
(?<![\/?$])\bfoo\b

I need to make it working in JS, so
foo             - need this

foo
  - need this

Foo         - dont need this
foobar      - dont need this
/foo/       - dont need this

Update: >solution<

A: (?:^|[^\/?$])(\bfoo\b)

You can use this and grab the group now.See demo.
https://regex101.com/r/cJ6zQ3/37


text:
Q: How to debug a library from an application in Angular v10 with VS Code I have created, built and npm published a library called @abc/library.
In my application I declared it in package.json and installed with npm install (I have it now in application node-modules/@abc/library folder).
Everything works fine but now I am looking for a way to debug the library from my application, allowing me to directly access its source code and place breakpoints (in node-module I can access only declarations, located in d.ts files).
Following advices from other threads I tried:

*

*Setting npm link on library main folder (npm link) and in application main folder (npm link "@abc/library")

*Setting sourceMap for scripts, style and vendor to true in application angular.json file:

"build": {
  "options": {
    "sourceMap": {
      "scripts": true,
      "styles": true,
      "vendor": true
     }
  }
}

Unfortunately nothing seems to work for me
Update
I found that after adding sourceMap options in application angular.json file, I'm able to debug the library in Chrome dev tools by following the path:
webpack://.node_modules/@abc/projects/library/src/lib

still though, I cannot debug it directly in Visual Studio Code


text:
Q: Losing Window focus in own Visual Studio extension (using EnvDTE) I'm writing a C# document outline extension for Visual Studio 2013.
The idea is to have a outline window and if the user clicks on a outline element the cursor jumps to the linked position in the code document. I'm using the EnvDTE.Document class to realise this:
DTE2 dte = GetService(typeof(DTE)) as DTE2;
var currentDocument = dte.ActiveDocument;

currentDocument.Activate();

var selection = (EnvDTE.TextSelection) CurrentDocument.Selection;
selection.MoveToLineAndOffset(line, offset);

I do the activation and selection change in a OnMouseDoubleClick event handler.
The issue is that at first the focus changes as intended but than my tool window gets the focus back.
How do I prevent the focus from returning to the my tool window?

A: Found the solution!
Actual Problem:
The Issue was caused by the TreeView bubble behaviour. I.e. even if you handle the MouseDoubleClick event it bubbles up till the tree root element. My first level of TreeViewItems doesn't had my OnMousDoubleClick event handler connected. Therefore they reclaimed the focus once the event bubble reached them.
Solution:
Connect the OnMousDoubleClick handler to all TreeViewItem element in your tree and let all them call
currentDocument.Activate();

right at the beginning in the event handler - always.


text:
Q: Pulling Docker Images - Manifest not found I'm trying to download a tagged docker image
docker pull clkao/postgres-plv8:10-2

and, in a compose file,
  postgres:
    image: clkao/postgres-plv8:10-2

But receive a manifest not found exception.
Unless I'm mistaken, that tag exists in Docker Hub, however I notice that it doesn't appear on the tags list.
Am I doing something wrong? Or is this perhaps an issue with Docker Hub or the way that repo has been set up?
If it isn't 'my fault', what's a recommendation to move forward? Create my own Dockerfile perhaps?

A: I just got over this "manifest for / not found: manifest unknown: The named manifest is not known to the registry."
Using
docker login <repo>

A: You might also try
docker pull -a <image>.
The -a will pull all versions of that image, which at least lets you know what is there.
(This is less useful if you really need a specific version, but helped me when I tried to pull an image that for some reason did not have a 'latest' tag.)
Edit:  This is actually a really bad idea, since it will pull down the entire history, which for many repositories could be many GB.  Better to go look at the repository site and see what tag you want.   Note to self: don't post answers when you are tired.  :-(

A: You get the error message because there exist no tag with "10-2".
You can try to figure out why and contact the repository owner or you can try to build your own one.

A: Check the docker's image also not only that the tag exists,  I was trying to run Flyway version 5.0.1 for an image flyway/flyway which version did not exist, it existed only in version flyway/flyway:latest it seems, whereas 5.0.1 existed and I pulled it but in/from a different repository name, with repository name boxfuse/flyway.
for the error message 'docker manifest unknown'

A: When you use docker pull, without a tag, it will default to the tag :latest. Make sure that when we are building a image add tag latest or we can access the image by the tag name after image name with colon

A: I think you are trying to tag your image as v8.10.2. Make sure while tagging image locally you use same tag which you want to pull in future. So steps will  be like below:

*

*docker build -t clkao/postgres-pl:v8.10.2 .

*docker push clkao/postgres-pl:v8.10.2

*docker pull clkao/postgres-pl:v8.10.2

A: If this is from Git via docker.pkg.github.com then you need to switch to use ghcr.io. The former is deprecated and does not support the manifest endpoint so some docker clients, when they attempt to download various resources, fail with this error message. If you instead publish your image to ghcr (Github Container Repository), the docker image pulling process should complete successfully.
cd <dir with Dockerfile in it>
docker build -f Dockerfile -t ghcr.io/<org_id>/<project_id>:<version> .
docker push ghcr.io/<org_id>/<project_id>:<version>

More info here: https://docs.github.com/en/packages/working-with-a-github-packages-registry/migrating-to-the-container-registry-from-the-docker-registry

Note: The Container registry is currently in public beta and subject
to change. During the beta, storage and bandwidth are free. To use the
Container registry, you must enable the feature preview. For more
information, see "Introduction to GitHub Packages" and "Enabling
improved container support with the Container registry."


text:
Q: Images positions are wrong in the Jpegimagestomovie (Video Recorder) I got a problem when I'm trying to record my screen.
Here's a code to begin with :
When I'm pressing a button which will record this is the code :
if (record) {
                                System.out.println("RECORDING!");
                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    try {
                                        Thread.sleep(1);
                                    } catch (InterruptedException e2) {
                                        // TODO Auto-generated catch block
                                        e2.printStackTrace();
                                    }
                                    while (record) {
                                        count++;
                                        try {
                                            BufferedImage image = new Robot()
                                                    .createScreenCapture(new Rectangle((int) width, (int) height));

                                            File f = new File(
                                                    "LOCATION" + count + ".jpg");
                                            ImageIO.write(image, "JPEG", f);

                                        } catch (AWTException e1) {
                                            e1.printStackTrace();
                                        } catch (IOException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }).start();

                        }

When I'm stopping the record then I'm starting to make the video (.avi) which is this code :
record = false;

                                    System.out.println("RECORDING HAS STOPPED!");
                                    try {
                                        Thread.sleep(3500);
                                    } catch (InterruptedException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }
                                    JpegImagesToMovie imageToMovie = new JpegImagesToMovie();

                                    Vector<String> imgList = new Vector<String>();

                                    File f2 = new File("LOCATION");
                                    File[] fileList = f2.listFiles();

                                    for (int i = 0; i < fileList.length; i++) {
                                        imgList.add(fileList[i].getAbsolutePath());

                                    MediaLocator ml;

                                    if ((ml = imageToMovie.createMediaLocator("a.avi")) == null) {
                                        System.exit(0);
                                    }

                                    imageToMovie.doIt((int) width, (int) height, 1, imgList, ml);
                                }

                            }

When It makes the video this is what I get and you can see that the images are completely out of position
Setting the track format to: JPEG
- create DataSink for: file:LOCATION\a.avi
start processing...
  - reading image file: LOCATION\image10.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image100.jpg
    read 115899 bytes.
  - reading image file: LOCATION\image101.jpg
    read 115899 bytes.
  - reading image file: LOCATION\image102.jpg
    read 115899 bytes.
  - reading image file: LOCATION\image11.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image12.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image13.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image14.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image15.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image16.jpg
    read 118065 bytes.
  - reading image file: LOCATION\image17.jpg
    read 118065 bytes.
  - reading image file: LOCATION\image18.jpg
    read 118065 bytes.
  - reading image file: LOCATION\image19.jpg
    read 118065 bytes.
  - reading image file: LOCATION\image2.jpg
    read 106079 bytes.
  - reading image file: LOCATION\image20.jpg
    read 118065 bytes.
  - reading image file: LOCATION\image21.jpg
    read 118065 bytes.
  - reading image file: LOCATION\image22.jpg
    read 118065 bytes.
  - reading image file: LOCATION\image23.jpg
    read 118040 bytes.
  - reading image file: LOCATION\image24.jpg
    read 118169 bytes.
  - reading image file: LOCATION\image25.jpg
    read 118150 bytes.
  - reading image file: LOCATION\image26.jpg
    read 118120 bytes.
  - reading image file: LOCATION\image27.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image28.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image29.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image3.jpg
    read 106612 bytes.
  - reading image file: LOCATION\image30.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image31.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image32.jpg
    read 118265 bytes.
  - reading image file: LOCATION\image33.jpg
    read 118263 bytes.
  - reading image file: LOCATION\image34.jpg
    read 118283 bytes.
  - reading image file: LOCATION\image35.jpg
    read 118283 bytes.
  - reading image file: LOCATION\image36.jpg
    read 118283 bytes.
  - reading image file: LOCATION\image37.jpg
    read 118283 bytes.
  - reading image file: LOCATION\image38.jpg
    read 118274 bytes.
  - reading image file: LOCATION\image39.jpg
    read 118270 bytes.
  - reading image file: LOCATION\image4.jpg
    read 106612 bytes.
  - reading image file: LOCATION\image40.jpg
    read 118209 bytes.
  - reading image file: LOCATION\image41.jpg
    read 118280 bytes.
  - reading image file: LOCATION\image42.jpg
    read 118203 bytes.
  - reading image file: LOCATION\image43.jpg
    read 118202 bytes.
  - reading image file: LOCATION\image44.jpg
    read 118165 bytes.
  - reading image file: LOCATION\image45.jpg
    read 118197 bytes.
  - reading image file: LOCATION\image46.jpg
    read 118251 bytes.
  - reading image file: LOCATION\image47.jpg
    read 118270 bytes.
  - reading image file: LOCATION\image48.jpg
    read 118172 bytes.
  - reading image file: LOCATION\image49.jpg
    read 118162 bytes.
  - reading image file: LOCATION\image5.jpg
    read 106612 bytes.
  - reading image file: LOCATION\image50.jpg
    read 118125 bytes.
  - reading image file: LOCATION\image51.jpg
    read 118101 bytes.
  - reading image file: LOCATION\image52.jpg
    read 118092 bytes.
  - reading image file: LOCATION\image53.jpg
    read 118096 bytes.
  - reading image file: LOCATION\image54.jpg
    read 118075 bytes.
  - reading image file: LOCATION\image55.jpg
    read 118060 bytes.
  - reading image file: LOCATION\image56.jpg
    read 118165 bytes.
  - reading image file: LOCATION\image57.jpg
    read 116149 bytes.
  - reading image file: LOCATION\image58.jpg
    read 117707 bytes.
  - reading image file: LOCATION\image59.jpg
    read 123115 bytes.
  - reading image file: LOCATION\image6.jpg
    read 106612 bytes.
  - reading image file: LOCATION\image60.jpg
    read 123115 bytes.
  - reading image file: LOCATION\image61.jpg
    read 123115 bytes.
  - reading image file: LOCATION\image62.jpg
    read 123575 bytes.
  - reading image file: LOCATION\image63.jpg
    read 123637 bytes.
  - reading image file: LOCATION\image64.jpg
    read 123488 bytes.
  - reading image file: LOCATION\image65.jpg
    read 123488 bytes.
  - reading image file: LOCATION\image66.jpg
    read 123637 bytes.
  - reading image file: LOCATION\image67.jpg
    read 123637 bytes.
  - reading image file: LOCATION\image68.jpg
    read 123481 bytes.
  - reading image file: LOCATION\image69.jpg
    read 123524 bytes.
  - reading image file: LOCATION\image7.jpg
    read 106612 bytes.
  - reading image file: LOCATION\image70.jpg
    read 123533 bytes.
  - reading image file: LOCATION\image71.jpg
    read 123115 bytes.
  - reading image file: LOCATION\image72.jpg
    read 124844 bytes.
  - reading image file: LOCATION\image73.jpg
    read 121337 bytes.
  - reading image file: LOCATION\image74.jpg
    read 119950 bytes.
  - reading image file: LOCATION\image75.jpg
    read 119528 bytes.
  - reading image file: LOCATION\image76.jpg
    read 119528 bytes.
  - reading image file: LOCATION\image77.jpg
    read 119528 bytes.
  - reading image file: LOCATION\image78.jpg
    read 119528 bytes.
  - reading image file: LOCATION\image79.jpg
    read 126779 bytes.
  - reading image file: LOCATION\image8.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image80.jpg
    read 126479 bytes.
  - reading image file: LOCATION\image81.jpg
    read 124403 bytes.
  - reading image file: LOCATION\image82.jpg
    read 124797 bytes.
  - reading image file: LOCATION\image83.jpg
    read 125287 bytes.
  - reading image file: LOCATION\image84.jpg
    read 125276 bytes.
  - reading image file: LOCATION\image85.jpg
    read 125450 bytes.
  - reading image file: LOCATION\image86.jpg
    read 125178 bytes.
  - reading image file: LOCATION\image87.jpg
    read 131495 bytes.
  - reading image file: LOCATION\image88.jpg
    read 127806 bytes.
  - reading image file: LOCATION\image89.jpg
    read 114765 bytes.
  - reading image file: LOCATION\image9.jpg
    read 118168 bytes.
  - reading image file: LOCATION\image90.jpg
    read 114801 bytes.
  - reading image file: LOCATION\image91.jpg
    read 115281 bytes.
  - reading image file: LOCATION\image92.jpg
    read 115281 bytes.
  - reading image file: LOCATION\image93.jpg
    read 115281 bytes.
  - reading image file: LOCATION\image94.jpg
    read 117940 bytes.
  - reading image file: LOCATION\image95.jpg
    read 116221 bytes.
  - reading image file: LOCATION\image96.jpg
    read 115899 bytes.
  - reading image file: LOCATION\image97.jpg
    read 115899 bytes.
  - reading image file: LOCATION\image98.jpg
    read 115899 bytes.
  - reading image file: LOCATION\image99.jpg
    read 115899 bytes.
Done reading all images.
...done processing.

I can't find the problem and even where to begin with.
What can I do to fix this?
Thanks In advance.

A: Change  this:
 File f = new File(
                  "LOCATION" + count + ".jpg");
                   ImageIO.write(image, "JPEG", f);

To :
 File f = new File(
                  "LOCATION" + String.format("%04d",count) + ".jpg");
                   ImageIO.write(image, "JPEG", f);

That will add extra zeros so LOCATION0009.jpg is before LOCATION0010.jpg unlike LOCATION9.jpg and LOCATION10.jpg. Since they are ordered alphabetically instead of numerically. It looks like 4 digits is enough but for longer movies you might want more digits. Alternatively you could keep the same file names sort the file list with a custom comparitor but it requires slightly more code.


text:
Q: Is it possible to search in the gnome-terminal? Is there something which can be used to search and highlight terms in terminal output? I need to search for "Error" after running make.

A: Go to the search menu. Otherwise:
Shift + Ctrl + F

A: Using grep and its variations
Usually grep is used for plain searching. It would work like this:
make 2&>1 | grep Error

Or if there was a lot of output and you wanted to use a pager:
make 2>&1 | grep Error | less

However, if you want to see all the content, and not just the lines that match your search, you could install the ack-grep package, and then do this:
make 2>&1 | ack-grep --passthru Error

And if that generates a lot of output and you want to use a pager, you need a bit more syntax to preserve the color:
make 2>&1 | ack-grep --passthru Error --color | less -R

In all the examples I included 2>&1 which merges the STDERR and STDOUT output streams. Otherwise, you would only get STDOUT, which might not include all the errors.
One more variation is just to go straight into a pager and search within that:
make 2>&1 | less

One way to search in less is by typing / to enter a search term. See man less for more searching options.
Using terminal menu
Using the Search menu or a keyboard short-cut Shift+Ctrl+F


text:
Q: Why does UICollectionView refresh data after scrolling? UICollectionView refreshes data after scrolling and changes the position of the cells. How can I stop it? I don't want to call cellForItemAtIndexPath on every scrolling?
I don't have too much data.
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

        cell.logo.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",news[indexPath.row]]];

    return cell;
}


text:
Q: ORA-00907 error missing right parenthesis in CREATE TABLE I am getting an error as ORA-00907 (missing right parenthesis) but I think it's a generic error and not related to parentheses.
CREATE TABLE reservation
(
  PNRno int(9) primary key,
  journey_date DATE,
  no_of_seats int(8),
  address varchar2(50),
  contact_no int(10),
  busno varchar2(10) references bus(busno),
  seat_no int(25)
)

What exactly is the underlying error?

A: Specifying a value after INT (e.g. INT(8)) does nothing in MySQL apart from affecting the ZEROFILL option. From here (the poster has ~ 500K rep. on StackOverflow and was MySQL Community Manager, so he probably knows what he's talking about):

The 20 in INT(20) and BIGINT(20) means almost nothing. It's a hint for
display width. It has nothing to do with storage, nor the range of
values that column will accept.

This syntax:
CREATE TABLE bus
(
  busno VARCHAR (10) PRIMARY KEY
);

and:
CREATE TABLE reservation
(
  PNRno        INT PRIMARY KEY,
  journey_date DATE,
  no_of_seats  INT,
  address      VARCHAR (50),
  contact_no   INT,
  busno        VARCHAR (10),
  seat_no      INT,

  CONSTRAINT res_bus_busno_fk FOREIGN KEY (busno) REFERENCES bus (busno)
);

works in both Oracle and MySQL (see the fiddles here and here).
A few points:

*

*please try and tag your questions with the correct RDBMS - some people here only answer questions on a particular server.

*you cannot just copy and paste code from one server to another - SQL has "dialects" which vary from vendor to vendor! There are some standards, but once you depart from these (as with INT(10) for example), you'll rapidly run into problems porting code.

*here is what happens when you put in something like INT(10) into an Oracle table definition which is exactly your error! Oracle's error messages are not the clearest. Check the PostgreSQL fiddle here where the integer with zerofill error is given a line number.
Another case in point, VARCHAR2 (xxx) is an Oracle data type and not a MySQL one. You can see that even MySQL's error messages are better than Oracle's!

*please use the formatting tools for your SQL (be it DDL or DML). Having an entire table definition on one line is not great for readability! You could make your own life much easier by having your table defintions over multiple lines and matching brackets.

*please do not upload images for the reasons outlined in this link.
Anyone reading your question who wanted to Google ORA-00907 would have to type it in manually adding unnecessary work and introducing the possibility of error! There are approx. 15 other factors to consider before posting images given in the link.


text:
Q: 'Deflected Off of' vs 'Deflected off' A question straight from the football commentary pages :

X's shot deflected off of Y before finding its way into the net.

What is the correct usage here ?
Deflected off of or deflected off ??
Or, are both usages correct?

A: "Deflected off" is correct in both AmE and BrE. But British English doesn't use "off of", so "deflected off of" is only correct in American English. Google "deflected off of" and "before finding its way", and you'll see that the pages it returns are nearly all North American hockey and soccer (i.e., football in the rest of the world).

A: Both are correct.  Off and of are both prepositions, but English likes to stack its prepositions where one alone may do.  Thus we get the following:
Either 'I jumped off of the cliff and in to the water' or 'I jumped off the cliff and in the water'.
Either 'I walked out through the door and jumped down from the porch on to the pavement' or 'I walked through the door and jumped from the porch on the pavement'.
Either 'I will be going over to Sally's house at about 8:30' or 'I will be going to Sally's house about 8:30'.
And so on.


text:
Q: Performance improvement: Finite Element Mesh graphics I have created a Finite Elements mesh on GID (quadrilateral 9 nodes elements). I exported the nodes and the elements topology and i'm reading it from the following two text files:
https://www.dropbox.com/s/93b98n139dfep4x/noschapacomfuroleft.txt?dl=0
https://www.dropbox.com/s/nhg8jass0ren6wc/elschapacomfuroleft.txt?dl=0
To read the files above i'm using the following code:
    topol = topol = Transpose@Drop[Transpose@Import["C:\\yourfolder\\elschapacomfuroleft.txt", "Table"], 1];
    nnodesx = Import["C:\\yourfolder\\noschapacomfuroleft.txt", "Table"][[;; , 2]];
    nnodesy = Import["C:\\yourfolder\\noschapacomfuroleft.txt", "Table"][[;; , 3]];
    nnodes = ParallelTable[{nnodesx[[i]], nnodesy[[i]]}, {i, 1,Length[nnodesx]}];

And then the following code plot's the mesh:
allcoords =
  ParallelTable[
   nnodes[[ topol[[i]][[j]] ]], {i, 1, Length[topol]}, {j, 1, 9}];

allcoords2 =
  ParallelTable[
   nnodes[[ topol[[i]][[j]] ]], {i, 1, Length[topol]}, {j, 1, 8}];

nodeids =
  ListPlot[Table[Labeled[nnodes[[i]], i], {i, Length@nnodes}],
   AspectRatio -> Automatic];

ord = FindCurvePath /@ allcoords2 // Flatten[#, 1] &;

allcoordsNEW =
  ParallelTable[allcoords2[[i, ord[[i]]]], {i, 1, Length@ord}];

undefplot =
  ListLinePlot[Tooltip[allcoordsNEW], PlotMarkers -> Automatic,
   AspectRatio -> Automatic, PlotStyle -> {Blue}];

Show[nodeids, undefplot]

Which gives:

The problem is that it takes too long to plot. Is there a way to speedup this code? Is there a beter way to do this? Thank you.
Related paper: https://onlinelibrary.wiley.com/doi/full/10.1002/cae.21958

A: Here is a way to speed things up
pack = Developer`ToPackedArray;
topol = pack @ Transpose @ Drop[Transpose @
      Import["~/Downloads/elschapacomfuroleft.txt", "Table"], 1];
nnodesAll = Import["~/Downloads/noschapacomfuroleft.txt", "Table"];
nnodes = pack@N[nnodesAll[[All, {2, 3}]]];

Now, the idea is to create graphics complexes:
(* edges are straight *)
meshVis1 =
 Graphics[{FaceForm[], EdgeForm[Blue],
   GraphicsComplex[nnodes, Polygon[topol[[All, {1, 2, 3, 4}]]]]}]

Or, if the edges could be curved, then this approximation is fast:
(* approximation to curved edges *)
meshVis2 =
 Graphics[{FaceForm[], EdgeForm[Blue],
   GraphicsComplex[nnodes,
    Polygon[topol[[All, {1, 5, 2, 6, 3, 7, 4, 8}]]]]}]

The nodes are done separately - this is the slowest part
(* this is the slowest part *)
nodeVis =
 Graphics[{MapIndexed[Text[#2[[1]], #1, {-1, 1}] &, nnodes], {Blue,
    Point[nnodes]}}]

You can combine them with Show
Show[meshVis1, nodeVis, ImageSize -> Large]


text:
Q: How to configure RSpec to find specs in alternate folder? Here's my code layout -- it's basically two separate rails apps that are being piece-wise refactored into a common code base:
app1/
  app/
  lib/
  spec/
    models/
    controllers/
    lib/
app2/
  app/
  lib/
  spec/
    models/
    controllers/
    lib/
common/
  lib/
  spec/

Both of the apps get build into docker containers, with the common/ part mounted under the root, so in the runtime env, it looks like this:
root/
  app/
  common/
    lib/
    spec/
  lib/
  spec/
    models/
    controllers/
    lib/

I know I can do rspec common/spec to run the specs in the common/spec folder, but is there a way to configure rspec so that just running rspec will run the specs in both spec/ and common/spec?


text:
Q: 401 error from download.file in for-loop in R I am trying to download a series of raster tiles from the USGS website here. I am using R and hope to accomplish this via a for-loop like below. Note - I am working on a Mac.
tdir = tempdir()

tiles = c("p017r030",
          "p016r030",
          "p017r031",
          "p016r031",
          "p015r030",
          "p014r030",
          "p014r031")

for(k in unique(tiles)){
    tileurl=paste("https://e4ftl01.cr.usgs.gov/MEASURES/GFCC30TC.003/2015.01.01/GFCC30TC_",k,"_TC_2015.zip",sep="")
    download.file(tileurl,destfile = file.path(paste(tdir,"Canopy",k,".zip",sep="")))
    unzip(file.path(paste(tdir,"Canopy",k,".zip",sep=""),exdir=tdir))
    Canopy_tile = paste("Canopy_tile",k,sep="")
    assign(Canopy_tile,terra::rast(paste(tdir,"Canopy",k,".zip",sep="")))}

However, I am left with an error because a USGS log in is required the first time you attempt to access these data. Error shown below. Is there a way to add the log in step into the for-loop, presumably only for the first time through the loop?
#> Warning in download.file(tileurl, destfile = file.path(paste(tdir,
#> "Canopy", : cannot open URL 'https://urs.earthdata.nasa.gov/oauth/authorize?
#> scope=uid&app_type=401&client_id=ijpRZvb9qeKCK5ctsn75Tg&response_type=code&redirect_uri=https%3A%2F%2Fe4ftl01.cr.usgs.gov%2Foauth&state=aHR0cHM6Ly9lNGZ0bDAxLmNyLnVzZ3MuZ292L01FQVNVUkVTL0dGQ0MzMFRDLjAwMy8yMDE1LjAxLjAxL0dGQ0MzMFRDX3AwMTdyMDMwX1RDXzIwMTUuemlw':
#> HTTP status was '401 Unauthorized'
#> Error in download.file(tileurl, destfile = file.path(paste(tdir, "Canopy", : cannot open URL 'https://e4ftl01.cr.usgs.gov/MEASURES/GFCC30TC.003/2015.01.01/GFCC30TC_p017r030_TC_2015.zip'