问:
select the next class with the previous class containing a text I gave
```<code><div class="">
    <span>
        <div class="ant-upload-list-item ant-upload-list-item-undefined ant-upload-list-item-list-type-text">
            <div class="ant-upload-list-item-info">
                <span>
                    <i aria-label="icon: paper-clip" class="anticon anticon-paper-clip">
                    </i>
                    <span class="ant-upload-list-item-name ant-upload-list-item-name-icon-count-1" title="fileDoc.doc">fileDoc.doc</span>
                    <span class="ant-upload-list-item-card-actions ">
                        <a title="Remove file">
                            <i aria-label="icon: delete" title="Remove file" tabindex="-1" class="anticon anticon-delete">
                                                    ...
                            </i>
                        </a>
                    </span>
                </span>
            </div>
        </div>
    </span>
</div>

<div class="">
    <span>
        <div class="ant-upload-list-item ant-upload-list-item-undefined ant-upload-list-item-list-type-text">
            <div class="ant-upload-list-item-info">
                <span>
                    <i aria-label="icon: paper-clip" class="anticon anticon-paper-clip">
                                ...
                    </i>
                    <span class="ant-upload-list-item-name ant-upload-list-item-name-icon-count-1" title="fileJpeg.jpeg">fileJpeg.jpeg</span>
                    <span class="ant-upload-list-item-card-actions ">
                        <a title="Remove file">
                            <i aria-label="icon: delete" title="Remove file" tabindex="-1" class="anticon anticon-delete">
                                    ...
                            </i>
                        </a>
                    </span>
                </span>
            </div>
        </div>
    </span>
</div>
</code>```

This is my case, i want to select the " .ant-upload-list-item-card-actions > a" when the class "ant-upload-list-item-name ant-upload-list-item-name-icon-count-1" contains fileDoc.doc

I made this

```<code>  candidateUploadFileButton = '#filesUpload';
  candidateUploadRemoveButton = '.ant-upload-list-item-card-actions > a';
cy.get(this.candidateUploadFileButton, {force: true}).contains(fileName);
cy.get(this.candidateUploadRemoveButton).click();

</code>```

It works for a single input only for a single div class, if there two classes like in the previously example , it doesn't work beacuse it says there are multiple values

I added this picture, maybe it will help what i want to do, i want to press Remove button for the file named "fileDoc.doc"
https://i.stack.imgur.com/voQqp.png

答:
Refer here:

As per your markup, you can use this:

```<code>cy.contains(fileName).next().find('> a').click()
</code>```

Body:
                    fileDoc.doc

                                                    ...

                                ...

                    fileJpeg.jpeg

                                    ...

This is my case, i want to select the " .ant-upload-list-item-card-actions > a" when the class "ant-upload-list-item-name ant-upload-list-item-name-icon-count-1" contains fileDoc.doc

I made this

  candidateUploadFileButton = '#filesUpload';
  candidateUploadRemoveButton = '.ant-upload-list-item-card-actions > a';
cy.get(this.candidateUploadFileButton, {force: true}).contains(fileName);
cy.get(this.candidateUploadRemoveButton).click();

It works for a single input only for a single div class, if there two classes like in the previously example , it doesn't work beacuse it says there are multiple values

I added this picture, maybe it will help what i want to do, i want to press Remove button for the file named "fileDoc.doc"
https://i.stack.imgur.com/voQqp.png

Body:
Refer here:

As per your markup, you can use this:

cy.contains(fileName).next().find('> a').click()


来源: stackexchange

问:
Is this possible: JPA/Hibernate query with list property in result?
In hibernate I want to run this JPQL / HQL query:

```<code>select new org.test.userDTO( u.id, u.name, u.securityRoles)
FROM User u
WHERE u.name = :name
</code>```

userDTO class:

```<code>public class UserDTO {
   private Integer id;
   private String name;
   private List<SecurityRole> securityRoles;

   public UserDTO(Integer id, String name, List<SecurityRole> securityRoles) {
     this.id = id;
     this.name = name;
     this.securityRoles = securityRoles;
   }

   ...getters and setters...
}
</code>```

User Entity:

```<code>@Entity
public class User {

  @id
  private Integer id;

  private String name;

  @ManyToMany
  @JoinTable(name = "user_has_role",
      joinColumns = { @JoinColumn(name = "user_id") },
      inverseJoinColumns = {@JoinColumn(name = "security_role_id") }
  )
  private List<SecurityRole> securityRoles;

  ...getters and setters...
}
</code>```

But when Hibernate 3.5 (JPA 2) starts I get this error:

```<code>org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate
constructor on class [org.test.UserDTO] [SELECT NEW org.test.UserDTO (u.id,
u.name, u.securityRoles) FROM nl.test.User u WHERE u.name = :name ]
</code>```

Is a select that includes a list (u.securityRoles) as a result not possible? Should I just create 2 seperate queries?

答:
I think that you should try something like:</p>

```<code>select new org.test.userDTO( u.id, u.name, u.securityRoles) AS uDTO,
  uDTO.setRoles(u.securityRoles)
 FROM User u
 WHERE u.name = :name
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In hibernate I want to run this JPQL / HQL query:

select new org.test.userDTO( u.id, u.name, u.securityRoles)
FROM User u
WHERE u.name = :name

userDTO class:

public class UserDTO {
   private Integer id;
   private String name;
   private List<SecurityRole> securityRoles;

   public UserDTO(Integer id, String name, List<SecurityRole> securityRoles) {
     this.id = id;
     this.name = name;
     this.securityRoles = securityRoles;
   }

   ...getters and setters...
}

User Entity:

@Entity
public class User {

  @id
  private Integer id;

  private String name;

  @ManyToMany
  @JoinTable(name = "user_has_role",
      joinColumns = { @JoinColumn(name = "user_id") },
      inverseJoinColumns = {@JoinColumn(name = "security_role_id") }
  )
  private List<SecurityRole> securityRoles;

  ...getters and setters...
}

But when Hibernate 3.5 (JPA 2) starts I get this error:

org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate
constructor on class [org.test.UserDTO] [SELECT NEW org.test.UserDTO (u.id,
u.name, u.securityRoles) FROM nl.test.User u WHERE u.name = :name ]

Is a select that includes a list (u.securityRoles) as a result not possible? Should I just create 2 seperate queries?

Body:
I think that you should try something like:

select new org.test.userDTO( u.id, u.name, u.securityRoles) AS uDTO,
  uDTO.setRoles(u.securityRoles)
 FROM User u
 WHERE u.name = :name

ContentLicense: CC BY-SA 3.0


问:
connect and withRouter issue
I am using Redux and React for my project. I have some Routes in App.js. I also use the connect function in react-redux in my project. To prevent update blocking issue, I usually wrapped my component in this way

```<code>withRouter(connect(mapStateToProps, mapDispatchToProps)(App)),
</code>```

However, If I changed order of withRouter and connect it doesn't work:

```<code>connect(mapStateToProps, mapDispatchToProps)(withRouter(App))
</code>```

I have console.log the props in App.js. It already receives location and history props. I am figuring out the theory behind why the order does matter ?

答:
If someone still has the issue then plz follow this one

const ShowTheLocationWithRouter = withRouter(Login);

export default connect(mapStateToProps, mapDispatchToProps)(ShowTheLocationWithRouter);
```

ContentLicense: CC BY-SA 4.0

Title: connect and withRouter issue

Body:
I am using Redux and React for my project. I have some Routes in App.js. I also use the connect function in react-redux in my project. To prevent update blocking issue, I usually wrapped my component in this way

withRouter(connect(mapStateToProps, mapDispatchToProps)(App)),

However, If I changed order of withRouter and connect it doesn't work:

connect(mapStateToProps, mapDispatchToProps)(withRouter(App))

I have console.log the props in App.js. It already receives location and history props. I am figuring out the theory behind why the order does matter ?


问:
How to convert exactPageList from any to any[] when assign it to pagefield?
I work on angular 7 app I face issue on paging cannot assign exactpagelist any to pagefield any[] .

because pagefield is type array and exactpagelist is type any .

issue exist on last line of function totalNoOfPages on this line

```<code>this.pageField = this.exactPageList;
this.pageField = 2; not correct
</code>```

I expected to be

```<code>this.pageField = [1,2];
</code>```

meaning i need to convert this.exactPageList; to array to be accepted assign to pagefield
How to do that ?

```<code>pageField:any[];
exactPageList:any;
totalNoOfPages() {

    this.paginationData = Number(this.totalReportCount / this.ReportPerPage);
    console.log("pagination data :" + this.paginationData)
    let tempPageData = this.paginationData.toFixed();
    console.log("tempPageData data :" + tempPageData)
    if (Number(tempPageData) < this.paginationData) {
      this.exactPageList = Number(tempPageData) + 1;
      this.paginationService.exactPageList = this.exactPageList;
      console.log("exactPageList1  data :" + this.exactPageList )
    } else {
      this.exactPageList = Number(tempPageData);
      this.paginationService.exactPageList = this.exactPageList
      console.log("exactPageList2  data" + this.exactPageList )
    }
    this.paginationService.pageOnLoad();
    this.pageField = this.exactPageList;

  }
</code>```

Result of code above as below :

```<code>pagination data1.0666666666666667
reportdetails.component.ts:265 tempPageData data1
reportdetails.component.ts:269 exactPageList1  data2
reportdetails.component.ts:263 pagination data1.0666666666666667
reportdetails.component.ts:265 tempPageData data1
reportdetails.component.ts:269 exactPageList1  data2
</code>```

Expected result

```<code>this.pageField = [1,2];
</code>```

答:
Some explanation by using comments:

```<code>this.paginationData = Number(this.totalReportCount / this.ReportPerPage);
console.log("pagination data :" + this.paginationData)
// Use Math.round instead. Then you get an numeral and not a string.
let tempPageData = this.paginationData.toFixed();
console.log("tempPageData data :" + tempPageData)
// Then Number() is not necessary here anymore.
// Moreover as far as I understand, you actually want to use always the 'bigger number'.
// That means, actually it would make sense to use Math.ceil() above.
// In that case, you don't need to use a condition at all.
if (Number(tempPageData) < this.paginationData) {
  this.exactPageList = Number(tempPageData) + 1;
  this.paginationService.exactPageList = this.exactPageList;
  console.log("exactPageList1  data :" + this.exactPageList )
} else {
  // You are doing almost the same like in the condition clause above.
  // It would be enough to set this.exactPageList condtionally and do the rest afterwards.
  this.exactPageList = Number(tempPageData);
  this.paginationService.exactPageList = this.exactPageList
  console.log("exactPageList2  data" + this.exactPageList )
}
this.paginationService.pageOnLoad();
this.pageField = this.exactPageList;
</code>```

What I would do:

```<code>this.paginationData = Number(this.totalReportCount / this.ReportPerPage);
console.log("pagination data :", this.paginationData)
let tempPageData = Math.ceil(this.paginationData);
console.log("tempPageData data :", tempPageData)
// Let's create an array from 1 .. N
// [...Array(4).keys()] would create an array with [0,1,2,3]
// but we want to have [1,2,3,4], that's why we are incrementing every value by using map().
// Think about moving this to an own method 'getOneToNArray' or so for a better readability.
this.exactPageList = [...Array(tempPageData).keys()].map(x => ++x);;
this.paginationService.exactPageList = this.exactPageList;
console.log("exactPageList data :", this.exactPageList )
this.paginationService.pageOnLoad();
this.pageField = this.exactPageList;
</code>```

Body:
I work on angular 7 app I face issue on paging cannot assign exactpagelist any to pagefield any[] .

because pagefield is type array and exactpagelist is type any .

issue exist on last line of function totalNoOfPages on this line

this.pageField = this.exactPageList;
this.pageField = 2; not correct

I expected to be

this.pageField = [1,2];

meaning i need to convert this.exactPageList; to array to be accepted assign to pagefield
How to do that ?

pageField:any[];
exactPageList:any;
totalNoOfPages() {

    this.paginationData = Number(this.totalReportCount / this.ReportPerPage);
    console.log("pagination data :" + this.paginationData)
    let tempPageData = this.paginationData.toFixed();
    console.log("tempPageData data :" + tempPageData)
    if (Number(tempPageData) < this.paginationData) {
      this.exactPageList = Number(tempPageData) + 1;
      this.paginationService.exactPageList = this.exactPageList;
      console.log("exactPageList1  data :" + this.exactPageList )
    } else {
      this.exactPageList = Number(tempPageData);
      this.paginationService.exactPageList = this.exactPageList
      console.log("exactPageList2  data" + this.exactPageList )
    }
    this.paginationService.pageOnLoad();
    this.pageField = this.exactPageList;

  }

Result of code above as below :

pagination data1.0666666666666667
reportdetails.component.ts:265 tempPageData data1
reportdetails.component.ts:269 exactPageList1  data2
reportdetails.component.ts:263 pagination data1.0666666666666667
reportdetails.component.ts:265 tempPageData data1
reportdetails.component.ts:269 exactPageList1  data2

Expected result

this.pageField = [1,2];

Body:
Some explanation by using comments:

this.paginationData = Number(this.totalReportCount / this.ReportPerPage);
console.log("pagination data :" + this.paginationData)
// Use Math.round instead. Then you get an numeral and not a string.
let tempPageData = this.paginationData.toFixed();
console.log("tempPageData data :" + tempPageData)
// Then Number() is not necessary here anymore.
// Moreover as far as I understand, you actually want to use always the 'bigger number'.
// That means, actually it would make sense to use Math.ceil() above.
// In that case, you don't need to use a condition at all.
if (Number(tempPageData) < this.paginationData) {
  this.exactPageList = Number(tempPageData) + 1;
  this.paginationService.exactPageList = this.exactPageList;
  console.log("exactPageList1  data :" + this.exactPageList )
} else {
  // You are doing almost the same like in the condition clause above.
  // It would be enough to set this.exactPageList condtionally and do the rest afterwards.
  this.exactPageList = Number(tempPageData);
  this.paginationService.exactPageList = this.exactPageList
  console.log("exactPageList2  data" + this.exactPageList )
}
this.paginationService.pageOnLoad();
this.pageField = this.exactPageList;

What I would do:

this.paginationData = Number(this.totalReportCount / this.ReportPerPage);
console.log("pagination data :", this.paginationData)
let tempPageData = Math.ceil(this.paginationData);
console.log("tempPageData data :", tempPageData)
// Let's create an array from 1 .. N
// [...Array(4).keys()] would create an array with [0,1,2,3]
// but we want to have [1,2,3,4], that's why we are incrementing every value by using map().
// Think about moving this to an own method 'getOneToNArray' or so for a better readability.
this.exactPageList = [...Array(tempPageData).keys()].map(x => ++x);;
this.paginationService.exactPageList = this.exactPageList;
console.log("exactPageList data :", this.exactPageList )
this.paginationService.pageOnLoad();
this.pageField = this.exactPageList;


问:
How to get the closest previous different prop in ReactJS
I have a functional component with props:

```<code>function MyComponent({propA, propB, propC}) {
    ...
}
</code>```

This component is rendered few times with different props values. I need to get the closest previous prop value which is not equal to current value. For example:

First render. propA is 1. previous value must be undefined

Second render. propA is 2. previous value must be 1

Third render. propA is 2. previous value must be 1 (not 2, because
current value is 2)

There is a similar "usePrevious" hook:

```<code>export const usePrevious = <T>(value: T): T | undefined => {
  const ref = useRef<T>();

  useEffect(() => {
    ref.current = value;
  });

  return ref.current;
};
</code>```

But it returns any previous value even if it has not changed. And it looks like I should modify this hook, but I don't know how

code example: https://codesandbox.io/s/cranky-snow-mkile?file=/src/index.js (props values are logged in console)

答:
Try this:</p>

```<code>const usePrevious = newValue => {
  const refPrev = useRef()
  const refCurr = useRef()

  if (newValue !== refCurr.current) {
    refPrev.current = refCurr.current;
    refCurr.current = newValue;
  }

  return refPrev.current;
}
</code>```

Body:
I have a functional component with props:

function MyComponent({propA, propB, propC}) {
    ...
}

This component is rendered few times with different props values. I need to get the closest previous prop value which is not equal to current value. For example:

First render. propA is 1. previous value must be undefined

Second render. propA is 2. previous value must be 1

Third render. propA is 2. previous value must be 1 (not 2, because
current value is 2)

There is a similar "usePrevious" hook:

export const usePrevious = <T>(value: T): T | undefined => {
  const ref = useRef<T>();

  useEffect(() => {
    ref.current = value;
  });

  return ref.current;
};

But it returns any previous value even if it has not changed. And it looks like I should modify this hook, but I don't know how

code example: https://codesandbox.io/s/cranky-snow-mkile?file=/src/index.js (props values are logged in console)

Body:
Try this:

const usePrevious = newValue => {
  const refPrev = useRef()
  const refCurr = useRef()

  if (newValue !== refCurr.current) {
    refPrev.current = refCurr.current;
    refCurr.current = newValue;
  }

  return refPrev.current;
}


问:
As a system user I have this error: ORA-01031: insufficient privileges
I have a stored procedure for deleting partitions. Before starting, I have to delete a constraint.

I installed the stored procedure on system user. When I test the procedure I have this error: 'ORA-01031: insufficient privileges'.

This is a piece of code that I wrote:

```<code>BEGIN

    EXECUTE IMMEDIATE 'ALTER TABLE USER_NAME.TABLE_NAME DISABLE CONSTRAINT CONSTRAINT_NAME';

EXCEPTION
    WHEN OTHERS THEN

        O_sCodError := 'NO_OK';
        O_sDesError := 'Error at DISABLE CONSTRAINT_NAME: ' || SQLERRM || ';';

        RETURN;

END;
</code>```

Well, as I execute the stored procedure as system, I do not understand the reason for I have that error. And I think I eventually think the same error when I try to delete a partition.

答:
First, you should never install custom code in an Oracle default schema like SYSTEM. Put your code in a dedicated application schema. Since it contains dynamic SQL (execute immediate) you might want to consider making it an "invoker's rights" procedure, then granting execute privileges on it to the user that will execute it.

That said, in Oracle 11g whoever's privileges are used to run the PL/SQL block must have direct permissions on the underlying table, not inherited permissions through a role like DBA. If the procedure has "definer's rights" then the schema that owns the procedure must have direct privileges on the table. If "invoker's rights" then the user executing the procedure must have the privileges.

See this link for additional details:
 Execute immediate within Oracle Procedure

Body:
I have a stored procedure for deleting partitions. Before starting, I have to delete a constraint.

I installed the stored procedure on system user. When I test the procedure I have this error: 'ORA-01031: insufficient privileges'.

This is a piece of code that I wrote:

BEGIN

    EXECUTE IMMEDIATE 'ALTER TABLE USER_NAME.TABLE_NAME DISABLE CONSTRAINT CONSTRAINT_NAME';

EXCEPTION
    WHEN OTHERS THEN

        O_sCodError := 'NO_OK';
        O_sDesError := 'Error at DISABLE CONSTRAINT_NAME: ' || SQLERRM || ';';

        RETURN;

END;

Well, as I execute the stored procedure as system, I do not understand the reason for I have that error. And I think I eventually think the same error when I try to delete a partition.


问:
unknown problem reaction detection discord.py
I'm writing a command to add roles to a user by having them react to a message. here is my code:

```<code>@BOT.command(pass_context = True , name = "join_game")
async def join_game(context):
    roles = {"minecraft" : "minecraft" , "AC" : "animal crossing" , "pokemon" : "pokemon"} #"emoji_name" : "role_name" , ...
    roleEmojis = {get(context.message.guild.emojis, name = emoji_name) : get(context.message.guild.roles , name = role_name) for emoji_name , role_name in zip(roles , roles.keys())}
    reactions = []
    msg = await context.message.channel.send("react with which game(s) you would like to be a part of.\n**press the :OK: when you are done**")

    for emoji in roleEmojis.keys():
        await msg.add_reaction(emoji)
    await msg.add_reaction(get(context.message.guild.emojis, name = "OK"))

    while True:
        reaction , user = await BOT.wait_for("reaction_add" , check = lambda react , user : True if react in [emoji for emoji in roleEmojis.keys()] and user == BOT.user else False)
        if reaction == get(context.message.guild.emojis, name = "OK"):
            continue
        else:
            reactions.append(reaction)

    print(reactions)

    #add roles
</code>```

everything works as expected, there are no errors but it won't detect when I add a reaction, as in there is no output and the while loop continues on forever without breaking. I am confident it is to do with my check function, but to be honest I'm not all that sure. ill not that this is my first attempt at my first bot and I likely missed something very obvious.

答:
You should try using the client event on_reaction_add.

