问:
MVCDonutCaching failing when using custom Redis output cache provider
I have the following custom Redis output cache:

```<code>public class CustomRedisOutputCache : RedisOutputCacheProvider
{
    public override object Add(string key, object entry, DateTime utcExpiry)
    {
        if (!HttpContextHelper.IsPreview())
        {
            return base.Add(key, entry, utcExpiry);
        }

        return entry;
    }

    public override void Set(string key, object entry, DateTime utcExpiry)
    {
        if (!HttpContextHelper.IsPreview())
        {
            base.Set(key, entry, utcExpiry);
        }
    }
}
</code>```

Which is set up in the web.config:

```<code><caching>
  <outputCache enableOutputCache="false" defaultProvider="CustomRedisOutputCache">
    <providers>
      <add name="CustomRedisOutputCache" type="xxx.xxx.Web.Caching.CustomRedisOutputCache" applicationName="xxx.xxx" connectionString="Redis" databaseId="4" throwOnError="false" retryTimeoutInMilliseconds="5000" loggingClassName="" loggingMethodName="" />
    </providers>
  </outputCache>
</code>```

Which all works fine when I use the outputcache attribute:

```<code>[OutputCache(CacheProfile = CacheProfile.Medium, VaryByParam = "*")]
</code>```

However, I'm trying to implement DonutCaching with the MVCDonutCaching Nuget Package and when I change the attribute to

```<code>[DonutOutputCache(CacheProfile = CacheProfile.Medium, VaryByParam = "*")]
</code>```

It is failing with the following error:

Unable to instantiate and initialize OutputCacheProvider of type 'xxx.xxx.Web.Caching.CustomRedisOutputCache'. Make sure you are specifying the full type name.

According to the documentation I should be able to use a custom cache provider, so does anyone know what the problem is?

Looking at the source code, it seems to be failing here:

```<code>            try
            {
                Instance = (OutputCacheProvider)Activator.CreateInstance(Type.GetType(providerSettings.Type));
                Instance.Initialize(providerSettings.Name, providerSettings.Parameters);

            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(
                    string.Format("Unable to instantiate and initialize OutputCacheProvider of type '{0}'. Make sure you are specifying the full type name.", providerSettings.Type),
                    ex
                );
            }
</code>```

Full source for the above class

Update

After downloading and stepping through the source code, it would seem the Type.GetType(providerSettings.Type) is returning null even though providerSettings.Type is xxx.xxx.Web.Caching.CustomRedisOutputCache and that class exists in the executing project xxx.xxx.Web

答: Ok the reason why the getType was returning null is because the nuget package is done in .net4 and the project using it was .net4.6.1 and therefore the nuget package was unable to get the type because the class was incompatible.  As I had the source, I was able to create a custom redis provider in the source solution and just point my project and web config at the updated output

Body:
I have the following custom Redis output cache:

public class CustomRedisOutputCache : RedisOutputCacheProvider
{
    public override object Add(string key, object entry, DateTime utcExpiry)
    {
        if (!HttpContextHelper.IsPreview())
        {
            return base.Add(key, entry, utcExpiry);
        }

        return entry;
    }

    public override void Set(string key, object entry, DateTime utcExpiry)
    {
        if (!HttpContextHelper.IsPreview())
        {
            base.Set(key, entry, utcExpiry);
        }
    }
}

Which is set up in the web.config:

<caching>
  <outputCache enableOutputCache="false" defaultProvider="CustomRedisOutputCache">
    <providers>
      <add name="CustomRedisOutputCache" type="xxx.xxx.Web.Caching.CustomRedisOutputCache" applicationName="xxx.xxx" connectionString="Redis" databaseId="4" throwOnError="false" retryTimeoutInMilliseconds="5000" loggingClassName="" loggingMethodName="" />
    </providers>
  </outputCache>

Which all works fine when I use the outputcache attribute:

[OutputCache(CacheProfile = CacheProfile.Medium, VaryByParam = "*")]

However, I'm trying to implement DonutCaching with the MVCDonutCaching Nuget Package and when I change the attribute to

[DonutOutputCache(CacheProfile = CacheProfile.Medium, VaryByParam = "*")]

It is failing with the following error:

Unable to instantiate and initialize OutputCacheProvider of type 'xxx.xxx.Web.Caching.CustomRedisOutputCache'. Make sure you are specifying the full type name.

According to the documentation I should be able to use a custom cache provider, so does anyone know what the problem is?

Looking at the source code, it seems to be failing here:

            try
            {
                Instance = (OutputCacheProvider)Activator.CreateInstance(Type.GetType(providerSettings.Type));
                Instance.Initialize(providerSettings.Name, providerSettings.Parameters);

            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(
                    string.Format("Unable to instantiate and initialize OutputCacheProvider of type '{0}'. Make sure you are specifying the full type name.", providerSettings.Type),
                    ex
                );
            }

Full source for the above class

Update

After downloading and stepping through the source code, it would seem the Type.GetType(providerSettings.Type) is returning null even though providerSettings.Type is xxx.xxx.Web.Caching.CustomRedisOutputCache and that class exists in the executing project xxx.xxx.Web


来源: stackexchange

问:
How to do a recursive sub-folder search and return files in a list?
I am working on a script to recursively go through subfolders in a mainfolder and build a list off a certain file type. I am having an issue with the script. It's currently set as follows:

```<code>for root, subFolder, files in os.walk(PATH):
    for item in files:
        if item.endswith(".txt") :
            fileNamePath = str(os.path.join(root,subFolder,item))
</code>```

the problem is that the subFolder variable is pulling in a list of subfolders rather than the folder that the ITEM file is located. I was thinking of running a for loop for the subfolder before and join the first part of the path but I figured I'd double check to see if anyone has any suggestions before that.

答:
Recursive is new in Python 3.5, so it won't work on Python 2.7. Here is the example that uses r strings so you just need to provide the path as is on either Win, Lin, ...

```<code>import glob

mypath=r"C:\Users\dj\Desktop\nba"

files = glob.glob(mypath + r'\**\*.py', recursive=True)
# print(files) # as list
for f in files:
    print(f) # nice looking single line per file
</code>```

Note: It will list all files, no matter how deep it should go.

ContentLicense: CC BY-SA 4.0

Body:
I am working on a script to recursively go through subfolders in a mainfolder and build a list off a certain file type. I am having an issue with the script. It's currently set as follows:

for root, subFolder, files in os.walk(PATH):
    for item in files:
        if item.endswith(".txt") :
            fileNamePath = str(os.path.join(root,subFolder,item))

the problem is that the subFolder variable is pulling in a list of subfolders rather than the folder that the ITEM file is located. I was thinking of running a for loop for the subfolder before and join the first part of the path but I figured I'd double check to see if anyone has any suggestions before that.

Body:
Recursive is new in Python 3.5, so it won't work on Python 2.7. Here is the example that uses r strings so you just need to provide the path as is on either Win, Lin, ...

import glob

mypath=r"C:\Users\dj\Desktop\nba"

files = glob.glob(mypath + r'\**\*.py', recursive=True)
# print(files) # as list
for f in files:
    print(f) # nice looking single line per file

Note: It will list all files, no matter how deep it should go.


问:
get android EGL shared context from unity for webrtc
I'm trying to bridge between Unity and WebRTC.

Update: Alright, I created a repo for this, still experiencing weird artifacts with rendering the textures, which I can't figure out
  the reason why. If anyone wants to take a look.

https://github.com/iBicha/WebRTC-for-Unity/

Since WebRTC is capable of providing frames from VideoTracks as a texture, I thought it would be best if it shares the EGL context with unity, so I can render it directly into the engine.

I figured that would be by setting the video hardware acceleration options on the PeerConnectionFactory. as follows:

```<code>    PeerConnectionFactory.initializeAndroidGlobals(mainActivity.getApplicationContext(), true);
    PeerConnectionFactory factory = new PeerConnectionFactory(new PeerConnectionFactory.Options());
    EglBase rootEglBase = EglBase.createEgl14(EGL14.eglGetCurrentContext(), EglBase.CONFIG_PIXEL_RGBA_BUFFER);
    factory.setVideoHwAccelerationOptions(rootEglBase.getEglBaseContext(),rootEglBase.getEglBaseContext());
</code>```

Of course, this is only few assumputions on how it should work.

Since setVideoHwAccelerationOptions takes an EglBase.Contextit means that I need to find the context from Unity and convert it into that.

In order to do that, I found that EglBase.createEgl14 might do the trick, but I need the correct config attributes, which I can't find. Tried few conbinations, but that didn't work.

I'm basically stuck, I do not know where to go from here.

One other option is to get the ByteBuffer from frames, and pass them to Unity, but that's going to be performance hit and a waste of resources, since both Unity and WebRTC speak OpenGL. I feel I'm very close to the answer, but something is missing.

Update: I figured that eglGetCurrentContext() was not returning the context because it was not called from the main Unity thread. Now that I got the context, the textureId of I420Frame frames make sense. But they are not rendering. I think it has to do with the config attributes im passing to EglBase.createEgl14. Or else this might be also a threading thing?

答: I had a similar situation that EGL14.eglGetCurrentContext always returns EGL_NO_CONTEXT.  It turns out to be because Vulkan was used by default.  The solution was also to change Graphics APIs in Player Settings.  Probably not the same as the problem in original post, but writing it down just in case helpful to someone.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to bridge between Unity and WebRTC.

Update: Alright, I created a repo for this, still experiencing weird artifacts with rendering the textures, which I can't figure out
  the reason why. If anyone wants to take a look.

https://github.com/iBicha/WebRTC-for-Unity/

