问:
No provider for Platform
So I have come across this issue making a unit test for an Angular 4 application

What happens is that it keeps giving the error stated here in the question title.

I tried to google it, tried to import a whole bunch of different modules and finally found that a close answer to what this "Platform" is might be the browserModule from @angular/browser Platform.

So in my unit testing, I tried to import it and declare it but it did not help.

Can anyone please help with this as I'm not even sure what this "Platform" is?

Question: what is exactly this "Platform" in the error and how to fix it?

Thanks.

I have attached my code as below:

```<code>import { ComponentFixture, TestBed, async} from "@angular/core/testing";
import { DebugElement, CUSTOM_ELEMENTS_SCHEMA, PlatformRef} from
"@angular/core";
import { TeamCreationAssignmentComponent } from "./team-creation-assignment.component";
import { OdmService } from "../../services/odm/odm.service";
import { UserNotificationService } from "../../services/user/user-notification.service";
import { MatSnackBar } from "@angular/material";
import { OVERLAY_PROVIDERS, ScrollStrategyOptions, ScrollDispatcher} from "@angular/cdk/overlay";

describe('Team creation assignment component', () => {
let comp: TeamCreationAssignmentComponent;
let fixture: ComponentFixture<TeamCreationAssignmentComponent>;

let odmServiceSub = {};

beforeEach(async(() => {
    TestBed.configureTestingModule({

        declarations: [TeamCreationAssignmentComponent],
        //imports: [BrowserModule],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [
            {provide: OdmService, useValue: odmServiceSub},
            UserNotificationService,
            MatSnackBar,
            OVERLAY_PROVIDERS,
            ScrollStrategyOptions,
            ScrollDispatcher,
        ],
    })
    .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(TeamCreationAssignmentComponent);
    comp = fixture.componentInstance;
});

it('should have defined component', () => {
    expect(comp).toBeDefined();
})
</code>```

});

答:
Whenever you get a message that there is "No provider for XXX" it generally means that you are missing something from the providers array in the configureTestingModule method. Have you tried adding PlatformRef to the providers array? Like this:

```<code>providers: [
    {provide: OdmService, useValue: odmServiceSub},
    UserNotificationService,
    MatSnackBar,
    OVERLAY_PROVIDERS,
    ScrollStrategyOptions,
    ScrollDispatcher,
    PlatformRef // <- added here
],
</code>```

One thing you are missing however is a call to detectChanges in your second beforeEach, it should look like this:

```<code>beforeEach(() => {
    fixture = TestBed.createComponent(TeamCreationAssignmentComponent);
    comp = fixture.componentInstance;
    fixture.detectChanges(); // <- this is required
});
</code>```

One thing I will say is that in my Angular 4 app, there are around 800 unit tests, and not a single one of them uses or requires this PlatformRef. I think the issue is the missing detectChanges rather than anything to do with this "platform".

Title: No provider for Platform

Body:
So I have come across this issue making a unit test for an Angular 4 application

What happens is that it keeps giving the error stated here in the question title.

I tried to google it, tried to import a whole bunch of different modules and finally found that a close answer to what this "Platform" is might be the browserModule from @angular/browser Platform.

So in my unit testing, I tried to import it and declare it but it did not help.

Can anyone please help with this as I'm not even sure what this "Platform" is?

Question: what is exactly this "Platform" in the error and how to fix it?

Thanks.

I have attached my code as below:

import { ComponentFixture, TestBed, async} from "@angular/core/testing";
import { DebugElement, CUSTOM_ELEMENTS_SCHEMA, PlatformRef} from
"@angular/core";
import { TeamCreationAssignmentComponent } from "./team-creation-assignment.component";
import { OdmService } from "../../services/odm/odm.service";
import { UserNotificationService } from "../../services/user/user-notification.service";
import { MatSnackBar } from "@angular/material";
import { OVERLAY_PROVIDERS, ScrollStrategyOptions, ScrollDispatcher} from "@angular/cdk/overlay";

describe('Team creation assignment component', () => {
let comp: TeamCreationAssignmentComponent;
let fixture: ComponentFixture<TeamCreationAssignmentComponent>;

let odmServiceSub = {};

beforeEach(async(() => {
    TestBed.configureTestingModule({

        declarations: [TeamCreationAssignmentComponent],
        //imports: [BrowserModule],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [
            {provide: OdmService, useValue: odmServiceSub},
            UserNotificationService,
            MatSnackBar,
            OVERLAY_PROVIDERS,
            ScrollStrategyOptions,
            ScrollDispatcher,
        ],
    })
    .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(TeamCreationAssignmentComponent);
    comp = fixture.componentInstance;
});

it('should have defined component', () => {
    expect(comp).toBeDefined();
})

});

Body:
Whenever you get a message that there is "No provider for XXX" it generally means that you are missing something from the providers array in the configureTestingModule method. Have you tried adding PlatformRef to the providers array? Like this:

providers: [
    {provide: OdmService, useValue: odmServiceSub},
    UserNotificationService,
    MatSnackBar,
    OVERLAY_PROVIDERS,
    ScrollStrategyOptions,
    ScrollDispatcher,
    PlatformRef // <- added here
],

One thing you are missing however is a call to detectChanges in your second beforeEach, it should look like this:

beforeEach(() => {
    fixture = TestBed.createComponent(TeamCreationAssignmentComponent);
    comp = fixture.componentInstance;
    fixture.detectChanges(); // <- this is required
});

One thing I will say is that in my Angular 4 app, there are around 800 unit tests, and not a single one of them uses or requires this PlatformRef. I think the issue is the missing detectChanges rather than anything to do with this "platform".


来源: stackexchange

问:
ActiveHash with negation
I have a class:

```<code>class Foo < ActiveHash::Base
  ...
end
</code>```

I want to query for the negation on some property. If it were a subclass of ActiveRecord, then it is possible to do:

```<code>Foo.where.not(some_property: ["foo", "bar"])
</code>```

But this raises an error for ActiveHash. How can I do this?

答: Well this line should work, can you submit the error that you are receiving?</p>

ContentLicense: CC BY-SA 3.0

Title: ActiveHash with negation

Body:
I have a class:

class Foo < ActiveHash::Base
  ...
end

I want to query for the negation on some property. If it were a subclass of ActiveRecord, then it is possible to do:

Foo.where.not(some_property: ["foo", "bar"])

But this raises an error for ActiveHash. How can I do this?


问:
Divide results in two columns depending on the input values? SQL Server
I am using the Nortwind database with SQL Server 2014, I try to make a query to divide the results of the orders in two different years, The format that I want in my query is

```<code>category |anio one | anio two
</code>```

where the years may vary , What I try so far is

```<code>SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;
</code>```

This gives me the totals of each category for a different year, 1996-1997-1998 in column  YEAR(o.OrderDate)

I want to get for example

```<code>CategoryName | 1996 | 1997

Beverages   |53879,20 | 110424,00
Condiments  |19458,30 | 59679,00
....
</code>```

答:
Use "conditional aggregates".

```<code>SELECT
      ca.CategoryName
    , SUM(case when year(o.OrderDate) = 1996 then ot.UnitPrice * ot.Quantity end) AS total_1996
    , SUM(case when year(o.OrderDate) = 1997 then ot.UnitPrice * ot.Quantity end) AS total_1997
FROM Orders o
INNER JOIN [Order Details] ot ON o.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
where o.OrderDate >= '19960101' and o.OrderDate < '19980101'
GROUP BY
      ca.CategoryName
ORDER BY
      ca.CategoryName
</code>```

Basically that means use a case expression inside the aggregate function.

I case you are wondering why I have not used "between in the where clause: see
Bad habits to kick : mis-handling date / range queries

Body:
I am using the Nortwind database with SQL Server 2014, I try to make a query to divide the results of the orders in two different years, The format that I want in my query is

category |anio one | anio two

where the years may vary , What I try so far is

SELECT ca.CategoryName , YEAR(o.OrderDate), SUM(ot.UnitPrice*ot.Quantity) as total
FROM Orders o
INNER JOIN [Order Details] ot ON O.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
GROUP BY ca.CategoryName,YEAR(o.OrderDate)
ORDER BY ca.CategoryName;

This gives me the totals of each category for a different year, 1996-1997-1998 in column  YEAR(o.OrderDate)

I want to get for example

CategoryName | 1996 | 1997

Beverages   |53879,20 | 110424,00
Condiments  |19458,30 | 59679,00
....

Body:
Use "conditional aggregates".

SELECT
      ca.CategoryName
    , SUM(case when year(o.OrderDate) = 1996 then ot.UnitPrice * ot.Quantity end) AS total_1996
    , SUM(case when year(o.OrderDate) = 1997 then ot.UnitPrice * ot.Quantity end) AS total_1997
FROM Orders o
INNER JOIN [Order Details] ot ON o.OrderID = ot.OrderID
INNER JOIN Products pro ON ot.ProductID = pro.ProductID
INNER JOIN Categories ca ON pro.CategoryID = ca.CategoryID
where o.OrderDate >= '19960101' and o.OrderDate < '19980101'
GROUP BY
      ca.CategoryName
ORDER BY
      ca.CategoryName

Basically that means use a case expression inside the aggregate function.

I case you are wondering why I have not used "between in the where clause: see
Bad habits to kick : mis-handling date / range queries

ContentLicense: CC BY-SA 4.0


问:
Hiding scrollbars via css doesn't work in Safari, how to fix it?
I'm trying to hide scrollbars of an html element by means of the CSS rule:

```<code>.element::-webkit-scrollbar {width: 0;}
</code>```

It works fine in Chrome, but doesn't work in Safari, although is't also webkit-based and should support this rule.

Any ideas, why should it happen and how to fix?

答:
You should also add this :

```<code>.element::-webkit-scrollbar {
    -webkit-appearance: none;
}
</code>```

Also check this answer. Useful Hiding the scrollbar on an HTML page

Body:
I'm trying to hide scrollbars of an html element by means of the CSS rule:

.element::-webkit-scrollbar {width: 0;}

It works fine in Chrome, but doesn't work in Safari, although is't also webkit-based and should support this rule.

Any ideas, why should it happen and how to fix?

Body:
You should also add this :

.element::-webkit-scrollbar {
    -webkit-appearance: none;
}

Also check this answer. Useful Hiding the scrollbar on an HTML page


问:
Why can't Anko ignore the passed value of _id when _id is INTEGER + PRIMARY_KEY+ AUTOINCREMENT?
I have designed the _id field is INTEGER + PRIMARY_KEY+ AUTOINCREMENT, I use the code SettingManage().addSetting(MSetting(10L,"My Settings",2000L,"This is description!")) to insert a record to the table.

I think Anko will ignore the passed value 10 of _id and pass a new value to _id  automatically, but in fact the value 10 of _id is inserted into the table.

How can make Anko ignore the passed value of _id when _id is INTEGER + PRIMARY_KEY+ AUTOINCREMENT ?

Insert Data

```<code>SettingManage().addSetting(MSetting(10L,"My Settings",2000L,"This is description!"))
</code>```

Design Table