(I'm assuming that you already have defined get() elsewhere in the code)

@BOT.command(pass_context = True , name = "join_game")
async def join_game(context):
    roles = {"minecraft" : "minecraft" , "AC" : "animal crossing" , "pokemon" : "pokemon"} #"emoji_name" : "role_name" , ...
    roleEmojis = {get(context.message.guild.emojis, name = emoji_name) : get(context.message.guild.roles , name = role_name) for emoji_name , role_name in zip(roles , roles.keys())}
    reactions = []
    msg = await context.message.channel.send("react with which game(s) you would like to be a part of.\n**press the :OK: when you are done**")

@BOT.event
async def on_reaction_add(reaction, user):

    # check if the user did the command #
    message = reaction.message
    if reaction.emoji == get(message.guild.emojis, name='minecraft'):
        role_to_assign = message.guild.get_role(ID_OF_MINECRAFT_ROLE_GOES_HERE)
    elif reaction.emoji == get(message.guild.emojis, name='AC'):
        role_to_assign = message.guild.get_role(ID_OF_ANIMALCROSSING_ROLE_GOES_HERE)
    elif reaction.emoji == get(message.guild.emojis, name='pokemon'):
        role_to_assign = message.guild.get_role(ID_OF_POKEMON_ROLE_GOES_HERE)
    elif reaction.emoji == get(message.guild.emojis, name='OK'):
        # do stuff to clean up (no more roles assigned) #
        return
    await user.add_role(role_to_assign)
```

Body:
I'm writing a command to add roles to a user by having them react to a message. here is my code:

@BOT.command(pass_context = True , name = "join_game")
async def join_game(context):
    roles = {"minecraft" : "minecraft" , "AC" : "animal crossing" , "pokemon" : "pokemon"} #"emoji_name" : "role_name" , ...
    roleEmojis = {get(context.message.guild.emojis, name = emoji_name) : get(context.message.guild.roles , name = role_name) for emoji_name , role_name in zip(roles , roles.keys())}
    reactions = []
    msg = await context.message.channel.send("react with which game(s) you would like to be a part of.\n**press the :OK: when you are done**")

    for emoji in roleEmojis.keys():
        await msg.add_reaction(emoji)
    await msg.add_reaction(get(context.message.guild.emojis, name = "OK"))

    while True:
        reaction , user = await BOT.wait_for("reaction_add" , check = lambda react , user : True if react in [emoji for emoji in roleEmojis.keys()] and user == BOT.user else False)
        if reaction == get(context.message.guild.emojis, name = "OK"):
            continue
        else:
            reactions.append(reaction)

    print(reactions)

    #add roles

everything works as expected, there are no errors but it won't detect when I add a reaction, as in there is no output and the while loop continues on forever without breaking. I am confident it is to do with my check function, but to be honest I'm not all that sure. ill not that this is my first attempt at my first bot and I likely missed something very obvious.


问:
can't define a function - based lookup table
I am trying to define a function based lookup table - an array of objects, each contains a function (existing function, not arrow function) and a string. I have tryied:

let lookup_table = [{'foo', bar}, {'abc', def}];
(.....)
function bar(command){(..)}
function def(command){(..)}
```

<p>another (and more prefered) soulotion will be to refer to the function by a string index, somethig like that</p>

<pre class="lang-js prettyprint-override"><code>lookup_table['foo']('abc'); //=bar('abc')
</code>```

答:
You have set an array for lookup_table when all you really need is a single object.

Syntax error also using comma as separator between property and value in your objects

The following example works

function bar(command){console.log('Called bar() , command =', command)}
function def(command){console.log('Called def() , command =', command)}

let lookup_table = {'foo': bar,'abc': def};

lookup_table['foo']('abc');
lookup_table['abc']('123');```

Body:
I am trying to define a function based lookup table - an array of objects, each contains a function (existing function, not arrow function) and a string. I have tryied:

let lookup_table = [{'foo', bar}, {'abc', def}];
(.....)
function bar(command){(..)}
function def(command){(..)}

another (and more prefered) soulotion will be to refer to the function by a string index, somethig like that

lookup_table['foo']('abc'); //=bar('abc')


问:
Kubernetes in-cluster authentication
it seems that my AKS cluster is unable to perform basic requests to the k8s api, i.e. using the in-cluster token for the pods. Everything works fine when I use the same code from my local machine, i.e. with config.load_kube_config .

I am using the python k8s client 11.0.0, and I am loading the configuration through config.load_incluster_config(). I get the following error:

HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}

when trying to simply list my pods (using client.list_namespaced_pod). I also tried to perform a raw get request, but same result.

I tried to extend the cluster role to specifically access the resources, here my clusterrole and clusterrolebinding:

```<code>apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: clusterrolename
rules:
- apiGroups:
  - ""
  resources:
  - pods
  - namespaces
  verbs:
  - get
  - list
- apiGroups:
  - metrics.k8s.io
  resources:
  - '*'
  verbs:
  - get
  - list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: clusterrolebindingname
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: clusterrolename
subjects:
- kind: ServiceAccount
  name: default
  namespace: mynamespace
</code>```

but I have always the same result.

The same approach does not work equally on linux and windows nodes.

The use of the very same approach was successful before on linux machine (pure linux cluster).

Could it be related to the SDK version?
Could it be something different in the cluster?
Does anyone know how I could retrieve a list of the authorisation for any specific ServiceAccount?

答:
the pod had indeed the necessary rights. The error was in the wrong initialisation of the api_client instance, which I performed separately just calling client.Configuration().

I solved the problem avoiding to initialise the api_client instance, and importing the one directly from client.CoreV1Api.

Title: Kubernetes in-cluster authentication

Body:
it seems that my AKS cluster is unable to perform basic requests to the k8s api, i.e. using the in-cluster token for the pods. Everything works fine when I use the same code from my local machine, i.e. with config.load_kube_config .

I am using the python k8s client 11.0.0, and I am loading the configuration through config.load_incluster_config(). I get the following error:

HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}

when trying to simply list my pods (using client.list_namespaced_pod). I also tried to perform a raw get request, but same result.

I tried to extend the cluster role to specifically access the resources, here my clusterrole and clusterrolebinding:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: clusterrolename
rules:
- apiGroups:
  - ""
  resources:
  - pods
  - namespaces
  verbs:
  - get
  - list
- apiGroups:
  - metrics.k8s.io
  resources:
  - '*'
  verbs:
  - get
  - list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: clusterrolebindingname
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: clusterrolename
subjects:
- kind: ServiceAccount
  name: default
  namespace: mynamespace

but I have always the same result.

The same approach does not work equally on linux and windows nodes.

The use of the very same approach was successful before on linux machine (pure linux cluster).

Could it be related to the SDK version?
Could it be something different in the cluster?
Does anyone know how I could retrieve a list of the authorisation for any specific ServiceAccount?


问:
I tried validating my css file but cant find the issue for resizing to tablet size for grid layout
Sorry im new to HTML/CSS. I have a CSS file that I believe to be working everything works except I cant figure out why my resizing from large screen to medium screen to small screen doesnt work. It jumps from 3 boxes in a row to 3 boxes in a column. Im trying to make the medium screen resize to 2 smaller boxes on top with 1 larger box on bottom. Sorry if this is a bad question. I will post my css file I dont believe its the HTML file. Thank you for helping

      * {
  box-sizing: border-box;
}

h1 {
  color: black;
  text-align: center;
}

h2 {
  color: black;
  border: 1px solid black;
  float: right;
  position: relative;
  top: -26px;
  left: 21px;
  width: 150px;
}

section {
  color: black;
  text-align: center;
  background: grey;
  border: 1px solid black;
  height: 100%;
  width: 85%;
  font-family: sans-serif;
  padding: 5px 20px 5px 20px;
  margin-top: 5%;
  margin-left: 16px;
  position: relative;
}

p {
  position: relative;
  bottom: 30px;
  clear: right;
}

#Chicken {
  background-color: salmon;
}

#Beef {
  background-color: red;
}