Since WebRTC is capable of providing frames from VideoTracks as a texture, I thought it would be best if it shares the EGL context with unity, so I can render it directly into the engine.

I figured that would be by setting the video hardware acceleration options on the PeerConnectionFactory. as follows:

    PeerConnectionFactory.initializeAndroidGlobals(mainActivity.getApplicationContext(), true);
    PeerConnectionFactory factory = new PeerConnectionFactory(new PeerConnectionFactory.Options());
    EglBase rootEglBase = EglBase.createEgl14(EGL14.eglGetCurrentContext(), EglBase.CONFIG_PIXEL_RGBA_BUFFER);
    factory.setVideoHwAccelerationOptions(rootEglBase.getEglBaseContext(),rootEglBase.getEglBaseContext());

Of course, this is only few assumputions on how it should work.

Since setVideoHwAccelerationOptions takes an EglBase.Contextit means that I need to find the context from Unity and convert it into that.

In order to do that, I found that EglBase.createEgl14 might do the trick, but I need the correct config attributes, which I can't find. Tried few conbinations, but that didn't work.

I'm basically stuck, I do not know where to go from here.

One other option is to get the ByteBuffer from frames, and pass them to Unity, but that's going to be performance hit and a waste of resources, since both Unity and WebRTC speak OpenGL. I feel I'm very close to the answer, but something is missing.

Update: I figured that eglGetCurrentContext() was not returning the context because it was not called from the main Unity thread. Now that I got the context, the textureId of I420Frame frames make sense. But they are not rendering. I think it has to do with the config attributes im passing to EglBase.createEgl14. Or else this might be also a threading thing?


问:
Convert a string made from array toString() back to Array
I converted an array to a string and added it to a TextArea. The user edited the TextArea and I need to now update the array by calling in the same string of data I first produced. How would you do this?

The string which I have produced and need to convert back to an array is:

```<code>{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}
</code>```

I tried to use the JSON Parser JSON.parse(text)

答:
The Below code should work:</p>

```<code>var text_string = '{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}';
console.log(JSON.parse(`[${text_string}]`));
</code>```

Body:
I converted an array to a string and added it to a TextArea. The user edited the TextArea and I need to now update the array by calling in the same string of data I first produced. How would you do this?

The string which I have produced and need to convert back to an array is:

{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}

I tried to use the JSON Parser JSON.parse(text)

Body:
The Below code should work:

var text_string = '{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}';
console.log(JSON.parse(`[${text_string}]`));


问:
The reference constraint is being triggered but unable to select rows from the table that would trigger it
I am attempting to update a bunch of different tables in my database.
However, when the update is completed, I am unable to delete a record from another table due to a foreign key constraint. However, other databases on different servers will accept the change just fine. And upon creating a fresh new db and applying a series of update scripts against it to pre-populate the data, it fails as well.

It should be SQL Server 2016.

I have had a coworker attempt to rebuild indexes and update usages and it still failed.

```<code>--- Query 1
SELECT  ROW_NUMBER() OVER(ORDER BY c.[name], t.[name]),
        SCHEMA_NAME(t.schema_id) AS SchemaName,
        c.[name] AS ColName,
        t.[name] AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE   c.[name] IN (...)
AND     t.[name] NOT IN (...)
ORDER BY ColName, TableName
</code>```

I select out a collection of schema, columns and tables that meet my criteria and generate dynamic SQL for each combination.

```<code>--- Query 2
SET @sql = 'UPDATE ' + @schemaName + '.' + @tableName + ' SET ' + @colName + ' = ' + CONVERT(NVARCHAR, @p1) + ' WHERE ' + @colName + ' = ' + CONVERT(NVARCHAR, @p2)
</code>```

Most/all of the tables returned by query 1 have a FK constraint against another table.
And query 2 seems to execute correctly without issue.

Table definition is as follows:

```<code>CREATE TABLE [Table1](
    [Table1ID] [int] NOT NULL,
    [ColX] [int] NOT NULL,
    [ColY] [int] NOT NULL,
    ...
    [ColZ] [int] NOT NULL,
    ...
) ON [PRIMARY]

ALTER TABLE [Table1] ADD  CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
    [Table1ID] ASC,
    [ColY] ASC,
    [ColZ] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

ALTER TABLE [Table1]  WITH CHECK ADD  CONSTRAINT [FK_Table1_ColY_Table2_ColY] FOREIGN KEY([ColY])
REFERENCES [Table2] ([ColY])

CREATE TABLE [Table2](
    [Table2ID] [int] IDENTITY(1,1) NOT NULL,
    [ColY] [int] NOT NULL,
    [ColZ] [int] NOT NULL,
    ...
) ON [PRIMARY]

ALTER TABLE [Table2] ADD  CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED
(
    [Table2ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

ALTER TABLE [Table2] ADD  CONSTRAINT [UK_Table2_ColY] UNIQUE NONCLUSTERED
(
    [ColY] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
</code>```

My expectation is that when I run the following:

```<code>DELETE  FROM Table2
WHERE   ColY = @p2
</code>```

that I do not trigger FK_Table1_ColY_Table2_ColY.

Especially because:

```<code>SELECT   *
FROM     Table1
WHERE    ColY = @p2
</code>```

returns no records.

The complete error message is as follows:

```<code>Msg 547, Level 16, State 0
The DELETE statement conflicted with the REFERENCE constraint
"FK_Table1_ColY_Table2_ColY". The conflict occurred in database "localhost", table
"dbo.Table1", column 'ColY'.
</code>```

答:
It seems that there was an issue fixed in an update to sql server.

Support Microsoft: Fix referential integrity constraints not being evaluated correctly.

The work around fixes detailed are:

Use a compatibility level below 130.

Modify the referencing table to change the index structure.

Body:
I am attempting to update a bunch of different tables in my database.
However, when the update is completed, I am unable to delete a record from another table due to a foreign key constraint. However, other databases on different servers will accept the change just fine. And upon creating a fresh new db and applying a series of update scripts against it to pre-populate the data, it fails as well.

It should be SQL Server 2016.

I have had a coworker attempt to rebuild indexes and update usages and it still failed.

--- Query 1
SELECT  ROW_NUMBER() OVER(ORDER BY c.[name], t.[name]),
        SCHEMA_NAME(t.schema_id) AS SchemaName,
        c.[name] AS ColName,
        t.[name] AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE   c.[name] IN (...)
AND     t.[name] NOT IN (...)
ORDER BY ColName, TableName

I select out a collection of schema, columns and tables that meet my criteria and generate dynamic SQL for each combination.

--- Query 2
SET @sql = 'UPDATE ' + @schemaName + '.' + @tableName + ' SET ' + @colName + ' = ' + CONVERT(NVARCHAR, @p1) + ' WHERE ' + @colName + ' = ' + CONVERT(NVARCHAR, @p2)

Most/all of the tables returned by query 1 have a FK constraint against another table.
And query 2 seems to execute correctly without issue.

Table definition is as follows:

CREATE TABLE [Table1](
    [Table1ID] [int] NOT NULL,
    [ColX] [int] NOT NULL,
    [ColY] [int] NOT NULL,
    ...
    [ColZ] [int] NOT NULL,
    ...
) ON [PRIMARY]

ALTER TABLE [Table1] ADD  CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
    [Table1ID] ASC,
    [ColY] ASC,
    [ColZ] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

ALTER TABLE [Table1]  WITH CHECK ADD  CONSTRAINT [FK_Table1_ColY_Table2_ColY] FOREIGN KEY([ColY])
REFERENCES [Table2] ([ColY])

CREATE TABLE [Table2](
    [Table2ID] [int] IDENTITY(1,1) NOT NULL,
    [ColY] [int] NOT NULL,
    [ColZ] [int] NOT NULL,
    ...
) ON [PRIMARY]