```<code>    class DBSettingHelper(mContext: Context = UIApp.instance) : ManagedSQLiteOpenHelper(
            mContext,
            DB_NAME,
            null,
            DB_VERSION) {

        companion object {
            val DB_NAME = "setting.db"
            val DB_VERSION = 5
            val instance by lazy { DBSettingHelper() }
        }

        override fun onCreate(db: SQLiteDatabase) {
            db.createTable( DBSettingTable.TableNAME , true,
                    DBSettingTable._ID to INTEGER + PRIMARY_KEY+ AUTOINCREMENT ,
                    DBSettingTable.Name to TEXT,
                    DBSettingTable.CreatedDate to INTEGER,
                    DBSettingTable.Description to TEXT
            )
        }

        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
            db.dropTable(DBSettingTable.TableNAME, true)
            onCreate(db)
        }

    }

    class DBSetting(val mMutableMap: MutableMap<String, Any?>) {
        var _id: Long by mMutableMap
        var name: String by mMutableMap
        var createdDate: Long by mMutableMap
        var description: String by mMutableMap

        constructor(_id: Long, name: String, createdDate: Long, description: String)
                : this(HashMap()) {
            this._id = _id
            this.name = name
            this.createdDate = createdDate
            this.description=description
        }
    }

    object DBSettingTable {
        val TableNAME = "SettingTable"

        val _ID = "_id"
        val Name = "name"
        val CreatedDate = "createdDate"
        val Description="description"
    }

   data class MSetting (
        val _id: Long,
        val name: String,
        val createdDate: Long,
        val description: String
   )
</code>```

Business Logic

```<code>class SettingManage {
    fun addSetting(mMSetting:MSetting){
        DBSettingManage().addDBSetting(DbDataMapper().convertMSetting_To_DBSetting(mMSetting))
    }
}

class DBSettingManage(private val mDBSettingHelper: DBSettingHelper =DBSettingHelper.instance) {
    fun addDBSetting(mDBSetting: DBSetting)=mDBSettingHelper.use{
        insert(DBSettingTable.TableNAME,*mDBSetting.mMutableMap.toVarargArray())
    }
}

class DbDataMapper {
    fun convertMSetting_To_DBSetting(mMSetting: MSetting) =with(mMSetting){
        DBSetting(_id,name,createdDate,description)
    }
    fun convertDBSetting_To_MSetting(mDBSetting: DBSetting)=with(mDBSetting){
        MSetting(_id,name,createdDate,description )
    }
}

fun <T : Any> SelectQueryBuilder.parseList(parser: (Map<String, Any?>) -> T): List<T> =
        parseList(object : MapRowParser<T> {
            override fun parseRow(columns: Map<String, Any?>): T = parser(columns)
        })
</code>```

答:
Anko, in your usage, is a wrapper for SQLite. SQL itself overrides auto increment when a custom value is passed. If no value is passed -> Automatic value. Otherwise -> manual. It assumes it's unique because of PRIMARY_KEY, but that's a different problem.

As far as I know, there is no integrated feature into Anko that allows for overriding this manually. Instead, the only thing you can do is not pass a value. Any SQL query that's wrong won't be caught by Anko itself, but by the raw SQL. It's SQL that throws any exceptions meaning Anko won't check for missing data.

Simply, don't pass an ID. You can write a function that still takes in the ID but discards it if the row is set to PRIMARY_KEY and AUTO_INCREMENT.

I have done more digging in the source code and there's no support for ignoring passed values if it's set to auto increment.

This means the only way you can get it to actually automatically increment is by not passing any values. If you are using manual queries of any kind, you simply don't pass any value. So, don't give the database the ID. Because it's auto increment it'll automatically add it and that's on the base SQL level.

Ank doesn't ignore it by default because it's essentially a wrapper for SQLite. Meaning it has to be able to be passed if the ID should be overridden (see the link in the second sentence of this answer). As such, Anko ignoring it would cause more problems than it'd do good. You have to make sure it isn't passed instead

Body:
I have designed the _id field is INTEGER + PRIMARY_KEY+ AUTOINCREMENT, I use the code SettingManage().addSetting(MSetting(10L,"My Settings",2000L,"This is description!")) to insert a record to the table.

I think Anko will ignore the passed value 10 of _id and pass a new value to _id  automatically, but in fact the value 10 of _id is inserted into the table.

How can make Anko ignore the passed value of _id when _id is INTEGER + PRIMARY_KEY+ AUTOINCREMENT ?

Insert Data

SettingManage().addSetting(MSetting(10L,"My Settings",2000L,"This is description!"))

Design Table

    class DBSettingHelper(mContext: Context = UIApp.instance) : ManagedSQLiteOpenHelper(
            mContext,
            DB_NAME,
            null,
            DB_VERSION) {

        companion object {
            val DB_NAME = "setting.db"
            val DB_VERSION = 5
            val instance by lazy { DBSettingHelper() }
        }

        override fun onCreate(db: SQLiteDatabase) {
            db.createTable( DBSettingTable.TableNAME , true,
                    DBSettingTable._ID to INTEGER + PRIMARY_KEY+ AUTOINCREMENT ,
                    DBSettingTable.Name to TEXT,
                    DBSettingTable.CreatedDate to INTEGER,
                    DBSettingTable.Description to TEXT
            )
        }

        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
            db.dropTable(DBSettingTable.TableNAME, true)
            onCreate(db)
        }

    }

    class DBSetting(val mMutableMap: MutableMap<String, Any?>) {
        var _id: Long by mMutableMap
        var name: String by mMutableMap
        var createdDate: Long by mMutableMap
        var description: String by mMutableMap

        constructor(_id: Long, name: String, createdDate: Long, description: String)
                : this(HashMap()) {
            this._id = _id
            this.name = name
            this.createdDate = createdDate
            this.description=description
        }
    }

    object DBSettingTable {
        val TableNAME = "SettingTable"

        val _ID = "_id"
        val Name = "name"
        val CreatedDate = "createdDate"
        val Description="description"
    }

   data class MSetting (
        val _id: Long,
        val name: String,
        val createdDate: Long,
        val description: String
   )

Business Logic

class SettingManage {
    fun addSetting(mMSetting:MSetting){
        DBSettingManage().addDBSetting(DbDataMapper().convertMSetting_To_DBSetting(mMSetting))
    }
}

class DBSettingManage(private val mDBSettingHelper: DBSettingHelper =DBSettingHelper.instance) {
    fun addDBSetting(mDBSetting: DBSetting)=mDBSettingHelper.use{
        insert(DBSettingTable.TableNAME,*mDBSetting.mMutableMap.toVarargArray())
    }
}

class DbDataMapper {
    fun convertMSetting_To_DBSetting(mMSetting: MSetting) =with(mMSetting){
        DBSetting(_id,name,createdDate,description)
    }
    fun convertDBSetting_To_MSetting(mDBSetting: DBSetting)=with(mDBSetting){
        MSetting(_id,name,createdDate,description )
    }
}

fun <T : Any> SelectQueryBuilder.parseList(parser: (Map<String, Any?>) -> T): List<T> =
        parseList(object : MapRowParser<T> {
            override fun parseRow(columns: Map<String, Any?>): T = parser(columns)
        })


问:
Error Returning Value From Switch Case?
after coding a custom event in AS3, i've come across a curious problem:

```<code>override public function toString():String
    {
    switch  (type)
            {
            case CHANGE:    return formatToString("HistoryEvent", "type", "action", "name", "data");
            case ABILITY:   return formatToString("HistoryEvent", "type", "undoable", "redoable");
            }
    }
</code>```

the above code returns the following compile-time error:

1170: Function does not return a
  value.

i can remedy the problem easily by adding return null; at the end of the function, but that's redundant and it annoys me that it seems to be the only solution.

why is returning a value from a switch case not seen by the compiler?  is this an issue specific to the AS3 compiler or am i actually attempting something here that is so completely dangerous and adverse that it shadows counterculturists the world over.

答: It is possible that your switch doesn't match, and in that case the function can't return anything. That's why the compiler complains. Adding default: return null; to your switch statement solves the problem as well as adding return null at the end of your function.

ContentLicense: CC BY-SA 2.5

Title: Error Returning Value From Switch Case?

Body:
after coding a custom event in AS3, i've come across a curious problem:

override public function toString():String
    {
    switch  (type)
            {
            case CHANGE:    return formatToString("HistoryEvent", "type", "action", "name", "data");
            case ABILITY:   return formatToString("HistoryEvent", "type", "undoable", "redoable");
            }
    }

the above code returns the following compile-time error:

1170: Function does not return a
  value.

i can remedy the problem easily by adding return null; at the end of the function, but that's redundant and it annoys me that it seems to be the only solution.

why is returning a value from a switch case not seen by the compiler?  is this an issue specific to the AS3 compiler or am i actually attempting something here that is so completely dangerous and adverse that it shadows counterculturists the world over.


问:
asp.net core how to add claims to User
I am using ASP.NET Core 2.0, with Azure AD v2.0 endpoint.
I am getting claims like this:

```<code>var currentUser = User;

var displayName = currentUser.FindFirst("name").Value;
var claims = currentUser.Claims;
</code>```

I am not used to using this User to get claims, but could not get the old way with System.Security.Claims to work. So my first question is, is this how I should be getting my claims? And my second question is, how do I add claims to this User?

答:
is this how I should be getting my claims?

AFAIK, you could leverage ControllerBase.HttpContext.User or ControllerBase.User for retrieving the System.Security.Claims.ClaimsPrincipal for current user. Details you could follow the similar issue1 and issue2.

And my second question is, how do I add claims to this User?

As you said you are using ASP.NET Core 2.0, with Azure AD v2.0. I assumed that when using UseOpenIdConnectAuthentication, you could add the additional claims under OnTokenValidated as follows:

```<code>app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["AzureAD:ClientId"],
    Authority = string.Format(CultureInfo.InvariantCulture, Configuration["AzureAd:AadInstance"], "common", "/v2.0"),
    ResponseType = OpenIdConnectResponseType.IdToken,
    PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
    Events = new OpenIdConnectEvents
    {
        OnRemoteFailure = RemoteFailure,
        OnTokenValidated = TokenValidated
    },
    TokenValidationParameters = new TokenValidationParameters
    {
        // Instead of using the default validation (validating against
        // a single issuer value, as we do in line of business apps),
        // we inject our own multitenant validation logic
        ValidateIssuer = false,

        NameClaimType = "name"
    }
});

private Task TokenValidated(TokenValidatedContext context)
{
    /* ---------------------
    // Replace this with your logic to validate the issuer/tenant
        ---------------------
    // Retriever caller data from the incoming principal
    string issuer = context.SecurityToken.Issuer;
    string subject = context.SecurityToken.Subject;
    string tenantID = context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

    // Build a dictionary of approved tenants
    IEnumerable<string> approvedTenantIds = new List<string>
    {
        "<Your tenantID>",
        "9188040d-6c67-4c5b-b112-36a304b66dad" // MSA Tenant
    };
    o
    if (!approvedTenantIds.Contains(tenantID))
        throw new SecurityTokenValidationException();
        --------------------- */

    var claimsIdentity=(ClaimsIdentity)context.Ticket.Principal.Identity;
    //add your custom claims here
    claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));

    return Task.FromResult(0);
}
</code>```