#Sushi {
  background-color: green;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%
  }
  .col-lg-2 {
    width: 16.66%
  }
  .col-lg-3 {
    width: 25%
  }
  .col-lg-4 {
    width: 33.33%
  }
  .col-lg-5 {
    width: 41.66%
  }
  .col-lg-6 {
    width: 50%
  }
  .col-lg-7 {
    width: 58.33%
  }
  .col-lg-8 {
    width: 66.66%
  }
  .col-lg-9 {
    width: 74.99%
  }
  .col-lg-10 {
    width: 83.33%
  }
  .col-lg-11 {
    width: 91.66%
  }
  .col-lg-12 {
    width: 100%
  }
  @media (min-width: 768px) and (max-width: 991px) {
    .col-md-1,
    .col-md-2,
    .col-md-3,
    .col-md-4,
    .col-md-5,
    .col-md-6,
    .col-md-7,
    .col-md-8,
    .col-md-9,
    .col-md-10,
    .col-md-11,
    .col-md-12 {
      float: left;
    }
    .col-md-1 {
      width: 8.33%
    }
    .col-md-2 {
      width: 16.66%
    }
    .col-md-3 {
      width: 25%
    }
    .col-md-4 {
      width: 33.33%
    }
    .col-md-5 {
      width: 41.66%
    }
    .col-md-6 {
      width: 50%
    }
    .col-md-7 {
      width: 58.33%
    }
    .col-md-8 {
      width: 66.66%
    }
    .col-md-9 {
      width: 74.99%
    }
    .col-md-10 {
      width: 83.33%
    }
    .col-md-11 {
      width: 91.66%
    }
    .col-md-12 {
      width: 100%
    }
    @media (max-width: 767px) {
      .col-sm-1,
      .col-sm-2,
      .col-sm-3,
      .col-sm-4,
      .col-sm-5,
      .col-sm-6,
      .col-sm-7,
      .col-sm-8,
      .col-sm-9,
      .col-sm-10,
      .col-sm-11,
      .col-sm-12 {
        float: left;
      }
      .col-sm-1 {
        width: 8.33%
      }
      .col-sm-2 {
        width: 16.66%
      }
      .col-sm-3 {
        width: 25%
      }
      .col-sm-4 {
        width: 33.33%
      }
      .col-sm-5 {
        width: 41.66%
      }
      .col-sm-6 {
        width: 50%
      }
      .col-sm-7 {
        width: 58.33%
      }
      .col-sm-8 {
        width: 66.66%
      }
      .col-sm-9 {
        width: 74.99%
      }
      .col-sm-10 {
        width: 83.33%
      }
      .col-sm-11 {
        width: 91.66%
      }
      .col-sm-12 {
        width: 100%
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>module2-solution css</title>
</head>

<body>
  <h1>Our Menu</h1>
  <div class="col-lg-4 col-md-6 col-sm-12">
    <section>
      <h2 id="Chicken">Chicken</h2>
      <p>Heat the olive oil in a small, non-stick pan over medium heat. Crack the egg directly into the pan and season generously with salt and pepper. Cook for about two minutes, then use a spatula to flip the egg, being careful not to break the yolk. For
        a runny yolk, turn off the heat and let the egg sit for one minute.</p>
    </section>
  </div>
  <div class="col-lg-4 col-md-6 col-sm-12">
    <section>
      <h2 id="Beef">Beef</h2>
      <p>Heat the olive oil in a small, non-stick pan over medium heat. Crack the egg directly into the pan and season generously with salt and pepper. Cook for about two minutes, then use a spatula to flip the egg, being careful not to break the yolk. For
        a runny yolk, turn off the heat and let the egg sit for one minute.</p>
    </section>
  </div>
  <div class="col-lg-4 col-md-6 col-sm-12">
    <section>
      <h2 id="Sushi">Sushi</h2>
      <p>Heat the olive oil in a small, non-stick pan over medium heat. Crack the egg directly into the pan and season generously with salt and pepper. Cook for about two minutes, then use a spatula to flip the egg, being careful not to break the yolk. For
        a runny yolk, turn off the heat and let the egg sit for one minute.</p>
    </section>
  </div>
</body>

</html></code>```

答: I think it would be better if you used something called flexbox. I've used it before but don't remember anything except that it was great. If I were you I would look up the syntax for it. (; -A person on the internet</p>

Body:
Sorry im new to HTML/CSS. I have a CSS file that I believe to be working everything works except I cant figure out why my resizing from large screen to medium screen to small screen doesnt work. It jumps from 3 boxes in a row to 3 boxes in a column. Im trying to make the medium screen resize to 2 smaller boxes on top with 1 larger box on bottom. Sorry if this is a bad question. I will post my css file I dont believe its the HTML file. Thank you for helping

      * {
  box-sizing: border-box;
}

h1 {
  color: black;
  text-align: center;
}

h2 {
  color: black;
  border: 1px solid black;
  float: right;
  position: relative;
  top: -26px;
  left: 21px;
  width: 150px;
}

section {
  color: black;
  text-align: center;
  background: grey;
  border: 1px solid black;
  height: 100%;
  width: 85%;
  font-family: sans-serif;
  padding: 5px 20px 5px 20px;
  margin-top: 5%;
  margin-left: 16px;
  position: relative;
}

p {
  position: relative;
  bottom: 30px;
  clear: right;
}

#Chicken {
  background-color: salmon;
}

#Beef {
  background-color: red;
}

#Sushi {
  background-color: green;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%
  }
  .col-lg-2 {
    width: 16.66%
  }
  .col-lg-3 {
    width: 25%
  }
  .col-lg-4 {
    width: 33.33%
  }
  .col-lg-5 {
    width: 41.66%
  }
  .col-lg-6 {
    width: 50%
  }
  .col-lg-7 {
    width: 58.33%
  }
  .col-lg-8 {
    width: 66.66%
  }
  .col-lg-9 {
    width: 74.99%
  }
  .col-lg-10 {
    width: 83.33%
  }
  .col-lg-11 {
    width: 91.66%
  }
  .col-lg-12 {
    width: 100%
  }
  @media (min-width: 768px) and (max-width: 991px) {
    .col-md-1,
    .col-md-2,
    .col-md-3,
    .col-md-4,
    .col-md-5,
    .col-md-6,
    .col-md-7,
    .col-md-8,
    .col-md-9,
    .col-md-10,
    .col-md-11,
    .col-md-12 {
      float: left;
    }
    .col-md-1 {
      width: 8.33%
    }
    .col-md-2 {
      width: 16.66%
    }
    .col-md-3 {
      width: 25%
    }
    .col-md-4 {
      width: 33.33%
    }
    .col-md-5 {
      width: 41.66%
    }
    .col-md-6 {
      width: 50%
    }
    .col-md-7 {
      width: 58.33%
    }
    .col-md-8 {
      width: 66.66%
    }
    .col-md-9 {
      width: 74.99%
    }
    .col-md-10 {
      width: 83.33%
    }
    .col-md-11 {
      width: 91.66%
    }
    .col-md-12 {
      width: 100%
    }
    @media (max-width: 767px) {
      .col-sm-1,
      .col-sm-2,
      .col-sm-3,
      .col-sm-4,
      .col-sm-5,
      .col-sm-6,
      .col-sm-7,
      .col-sm-8,
      .col-sm-9,
      .col-sm-10,
      .col-sm-11,
      .col-sm-12 {
        float: left;
      }
      .col-sm-1 {
        width: 8.33%
      }
      .col-sm-2 {
        width: 16.66%
      }
      .col-sm-3 {
        width: 25%
      }
      .col-sm-4 {
        width: 33.33%
      }
      .col-sm-5 {
        width: 41.66%
      }
      .col-sm-6 {
        width: 50%
      }
      .col-sm-7 {
        width: 58.33%
      }
      .col-sm-8 {
        width: 66.66%
      }
      .col-sm-9 {
        width: 74.99%
      }
      .col-sm-10 {
        width: 83.33%
      }
      .col-sm-11 {
        width: 91.66%
      }
      .col-sm-12 {
        width: 100%
      }

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>module2-solution css</title>

Our Menu

Chicken

Heat the olive oil in a small, non-stick pan over medium heat. Crack the egg directly into the pan and season generously with salt and pepper. Cook for about two minutes, then use a spatula to flip the egg, being careful not to break the yolk. For
        a runny yolk, turn off the heat and let the egg sit for one minute.

Beef

Heat the olive oil in a small, non-stick pan over medium heat. Crack the egg directly into the pan and season generously with salt and pepper. Cook for about two minutes, then use a spatula to flip the egg, being careful not to break the yolk. For
        a runny yolk, turn off the heat and let the egg sit for one minute.

Sushi

Heat the olive oil in a small, non-stick pan over medium heat. Crack the egg directly into the pan and season generously with salt and pepper. Cook for about two minutes, then use a spatula to flip the egg, being careful not to break the yolk. For
        a runny yolk, turn off the heat and let the egg sit for one minute.


问:
Extract Numeric and Special Characters Separately
I have column in a table with values stored as

```<code>Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05
</code>```

Now, I need to store these values to another table like

```<code>Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05
</code>```

Plz let me the Query how to do this....

答:
I'd use Perl for this...</p>

```<code>#!/usr/bin/perl
use strict;
use warnings;

open(FH,"<data.txt");

my @lines=<FH>;

print "Currency"."\t"."Cost\n";

foreach my $line (@lines){
    $line=~s/\n//g;
    if($line ne ""){
        my @split1=split(/\s+/,$line);
        if($split1[0]=~m/[0-9.]/){
            print "\t".$split1[0]."\n";
        }else{
            print $split1[0]."\t".$split1[1]."\n";
        }
    }
}
</code>```

Body:
I have column in a table with values stored as

Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05

Now, I need to store these values to another table like

Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05

Plz let me the Query how to do this....

Body:
I'd use Perl for this...

#!/usr/bin/perl
use strict;
use warnings;

open(FH,"<data.txt");

my @lines=<FH>;

print "Currency"."\t"."Cost\n";

foreach my $line (@lines){
    $line=~s/\n//g;
    if($line ne ""){
        my @split1=split(/\s+/,$line);
        if($split1[0]=~m/[0-9.]/){
            print "\t".$split1[0]."\n";
        }else{
            print $split1[0]."\t".$split1[1]."\n";
        }
    }
}


问:
Exporting a Dynamoose Typescript model

The dynamoose library provides the following signature for constructing a model:

```<code>    model: {
        <T extends Document>(name: string, schema?: SchemaDefinition | Schema, options?: Partial<import("./Model").ModelOptions>): T & Model<T> & ModelDocumentConstructor<T>;
        defaults: any;
    };
</code>```

Consumption in a TypeScript file is being done as follows:

import * as dynamoose from 'dynamoose';
...
const ExampleRepository = dynamoose.model(
  schemaName,
  ExampleSchema,
);

export default ExampleRepository;
```

<ol start="3">
<li>Compilation produces the error:</li>
</ol>

```Exported variable 'ExampleRepository' has or is using name 'ModelDocumentConstructor' from external module ".../node_modules/dynamoose/dist/index" but cannot be named.
```

Other answers to similar questions on SO would suggest that the ModelDocumentConstructor should be imported. TS4023: Exported Variable <x> has or is using name <y> from external module but cannot be named

However the interface itself is not exported, so cannot be imported.

答:
Since ModelDocumentConstructor is not exported, I have implemented the following solution as a workaround.  Create a second wrapper object to export, which contains the methods you need.

For example:

const Model = dynamoose.model('MyObj', Schema, {
  create: false,
  update: false,
});

async function add(obj: {}) {
  try {
    await Model.create(obj);
  } catch (e) {
    console.error(e);
  }
}

async function findMany(obj: { [key: string]: any }) {
  try {
    return await Model.batchGet(obj);
  } catch (e) {
    console.error(e);
  }
}

...

export const myObjDb = {
  find,
  findMany,
  add,
  remove,
  update,
  updateMany,
};```

Title: Exporting a Dynamoose Typescript model

Body:
The dynamoose library provides the following signature for constructing a model:

    model: {
        <T extends Document>(name: string, schema?: SchemaDefinition | Schema, options?: Partial<import("./Model").ModelOptions>): T & Model<T> & ModelDocumentConstructor<T>;
        defaults: any;
    };

Consumption in a TypeScript file is being done as follows:

import * as dynamoose from 'dynamoose';
...
const ExampleRepository = dynamoose.model(
  schemaName,
  ExampleSchema,
);

export default ExampleRepository;

Compilation produces the error:

Exported variable 'ExampleRepository' has or is using name 'ModelDocumentConstructor' from external module ".../node_modules/dynamoose/dist/index" but cannot be named.

Other answers to similar questions on SO would suggest that the ModelDocumentConstructor should be imported. TS4023: Exported Variable <x> has or is using name <y> from external module but cannot be named

However the interface itself is not exported, so cannot be imported.


问:
Make Bootstrap Column take full page width (or at least 90%)
I am working on a final project for a class, and am just learning how to use bootstrap. While I have some working knowledge of HTML and the like (or know where to go if I get stuck), the one thing I cannot figure out for the life of me is how to make the bootstrap columns take up more of the screen. I've copied and pasted the relevant code below, hopefully someone can tell me what I am doing wrong or if this can even be resolved!

I have been looking at other slack posts (I forgot to copy the link, sorry!) and the w3schools website, but am still having the same problem.

```<code><nav class="navbar navbar-expand-sm bg-white navbar-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#">Awards</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Resume</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Papers</a>
      </li>
    </ul>
  </div>
</nav>

<div class="container">
  <div class="row">
  <! –– The columns still aren't taking up 100% of the screen width. ––>
    <div class="col-sm-2">
        <! –– Ideally more to the left ––>
        Welcome the user to the website here
    </div>
    <div class="col-sm-4">
        Brief bit of information about me
    </div>
    <div class="col-sm-6">
        Image carosel (idk how to spell) with images of me, my friends & family
    </div>
  </div>
</div>
</code>```

答:
When you use container class its by default takes 80% of window width along with margin right and left auto. For 90% of window you need to use container-fluid class so it cover full width of window. Then you col-4 col-2 and col-5 to achieve 90%.

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

  </button>

        Awards

        Resume

        Papers

  <! –– The columns still aren't taking up 100% of the screen width. ––>

        <! –– Ideally more to the left ––>
        Welcome the user to the website here

        Brief bit of information about me

        Image carosel (idk how to spell) with images of me, my friends & family

```
</div>
</div>
</p>

<p>Use this : </p>

<pre class="lang-html prettyprint-override"><code><div class="container-fluid">
  <div class="row">
  <! –– The columns still aren't taking up 100% of the screen width. ––>
    <div class="col-sm-2">
        <! –– Ideally more to the left ––>
        Welcome the user to the website here
    </div>
    <div class="col-sm-4">
        Brief bit of information about me
    </div>
    <div class="col-sm-5">
        Image carosel (idk how to spell) with images of me, my friends & family
    </div>
  </div>
</div>
</code>```

Body:
I am working on a final project for a class, and am just learning how to use bootstrap. While I have some working knowledge of HTML and the like (or know where to go if I get stuck), the one thing I cannot figure out for the life of me is how to make the bootstrap columns take up more of the screen. I've copied and pasted the relevant code below, hopefully someone can tell me what I am doing wrong or if this can even be resolved!

I have been looking at other slack posts (I forgot to copy the link, sorry!) and the w3schools website, but am still having the same problem.

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

  </button>

        Awards

        Resume

        Papers

  <! –– The columns still aren't taking up 100% of the screen width. ––>

        <! –– Ideally more to the left ––>
        Welcome the user to the website here

        Brief bit of information about me

        Image carosel (idk how to spell) with images of me, my friends & family

Body:
When you use container class its by default takes 80% of window width along with margin right and left auto. For 90% of window you need to use container-fluid class so it cover full width of window. Then you col-4 col-2 and col-5 to achieve 90%.

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-sm bg-white navbar-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" href="#">Awards</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Resume</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Papers</a>
      </li>
    </ul>
  </div>
</nav>

<div class="container-fluid">
  <div class="row">
  <! –– The columns still aren't taking up 100% of the screen width. ––>
    <div class="col-sm-2">
        <! –– Ideally more to the left ––>
        Welcome the user to the website here
    </div>
    <div class="col-sm-4">
        Brief bit of information about me
    </div>
    <div class="col-sm-5">
        Image carosel (idk how to spell) with images of me, my friends & family
    </div>
  </div>
</div>

Use this :

<div class="container-fluid">
  <div class="row">
  <! –– The columns still aren't taking up 100% of the screen width. ––>
    <div class="col-sm-2">
        <! –– Ideally more to the left ––>
        Welcome the user to the website here
    </div>
    <div class="col-sm-4">
        Brief bit of information about me
    </div>
    <div class="col-sm-5">
        Image carosel (idk how to spell) with images of me, my friends & family
    </div>
  </div>
</div>


问:
How to apply a .fillna() to a filtered dataframe?
I am learning pandas using a dataset of players from the womans world cup.

I want to apply a .fillna() on the results of the following filter of the main dataframe:

```<code>df[(df["pos"] == "GK") & (df["goals"].isnull())]
</code>```

How can I apply:

```<code>fillna(0, inplace=True)
</code>```

To the above filter, , on the 'goals' column.

I did use the below code but when I apply it, it runs but doesn't seem to work:

```<code>df.loc[df["pos"] == "GK"].loc[df["goals"].isnull()].loc[:,"goals"].fillna(0, inplace=True)
</code>```

答:
```<code>df[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals']=0
</code>```

That will solve your problem.

Body:
I am learning pandas using a dataset of players from the womans world cup.

I want to apply a .fillna() on the results of the following filter of the main dataframe:

df[(df["pos"] == "GK") & (df["goals"].isnull())]

How can I apply:

fillna(0, inplace=True)

To the above filter, , on the 'goals' column.

I did use the below code but when I apply it, it runs but doesn't seem to work:

df.loc[df["pos"] == "GK"].loc[df["goals"].isnull()].loc[:,"goals"].fillna(0, inplace=True)

Body:
df[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals']=0

That will solve your problem.


问:
Show/Hide dropdown menu based on previous selection
I would like to show an additional dropdown menu based on a user's selection. Using my case, if a user selects installments an additional dropdown menu would appear, it would then be hidden if the user changes its selection.

This is what I have tried

```<code>            <select name='installments' required class="form-control my-2" onclick="choose()">
                <option value="" disabled selected hidden>How would you like to pay?</option>
                {% for value, name in form.fields.installments.choices %}
                    <option value="{{value}}">{{name}}</option>
                {% endfor %}
            </select>
            <!-- if installments -->
            <select name='installnum' class="form-control my-2" style="display:none">
                <option value="" disabled selected hidden>How many months would you like to pay this over?</option>
                {% for value, name in form.fields.installmnum.choices %}
                    <option value="{{value}}">{{name}}</option>
                {% endfor %}
            </select>
</code>```

This is the javascript I wrote

```<code><script>
    function choose() {
        if (document.getElementById('installments').value == 'installments') {
            document.getElementById('installnum').style.display == 'block';
                } else {
                    document.getElementById('installnum').style.display = 'none';
                }
            }
</script>
</code>```

The idea is supposed to be if you select installments the dropdown menu installnum would appear

This is my forms.py with the list of options for each dropdown menu

```<code>installment_choices = (
    ('upfront', 'Upfront'),
    ('installments', 'Installments'),
)
installnum_choices = (
    ('2', '2 months'),
    ('3', '3 months'),
    ('4', '4 months'),
    ('5', '5 months'),
    ('6', '6 months'),
    ('7', '7 months'),
    ('8', '8 months'),
    ('9', '9 months'),
    ('10', '10 months'),
)
</code>```

答:
I'm not entirely sure this answers the question, but it looks like you're trying to access the DOM element and read it's value directly. I believe you need to look at the value generated by the event.</p>

```<code>function choose (event)
{
   event.preventDefault();
   if(event.value === "expected") { // ... then modify the css }
}
</code>```

Body:
I would like to show an additional dropdown menu based on a user's selection. Using my case, if a user selects installments an additional dropdown menu would appear, it would then be hidden if the user changes its selection.

This is what I have tried

            <select name='installments' required class="form-control my-2" onclick="choose()">
                <option value="" disabled selected hidden>How would you like to pay?</option>
                {% for value, name in form.fields.installments.choices %}
                    <option value="{{value}}">{{name}}</option>
                {% endfor %}
            </select>

            <select name='installnum' class="form-control my-2" style="display:none">
                <option value="" disabled selected hidden>How many months would you like to pay this over?</option>
                {% for value, name in form.fields.installmnum.choices %}
                    <option value="{{value}}">{{name}}</option>
                {% endfor %}
            </select>

This is the javascript I wrote

The idea is supposed to be if you select installments the dropdown menu installnum would appear

This is my forms.py with the list of options for each dropdown menu

installment_choices = (
    ('upfront', 'Upfront'),
    ('installments', 'Installments'),
)
installnum_choices = (
    ('2', '2 months'),
    ('3', '3 months'),
    ('4', '4 months'),
    ('5', '5 months'),
    ('6', '6 months'),
    ('7', '7 months'),
    ('8', '8 months'),
    ('9', '9 months'),
    ('10', '10 months'),
)

Body:
I'm not entirely sure this answers the question, but it looks like you're trying to access the DOM element and read it's value directly. I believe you need to look at the value generated by the event.

function choose (event)
{
   event.preventDefault();
   if(event.value === "expected") { // ... then modify the css }
}


问:
Black screen after loading SceneView, using Scenform, into a fragment
I am working on a project that will have a 3D model viewer in one fragment. In order to do so, I decided to use sceneform. I have encountered a problem with SceneView, after trying to display it, in my tab fragment.

Everything is done according to examples and sceneform documentation, but sceneView display black screen, regardless of the colour I am assigning.

Here is scene loader

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        vw = inflater.inflate(R.layout.fragment_open_gl, container, false);
        sceneView = vw.findViewById(R.id.scene_view);
        return vw;
    }
</code>```

And fragment :

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".OpenGL">

    <com.google.ar.sceneform.SceneView
        android:id="@+id/scene_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/Crimson"/>

</FrameLayout>

</code>```

答:
I solved the issue by adding pausing and resuming sceneview, along with the fragment: </p>

```<code>    @Override
    public void onPause() {
        super.onPause();
        sceneView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            sceneView.resume();
        } catch (CameraNotAvailableException e) {
            e.printStackTrace();
        }
    }
</code>```

Body:
I am working on a project that will have a 3D model viewer in one fragment. In order to do so, I decided to use sceneform. I have encountered a problem with SceneView, after trying to display it, in my tab fragment.

Everything is done according to examples and sceneform documentation, but sceneView display black screen, regardless of the colour I am assigning.

Here is scene loader

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        vw = inflater.inflate(R.layout.fragment_open_gl, container, false);
        sceneView = vw.findViewById(R.id.scene_view);
        return vw;
    }

And fragment :

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".OpenGL">

    <com.google.ar.sceneform.SceneView
        android:id="@+id/scene_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/Crimson"/>

</FrameLayout>

Body:
I solved the issue by adding pausing and resuming sceneview, along with the fragment:

    @Override
    public void onPause() {
        super.onPause();
        sceneView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            sceneView.resume();
        } catch (CameraNotAvailableException e) {
            e.printStackTrace();
        }
    }


问:
Sorting image name files in Matlab?
I have two different types of dicom(medical imaging files) in the same folder. I want to sort them into two different arrays one for the SE006 and the other for the SE014.

```<code>    MR-ST001-SE006-0001.dcm... MR-ST001-SE006-0021.dcm
    MR-ST001-SE014-0001.dcm... MR-ST001-SE014-0013.dcm
</code>```

I have been using something like this code below but it is wrong I think I have some syntax errors.

```<code>  if image == 'MR-ST001-SE006-%4.4.dcm'
      SE006(end+1) = image
  if image == 'MR-ST001-SE014-%4.4.dcm'
      SE014(end+1) = image
</code>```

Anyone have any tips to help improve this so it works?

答:
You can read all the files into a cell array with DIR command and then use CELLFUN to vectorize the solution from  @jonsca.</p>

```<code>files = dir('MR-ST001-SE*.dcm');
dcmnames = {files(:).name}';
idx06 = ~cellfun(@isempty,strfind(dcmnames,'SE006'));
idx14 = ~cellfun(@isempty,strfind(dcmnames,'SE014'));
SE006 = dcmnames(idx06);
SE014 = dcmnames(idx14);
</code>```

Title: Sorting image name files in Matlab?

Body:
I have two different types of dicom(medical imaging files) in the same folder. I want to sort them into two different arrays one for the SE006 and the other for the SE014.

    MR-ST001-SE006-0001.dcm... MR-ST001-SE006-0021.dcm
    MR-ST001-SE014-0001.dcm... MR-ST001-SE014-0013.dcm

I have been using something like this code below but it is wrong I think I have some syntax errors.

  if image == 'MR-ST001-SE006-%4.4.dcm'
      SE006(end+1) = image
  if image == 'MR-ST001-SE014-%4.4.dcm'
      SE014(end+1) = image

Anyone have any tips to help improve this so it works?

Body:
You can read all the files into a cell array with DIR command and then use CELLFUN to vectorize the solution from  @jonsca.

files = dir('MR-ST001-SE*.dcm');
dcmnames = {files(:).name}';
idx06 = ~cellfun(@isempty,strfind(dcmnames,'SE006'));
idx14 = ~cellfun(@isempty,strfind(dcmnames,'SE014'));
SE006 = dcmnames(idx06);
SE014 = dcmnames(idx14);


问:
Class level variables Javascript/Angular
I am new to angular I have a class level variable in my angular component called moratoriumID. I call a method which calls a POST and then assigns a number to moratoriumID that is returned from the POST . I believe this works as intended, as I see the number show up in the chrome debugger console . Later on I try to access the variable and use it. It says its undefined. Why ? What am I not understanding ? How can I use the moratoriumID later in code ? Any explanation would be most appreciated.  --Jason

```<code>export class AddMoratoriumsComponent implements OnInit {
   moratoriumID: number;

   //this gets called and assigns the moratoriumID from what I see
   PostMoratorium(moratoriumtopost: Moratorium):void {
     this.moratoriumService.PostMoratorium(moratoriumtopost)
    .pipe(takeUntil(this.ngUnsubscribe))
    .subscribe((data) => (this.moratoriumID) = (data),
    (error) => (console.log(error)),
    () => console.log('Post moratorium is complete', this.moratoriumID),
  );}

    //...I call it
      this.PostMoratorium(moratoriumtopost);

    //Later I try to use moratoriumID but it says its undefined ...why ?
       if (this.selectzipvalues.length>0){
         const res = this.isoLocs.filter(i => this.selectzipvalues.includes(i.zipCode));
         res.forEach(myFunction);
         function myFunction(item) {
            const moratoriumlocationstopost = {
              county:item.county ,
              city:item.city,
              zip:item.zipCode,
              moratoriumId:this.moratoriumID, //IT SAYS ITS UNDEFINED ..WHY ?
    } as MoratoriumLocation;
</code>```

}}

答: Answer seems to be be to use switchMap().</p>

Body:
I am new to angular I have a class level variable in my angular component called moratoriumID. I call a method which calls a POST and then assigns a number to moratoriumID that is returned from the POST . I believe this works as intended, as I see the number show up in the chrome debugger console . Later on I try to access the variable and use it. It says its undefined. Why ? What am I not understanding ? How can I use the moratoriumID later in code ? Any explanation would be most appreciated.  --Jason

export class AddMoratoriumsComponent implements OnInit {
   moratoriumID: number;

   //this gets called and assigns the moratoriumID from what I see
   PostMoratorium(moratoriumtopost: Moratorium):void {
     this.moratoriumService.PostMoratorium(moratoriumtopost)
    .pipe(takeUntil(this.ngUnsubscribe))
    .subscribe((data) => (this.moratoriumID) = (data),
    (error) => (console.log(error)),
    () => console.log('Post moratorium is complete', this.moratoriumID),
  );}

    //...I call it
      this.PostMoratorium(moratoriumtopost);

    //Later I try to use moratoriumID but it says its undefined ...why ?
       if (this.selectzipvalues.length>0){
         const res = this.isoLocs.filter(i => this.selectzipvalues.includes(i.zipCode));
         res.forEach(myFunction);
         function myFunction(item) {
            const moratoriumlocationstopost = {
              county:item.county ,
              city:item.city,
              zip:item.zipCode,
              moratoriumId:this.moratoriumID, //IT SAYS ITS UNDEFINED ..WHY ?
    } as MoratoriumLocation;

}}


问:
regex to not allow continuous characters without space
Hi i am trying to not allow continuous characters without space assuming max length of word can be 25 chars.

Allowed -> hi there how are you i'm fine over here "dfsdfsd'"()sdfnjsd. fhhdfbsdfbdhhbdhfb.

Not Allowed-> hi there howareyou, "()#jsdfhsdjfhjshdasdjasjdd34!fsdfsdfsddfsdfsdff*&

What i have tried

This will allow only alphanumeric and certain special characters

```<code>^[a-zA-Z0-9 ,()!'".\-_:/\\-]*$
</code>```

but not sure how to find continuous Words length greater than 25 chars without space

答:
You may check if a string contains 26 consecutive non-whitespace chars (with the \S{26} regex) and if it does, return false, else, return true.

```<code>val s = """hi there how are you i'm fine over here "dfsdfsd'"()sdfnjsd. fhhdfbsdfbdhhbdhfb."""
println(!"""\S{26}""".toRegex().containsMatchIn(s)) // => true

val s2 = """hi there howareyou, "()#jsdfhsdjfhjshdasdjasjdd34!fsdfsdfsddfsdfsdff*&"""
println(!"""\S{26}""".toRegex().containsMatchIn(s2)) // => false
</code>```

The .containsMatchIn method searches for the pattern match anywhere in the whole input string.

You may further precise the pattern.

Body:
Hi i am trying to not allow continuous characters without space assuming max length of word can be 25 chars.

Allowed -> hi there how are you i'm fine over here "dfsdfsd'"()sdfnjsd. fhhdfbsdfbdhhbdhfb.

Not Allowed-> hi there howareyou, "()#jsdfhsdjfhjshdasdjasjdd34!fsdfsdfsddfsdfsdff*&

What i have tried

This will allow only alphanumeric and certain special characters

^[a-zA-Z0-9 ,()!'".\-_:/\\-]*$

but not sure how to find continuous Words length greater than 25 chars without space

Body:
You may check if a string contains 26 consecutive non-whitespace chars (with the \S{26} regex) and if it does, return false, else, return true.

val s = """hi there how are you i'm fine over here "dfsdfsd'"()sdfnjsd. fhhdfbsdfbdhhbdhfb."""
println(!"""\S{26}""".toRegex().containsMatchIn(s)) // => true

val s2 = """hi there howareyou, "()#jsdfhsdjfhjshdasdjasjdd34!fsdfsdfsddfsdfsdff*&"""
println(!"""\S{26}""".toRegex().containsMatchIn(s2)) // => false

The .containsMatchIn method searches for the pattern match anywhere in the whole input string.

You may further precise the pattern.


问:
Identify duplicate rows with pandas and convert such rows into one row, creating a new columns as a result
I have a dataset of stations

```<code>    map_id  longitude   latitude  zip_code
0   40830 -87.669147  41.857908     60608
1   40830 -87.669147  41.857908     60608
2   40120 -87.680622  41.829353     60609
3   40120 -87.680622  41.829353     60609
4   41120 -87.625826  41.831677     60616
</code>```

As you can see, the first four rows are duplications and it is not an accident. They are the same stations, which are treated as separate stations of different lines.

I would like to eliminate such duplicates (it can be 2 or even 5 rows for some stations) and treat it as one station.

Moreover, I would like to create a new column "Hub", where aggregated rows will be treated a hub station. For example, as a boolean (0 for a regular station, 1 for a hub).

The desired output for the sample above with two cases of duplication -> transformed into 3 rows with 2 hubs.

```<code>    map_id  longitude   latitude  zip_code    hub
0   40830 -87.669147  41.857908     60608      1
1   40120 -87.680622  41.829353     60609      1
1   41120 -87.625826  41.831677     60616      0
</code>```

I appreciate any tips!

答:
Looks to me like you want to drop duplicates and assign certain zipcodes as hub. If so, I would drop duplicates and use np.where to assign hubs. I included a non existent opcode to demonstrate how you can do this if more than one zipcode is designated as a hub

```<code>import numpy as np

df2=df.drop_duplicates(subset=['map_id','longitude','latitude','zip_code'], keep='first')
conditions=df2['zip_code'].isin(['60616','60619'])
df2['hub']=np.where(conditions,0,1)
</code>```

Body:
I have a dataset of stations

    map_id  longitude   latitude  zip_code
0   40830 -87.669147  41.857908     60608
1   40830 -87.669147  41.857908     60608
2   40120 -87.680622  41.829353     60609
3   40120 -87.680622  41.829353     60609
4   41120 -87.625826  41.831677     60616

As you can see, the first four rows are duplications and it is not an accident. They are the same stations, which are treated as separate stations of different lines.

I would like to eliminate such duplicates (it can be 2 or even 5 rows for some stations) and treat it as one station.

Moreover, I would like to create a new column "Hub", where aggregated rows will be treated a hub station. For example, as a boolean (0 for a regular station, 1 for a hub).

The desired output for the sample above with two cases of duplication -> transformed into 3 rows with 2 hubs.

    map_id  longitude   latitude  zip_code    hub
0   40830 -87.669147  41.857908     60608      1
1   40120 -87.680622  41.829353     60609      1
1   41120 -87.625826  41.831677     60616      0

I appreciate any tips!

Body:
Looks to me like you want to drop duplicates and assign certain zipcodes as hub. If so, I would drop duplicates and use np.where to assign hubs. I included a non existent opcode to demonstrate how you can do this if more than one zipcode is designated as a hub

import numpy as np

df2=df.drop_duplicates(subset=['map_id','longitude','latitude','zip_code'], keep='first')
conditions=df2['zip_code'].isin(['60616','60619'])
df2['hub']=np.where(conditions,0,1)


问:
How to clear console in Windows
I want to clear the console

I tried using this, but it doesn't work for Windows

```<code>print!("\x1B[2J");
</code>```

Is there an easy way to clear the console?

答:
I think I need some clarification first, on what you're attempting to do. Regardless, this is my best attempt at answering your question <3

Preamble

Given that different terminals work differently and have different APIs, I think you probably will want to use a crate that provides this functionality in a cross-plaform manner.

I'm assuming from here on that you want cross-platform functionality and that you don't mind using external dependencies. If this is correct, you might be happy to know that the terminal interaction crates are actually really developed in the Rust ecosystem. I have heard only good things about them.

With that out of the way, let's move on.

Do you want to just perform actions on the terminal?

If you just want to perform some actions on the terminal, like "clearing", "scrolling", "moving the cursor" and whatnot, I think you will be satisfied with the terminal crate. It allows to perform many actions, like clearing, independently of the platform you're in. It also allows for using interactivity features like interacting with the Mouse and the Keyboard :3

Or do you want to write a GUI for the terminal?

If what you want to do is write a Console-based User Interface though, I think that what might work for you instead is the tui crate. It has all of what you need to build terminal GUIs, from clearing of the console up to graphical widgets. Tools like gitui are written with tui.

Did I answer your question? Feel free to follow up if I fell short :)

Title: How to clear console in Windows

Body:
I want to clear the console

I tried using this, but it doesn't work for Windows

print!("\x1B[2J");

Is there an easy way to clear the console?


问:
C Programming-Enter 3 Characters and print in reverse order
I'm having some trouble with this program. I think I have it almost right, besides the fact that it prints garbage to the screen :(</p>

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

#define strsize 30

typedef struct member
{
    int number;
    char fname[strsize];
    struct member *next;
} RECORD;

RECORD* insert (RECORD *it);
RECORD* print(RECORD *it, int j);

int main (void)
{
    int i, result;
    RECORD *head, *p;
    head=NULL;
    printf("Enter the number of characters: ");
    scanf("%d", &result);

    for (i=1; i<=result; i++)
        head=insert (head);

    print (head, result);

    return 0;
}

RECORD* insert (RECORD *it)
{
    RECORD *cur, *q;
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%c", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));

    strcpy(cur->fname, first);
    cur->next=NULL;

    if (it==NULL)
        it=cur;
    else
    {
        q=it;

        while (q->next!=NULL)
            q=q->next;

        q->next=cur;
    }

    return (it);
}

RECORD* print(RECORD *it, int j)
{
    RECORD *cur;
    cur=it;
    int i;

    for(i=1;i<=j;i++)
    {
        printf("%c \n", cur->fname);
        cur=cur->next;
    }

    return;
}
</code>```

答:
In your RECORD* print(RECORD *it, int j) function,  you tell printf that you want to print a character but you are passing a pointer to the first element in your fname array, which is a memory address.

Use either:

```<code>printf("%s \n", cur->fname); /* print the string */
</code>```

or

```<code>printf("%c \n", *cur->fname); /* print the first character */
</code>```

I'm not sure what you want since your question is extremely vague.

Body:
I'm having some trouble with this program. I think I have it almost right, besides the fact that it prints garbage to the screen :(

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

#define strsize 30

typedef struct member
{
    int number;
    char fname[strsize];
    struct member *next;
} RECORD;

RECORD* insert (RECORD *it);
RECORD* print(RECORD *it, int j);

int main (void)
{
    int i, result;
    RECORD *head, *p;
    head=NULL;
    printf("Enter the number of characters: ");
    scanf("%d", &result);

    for (i=1; i<=result; i++)
        head=insert (head);

    print (head, result);

    return 0;
}

RECORD* insert (RECORD *it)
{
    RECORD *cur, *q;
    int num;
    char junk;
    char first[strsize];
    printf("Enter a character:");
    scanf("%c", &first);

    cur=(RECORD *) malloc(sizeof(RECORD));

    strcpy(cur->fname, first);
    cur->next=NULL;

    if (it==NULL)
        it=cur;
    else
    {
        q=it;

        while (q->next!=NULL)
            q=q->next;

        q->next=cur;
    }

    return (it);
}

RECORD* print(RECORD *it, int j)
{
    RECORD *cur;
    cur=it;
    int i;

    for(i=1;i<=j;i++)
    {
        printf("%c \n", cur->fname);
        cur=cur->next;
    }

    return;
}

Body:
In your RECORD* print(RECORD *it, int j) function,  you tell printf that you want to print a character but you are passing a pointer to the first element in your fname array, which is a memory address.

Use either:

printf("%s \n", cur->fname); /* print the string */

or

printf("%c \n", *cur->fname); /* print the first character */

I'm not sure what you want since your question is extremely vague.


问:
I don't understand association class - UML class diagram

I  don't yet completely seem to understand how association class works, why the role class attributes can't just be inside the person class?

as example:

Person

name

position

description

答:
why the role class attributes can't just be inside the person class?

notice the multiplicity 1..*, if you move position and description into Person you have to manage a collection of them and to associate each to the corresponding Company.

[from your remark]

For a given Person the position and description depends on each associated Compagny, so it is not possible to have the fields you propose except if position and description are both a collection, and to have a way/rule to know which entry in position and description correspond to the right Compagny.

Moving also these information in Person you remove the symmetry, it is also possible to move these information in Compagny, with the same remarks as for Person

An association class is both a class and a relation, when you implement it in a language like C++ or Java etc of course that concept does not exist, so one way is as you propose to move the fields in one of the two classes, or to create a third class having the expected fields more one to a Person and one to Company.

The advantage of the third class is to have all the associated information grouped having the equivalent of :

As example an object diagram can be :

Without the third class you need to know how to associate all the separated information, for instance having all in Person using three vectors to memorize the company and position and description you may use the same index value for all, but this is less clear and when you add/remove a Company for a Person you have to update all these vectors.


问:
Google Cloud Run service url (discovery)
I am running several gcloud services which have assigned urls automatically in following format:

https://SERVICE_NAME-XXXXXXX-ew.a.run.app/

This is not particularly easy to work with and to pass these URLs to clients. Alternative is to use the custom domain, but this needs hardcoding subdomains within DNS records (as far as I understand) and I would like to avoid that and use the default URLs.

What is the best practice to work with these URLs? I can imagine keeping some mapping of service->URL and passing it to clients, but I would like to avoid reinventing the wheels.

答:
You can use a beta service Service Directory.

At service deployment

Create your service with a name and the URL as metadata

In your code

Request the service metadata with its name, and get the URL

Use the url

You can't use the endpoint feature of the service because your don't have IP/Port.

However, for now, there is client library and you have to use API directly.


问:
Using for loop to find the biggest number in an array
I'm a begginer in c# and I'm trying to solve problems and exercises, what I have to do is write a method that compares the jump height of a jumper to the height of the hurdles, if the jump height is equal to or greater than the biggest hurdle, the method should return true. The heights of the hurdles are imputed in the form of an array, and the jump height is an integer.
The code I wrote was:

```<code>public static bool hurdleJump(int[] hurdles, int jumpHeight)
{
    int height= 0;
    for(int i = 0; i == hurdles.Length; i++)
    {
        if(hurdles[i] > height)
            height = hurdles[i];
    }

    if(jumpHeight >= height)
    {
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

I used a for loop to find the biggest value inside of the array and then compared that to the int, but this code doesn't work with some arrays and I have no idea why, what am I missing?

答:
This should do it, much simple than using a loop:</p>

```<code>public static bool hurdleJump(int[] hurdles, int jumpHeight)
{
    return jumpHeight >= hurdles.Max();
}
</code>```

Body:
I'm a begginer in c# and I'm trying to solve problems and exercises, what I have to do is write a method that compares the jump height of a jumper to the height of the hurdles, if the jump height is equal to or greater than the biggest hurdle, the method should return true. The heights of the hurdles are imputed in the form of an array, and the jump height is an integer.
The code I wrote was:

public static bool hurdleJump(int[] hurdles, int jumpHeight)
{
    int height= 0;
    for(int i = 0; i == hurdles.Length; i++)
    {
        if(hurdles[i] > height)
            height = hurdles[i];
    }

    if(jumpHeight >= height)
    {
        return true;
    }
    else
    {
        return false;
    }
}

I used a for loop to find the biggest value inside of the array and then compared that to the int, but this code doesn't work with some arrays and I have no idea why, what am I missing?

Body:
This should do it, much simple than using a loop:

public static bool hurdleJump(int[] hurdles, int jumpHeight)
{
    return jumpHeight >= hurdles.Max();
}


问:
AVPlayer: how to "play" image instead of video?
I'm working on a health/fitness app with video trainings and in some cases i wanna show static images instead of videos for some "static" exercises. I wonder if there is any way to "play" image instead of video by AVPlayer?

Or, probably, some simple way to convert an image into a video "on the fly"

That would save me lots of time/coding efforts as everything is already made for AVplayer, not for displaying uiImage.

Thanks in advance.

答:
If the image is separate from the video data, no you cannot. Instead, you could just add a UIImageView with the same frame as the AVPlayer and show/hide whichever one you need at that time. If the image is a frame from the video, you can try playing around with .step function on AVPlayer, something like:

```<code>videoPlayer.currentItem?.step(byCount: 1)
</code>```

If you use an UIImageView and need several photos to loop, you can use the built in

```<code>imageView.animationImages = [arrayOfImages]
imageView.animationDuration = TimeInterval(Double(0.5) * Double([arrayOfImages.count])) //seconds * # images
imageView.startAnimating()
</code>```

Body:
If the image is separate from the video data, no you cannot. Instead, you could just add a UIImageView with the same frame as the AVPlayer and show/hide whichever one you need at that time. If the image is a frame from the video, you can try playing around with .step function on AVPlayer, something like:

videoPlayer.currentItem?.step(byCount: 1)

If you use an UIImageView and need several photos to loop, you can use the built in

imageView.animationImages = [arrayOfImages]
imageView.animationDuration = TimeInterval(Double(0.5) * Double([arrayOfImages.count])) //seconds * # images
imageView.startAnimating()


问:
How to Zip Files using PowerShell (without PS Version 5 or .NET Framework 4.5)
I'm looking for a way to create a new ZIP Archive or add files to an existing archive using Powershell. This script is going to be ran on very old systems some of which are still using Powershell Version 2 and .NET Framework 3.0 or earlier. There isn't any possibility of upgrading because they are client production systems that aren't connected to the internet and I don't have the ability to install any add-ons or extensions.

Due to how old these systems are I can't use Compress-Archive or System.IO.Compression.FileSystem. I have the whole script complete apart from the actual zipping function. All the other solutions online have told me to either use the .NET 4.5 way or the powershell V5 way and that isn't possible on the systems that I'm working on. Any ideas?

Here is a link to my code: https://pastebin.com/m8FjFhcr
Line #113 is where the zip commands would go.

答:
You can use Shell.Application.

# Create an empty zip file
$byte = @([byte]80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
[System.IO.File]::WriteAllBytes(".\Desktop\zip.zip", $byte)

# New Shell.Application ComObject
$sa = New-Object -ComObject Shell.Application

# Path to folder containing items you wish to zip
$in = $sa.NameSpace("C:\Users\Ash\Desktop\test") # Specify full path

# Path to zip file created earlier
$out = $sa.NameSpace("C:\Users\Ash\Desktop\zip.zip") # Specify full path

# Copy files in to archive.
$out.CopyHere($in.Items(), 4) # 4 = No Progress Box
```

<p>Folder.CopyHere</p>

<p>Everyone likes a reusable function and being able to use relative paths...</p>

<pre class="lang-bsh prettyprint-override"><code>function ConvertTo-Archive {
    Param(
        [parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [Alias("FullName")]
        [ValidateScript({Test-Path $_})]
        [string]$Path,

        [parameter(Mandatory=$true)]
        [string]$Output
    )
    # Convert relative path if one has been used.
    $Source = [System.IO.Path]::GetFullPath($Path)
    $Destination = [System.IO.Path]::GetFullPath($Output)

    $byte = @([byte]80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
    [System.IO.File]::WriteAllBytes($Destination, $byte)
    $sa = New-Object -ComObject Shell.Application
    $in = $sa.NameSpace($Source)
    $out = $sa.NameSpace($Destination)
    $out.CopyHere($in.Items(), 4)
}
</code>```

Usage

ConvertTo-Archive -Path .\Desktop\test\ -Output .\Desktop\zip.zip
```

<p>Or</p>

<pre class="lang-bsh prettyprint-override"><code>Get-Item .\Desktop\test\ | ConvertTo-Archive -Output .\Desktop\zip.zip
</code>```

Body:
You can use Shell.Application.

# Create an empty zip file
$byte = @([byte]80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
[System.IO.File]::WriteAllBytes(".\Desktop\zip.zip", $byte)

# New Shell.Application ComObject
$sa = New-Object -ComObject Shell.Application

# Path to folder containing items you wish to zip
$in = $sa.NameSpace("C:\Users\Ash\Desktop\test") # Specify full path

# Path to zip file created earlier
$out = $sa.NameSpace("C:\Users\Ash\Desktop\zip.zip") # Specify full path

# Copy files in to archive.
$out.CopyHere($in.Items(), 4) # 4 = No Progress Box

Folder.CopyHere

Everyone likes a reusable function and being able to use relative paths...

function ConvertTo-Archive {
    Param(
        [parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [Alias("FullName")]
        [ValidateScript({Test-Path $_})]
        [string]$Path,

        [parameter(Mandatory=$true)]
        [string]$Output
    )
    # Convert relative path if one has been used.
    $Source = [System.IO.Path]::GetFullPath($Path)
    $Destination = [System.IO.Path]::GetFullPath($Output)

    $byte = @([byte]80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
    [System.IO.File]::WriteAllBytes($Destination, $byte)
    $sa = New-Object -ComObject Shell.Application
    $in = $sa.NameSpace($Source)
    $out = $sa.NameSpace($Destination)
    $out.CopyHere($in.Items(), 4)
}

Usage

ConvertTo-Archive -Path .\Desktop\test\ -Output .\Desktop\zip.zip

Or

Get-Item .\Desktop\test\ | ConvertTo-Archive -Output .\Desktop\zip.zip


问:
My mouse listeners don't seem to be working. Can someone help me? I have to move a ball to where my mouse is clicked and it is not working
This is the code but it is not working. I thought i added the right thing but the mouse listener is even responding. Much help is needed.

```<code>class Mouse implements MouseListener {
    /**
    * Moves the ball to the (x, y) location where the mouse has been clicked
    */
    public void mousePressed(MouseEvent e) {
        ball.setX(e.getX());
        ball.setY(e.getY());

        if (e.isMetaDown()) {
            ball.move(getX(), getY());
            repaint();
        }
        if (e.isShiftDown()) {
            ball.setRandomSpeed(20);
            ball.setLocation(Math.random(), Math.random());
            repaint();
        }
    }
}
</code>```

It is not working as you can see. I don't know what is wrong.

答:
You are working with the java.awt.event.MouseEvent, right?

The problem is, that you invoke methods on the MouseEvent e that do not work like expected in your case. The Methods e.isMetaDown() and e.isShiftDown() check weather the Meta modfier or the Shift modifier is down on this event. I think you searches for a method to check if you pressed the left ( MouseEvent.BUTTON1) or right mouse button (MouseEvent.BUTTON3). You can consult this page:

https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/event/MouseEvent.html

to inform yoursef about the Methods that can be invoked on MouseEvents.

You could try these two small changes. (But this code is not tested!!) If you want  somebody to test the code, then please post a minimal reproducible example as @DontKnowMuchBut Getting Better already mentioned.

```<code>class Mouse implements MouseListener {
    /**
    * Moves the ball to the (x, y) location where the mouse has been clicked
    */
    public void mousePressed(MouseEvent e) {
        ball.setX(e.getX());
        ball.setY(e.getY());

        if (e.getButton().equals(MouseEvent.BUTTON1)) {
            ball.move(getX(), getY());
            repaint();
        }
        if (e.getButton().equals(MouseEvent.BUTTON2)) {
            ball.setRandomSpeed(20);
            ball.setLocation(Math.random(), Math.random());
            repaint();
        }
    }
}
</code>```

I hope this is helpfull.

Body:
This is the code but it is not working. I thought i added the right thing but the mouse listener is even responding. Much help is needed.

class Mouse implements MouseListener {
    /**
    * Moves the ball to the (x, y) location where the mouse has been clicked
    */
    public void mousePressed(MouseEvent e) {
        ball.setX(e.getX());
        ball.setY(e.getY());

        if (e.isMetaDown()) {
            ball.move(getX(), getY());
            repaint();
        }
        if (e.isShiftDown()) {
            ball.setRandomSpeed(20);
            ball.setLocation(Math.random(), Math.random());
            repaint();
        }
    }
}

It is not working as you can see. I don't know what is wrong.

Body:
You are working with the java.awt.event.MouseEvent, right?

The problem is, that you invoke methods on the MouseEvent e that do not work like expected in your case. The Methods e.isMetaDown() and e.isShiftDown() check weather the Meta modfier or the Shift modifier is down on this event. I think you searches for a method to check if you pressed the left ( MouseEvent.BUTTON1) or right mouse button (MouseEvent.BUTTON3). You can consult this page:

https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/event/MouseEvent.html

to inform yoursef about the Methods that can be invoked on MouseEvents.

You could try these two small changes. (But this code is not tested!!) If you want  somebody to test the code, then please post a minimal reproducible example as @DontKnowMuchBut Getting Better already mentioned.

class Mouse implements MouseListener {
    /**
    * Moves the ball to the (x, y) location where the mouse has been clicked
    */
    public void mousePressed(MouseEvent e) {
        ball.setX(e.getX());
        ball.setY(e.getY());

        if (e.getButton().equals(MouseEvent.BUTTON1)) {
            ball.move(getX(), getY());
            repaint();
        }
        if (e.getButton().equals(MouseEvent.BUTTON2)) {
            ball.setRandomSpeed(20);
            ball.setLocation(Math.random(), Math.random());
            repaint();
        }
    }
}

I hope this is helpfull.


问:
Connecting to MSSQL in Flask using Flask-SQLAlchemy and pyodbc
I am not able to connect to MSSQL Server 2016 database using Flask-SQLALchemy and pyodbc. I have searched through Google and none of the solutions work.

I am getting the following error:

sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002',
  u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found
  and no default driver specified (0) (SQLDriverConnect)')

My current local environment is:

Windows 7 Professional

Python 2.7

I am able to connect to the database with just pyodbc and no Flask.

```<code>import pyodbc
server = '<server>'
database = '<database>'
username = '<username>'
password = '<password>'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

#Select Query
print ('Reading data from table')
tsql = "SELECT DISTINCT TOP 10 * FROM dbo.Test;"
with cursor.execute(tsql):
    row = cursor.fetchone()
    while row:
        print (str(row[0]) + " " + str(row[1]))
        row = cursor.fetchone()
</code>```

Application Code Snippets

config.py

```<code>SQLALCHEMY_DATABASE_URI = mssql+pyodbc:///?odbc_connect="DRIVER={ODBC Driver 13 for SQL Server};SERVER=<server>;DATABASE=<database>;UID=<username>;PWD=<password>
SQLALCHEMY_TRACK_MODIFICATIONS = False
</code>```

__init__.py

```<code>import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

db = SQLAlchemy()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)

    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app

from app import models
</code>```

答:
This should work as your SQLALCHEMY_DATABASE_URI connection value:

```<code>mssql://user:pwd!@PATH_TO_MSSQL_LOCATION?driver=SQL+Server+Native+Client+11.0
</code>```

You might need to experiment with different version numbers up and down, although the version of the native driver is probably ascertainable.

Body:
I am not able to connect to MSSQL Server 2016 database using Flask-SQLALchemy and pyodbc. I have searched through Google and none of the solutions work.

I am getting the following error:

sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002',
  u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found
  and no default driver specified (0) (SQLDriverConnect)')

My current local environment is:

Windows 7 Professional

Python 2.7

I am able to connect to the database with just pyodbc and no Flask.

import pyodbc
server = '<server>'
database = '<database>'
username = '<username>'
password = '<password>'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()

#Select Query
print ('Reading data from table')
tsql = "SELECT DISTINCT TOP 10 * FROM dbo.Test;"
with cursor.execute(tsql):
    row = cursor.fetchone()
    while row:
        print (str(row[0]) + " " + str(row[1]))
        row = cursor.fetchone()

Application Code Snippets

config.py

SQLALCHEMY_DATABASE_URI = mssql+pyodbc:///?odbc_connect="DRIVER={ODBC Driver 13 for SQL Server};SERVER=<server>;DATABASE=<database>;UID=<username>;PWD=<password>
SQLALCHEMY_TRACK_MODIFICATIONS = False

__init__.py

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

db = SQLAlchemy()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)

    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    return app

from app import models

Body:
This should work as your SQLALCHEMY_DATABASE_URI connection value:

mssql://user:pwd!@PATH_TO_MSSQL_LOCATION?driver=SQL+Server+Native+Client+11.0

You might need to experiment with different version numbers up and down, although the version of the native driver is probably ascertainable.


问:
Three JS Keep Label Size On Zoom
I'm working on a solar system in three.js and am curious if there is an easy way to make the labels for the planets I have below all show up the same size regardless of how far they are from the camera? I can't seem to find a solution to this. I figure you could calculate the distance from each label to the camera then come up with some sort of scaling factor based on that. Seems like there would be an easier way to accomplish this?

Thanks!

Updated with answer from prisoner849. Works excellent!

答:
If you are using spriteMaterial to present your text, you could try to set the sizeAttenuation attribute to false.

```<code>var spriteMaterial = new THREE.SpriteMaterial( { map: spriteMap, color: 0xffffff, sizeAttenuation:false } );
</code>```

See more information from here:
https://threejs.org/docs/index.html#api/en/materials/SpriteMaterial.sizeAttenuation

Title: Three JS Keep Label Size On Zoom

Body:
If you are using spriteMaterial to present your text, you could try to set the sizeAttenuation attribute to false.

var spriteMaterial = new THREE.SpriteMaterial( { map: spriteMap, color: 0xffffff, sizeAttenuation:false } );

See more information from here:
https://threejs.org/docs/index.html#api/en/materials/SpriteMaterial.sizeAttenuation