问:
Couldn't add the Keychain Item. Error - 25299 after change the identifier with KeychainItemWrapper?
I wanna save UUID in keychain with KeychainItemWrapper, so I add the following methods in MyKeychainManager.m :

```<code>#define keychain_idenentify @"com.myapp.bundle1"

+ (void)saveUUID:(NSString *)UUID{
  if([MyKeychainManager getUUID].length > 0) {
    return;
  }
  KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc]initWithIdentifier:keychain_idenentify accessGroup:nil];
  [keychain setObject:UUID forKey:(__bridge id)kSecAttrLabel];
}

+ (NSString *)getUUID {
  KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc]initWithIdentifier:keychain_idenentify accessGroup:nil];

  NSString *uuidString = [keychain objectForKey:(__bridge id)kSecAttrLabel];
  return uuidString;
}
</code>```

But after I change the keychain_idenentify to com.otherApp.bundle, it crashed at

result = SecItemAdd((CFDictionaryRef)[self
  dictionaryToSecItemFormat:keychainItemData], NULL);       NSAssert( result
  == noErr, @"Couldn't add the Keychain Item." );

and the error is Error - 25299

Why is this and how to solve this? Which I should choose such as kSecAttrLabel? I changed it to kSecAttrService it works fun but I don't know is there any other potential bugs.

Any help will be appreciate.

答:
I've spent a lot of days in struggling the same problem. At last , I'v found the cause of it that I pass by too easily.

That is an important constant of keychain. Take a look at the codes.
(Assuming that I used keychain in my target for the first time)

```<code>KeychainItemWrapper *test1 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test10"  accessGroup:nil];
[test1 setObject:(id)@"value1" forKey:(id)kSecValueData];
//Normally it works

KeychainItemWrapper *test2 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test20"  accessGroup:nil];
//At this point , we meet the crash with the message of 'Couldn't add the Keychain Item.'
[test2 setObject:(id)@"value2" forKey:(id)kSecValueData];
</code>```

Even if the name of 'initWithIdentifier' is different , the constant 'kSecAttrAccount' must be unique.
Its default value is ""( that is empty). Once keychain wrapper is used , the 'kSecAttrAccount' of it is saved . So you need to pay much attention to the 'kSecAttrAccount' when you use the another 'initWithIdentifier'.

I can fix the crash of above codes by adding some codes.

```<code>    KeychainItemWrapper *test1 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test10"  accessGroup:nil];
[test1 setObject:@"test1" forKey:(id)kSecAttrAccount];
[test1 setObject:(id)@"value1" forKey:(id)kSecValueData];

KeychainItemWrapper *test2 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test20"  accessGroup:nil];
[test2 setObject:@"test2" forKey:(id)kSecAttrAccount];
[test2 setObject:(id)@"value2" forKey:(id)kSecValueData];
</code>```

For more information, if you use the accessGroup of KeychainItemWrapper,
as I mention above , the kSecAttrAccount must be unique regardless of using accessGroup or not.

The following is an example.

```<code>KeychainItemWrapper *test = [[KeychainItemWrapper alloc] initWithIdentifier:@"test"  accessGroup:"App_ID.SampleName"];
</code>```

As you know , App_ID should be created at the apple developer and SampleName should be setup at the capabilities of KeyChain Sharing of your app target.
The '.' between App_ID and SampleName must be added. This is a key point.

Please refer to the postings the other persons uploaded about how to set it.

Body:
I wanna save UUID in keychain with KeychainItemWrapper, so I add the following methods in MyKeychainManager.m :

#define keychain_idenentify @"com.myapp.bundle1"

+ (void)saveUUID:(NSString *)UUID{
  if([MyKeychainManager getUUID].length > 0) {
    return;
  }
  KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc]initWithIdentifier:keychain_idenentify accessGroup:nil];
  [keychain setObject:UUID forKey:(__bridge id)kSecAttrLabel];
}

+ (NSString *)getUUID {
  KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc]initWithIdentifier:keychain_idenentify accessGroup:nil];

  NSString *uuidString = [keychain objectForKey:(__bridge id)kSecAttrLabel];
  return uuidString;
}

But after I change the keychain_idenentify to com.otherApp.bundle, it crashed at

result = SecItemAdd((CFDictionaryRef)[self
  dictionaryToSecItemFormat:keychainItemData], NULL);       NSAssert( result
  == noErr, @"Couldn't add the Keychain Item." );

and the error is Error - 25299

Why is this and how to solve this? Which I should choose such as kSecAttrLabel? I changed it to kSecAttrService it works fun but I don't know is there any other potential bugs.

Any help will be appreciate.

Body:
I've spent a lot of days in struggling the same problem. At last , I'v found the cause of it that I pass by too easily.

That is an important constant of keychain. Take a look at the codes.
(Assuming that I used keychain in my target for the first time)

KeychainItemWrapper *test1 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test10"  accessGroup:nil];
[test1 setObject:(id)@"value1" forKey:(id)kSecValueData];
//Normally it works

KeychainItemWrapper *test2 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test20"  accessGroup:nil];
//At this point , we meet the crash with the message of 'Couldn't add the Keychain Item.'
[test2 setObject:(id)@"value2" forKey:(id)kSecValueData];

Even if the name of 'initWithIdentifier' is different , the constant 'kSecAttrAccount' must be unique.
Its default value is ""( that is empty). Once keychain wrapper is used , the 'kSecAttrAccount' of it is saved . So you need to pay much attention to the 'kSecAttrAccount' when you use the another 'initWithIdentifier'.

I can fix the crash of above codes by adding some codes.

    KeychainItemWrapper *test1 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test10"  accessGroup:nil];
[test1 setObject:@"test1" forKey:(id)kSecAttrAccount];
[test1 setObject:(id)@"value1" forKey:(id)kSecValueData];

KeychainItemWrapper *test2 = [[KeychainItemWrapper alloc] initWithIdentifier:@"test20"  accessGroup:nil];
[test2 setObject:@"test2" forKey:(id)kSecAttrAccount];
[test2 setObject:(id)@"value2" forKey:(id)kSecValueData];

For more information, if you use the accessGroup of KeychainItemWrapper,
as I mention above , the kSecAttrAccount must be unique regardless of using accessGroup or not.

The following is an example.

KeychainItemWrapper *test = [[KeychainItemWrapper alloc] initWithIdentifier:@"test"  accessGroup:"App_ID.SampleName"];

As you know , App_ID should be created at the apple developer and SampleName should be setup at the capabilities of KeyChain Sharing of your app target.
The '.' between App_ID and SampleName must be added. This is a key point.

Please refer to the postings the other persons uploaded about how to set it.


来源: stackexchange

问:
Transpose all rows in one column of dataframe to multiple columns based on certain conditions
I would like to convert one column of data to multiple columns in dataframe based on certain values/conditions.

Please find the code to generate the input dataframe

```<code>df1 = pd.DataFrame({'VARIABLE':['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']})
</code>```

The data looks like as shown below

Please note that I may not know the column names in advance. But it usually follows this format. What I have shown above is a sample data and real data might have around 600-700 columns and data arranged in this fashion

What I would like to do is convert values which start with non-digits(characters) as new columns in dataframe. It can be a new dataframe.

I attempted to write a for loop but failed to due to the below error. Can you please help me achieve this outcome.

```<code>for i in range(3,len(df1)):
#str(df1['VARIABLE'][i].contains('^\d'))
    if (df1['VARIABLE'][i].astype(str).contains('^\d') == True):
</code>```

Through the above loop, I was trying to check whether first char is a digit, if yes, then retain it as a value (ex: 1,2,3 etc) and if it's a character (ex:gender, ethnicity etc), then create a new column. But guess this is an incorrect and lengthy approach

For example, in the above example, the columns would be studyid,age_interview,Gender,Ethnicity.

The final output would look like this

Can you please let me know if there is an elegant approach to do this?

答:
You can use groupby to do something like:

```<code>m=~df1['VARIABLE'].str[0].str.isdigit().fillna(True)
new_df=(pd.DataFrame(df1.groupby(m.cumsum()).VARIABLE.apply(list).
                                    values.tolist()).set_index(0).T)
print(new_df.rename_axis(None,axis=1))
</code>```

```<code>  studyid age_interview    Gender  Ethnicity
1       1            65    1.Male  1.Chinese
2    None          None  2.Female   2.Indian
3    None          None      None    3.Malay
</code>```

Explanation: m is a helper series which helps seperating the groups:

```<code>print(m.cumsum())
0     1
1     1
2     2
3     2
4     3
5     3
6     3
7     4
8     4
9     4
10    4
</code>```

Then we group this helper series and apply list:

```<code>df1.groupby(m.cumsum()).VARIABLE.apply(list)
VARIABLE
1                                 [studyid, 1]
2                          [age_interview, 65]
3                   [Gender, 1.Male, 2.Female]
4    [Ethnicity, 1.Chinese, 2.Indian, 3.Malay]
Name: VARIABLE, dtype: object
</code>```

At this point we have each group as a list with the column name as the first entry.
So we create a dataframe with this and set the first column as index and transpose to get our desired output.

ContentLicense: CC BY-SA 4.0

Body:
I would like to convert one column of data to multiple columns in dataframe based on certain values/conditions.

Please find the code to generate the input dataframe

df1 = pd.DataFrame({'VARIABLE':['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']})

The data looks like as shown below

Please note that I may not know the column names in advance. But it usually follows this format. What I have shown above is a sample data and real data might have around 600-700 columns and data arranged in this fashion

What I would like to do is convert values which start with non-digits(characters) as new columns in dataframe. It can be a new dataframe.

I attempted to write a for loop but failed to due to the below error. Can you please help me achieve this outcome.

for i in range(3,len(df1)):
#str(df1['VARIABLE'][i].contains('^\d'))
    if (df1['VARIABLE'][i].astype(str).contains('^\d') == True):

Through the above loop, I was trying to check whether first char is a digit, if yes, then retain it as a value (ex: 1,2,3 etc) and if it's a character (ex:gender, ethnicity etc), then create a new column. But guess this is an incorrect and lengthy approach