Then, I used the following code to retrieve the user claims:

```<code>public IActionResult UserInfo()
{
    return Json(User.Claims.Select(c=>new {type=c.Type,value=c.Value}).ToList());
}
</code>```

Test:

Moreover, you could refer to this sample Integrating Azure AD (v2.0 endpoint) into an ASP.NET Core web app.

Title: asp.net core how to add claims to User

Body:
I am using ASP.NET Core 2.0, with Azure AD v2.0 endpoint.
I am getting claims like this:

var currentUser = User;

var displayName = currentUser.FindFirst("name").Value;
var claims = currentUser.Claims;

I am not used to using this User to get claims, but could not get the old way with System.Security.Claims to work. So my first question is, is this how I should be getting my claims? And my second question is, how do I add claims to this User?

Body:
is this how I should be getting my claims?

AFAIK, you could leverage ControllerBase.HttpContext.User or ControllerBase.User for retrieving the System.Security.Claims.ClaimsPrincipal for current user. Details you could follow the similar issue1 and issue2.

And my second question is, how do I add claims to this User?

As you said you are using ASP.NET Core 2.0, with Azure AD v2.0. I assumed that when using UseOpenIdConnectAuthentication, you could add the additional claims under OnTokenValidated as follows:

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["AzureAD:ClientId"],
    Authority = string.Format(CultureInfo.InvariantCulture, Configuration["AzureAd:AadInstance"], "common", "/v2.0"),
    ResponseType = OpenIdConnectResponseType.IdToken,
    PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
    Events = new OpenIdConnectEvents
    {
        OnRemoteFailure = RemoteFailure,
        OnTokenValidated = TokenValidated
    },
    TokenValidationParameters = new TokenValidationParameters
    {
        // Instead of using the default validation (validating against
        // a single issuer value, as we do in line of business apps),
        // we inject our own multitenant validation logic
        ValidateIssuer = false,

        NameClaimType = "name"
    }
});

private Task TokenValidated(TokenValidatedContext context)
{
    /* ---------------------
    // Replace this with your logic to validate the issuer/tenant
        ---------------------
    // Retriever caller data from the incoming principal
    string issuer = context.SecurityToken.Issuer;
    string subject = context.SecurityToken.Subject;
    string tenantID = context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

    // Build a dictionary of approved tenants
    IEnumerable<string> approvedTenantIds = new List<string>
    {
        "<Your tenantID>",
        "9188040d-6c67-4c5b-b112-36a304b66dad" // MSA Tenant
    };
    o
    if (!approvedTenantIds.Contains(tenantID))
        throw new SecurityTokenValidationException();
        --------------------- */

    var claimsIdentity=(ClaimsIdentity)context.Ticket.Principal.Identity;
    //add your custom claims here
    claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));

    return Task.FromResult(0);
}

Then, I used the following code to retrieve the user claims:

public IActionResult UserInfo()
{
    return Json(User.Claims.Select(c=>new {type=c.Type,value=c.Value}).ToList());
}

Test:

Moreover, you could refer to this sample Integrating Azure AD (v2.0 endpoint) into an ASP.NET Core web app.


问:
Ansible: Can I execute role from command line?
Suppose I have a role called "apache"

Now I want to execute that role on host 192.168.0.10 from the command line from Ansible host

```<code>ansible-playbook -i  "192.168.0.10" --role  "path to role"
</code>```

Is there a way to do that?

答:
I have written a small Ansible plugin, called auto_tags, that dynamically generates for each role in your playbook a tag of the same name. You can find it here.

After installing it (instructions are in the gist above) you could then execute a specific role with:

ansible-playbook -i  "192.168.0.10" --tags "name_of_role"

Body:
Suppose I have a role called "apache"

Now I want to execute that role on host 192.168.0.10 from the command line from Ansible host

ansible-playbook -i  "192.168.0.10" --role  "path to role"

Is there a way to do that?


问:
Create file failed from mkdir()
I try to create file in my android emulator, but when i finish my code.
I can't find the file i create from android device monitor.

Here is my code:

```<code>try {
    if (Environment.getExternalStorageState()
            .equals(Environment.MEDIA_MOUNTED)) {
        System.out.println("can be read and write");
        File sdFile = android.os.Environment.getExternalStorageDirectory();

        //String path = sdFile.getPath() + File.separator + "DestPdf";
        String path = sdFile.getPath() + "/demos/file/tmp/test";
        File dirFile = new File(path);

        if (!dirFile.exists()) { // if file doesn't exist
            System.out.println("create file");
            dirFile.mkdir(); // create file
            System.out.println(dirFile.toString());
        }
    }
} catch (Exception ex) {
    ex.toString();
}
</code>```

I also add some permissions:

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
</code>```

Here is my print out, i can see the root /storage/sdcard/demos/file/tmp/test

```<code>11-17 08:38:10.263 15501-15501/? I/System.out: can be read and write
11-17 08:38:10.263 15501-15501/? I/System.out: create file
11-17 08:38:10.264 15501-15501/? I/System.out: /storage/sdcard/demos/file/tmp/test
</code>```

But i can't find the file from android device monitor

What step i miss it ? Any help would be appreciated . Thanks in advance.

答:
you should replace

```<code>dirFile.mkdir();
</code>```

to

```<code>dirFile.mkdirs();
</code>```

Example:

```<code>if (!dirFile.exists()) { // if file doesn't exist
        System.out.println(dirFile.mkdir());
        System.out.println(dirFile.mkdirs());

    }
</code>```

will yield false for the first [and no dir will be created], and true for the second, and you will have created /demos/file/tmp/test

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any
  necessary but nonexistent parent directories. Note that if this
  operation fails it may have succeeded in creating some of the
  necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

hope help you!

Title: Create file failed from mkdir()

Body:
I try to create file in my android emulator, but when i finish my code.
I can't find the file i create from android device monitor.

Here is my code:

try {
    if (Environment.getExternalStorageState()
            .equals(Environment.MEDIA_MOUNTED)) {
        System.out.println("can be read and write");
        File sdFile = android.os.Environment.getExternalStorageDirectory();

        //String path = sdFile.getPath() + File.separator + "DestPdf";
        String path = sdFile.getPath() + "/demos/file/tmp/test";
        File dirFile = new File(path);

        if (!dirFile.exists()) { // if file doesn't exist
            System.out.println("create file");
            dirFile.mkdir(); // create file
            System.out.println(dirFile.toString());
        }
    }
} catch (Exception ex) {
    ex.toString();
}

I also add some permissions:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

Here is my print out, i can see the root /storage/sdcard/demos/file/tmp/test

11-17 08:38:10.263 15501-15501/? I/System.out: can be read and write
11-17 08:38:10.263 15501-15501/? I/System.out: create file
11-17 08:38:10.264 15501-15501/? I/System.out: /storage/sdcard/demos/file/tmp/test

But i can't find the file from android device monitor

What step i miss it ? Any help would be appreciated . Thanks in advance.

Body:
you should replace

dirFile.mkdir();

to

dirFile.mkdirs();

Example:

if (!dirFile.exists()) { // if file doesn't exist
        System.out.println(dirFile.mkdir());
        System.out.println(dirFile.mkdirs());

    }

will yield false for the first [and no dir will be created], and true for the second, and you will have created /demos/file/tmp/test

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any
  necessary but nonexistent parent directories. Note that if this
  operation fails it may have succeeded in creating some of the
  necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

hope help you!


问:
How to use Enzyme Shallow with Jest snapshots
I'm trying to use shallow from enzyme and also use snapshots from jest together.

The problem I'm facing is that I need to change something from the state using setState() from enzyme and then match the result with the snapshot.

See the code of my component:

```<code>....

getPrevProduct = () => {
  const key = this.state.indexCurrent > 0 &&
   this.productsKeys[this.state.indexCurrent - 1];

  let product = null;

  if (key) {
    product = this.props.products[key];
  }

  return product;
}

renderPrev = () => this.getPrevProduct() && <PrevButton />;

render() {
  return (
    <div>
      ...
      {this.renderPrev()}
      ...
    <div>
  )
}
</code>```

The previous code checks if the product, passed from props in the currentIndex, exists.

That's why I need Enzyme to change the state. Then, if it matches, <PrevButton /> has to be rendered.

This test is when I want to match the component with the snapshot:

```<code>const nextProps = {
  products: {
    test: 'test'
  }
};

const tree = create(<Component nextProps={nextProps} />).toJSON();

expect(tree).toMatchSnapshot();
</code>```

But I need to change the state. How I can do that? This doesn't work:

```<code>it('should render component with prev button', () => {
  const nextProps = {
    products: {
      test: 'test'
    }
  };
  const instance = shallow(<Component nextProps={nextProps} />).instance()

  instance.setState({
    indexCurrent: 1
  });

  const tree = create(<Component nextProps={nextProps} />).toJSON();

  expect(tree).toMatchSnapshot();
});
</code>```

I also tried to save the declaration of the component into a variable like the next uncompleted code and use it in shallow and create:

```<code>const component = <Component nextProps={nextProps} />;

 shallow(component).instance()).instance()
 create(component).toJSON()`
</code>```

I also tried with no luck enzyme-to-json.

What would you do?