ALTER TABLE [Table2] ADD  CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED
(
    [Table2ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

ALTER TABLE [Table2] ADD  CONSTRAINT [UK_Table2_ColY] UNIQUE NONCLUSTERED
(
    [ColY] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

My expectation is that when I run the following:

DELETE  FROM Table2
WHERE   ColY = @p2

that I do not trigger FK_Table1_ColY_Table2_ColY.

Especially because:

SELECT   *
FROM     Table1
WHERE    ColY = @p2

returns no records.

The complete error message is as follows:

Msg 547, Level 16, State 0
The DELETE statement conflicted with the REFERENCE constraint
"FK_Table1_ColY_Table2_ColY". The conflict occurred in database "localhost", table
"dbo.Table1", column 'ColY'.


问:
Handling of asynchronous NgRx actions
I have an Angular application, and the main view is split into 2 components. This will be regarding the handling of the dispatching of NgRx actions, in an asynchronous manner.

1) MenuComponent - this contains the various navigation buttons, such as the logout button. Upon clicking the logout button, it call authenticationService.logout(), which sends a http request to the backend, followed by logging out the user. Hence, this is an asynchronous operation.

```<code>public logout() {
  this.authenticationService.logout();
  this.router.navigate(['login']);
}
</code>```

2) DashboardComponent - I have written the following to handle the OnDestroy lifecycle hook, which will be called whenever the component is destroyed. It uses NgRx for state management.

```<code>ngOnDestroy() {
  this.store.dispatch(new UpdateDashboardConfiguration());
  this.store.dispatch(new ClearDashboardState());
}
</code>```

Dispatching of the UpdateDashboardConfiguration() action will result in the application sending a http request to the server to save the dashboard's configurations, therefore it is asynchronous too.

The main question is, when the user decides to logout by clicking the logout button on the MenuComponent, is there a way to ensure that the dispatching of UpdateDashboardConfiguration() will be completed before the dispatching of ClearDashboardState() actions,  as well as authenticationService.logout() from the other MenuComponent are being called?

The preferred flow would be the following:

UpdateDashboardConfiguration => ClearDashboardState => logout()

For those who are wondering, this.store.dispatch(new UpdateDashboardConfiguration()).subscribe(...) will not work as store.dispatch() is of void type, and not an observable.

Thank you in advance.

For those who are interested, this is the Effect for the UpdateDashboardConfiguration action.

```<code>@Effect()
UpdateDashboardConfiguration$ = this.actions$.pipe(
  ofType<UpdateDashboardConfiguration>.(DashboardActionTypes.UpdateDashboardWidget),
  withLatestFrom(this.store.select(selectDashboardLayoutStateConfig)),
  switchMap(action => {
    return this.dashboardService.updateDashboardConfiguration(action).pipe(
      map(data => (new UpdateDashboardConfigurationSuccess(data))),
    );
  }
  ),
);
</code>```

答:
It sounds like you'll need to modify what your logout function is doing. If you have a desired order for your actions to execute in, you shouldn't be letting them run asynchronously.

Since you're using NgRx you should be dispatching a LogoutClicked action rather than calling a service function. This will allow you to control the flow so you can handle everything in the correct order. You can set up an effect that handles LogoutClicked and dispatches the UpdateDashboardConfiguration action. Then when you handle UpdateDashboardConfigurationSuccess you can decide if you need to dispatch a ClearDashboardState action and from there you can finally dispatch a Logout action that calls your logout service function.

You'll probably need to update the payloads contained in your actions to help the effects make decisions about which actions to dispatch next. You can use the Content-Based Decider effect pattern found here.

Title: Handling of asynchronous NgRx actions

Body:
I have an Angular application, and the main view is split into 2 components. This will be regarding the handling of the dispatching of NgRx actions, in an asynchronous manner.

1) MenuComponent - this contains the various navigation buttons, such as the logout button. Upon clicking the logout button, it call authenticationService.logout(), which sends a http request to the backend, followed by logging out the user. Hence, this is an asynchronous operation.

public logout() {
  this.authenticationService.logout();
  this.router.navigate(['login']);
}

2) DashboardComponent - I have written the following to handle the OnDestroy lifecycle hook, which will be called whenever the component is destroyed. It uses NgRx for state management.

ngOnDestroy() {
  this.store.dispatch(new UpdateDashboardConfiguration());
  this.store.dispatch(new ClearDashboardState());
}

Dispatching of the UpdateDashboardConfiguration() action will result in the application sending a http request to the server to save the dashboard's configurations, therefore it is asynchronous too.

The main question is, when the user decides to logout by clicking the logout button on the MenuComponent, is there a way to ensure that the dispatching of UpdateDashboardConfiguration() will be completed before the dispatching of ClearDashboardState() actions,  as well as authenticationService.logout() from the other MenuComponent are being called?

The preferred flow would be the following:

UpdateDashboardConfiguration => ClearDashboardState => logout()

For those who are wondering, this.store.dispatch(new UpdateDashboardConfiguration()).subscribe(...) will not work as store.dispatch() is of void type, and not an observable.

Thank you in advance.

For those who are interested, this is the Effect for the UpdateDashboardConfiguration action.

@Effect()
UpdateDashboardConfiguration$ = this.actions$.pipe(
  ofType<UpdateDashboardConfiguration>.(DashboardActionTypes.UpdateDashboardWidget),
  withLatestFrom(this.store.select(selectDashboardLayoutStateConfig)),
  switchMap(action => {
    return this.dashboardService.updateDashboardConfiguration(action).pipe(
      map(data => (new UpdateDashboardConfigurationSuccess(data))),
    );
  }
  ),
);


问:
Specified file not found '''FileNotFoundError: [Errno 2] No such file or directory''':
I am working on this chatbot called Albert and ran into this problem while i was debugging it and I didn't know how to solve my problem.since I am newbie.

I would be grateful if anyone could help me.

I tried double back slashes for overcoming the unicode error

'''

```<code>if __name__ == '__main__':
    create_table()
    row_counter = 0
    paired_rows = 0

    with open("C:\\Users\\Dell\\Desktop\\Albin Johns\\PROJECT
MATRIX\\Database\\RC_{}".format(timeframe.split('-')[0],timeframe),
buffering=1000) as f:
</code>```

'''

Please do let me know if u require more than the given code to solve this problem

答:
Do not combine everything at one statement like that, please try to split it to some smaller statements. It will help you a lot when you need to trace the problem

Try this:

```<code>fileDir = "C:\\Users\\Dell\\Desktop\\Albin Johns\\PROJECT
MATRIX\\Database\\RC_"

filename = format(timeframe.split('-')[0],timeframe)
#print to make sure filename is correct
print(filename)

filepath = os.path.join(fileDir, 'filename')

with open(filepath, buffering=1000) as f:
</code>```

Body:
I am working on this chatbot called Albert and ran into this problem while i was debugging it and I didn't know how to solve my problem.since I am newbie.

I would be grateful if anyone could help me.

I tried double back slashes for overcoming the unicode error

'''

if __name__ == '__main__':
    create_table()
    row_counter = 0
    paired_rows = 0

    with open("C:\\Users\\Dell\\Desktop\\Albin Johns\\PROJECT
MATRIX\\Database\\RC_{}".format(timeframe.split('-')[0],timeframe),
buffering=1000) as f:

'''

Please do let me know if u require more than the given code to solve this problem

Body:
Do not combine everything at one statement like that, please try to split it to some smaller statements. It will help you a lot when you need to trace the problem

Try this:

fileDir = "C:\\Users\\Dell\\Desktop\\Albin Johns\\PROJECT
MATRIX\\Database\\RC_"

filename = format(timeframe.split('-')[0],timeframe)
#print to make sure filename is correct
print(filename)

filepath = os.path.join(fileDir, 'filename')

with open(filepath, buffering=1000) as f:


问:
How do I remove leading whitespace chars from Ruby HEREDOC?
I'm having a problem with a Ruby heredoc i'm trying to make. It's returning the leading whitespace from each line even though i'm including the - operator, which is supposed to suppress all leading whitespace characters. my method looks like this:

```<code>    def distinct_count
    <<-EOF
        \tSELECT
        \t CAST('#{name}' AS VARCHAR(30)) as COLUMN_NAME
        \t,COUNT(DISTINCT #{name}) AS DISTINCT_COUNT
        \tFROM #{table.call}
    EOF
end
</code>```

and my output looks like this:

```<code>    => "            \tSELECT\n            \t CAST('SRC_ACCT_NUM' AS VARCHAR(30)) as
COLUMN_NAME\n            \t,COUNT(DISTINCT SRC_ACCT_NUM) AS DISTINCT_COUNT\n
        \tFROM UD461.MGMT_REPORT_HNB\n"
</code>```

this, of course, is right in this specific instance, except for all the spaces between the first " and \t.  does anyone know what i'm doing wrong here?

答:
Here's a far simpler version of the unindent script that I use:

```<code>class String
  # Strip leading whitespace from each line that is the same as the
  # amount of whitespace on the first line of the string.
  # Leaves _additional_ indentation on later lines intact.
  def unindent
    gsub /^#{self[/\A[ \t]*/]}/, ''
  end
end
</code>```

Use it like so:

```<code>foo = {
  bar: <<-ENDBAR.unindent
    My multiline
      and indented
        content here
    Yay!
  ENDBAR
}
#=> {:bar=>"My multiline\n  and indented\n    content here\nYay!"}
</code>```

If the first line may be indented more than others, and want (like Rails) to unindent based on the least-indented line, you may instead wish to use:

```<code>class String
  # Strip leading whitespace from each line that is the same as the
  # amount of whitespace on the least-indented line of the string.
  def strip_indent
    if mindent=scan(/^[ \t]+/).min_by(&:length)
      gsub /^#{mindent}/, ''
    end
  end
end
</code>```

Note that if you scan for \s+ instead of [ \t]+ you may end up stripping newlines from your heredoc instead of leading whitespace. Not desirable!