For example, in the above example, the columns would be studyid,age_interview,Gender,Ethnicity.

The final output would look like this

Can you please let me know if there is an elegant approach to do this?

Body:
You can use groupby to do something like:

m=~df1['VARIABLE'].str[0].str.isdigit().fillna(True)
new_df=(pd.DataFrame(df1.groupby(m.cumsum()).VARIABLE.apply(list).
                                    values.tolist()).set_index(0).T)
print(new_df.rename_axis(None,axis=1))

  studyid age_interview    Gender  Ethnicity
1       1            65    1.Male  1.Chinese
2    None          None  2.Female   2.Indian
3    None          None      None    3.Malay

Explanation: m is a helper series which helps seperating the groups:

print(m.cumsum())
0     1
1     1
2     2
3     2
4     3
5     3
6     3
7     4
8     4
9     4
10    4

Then we group this helper series and apply list:

df1.groupby(m.cumsum()).VARIABLE.apply(list)
VARIABLE
1                                 [studyid, 1]
2                          [age_interview, 65]
3                   [Gender, 1.Male, 2.Female]
4    [Ethnicity, 1.Chinese, 2.Indian, 3.Malay]
Name: VARIABLE, dtype: object

At this point we have each group as a list with the column name as the first entry.
So we create a dataframe with this and set the first column as index and transpose to get our desired output.


问:
Click on link changes the url but not the content/data on page
the story:

I am on product page #/product/7 and on the same page I have 4 more products that are similar to the one that is being viewed. All these products have links to their pages:

router-link(:to="{ name: 'product', params: { id: product.id }}" v-text='product.title').

the problem:

When I click on any of the product links, the url changes but the content remains the same. So, if I am on #/product/7 and click on #/product/8 the url only will change. If I navigate from /product/:id page and click on a product it takes me to the right page with proper content.

As you can see on screenshot, current product id is 15, but the content is the one from the id 7, as shown in url at the bottom while I was hovering over the Sleek Silk Shirt product in cart.
Any ideas how to fix this?

答:
I couldnt really internalise the above answer with 'getProduct', so to be put simply.

I am using a Store and I needed to watch the $route and when it changes I called my store to dispatch the api call.

```<code>watch: {
    $route () {
      this.$store.dispatch('fetchStudyStandards',
      this.$route.params.standardID);
    }
}
</code>```

So basically watch the route and if it changes, re do your api call.

ContentLicense: CC BY-SA 3.0

Body:
I couldnt really internalise the above answer with 'getProduct', so to be put simply.

I am using a Store and I needed to watch the $route and when it changes I called my store to dispatch the api call.

watch: {
    $route () {
      this.$store.dispatch('fetchStudyStandards',
      this.$route.params.standardID);
    }
}

So basically watch the route and if it changes, re do your api call.


问:
FluentNHibernate - Automapping ignore property
I have a base class that contains a property called IsDirty. This is used for the domain model and is not a column in the database table.

When using automapping, fluent nhibernate tries to add this column to the table. A way to fix this is to put .ForTypesThatDeriveFrom<Address>(p => p.IgnoreProperty(x => x.IsDirty)) in the automapping setup.

The problem is, all my entities will do this, is there a way to state this without have to add this line for every entity? If I put .ForTypesThatDeriveFrom<Entity>(p => p.IgnoreProperty(x => x.IsDirty)), then I get an error trying to convert Entity to Address.

I also have entity set as the base type.

Thanks in advance,
JT

答:
OverrideAll seems to fit well if you do not define your configuration.

```<code>Fluently
    .Configure()
    .Mappings(x => x.AutoMappings.Add(AutoMap.AssemblyOf<MyEntity>(mapConfig)
            .OverrideAll(ign => ign.IgnoreProperty("MyPropertyToBeIgnored"))
                ))
</code>```

Source: https://bernardorezende.wordpress.com/2011/12/12/ignore-property-mapping-with-fluent-nhibernates-automapping-model/

OwnerDisplayName: JT

Body:
OverrideAll seems to fit well if you do not define your configuration.

Fluently
    .Configure()
    .Mappings(x => x.AutoMappings.Add(AutoMap.AssemblyOf<MyEntity>(mapConfig)
            .OverrideAll(ign => ign.IgnoreProperty("MyPropertyToBeIgnored"))
                ))

Source: https://bernardorezende.wordpress.com/2011/12/12/ignore-property-mapping-with-fluent-nhibernates-automapping-model/


问:
error Type mismatch after upgrading to 6.0.2 in inno
Code was working normally, but after upgrading to inno 6.0.2, i got an error when compile. Error:

Type mismatch

in line if LoadStringFromFile(TmpFile, ExecStdout) then code as below:

```<code>function NextButtonClick(CurPageID: Integer): Boolean;
var
  TmpFile, ExecStdout: string;
  ResultCode: integer;
begin
  Result := True;
  if CurPageID = HostingPage.ID then
    begin
      Domain   := HostingPage.values[0];
      DomainPort := HostingPage.values[1];

        TmpFile := ExpandConstant('{tmp}') + '\~pid.txt';
        Exec('cmd.exe',
        '/C FOR /F "usebackq tokens=5 delims= " %i IN (`netstat -ano ^|find "0.0:'+DomainPort+'"`) DO '
        + '@tasklist /fi "pid eq %i" | find "%i" > "' + TmpFile + '"', '', SW_HIDE,
        ewWaitUntilTerminated, ResultCode);
        if LoadStringFromFile(TmpFile, ExecStdout) then
        begin
            MsgBox('The Port ('+DomainPort+')  ' #13 + ExecStdout, mbError, MB_OK);
            Result := False;
        end;
        DeleteFile(TmpFile);
    end;
end;
</code>```

答:
The code you posted in not complete, always post MCVE.

The problem resides in using wrong type of parameter, see the documentation:

function LoadStringFromFile(const FileName: String; var S:
  AnsiString): Boolean;

Change it like this:

```<code>function NextButtonClick(CurPageID: Integer): Boolean;
var
  TmpFile: String;
  ExecStdout: AnsiString; // << Was String in your script
  ResultCode: Integer;
</code>```

This is because Inno Setup 6 is Unicode only:

Change in default behavior: Starting with Inno Setup 6 there's only one version available: Unicode Inno Setup. Unicode Inno Setup has been available for 9 years but in case you have not yet updated to it: please see the Unicode Inno Setup topic in the help file for more information. Basically, unless you're using [Code] to make DLL calls with string parameters you shouldn't have to make any changes to your script.

Body:
Code was working normally, but after upgrading to inno 6.0.2, i got an error when compile. Error:

Type mismatch

in line if LoadStringFromFile(TmpFile, ExecStdout) then code as below:

function NextButtonClick(CurPageID: Integer): Boolean;
var
  TmpFile, ExecStdout: string;
  ResultCode: integer;