答:
After trial and error, I found that enzyme has a method, not documented (or I didn't find it) called getRenderOutput.

That method return the component in JSON format so I can do that:

```<code>it('should render component with prev button', () => {
  const nextProps = {
    products: {
      test: 'test'
    }
  };
  const render = shallow(mockComponent(nextProps))
  const instance = render.instance();

  instance.setState({
    indexCurrent: 1
  });

  const tree = render.renderer.getRenderOutput();

  expect(tree).toMatchSnapshot();
});
</code>```

That's how I can use snapshots from Jest with enzyme.

The only problem with getRenderOutput is that if I put a console log, it will be printed twice. That's because instance() and getRenderOutput(), both fires the test.

This is the output of the snapshot:

```<code>exports[`ProductNavigator should render component with prev button 1`] = `
  <div>
    <FloatingActionButton
      className="NavigatorButton left"
      onTouchTap={[Function]}
      secondary={true}
    >
      <KeyboardArrowLeft />
    </FloatingActionButton>
  </div>
`;
</code>```

If someone knows a better way to do that, please, add a comment.

Thanks!

Body:
I'm trying to use shallow from enzyme and also use snapshots from jest together.

The problem I'm facing is that I need to change something from the state using setState() from enzyme and then match the result with the snapshot.

See the code of my component:

....

getPrevProduct = () => {
  const key = this.state.indexCurrent > 0 &&
   this.productsKeys[this.state.indexCurrent - 1];

  let product = null;

  if (key) {
    product = this.props.products[key];
  }

  return product;
}

renderPrev = () => this.getPrevProduct() && <PrevButton />;

render() {
  return (

      ...
      {this.renderPrev()}
      ...

  )
}

The previous code checks if the product, passed from props in the currentIndex, exists.

That's why I need Enzyme to change the state. Then, if it matches, <PrevButton /> has to be rendered.

This test is when I want to match the component with the snapshot:

const nextProps = {
  products: {
    test: 'test'
  }
};

const tree = create(<Component nextProps={nextProps} />).toJSON();

expect(tree).toMatchSnapshot();

But I need to change the state. How I can do that? This doesn't work:

it('should render component with prev button', () => {
  const nextProps = {
    products: {
      test: 'test'
    }
  };
  const instance = shallow(<Component nextProps={nextProps} />).instance()

  instance.setState({
    indexCurrent: 1
  });

  const tree = create(<Component nextProps={nextProps} />).toJSON();

  expect(tree).toMatchSnapshot();
});

I also tried to save the declaration of the component into a variable like the next uncompleted code and use it in shallow and create:

const component = <Component nextProps={nextProps} />;

 shallow(component).instance()).instance()
 create(component).toJSON()`

I also tried with no luck enzyme-to-json.

What would you do?

Body:
After trial and error, I found that enzyme has a method, not documented (or I didn't find it) called getRenderOutput.

That method return the component in JSON format so I can do that:

it('should render component with prev button', () => {
  const nextProps = {
    products: {
      test: 'test'
    }
  };
  const render = shallow(mockComponent(nextProps))
  const instance = render.instance();

  instance.setState({
    indexCurrent: 1
  });

  const tree = render.renderer.getRenderOutput();

  expect(tree).toMatchSnapshot();
});

That's how I can use snapshots from Jest with enzyme.

The only problem with getRenderOutput is that if I put a console log, it will be printed twice. That's because instance() and getRenderOutput(), both fires the test.

This is the output of the snapshot:

exports[`ProductNavigator should render component with prev button 1`] = `
  <div>
    <FloatingActionButton
      className="NavigatorButton left"
      onTouchTap={[Function]}
      secondary={true}
    >
      <KeyboardArrowLeft />
    </FloatingActionButton>
  </div>
`;

If someone knows a better way to do that, please, add a comment.

Thanks!


问:
How to properly get table-row indexes and named values from trapped var-binds in pysnmp
I'm trying to keep my code as clean as possible but I'm not completely satisfied with what I achieved so far.

I built a SNMP manager which receive traps from another device using a custom MIB, which I will refer to as MY-MIB.

I am not sure this is the cleanest way, but essentially I have:

```<code>from pysnmp.entity import engine, config
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv, context
from pysnmp.smi import builder, rfc1902
from pysnmp.smi.view import MibViewController
from pysnmp.entity.rfc3413 import mibvar

_snmp_engine = engine.SnmpEngine()
_snmpContext = context.SnmpContext(_snmpEngine)
_mibBuilder = _snmpContext.getMibInstrum().getMibBuilder()
#Add local path where MY-MIB is located
_mibSources = _mibBuilder.getMibSources() + (builder.DirMibSource('.'),)
_mibBuilder.setMibSources(*mibSources)
_mibBuilder.loadModules('MY-MIB')
_view_controller = MibViewController(_mibBuilder)

def my_callback_trap_processor(snmp_engine, state_reference,
                                   context_id, context_name, var_binds, ctx):

    #...CALLBACK CODE...

config.addV1System(snmp_engine, 'my-area', 'MYCOMMUNITY')
config.addTargetParams(snmp_engine, 'my-creds', 'my-area',
                       'noAuthNoPriv', 1)

config.addSocketTransport(snmp_engine,
                          udp.domainName + (1,),
                          udp.UdpTransport().openServerMode((IP_ADDRESS,
                                                             PORT)))

ntfrcv.NotificationReceiver(snmp_engine, my_callback_trap_processor)

snmp_engine.transportDispatcher.jobStarted(1)

try:
    snmp_engine.transportDispatcher.runDispatcher()
except:
    snmp_engine.transportDispatcher.closeDispatcher()
    raise
</code>```

In the callback function above I can get a pretty intelligible print by just using the following code:

```<code>    varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(_view_controller) for x in var_binds]
    for varBind in varBinds:
        print(varBind.prettyPrint())
</code>```

which, from a given trap that I receive, gives me:

```<code>SNMPv2-MIB::sysUpTime.0 = 0
SNMPv2-MIB::snmpTrapOID.0 = MY-MIB::myNotificationType
MY-MIB::myReplyKey.47746."ABC" = 0x00000000000000000000000000000000000
MY-MIB::myTime.0 = 20171115131544Z
MY-MIB::myOperationMode.0 = 'standalone'
</code>```

Nice. But I want to manipulate/dissect each bit of information from the given var-binds, especially in a higher level way.

Looking at the innards of the library I was able to gather this code up:

```<code>for varBind in var_binds:
    objct = rfc1902.ObjectIdentity(varBind[0]).resolveWithMib(self._view_controller)
    (symName, modName), indices = mibvar.oidToMibName(
                self._view_controller, objct.getOid()
                )
    print(symName, modName, indices, varBind[1])
</code>```

that gives me:

```<code>sysUpTime SNMPv2-MIB (Integer(0),) 0
snmpTrapOID SNMPv2-MIB (Integer(0),) 1.3.6.1.X.Y.Z.A.B.C.D
myReplyKey MY-MIB (myTimeStamp(47746), myName(b'X00080')) 0x00000000000000000000000000000000000
myTime MY-MIB (Integer(0),) 20171115131544Z
myOperationMode MY-MIB (Integer(0),) 1
</code>```

and in the case of myReplyKey indexes I can just do a:

```<code>    for idx in indices:
        try:
            print(idx.getValue())
        except AttributeError:
            print(int(idx))
</code>```

But in the case of the myOperationMode var-bind, how do I get the named-value 'standalone' instead of 1? And how to get the names of the indexes (myTimeStamp and myName)?

Update:

After Ilya's suggestions I researched the library a little bit more for getting the namedValues and, also, I used some Python hacking to get what I was looking for on the indices.

```<code>varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(_view_controller) for x in var_binds]
processed_var_binds = []
for var_bind in resolved_var_binds:

    object_identity, object_value = var_bind
    mod_name, var_name, indices = object_identity.getMibSymbol()

    var_bind_dict = {'mib': mod_name, 'name': var_name, 'indices': {}}

    for idx in indices:
        try:
            value = idx.getValue()
        except AttributeError:
            var_bind_dict['indices'] = int(idx.prettyPrint())
        else:
            var_bind_dict['indices'][type(value).__name__] = str(value)

    try:
        var_bind_dict['value'] = object_value.namedValues[object_value]
    except (AttributeError, KeyError):
        try:
            var_bind_dict['value'] = int(object_value.prettyPrint())
        except ValueError:
            var_bind_dict['value'] = object_value.prettyPrint()

    processed_var_binds.append(var_bind_dict)
</code>```

答:
To resolve SNMP PDU var-bindings against a MIB you can use this snippet what I think you have done already:

```<code>from pysnmp.smi.rfc1902 import *

var_binds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController)
            for x in var_binds]
</code>```

By this point you have a list of rfc1902.ObjectType objects. The ObjectType instance mimics a two-element tuple: ObjectIdentity and SNMP value object.

```<code>var_bind = var_binds[0]
object_identity, object_value = var_bind
</code>```

Now, getMibSymbol() will give you MIB name, MIB object name and the tuple of indices made up from the trailing part of the OID. Index elements are SNMP value objects just as object_value:

```<code>>>> object_identity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))
</code>```

The enumeration, should it present, is reported by .prettyPrint():

```<code>>>> from pysnmp.proto.rfc1902 import *
>>> Error = Integer.withNamedValues(**{'disk-full': 1, 'no-disk': -1})
>>> error = Error(1)
>>> error.prettyPrint()
'disk-full'
>>> int(error)
1
</code>```

Body:
I'm trying to keep my code as clean as possible but I'm not completely satisfied with what I achieved so far.

I built a SNMP manager which receive traps from another device using a custom MIB, which I will refer to as MY-MIB.

I am not sure this is the cleanest way, but essentially I have:

from pysnmp.entity import engine, config
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.entity.rfc3413 import ntfrcv, context
from pysnmp.smi import builder, rfc1902
from pysnmp.smi.view import MibViewController
from pysnmp.entity.rfc3413 import mibvar

_snmp_engine = engine.SnmpEngine()
_snmpContext = context.SnmpContext(_snmpEngine)
_mibBuilder = _snmpContext.getMibInstrum().getMibBuilder()
#Add local path where MY-MIB is located
_mibSources = _mibBuilder.getMibSources() + (builder.DirMibSource('.'),)
_mibBuilder.setMibSources(*mibSources)
_mibBuilder.loadModules('MY-MIB')
_view_controller = MibViewController(_mibBuilder)

def my_callback_trap_processor(snmp_engine, state_reference,
                                   context_id, context_name, var_binds, ctx):

    #...CALLBACK CODE...

config.addV1System(snmp_engine, 'my-area', 'MYCOMMUNITY')
config.addTargetParams(snmp_engine, 'my-creds', 'my-area',
                       'noAuthNoPriv', 1)

config.addSocketTransport(snmp_engine,
                          udp.domainName + (1,),
                          udp.UdpTransport().openServerMode((IP_ADDRESS,
                                                             PORT)))

ntfrcv.NotificationReceiver(snmp_engine, my_callback_trap_processor)

snmp_engine.transportDispatcher.jobStarted(1)

try:
    snmp_engine.transportDispatcher.runDispatcher()
except:
    snmp_engine.transportDispatcher.closeDispatcher()
    raise

In the callback function above I can get a pretty intelligible print by just using the following code:

    varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(_view_controller) for x in var_binds]
    for varBind in varBinds:
        print(varBind.prettyPrint())

which, from a given trap that I receive, gives me:

SNMPv2-MIB::sysUpTime.0 = 0
SNMPv2-MIB::snmpTrapOID.0 = MY-MIB::myNotificationType
MY-MIB::myReplyKey.47746."ABC" = 0x00000000000000000000000000000000000
MY-MIB::myTime.0 = 20171115131544Z
MY-MIB::myOperationMode.0 = 'standalone'

Nice. But I want to manipulate/dissect each bit of information from the given var-binds, especially in a higher level way.

Looking at the innards of the library I was able to gather this code up:

for varBind in var_binds:
    objct = rfc1902.ObjectIdentity(varBind[0]).resolveWithMib(self._view_controller)
    (symName, modName), indices = mibvar.oidToMibName(
                self._view_controller, objct.getOid()
                )
    print(symName, modName, indices, varBind[1])

that gives me:

sysUpTime SNMPv2-MIB (Integer(0),) 0
snmpTrapOID SNMPv2-MIB (Integer(0),) 1.3.6.1.X.Y.Z.A.B.C.D
myReplyKey MY-MIB (myTimeStamp(47746), myName(b'X00080')) 0x00000000000000000000000000000000000
myTime MY-MIB (Integer(0),) 20171115131544Z
myOperationMode MY-MIB (Integer(0),) 1

and in the case of myReplyKey indexes I can just do a:

    for idx in indices:
        try:
            print(idx.getValue())
        except AttributeError:
            print(int(idx))

But in the case of the myOperationMode var-bind, how do I get the named-value 'standalone' instead of 1? And how to get the names of the indexes (myTimeStamp and myName)?

Update:

After Ilya's suggestions I researched the library a little bit more for getting the namedValues and, also, I used some Python hacking to get what I was looking for on the indices.

varBinds = [rfc1902.ObjectType(rfc1902.ObjectIdentity(x[0]), x[1]).resolveWithMib(_view_controller) for x in var_binds]
processed_var_binds = []
for var_bind in resolved_var_binds:

    object_identity, object_value = var_bind
    mod_name, var_name, indices = object_identity.getMibSymbol()

    var_bind_dict = {'mib': mod_name, 'name': var_name, 'indices': {}}

    for idx in indices:
        try:
            value = idx.getValue()
        except AttributeError:
            var_bind_dict['indices'] = int(idx.prettyPrint())
        else:
            var_bind_dict['indices'][type(value).__name__] = str(value)

    try:
        var_bind_dict['value'] = object_value.namedValues[object_value]
    except (AttributeError, KeyError):
        try:
            var_bind_dict['value'] = int(object_value.prettyPrint())
        except ValueError:
            var_bind_dict['value'] = object_value.prettyPrint()

    processed_var_binds.append(var_bind_dict)

Body:
To resolve SNMP PDU var-bindings against a MIB you can use this snippet what I think you have done already:

from pysnmp.smi.rfc1902 import *

var_binds = [ObjectType(ObjectIdentity(x[0]), x[1]).resolveWithMib(mibViewController)
            for x in var_binds]

By this point you have a list of rfc1902.ObjectType objects. The ObjectType instance mimics a two-element tuple: ObjectIdentity and SNMP value object.

var_bind = var_binds[0]
object_identity, object_value = var_bind

Now, getMibSymbol() will give you MIB name, MIB object name and the tuple of indices made up from the trailing part of the OID. Index elements are SNMP value objects just as object_value:

>>> object_identity.getMibSymbol()
('SNMPv2-MIB', 'sysDescr', (0,))

The enumeration, should it present, is reported by .prettyPrint():

>>> from pysnmp.proto.rfc1902 import *
>>> Error = Integer.withNamedValues(**{'disk-full': 1, 'no-disk': -1})
>>> error = Error(1)
>>> error.prettyPrint()
'disk-full'
>>> int(error)
1


问:
How to concatenate two dataframes based on the particular columns?
There are 2 dataframes which have different columns.
I'm trying to concatenate them based on the first 3 columns.

```<code>   a b c X
1  H A 8 1
2  M D 3 2
3  H A 9 3
4  L C 9 4

   a b c Y