Body:
I'm having a problem with a Ruby heredoc i'm trying to make. It's returning the leading whitespace from each line even though i'm including the - operator, which is supposed to suppress all leading whitespace characters. my method looks like this:

    def distinct_count
    <<-EOF
        \tSELECT
        \t CAST('#{name}' AS VARCHAR(30)) as COLUMN_NAME
        \t,COUNT(DISTINCT #{name}) AS DISTINCT_COUNT
        \tFROM #{table.call}
    EOF
end

and my output looks like this:

    => "            \tSELECT\n            \t CAST('SRC_ACCT_NUM' AS VARCHAR(30)) as
COLUMN_NAME\n            \t,COUNT(DISTINCT SRC_ACCT_NUM) AS DISTINCT_COUNT\n
        \tFROM UD461.MGMT_REPORT_HNB\n"

this, of course, is right in this specific instance, except for all the spaces between the first " and \t.  does anyone know what i'm doing wrong here?

Body:
Here's a far simpler version of the unindent script that I use:

class String
  # Strip leading whitespace from each line that is the same as the
  # amount of whitespace on the first line of the string.
  # Leaves _additional_ indentation on later lines intact.
  def unindent
    gsub /^#{self[/\A[ \t]*/]}/, ''
  end
end

Use it like so:

foo = {
  bar: <<-ENDBAR.unindent
    My multiline
      and indented
        content here
    Yay!
  ENDBAR
}
#=> {:bar=>"My multiline\n  and indented\n    content here\nYay!"}

If the first line may be indented more than others, and want (like Rails) to unindent based on the least-indented line, you may instead wish to use:

class String
  # Strip leading whitespace from each line that is the same as the
  # amount of whitespace on the least-indented line of the string.
  def strip_indent
    if mindent=scan(/^[ \t]+/).min_by(&:length)
      gsub /^#{mindent}/, ''
    end
  end
end

Note that if you scan for \s+ instead of [ \t]+ you may end up stripping newlines from your heredoc instead of leading whitespace. Not desirable!


问:
How to handle seg faults under Windows?
How can a Windows application handle segmentation faults? By 'handle' I mean intercept them and perhaps output a descriptive message. Also, the ability to recover from them would be nice too, but I assume that is too complicated.</p>

答:
Similar to Jean-François Fabre solution, but with Posix code in MinGW-w64.  But note that the program must exit - it can't recover from the SIGSEGV and continue.</p>

```<code>#include <stdio.h>
#include <signal.h>
#include <stdlib.h>

void sigHandler(int s)
{
    printf("signal %d\n", s);
    exit(1);
}

int main()
{
    signal(SIGSEGV, sigHandler);
    int *v=0;
    *v = 0;   // trigger the fault

    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to handle seg faults under Windows?

Body:
Similar to Jean-François Fabre solution, but with Posix code in MinGW-w64.  But note that the program must exit - it can't recover from the SIGSEGV and continue.

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>

void sigHandler(int s)
{
    printf("signal %d\n", s);
    exit(1);
}

int main()
{
    signal(SIGSEGV, sigHandler);
    int *v=0;
    *v = 0;   // trigger the fault

    return 0;
}


问:
Generating SAS for Azure storage access
I have a very basic question on generating SAS Token. As per Azure SDK, http://azure.github.io/azure-storage-android/, we can use generateSharedAccessSignature to generate SAS Token. So, why do we need to use code shown in following pages -- https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token.</p>

答:
Microsoft attempts to provide detailed tutorials and examples for the different integration options.  The first link you provided (http://azure.github.io/azure-storage-android/) is specific to android development.  If that is what you are doing, then that is a great example.  </p>

<p>The examples shown on https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token are focused on the specific tasks.  Within there, they include the common languages; 6 implementation languages in the referenced article.  </p>

Title: Generating SAS for Azure storage access

Body:
Microsoft attempts to provide detailed tutorials and examples for the different integration options.  The first link you provided (http://azure.github.io/azure-storage-android/) is specific to android development.  If that is what you are doing, then that is a great example.

The examples shown on https://learn.microsoft.com/en-us/rest/api/eventhub/generate-sas-token are focused on the specific tasks.  Within there, they include the common languages; 6 implementation languages in the referenced article.


问:
Android program was working, and now it doesnt
I am facing an error on android studio. I have been working on an assignment and for the past week, with everything going according to plan. Today I added some small code and the build executes, however, it force closes the app. I tried running a previous version (which I am SURE that worked) and it's giving me the same error in logcat. The error is:

```<code>2019-05-30 13:10:01.626 28770-28770/? E/Zygote: isWhitelistProcess -
Process is Whitelisted
2019-05-30 13:10:01.629 28770-28770/? E/Zygote: accessInfo : 1
2019-05-30 13:10:02.768 28770-28770/com.example.myapplication
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 28770
    java.lang.RuntimeException: Unable to start activity

ComponentInfo{com.example.myapplication/
com.example.myapplication.fingerprint}:
    android.view.InflateException: Binary XML file line #70: Binary XML
file
    line #70: Error inflating class Button
        at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3115)
        at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3258)
        at

android.app.servertransaction.LaunchActivityItem.execute
(LaunchActivityItem.ja    va:78)
        at

android.app.servertransaction.TransactionExecutor.
executeCallbacks(TransactionExecutor.java:108)
        at
android.app.servertransaction.TransactionExecutor.
execute(TransactionExecutor.java:68)
        at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7073)
        at java.lang.reflect.Method.invoke(Native Method)
        at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller
.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: android.view.InflateException: Binary XML file line #70:
Binary XML file line #70: Error inflating class Button
     Caused by: android.view.InflateException: Binary XML file line #70:
Error inflating class Button
     Caused by: android.content.res.Resources$NotFoundException: Drawable
android:color/tertiary_text_light with resource ID #0x1060011
      Caused by: android.content.res.Resources$NotFoundException: File
res/color/tertiary_text_light.xml from drawable resource ID #0x1060011
        at android.content.res.ResourcesImpl.loadDrawableForCookie
        (ResourcesImpl.java:898)
         at
android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:677)
        at android.content.res.Resources.loadDrawable(Resources.java:912)
        at
android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:955)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:930)
        at android.view.View.<init>(View.java:5442)
        at android.widget.TextView.<init>(TextView.java:1118)
        at android.widget.Button.<init>(Button.java:181)
        at android.widget.Button.<init>(Button.java:156)
        at android.support.v7.widget.AppCompatButton.<init>
        (AppCompatButton.java:71)
        at android.support.v7.widget.AppCompatButton.<init>
        (AppCompatButton.java:67)
        at android.support.v7.app.AppCompatViewInflater.createButton
        (AppCompatViewInflater.java:187)
        at android.support.v7.app.AppCompatViewInflater.createView
        (AppCompatViewInflater.java:110)
        at android.support.v7.app.AppCompatDelegateImpl.createView
        (AppCompatDelegateImpl.java:1266)
        at android.support.v7.app.AppCompatDelegateImpl.onCreateView
        (AppCompatDelegateImpl.java:1316)
        at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:811)
        at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:902)
        at
android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:863)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:554)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:461)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:383)
        at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
    at android.support.v7.app.AppCompatActivity.setContentView
    (AppCompatActivity.java:140)
        at com.example.myapplication.fingerprint.onCreate
        (fingerprint.java:58)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate
        (Instrumentation.java:1275)
        at android.app.ActivityThread.performLaunchActivity
        (ActivityThread.java:3095)
        at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3258)
        at android.app.servertransaction.LaunchActivityItem.execute
        (LaunchActivityItem.java:78)