begin
  Result := True;
  if CurPageID = HostingPage.ID then
    begin
      Domain   := HostingPage.values[0];
      DomainPort := HostingPage.values[1];

        TmpFile := ExpandConstant('{tmp}') + '\~pid.txt';
        Exec('cmd.exe',
        '/C FOR /F "usebackq tokens=5 delims= " %i IN (`netstat -ano ^|find "0.0:'+DomainPort+'"`) DO '
        + '@tasklist /fi "pid eq %i" | find "%i" > "' + TmpFile + '"', '', SW_HIDE,
        ewWaitUntilTerminated, ResultCode);
        if LoadStringFromFile(TmpFile, ExecStdout) then
        begin
            MsgBox('The Port ('+DomainPort+')  ' #13 + ExecStdout, mbError, MB_OK);
            Result := False;
        end;
        DeleteFile(TmpFile);
    end;
end;

Body:
The code you posted in not complete, always post MCVE.

The problem resides in using wrong type of parameter, see the documentation:

function LoadStringFromFile(const FileName: String; var S:
  AnsiString): Boolean;

Change it like this:

function NextButtonClick(CurPageID: Integer): Boolean;
var
  TmpFile: String;
  ExecStdout: AnsiString; // << Was String in your script
  ResultCode: Integer;

This is because Inno Setup 6 is Unicode only:

Change in default behavior: Starting with Inno Setup 6 there's only one version available: Unicode Inno Setup. Unicode Inno Setup has been available for 9 years but in case you have not yet updated to it: please see the Unicode Inno Setup topic in the help file for more information. Basically, unless you're using [Code] to make DLL calls with string parameters you shouldn't have to make any changes to your script.


问:
NodeJS sequelize auto generate models and run migrations SQL syntax error
I am building a new NodeJS application with MySQL. I need to use the existing database schema. I have a mysql dump file that is loaded into the database (in a docker container). I am trying to generate models and migrations automatically and then run the migrations successfully. I am able to generate the models and migrations, however there is a SQL syntax error when running the generated migrations.

Here are the relevant versions:

Node10-alpine

```<code>"mysql": "^2.17.1",
"mysql2": "^1.6.5",
"sequelize": "^5.8.5",
"sequelize-auto": "^0.4.29",
"sequelize-auto-migrations": "^1.0.3"
</code>```

I used the sequelize-auto module to generate the Models automatically. That works.

```<code>sequelize-auto -o "./models" -d sequelize_auto_test -h localhost -u username -p 5432 -x password -e mysql
</code>```

I then attempted to use the sequelize-auto-migrations module to generate the Migrations and then run them automatically.

Generating the initial migration file works.

```<code>node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>
</code>```

However, when running the actual migration, there is a syntax error.

```<code>node ./node_modules/sequelize-auto-migrations/bin/runmigration
</code>```

That works for many of the tables but then it runs into a syntax error.

```<code>     code: 'ER_PARSE_ERROR',
     errno: 1064,
     sqlState: '42000',
     sqlMessage:
      'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \') ENGINE=InnoDB\' at line 1',
     sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' },
  sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' }
</code>```

Here is the relevant model osw.js (generated by the sequelize-auto module):

```<code>/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('osw', {
    OSWID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: false,
      primaryKey: true
    },
    IdentificationID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true,
      references: {
        model: 'itemidentification',
        key: 'IdentificationID'
      }
    },
    ProposedHours: {
      type: DataTypes.DECIMAL,
      allowNull: true
    },
    WorkStartDate: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    WorkEndDate: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    FormatID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true,
      references: {
        model: 'formats',
        key: 'FormatID'
      }
    },
    WorkLocationID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true
    }
  }, {
    tableName: 'osw'
  });
};
</code>```

Here is the relevant part of the mysql dump file:

```<code>CREATE TABLE `OSW` (
  `OSWID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `IdentificationID` int(10) unsigned DEFAULT NULL,
  `ProposedHours` decimal(10,2) DEFAULT NULL,
  `WorkStartDate` date DEFAULT NULL,
  `WorkEndDate` date DEFAULT NULL,
  `FormatID` int(10) unsigned DEFAULT NULL,
  `WorkLocationID` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`OSWID`),
  KEY `OSW_FKIndex1` (`IdentificationID`),
  KEY `OSW_Format` (`FormatID`),
  CONSTRAINT `OSW_Format` FOREIGN KEY (`FormatID`) REFERENCES `formats` (`formatid`) ON DELETE SET NULL,
  CONSTRAINT `OSW_Ident` FOREIGN KEY (`IdentificationID`) REFERENCES `itemidentification` (`identificationid`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1147 DEFAULT CHARSET=utf8 PACK_KEYS=0;
</code>```

UPDATE: I think the issue might be related to the migration that was generated automatically. The migration file seems to be missing the column and field type definitions, so that might be why the SQL CREATE table command is missing the column names. Here is the relevant part of the migration file that was generated regarding the osw table:

```<code>var migrationCommands = [{
    {
        fn: "createTable",
        params: [
            "osw",
            {

            },
            {}
        ]
    }
];
</code>```

答:
Yes, the SQL error is because there should be a list of columns between the parentheses.

Yes, the migration file should contain columns instead of empty brackets, as will be shown by the correct file lower in this answer.

The cause of the bad migration appears to involve the recent Sequelize version specified in your package.json. The rest of this answer explains the process.

Your sequelize-auto output looked normal, so I tried to reproduce just the migrations step, by:

Running sequelize init (not explicitly installed, NPM showed 4.44) in a new directory and pasting osw.js in ./models.

Installing matching versions of mysql2 and sequelize-auto-migrations, the bare minimum needed to call node ./node_modules/sequelize-auto-migrations/bin/makemigration --name osw

This produced migrations/1-osw.js:

```<code>'use strict';

var Sequelize = require('sequelize');

/**
 * Actions summary:
 *
 * createTable "osw", deps: [itemidentification, formats]
 *
 **/

var info = {
    "revision": 1,
    "name": "osw",
    "created": "2019-05-30T03:54:19.054Z",
    "comment": ""
};

var migrationCommands = [{
    fn: "createTable",
    params: [
        "osw",
        {
            "OSWID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "OSWID",
                "primaryKey": true,
                "allowNull": false
            },
            "IdentificationID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "IdentificationID",
                "references": {
                    "model": "itemidentification",
                    "key": "IdentificationID"
                },
                "allowNull": true
            },
            "ProposedHours": {
                "type": Sequelize.DECIMAL,
                "field": "ProposedHours",
                "allowNull": true
            },
            "WorkStartDate": {
                "type": Sequelize.DATEONLY,
                "field": "WorkStartDate",
                "allowNull": true
            },
            "WorkEndDate": {
                "type": Sequelize.DATEONLY,
                "field": "WorkEndDate",
                "allowNull": true
            },
            "FormatID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "FormatID",
                "references": {
                    "model": "formats",
                    "key": "FormatID"
                },
                "allowNull": true
            },
            "WorkLocationID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "WorkLocationID",
                "allowNull": true
            },
            "createdAt": {
                "type": Sequelize.DATE,
                "field": "createdAt",
                "allowNull": false
            },
            "updatedAt": {
                "type": Sequelize.DATE,
                "field": "updatedAt",
                "allowNull": false
            }
        },
        {}
    ]
}];

module.exports = {
    pos: 0,
    up: function(queryInterface, Sequelize)
    {
        var index = this.pos;
        return new Promise(function(resolve, reject) {
            function next() {
                if (index < migrationCommands.length)
                {
                    let command = migrationCommands[index];
                    console.log("[#"+index+"] execute: " + command.fn);
                    index++;
                    queryInterface[command.fn].apply(queryInterface, command.params).then(next, reject);
                }
                else
                    resolve();
            }
            next();
        });
    },
    info: info
};
</code>```

This solves the immediate problem, but does not explain it. I cleaned the directory, initialized the package, installed all the dependencies, and tried to generate the migration again. That produced an empty migrationCommands variable like you showed above. Attempting to uninstall and reinstall various packages had no effect - I generated empty a dozen times. Uninstalling sequelize caused an error, so I started fresh with an empty directory and npm i -s mysql2 sequelize-auto-migrations; sequelize init. Generation from osw.js worked again.

npm showed that sequelize-auto-migrations was using sequelize 4.44 again. npm i sequelize installed 5.8.7, and generation immediately began failing. So sequelize-auto-migrations can only generate for your model when depending on an earlier version of sequelize. No idea what the root cause is.

Body:
I am building a new NodeJS application with MySQL. I need to use the existing database schema. I have a mysql dump file that is loaded into the database (in a docker container). I am trying to generate models and migrations automatically and then run the migrations successfully. I am able to generate the models and migrations, however there is a SQL syntax error when running the generated migrations.

Here are the relevant versions:

Node10-alpine

"mysql": "^2.17.1",
"mysql2": "^1.6.5",
"sequelize": "^5.8.5",
"sequelize-auto": "^0.4.29",
"sequelize-auto-migrations": "^1.0.3"

I used the sequelize-auto module to generate the Models automatically. That works.

sequelize-auto -o "./models" -d sequelize_auto_test -h localhost -u username -p 5432 -x password -e mysql

I then attempted to use the sequelize-auto-migrations module to generate the Migrations and then run them automatically.

Generating the initial migration file works.

node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>

However, when running the actual migration, there is a syntax error.

node ./node_modules/sequelize-auto-migrations/bin/runmigration

That works for many of the tables but then it runs into a syntax error.

     code: 'ER_PARSE_ERROR',
     errno: 1064,
     sqlState: '42000',
     sqlMessage:
      'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \') ENGINE=InnoDB\' at line 1',
     sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' },
  sql: 'CREATE TABLE IF NOT EXISTS `osw` () ENGINE=InnoDB;' }

Here is the relevant model osw.js (generated by the sequelize-auto module):

/* jshint indent: 2 */

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('osw', {
    OSWID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: false,
      primaryKey: true
    },
    IdentificationID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true,
      references: {
        model: 'itemidentification',
        key: 'IdentificationID'
      }
    },
    ProposedHours: {
      type: DataTypes.DECIMAL,
      allowNull: true
    },
    WorkStartDate: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    WorkEndDate: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    FormatID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true,
      references: {
        model: 'formats',
        key: 'FormatID'
      }
    },
    WorkLocationID: {
      type: DataTypes.INTEGER(10).UNSIGNED,
      allowNull: true
    }
  }, {
    tableName: 'osw'
  });
};

Here is the relevant part of the mysql dump file:

CREATE TABLE `OSW` (
  `OSWID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `IdentificationID` int(10) unsigned DEFAULT NULL,
  `ProposedHours` decimal(10,2) DEFAULT NULL,
  `WorkStartDate` date DEFAULT NULL,
  `WorkEndDate` date DEFAULT NULL,
  `FormatID` int(10) unsigned DEFAULT NULL,
  `WorkLocationID` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`OSWID`),
  KEY `OSW_FKIndex1` (`IdentificationID`),
  KEY `OSW_Format` (`FormatID`),
  CONSTRAINT `OSW_Format` FOREIGN KEY (`FormatID`) REFERENCES `formats` (`formatid`) ON DELETE SET NULL,
  CONSTRAINT `OSW_Ident` FOREIGN KEY (`IdentificationID`) REFERENCES `itemidentification` (`identificationid`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1147 DEFAULT CHARSET=utf8 PACK_KEYS=0;

UPDATE: I think the issue might be related to the migration that was generated automatically. The migration file seems to be missing the column and field type definitions, so that might be why the SQL CREATE table command is missing the column names. Here is the relevant part of the migration file that was generated regarding the osw table:

var migrationCommands = [{
    {
        fn: "createTable",
        params: [
            "osw",
            {

            },
            {}
        ]
    }
];

Body:
Yes, the SQL error is because there should be a list of columns between the parentheses.

Yes, the migration file should contain columns instead of empty brackets, as will be shown by the correct file lower in this answer.

The cause of the bad migration appears to involve the recent Sequelize version specified in your package.json. The rest of this answer explains the process.

Your sequelize-auto output looked normal, so I tried to reproduce just the migrations step, by:

Running sequelize init (not explicitly installed, NPM showed 4.44) in a new directory and pasting osw.js in ./models.

Installing matching versions of mysql2 and sequelize-auto-migrations, the bare minimum needed to call node ./node_modules/sequelize-auto-migrations/bin/makemigration --name osw

This produced migrations/1-osw.js:

'use strict';

var Sequelize = require('sequelize');

/**
 * Actions summary:
 *
 * createTable "osw", deps: [itemidentification, formats]
 *
 **/

var info = {
    "revision": 1,
    "name": "osw",
    "created": "2019-05-30T03:54:19.054Z",
    "comment": ""
};

var migrationCommands = [{
    fn: "createTable",
    params: [
        "osw",
        {
            "OSWID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "OSWID",
                "primaryKey": true,
                "allowNull": false
            },
            "IdentificationID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "IdentificationID",
                "references": {
                    "model": "itemidentification",
                    "key": "IdentificationID"
                },
                "allowNull": true
            },
            "ProposedHours": {
                "type": Sequelize.DECIMAL,
                "field": "ProposedHours",
                "allowNull": true
            },
            "WorkStartDate": {
                "type": Sequelize.DATEONLY,
                "field": "WorkStartDate",
                "allowNull": true
            },
            "WorkEndDate": {
                "type": Sequelize.DATEONLY,
                "field": "WorkEndDate",
                "allowNull": true
            },
            "FormatID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "FormatID",
                "references": {
                    "model": "formats",
                    "key": "FormatID"
                },
                "allowNull": true
            },
            "WorkLocationID": {
                "type": Sequelize.INTEGER(10).UNSIGNED,
                "field": "WorkLocationID",
                "allowNull": true
            },
            "createdAt": {
                "type": Sequelize.DATE,
                "field": "createdAt",
                "allowNull": false
            },
            "updatedAt": {
                "type": Sequelize.DATE,
                "field": "updatedAt",
                "allowNull": false
            }
        },
        {}
    ]
}];