1  H A 8 4
2  M D 3 3
3  H A 9 2
4  L C 9 2
</code>```

It's the expected result:

```<code>   a b c X Y
1  H A 8 1 4
2  M D 3 2 3
3  H A 9 3 2
4  L C 9 4 2
</code>```

I can't find a efficient way to concatenate them!!

答:
I think merge should working nice:

```<code>df = pd.merge(df1, df2, on=['a','b','c'])
</code>```

If need dynamically use first 3 columns:

```<code>print (df1.columns[:3].tolist())
['a', 'b', 'c']

df = pd.merge(df1, df2, on=df1.columns[:3].tolist())
</code>```

```<code>print (df)
   a  b  c  X  Y
0  H  A  8  1  4
1  M  D  3  2  3
2  H  A  9  3  2
3  L  C  9  4  2
</code>```

But if possible first 3 columns are different in both DataFrames and need join by them:

```<code>cols = df1.columns[:3].tolist()
df2 = df2.rename(columns=dict(zip(df2.columns[:3], cols)))
df = pd.merge(df1, df2, on=cols)
</code>```

Body:
There are 2 dataframes which have different columns.
I'm trying to concatenate them based on the first 3 columns.

   a b c X
1  H A 8 1
2  M D 3 2
3  H A 9 3
4  L C 9 4

   a b c Y
1  H A 8 4
2  M D 3 3
3  H A 9 2
4  L C 9 2

It's the expected result:

   a b c X Y
1  H A 8 1 4
2  M D 3 2 3
3  H A 9 3 2
4  L C 9 4 2

I can't find a efficient way to concatenate them!!

Body:
I think merge should working nice:

df = pd.merge(df1, df2, on=['a','b','c'])

If need dynamically use first 3 columns:

print (df1.columns[:3].tolist())
['a', 'b', 'c']

df = pd.merge(df1, df2, on=df1.columns[:3].tolist())

print (df)
   a  b  c  X  Y
0  H  A  8  1  4
1  M  D  3  2  3
2  H  A  9  3  2
3  L  C  9  4  2

But if possible first 3 columns are different in both DataFrames and need join by them:

cols = df1.columns[:3].tolist()
df2 = df2.rename(columns=dict(zip(df2.columns[:3], cols)))
df = pd.merge(df1, df2, on=cols)


问:
laravel Expected response code 250 but got code "530"
Im trying to Mail in Laravel 5.1

my mail.php code is

```<code> return [
     'driver' => env('MAIL_DRIVER', 'smtp'),
     'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
     'port' => env('MAIL_PORT', 587),
     'from' => ['address' => 'myemail@gmail.com', 'name' => 'sample'],
     'encryption' => env('MAIL_ENCRYPTION', 'tls'),
     'username' => env('MAIL_USERNAME'),
     'password' => env('MAIL_PASSWORD'),
     'sendmail' => '/usr/sbin/sendmail -bs',
     'pretend' => env('MAIL_PRETEND', false),

 ];
</code>```

my .env file is

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=null
</code>```

my function to email is

```<code>public function sendEmailVerification()
{
    $user = $this->user;//retrieved by $request->user() in __construct

    Mail::send('emails.verifyemail', ['user' => $user], function ($m) use ($user) {
        $m->from('myemail@gmail.com, 'sample');

        $m->to($user->email, $user->name)->subject('Verify Email');
    });
}
</code>```

Error appears every time i call my function.

Expected response code 250 but got code "530", with message "530 5.7.0
Must issue a STARTTLS command first. l188sm21749863pfl.28 - gsmtp"

答:
I had the same problem. I changed,

```<code>MAIL_ENCRYPTION=null to
MAIL_ENCRYPTION=tls

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

and it worked.

Body:
Im trying to Mail in Laravel 5.1

my mail.php code is

 return [
     'driver' => env('MAIL_DRIVER', 'smtp'),
     'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
     'port' => env('MAIL_PORT', 587),
     'from' => ['address' => 'myemail@gmail.com', 'name' => 'sample'],
     'encryption' => env('MAIL_ENCRYPTION', 'tls'),
     'username' => env('MAIL_USERNAME'),
     'password' => env('MAIL_PASSWORD'),
     'sendmail' => '/usr/sbin/sendmail -bs',
     'pretend' => env('MAIL_PRETEND', false),

 ];

my .env file is

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=null

my function to email is

public function sendEmailVerification()
{
    $user = $this->user;//retrieved by $request->user() in __construct

    Mail::send('emails.verifyemail', ['user' => $user], function ($m) use ($user) {
        $m->from('myemail@gmail.com, 'sample');

        $m->to($user->email, $user->name)->subject('Verify Email');
    });
}

Error appears every time i call my function.

Expected response code 250 but got code "530", with message "530 5.7.0
Must issue a STARTTLS command first. l188sm21749863pfl.28 - gsmtp"

Body:
I had the same problem. I changed,

MAIL_ENCRYPTION=null to
MAIL_ENCRYPTION=tls

php artisan config:cache

and it worked.


问:
Is running a lamp dev server secure
Curious if there are any security concerns with running a dev server, with a standard lamp setup. More specifically, if I was downloading a new client’s existing Wordpress site with no idea what it’s security standards are like (malacious plugins etc), could I be exposing myself? If this was an issue, would running some sort of vagrant/docker setup be more secure?</p>

答:
VM or Vagrant/Docker would be more secure, indeed.

That WP install which

may contain small malicious JS code which may copy itself to another path of your localhost and then use your PC as a zombie computer.

can harm data of your filesystem (where PHP has an access to)

can steal your data

etc.

So, it is obvious that you can't trust it.

Title: Is running a lamp dev server secure


问:
Outputting a square wave at a specific frequency in verilog
so I'm trying to produce sound via an audio controller by creating a square wave at various frequencies depending on which switch gets flipped on an FPGA. I'm using an audio controller that has a chip clock of 48kHz, so I'm using a clock divider (one for each note, it's not necessary now but it will be later if you're wondering why I'm doing that) to count the duty cycle for each note, flipping between +amplitude and -amplitude every half duty cycle. For some reason I am able to get audio to output, but the tone of the notes do not represent the frequency I gave them (the tones are seemingly random, and much higher pitched than they should be). I've searched the internet dry and cannot come up with a solution as to why this is... any help is much appreciated!

Here's a snippet of my code:

```<code>// Positive and negative amplitude parameters for square wave
parameter pos_amp = 32'h7FFFFFFF;
parameter neg_amp = 32'h80000000;

// Determines channel_audio_out via dac_out
wire signed [32:1] channel_audio_out = dac_out ? pos_amp : neg_amp;

// Seperate 8-bit counter for each note
reg [7:0] ac_counter_C4;
reg [7:0] ac_counter_D4;
reg [7:0] ac_counter_E4;
reg [7:0] ac_counter_F4;
reg [7:0] ac_counter_G4;
reg [7:0] ac_counter_A4;
reg [7:0] ac_counter_B4;

reg clear_audio_out_memory;             // To clear audio_out buffer when no SW is flipped
reg write_audio_out;                            // To signal when to write to audio_out buffer
reg dac_out;                                    // Determines pos_amp or neg_amp for channel_audio_out