2019-05-30 13:10:02.773 28770-28770/com.example.myapplication
E/AndroidRuntime:     at
android.app.servertransaction.TransactionExecutor.executeCallbacks
(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute
(TransactionExecutor.java:68)
        at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7073)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
        (RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file
     line #18: <item> tag requires a 'drawable' attribute or child tag
     defining a drawable
        at

     android.graphics.drawable.StateListDrawable.inflateChildElements
    (StateListDrawable.java:190)
     at
    android.graphics.drawable.StateListDrawable.inflate
    (StateListDrawable.java:122)
        at
android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity
(DrawableInflater.java:146)
        at android.graphics.drawable.Drawable.createFromXmlInnerForDensity
(Drawable.java:1359)
        at android.graphics.drawable.Drawable.createFromXmlForDensity
(Drawable.java:1318)
        at android.content.res.ResourcesImpl.loadDrawableForCooki
e(ResourcesImpl.java:879)
</code>```

This is my layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="427dp"
            android:layout_height="wrap_content"
            android:background="@android:color/background_dark"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="169dp"
        android:layout_height="22dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="76dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Enter Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.513"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout" />

    <EditText
        android:id="@+id/eT_name"
        android:layout_width="212dp"
        android:layout_height="37dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.601"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_name" />

    <TextView
        android:id="@+id/txt_surname"
        android:layout_width="169dp"
        android:layout_height="21dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Enter Surname"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_name" />

    <EditText
        android:id="@+id/eT_surname"
        android:layout_width="212dp"
        android:layout_height="37dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.601"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_surname" />

    <Button
        android:id="@+id/btn_loadData"
        android:layout_width="172dp"
        android:layout_height="43dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Load Data"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/eT_surname" />

    <TextView
        android:id="@+id/txt_savedData"
        android:layout_width="219dp"
        android:layout_height="102dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="132dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

答: The problem was that I set the color to a button. Upon changing the color, it worked. I don't know what made it not work though..</p>

Body:
I am facing an error on android studio. I have been working on an assignment and for the past week, with everything going according to plan. Today I added some small code and the build executes, however, it force closes the app. I tried running a previous version (which I am SURE that worked) and it's giving me the same error in logcat. The error is:

2019-05-30 13:10:01.626 28770-28770/? E/Zygote: isWhitelistProcess -
Process is Whitelisted
2019-05-30 13:10:01.629 28770-28770/? E/Zygote: accessInfo : 1
2019-05-30 13:10:02.768 28770-28770/com.example.myapplication
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 28770
    java.lang.RuntimeException: Unable to start activity

ComponentInfo{com.example.myapplication/
com.example.myapplication.fingerprint}:
    android.view.InflateException: Binary XML file line #70: Binary XML
file
    line #70: Error inflating class Button
        at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3115)
        at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3258)
        at

android.app.servertransaction.LaunchActivityItem.execute
(LaunchActivityItem.ja    va:78)
        at

android.app.servertransaction.TransactionExecutor.
executeCallbacks(TransactionExecutor.java:108)
        at
android.app.servertransaction.TransactionExecutor.
execute(TransactionExecutor.java:68)
        at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7073)
        at java.lang.reflect.Method.invoke(Native Method)
        at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller
.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: android.view.InflateException: Binary XML file line #70:
Binary XML file line #70: Error inflating class Button
     Caused by: android.view.InflateException: Binary XML file line #70:
Error inflating class Button
     Caused by: android.content.res.Resources$NotFoundException: Drawable
android:color/tertiary_text_light with resource ID #0x1060011
      Caused by: android.content.res.Resources$NotFoundException: File
res/color/tertiary_text_light.xml from drawable resource ID #0x1060011
        at android.content.res.ResourcesImpl.loadDrawableForCookie
        (ResourcesImpl.java:898)
         at
android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:677)
        at android.content.res.Resources.loadDrawable(Resources.java:912)
        at
android.content.res.TypedArray.getDrawableForDensity(TypedArray.java:955)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:930)
        at android.view.View.<init>(View.java:5442)
        at android.widget.TextView.<init>(TextView.java:1118)
        at android.widget.Button.<init>(Button.java:181)
        at android.widget.Button.<init>(Button.java:156)
        at android.support.v7.widget.AppCompatButton.<init>
        (AppCompatButton.java:71)
        at android.support.v7.widget.AppCompatButton.<init>
        (AppCompatButton.java:67)
        at android.support.v7.app.AppCompatViewInflater.createButton
        (AppCompatViewInflater.java:187)
        at android.support.v7.app.AppCompatViewInflater.createView
        (AppCompatViewInflater.java:110)
        at android.support.v7.app.AppCompatDelegateImpl.createView
        (AppCompatDelegateImpl.java:1266)
        at android.support.v7.app.AppCompatDelegateImpl.onCreateView
        (AppCompatDelegateImpl.java:1316)
        at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:811)
        at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:902)
        at
android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:863)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:554)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:461)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:383)
        at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
    at android.support.v7.app.AppCompatActivity.setContentView
    (AppCompatActivity.java:140)
        at com.example.myapplication.fingerprint.onCreate
        (fingerprint.java:58)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate
        (Instrumentation.java:1275)
        at android.app.ActivityThread.performLaunchActivity
        (ActivityThread.java:3095)
        at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3258)
        at android.app.servertransaction.LaunchActivityItem.execute
        (LaunchActivityItem.java:78)
2019-05-30 13:10:02.773 28770-28770/com.example.myapplication
E/AndroidRuntime:     at
android.app.servertransaction.TransactionExecutor.executeCallbacks
(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute
(TransactionExecutor.java:68)
        at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1955)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7073)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
        (RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)
     Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file
     line #18: <item> tag requires a 'drawable' attribute or child tag
     defining a drawable
        at

     android.graphics.drawable.StateListDrawable.inflateChildElements
    (StateListDrawable.java:190)
     at
    android.graphics.drawable.StateListDrawable.inflate
    (StateListDrawable.java:122)
        at
android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity
(DrawableInflater.java:146)
        at android.graphics.drawable.Drawable.createFromXmlInnerForDensity
(Drawable.java:1359)
        at android.graphics.drawable.Drawable.createFromXmlForDensity
(Drawable.java:1318)
        at android.content.res.ResourcesImpl.loadDrawableForCooki
e(ResourcesImpl.java:879)

This is my layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="427dp"
            android:layout_height="wrap_content"
            android:background="@android:color/background_dark"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="169dp"
        android:layout_height="22dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="76dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Enter Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.513"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout" />

    <EditText
        android:id="@+id/eT_name"
        android:layout_width="212dp"
        android:layout_height="37dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.601"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_name" />

    <TextView
        android:id="@+id/txt_surname"
        android:layout_width="169dp"
        android:layout_height="21dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Enter Surname"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_name" />

    <EditText
        android:id="@+id/eT_surname"
        android:layout_width="212dp"
        android:layout_height="37dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.601"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txt_surname" />

    <Button
        android:id="@+id/btn_loadData"
        android:layout_width="172dp"
        android:layout_height="43dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="64dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="Load Data"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/eT_surname" />

    <TextView
        android:id="@+id/txt_savedData"
        android:layout_width="219dp"
        android:layout_height="102dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="132dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>


问:
Getting MP4 property data in VB.NET
I’d like to know if there’s any possible way i can get the file title or comments as a string in VB.NET. It’s easy to get the file name but the title under details in the actual files properties seems much harder to get. I need to get the entire property title of a MP4 file i give it. Thanks. I do not have much knowledge of VB but I’m hoping someone can help me :)</p>

答:
Use this:

```<code>Dim information = My.Computer.FileSystem.GetFileInfo("C:\myfile.mp4")
</code>```

https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netframework-4.8

To get more information, this could be a possible answer:
Get extended file information details

Title: Getting MP4 property data in VB.NET

Body:
Use this:

Dim information = My.Computer.FileSystem.GetFileInfo("C:\myfile.mp4")

https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netframework-4.8

To get more information, this could be a possible answer:
Get extended file information details


问:
didReceiveRemoteNotification function doesn't called with FCM notification server
I'm using FCM server for remote notifications, it worked perfectly with sending and receiving notifications.

My problem is when the device is in the background, this function func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) doesn't called.

Solutions that I've tried:

This function:

```<code>userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
</code>```

is called when user tapped on the notification. Otherwise, it's not triggered.

Adding "content-available": true, "priority": "high" to the payload. Also, I tried this value "content-available": 1.

This is my function code:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        print("userInfo: \(userInfo)")
      completionHandler(.newData);

    }```

答:
Just adding on accepted answer: in my case the problem was the same, but as I'm sending the Notification through an http "POST" NSMUtableRequest the way to apply the accepted answer was to actually add it in the notification parameters together with sound, badge, tiles etc etc..

```<code>let postParams: [String : Any] = [
                "to": receiverToken,
                "notification": [
                    "badge" : 1,
                    "body": body,
                    "title": title,
                    "subtitle": subtitle,
                    "sound" : true, // or specify audio name to play
                    "content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
                    "priority": "high"
                ],
                "data" : [
                    "data": "ciao",
            ]
                ]
</code>```

Hope this will also help others, as I spent a long time trying to figure out how to apply this solution.
Many thanks.

Body:
I'm using FCM server for remote notifications, it worked perfectly with sending and receiving notifications.

My problem is when the device is in the background, this function func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) doesn't called.

Solutions that I've tried:

This function:

userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)

is called when user tapped on the notification. Otherwise, it's not triggered.

Adding "content-available": true, "priority": "high" to the payload. Also, I tried this value "content-available": 1.

This is my function code:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

        print("userInfo: \(userInfo)")
      completionHandler(.newData);

    }

Body:
Just adding on accepted answer: in my case the problem was the same, but as I'm sending the Notification through an http "POST" NSMUtableRequest the way to apply the accepted answer was to actually add it in the notification parameters together with sound, badge, tiles etc etc..

let postParams: [String : Any] = [
                "to": receiverToken,
                "notification": [
                    "badge" : 1,
                    "body": body,
                    "title": title,
                    "subtitle": subtitle,
                    "sound" : true, // or specify audio name to play
                    "content_available": true, // this will call didReceiveRemoteNotification in receiving app, else won't work
                    "priority": "high"
                ],
                "data" : [
                    "data": "ciao",
            ]
                ]

Hope this will also help others, as I spent a long time trying to figure out how to apply this solution.
Many thanks.


问:
Password verify option to check for false in php
We are using password_verify in php to check if password is correct or not... and commonly used as follows....

```<code>$hash = '$2y$10$SwSqhfgfghdhooyut54quJQ28fQbNY1Q3JdTFnoe.2VxD/D2RXBS';
$password = 'Rf@1P9812JG';

if (password_verify($password, $hash)) {
  echo 'Password is valid!';
 } else {
   echo 'Invalid password.';
 }
</code>```

My question is, can we use it as follows ?

```<code>$hash = '$2y$10$SwSqhfgfghdhooyut54quJQ28fQbNY1Q3JdTFnoe.2VxD/D2RXBS';
$password = 'Rf@1P9812JG';

if (!password_verify($password, $hash)) {
  echo 'Invalid password!';
}
</code>```

I just want to check if password is wrong... and if it is wrong, show error...

答:
Sure you can

If you check PHP's documentation for the password_verify function, you can see it says:

Return Values

Returns TRUE if the password and hash match, or FALSE otherwise.

So (!password_verify($password, $hash)) will indicate that the function returned false, so the verification failed. It is valid to output an error at this point.

Body:
We are using password_verify in php to check if password is correct or not... and commonly used as follows....

$hash = '$2y$10$SwSqhfgfghdhooyut54quJQ28fQbNY1Q3JdTFnoe.2VxD/D2RXBS';
$password = 'Rf@1P9812JG';

if (password_verify($password, $hash)) {
  echo 'Password is valid!';
 } else {
   echo 'Invalid password.';
 }

My question is, can we use it as follows ?

$hash = '$2y$10$SwSqhfgfghdhooyut54quJQ28fQbNY1Q3JdTFnoe.2VxD/D2RXBS';
$password = 'Rf@1P9812JG';

if (!password_verify($password, $hash)) {
  echo 'Invalid password!';
}

I just want to check if password is wrong... and if it is wrong, show error...


问:
MySQL: Select only if field values are ascending
I have two tables: Route and Stop (one to many). And also I have input data: two location IDs which is related to 'stop' table. Every route has it's own ORDERED list of stops. I need to select Route based on the stops order (OLNY where stop.order is ascending) having start and finish locations.

Data example:

```<code>| ROUTE            |
--------------------
| id | name        |
--------------------
| 1 | first        |
--------------------
| 2 | second       |
--------------------

---------------------------
| STOP                    |
---------------------------
|id | order |loc_id|route_id|
----------------------------
| 1 | 1     |  1   |  1   |
---------------------------
| 2 | 2     |  2   |  1   |
---------------------------
| 3 | 3     |  3   |  1   |
---------------------------
| 4 | 3     |  1   |  2   |
---------------------------
| 5 | 2     |  2   |  2   |
---------------------------
| 6 | 1     |  3   |  2   |
---------------------------
</code>```