module.exports = {
    pos: 0,
    up: function(queryInterface, Sequelize)
    {
        var index = this.pos;
        return new Promise(function(resolve, reject) {
            function next() {
                if (index < migrationCommands.length)
                {
                    let command = migrationCommands[index];
                    console.log("[#"+index+"] execute: " + command.fn);
                    index++;
                    queryInterface[command.fn].apply(queryInterface, command.params).then(next, reject);
                }
                else
                    resolve();
            }
            next();
        });
    },
    info: info
};

This solves the immediate problem, but does not explain it. I cleaned the directory, initialized the package, installed all the dependencies, and tried to generate the migration again. That produced an empty migrationCommands variable like you showed above. Attempting to uninstall and reinstall various packages had no effect - I generated empty a dozen times. Uninstalling sequelize caused an error, so I started fresh with an empty directory and npm i -s mysql2 sequelize-auto-migrations; sequelize init. Generation from osw.js worked again.

npm showed that sequelize-auto-migrations was using sequelize 4.44 again. npm i sequelize installed 5.8.7, and generation immediately began failing. So sequelize-auto-migrations can only generate for your model when depending on an earlier version of sequelize. No idea what the root cause is.


问:
Programmatically added a shortcut to the All Users desktop and can't remove it
In VB.NET I used wscript.shell to add a shortcut to the desktop.  I didn't realize it created the shortcut on the "All Users" desktop, which means I can't delete it.  I don't have admin rights as this is my work computer, and asking for admin isn't an option.  WScript.Shell has a createshortcut method but not a remove shortcut method! I've been googling for days with no luck. Windows XP Pro 2002, SP3.

It may be impossible, but it's frustrating I can add a shortcut but not remove it.  If anyone could help I'd be so grateful!

答:
If you can add shortcuts to "All Users" through VB.NET then your work security obviously isn't up to scratch.  Let them know that the only reason it got there in the first place is because of their systems' lack of security, and that it needs deleted one way or another.

Is it really impossible to get an admin to delete it for you?


问:
in onPurchasesUpdated, how to get accountid which was setted in BillingFlowParams
I am using com.android.billingclient:billing:1.1 for android's in app billing. I start pay in below code:

```<code>BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                            .setSku(productId)
                            .setType(BillingClient.SkuType.INAPP)
                            .setAccountId(accountId)
                            .build();
billingClient.launchBillingFlow(this, flowParams);
</code>```

It will callback on:

```<code>void onPurchasesUpdated(@BillingResponse int responseCode, @Nullable List<Purchase> purchases);
</code>```

The question is how to get account which was seated in BillingFlowParams?

答:
We recommend that you use a one-way hash to generate a
string from the user's ID and store the hashed string in this field as mentioned in documentation:

```<code>/**
 * Specify an optional obfuscated string that is uniquely associated with the user's account in
 * your app.
 *
 * <p>If you pass this value, Google Play can use it to detect irregular activity, such as many
 * devices making purchases on the same account in a short period of time. Do not use the
 * developer ID or the user's Google ID for this field. In addition, this field should not
 * contain the user's ID in cleartext. **We recommend that you use a one-way hash to generate a
 * string from the user's ID and store the hashed string in this field**.
 *
 * <p>Optional:
 *
 * <ul>
 *   <li>To buy in-app item
 *   <li>To create a new subscription
 *   <li>To replace an old subscription
 * </ul>
 */
public Builder setAccountId(String accountId) {
  this.mAccountId = accountId;
  return this;
}
</code>```

Optional obfuscated string that is uniquely associated with the user's account in your app. If you pass this value, Google Play can use it to detect irregular activity, such as many devices making purchases on the same account in a short period of time

Body:
I am using com.android.billingclient:billing:1.1 for android's in app billing. I start pay in below code:

BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                            .setSku(productId)
                            .setType(BillingClient.SkuType.INAPP)
                            .setAccountId(accountId)
                            .build();
billingClient.launchBillingFlow(this, flowParams);

It will callback on:

void onPurchasesUpdated(@BillingResponse int responseCode, @Nullable List<Purchase> purchases);

The question is how to get account which was seated in BillingFlowParams?

Body:
We recommend that you use a one-way hash to generate a
string from the user's ID and store the hashed string in this field as mentioned in documentation:

/**
 * Specify an optional obfuscated string that is uniquely associated with the user's account in
 * your app.
 *
 * <p>If you pass this value, Google Play can use it to detect irregular activity, such as many
 * devices making purchases on the same account in a short period of time. Do not use the
 * developer ID or the user's Google ID for this field. In addition, this field should not
 * contain the user's ID in cleartext. **We recommend that you use a one-way hash to generate a
 * string from the user's ID and store the hashed string in this field**.
 *
 * <p>Optional:
 *
 * <ul>
 *   <li>To buy in-app item
 *   <li>To create a new subscription
 *   <li>To replace an old subscription
 * </ul>
 */
public Builder setAccountId(String accountId) {
  this.mAccountId = accountId;
  return this;
}

Optional obfuscated string that is uniquely associated with the user's account in your app. If you pass this value, Google Play can use it to detect irregular activity, such as many devices making purchases on the same account in a short period of time


问:
Run time error 53 file not found for some files in directory
I wrote a program to prompt the user to select a folder filled with .txt files and then extract information.

There are some files it cannot find and gives me a run time error 53 file not found despite the file being in the folder.

Debugging points to the 'Open MyFile For Input As #1' line.

If I specify the file path and run the macro it extracts the information so the file path is correct.

I looked at this solution

Excel VBA - Run-time error '53': File not found. But file was found

basically specifying a directory then trying to read each file from that directory but I get the same error.

Here is the original code to prompt the user to select a folder than read each file in the folder.

```<code>Sub read()
'PURPOSE: Send All Data From Text File To A String Variable

    Dim TextFile As Integer
    Dim FilePath As String
    Dim FileContent As String

    Dim MyFolder As String, MyFile As String

'Opens a file dialog box for user to select a folder

    With Application.FileDialog(msoFileDialogFolderPicker)
       .AllowMultiSelect = False
       .Show
       MyFolder = .SelectedItems(1)
       Err.Clear
    End With

'create a new object for files in that folder and apply the for/loop as below
    Dim objFSO As Object
    Dim objFolder As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.getFolder(MyFolder)

    Dim fls As Object
    Dim i As Integer
    i = 1
    For Each fls In objFolder.Files

'File Path of Text File

    MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)

'Determine the next file number available for use by the FileOpen function

    TextFile = FreeFile

'Open the text file

    Open MyFile For Input As #1
</code>```

答:
by using the line you actually stripping the file name of its path

```<code>MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)
</code>```

simply make it

```<code>MyFile = MyFolder & "\" & fls.Name
</code>```

Body:
I wrote a program to prompt the user to select a folder filled with .txt files and then extract information.

There are some files it cannot find and gives me a run time error 53 file not found despite the file being in the folder.

Debugging points to the 'Open MyFile For Input As #1' line.

If I specify the file path and run the macro it extracts the information so the file path is correct.

I looked at this solution

Excel VBA - Run-time error '53': File not found. But file was found

basically specifying a directory then trying to read each file from that directory but I get the same error.

Here is the original code to prompt the user to select a folder than read each file in the folder.

Sub read()
'PURPOSE: Send All Data From Text File To A String Variable

    Dim TextFile As Integer
    Dim FilePath As String
    Dim FileContent As String

    Dim MyFolder As String, MyFile As String

'Opens a file dialog box for user to select a folder

    With Application.FileDialog(msoFileDialogFolderPicker)
       .AllowMultiSelect = False
       .Show
       MyFolder = .SelectedItems(1)
       Err.Clear
    End With

'create a new object for files in that folder and apply the for/loop as below
    Dim objFSO As Object
    Dim objFolder As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.getFolder(MyFolder)

    Dim fls As Object
    Dim i As Integer
    i = 1
    For Each fls In objFolder.Files

'File Path of Text File

    MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)

'Determine the next file number available for use by the FileOpen function

    TextFile = FreeFile

'Open the text file

    Open MyFile For Input As #1

Body:
by using the line you actually stripping the file name of its path

MyFile = Dir(MyFolder & "\" & fls.Name, vbReadOnly)

simply make it

MyFile = MyFolder & "\" & fls.Name


问:
Is there a difference between np.matrix(np.array([0,0])) and np.matrix([0,0])?
I was reading this code, for implementing linear regression from scratch:

```<code># convert from data frames to numpy matrices
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
</code>```

When I came across this line:

```<code>np.matrix(np.array([0,0]))
</code>```

I was wondering why didn't the person just write np.matrix([0,0]).

I ran both in jupyter notebook and got the same output:

```<code>theta = np.matrix([0,0])
theta2 = np.matrix(np.array([0,0]))
print(theta,theta2,type(theta),type(theta2))
</code>```

Output:[[0 0]] [[0 0]] <class 'numpy.matrix'> <class 'numpy.matrix'>

Is there a difference between the two? Does the extra np.array somehow part add to the functionality of theta? Will the final code function properly if I replace the former with the latter?

答:
You may check the documentation:

The signature "data" of np.matrix can be either array_like or string, while both [0,0] and its corresponding numpy.ndarray counterpart suffice.

Body:
I was reading this code, for implementing linear regression from scratch:

# convert from data frames to numpy matrices
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))