// Determines dac_out via ac_counter's (AUD_XCK dividers)
always@(posedge AUD_XCK) // 48kHz
begin
    clear_audio_out_memory <= 1'b0;
        if (SW[0] == 1'b1) // C4 --- f = 261.626 Hz --- Duty Cycle = 184
            begin
                ac_counter_C4 <= ac_counter_C4 + 1'b1;
                if (ac_counter_C4 >= 8'd183)
                    ac_counter_C4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_C4 < 8'd92) ? 1'b1 : 1'b0;
            end
        else if (SW[1] == 1'b1) // D4 --- f = 293.665 Hz --- Duty Cycle = 164
            begin
                ac_counter_D4 <= ac_counter_D4 + 1'b1;
                if (ac_counter_D4 >= 8'd163)
                    ac_counter_D4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_D4 < 8'd82) ? 1'b1 : 1'b0;
            end
        else if (SW[2] == 1'b1) // E4 --- f = 329.628 Hz --- Duty Cycle = 146
            begin
                ac_counter_E4 <= ac_counter_E4 + 1'b1;
                if (ac_counter_E4 >= 8'd145)
                    ac_counter_E4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_E4 < 8'd73) ? 1'b1 : 1'b0;
            end
        else if (SW[3] == 1'b1) // F4 --- f = 349.228 Hz --- Duty Cycle = 138 // Wrong note completely
            begin
                ac_counter_F4 <= ac_counter_F4 + 1'b1;
                if (ac_counter_F4 >= 8'd137)
                    ac_counter_F4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_F4 < 8'd69) ? 1'b1 : 1'b0;
            end
        else if (SW[4] == 1'b1) // G4 --- f = 391.995 Hz --- Duty Cycle = 122
            begin
                ac_counter_G4 <= ac_counter_G4 + 1'b1;
                if (ac_counter_G4 >= 8'd121)
                    ac_counter_G4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_G4 < 8'd61) ? 1'b1 : 1'b0;
            end
        else if (SW[5] == 1'b1) // A4 --- f = 440 Hz --- Duty Cycle = 110
            begin
                ac_counter_A4 <= ac_counter_A4 + 1'b1;
                if (ac_counter_A4 >= 8'd109)
                    ac_counter_A4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_A4 < 8'd55) ? 1'b1 : 1'b0;
            end
        else if (SW[6] == 1'b1) // B4 --- f = 493.883 Hz --- Duty Cycle = 98
            begin
                ac_counter_B4 <= ac_counter_B4 + 1'b1;
                if (ac_counter_B4 >= 8'd97)
                    ac_counter_B4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_B4 < 8'd44) ? 1'b1 : 1'b0;
            end
        else // NO SWITCH ON --- DEFAULT STATE
            begin

                ac_counter_C4 <= 1'd0;
                ac_counter_D4 <= 1'd0;
                ac_counter_E4 <= 1'd0;
                ac_counter_F4 <= 1'd0;
                ac_counter_G4 <= 1'd0;
                ac_counter_A4 <= 1'd0;
                ac_counter_B4 <= 1'd0;

                write_audio_out <= 1'b0;
                clear_audio_out_memory <= 1'b1;
                dac_out <= 1'b0;
            end
end
</code>```

Thanks!

答: If I understood your system correctly, shouldn't you be generating sine wave amplitude values of the specified frequency as input for your DAC? . If you feed 2-amplitude signal to the DAC, I am supposing the analog output is also a square wave, which is essentially a combination of your required base frequency, and higher order harmonics(These might be contributing to apparent higher pitches).</p>

Body:
so I'm trying to produce sound via an audio controller by creating a square wave at various frequencies depending on which switch gets flipped on an FPGA. I'm using an audio controller that has a chip clock of 48kHz, so I'm using a clock divider (one for each note, it's not necessary now but it will be later if you're wondering why I'm doing that) to count the duty cycle for each note, flipping between +amplitude and -amplitude every half duty cycle. For some reason I am able to get audio to output, but the tone of the notes do not represent the frequency I gave them (the tones are seemingly random, and much higher pitched than they should be). I've searched the internet dry and cannot come up with a solution as to why this is... any help is much appreciated!

Here's a snippet of my code:

// Positive and negative amplitude parameters for square wave
parameter pos_amp = 32'h7FFFFFFF;
parameter neg_amp = 32'h80000000;

// Determines channel_audio_out via dac_out
wire signed [32:1] channel_audio_out = dac_out ? pos_amp : neg_amp;

// Seperate 8-bit counter for each note
reg [7:0] ac_counter_C4;
reg [7:0] ac_counter_D4;
reg [7:0] ac_counter_E4;
reg [7:0] ac_counter_F4;
reg [7:0] ac_counter_G4;
reg [7:0] ac_counter_A4;
reg [7:0] ac_counter_B4;

reg clear_audio_out_memory;             // To clear audio_out buffer when no SW is flipped
reg write_audio_out;                            // To signal when to write to audio_out buffer
reg dac_out;                                    // Determines pos_amp or neg_amp for channel_audio_out

// Determines dac_out via ac_counter's (AUD_XCK dividers)
always@(posedge AUD_XCK) // 48kHz
begin
    clear_audio_out_memory <= 1'b0;
        if (SW[0] == 1'b1) // C4 --- f = 261.626 Hz --- Duty Cycle = 184
            begin
                ac_counter_C4 <= ac_counter_C4 + 1'b1;
                if (ac_counter_C4 >= 8'd183)
                    ac_counter_C4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_C4 < 8'd92) ? 1'b1 : 1'b0;
            end
        else if (SW[1] == 1'b1) // D4 --- f = 293.665 Hz --- Duty Cycle = 164
            begin
                ac_counter_D4 <= ac_counter_D4 + 1'b1;
                if (ac_counter_D4 >= 8'd163)
                    ac_counter_D4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_D4 < 8'd82) ? 1'b1 : 1'b0;
            end
        else if (SW[2] == 1'b1) // E4 --- f = 329.628 Hz --- Duty Cycle = 146
            begin
                ac_counter_E4 <= ac_counter_E4 + 1'b1;
                if (ac_counter_E4 >= 8'd145)
                    ac_counter_E4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_E4 < 8'd73) ? 1'b1 : 1'b0;
            end
        else if (SW[3] == 1'b1) // F4 --- f = 349.228 Hz --- Duty Cycle = 138 // Wrong note completely
            begin
                ac_counter_F4 <= ac_counter_F4 + 1'b1;
                if (ac_counter_F4 >= 8'd137)
                    ac_counter_F4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_F4 < 8'd69) ? 1'b1 : 1'b0;
            end
        else if (SW[4] == 1'b1) // G4 --- f = 391.995 Hz --- Duty Cycle = 122
            begin
                ac_counter_G4 <= ac_counter_G4 + 1'b1;
                if (ac_counter_G4 >= 8'd121)
                    ac_counter_G4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_G4 < 8'd61) ? 1'b1 : 1'b0;
            end
        else if (SW[5] == 1'b1) // A4 --- f = 440 Hz --- Duty Cycle = 110
            begin
                ac_counter_A4 <= ac_counter_A4 + 1'b1;
                if (ac_counter_A4 >= 8'd109)
                    ac_counter_A4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_A4 < 8'd55) ? 1'b1 : 1'b0;
            end
        else if (SW[6] == 1'b1) // B4 --- f = 493.883 Hz --- Duty Cycle = 98
            begin
                ac_counter_B4 <= ac_counter_B4 + 1'b1;
                if (ac_counter_B4 >= 8'd97)
                    ac_counter_B4 <= 8'd0;
                write_audio_out <= 1'b1;
                dac_out = (ac_counter_B4 < 8'd44) ? 1'b1 : 1'b0;
            end
        else // NO SWITCH ON --- DEFAULT STATE
            begin

                ac_counter_C4 <= 1'd0;
                ac_counter_D4 <= 1'd0;
                ac_counter_E4 <= 1'd0;
                ac_counter_F4 <= 1'd0;
                ac_counter_G4 <= 1'd0;
                ac_counter_A4 <= 1'd0;
                ac_counter_B4 <= 1'd0;

                write_audio_out <= 1'b0;
                clear_audio_out_memory <= 1'b1;
                dac_out <= 1'b0;
            end
end

Thanks!


问:
Test string with a string list
I have a list of Id contained in an array :

```<code>var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}
</code>```

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

```<code>for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }
</code>```

I do not see how to do it .. My proposed solution does not work

答:
Don't return false in else, do it outside for-loop once you are sure that items are processed.

```<code>for(let i of listId) {
    if(member.userId !== listId[i]) {
      return true;
    }
  }
return false;
</code>```

Otherwise unless first item's check return true, your method will always return false without checking the rest of the items, since it hasn't got the chance to iterate and process rest of the items.

Yes but I need a variable boolean who return true or false. Like newId
  because after I do that if(member.userId !== userId && newId) { ... }

Using flag

```<code>var flag = false;
for(let i of listId) {
    if(member.userId !== listId[i]) {
      flag = true;
      break;
    }
  }
return flag;
</code>```

Title: Test string with a string list

Body:
I have a list of Id contained in an array :

var listId: string[] = [];
var newId: boolean;
for (let i in data.chunk) {
    listId.push(data.chunk[i].aliases[0]);
}

I then want to test my new Id with this whole list. If my new Id is in the list I want to return a false, and if it is not returned a true.

for(let i of listId) {
    if(member.userId !== listId[i]) {
      newid = true;
    }
    else {
      newId = false;
    }
  }

I do not see how to do it .. My proposed solution does not work

Body:
Don't return false in else, do it outside for-loop once you are sure that items are processed.

for(let i of listId) {
    if(member.userId !== listId[i]) {
      return true;
    }
  }
return false;

Otherwise unless first item's check return true, your method will always return false without checking the rest of the items, since it hasn't got the chance to iterate and process rest of the items.

Yes but I need a variable boolean who return true or false. Like newId
  because after I do that if(member.userId !== userId && newId) { ... }

Using flag

var flag = false;
for(let i of listId) {
    if(member.userId !== listId[i]) {
      flag = true;
      break;
    }
  }
return flag;


问:
Error:com.duplicate entry: com/google/android/gms/internal/zzfj.class
I'm trying to port an old android app to new devices. It works well from Android 5.x to 7.1, but it doesn't work in Android 4.x versions.

When I try to install it in an android device or in a emulator with Android 4.x the build always fails with the same exception:

Error:com.duplicate entry: com/google/android/gms/internal/zzfj.class

apply plugin: 'com.android.application'

android {
  compileSdkVersion 25
  buildToolsVersion "25.0.2"
  defaultConfig {
    applicationId "sigmanews.sigmamentors"
    manifestPlaceholders = [onesignal_app_id: "c4321xxx-f85a-4ba1-983f-cc1399efb839",
      // Project number pulled from dashboard, local value is ignored.
      onesignal_google_project_number: "REMOTE"
    ]
    minSdkVersion 17
    targetSdkVersion 25
    versionCode 21
    versionName "23"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

repositories {
  mavenCentral()
  maven {
    url "https://jitpack.io"
  }
  maven {
    url "https://mint.splunk.com/gradle/"
  }
}

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support',
    module: 'support-annotations'
  })

  compile 'com.android.support:appcompat-v7:25.3.1'
  compile 'com.android.support.constraint:constraint-layout:1.0.2'

  compile "com.google.android.gms:play-services-ads:10.0.1"
  compile 'com.mcxiaoke.volley:library-aar:1.0.0'
  compile 'com.github.bumptech.glide:glide:3.7.0'
  compile 'com.github.tarek360:instacapture:2.0.0-kotlin-beta1'
  compile 'com.android.support:cardview-v7:25.1.0'
  compile 'org.apmem.tools:layouts:1.10@aar'
  compile 'com.github.TheBrownArrow:PermissionManager:1.0.0'
  compile 'com.google.code.gson:gson:2.7'
  compile 'com.squareup.picasso:picasso:2.5.2'
  compile 'pl.droidsonroids.gif:android-gif-drawable:1.1.17'
  compile 'com.onesignal:OneSignal:[3.5.3,4.0.0)'
  compile 'com.splunk.mint:mint:5.0.0'
  compile 'com.facebook.android:facebook-android-sdk:4.6.0'
  compile 'com.google.android.gms:play-services-plus:11.0.4'
  compile 'com.google.android.gms:play-services-auth:10.0.1'
  compile 'com.github.siyamed:android-shape-imageview:0.9.+@aar'
  compile 'com.github.robertsimoes:Shareable:0.1.0'

  testCompile 'junit:junit:4.12'
}
```

答:
use same version of play-services dependencies</p>

```<code>compile 'com.google.android.gms:play-services-plus:11.0.4'
compile 'com.google.android.gms:play-services-auth:11.0.4'
compile "com.google.android.gms:play-services-ads:11.0.4'
</code>```

Body:
use same version of play-services dependencies

compile 'com.google.android.gms:play-services-plus:11.0.4'
compile 'com.google.android.gms:play-services-auth:11.0.4'
compile "com.google.android.gms:play-services-ads:11.0.4'


问:
dateadd function won't work in SAS sql
I am migrating the queries written in teradata to SAS tool.
Below statement is throwing an error Function DATEADD could not be located:

```<code>ct.MaturityDate < dateadd(dd, 30,getdate())
</code>```

I googled and found intck works here. But, not getting an idea how to use it here.

答:
If what you want is add 30 days to the current date you can, as @pingulf suggests, simply use

```<code>ct.maturitydate < date() + 30
</code>```

or

```<code>ct.maturitydate < today() + 30
</code>```

today() and date() being aliases of the same function.

This solution only works for days. To do the same with months or years you would indeed use intnx not intck. In your case:

```<code>ct.MaturityDate < intnx('day',date(),30)
</code>```

More information on the intnx function on the SAS support website

Title: dateadd function won't work in SAS sql

Body:
I am migrating the queries written in teradata to SAS tool.
Below statement is throwing an error Function DATEADD could not be located:

ct.MaturityDate < dateadd(dd, 30,getdate())

I googled and found intck works here. But, not getting an idea how to use it here.

Body:
If what you want is add 30 days to the current date you can, as @pingulf suggests, simply use

ct.maturitydate < date() + 30

or

ct.maturitydate < today() + 30

today() and date() being aliases of the same function.

This solution only works for days. To do the same with months or years you would indeed use intnx not intck. In your case:

ct.MaturityDate < intnx('day',date(),30)

More information on the intnx function on the SAS support website


问:
C++: overriding public\private inheritance
If B inherits from A using public, can B override one of the functions and force it to be private?

```<code>class A
{
public:
    virtual double my_func1(int i);
    virtual double my_func2(int i);
}

class B : public A // Notice the public inheritance
{
public:
    virtual double my_func1(int i);
private:
    virtual double my_func2(int i);
}
</code>```

How about the other way around? if the inheritance type is private - can B force a specific function to be public?

What if A is pure abstract? does it make a difference?

Would protected make any difference in any combination?

答:
I was going through posts made by others and found explanation related to errors encountered when inheritance being private/protected in Derived class somewhat confusing/incomplete.

Consider below code snippet,

```<code>class A
{
public:
    virtual double my_func1(int i);
    virtual double my_func2(int i);
}

class B : private A // Notice private inheritance
{
public:
    virtual double my_func1(int i);
private:
    virtual double my_func2(int i);
}

A* ptr = new B; // this is not legal because B has a private base
ptr->my_func1(); // my_func1() is not accessible
ptr->my_func2(); // my_func2() is also not accessible not because it is private but due
                 // base class A being inherited privately
</code>```

So when we inherit class B from class A using private/protected specifiers then it means that nobody in outside world knows that class B has inherited from class A hence it's illegal to assign pointer/reference of type class B to pointer/reference of type class A. Hence, access of private/protected overridden virtual function in derived classes is only valid when inheritance in public.

Body:
If B inherits from A using public, can B override one of the functions and force it to be private?

class A
{
public:
    virtual double my_func1(int i);
    virtual double my_func2(int i);
}

class B : public A // Notice the public inheritance
{
public:
    virtual double my_func1(int i);
private:
    virtual double my_func2(int i);
}

How about the other way around? if the inheritance type is private - can B force a specific function to be public?

What if A is pure abstract? does it make a difference?

Would protected make any difference in any combination?

Body:
I was going through posts made by others and found explanation related to errors encountered when inheritance being private/protected in Derived class somewhat confusing/incomplete.

Consider below code snippet,

class A
{
public:
    virtual double my_func1(int i);
    virtual double my_func2(int i);
}

class B : private A // Notice private inheritance
{
public:
    virtual double my_func1(int i);
private:
    virtual double my_func2(int i);
}

A* ptr = new B; // this is not legal because B has a private base
ptr->my_func1(); // my_func1() is not accessible
ptr->my_func2(); // my_func2() is also not accessible not because it is private but due
                 // base class A being inherited privately

So when we inherit class B from class A using private/protected specifiers then it means that nobody in outside world knows that class B has inherited from class A hence it's illegal to assign pointer/reference of type class B to pointer/reference of type class A. Hence, access of private/protected overridden virtual function in derived classes is only valid when inheritance in public.


问:
How to password protect my excel sheet after saving them using vb script
In my code I have used vb scripting to take input from the user using inputbox and save it in excel also it is saving the data in newline plus it is also keeping the old entries but I want to password protect my excel sheet after saving it after taking values from inputbox througfh vb scripting I have tried it in my code below but it is not working kindly help me out I have highlighted the lines of the code where I tried to implement my logic to password protect the excel sheet after saving it using ** sign

```<code>sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

**objExcel.sheet(1).unprotect= "saurabh"**
Set rg = objExcel.Sheets(1).Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = sInput
    .Offset(lr, 1).Value = sInput1

End With

objExcel.ActiveWorkbook.Save
**objExcel.sheet(1).protect= "saurabh"**
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
</code>```

Thanks in advance.

答:
Hi it is working now below is the working code for that--</p>

```<code>sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput1)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

objExcel.Sheets(1).unprotect "saurabh"
Set rg = objExcel.Sheets(1).Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = sInput
    .Offset(lr, 1).Value = sInput1

End With

objExcel.ActiveWorkbook.Save
objExcel.Sheets(1).protect "saurabh"
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
</code>```

Body:
In my code I have used vb scripting to take input from the user using inputbox and save it in excel also it is saving the data in newline plus it is also keeping the old entries but I want to password protect my excel sheet after saving it after taking values from inputbox througfh vb scripting I have tried it in my code below but it is not working kindly help me out I have highlighted the lines of the code where I tried to implement my logic to password protect the excel sheet after saving it using ** sign

sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

**objExcel.sheet(1).unprotect= "saurabh"**
Set rg = objExcel.Sheets(1).Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = sInput
    .Offset(lr, 1).Value = sInput1

End With

objExcel.ActiveWorkbook.Save
**objExcel.sheet(1).protect= "saurabh"**
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit

Thanks in advance.

Body:
Hi it is working now below is the working code for that--

sInput = InputBox("Enter your name")

MsgBox ("You entered:" & sInput)

sInput1 = InputBox("Enter your name")

MsgBox ("You entered:" & sInput1)

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\saurabh.ad.sharma\Desktop\rrr.xlsx")

objExcel.Application.Visible = True

objExcel.Sheets(1).unprotect "saurabh"
Set rg = objExcel.Sheets(1).Range("A1")

lr = rg.CurrentRegion.Rows.Count

With rg
    .Offset(lr, 0).Value = sInput
    .Offset(lr, 1).Value = sInput1

End With

objExcel.ActiveWorkbook.Save
objExcel.Sheets(1).protect "saurabh"
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close

objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit


问:
Shifting rows in a UITableView
I have looked at several forums and read different threads, but I can't seem to find an answer. I'd really like some help. I have an array that stores Labels whose contents I display in the UITableView's row. The second row contains fresh data added to the same array and so on. My question is, everytime the labels are displayed in the UITableView, I want it to be displayed on the top row. In essence, the older ones keeps shifting one row down. I understand I need to use: "tableView:moveRowAtIndexPath:toIndexPath:" but it only seems to work with arrays whose contents are strings.

Just to clarify, I'm not displaying each element of the array on a new line. I'm displaying all the elements of the array on a single row, then changing the elements and displaying that as the next row. Except I want the second row to be above the first and so on.

答:
The array you're using is an ordered collection of object, so the easiest way to perform what you're looking fro would be to add the new object in the first position of your array. You can achieve that using the method insertObject:atIndex: of NSMutableArray

ex:

```<code>[myArray insertObject:newObject atIndex:0];
</code>```

This way you don't have to worry about moving your tableView cells ordering.

Hope this helps,
Vincent

Title: Shifting rows in a UITableView

Body:
The array you're using is an ordered collection of object, so the easiest way to perform what you're looking fro would be to add the new object in the first position of your array. You can achieve that using the method insertObject:atIndex: of NSMutableArray

ex:

[myArray insertObject:newObject atIndex:0];

This way you don't have to worry about moving your tableView cells ordering.

Hope this helps,
Vincent


问:
Reorder to some items and changing primary key
I've a table MENU_ITEMS with a column SEQ to define the position at which each item should be displayed in a menu.  Simplified for the sake of this question, something like...

```<code>MENU_ITEMS:
ITEM_CODE    PARENT_CODE   SEQ* (*unique to parent)
------------------------------
BANANAS      FRUIT         1
APPLES       FRUIT         2
CHERRIES     FRUIT         4
DURIANS      FRUIT         3
POTATOES     VEG           1
</code>```

I've a procedure to re-order the items.  One of its parameters is a string array containing the ITEM_CODEs in the new order.  As it stands, something like this...

```<code>procedure arrange_items(
  ITEM_CODES in CORE.T_STRINGARRAY,
  PARENT in VARCHAR2
)
as
  V_SEQS T_NUMBERARRAY := T_NUMBERARRAY();
begin

  for i in 1..ITEM_CODES.count loop
    V_SEQS.extend();
    V_SEQS(i) := i;
  end loop

  forall i in 1..ITEM_CODES.count
    update MENU_ITEMS
    set SEQ = V_SEQS(i)
    where ITEM_CODE = ITEM_CODES(i) and PARENT_CODE = PARENT;

end arrange_items
</code>```

PROBLEM

When calling the procedure with ITEM_CODES = ("APPLES", "BANANAS", "CHERRIES"), I get a 'unique constraint violated' exception (...presumably because the first item's SEQ can't be set to 1 while there exists another row whose SEQ is also 1)

I don't know how to handle items that weren't specified in the ITEM_CODES parameter, whose sequence is irrelevant (being disabled menu items and never displayed.) NB: Only the items to be re-arranged can be included in the ITEM_CODES array parameter; disabled items not requiring re-arranging can't be passed in.

Reading the Oracle docs seems to suggest a BULK COLLECT/UPDATE is needed to change all the records in one hit without violating the unique constraint (I had thought FORALL instead of FOR LOOP might do this) but I have extremely limited SQL knowledge and can't get the application right, nor can I see a way of taking into account the unspecified ITEM_CODES whose sequence might need changing just to avoid conflicting with the codes that were specified.

Is anyone able to suggest at least the correct approach I should investigate, if not a working solution?

答:
You can't do it without changing your procedure unless you disable the constraints.

There seems to be nothing wrong with your code although you could have used simple update statements than FORALL. The problem is that when you are updating the column seq , a unique  entry already exists for the same parent_code and seq . It is only that you are reordering it while running your update statement. So , the constraint will be violated no matter how you change the order of update.

So, the solution I recommend you is to disable the constraint.If you don't know the constraint name, you need to look at USER_CONS_COLUMNS or ALL_CONS_COLUMNS  data dictionary view giving proper column names.Refer this link if you need.

Constraint name

```<code>ALTER TABLE MENU_ITEMS DISABLE CONSTRAINT name_of_unique_constraint;
</code>```

Then execute your procedure and make sure you don't have any duplicate (SEQ,PARENT_CODE )combination after update.

Then enable constraints.

```<code>ALTER TABLE MENU_ITEMS ENABLE CONSTRAINT name_of_unique_constraint;
</code>```

and make sure it does not fail.

EDIT: : It seems the word "can't" I used at the top was taken as a challenge by others and alternate solutions were provided, which is much appreciated. I have slightly changed my first sentence to make it clear.

Body:
I've a table MENU_ITEMS with a column SEQ to define the position at which each item should be displayed in a menu.  Simplified for the sake of this question, something like...

MENU_ITEMS:
ITEM_CODE    PARENT_CODE   SEQ* (*unique to parent)
------------------------------
BANANAS      FRUIT         1
APPLES       FRUIT         2
CHERRIES     FRUIT         4
DURIANS      FRUIT         3
POTATOES     VEG           1

I've a procedure to re-order the items.  One of its parameters is a string array containing the ITEM_CODEs in the new order.  As it stands, something like this...

procedure arrange_items(
  ITEM_CODES in CORE.T_STRINGARRAY,
  PARENT in VARCHAR2
)
as
  V_SEQS T_NUMBERARRAY := T_NUMBERARRAY();
begin

  for i in 1..ITEM_CODES.count loop
    V_SEQS.extend();
    V_SEQS(i) := i;
  end loop

  forall i in 1..ITEM_CODES.count
    update MENU_ITEMS
    set SEQ = V_SEQS(i)
    where ITEM_CODE = ITEM_CODES(i) and PARENT_CODE = PARENT;

end arrange_items

PROBLEM

When calling the procedure with ITEM_CODES = ("APPLES", "BANANAS", "CHERRIES"), I get a 'unique constraint violated' exception (...presumably because the first item's SEQ can't be set to 1 while there exists another row whose SEQ is also 1)

I don't know how to handle items that weren't specified in the ITEM_CODES parameter, whose sequence is irrelevant (being disabled menu items and never displayed.) NB: Only the items to be re-arranged can be included in the ITEM_CODES array parameter; disabled items not requiring re-arranging can't be passed in.

Reading the Oracle docs seems to suggest a BULK COLLECT/UPDATE is needed to change all the records in one hit without violating the unique constraint (I had thought FORALL instead of FOR LOOP might do this) but I have extremely limited SQL knowledge and can't get the application right, nor can I see a way of taking into account the unspecified ITEM_CODES whose sequence might need changing just to avoid conflicting with the codes that were specified.

Is anyone able to suggest at least the correct approach I should investigate, if not a working solution?

Body:
You can't do it without changing your procedure unless you disable the constraints.

There seems to be nothing wrong with your code although you could have used simple update statements than FORALL. The problem is that when you are updating the column seq , a unique  entry already exists for the same parent_code and seq . It is only that you are reordering it while running your update statement. So , the constraint will be violated no matter how you change the order of update.

So, the solution I recommend you is to disable the constraint.If you don't know the constraint name, you need to look at USER_CONS_COLUMNS or ALL_CONS_COLUMNS  data dictionary view giving proper column names.Refer this link if you need.

Constraint name

ALTER TABLE MENU_ITEMS DISABLE CONSTRAINT name_of_unique_constraint;

Then execute your procedure and make sure you don't have any duplicate (SEQ,PARENT_CODE )combination after update.

Then enable constraints.

ALTER TABLE MENU_ITEMS ENABLE CONSTRAINT name_of_unique_constraint;

and make sure it does not fail.

EDIT: : It seems the word "can't" I used at the top was taken as a challenge by others and alternate solutions were provided, which is much appreciated. I have slightly changed my first sentence to make it clear.


问:
cakephp3 admin prefix for webroot directory
I have cakephp3 application and i created a prefix named admin

so as cakephp doc said i created a directory in Template and Controller .

now i want to do the same thing for css and images in webroot but as soon as move the files in Admin directory in webroot cakephp don't recognise them.

my (css , js ) files for admin panel and main site are completely different and i want them apart.

how can i move the files (css , js , etc ) for admin prefix in Admin directory

update

Adding ../Admin/css/ before the style name (for css ) is the only way i found working but it isn't clean . I appriciate any idea's thanks

答:
I use an extra admin layout (/src/Template/Layout/admin.ctp).
In this Layout I add the css and Javascript files for the admin views (e.g echo $this->Html->css('admin/style.css');)
In the admin controllers i add a beforeFilter method to load the admin layout for all actions:</p>

```<code>/**
* @param Event $event
* @return \Cake\Http\Response|null|void
*/
public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    $this->viewBuilder()->setLayout('admin');
}
</code>```

Body:
I use an extra admin layout (/src/Template/Layout/admin.ctp).
In this Layout I add the css and Javascript files for the admin views (e.g echo $this->Html->css('admin/style.css');)
In the admin controllers i add a beforeFilter method to load the admin layout for all actions:

/**
* @param Event $event
* @return \Cake\Http\Response|null|void
*/
public function beforeFilter(Event $event)
{
    parent::beforeFilter($event);
    $this->viewBuilder()->setLayout('admin');
}


答:
I had the same problem a few months ago.

In my case the file was there, but windows couldn't see it (or the integration between adb and windows explorer).

Resetting the MOBILE was the only solution I found... After the reset the file was there in Windows Explorer.

I recommend you to try to find your files using the cli command:

```<code>adb shell ls sdcard/"your_path"
</code>```

Also, try to create it using:

```<code>.getAbsolutePath()
</code>```

Like this:

```<code>File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "YOUR_FOLDER_NAME");

if(!path.exists())
{
    path.mkdirs();
}
else
{
    Log.d ("TAG","Path already exists");
}
</code>```

Hope it helps

Title: Create file failed from mkdir()

Body:
I try to create file in my android emulator, but when i finish my code.
I can't find the file i create from android device monitor.

Here is my code:

try {
    if (Environment.getExternalStorageState()
            .equals(Environment.MEDIA_MOUNTED)) {
        System.out.println("can be read and write");
        File sdFile = android.os.Environment.getExternalStorageDirectory();

        //String path = sdFile.getPath() + File.separator + "DestPdf";
        String path = sdFile.getPath() + "/demos/file/tmp/test";
        File dirFile = new File(path);

        if (!dirFile.exists()) { // if file doesn't exist
            System.out.println("create file");
            dirFile.mkdir(); // create file
            System.out.println(dirFile.toString());
        }
    }
} catch (Exception ex) {
    ex.toString();
}

I also add some permissions:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

Here is my print out, i can see the root /storage/sdcard/demos/file/tmp/test

11-17 08:38:10.263 15501-15501/? I/System.out: can be read and write
11-17 08:38:10.263 15501-15501/? I/System.out: create file
11-17 08:38:10.264 15501-15501/? I/System.out: /storage/sdcard/demos/file/tmp/test

But i can't find the file from android device monitor

What step i miss it ? Any help would be appreciated . Thanks in advance.

Body:
I had the same problem a few months ago.

In my case the file was there, but windows couldn't see it (or the integration between adb and windows explorer).

Resetting the MOBILE was the only solution I found... After the reset the file was there in Windows Explorer.

I recommend you to try to find your files using the cli command:

adb shell ls sdcard/"your_path"

Also, try to create it using:

.getAbsolutePath()

Like this:

File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "YOUR_FOLDER_NAME");

if(!path.exists())
{
    path.mkdirs();
}
else
{
    Log.d ("TAG","Path already exists");
}

Hope it helps


问:
Tokenize words stored in a string in Python
So in my program, I have an input text file. I iterate through the list, add all the words in the list into a string called "text". Then, I use tokenizer on the string, which fails.

```<code>x = open("Tokens.txt")
text = ""
for line in iter(x):

   text += line[0:-1] + " "

x.close()

for i in tokenizer(text):
    print(i)
</code>```

The input stored in the text file-

```<code>abx
*
22;
print "example"
time = 26
</code>```

When I hard code the input into the tokenizer, it works- the program outputs the correct tokens. Like this-

```<code>#for i in tokenizer("abx * 22; print \"example\"  time = 26"):
  #print(i)
</code>```

However, I'm required to open the text file, grab the input from the file, then analyze it, but that won't work. This is the error I'm getting.

```<code>Traceback (most recent call last):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 35, in <module>
    for i in tokenizer(text):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 26, in tokenizer
    raise Exception('Cannot output tokens')
Exception: Cannot output tokens
</code>```

答:
Just for reference, a shorter version of your code. Always prefer "with" syntax over explicit open and close.

```<code>with open("Tokens.txt") as f:
    text = " ".join(f.readlines())

[print(i) for i in tokenizer(text)]
</code>```

Body:
So in my program, I have an input text file. I iterate through the list, add all the words in the list into a string called "text". Then, I use tokenizer on the string, which fails.

x = open("Tokens.txt")
text = ""
for line in iter(x):

   text += line[0:-1] + " "

x.close()

for i in tokenizer(text):
    print(i)

The input stored in the text file-

abx
*
22;
print "example"
time = 26

When I hard code the input into the tokenizer, it works- the program outputs the correct tokens. Like this-

#for i in tokenizer("abx * 22; print \"example\"  time = 26"):
  #print(i)

However, I'm required to open the text file, grab the input from the file, then analyze it, but that won't work. This is the error I'm getting.

Traceback (most recent call last):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 35, in <module>
    for i in tokenizer(text):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 26, in tokenizer
    raise Exception('Cannot output tokens')
Exception: Cannot output tokens

Body:
Just for reference, a shorter version of your code. Always prefer "with" syntax over explicit open and close.

with open("Tokens.txt") as f:
    text = " ".join(f.readlines())

[print(i) for i in tokenizer(text)]


问:
Google Cloud and Go creating instances
thanks for looking at my post. i need to create an Linux instance with go lang and display the created public IP on the webpage.</p>

答:
Actually this is well hidden in the API docs.
First you need to get an Google Cloud SDK Client authenticated.
Then you might want to look at the following API operations:

https://godoc.org/google.golang.org/api/compute/v1#InstancesService.Insert

https://godoc.org/google.golang.org/api/compute/v1#Operation

https://godoc.org/google.golang.org/api/compute/v1#InstancesService.List

Title: Google Cloud and Go creating instances