USE CASE: for example, i have 3 locations: Los Angeles (id=1), Chicago (id=2) and New York (id=3). Also there are 2 bus routes: LA to NY and NY to LA. It means i have 3 bus-stops based on given locations for every route but they have opposite order. So i need to create MySQL query to select appropriate route having start and finish locations.
For example if i have Chicago as starting point and LA as finish, the query have to return to me NY to LA route. If i have Chicago and NY locations - it should get LA to NY route.

That's the query i was able to create but of course it doesn't work

```<code>SELECT `route`.*
FROM `route`
WHERE (SELECT stop.order FROM `stop` WHERE stop.locationId = 1) < (
        SELECT stop.order FROM `stop` WHERE stop.locationId = 2)
</code>```

(where 1 and 2 are location IDs input data)

I need to have this result if i have loc_id 1 and 2

```<code>--------------------
| id | name        |
--------------------
| 1 | first        |
--------------------
</code>```

Therefore, if loc_id = 2 and 1 i need to have next result:

```<code>--------------------
| id | name        |
--------------------
| 2 | second       |
--------------------
</code>```

答:
Try this:</p>

```<code>SELECT R.id, R.name
FROM Stop S
INNER JOIN Route R ON R.id = S.route_id
WHERE
S.loc_id = 1 AND
EXISTS (SELECT Id FROM Stop F WHERE S.route_id = F.route_id AND F.order > S.order AND F.loc_id = 2);
</code>```

Body:
I have two tables: Route and Stop (one to many). And also I have input data: two location IDs which is related to 'stop' table. Every route has it's own ORDERED list of stops. I need to select Route based on the stops order (OLNY where stop.order is ascending) having start and finish locations.

Data example:

| ROUTE            |
--------------------
| id | name        |
--------------------
| 1 | first        |
--------------------
| 2 | second       |
--------------------

---------------------------
| STOP                    |
---------------------------
|id | order |loc_id|route_id|
----------------------------
| 1 | 1     |  1   |  1   |
---------------------------
| 2 | 2     |  2   |  1   |
---------------------------
| 3 | 3     |  3   |  1   |
---------------------------
| 4 | 3     |  1   |  2   |
---------------------------
| 5 | 2     |  2   |  2   |
---------------------------
| 6 | 1     |  3   |  2   |
---------------------------

USE CASE: for example, i have 3 locations: Los Angeles (id=1), Chicago (id=2) and New York (id=3). Also there are 2 bus routes: LA to NY and NY to LA. It means i have 3 bus-stops based on given locations for every route but they have opposite order. So i need to create MySQL query to select appropriate route having start and finish locations.
For example if i have Chicago as starting point and LA as finish, the query have to return to me NY to LA route. If i have Chicago and NY locations - it should get LA to NY route.

That's the query i was able to create but of course it doesn't work

SELECT `route`.*
FROM `route`
WHERE (SELECT stop.order FROM `stop` WHERE stop.locationId = 1) < (
        SELECT stop.order FROM `stop` WHERE stop.locationId = 2)

(where 1 and 2 are location IDs input data)

I need to have this result if i have loc_id 1 and 2

--------------------
| id | name        |
--------------------
| 1 | first        |
--------------------

Therefore, if loc_id = 2 and 1 i need to have next result:

--------------------
| id | name        |
--------------------
| 2 | second       |
--------------------

Body:
Try this:

SELECT R.id, R.name
FROM Stop S
INNER JOIN Route R ON R.id = S.route_id
WHERE
S.loc_id = 1 AND
EXISTS (SELECT Id FROM Stop F WHERE S.route_id = F.route_id AND F.order > S.order AND F.loc_id = 2);


问:
Is there a way to check if an object is a table or a view in SQL Server?
I have a view that I am changing to a table in SQL Server.

I am dropping the view and then the next part of my code I am establishing the table.

My code works the first time I run it (when the object is a view), but when I need to run it multiple times, I get this error:

Cannot use DROP VIEW with 'engineer.Well' because 'engineer.Well' is a table. Use DROP TABLE.

I've been looking online but cannot find a way to check if an object is a table or a view, and the subsequently drop the object.

Any advice would be greatly appreciated.

Right now it looks like this,

```<code>IF OBJECT_ID('engineer.well') IS NOT NULL
BEGIN
    DROP TABLE [engineer].[Well]
    PRINT '<<< DROPPED TABLE Vendor >>>'
END
</code>```

I am playing around with a way to check if the object is a table and then drop it, or check if it is a view then drop it.

答:
OBJECTPROPERTY(OBJECT_ID('name'), 'IsView')
https://learn.microsoft.com/en-us/sql/t-sql/functions/objectproperty-transact-sql?view=sql-server-2017
or
SELECT id, type FROM sysobjects where id=OBJECT_ID('objectName')</p>

Body:
I have a view that I am changing to a table in SQL Server.

I am dropping the view and then the next part of my code I am establishing the table.

My code works the first time I run it (when the object is a view), but when I need to run it multiple times, I get this error:

Cannot use DROP VIEW with 'engineer.Well' because 'engineer.Well' is a table. Use DROP TABLE.

I've been looking online but cannot find a way to check if an object is a table or a view, and the subsequently drop the object.

Any advice would be greatly appreciated.

Right now it looks like this,

IF OBJECT_ID('engineer.well') IS NOT NULL
BEGIN
    DROP TABLE [engineer].[Well]
    PRINT '<<< DROPPED TABLE Vendor >>>'
END

I am playing around with a way to check if the object is a table and then drop it, or check if it is a view then drop it.


答:
You can query sys.objects table:</p>

```<code>select type_desc, * from sys.objects where object_id = object_id('[dbo].[DimDates]')
</code>```

Title: Is there a way to check if an object is a table or a view in SQL Server?

Body:
You can query sys.objects table:

select type_desc, * from sys.objects where object_id = object_id('[dbo].[DimDates]')


问:
Problem with stopping Python window from closing
This is a small and very basic program/game. I am having trouble with the unexpected close of the Python terminal before the end of the code. But within the PyCharm IDE, when I run the code, the program runs fine and only ends when all of the code is executed and the input has been entered from the user. I don't know if it's because of the logic behind my programming, I am still very new at this and so I am aware that might be the problem.

I have tried using an input to prevent the window from closing.

input("\nPress any key to exit... ")

Like I have previously said, that seems to work in the IDE but not when running the program directly from the .py file

I do not want to pass by CMD or a batch file to run the program. I want the users to be able to run the game by simply pressing on the Pycharm file and running it trough it's respective console.

Here is the code :

```<code>import random
inputCounter = 0
lineNumber = 0
playerNumber = 0
randomNumber = random.randint(1, 100)
win = 0
playerName = input("Please enter your name: ")

while playerNumber is not randomNumber:
    playerNumber = int(input("Please guess a whole number from 1 to 100: "))
    inputCounter += 1
    if playerNumber < randomNumber:
        print("The number you have entered is LOWER than the generated number, please try again!")
        continue
    elif playerNumber > randomNumber:
        print("The number you have entered is HIGHER than the generated number, please try again!")
print()

if inputCounter > 1:
    print("You won with {0} guesses".format(inputCounter))
else:
    print("CONGRATS! You won with 1 guess!!")

scoreList = open("Score.txt", "a",)
scoreList.write("Player: {0} | Guesses: {1}\n".format(playerName, inputCounter,))
scoreList = open("Score.txt", "r")
print("\nHere is your score list :")
for line in scoreList:
    line = line.strip()
    find = line.find(playerName)
    if find >0:
        lineNumber += 1
        score = line[line.rfind(" ")+1:]
        print("Attempt #{0} | Score: {1}".format(lineNumber, score))
input("\nPress any key to exit... ")

scoreList.close()
</code>```