When I came across this line:

np.matrix(np.array([0,0]))

I was wondering why didn't the person just write np.matrix([0,0]).

I ran both in jupyter notebook and got the same output:

theta = np.matrix([0,0])
theta2 = np.matrix(np.array([0,0]))
print(theta,theta2,type(theta),type(theta2))

Output:[[0 0]] [[0 0]] <class 'numpy.matrix'> <class 'numpy.matrix'>

Is there a difference between the two? Does the extra np.array somehow part add to the functionality of theta? Will the final code function properly if I replace the former with the latter?


问:
How do I prevent print screen
I have a requirement that an application I am working on prevent the user from being able to easily capture the contents of the screen.

I have communicated that there is no feasible way to completely prevent this from happening, but I'm looking for methods to introduce some hurdles to the process.

I'm using C#/.NET 2.0 and WinForms

答:
In windows form application, Use this code in form keyup event,

```<code>   if (e.KeyCode == Keys.PrintScreen)
                {
                    Clipboard.Clear();
                }
</code>```

Form keypreview should be TRUE

OwnerDisplayName: Grady

ContentLicense: CC BY-SA 2.5

Title: How do I prevent print screen

Body:
In windows form application, Use this code in form keyup event,

   if (e.KeyCode == Keys.PrintScreen)
                {
                    Clipboard.Clear();
                }

Form keypreview should be TRUE


问:
How to load properties into environment from zookeeper before initialising beans in web application
Spring based web application:
Existing: The context is loaded from file("web.xml") and properties required for application are being loaded from properties file referred in xml context file.

New: Now properties should be read from zookeeper (along with properties file). Required java code for reading the properties is done by using ZookeeperPropertySource

Problem: Where do i need to insert the java code so that the properties will be loaded from zookeeper along with the initialization of application context?

I am unable to achieve this using ApplicationEventListener (as ContextStartedEvent is not triggered automatically) and BeanFactoryPostProcessor (Environment is not available to bind the properties)

答:
Solution:

Create a new class extending "ContextLoaderListener" class and override the method "WebApplicationContext createWebApplicationContext(ServletContext sc)". As WebApplicationContext will be available here, ZookeeperPropertySource can be set to the environment.

Sample Code:

```
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
    WebApplicationContext webApplicationContext = super.createWebApplicationContext(servletContext);
    loadZookeeperPropertySource(webApplicationContext.getEnvironment());
    return webApplicationContext;
}```

loadZookeeperPropertySource(Environment environment) is a method where properties sources are loaded from zookeeper using ZookeeperPropertySourceLocator and set to the environment

Body:
Solution:

Create a new class extending "ContextLoaderListener" class and override the method "WebApplicationContext createWebApplicationContext(ServletContext sc)". As WebApplicationContext will be available here, ZookeeperPropertySource can be set to the environment.

Sample Code:

@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
    WebApplicationContext webApplicationContext = super.createWebApplicationContext(servletContext);
    loadZookeeperPropertySource(webApplicationContext.getEnvironment());
    return webApplicationContext;
}

loadZookeeperPropertySource(Environment environment) is a method where properties sources are loaded from zookeeper using ZookeeperPropertySourceLocator and set to the environment


问:
Bad state: Mock method was not called within `when()`. Was a real method called?
I'm trying to make a mock of an httpRequest in flutter using mockito.

Here I define a global http client:

library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();
```

<p>Then I replace in integration testing:</p>

<pre class="lang-dart prettyprint-override"><code>import 'package:flutter_driver/driver_extension.dart';
import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:mockito/mockito.dart';

import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  final MockClient client = MockClient();
  globals.httpClient = client;

  enableFlutterDriverExtension();

  app.main();
}
</code>```

Then I try to use when of mockito:

test('login with correct password', () async {
      final client = MockClient();

      when(globals.httpClient.post('http://www.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });
```

But I receive the following error:

Bad state: Mock method was not called within when(). Was a real method called?

答:
The solution I found was to define the mock in test_driver/app.dart and call the runApp function after that, this way you can apply the mock even with flutter integration testing:

import 'package:flutter/widgets.dart';
import 'package:flutter_driver/driver_extension.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:utgard/business/config/globals.dart';
import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  enableFlutterDriverExtension();

  final MockClient client = MockClient();
  // make your mocks here
  httpClient = client;

  runApp(app.MyApp());
}
```

<p>Since it can become a huge code to mock all the requests there you can make a separate function in order to better organize the code:</p>

<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/widgets.dart';
import 'package:flutter_driver/driver_extension.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:utgard/business/config/globals.dart';
import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  enableFlutterDriverExtension();

  final MockClient client = MockClient();
  makeMock();
  httpClient = client;

  runApp(app.MyApp());
}
</code>```

Body:
I'm trying to make a mock of an httpRequest in flutter using mockito.

Here I define a global http client:

library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();

Then I replace in integration testing:

import 'package:flutter_driver/driver_extension.dart';
import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:mockito/mockito.dart';

import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  final MockClient client = MockClient();
  globals.httpClient = client;

  enableFlutterDriverExtension();

  app.main();
}

Then I try to use when of mockito:

test('login with correct password', () async {
      final client = MockClient();

      when(globals.httpClient.post('http://www.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });

But I receive the following error:

Bad state: Mock method was not called within when(). Was a real method called?

Body:
The solution I found was to define the mock in test_driver/app.dart and call the runApp function after that, this way you can apply the mock even with flutter integration testing:

import 'package:flutter/widgets.dart';
import 'package:flutter_driver/driver_extension.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:utgard/business/config/globals.dart';
import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  enableFlutterDriverExtension();

  final MockClient client = MockClient();
  // make your mocks here
  httpClient = client;

  runApp(app.MyApp());
}

Since it can become a huge code to mock all the requests there you can make a separate function in order to better organize the code:

import 'package:flutter/widgets.dart';
import 'package:flutter_driver/driver_extension.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:utgard/business/config/globals.dart';
import 'package:utgard/main.dart' as app;

class MockClient extends Mock implements http.Client {}

void main() {
  enableFlutterDriverExtension();

  final MockClient client = MockClient();
  makeMock();
  httpClient = client;

  runApp(app.MyApp());
}


问:
Is there a built-in way to convert IEnumerator to IEnumerable
Is there a built-in way to convert IEnumerator<T> to IEnumerable<T>?

答:
EnumeratorEnumerable<T>

A threadsafe, resettable adaptor from IEnumerator<T> to IEnumerable<T>

I use Enumerator parameters like in C++ forward_iterator concept.

I agree that this can lead to confusion as too many people will indeed assume Enumerators are /like/ Enumerables, but they are not.

However, the confusion is fed by the fact that IEnumerator contains the Reset method. Here is my idea of the most correct implementation. It leverages the implementation of IEnumerator.Reset()

A major difference between an Enumerable and and Enumerator is, that an Enumerable might be able to create several Enumerators simultaneously. This implementation puts a whole lot of work into making sure that this never happens for the EnumeratorEnumerable<T> type. There are two EnumeratorEnumerableModes:

Blocking (meaning that a second caller will simply wait till the first enumeration is completed)

NonBlocking (meaning that a second (concurrent) request for an enumerator simply throws an exception)

Note 1: 74 lines are implementation, 79 lines are testing code :)

Note 2: I didn't refer to any unit testing framework for SO convenience

```<code>using System;
using System.Diagnostics;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace EnumeratorTests
{
    public enum EnumeratorEnumerableMode
    {
        NonBlocking,
        Blocking,
    }

    public sealed class EnumeratorEnumerable<T> : IEnumerable<T>
    {
        #region LockingEnumWrapper

        public sealed class LockingEnumWrapper : IEnumerator<T>
        {
            private static readonly HashSet<IEnumerator<T>> BusyTable = new HashSet<IEnumerator<T>>();
            private readonly IEnumerator<T> _wrap;

            internal LockingEnumWrapper(IEnumerator<T> wrap, EnumeratorEnumerableMode allowBlocking)
            {
                _wrap = wrap;

                if (allowBlocking == EnumeratorEnumerableMode.Blocking)
                    Monitor.Enter(_wrap);
                else if (!Monitor.TryEnter(_wrap))
                    throw new InvalidOperationException("Thread conflict accessing busy Enumerator") {Source = "LockingEnumWrapper"};

                lock (BusyTable)
                {
                    if (BusyTable.Contains(_wrap))
                        throw new LockRecursionException("Self lock (deadlock) conflict accessing busy Enumerator") { Source = "LockingEnumWrapper" };
                    BusyTable.Add(_wrap);
                }

                // always implicit Reset
                _wrap.Reset();
            }

            #region Implementation of IDisposable and IEnumerator

            public void Dispose()
            {
                lock (BusyTable)
                    BusyTable.Remove(_wrap);

                Monitor.Exit(_wrap);
            }
            public bool MoveNext()      { return _wrap.MoveNext(); }
            public void Reset()         { _wrap.Reset(); }
            public T Current            { get { return _wrap.Current; } }
            object IEnumerator.Current  { get { return Current; } }

            #endregion
        }

        #endregion

        private readonly IEnumerator<T> _enumerator;
        private readonly EnumeratorEnumerableMode _allowBlocking;

        public EnumeratorEnumerable(IEnumerator<T> e, EnumeratorEnumerableMode allowBlocking)
        {
            _enumerator = e;
            _allowBlocking = allowBlocking;
        }

        private LockRecursionPolicy a;
        public IEnumerator<T> GetEnumerator()
        {
            return new LockingEnumWrapper(_enumerator, _allowBlocking);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    class TestClass
    {
        private static readonly string World = "hello world\n";

        public static void Main(string[] args)
        {
            var master = World.GetEnumerator();
            var nonblocking = new EnumeratorEnumerable<char>(master, EnumeratorEnumerableMode.NonBlocking);
            var blocking    = new EnumeratorEnumerable<char>(master, EnumeratorEnumerableMode.Blocking);

            foreach (var c in nonblocking)  Console.Write(c); // OK (implicit Reset())
            foreach (var c in blocking)     Console.Write(c); // OK (implicit Reset())
            foreach (var c in nonblocking)  Console.Write(c); // OK (implicit Reset())
            foreach (var c in blocking)     Console.Write(c); // OK (implicit Reset())

            try
            {
                var willRaiseException = from c1 in nonblocking from c2 in nonblocking select new {c1, c2};
                Console.WriteLine("Cartesian product: {0}", willRaiseException.Count()); // RAISE
            }
            catch (Exception e) { Console.WriteLine(e); }

            foreach (var c in nonblocking)  Console.Write(c); // OK (implicit Reset())
            foreach (var c in blocking)     Console.Write(c); // OK (implicit Reset())

            try
            {
                var willSelfLock = from c1 in blocking from c2 in blocking select new { c1, c2 };
                Console.WriteLine("Cartesian product: {0}", willSelfLock.Count()); // LOCK
            }
            catch (Exception e) { Console.WriteLine(e); }

            // should not externally throw (exceptions on other threads reported to console)
            if (ThreadConflictCombinations(blocking, nonblocking))
                throw new InvalidOperationException("Should have thrown an exception on background thread");
            if (ThreadConflictCombinations(nonblocking, nonblocking))
                throw new InvalidOperationException("Should have thrown an exception on background thread");

            if (ThreadConflictCombinations(nonblocking, blocking))
                Console.WriteLine("Background thread timed out");
            if (ThreadConflictCombinations(blocking, blocking))
                Console.WriteLine("Background thread timed out");

            Debug.Assert(true); // Must be reached
        }

        private static bool ThreadConflictCombinations(IEnumerable<char> main, IEnumerable<char> other)
        {
            try
            {
                using (main.GetEnumerator())
                {
                    var bg = new Thread(o =>
                        {
                            try { other.GetEnumerator(); }
                            catch (Exception e) { Report(e); }
                        }) { Name = "background" };
                    bg.Start();

                    bool timedOut = !bg.Join(1000); // observe the thread waiting a full second for a lock (or throw the exception for nonblocking)

                    if (timedOut)
                        bg.Abort();

                    return timedOut;
                }
            } catch
            {
                throw new InvalidProgramException("Cannot be reached");
            }
        }

        static private readonly object ConsoleSynch = new Object();
        private static void Report(Exception e)
        {
            lock (ConsoleSynch)
                Console.WriteLine("Thread:{0}\tException:{1}", Thread.CurrentThread.Name, e);
        }
    }
}
</code>```

Note 3: I think the implementation of the thread locking (especially around BusyTable) is quite ugly; However, I didn't want to resort to ReaderWriterLock(LockRecursionPolicy.NoRecursion) and didn't want to assume .Net 4.0 for SpinLock

Body:
EnumeratorEnumerable<T>

A threadsafe, resettable adaptor from IEnumerator<T> to IEnumerable<T>

I use Enumerator parameters like in C++ forward_iterator concept.

I agree that this can lead to confusion as too many people will indeed assume Enumerators are /like/ Enumerables, but they are not.

However, the confusion is fed by the fact that IEnumerator contains the Reset method. Here is my idea of the most correct implementation. It leverages the implementation of IEnumerator.Reset()

A major difference between an Enumerable and and Enumerator is, that an Enumerable might be able to create several Enumerators simultaneously. This implementation puts a whole lot of work into making sure that this never happens for the EnumeratorEnumerable<T> type. There are two EnumeratorEnumerableModes:

Blocking (meaning that a second caller will simply wait till the first enumeration is completed)

NonBlocking (meaning that a second (concurrent) request for an enumerator simply throws an exception)

Note 1: 74 lines are implementation, 79 lines are testing code :)

Note 2: I didn't refer to any unit testing framework for SO convenience

using System;
using System.Diagnostics;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Threading;

namespace EnumeratorTests
{
    public enum EnumeratorEnumerableMode
    {
        NonBlocking,
        Blocking,
    }

    public sealed class EnumeratorEnumerable<T> : IEnumerable<T>
    {
        #region LockingEnumWrapper

        public sealed class LockingEnumWrapper : IEnumerator<T>
        {
            private static readonly HashSet<IEnumerator<T>> BusyTable = new HashSet<IEnumerator<T>>();
            private readonly IEnumerator<T> _wrap;

            internal LockingEnumWrapper(IEnumerator<T> wrap, EnumeratorEnumerableMode allowBlocking)
            {
                _wrap = wrap;

                if (allowBlocking == EnumeratorEnumerableMode.Blocking)
                    Monitor.Enter(_wrap);
                else if (!Monitor.TryEnter(_wrap))
                    throw new InvalidOperationException("Thread conflict accessing busy Enumerator") {Source = "LockingEnumWrapper"};

                lock (BusyTable)
                {
                    if (BusyTable.Contains(_wrap))
                        throw new LockRecursionException("Self lock (deadlock) conflict accessing busy Enumerator") { Source = "LockingEnumWrapper" };
                    BusyTable.Add(_wrap);
                }

                // always implicit Reset
                _wrap.Reset();
            }

            #region Implementation of IDisposable and IEnumerator

            public void Dispose()
            {
                lock (BusyTable)
                    BusyTable.Remove(_wrap);

                Monitor.Exit(_wrap);
            }
            public bool MoveNext()      { return _wrap.MoveNext(); }
            public void Reset()         { _wrap.Reset(); }
            public T Current            { get { return _wrap.Current; } }
            object IEnumerator.Current  { get { return Current; } }

            #endregion
        }

        #endregion

        private readonly IEnumerator<T> _enumerator;
        private readonly EnumeratorEnumerableMode _allowBlocking;

        public EnumeratorEnumerable(IEnumerator<T> e, EnumeratorEnumerableMode allowBlocking)
        {
            _enumerator = e;
            _allowBlocking = allowBlocking;
        }

        private LockRecursionPolicy a;
        public IEnumerator<T> GetEnumerator()
        {
            return new LockingEnumWrapper(_enumerator, _allowBlocking);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    class TestClass
    {
        private static readonly string World = "hello world\n";

        public static void Main(string[] args)
        {
            var master = World.GetEnumerator();
            var nonblocking = new EnumeratorEnumerable<char>(master, EnumeratorEnumerableMode.NonBlocking);
            var blocking    = new EnumeratorEnumerable<char>(master, EnumeratorEnumerableMode.Blocking);

            foreach (var c in nonblocking)  Console.Write(c); // OK (implicit Reset())
            foreach (var c in blocking)     Console.Write(c); // OK (implicit Reset())
            foreach (var c in nonblocking)  Console.Write(c); // OK (implicit Reset())
            foreach (var c in blocking)     Console.Write(c); // OK (implicit Reset())

            try
            {
                var willRaiseException = from c1 in nonblocking from c2 in nonblocking select new {c1, c2};
                Console.WriteLine("Cartesian product: {0}", willRaiseException.Count()); // RAISE
            }
            catch (Exception e) { Console.WriteLine(e); }

            foreach (var c in nonblocking)  Console.Write(c); // OK (implicit Reset())
            foreach (var c in blocking)     Console.Write(c); // OK (implicit Reset())

            try
            {
                var willSelfLock = from c1 in blocking from c2 in blocking select new { c1, c2 };
                Console.WriteLine("Cartesian product: {0}", willSelfLock.Count()); // LOCK
            }
            catch (Exception e) { Console.WriteLine(e); }

            // should not externally throw (exceptions on other threads reported to console)
            if (ThreadConflictCombinations(blocking, nonblocking))
                throw new InvalidOperationException("Should have thrown an exception on background thread");
            if (ThreadConflictCombinations(nonblocking, nonblocking))
                throw new InvalidOperationException("Should have thrown an exception on background thread");

            if (ThreadConflictCombinations(nonblocking, blocking))
                Console.WriteLine("Background thread timed out");
            if (ThreadConflictCombinations(blocking, blocking))
                Console.WriteLine("Background thread timed out");

            Debug.Assert(true); // Must be reached
        }

        private static bool ThreadConflictCombinations(IEnumerable<char> main, IEnumerable<char> other)
        {
            try
            {
                using (main.GetEnumerator())
                {
                    var bg = new Thread(o =>
                        {
                            try { other.GetEnumerator(); }
                            catch (Exception e) { Report(e); }
                        }) { Name = "background" };
                    bg.Start();

                    bool timedOut = !bg.Join(1000); // observe the thread waiting a full second for a lock (or throw the exception for nonblocking)

                    if (timedOut)
                        bg.Abort();

                    return timedOut;
                }
            } catch
            {
                throw new InvalidProgramException("Cannot be reached");
            }
        }

        static private readonly object ConsoleSynch = new Object();
        private static void Report(Exception e)
        {
            lock (ConsoleSynch)
                Console.WriteLine("Thread:{0}\tException:{1}", Thread.CurrentThread.Name, e);
        }
    }
}

Note 3: I think the implementation of the thread locking (especially around BusyTable) is quite ugly; However, I didn't want to resort to ReaderWriterLock(LockRecursionPolicy.NoRecursion) and didn't want to assume .Net 4.0 for SpinLock


问:
Vue-Owl-Carousel not working when using Loop
Vue-Owl-Carousel workign fine using the basic model :

```<code><carousel>
  <img src="https://placeimg.com/200/200/any?1">
  <img src="https://placeimg.com/200/200/any?2">
  <img src="https://placeimg.com/200/200/any?3">
  <img src="https://placeimg.com/200/200/any?4">
</carousel>
</code>```

But when i use a loop on  , the Carousel broke and shows all slides in column.

```<code><carousel> // Not Working
 <img v-for="slide in slides" :src="getslide(slide)">
</carousel>

<carousel> // Not Working
 <template  v-for="slide in slides"><img :src="getslide(slide)"></template>
</carousel>

<carousel> // Not Working, the error is with v-for..
<img v-for="slide in slides" src="/slide.png">
</carousel>
</code>```

Thank you if you can help.

答:
You can try:</p>

```<code><div v-if="slides.length > 0">
<carousel>
 <img v-for="slide in slides" :src="getslide(slide)">
</carousel>
</div
</code>```

Body:
Vue-Owl-Carousel workign fine using the basic model :

<carousel>

</carousel>

But when i use a loop on  , the Carousel broke and shows all slides in column.

<carousel> // Not Working

</carousel>

<carousel> // Not Working
 <template  v-for="slide in slides"></template>
</carousel>

<carousel> // Not Working, the error is with v-for..

</carousel>

Thank you if you can help.

Body:
You can try:

<div v-if="slides.length > 0">
<carousel>
 <img v-for="slide in slides" :src="getslide(slide)">
</carousel>
</div


问:
How to add SSL certificates to cacerts and keystore?
I created a CSR file using

openssl req -nodes -newkey rsa:2048 -keyout yourdomain.key -out yourdomain.csr –sha256

It created a CSR file and a key file. I submitted the CSR file to a CA.
They responded with a single yourdomain.crt a single file.

I've tried to import the yourdomain.crt to my java's cacert by:

keytool -import -keystore /usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/security/cacerts -file ~/Desktop/user/yourdomain.crt -alias yourdomain

And now I am confused on how to generate a Keystore (jks file). Do I use the same yourdomain.crt?
And what is the command that I should use?

My spring boot program consists of

```<code> File trustStoreFile = new File(CACERTS_PATH);
        File keyStoreFile = new File(JKS_PATH);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyStoreFile), KEY_PASS.toCharArray());
        return SSLContextBuilder.create()
                .useProtocol("TLS")
                .loadKeyMaterial(ks, KEY_PASS.toCharArray())
                .loadTrustMaterial(trustStoreFile, TRUST_PASS.toCharArray())
                .build();
</code>```

So I need a cacerts path which I believe is the cacerts from my jdk, and the password is the one which I typed when prompted for it.

Now how do I generate a Keystore file for it?

And do I need to add the server.ssl properties for Spring boot?

答:
First, You have to convert yourdomain.crt to .p12 Format, to do so, write following command on openssl terminal

```<code>pkcs12 -export -in yourdomain.crt -inkey yourdomain.key -chain -CAfile rootCA.pem -name “localhost” -out my.p12
</code>```

where,
rootCA.pem = you have to create it, for that write following command on openssl,

```<code>step 1 : genrsa -des3 -out rootCA.key 2048 and hit enter

 you will get rootCA.key file.

step 2 : req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem
</code>```

yourdomain.key = you have to create it  by entering following command on openssl,

```<code>req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config
server.csr.cnf
</code>```

where,
 server.csr.cnf file contain this and inside it you can write

```<code>authorityKeyIdentifier = keyid, issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]

DNS.1 = localhost
IP.1=127.0.0.1
IP.2 = 192.168.1.XX
IP.3 = 192.XXX.XX.XXX
IP.4 = 192.XX.XX.XX and soon
</code>```

server.csr and server.key file is created.

After following all the steps , you will get .p12 format file , now you have to convert .p12 file format to keystore.jks file format, to do so write following command on cmd (open in administration mode)

```<code>Keytool -importkeystore -deststorepass MY-KEYSTORE-PASS -destkeystore my-keystore.jks
-srckeystore my.p12 -srcstoretype PKCS12
</code>```

Body:
I created a CSR file using

openssl req -nodes -newkey rsa:2048 -keyout yourdomain.key -out yourdomain.csr –sha256

It created a CSR file and a key file. I submitted the CSR file to a CA.
They responded with a single yourdomain.crt a single file.

I've tried to import the yourdomain.crt to my java's cacert by:

keytool -import -keystore /usr/lib/jvm/java-1.8.0-openjdk-amd64/jre/lib/security/cacerts -file ~/Desktop/user/yourdomain.crt -alias yourdomain

And now I am confused on how to generate a Keystore (jks file). Do I use the same yourdomain.crt?
And what is the command that I should use?

My spring boot program consists of

 File trustStoreFile = new File(CACERTS_PATH);
        File keyStoreFile = new File(JKS_PATH);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyStoreFile), KEY_PASS.toCharArray());
        return SSLContextBuilder.create()
                .useProtocol("TLS")
                .loadKeyMaterial(ks, KEY_PASS.toCharArray())
                .loadTrustMaterial(trustStoreFile, TRUST_PASS.toCharArray())
                .build();

So I need a cacerts path which I believe is the cacerts from my jdk, and the password is the one which I typed when prompted for it.

Now how do I generate a Keystore file for it?

And do I need to add the server.ssl properties for Spring boot?

Body:
First, You have to convert yourdomain.crt to .p12 Format, to do so, write following command on openssl terminal

pkcs12 -export -in yourdomain.crt -inkey yourdomain.key -chain -CAfile rootCA.pem -name “localhost” -out my.p12

where,
rootCA.pem = you have to create it, for that write following command on openssl,

step 1 : genrsa -des3 -out rootCA.key 2048 and hit enter

 you will get rootCA.key file.

step 2 : req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

yourdomain.key = you have to create it  by entering following command on openssl,

req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config
server.csr.cnf

where,
 server.csr.cnf file contain this and inside it you can write

authorityKeyIdentifier = keyid, issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]

DNS.1 = localhost
IP.1=127.0.0.1
IP.2 = 192.168.1.XX
IP.3 = 192.XXX.XX.XXX
IP.4 = 192.XX.XX.XX and soon

server.csr and server.key file is created.

After following all the steps , you will get .p12 format file , now you have to convert .p12 file format to keystore.jks file format, to do so write following command on cmd (open in administration mode)

Keytool -importkeystore -deststorepass MY-KEYSTORE-PASS -destkeystore my-keystore.jks
-srckeystore my.p12 -srcstoretype PKCS12


问:
update nested value of state using dynamic key
I wants to change grade object of state using dynamic key. Below is my code

```<code>state = {
            id1: {
                name: 'XYZ',
                grade: {
                    science: 'A',
                    maths: 'C',
                },
            },
            id2: {
                name: 'ABC',
                grade: {
                    science: 'A+',
                    maths: 'A+',
                },
            },
}
</code>```

I tried couple of things but couldn't found successful result.

```<code>updateGrade(gradeObj, dyamicKey) { // dyamicKey will be id1, id2
    this.setState({
        [dyamicKey]: {
            ... dyamicKey.grade,
            grade: gradeObj,
        },
    });
}

updateGrade(gradeObj, dyamicKey) { // dyamicKey will be id1, id2
    this.setState({
        [dyamicKey[grade]]: gradeObj,
    });
}
</code>```

答:
FYI: this topic was extensively cover here, and even is recommended not to use nested states, according to this answer.

As an extra comment to the first answer and for the ones to come, if you have two or more nested values in your state and you want to update a single nested value, you could do the following:

```<code>this.setState(prevState => ({
  [dynamicKey]: {
  ...prevState[dynamicKey],
  grade: {
    ...prevState[dynamicKey].grade,
    science: "Z"
  },
}));
</code>```

Or, if the dynamic key is related to a specific attribute:

```<code>this.setState(prevState => ({
  id1: {
  ...prevState.id1,
  grade: {
    ...prevState.id1.grade,
    [dynamicKey]: "Z"
  },
}));
</code>```

One or more dynamic keys can be used and the spread operator can be used for each nested level (although the code will start to look ugly/dirty with this approach).

Body:
I wants to change grade object of state using dynamic key. Below is my code

state = {
            id1: {
                name: 'XYZ',
                grade: {
                    science: 'A',
                    maths: 'C',
                },
            },
            id2: {
                name: 'ABC',
                grade: {
                    science: 'A+',
                    maths: 'A+',
                },
            },
}

I tried couple of things but couldn't found successful result.

updateGrade(gradeObj, dyamicKey) { // dyamicKey will be id1, id2
    this.setState({
        [dyamicKey]: {
            ... dyamicKey.grade,
            grade: gradeObj,
        },
    });
}

updateGrade(gradeObj, dyamicKey) { // dyamicKey will be id1, id2
    this.setState({
        [dyamicKey[grade]]: gradeObj,
    });
}

Body:
FYI: this topic was extensively cover here, and even is recommended not to use nested states, according to this answer.

As an extra comment to the first answer and for the ones to come, if you have two or more nested values in your state and you want to update a single nested value, you could do the following:

this.setState(prevState => ({
  [dynamicKey]: {
  ...prevState[dynamicKey],
  grade: {
    ...prevState[dynamicKey].grade,
    science: "Z"
  },
}));

Or, if the dynamic key is related to a specific attribute:

this.setState(prevState => ({
  id1: {
  ...prevState.id1,
  grade: {
    ...prevState.id1.grade,
    [dynamicKey]: "Z"
  },
}));

One or more dynamic keys can be used and the spread operator can be used for each nested level (although the code will start to look ugly/dirty with this approach).


问:
What happens when a previously "FETCHED" url is removed on the web server side and StormCrawler goes to it again?
We have lots of sites being updated, added, and deleted. I'm curious as to how Stormcrawler handles a site with a url that has been previously "FETCHED", when the next time SC reaches it it has been removed and either generates a redirect or a 404.  What happens to the content that is from the old version of the page, in the "Index" index?

I know the url in the "Status" index probably changes to "REDIRECTION" or "FETCH ERROR" or something, but what about the content itself? Is it deleted? Is it left?  I am trying to figure out how SC reacts here and if I have to work at cleaning up these orphaned docs in the "Index" index.

I would expect SC to delete the content if it's no longer there, but I thought I would ask to be sure.

答:
As you pointed out, a missing URL will get a FETCH_ERROR status, which after being retried a number of times (param max.fetch.errors - default 3) will turn into an ERROR status.

The content will be deleted if you connect a DeletionBolt to the status updater, see example topology.


问:
Best way to add comments in erb
How do we add comments in erb files, if we do not want them to be generated into the html content? </p>

答:
In my text editor, i run command + / (sublime-text shortcut). It will be like this.

```<code><%
=begin%>
    Here is the comment
<%
=end%>
</code>```

It doesn't look simply, but it works.

Title: Best way to add comments in erb

Body:
In my text editor, i run command + / (sublime-text shortcut). It will be like this.

<%
=begin%>
    Here is the comment
<%
=end%>

It doesn't look simply, but it works.


问:
Unable to reuse port when forcibly killing and re-spawning a TCP Socket application
I have an application that acts as a watchdog for another application. The duty of the watchdog is to monitor the host application existence and respawn it whenever it dies.

Below is the socket code:

```<code>sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
    return (-1);
}

int optval = 1;
struct timeval tv;
tv.tv_sec = SOC_READ_TIMEOUT;
tv.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*) &tv, sizeof(tv));

tv.tv_sec = SOC_READ_TIMEOUT;
tv.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*) &tv, sizeof(tv));
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (int*) &optval,
        sizeof(int));

name.sin_family = AF_INET;
name.sin_port = htons(port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (sockaddr *) &name, sizeof(name)) < 0) {
    close(sock);
    return (-1);
}
</code>```

The problem I am facing is that whenever I kill the host application instance. The new instance gives an error "Cannot assign requested address". I believe this is occurring because the Raspbian OS doesn't support SO_REUSEPORT.

Is there any way, I can work this out? Any suggestion is welcome.

答: Thanks, Tony, and super. Seems like the host application had multiple instances spawned by the watchdog process and that's why the issue was occurring. Have resolved it.</p>

Body:
I have an application that acts as a watchdog for another application. The duty of the watchdog is to monitor the host application existence and respawn it whenever it dies.

Below is the socket code:

sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
    return (-1);
}

int optval = 1;
struct timeval tv;
tv.tv_sec = SOC_READ_TIMEOUT;
tv.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*) &tv, sizeof(tv));

tv.tv_sec = SOC_READ_TIMEOUT;
tv.tv_usec = 0;
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*) &tv, sizeof(tv));
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (int*) &optval,
        sizeof(int));

name.sin_family = AF_INET;
name.sin_port = htons(port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (sockaddr *) &name, sizeof(name)) < 0) {
    close(sock);
    return (-1);
}

The problem I am facing is that whenever I kill the host application instance. The new instance gives an error "Cannot assign requested address". I believe this is occurring because the Raspbian OS doesn't support SO_REUSEPORT.

Is there any way, I can work this out? Any suggestion is welcome.


问:
ReflectionException Class emails does not exist php artisan queue:work
when I do php artisan queue:work I'm getting error

ReflectionException        Class emails does not exist

答:
Make sure to update composer.

or try this - delete vendor folder and run.

```<code>composer update
</code>```

Body:
Make sure to update composer.

or try this - delete vendor folder and run.

composer update


问:
Why handle clicking on TableView Swift IOS worth cell rows are the previous rows clicked?
I already the TableView for displaying JSON Values from API. But the result of the click does not match the existing title, but it is worth the title from the previous click. More clearly see the picture

Code InfoViewCell.swift
This code for cell in tableview

```<code>import UIKit