PyCharm IDE runs the program until the ends (Print's the number of attempts and the player's scoreboard and then waits for the user's input to exit).
This is what I want to happen when running the app through Python's console.

EDIT :
This is also the case if I run the program through CMD via a batch file, I would still like to avoid that if possible

As of now, Python's console closes as soon as the user guesses the corrects number, not waiting for the user's input to exit. I am guessing that the program does still print the number of attempts and the player's scoreboard but the console closes way too quickly for the user to see those lines.

答:
Ok, so I added a try-except block around the entire score reading code, and I managed to grab an error. However, I think that might be specific to my own Python 3 installation, so you should use the same approach and see what your problem might be.

In my case, Python 2 is installed in C:\ while Python 3 is in (for some reason) C:\Users\username\AppData\Local\Programs\Python\Python36. When I run your code, it used to open using Python2 by default and that worked fine. It created and read from Scores.txt as expected.

When I manually made it use Python3 though, it always crashed with [Errno 13] Permission denied: 'Score.txt', which is a permissions issue. You probably see why I think this is due to my install location now.

Anyway, you can use the code below to hopefully print the error message. Once you have that, it should be easy to fix whatever the bug may be. The rest of the code (including the input call after this) should remain the same.

```<code>try:
    scoreList = open("Score.txt", "a",)
    scoreList.write("Player: {0} | Guesses: {1}\n".format(playerName, inputCounter,))
    scoreList = open("Score.txt", "r")
    print("\nHere is your score list :")
    for line in scoreList:
        line = line.strip()
        find = line.find(playerName)
        if find >0:
            lineNumber += 1
            score = line[line.rfind(" ")+1:]
            print("Attempt #{0} | Score: {1}".format(lineNumber, score))
except Exception as e:
    print(e)
</code>```

Body:
This is a small and very basic program/game. I am having trouble with the unexpected close of the Python terminal before the end of the code. But within the PyCharm IDE, when I run the code, the program runs fine and only ends when all of the code is executed and the input has been entered from the user. I don't know if it's because of the logic behind my programming, I am still very new at this and so I am aware that might be the problem.

I have tried using an input to prevent the window from closing.

input("\nPress any key to exit... ")

Like I have previously said, that seems to work in the IDE but not when running the program directly from the .py file

I do not want to pass by CMD or a batch file to run the program. I want the users to be able to run the game by simply pressing on the Pycharm file and running it trough it's respective console.

Here is the code :

import random
inputCounter = 0
lineNumber = 0
playerNumber = 0
randomNumber = random.randint(1, 100)
win = 0
playerName = input("Please enter your name: ")

while playerNumber is not randomNumber:
    playerNumber = int(input("Please guess a whole number from 1 to 100: "))
    inputCounter += 1
    if playerNumber < randomNumber:
        print("The number you have entered is LOWER than the generated number, please try again!")
        continue
    elif playerNumber > randomNumber:
        print("The number you have entered is HIGHER than the generated number, please try again!")
print()

if inputCounter > 1:
    print("You won with {0} guesses".format(inputCounter))
else:
    print("CONGRATS! You won with 1 guess!!")

scoreList = open("Score.txt", "a",)
scoreList.write("Player: {0} | Guesses: {1}\n".format(playerName, inputCounter,))
scoreList = open("Score.txt", "r")
print("\nHere is your score list :")
for line in scoreList:
    line = line.strip()
    find = line.find(playerName)
    if find >0:
        lineNumber += 1
        score = line[line.rfind(" ")+1:]
        print("Attempt #{0} | Score: {1}".format(lineNumber, score))
input("\nPress any key to exit... ")

scoreList.close()

PyCharm IDE runs the program until the ends (Print's the number of attempts and the player's scoreboard and then waits for the user's input to exit).
This is what I want to happen when running the app through Python's console.

EDIT :
This is also the case if I run the program through CMD via a batch file, I would still like to avoid that if possible

As of now, Python's console closes as soon as the user guesses the corrects number, not waiting for the user's input to exit. I am guessing that the program does still print the number of attempts and the player's scoreboard but the console closes way too quickly for the user to see those lines.

Body:
Ok, so I added a try-except block around the entire score reading code, and I managed to grab an error. However, I think that might be specific to my own Python 3 installation, so you should use the same approach and see what your problem might be.

In my case, Python 2 is installed in C:\ while Python 3 is in (for some reason) C:\Users\username\AppData\Local\Programs\Python\Python36. When I run your code, it used to open using Python2 by default and that worked fine. It created and read from Scores.txt as expected.

When I manually made it use Python3 though, it always crashed with [Errno 13] Permission denied: 'Score.txt', which is a permissions issue. You probably see why I think this is due to my install location now.

Anyway, you can use the code below to hopefully print the error message. Once you have that, it should be easy to fix whatever the bug may be. The rest of the code (including the input call after this) should remain the same.

try:
    scoreList = open("Score.txt", "a",)
    scoreList.write("Player: {0} | Guesses: {1}\n".format(playerName, inputCounter,))
    scoreList = open("Score.txt", "r")
    print("\nHere is your score list :")
    for line in scoreList:
        line = line.strip()
        find = line.find(playerName)
        if find >0:
            lineNumber += 1
            score = line[line.rfind(" ")+1:]
            print("Attempt #{0} | Score: {1}".format(lineNumber, score))
except Exception as e:
    print(e)


问:
How to convert a number read from a file from str to int?
I use bash, I have to read a file that contains many lines

Each line is composed by a single number. Then, for each line (number) I have to check if value > 80.

And here's my problem, no matter what I try, I always get:

```<code>>integer expression expected
</code>```

after the if condition. That's because the variable I use to put the value of the line is a string.

Here's my original file

```<code>[root@michelep_centos2 ~]# cat temp1

0

0

0

98

0

0

79

0

81
</code>```

In the bash script I have

```<code>##!/bin/bash

file=/root/temp1

while IFS= read -r line

do

        if [ 'expr $line /1' -gt 80 ]

        then echo "hit>80"

        fi

done <"$file"
</code>```

And here expr returns error as $line is a string. I have tried using another variable

```<code>val=$(($line + 0))

if [ $val -gt 80 ]
</code>```

Here the if condition returns "integer expression expected"

I have used also echo

```<code>val=$(echo "$((line /1))")

if [ $val -gt 80 ]
</code>```

I get

syntax error: invalid arithmetic operator (error token is ...

from echo command and of course again the if condition returns

integer expression expected

答:
First action: dos2unix -f inputfile

Second action:

From the input file it can be observed that it contains blank lines, and this will cause if comparison to fail.  You can put an additional check on top of your -gt 80 check to ensure before passing the variable $line its not empty using if [ ! -z $line ] or better you can put a check to ensure the line is an integer or may be both using AND.

Example:

```<code>while read line;
do
  if [[ $line =~ ^[0-9]+$ ]];then
      if [ $line -gt 80 ];then
          echo "$line is greater then 80"
      fi
  fi
done <input_file
</code>```

Or , if you do not want to put empty check([ ! -z $line ]) ,

Also, this can be done using other tools like awk in one line, but this may or may not fit in your requirement.

```<code>awk 'NF && $0>80{print $0 ,"is greater then 80"}' inputfile
</code>```

Body:
I use bash, I have to read a file that contains many lines

Each line is composed by a single number. Then, for each line (number) I have to check if value > 80.

And here's my problem, no matter what I try, I always get:

>integer expression expected

after the if condition. That's because the variable I use to put the value of the line is a string.

Here's my original file

[root@michelep_centos2 ~]# cat temp1

0

0

0

98

0

0

79

0

81

In the bash script I have

##!/bin/bash

file=/root/temp1

while IFS= read -r line

do

        if [ 'expr $line /1' -gt 80 ]

        then echo "hit>80"

        fi

done <"$file"

And here expr returns error as $line is a string. I have tried using another variable

val=$(($line + 0))

if [ $val -gt 80 ]

Here the if condition returns "integer expression expected"

I have used also echo

val=$(echo "$((line /1))")

if [ $val -gt 80 ]

I get

syntax error: invalid arithmetic operator (error token is ...

from echo command and of course again the if condition returns

integer expression expected

Body:
First action: dos2unix -f inputfile

Second action:

From the input file it can be observed that it contains blank lines, and this will cause if comparison to fail.  You can put an additional check on top of your -gt 80 check to ensure before passing the variable $line its not empty using if [ ! -z $line ] or better you can put a check to ensure the line is an integer or may be both using AND.

Example:

while read line;
do
  if [[ $line =~ ^[0-9]+$ ]];then
      if [ $line -gt 80 ];then
          echo "$line is greater then 80"
      fi
  fi
done <input_file

Or , if you do not want to put empty check([ ! -z $line ]) ,

Also, this can be done using other tools like awk in one line, but this may or may not fit in your requirement.

awk 'NF && $0>80{print $0 ,"is greater then 80"}' inputfile


问:
Boot process "scheduler"
Where in the boot process does the "scheduler"  get created and when created how can its instructions be accessed?</p>

答:
the default scheduler is set in kernel config :
adrian@adrian: ~ $ grep cfq /boot/config-2.6.36.2-desktop-2mnb
CONFIG_DEFAULT_IOSCHED="cfq"

at boot time you can do in the kernel line as example:
kernel /vmlinuz-2.6.18-8.el5 ro root=/dev/sda2 elevator=deadline

Title: Boot process "scheduler"


问:
How can I count the number of devices connected via bluetooth?
I want to connect 4 devices via Bluetooth in my app and after 4 devices are connected I want to stop any more devices to get connected.To do this I need to know the number of connected devices.

How can I find the number of connected devices programmatically?

答:
getBondedDevices() returns a set of currently paired devices
   you can get the number of connected devices from its size()

```<code>Set<BluetoothDevice> devices =  bluetoothAdapter.getBondedDevices();
//deviceS.size()
</code>```

Body:
getBondedDevices() returns a set of currently paired devices
   you can get the number of connected devices from its size()

Set<BluetoothDevice> devices =  bluetoothAdapter.getBondedDevices();
//deviceS.size()


问:
How can I call geoLocation in componentDidMount in React
So I was trying to use axios to pull up an api along with HTML5Geolocation.

I place it inside the componentDidMount and was expecting it to work atleast console.log the result using async and eventually set the state to the country.

```<code>componentDidMount(){
    async onLoad() {
        if (window.navigator.geolocation) {
           window.navigator.geolocation.getCurrentPosition(
           position => {
              const response = axios.get('http://ws.geonames.org/countryCode' , {
                   lat: position.coords.latitude,
                   lng: position.coords.longitude,
                   type: 'JSON'
               });
               console.log('here is the response >>>>', response.countryName);
               this.setState({ country: response.countryName })
           });

           }
         }

}
</code>```

However this is currently not working. I am using Geonames for my API

Any idea what am I doing wrong on my code?

答:
As stated by @Shridhar Sharma remove the onLoad.

You're missing the await in your code. Without it the await expression, the execution of the async function wont wait for the Promise resolution.

One more thing to keep in mind, even if the browser supports geolocation there could be other errors such as PERMISSION_DENIED, POSITION_UNAVAILABLE and TIMEOUT. See more

https://developer.mozilla.org/en-US/docs/Web/API/PositionError/code

```<code>componentDidMount() {
        if (window.navigator.geolocation) {
            window.navigator.geolocation.getCurrentPosition( async (position) => {
                const response = await axios.get("http://ws.geonames.org/countryCode", {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                    type: "JSON"
                });
                console.log("here is the response >>>>", response.countryName);
                this.setState({ country: response.countryName });

            }, (e) => {
                // other errors appear here
                console.log(e);
            });
        } else {
            console.log("navigator not supported");
        }
    }
</code>```

Body:
So I was trying to use axios to pull up an api along with HTML5Geolocation.

I place it inside the componentDidMount and was expecting it to work atleast console.log the result using async and eventually set the state to the country.

componentDidMount(){
    async onLoad() {
        if (window.navigator.geolocation) {
           window.navigator.geolocation.getCurrentPosition(
           position => {
              const response = axios.get('http://ws.geonames.org/countryCode' , {
                   lat: position.coords.latitude,
                   lng: position.coords.longitude,
                   type: 'JSON'
               });
               console.log('here is the response >>>>', response.countryName);
               this.setState({ country: response.countryName })
           });

           }
         }

}

However this is currently not working. I am using Geonames for my API

Any idea what am I doing wrong on my code?

Body:
As stated by @Shridhar Sharma remove the onLoad.

You're missing the await in your code. Without it the await expression, the execution of the async function wont wait for the Promise resolution.

One more thing to keep in mind, even if the browser supports geolocation there could be other errors such as PERMISSION_DENIED, POSITION_UNAVAILABLE and TIMEOUT. See more

https://developer.mozilla.org/en-US/docs/Web/API/PositionError/code

componentDidMount() {
        if (window.navigator.geolocation) {
            window.navigator.geolocation.getCurrentPosition( async (position) => {
                const response = await axios.get("http://ws.geonames.org/countryCode", {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                    type: "JSON"
                });
                console.log("here is the response >>>>", response.countryName);
                this.setState({ country: response.countryName });

            }, (e) => {
                // other errors appear here
                console.log(e);
            });
        } else {
            console.log("navigator not supported");
        }
    }


答:
You can query the system views.</p>

```<code>DECLARE @Type varchar(2)
SELECT @Type = type
FROM sys.objects o
JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE o.name = 'well'
AND s.name = 'engineer'

IF  @Type = 'U'
BEGIN
    DROP TABLE [engineer].[Well]
    PRINT '<<< DROPPED TABLE Vendor >>>'
END

IF  @Type = 'V'
BEGIN
    DROP VIEW [engineer].[Well]
    PRINT '<<< DROPPED VIEW Vendor >>>'
END
</code>```

Body:
You can query the system views.

DECLARE @Type varchar(2)
SELECT @Type = type
FROM sys.objects o
JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE o.name = 'well'
AND s.name = 'engineer'

IF  @Type = 'U'
BEGIN
    DROP TABLE [engineer].[Well]
    PRINT '<<< DROPPED TABLE Vendor >>>'
END

IF  @Type = 'V'
BEGIN
    DROP VIEW [engineer].[Well]
    PRINT '<<< DROPPED VIEW Vendor >>>'
END


问:
Cutting a database down to size
Say you have a database that has served a company for 10 years. It is 500GB in size, it has myriad tables, stored procedures and triggers.

Now say you wish to create a cut down version of the database to use as a test bed for use in integration testing and for individual testers and developers to spin up instances of to play around with.

In broad terms how would you set about this task?

In case it matters, the database I have in mind is SQL Server 2008.

Edit: removed "unit testing" because of course unit tests should not test db integration

答:
I would script the database including tables, indexes, triggers, and stored procedures. Then create a new empty database with this script. Now you can add data to the database as needed for your integration tests.

You can use tools like http://code.google.com/p/ndbunit/ to load data for the tests that way the data is part of the test and will be removed once the test finishes. Also I would run the tests in SQL Express on the developers local computer this way tests don't fail if multiple developers are running them at the same time.

Title: Cutting a database down to size


问:
VBA, For Each Loop, incrementing offset by 1 column
I have a for each loop, how can I incrementally increase my cells output by one column? Currently this just writes to one cell in output.</p>

```<code>Sub quarterly()

Dim result As String

rev = Sheets("fin").Range("B105:F105")

For Each x In rev:

    result = Replace(x, "M", "")
    Sheets("output").Cells(2, 2) = result

Next

End Sub
</code>```

答:
if your "target" range is empty then you could use End(xlToLeft) and step one cell right at any cell writing :

```<code>Sub quarterly()
    Dim x, rev

    rev = Sheets("fin").Range("B105:F105").Value
    With Sheets("output")
        For Each x In rev
            .Cells(2, .Columns.Count).End(xlToLeft).Offset(, 1) = Replace(x, "M", "")
        Next
    End With
End Sub
</code>```

Body:
I have a for each loop, how can I incrementally increase my cells output by one column? Currently this just writes to one cell in output.

Sub quarterly()

Dim result As String

rev = Sheets("fin").Range("B105:F105")

For Each x In rev:

    result = Replace(x, "M", "")
    Sheets("output").Cells(2, 2) = result

Next

End Sub

Body:
if your "target" range is empty then you could use End(xlToLeft) and step one cell right at any cell writing :

Sub quarterly()
    Dim x, rev

    rev = Sheets("fin").Range("B105:F105").Value
    With Sheets("output")
        For Each x In rev
            .Cells(2, .Columns.Count).End(xlToLeft).Offset(, 1) = Replace(x, "M", "")
        Next
    End With
End Sub


问:
Optimising Matrix Calculation in C
I'm trying to find the most efficient method for multiplying a Matrix by its transpose. Any ideas on the most efficient mathematical formula?</p>

答:
The posted code gives the correct answer, a matrix B which is the product of another matrix A by its transposed, but both matrices are stored in a couple of arrays in column-major order (or at least, that's what what the OP states in the comments).

Considering this snippet:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
            B[i + n * j] = B[i + n * j] + A[i + n * k] * A[j + n * k];
        //                                  ^^^^^^^^^      ^^^^^^^^^
        }
    }
}
```

<p>We can notice that the inner loop traverses those arrays skipping <code>n</code> elements every time and that's not cache-friendly.</p>

<p>If we arrange the order of the loops so that the inner one iterates over contiguous elements, we could have a performance gain:</p>

<pre class="lang-cpp prettyprint-override"><code>// Calculate the matrix B = A times A transposed. A is an n x n matrix.
// A and B are stored in plain arrays ('src' and 'dest') in column-major order
void mult_AAT(size_t n, value_t const *src, value_t *dest)
{
    for (size_t i = 0, end = n * n; i < end; i++)
    {
        dest[i] = 0;
    }
    for (size_t k = 0; k < n; k++)         // <--
    {
        for (size_t j = 0; j < n; j++)     // <-
        {
            for (size_t i = 0; i < n; i++)
            {
                dest[j * n + i] += src[k * n + i] * src[k * n + j];
                //   ^^^^^^^^^         ^^^^^^^^^        ^^^^^^^^^
            }
        }
    }
}
</code>```

Live HERE.

Title: Optimising Matrix Calculation in C

Body:
The posted code gives the correct answer, a matrix B which is the product of another matrix A by its transposed, but both matrices are stored in a couple of arrays in column-major order (or at least, that's what what the OP states in the comments).

Considering this snippet:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
            B[i + n * j] = B[i + n * j] + A[i + n * k] * A[j + n * k];
        //                                  ^^^^^^^^^      ^^^^^^^^^
        }
    }
}