class InfoViewCell: UITableViewCell {
    @IBOutlet weak var imgInfo: UIImageView!
    @IBOutlet weak var lblInfo: UILabel!
    @IBOutlet weak var lblBerita: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

</code>```

Code Info.swift this code for models

```<code>class Info {

    var id_informasi: Int?
    var tgl_informasi: String?
    var judul: String?
    var berita: String?
    var foto: String?

    init(id_informasi:Int?,judul: String?,berita: String?,foto: String?) {
        self.id_informasi = id_informasi
        self.judul = judul
        self.berita = berita
        self.foto = foto
    }
}

</code>```

Code InfoViewController.swift

```<code>import UIKit
import Alamofire
import AlamofireImage

class InformasiViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tableInfo: UITableView!
    var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()

    var infoes = [Info]()

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return infoes.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellInfo", for: indexPath) as! InfoViewCell

        //getting the hero for the specified position
        let inpo: Info
        inpo = infoes[indexPath.row]

        //displaying values
        cell.lblInfo.text = inpo.judul
        cell.lblBerita.text = inpo.berita

        //displaying image
        Alamofire.request(inpo.foto!).responseImage { response in
            debugPrint(response)

            if let image = response.result.value {
                cell.imgInfo.image = image
            }
        }

        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

        let info: Info
        info  = infoes[indexPath.row]

        //building an alert
        let alertController = UIAlertController(title: info.judul, message: "", preferredStyle: .alert)

        //the confirm action taking the inputs
        let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in

        }

        //the cancel action doing nothing
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

        //adding action
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)

        //presenting dialog
        present(alertController, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let defaultValues = UserDefaults.standard
        let token = defaultValues.string(forKey: "token")

        //the Web API URL
        let URL_GET_DATA = "https://api.landslidepad.com/api/admin_desa/informasi_penting?token=" + token!

        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.style = UIActivityIndicatorView.Style.gray
        view.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        //fetching data from web api
        Alamofire.request(URL_GET_DATA, method: .get).responseJSON
            {

                response in
                //printing response
                print(response)

                self.activityIndicator.stopAnimating()
                //getting the json value from the server
                if let result = response.result.value {

                    let jsonData = result as! NSDictionary

                    //if there is no error
                    if((jsonData.value(forKey: "message") as! String == "Sukses!")){

                        //getting the user from response
                        let user = jsonData.value(forKey: "values") as! NSArray

                        for i in 0..<user.count{

                            //adding hero values to the hero list
                            self.infoes.append(Info(
                                id_informasi: (user[i] as AnyObject).value(forKey: "id_informasi") as? Int,
                                judul: (user[i] as AnyObject).value(forKey: "judul") as? String,
                                berita: (user[i] as AnyObject).value(forKey: "berita") as? String,
                                foto: (user[i] as AnyObject).value(forKey: "foto") as? String
                            ))
                        }
                        //displaying data in tableview
                        self.tableInfo.reloadData()

                    }else{
                        let alert = UIAlertController(title: "Ada yang salah?", message: "Silahkan Ulangi Kembali!.", preferredStyle: .alert)

                        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: nil))
                        alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))

                        self.present(alert, animated: true)
                    }
                }
        }

        self.tableInfo.reloadData()
        // Do any additional setup after loading the view, typically from a nib.

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

</code>```

I already tried to create func tableview didDeselectRowAt indexPath,
but the value I want to display is not in line with my expectations. I will pass this value to the detailed view

Thanks

答: When you click on a row, that row is selected — and the previous selected row is deselected. Well, you have implemented didDeselect, so the previous selected row is displayed. Instead, implement didSelect.

Body:
I already the TableView for displaying JSON Values from API. But the result of the click does not match the existing title, but it is worth the title from the previous click. More clearly see the picture

Code InfoViewCell.swift
This code for cell in tableview

import UIKit

class InfoViewCell: UITableViewCell {
    @IBOutlet weak var imgInfo: UIImageView!
    @IBOutlet weak var lblInfo: UILabel!
    @IBOutlet weak var lblBerita: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Code Info.swift this code for models

class Info {

    var id_informasi: Int?
    var tgl_informasi: String?
    var judul: String?
    var berita: String?
    var foto: String?

    init(id_informasi:Int?,judul: String?,berita: String?,foto: String?) {
        self.id_informasi = id_informasi
        self.judul = judul
        self.berita = berita
        self.foto = foto
    }
}

Code InfoViewController.swift

import UIKit
import Alamofire
import AlamofireImage

class InformasiViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tableInfo: UITableView!
    var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()

    var infoes = [Info]()

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return infoes.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellInfo", for: indexPath) as! InfoViewCell

        //getting the hero for the specified position
        let inpo: Info
        inpo = infoes[indexPath.row]

        //displaying values
        cell.lblInfo.text = inpo.judul
        cell.lblBerita.text = inpo.berita

        //displaying image
        Alamofire.request(inpo.foto!).responseImage { response in
            debugPrint(response)

            if let image = response.result.value {
                cell.imgInfo.image = image
            }
        }

        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {

        let info: Info
        info  = infoes[indexPath.row]

        //building an alert
        let alertController = UIAlertController(title: info.judul, message: "", preferredStyle: .alert)

        //the confirm action taking the inputs
        let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in

        }

        //the cancel action doing nothing
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

        //adding action
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)

        //presenting dialog
        present(alertController, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let defaultValues = UserDefaults.standard
        let token = defaultValues.string(forKey: "token")

        //the Web API URL
        let URL_GET_DATA = "https://api.landslidepad.com/api/admin_desa/informasi_penting?token=" + token!

        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.style = UIActivityIndicatorView.Style.gray
        view.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        //fetching data from web api
        Alamofire.request(URL_GET_DATA, method: .get).responseJSON
            {

                response in
                //printing response
                print(response)

                self.activityIndicator.stopAnimating()
                //getting the json value from the server
                if let result = response.result.value {

                    let jsonData = result as! NSDictionary

                    //if there is no error
                    if((jsonData.value(forKey: "message") as! String == "Sukses!")){

                        //getting the user from response
                        let user = jsonData.value(forKey: "values") as! NSArray

                        for i in 0..<user.count{

                            //adding hero values to the hero list
                            self.infoes.append(Info(
                                id_informasi: (user[i] as AnyObject).value(forKey: "id_informasi") as? Int,
                                judul: (user[i] as AnyObject).value(forKey: "judul") as? String,
                                berita: (user[i] as AnyObject).value(forKey: "berita") as? String,
                                foto: (user[i] as AnyObject).value(forKey: "foto") as? String
                            ))
                        }
                        //displaying data in tableview
                        self.tableInfo.reloadData()

                    }else{
                        let alert = UIAlertController(title: "Ada yang salah?", message: "Silahkan Ulangi Kembali!.", preferredStyle: .alert)

                        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: nil))
                        alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))

                        self.present(alert, animated: true)
                    }
                }
        }

        self.tableInfo.reloadData()
        // Do any additional setup after loading the view, typically from a nib.

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I already tried to create func tableview didDeselectRowAt indexPath,
but the value I want to display is not in line with my expectations. I will pass this value to the detailed view

Thanks