We can notice that the inner loop traverses those arrays skipping n elements every time and that's not cache-friendly.

If we arrange the order of the loops so that the inner one iterates over contiguous elements, we could have a performance gain:

// Calculate the matrix B = A times A transposed. A is an n x n matrix.
// A and B are stored in plain arrays ('src' and 'dest') in column-major order
void mult_AAT(size_t n, value_t const *src, value_t *dest)
{
    for (size_t i = 0, end = n * n; i < end; i++)
    {
        dest[i] = 0;
    }
    for (size_t k = 0; k < n; k++)         // <--
    {
        for (size_t j = 0; j < n; j++)     // <-
        {
            for (size_t i = 0; i < n; i++)
            {
                dest[j * n + i] += src[k * n + i] * src[k * n + j];
                //   ^^^^^^^^^         ^^^^^^^^^        ^^^^^^^^^
            }
        }
    }
}

Live HERE.


问:
Is there anyway to reset multi index in pandas?
I want to obtain stock data using pandas_datareader. I have the data, but the index I got is multiIndex.
_data.columns

```<code>MultiIndex(levels=[['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close'], ['MSFT']],
           codes=[[0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0]],
           names=['Attributes', 'Symbols'])

from pandas_datareader import data as pdr
import yfinance
_data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')
</code>```

The format I want to get is single index.So that i can use that data to plot

```<code>    symbol  date            price
0   MSFT    2000-01-01  39.81
1   MSFT    2000-02-01  36.35
2   MSFT    2000-03-01  43.22
3   MSFT    2000-04-01  28.37
4   MSFT    2000-05-01  25.45
</code>```

答:
You need to use multiindex droplevel
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.droplevel.html</p>

Body:
I want to obtain stock data using pandas_datareader. I have the data, but the index I got is multiIndex.
_data.columns

MultiIndex(levels=[['High', 'Low', 'Open', 'Close', 'Volume', 'Adj Close'], ['MSFT']],
           codes=[[0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0]],
           names=['Attributes', 'Symbols'])

from pandas_datareader import data as pdr
import yfinance
_data = pdr.get_data_yahoo(['MSFT'], start='2019-01-01', end='2019-05-30')

The format I want to get is single index.So that i can use that data to plot

    symbol  date            price
0   MSFT    2000-01-01  39.81
1   MSFT    2000-02-01  36.35
2   MSFT    2000-03-01  43.22
3   MSFT    2000-04-01  28.37
4   MSFT    2000-05-01  25.45