问:
else command not running correctly? (Python 3 Beginner)
I'm working on a combo menu for my first Python program. I've gotten everything to work properly up to this point. I want the program to exit if the user's input isn't equal to the accepted answers. I've tried a few different methods to get this working, but it still just runs like I answered "Yes" or "yes". Any help? Thanks a ton. </p>

<p>Here is my code: </p>

```<code>def p(): #Prints new line quiokly
    print()

def error(): #Restarts the main
    question = input("You have entered an invalid option. Would you like to try your order again? \n")
    if question in ("Yes","yes","yes"):
        main()
    else:
        exit

def main(): #Main block of code
    cost = 0 #total cost variable
    if cost == 0:
        print("What type of sandwhich would you like? Refer to the cost and type of sandwhich below.")
        p()
        print("Chicken Sandwhich = $5.25")
        p()
        print("Tofu Sandwhich = $5.75")
        p()
        print("Beef Sandwhich = $6.25") #initial questions
        x = input()
        if x == ("Beef") or x == ("beef"):
            cost += 6.25
            print("You have selected Beef. Your total is so far is $6.25.")
        elif x == ("Chicken") or x == ("chicken"):
            cost += 5.25
            print("You have selected Chicken. Your total is so far is $5.25.")
        elif x == ("Tofu") or x == ("tofu"):
            cost += 5.75
            print("You have selected Tofu. Your total is so far is $5.75.")
        if x not in ("beef" , "Beef" , "Tofu" , "tofu" , "chicken" , "Chicken"): #checks for valid resposne
            error()

        print("Would you like to add a drink to your meal?")
        p()
        yzz = input()
        if yzz == ("Yes") or ("yes"):
            p()
            print("Okay, would you like small, medium, or large? Refer to the prices below.")
            print(cost)
            p()
            print("Small - $1.00")
            p()
            print("Medium - $1.75")
            p()
            print("Large - $2.25")
            p()
            yzzz = input()
            if yzzz == ("Small") or yzzz == ("small"):
                cost += 1
                print("You have selected a small drink. Your total is so far is " + "$%.2f" %cost + ".")
            elif yzzz == ("Medium") or yzzz == ("medium"):
                cost += 1.75
                print("You have selected a medium drink. Your total is so far is " + "$%.2f" %cost + ".")
            elif yzzz == ("Large") or yzzz == ("large"):
                cost += 2.25
                print("You have selected a large drink. Your total is so far is " + "$%.2f" %cost + ".")
            if yzzz not in ("small" , "Small" , "Medium" , "medium" , "large" , "Large"): #checks for valid response
                error()
    elif yzz not in ("yes","Yes"):
        exit

#Main code starts here!
main()
</code>```

答:
The indent for the line elif yzz not in ("yes","Yes"): is wrong, you need to indent it one more time.

Also the expression if yzz == ('Yes') or ('yes') will always evaluate to True because the or expects a boolean to either side and ('yes') evaluates to True.

instead write if yzz in ['Yes', 'yes']

Body:
I'm working on a combo menu for my first Python program. I've gotten everything to work properly up to this point. I want the program to exit if the user's input isn't equal to the accepted answers. I've tried a few different methods to get this working, but it still just runs like I answered "Yes" or "yes". Any help? Thanks a ton.

Here is my code:

def p(): #Prints new line quiokly
    print()

def error(): #Restarts the main
    question = input("You have entered an invalid option. Would you like to try your order again? \n")
    if question in ("Yes","yes","yes"):
        main()
    else:
        exit

def main(): #Main block of code
    cost = 0 #total cost variable
    if cost == 0:
        print("What type of sandwhich would you like? Refer to the cost and type of sandwhich below.")
        p()
        print("Chicken Sandwhich = $5.25")
        p()
        print("Tofu Sandwhich = $5.75")
        p()
        print("Beef Sandwhich = $6.25") #initial questions
        x = input()
        if x == ("Beef") or x == ("beef"):
            cost += 6.25
            print("You have selected Beef. Your total is so far is $6.25.")
        elif x == ("Chicken") or x == ("chicken"):
            cost += 5.25
            print("You have selected Chicken. Your total is so far is $5.25.")
        elif x == ("Tofu") or x == ("tofu"):
            cost += 5.75
            print("You have selected Tofu. Your total is so far is $5.75.")
        if x not in ("beef" , "Beef" , "Tofu" , "tofu" , "chicken" , "Chicken"): #checks for valid resposne
            error()

        print("Would you like to add a drink to your meal?")
        p()
        yzz = input()
        if yzz == ("Yes") or ("yes"):
            p()
            print("Okay, would you like small, medium, or large? Refer to the prices below.")
            print(cost)
            p()
            print("Small - $1.00")
            p()
            print("Medium - $1.75")
            p()
            print("Large - $2.25")
            p()
            yzzz = input()
            if yzzz == ("Small") or yzzz == ("small"):
                cost += 1
                print("You have selected a small drink. Your total is so far is " + "$%.2f" %cost + ".")
            elif yzzz == ("Medium") or yzzz == ("medium"):
                cost += 1.75
                print("You have selected a medium drink. Your total is so far is " + "$%.2f" %cost + ".")
            elif yzzz == ("Large") or yzzz == ("large"):
                cost += 2.25
                print("You have selected a large drink. Your total is so far is " + "$%.2f" %cost + ".")
            if yzzz not in ("small" , "Small" , "Medium" , "medium" , "large" , "Large"): #checks for valid response
                error()
    elif yzz not in ("yes","Yes"):
        exit

#Main code starts here!
main()


来源: stackexchange

问:
Avoiding redundant rows in result of mysql inner join
I have 2 tables

```<code>CREATE TABLE `CORPUS_FILE_SENTENCE` (
  `corpus_file_sentence_id` int(11) NOT NULL AUTO_INCREMENT,
  `corpus_file_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `date_sentence_saved` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `sentence_number` int(11) NOT NULL,
  `corpus_file_id` int(11) NOT NULL,
  `comment` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`corpus_file_sentence_id`),
  KEY `fk_corpus_file_sentence-corpus_file_id` (`corpus_file_id`),
  CONSTRAINT `fk_corpus_file_sentence-corpus_file_id` FOREIGN KEY (`corpus_file_id`) REFERENCES `CORPUS_FILE` (`corpus_file_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
</code>```

and

```<code>CREATE TABLE `CORPUS_FILE_PREPROCESSED_SENTENCE` (
  `corpus_file_preprocessed_sentence_id` int(11) NOT NULL AUTO_INCREMENT,
  `coreference_resolved_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `stopword_removed_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lemmatized_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lowercased_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `preprocessed_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `date_preprocessed_sentence_saved` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `corpus_file_sentence_id` int(11) NOT NULL,
  `comment` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`corpus_file_preprocessed_sentence_id`),
  KEY `fk_corpus_file_preprocessed_sentence-corpus_file_sentence_id` (`corpus_file_sentence_id`),
  CONSTRAINT `fk_corpus_file_preprocessed_sentence-corpus_file_sentence_id` FOREIGN KEY (`corpus_file_sentence_id`) REFERENCES `CORPUS_FILE_SENTENCE` (`corpus_file_sentence_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
</code>```

I need to show the result of Coreference Resolution along with the original sentence and I was trying

```<code>select
  CFS.corpus_file_sentence_id,
  CFS.sentence_number,
  CFS.corpus_file_sentence_text,
  CFPS.coreference_resolved_sentence_text
from CORPUS_FILE_SENTENCE CFS
inner join CORPUS_FILE_PREPROCESSED_SENTENCE CFPS
  on  CFS.corpus_file_sentence_id = CFPS.corpus_file_sentence_id
  and CFS.corpus_file_id = 3;
</code>```

This is resulting in duplicate rows of the form

How do I remove the redundant rows?

答:
It is really strange that you get these results, but for these results you can remove the rows with nulls in the column coreference_resolved_sentence_text with group by and aggregation:

```<code>select
  CFS.corpus_file_sentence_id, CFS.sentence_number,
  CFS.corpus_file_sentence_text, max(CFPS.coreference_resolved_sentence_text)
from CORPUS_FILE_SENTENCE CFS inner join CORPUS_FILE_PREPROCESSED_SENTENCE CFPS
on CFS.corpus_file_sentence_id = CFPS.corpus_file_sentence_id and CFS.corpus_file_id = 3
group by
  CFS.corpus_file_sentence_id,
  CFS.sentence_number,
  CFS.corpus_file_sentence_text
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have 2 tables

CREATE TABLE `CORPUS_FILE_SENTENCE` (
  `corpus_file_sentence_id` int(11) NOT NULL AUTO_INCREMENT,
  `corpus_file_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `date_sentence_saved` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `sentence_number` int(11) NOT NULL,
  `corpus_file_id` int(11) NOT NULL,
  `comment` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`corpus_file_sentence_id`),
  KEY `fk_corpus_file_sentence-corpus_file_id` (`corpus_file_id`),
  CONSTRAINT `fk_corpus_file_sentence-corpus_file_id` FOREIGN KEY (`corpus_file_id`) REFERENCES `CORPUS_FILE` (`corpus_file_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

and

CREATE TABLE `CORPUS_FILE_PREPROCESSED_SENTENCE` (
  `corpus_file_preprocessed_sentence_id` int(11) NOT NULL AUTO_INCREMENT,
  `coreference_resolved_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `stopword_removed_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lemmatized_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lowercased_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `preprocessed_sentence_text` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `date_preprocessed_sentence_saved` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `corpus_file_sentence_id` int(11) NOT NULL,
  `comment` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`corpus_file_preprocessed_sentence_id`),
  KEY `fk_corpus_file_preprocessed_sentence-corpus_file_sentence_id` (`corpus_file_sentence_id`),
  CONSTRAINT `fk_corpus_file_preprocessed_sentence-corpus_file_sentence_id` FOREIGN KEY (`corpus_file_sentence_id`) REFERENCES `CORPUS_FILE_SENTENCE` (`corpus_file_sentence_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

I need to show the result of Coreference Resolution along with the original sentence and I was trying

select
  CFS.corpus_file_sentence_id,
  CFS.sentence_number,
  CFS.corpus_file_sentence_text,
  CFPS.coreference_resolved_sentence_text
from CORPUS_FILE_SENTENCE CFS
inner join CORPUS_FILE_PREPROCESSED_SENTENCE CFPS
  on  CFS.corpus_file_sentence_id = CFPS.corpus_file_sentence_id
  and CFS.corpus_file_id = 3;

This is resulting in duplicate rows of the form

How do I remove the redundant rows?

Body:
It is really strange that you get these results, but for these results you can remove the rows with nulls in the column coreference_resolved_sentence_text with group by and aggregation:

select
  CFS.corpus_file_sentence_id, CFS.sentence_number,
  CFS.corpus_file_sentence_text, max(CFPS.coreference_resolved_sentence_text)
from CORPUS_FILE_SENTENCE CFS inner join CORPUS_FILE_PREPROCESSED_SENTENCE CFPS
on CFS.corpus_file_sentence_id = CFPS.corpus_file_sentence_id and CFS.corpus_file_id = 3
group by
  CFS.corpus_file_sentence_id,
  CFS.sentence_number,
  CFS.corpus_file_sentence_text


问:
Duplicate dominating parents when using Deterministic Crowding in Genetic Algorithm
This is pseudocode for using deterministic crowding:

```<code>for i from 0 to N/2
     p1, p2 = select_two_random_individual()
     c1, c2 = crossover(p1, p2)

     c1 = mutate(c1)
     c2 = mutate(c2)

     if((d(p1, c1) + d(p2, c2)) < (d(p1, c2) + d(p2, c1))
          population.add(Winner between p1 and c1)
          population.add(Winner between p2 and c2)
     Else
          population.add(Winner between p1 and c2)
          population.add(Winner between p2 and c1)
</code>```

Which d is a function that determines the difference between two individual.

The question is, what happens if an individual gets selected two times as parent, and wins over its child both times? Do I end up with duplicate individual in new population?

答: Yes, it is not uncommon to have duplicate individuals in a population. It is in fact expected that at some point all solutions will converge to an optimal, this is where all solutions in a population are the same. This is only a problem when there is premature convergence.</p>

Body:
This is pseudocode for using deterministic crowding:

for i from 0 to N/2
     p1, p2 = select_two_random_individual()
     c1, c2 = crossover(p1, p2)

     c1 = mutate(c1)
     c2 = mutate(c2)

     if((d(p1, c1) + d(p2, c2)) < (d(p1, c2) + d(p2, c1))
          population.add(Winner between p1 and c1)
          population.add(Winner between p2 and c2)
     Else
          population.add(Winner between p1 and c2)
          population.add(Winner between p2 and c1)

Which d is a function that determines the difference between two individual.

The question is, what happens if an individual gets selected two times as parent, and wins over its child both times? Do I end up with duplicate individual in new population?


问:
Can you do this using jquery?
Is it possible to do this from within a class?

```<code>   $("#" + field).click(this.validate);
</code>```

So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed.

答:
Is it possible to do this from within a class?

$("#" + field).click(this.validate);

“this.validate” is problematic. JavaScript does not have bound methods, so when you pass that reference, it is only pointing to a plain function. When called, ‘this’ will not be correctly set. See ALA for a fairly thorough discussion of the binding loss problem.

Some frameworks provide built-in method-binding functionality; jQuery does not, as it tends to concentrate more on closures than JavaScript objects. In any case, creating a binding wrapper using a closure is pretty simple; Andrey's answer is the usual approach for jQuery users.

The one thing to look out for with closures for event handlers (whether you are using jQuery or not) is that it tends to cause memory leaks in IE. For simple, short-lived web pages you may not care.

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Title: Can you do this using jquery?

Body:
Is it possible to do this from within a class?

   $("#" + field).click(this.validate);

So basically I want to pass a function of the object that should be executed whenever something is clicked. Also, if there are more than 1 instances of this object, then the correct instance (i.e the one which runs this code for the given field) should be executed.

OwnerDisplayName: bobince


问:
Kotlin iterator to check if payload list have an id/projectId or not, returning false when there is no attributes?
I have an issue where i have a method where i am checking the payload has the attributes or not. When i am sending my payload i want to check that the user dont have inserted attributes which not allowed in the payload.

My entity class:

```<code>@Entity
data class ProjectAssociated(

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    var id: UUID? = null,

    @Column(columnDefinition = "BINARY(16)")
    var projectId: UUID? = null,

    @Column(columnDefinition = "BINARY(16)")
    var associatedProjectId: UUID? = null
)
</code>```

My Service class:

```<code>fun addAssociatedProjectByProjectId(
    projectId: UUID,
    projectAssociatedList: MutableList<ProjectAssociated>
): MutableList<ProjectAssociated> {

    if (projectAssociatedList.isNotEmpty()) {

        println(projectAssociatedList)

        if (!projectAssociatedList.map { it.id }.isNullOrEmpty()) {
            val errorMessage = "Not allowed to provide parameter 'id' in this request"
            throw UserInputValidationException(errorMessage)
        }

        if (!projectAssociatedList.map { it.projectId }.isNullOrEmpty()) {
            val errorMessage = "Not allowed to provide parameter 'projectId' in this request"
            throw UserInputValidationException(errorMessage)
        }

        val checkIds = projectAssociatedList.map {
            projectRepository.existsById(it.associatedProjectId)
        }

        if (checkIds.contains(false)) {
            val errorMessage = "One or more ID 'associatedProjectId' not exists"
            throw UserInputValidationException(errorMessage)
        }
    }

    return projectAssociatedList.map {
        projectAssociatedRepository.save(
            ProjectAssociated(
                null,
                projectId,
                it.associatedProjectId
            )
        )
    }.toMutableList()
}
</code>```

My Controller class:

```<code>@ApiOperation("Add associated Projects to a specific Project")
@PostMapping(path = ["/project-associated"], consumes = [MediaType.APPLICATION_JSON_VALUE])
fun createAssociatedProjectList(
    @ApiParam("The id of the Project", required = true)
    @RequestParam("id")
    id: UUID,
    @ApiParam("JSON object representing the ProjectAssociated")
    @RequestBody projectAssociated: MutableList<ProjectAssociated>
): ResponseEntity<WrappedResponse<MutableList<ProjectAssociated>>> {

    val createdProjectAssociatedList = projectService.addAssociatedProjectByProjectId(id, projectAssociated)

    return ResponseEntity
        .status(201)
        .location(URI.create("$id/project-associated"))
        .body(
            ResponseDto(
                code = 201,
                data = PageDto(list = mutableListOf(createdProjectAssociatedList))
            ).validated()
        )
}
</code>```

But when i try to send this payload with the project id in @RequestParam:

```<code>[
  {
    "associatedProjectId": "7fe40f90-5178-11ea-9136-1b65a920a5d9"
  },
  {
    "associatedProjectId": "7fe8aaaa-5178-11ea-9136-1b65a920a5d9"
  }
]
</code>```

I have a custom exception where i tell the user if projectId or the id is in the payload that is now allowed to have it in the payload. When i try to POST the payload example above it tells me that projectId or id is in the request? How can that be?

I also printed out the list before if checks:

[ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe40f90-5178-11ea-9136-1b65a920a5d9), ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe8aaaa-5178-11ea-9136-1b65a920a5d9)]

What am I doing wrong?

Thanks for the help!

答:
In the block projectAssociatedList.map { it.id } you are mapping your list to something like [null, null] and it is not null or empty.

So, the complete condition !projectAssociatedList.map { it.id }.isNullOrEmpty() returns true.

If you want to continue using the same logic, you should use !projectAssociatedList.mapNotNull { it.id }.isNullOrEmpty() instead.

The mapNotNull function will filter the null values and output a list just with the not null values. If there is only null values, the list will be empty.

But, a simpler and expressive way to check if there is any not null attribute in a list of objects could be projectAssociatedList.any { it.id != null }

Body:
I have an issue where i have a method where i am checking the payload has the attributes or not. When i am sending my payload i want to check that the user dont have inserted attributes which not allowed in the payload.

My entity class:

@Entity
data class ProjectAssociated(

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(columnDefinition = "BINARY(16)")
    var id: UUID? = null,

    @Column(columnDefinition = "BINARY(16)")
    var projectId: UUID? = null,

    @Column(columnDefinition = "BINARY(16)")
    var associatedProjectId: UUID? = null
)

My Service class:

fun addAssociatedProjectByProjectId(
    projectId: UUID,
    projectAssociatedList: MutableList<ProjectAssociated>
): MutableList<ProjectAssociated> {

    if (projectAssociatedList.isNotEmpty()) {

        println(projectAssociatedList)

        if (!projectAssociatedList.map { it.id }.isNullOrEmpty()) {
            val errorMessage = "Not allowed to provide parameter 'id' in this request"
            throw UserInputValidationException(errorMessage)
        }

        if (!projectAssociatedList.map { it.projectId }.isNullOrEmpty()) {
            val errorMessage = "Not allowed to provide parameter 'projectId' in this request"
            throw UserInputValidationException(errorMessage)
        }

        val checkIds = projectAssociatedList.map {
            projectRepository.existsById(it.associatedProjectId)
        }

        if (checkIds.contains(false)) {
            val errorMessage = "One or more ID 'associatedProjectId' not exists"
            throw UserInputValidationException(errorMessage)
        }
    }

    return projectAssociatedList.map {
        projectAssociatedRepository.save(
            ProjectAssociated(
                null,
                projectId,
                it.associatedProjectId
            )
        )
    }.toMutableList()
}

My Controller class:

@ApiOperation("Add associated Projects to a specific Project")
@PostMapping(path = ["/project-associated"], consumes = [MediaType.APPLICATION_JSON_VALUE])
fun createAssociatedProjectList(
    @ApiParam("The id of the Project", required = true)
    @RequestParam("id")
    id: UUID,
    @ApiParam("JSON object representing the ProjectAssociated")
    @RequestBody projectAssociated: MutableList<ProjectAssociated>
): ResponseEntity<WrappedResponse<MutableList<ProjectAssociated>>> {

    val createdProjectAssociatedList = projectService.addAssociatedProjectByProjectId(id, projectAssociated)

    return ResponseEntity
        .status(201)
        .location(URI.create("$id/project-associated"))
        .body(
            ResponseDto(
                code = 201,
                data = PageDto(list = mutableListOf(createdProjectAssociatedList))
            ).validated()
        )
}

But when i try to send this payload with the project id in @RequestParam:

[
  {
    "associatedProjectId": "7fe40f90-5178-11ea-9136-1b65a920a5d9"
  },
  {
    "associatedProjectId": "7fe8aaaa-5178-11ea-9136-1b65a920a5d9"
  }
]

I have a custom exception where i tell the user if projectId or the id is in the payload that is now allowed to have it in the payload. When i try to POST the payload example above it tells me that projectId or id is in the request? How can that be?

I also printed out the list before if checks:

[ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe40f90-5178-11ea-9136-1b65a920a5d9), ProjectAssociated(id=null, projectId=null, associatedProjectId=7fe8aaaa-5178-11ea-9136-1b65a920a5d9)]

What am I doing wrong?

Thanks for the help!


问:
publishing the database with the project
How can I publish the application database along with it?

I'm using Visual Studio 2008 with C# language.

The database has the log-in information needed in order to go in the MdiParent and do tasks there. The same database is where employee records would also be saved...

I'm currently developing an employee information system.

答:
What is your db  engine? For MySQL, I use the utility mysqldump. You then can use the source command in a scripted installer to deploy your db from the dump file.

With SQLSERVER, I use the Import/Export tool that comes with SQLSERVER to script out the db with any data that I want to have deployed with the database. I then run the script on the db in my installer.

You have several options. The question is, what are you using for an installer? NSIS, Visual Studio Setup Projects? etc... How you answer that will determine the best approach for how to deploy your database.

You can also do as @oded recommends though I have never done this except for with basic ASP.NET sites and the sqlexpress db that come with the VS project. Usually, I find that whether or not it is a good idea to use the file just depends on your complexity.

ContentLicense: CC BY-SA 3.0


问:
Is there a way of creating AWS EC2 instance with postman?
I want to create an EC2 instance with Postman but, I couldn't find anything on the internet? Is there a way of doing this? or should I use aws-cli instead?

答:
Everything in AWS is an API that can be hit directly or via CLI or SDK. All those do is make the same calls you'd have to make. The advantage to using the CLI or SDK is that they manage the auth for you, which is no trivial matter. The following document gives you a place to start looking at all the options for using AWS APIs.

Making API Requests


问:
Plotting grids across the subplots Python matplotlib
I have tried the following:

```<code>d = [1,2,3,4,5,6,7,8,9]
f = [0,1,0,0,1,0,1,1,0]
fig = plt.figure()
fig.set_size_inches(30,10)
ax1 = fig.add_subplot(211)
line1 = ax1.plot(d,marker='.',color='b',label="1 row")
ax2 = fig.add_subplot(212)
line1 = ax2.plot(f,marker='.',color='b',label="1 row")
ax1.grid()
ax2.grid()
plt.show()
</code>```

I got the following output :

But I was expecting the following output:

How I can get the grids across the two plots?

答:
Here is my solution:

```<code>import matplotlib.pyplot as plt

x1 = [1,2,3,4,5,6,7,8,9]
x2= [0,1,0,0,1,0,1,1,0]
x3= range(-10,0)
# frameon=False removes frames
# fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True, subplot_kw=dict(frameon=False))
fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True)
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)

ax1.grid()
ax2.grid()
ax3.grid()

ax1.plot(x1)
ax2.plot(x2)
ax3.plot(x3)
</code>```

Without frames subplot_kw=dict(frameon=False):

Body:
I have tried the following:

d = [1,2,3,4,5,6,7,8,9]
f = [0,1,0,0,1,0,1,1,0]
fig = plt.figure()
fig.set_size_inches(30,10)
ax1 = fig.add_subplot(211)
line1 = ax1.plot(d,marker='.',color='b',label="1 row")
ax2 = fig.add_subplot(212)
line1 = ax2.plot(f,marker='.',color='b',label="1 row")
ax1.grid()
ax2.grid()
plt.show()

I got the following output :

But I was expecting the following output:

How I can get the grids across the two plots?

Body:
Here is my solution:

import matplotlib.pyplot as plt

x1 = [1,2,3,4,5,6,7,8,9]
x2= [0,1,0,0,1,0,1,1,0]
x3= range(-10,0)
# frameon=False removes frames
# fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True, subplot_kw=dict(frameon=False))
fig, (ax1,ax2, ax3) = plt.subplots(nrows=3, sharex=True)
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)

ax1.grid()
ax2.grid()
ax3.grid()

ax1.plot(x1)
ax2.plot(x2)
ax3.plot(x3)

Without frames subplot_kw=dict(frameon=False):


问:
Object creation order with class having containment of other objects
```<code>#include "iostream"
using namespace std;
class C
{
    public:
    C() { cout << "C's Constructor Called " << endl;  }
};

class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
    A(int) {  cout << "A's int Constructor Called " << endl;  }
};

class B
{
    public:
    A a;
    B() { cout << "B's Constructor Called " << endl; }
    B(int i) : a(i) { cout << "B's int Constructor Called " << endl; }
    C c;
};

int main()
{
    B b1(1);
    return 0;
}
</code>```

Output:

    A's int Constructor Called

    C's Constructor Called

    B's int Constructor Called

Question :

Why output does not contain "A's Constructor Called"

According to me i thought Output would be like below :

    A's Constructor Called

    C's Constructor Called

    B's int Constructor Called

Wondering why A a does not lead to constructor A() being called but only A(int) because of a(i)

答:
C++ always calls only exactly one constructor of a class.

In your case, the compiler chooses the A(int) constructor (since that's what you're using in B) and therefore never calls any other constructor.

Body:
#include "iostream"
using namespace std;
class C
{
    public:
    C() { cout << "C's Constructor Called " << endl;  }
};

class A
{
    public:
    A() { cout << "A's Constructor Called " << endl;  }
    A(int) {  cout << "A's int Constructor Called " << endl;  }
};

class B
{
    public:
    A a;
    B() { cout << "B's Constructor Called " << endl; }
    B(int i) : a(i) { cout << "B's int Constructor Called " << endl; }
    C c;
};

int main()
{
    B b1(1);
    return 0;
}

Output:

    A's int Constructor Called

    C's Constructor Called

    B's int Constructor Called

Question :

Why output does not contain "A's Constructor Called"

According to me i thought Output would be like below :

    A's Constructor Called

    C's Constructor Called

    B's int Constructor Called

Wondering why A a does not lead to constructor A() being called but only A(int) because of a(i)


问:
Detect hardware graphics support
I am looking for a way to programatically differentiate between running on a machine with hardware graphics support, for example

as opposed to running without hardware drivers, in which case I'll revert to software rendering

I've tried using the wmi module, however in the former case when graphics hardware was available, I can find nothing in the video controllers that indicates they were properly detected

```<code>import wmi
pc = wmi.WMI()
for graphics in pc.Win32_VideoController():
    print(graphics.properties)
</code>```

Output

```<code>{'AcceleratorCapabilities': None, 'AdapterCompatibility': None, 'AdapterDACType': None, 'AdapterRAM': None, 'Availability': None, 'CapabilityDescriptions': None, 'Caption': None, 'ColorTableEntries': None, 'ConfigManagerErrorCode': None, 'ConfigManagerUserConfig': None, 'CreationClassName': None, 'CurrentBitsPerPixel': None, 'CurrentHorizontalResolution': None, 'CurrentNumberOfColors': None, 'CurrentNumberOfColumns': None, 'CurrentNumberOfRows': None, 'CurrentRefreshRate': None, 'CurrentScanMode': None, 'CurrentVerticalResolution': None, 'Description': None, 'DeviceID': None, 'DeviceSpecificPens': None, 'DitherType': None, 'DriverDate': None, 'DriverVersion': None, 'ErrorCleared': None, 'ErrorDescription': None, 'ICMIntent': None, 'ICMMethod': None, 'InfFilename': None, 'InfSection': None, 'InstallDate': None, 'InstalledDisplayDrivers': None, 'LastErrorCode': None, 'MaxMemorySupported': None, 'MaxNumberControlled': None, 'MaxRefreshRate': None, 'MinRefreshRate': None, 'Monochrome': None, 'Name': None, 'NumberOfColorPlanes': None, 'NumberOfVideoPages': None, 'PNPDeviceID': None, 'PowerManagementCapabilities': None, 'PowerManagementSupported': None, 'ProtocolSupported': None, 'ReservedSystemPaletteEntries': None, 'SpecificationVersion': None, 'Status': None, 'StatusInfo': None, 'SystemCreationClassName': None, 'SystemName': None, 'SystemPaletteEntries': None, 'TimeOfLastReset': None, 'VideoArchitecture': None, 'VideoMemoryType': None, 'VideoMode': None, 'VideoModeDescription': None, 'VideoProcessor': None}
{'AcceleratorCapabilities': None, 'AdapterCompatibility': None, 'AdapterDACType': None, 'AdapterRAM': None, 'Availability': None, 'CapabilityDescriptions': None, 'Caption': None, 'ColorTableEntries': None, 'ConfigManagerErrorCode': None, 'ConfigManagerUserConfig': None, 'CreationClassName': None, 'CurrentBitsPerPixel': None, 'CurrentHorizontalResolution': None, 'CurrentNumberOfColors': None, 'CurrentNumberOfColumns': None, 'CurrentNumberOfRows': None, 'CurrentRefreshRate': None, 'CurrentScanMode': None, 'CurrentVerticalResolution': None, 'Description': None, 'DeviceID': None, 'DeviceSpecificPens': None, 'DitherType': None, 'DriverDate': None, 'DriverVersion': None, 'ErrorCleared': None, 'ErrorDescription': None, 'ICMIntent': None, 'ICMMethod': None, 'InfFilename': None, 'InfSection': None, 'InstallDate': None, 'InstalledDisplayDrivers': None, 'LastErrorCode': None, 'MaxMemorySupported': None, 'MaxNumberControlled': None, 'MaxRefreshRate': None, 'MinRefreshRate': None, 'Monochrome': None, 'Name': None, 'NumberOfColorPlanes': None, 'NumberOfVideoPages': None, 'PNPDeviceID': None, 'PowerManagementCapabilities': None, 'PowerManagementSupported': None, 'ProtocolSupported': None, 'ReservedSystemPaletteEntries': None, 'SpecificationVersion': None, 'Status': None, 'StatusInfo': None, 'SystemCreationClassName': None, 'SystemName': None, 'SystemPaletteEntries': None, 'TimeOfLastReset': None, 'VideoArchitecture': None, 'VideoMemoryType': None, 'VideoMode': None, 'VideoModeDescription': None, 'VideoProcessor': None}
</code>```

If it matters, I will be targeting a Windows system, in case there is an OS-specific solution to this.

答:
One way to accomplish this is to use infi.devicemanager to detect if 'Microsoft Basic Display Driver' is listed in the device descriptions, which would indicate lack of hardware graphics support.

```<code>from infi.devicemanager import DeviceManager

def has_hardware_graphics():
    dm = DeviceManager()
    return all(dev.description != 'Microsoft Basic Display Driver' for dev in dm.all_devices)
</code>```

Title: Detect hardware graphics support

Body:
I am looking for a way to programatically differentiate between running on a machine with hardware graphics support, for example

as opposed to running without hardware drivers, in which case I'll revert to software rendering

I've tried using the wmi module, however in the former case when graphics hardware was available, I can find nothing in the video controllers that indicates they were properly detected

import wmi
pc = wmi.WMI()
for graphics in pc.Win32_VideoController():
    print(graphics.properties)

Output

{'AcceleratorCapabilities': None, 'AdapterCompatibility': None, 'AdapterDACType': None, 'AdapterRAM': None, 'Availability': None, 'CapabilityDescriptions': None, 'Caption': None, 'ColorTableEntries': None, 'ConfigManagerErrorCode': None, 'ConfigManagerUserConfig': None, 'CreationClassName': None, 'CurrentBitsPerPixel': None, 'CurrentHorizontalResolution': None, 'CurrentNumberOfColors': None, 'CurrentNumberOfColumns': None, 'CurrentNumberOfRows': None, 'CurrentRefreshRate': None, 'CurrentScanMode': None, 'CurrentVerticalResolution': None, 'Description': None, 'DeviceID': None, 'DeviceSpecificPens': None, 'DitherType': None, 'DriverDate': None, 'DriverVersion': None, 'ErrorCleared': None, 'ErrorDescription': None, 'ICMIntent': None, 'ICMMethod': None, 'InfFilename': None, 'InfSection': None, 'InstallDate': None, 'InstalledDisplayDrivers': None, 'LastErrorCode': None, 'MaxMemorySupported': None, 'MaxNumberControlled': None, 'MaxRefreshRate': None, 'MinRefreshRate': None, 'Monochrome': None, 'Name': None, 'NumberOfColorPlanes': None, 'NumberOfVideoPages': None, 'PNPDeviceID': None, 'PowerManagementCapabilities': None, 'PowerManagementSupported': None, 'ProtocolSupported': None, 'ReservedSystemPaletteEntries': None, 'SpecificationVersion': None, 'Status': None, 'StatusInfo': None, 'SystemCreationClassName': None, 'SystemName': None, 'SystemPaletteEntries': None, 'TimeOfLastReset': None, 'VideoArchitecture': None, 'VideoMemoryType': None, 'VideoMode': None, 'VideoModeDescription': None, 'VideoProcessor': None}
{'AcceleratorCapabilities': None, 'AdapterCompatibility': None, 'AdapterDACType': None, 'AdapterRAM': None, 'Availability': None, 'CapabilityDescriptions': None, 'Caption': None, 'ColorTableEntries': None, 'ConfigManagerErrorCode': None, 'ConfigManagerUserConfig': None, 'CreationClassName': None, 'CurrentBitsPerPixel': None, 'CurrentHorizontalResolution': None, 'CurrentNumberOfColors': None, 'CurrentNumberOfColumns': None, 'CurrentNumberOfRows': None, 'CurrentRefreshRate': None, 'CurrentScanMode': None, 'CurrentVerticalResolution': None, 'Description': None, 'DeviceID': None, 'DeviceSpecificPens': None, 'DitherType': None, 'DriverDate': None, 'DriverVersion': None, 'ErrorCleared': None, 'ErrorDescription': None, 'ICMIntent': None, 'ICMMethod': None, 'InfFilename': None, 'InfSection': None, 'InstallDate': None, 'InstalledDisplayDrivers': None, 'LastErrorCode': None, 'MaxMemorySupported': None, 'MaxNumberControlled': None, 'MaxRefreshRate': None, 'MinRefreshRate': None, 'Monochrome': None, 'Name': None, 'NumberOfColorPlanes': None, 'NumberOfVideoPages': None, 'PNPDeviceID': None, 'PowerManagementCapabilities': None, 'PowerManagementSupported': None, 'ProtocolSupported': None, 'ReservedSystemPaletteEntries': None, 'SpecificationVersion': None, 'Status': None, 'StatusInfo': None, 'SystemCreationClassName': None, 'SystemName': None, 'SystemPaletteEntries': None, 'TimeOfLastReset': None, 'VideoArchitecture': None, 'VideoMemoryType': None, 'VideoMode': None, 'VideoModeDescription': None, 'VideoProcessor': None}

If it matters, I will be targeting a Windows system, in case there is an OS-specific solution to this.

Body:
One way to accomplish this is to use infi.devicemanager to detect if 'Microsoft Basic Display Driver' is listed in the device descriptions, which would indicate lack of hardware graphics support.

from infi.devicemanager import DeviceManager

def has_hardware_graphics():
    dm = DeviceManager()
    return all(dev.description != 'Microsoft Basic Display Driver' for dev in dm.all_devices)


问:
Kotlin reflection - creating objects from CSV
I have a data class named Member:

```<code>data class Member(){
    val first_name: String
    val last_name: String
    //30 more

    //a few simple methods
}
</code>```

I am trying to import a CSV file. Each line of the file contains the fields I want to use to instantiate my Members.

```<code>fun ReadCsvFileKotlin() {
    val csvFile = "C:\\Data.csv"
    var memberList = mutableListOf<Member>()
    var reader = File(csvFile).readLines()
    var mbr: Member
    class Member(val p: Int)
    val prop = Member::p
    for(line in reader){
        val mbrProperties = line.split(",")
        for(i in 0..mbrProperties.lastIndex){
            //assign mbrProperties[i] to mbr property
            //mbrProperties[0] = "Bob"
            //mbr.first_name = "Bob"
            //Member::p = mbrProperties[i]
    }
    memberList.add(mbr)
}
</code>```

I've done my research, but I'm failing to wrap my head around the information I've read and just can't bridge the gap between where I am and where I want to be.

Any advice would be appreciated! Walking me through or giving me examples using my example code would be welcome.

Background: I am automating tests for a website. Prior to executing each test, the member meeting the necessary test criteria is selected from a list, populated from the CSV file. I am looking to create my member objects in this fashion to reduce maintenance overhead as the test scope expands and additional criteria (and Member class fields) are added.

Why am I doing any of this in the manner I am doing? Because I still have much to learn... (So, if you see a better way, please, educate me!)

Thanks!

答:
While I did play around with yole's response, and reflection even further, I found a better way to handle me issue.

As a less experienced programmer, I was trying to use the wrong tool for the job. I wanted to take an object, that had a number of functions that i would need for a number of different automated tests, simulating a user - Code I wanted in every instance, whether I needed it for a test or not.

But what I wanted was the flexibility in my data. So instead of a single object with a growing amount of attributes, or multiple objects, each custom to a specific data set, I went to one attribute. The best solution, was a key/value pair attribute. I apologize if my Kotlin speak is rusty, I've been focused on python the last two+ years. Dictionary?

Essentially, I stripped off the header of my csv, mapped it to each row as a dictionary/key,value pair which was then added as I instantiated an object and added the object to a list. Similar if querying a database directly rather than working with csv or Excel files.

So as long as I don't write queries that change the column names of my tables for my results, and I know the column names in the database (They are not changing anytime soon), and I'm already mapping that data to the process and/or gui (or both) things turned quite nicely without the reflection overhead.

Body:
I have a data class named Member:

data class Member(){
    val first_name: String
    val last_name: String
    //30 more

    //a few simple methods
}

I am trying to import a CSV file. Each line of the file contains the fields I want to use to instantiate my Members.

fun ReadCsvFileKotlin() {
    val csvFile = "C:\\Data.csv"
    var memberList = mutableListOf<Member>()
    var reader = File(csvFile).readLines()
    var mbr: Member
    class Member(val p: Int)
    val prop = Member::p
    for(line in reader){
        val mbrProperties = line.split(",")
        for(i in 0..mbrProperties.lastIndex){
            //assign mbrProperties[i] to mbr property
            //mbrProperties[0] = "Bob"
            //mbr.first_name = "Bob"
            //Member::p = mbrProperties[i]
    }
    memberList.add(mbr)
}

I've done my research, but I'm failing to wrap my head around the information I've read and just can't bridge the gap between where I am and where I want to be.

Any advice would be appreciated! Walking me through or giving me examples using my example code would be welcome.

Background: I am automating tests for a website. Prior to executing each test, the member meeting the necessary test criteria is selected from a list, populated from the CSV file. I am looking to create my member objects in this fashion to reduce maintenance overhead as the test scope expands and additional criteria (and Member class fields) are added.

Why am I doing any of this in the manner I am doing? Because I still have much to learn... (So, if you see a better way, please, educate me!)

Thanks!


问:
How I use an external javasrript file inside .ts file without converting it?
i have external javascript file. I want to use it in .ts file without converting it. Anyone have idea to use it inside typescript without converting.</p>

答:
Option 1

Place your script inside the src\assets folder.

Include the script in angular.json

```<code>"scripts": [
  "src/assets/myscript.js"
]
</code>```

Option 2

Alternatively, host your script via a CDN (or anywhere really):
https://www.cloudflare.com/myscript.js

Then reference that script as you normally would in your HTML:

Index.html

<!doctype html>

  <meta charset="utf-8">
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <app-root></app-root>

```

Body:
Option 1

Place your script inside the src\assets folder.

Include the script in angular.json

"scripts": [
  "src/assets/myscript.js"
]

Option 2

Alternatively, host your script via a CDN (or anywhere really):
https://www.cloudflare.com/myscript.js

Then reference that script as you normally would in your HTML:

Index.html

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://www.cloudflare.com/myscript.js"></script>
</head>

<body>
  <app-root></app-root>
</body>

</html>


问:
Flutter Dart HTTP headers not working. Sending Request with "headers". On response authorization error, {"CODE":401,"MESSAGE":"Unauthorized"}
Sending request to API with authorization and other headers, its returning unauthorized. it seems like server is not getting headers while requesting. i tried different approaches to send http headers on request but failed. I tried Dio , HttpClient, Normal http request all are failed. I spent my 2 days on this thing, still not resolved. from Postman, and other mediums request is working.</p>

```<code>Map<String,String> reqHeaders = {
  'Content-type': 'application/json',
  'Accept': 'application/json',
  "Authorization": "xxxxx",
  "langapi": "en"
};
Future<MzResponseData> getHttp() async {
  var dio = Dio();
  dio.options.baseUrl = baseUrl;
  dio.options.headers = reqHeaders;
  dio.options.contentType = ContentType.parse("application/json");
  Response response = await dio.get("/uri/");
  print(response);
}
</code>```

答:
Try this..</p>

```<code>final response = await dio.get(
      url,
      options: Options(
        headers: {
          'Authorization': 'Bearer $token',
        },
      )
    );
</code>```

Body:
Sending request to API with authorization and other headers, its returning unauthorized. it seems like server is not getting headers while requesting. i tried different approaches to send http headers on request but failed. I tried Dio , HttpClient, Normal http request all are failed. I spent my 2 days on this thing, still not resolved. from Postman, and other mediums request is working.

Map<String,String> reqHeaders = {
  'Content-type': 'application/json',
  'Accept': 'application/json',
  "Authorization": "xxxxx",
  "langapi": "en"
};
Future<MzResponseData> getHttp() async {
  var dio = Dio();
  dio.options.baseUrl = baseUrl;
  dio.options.headers = reqHeaders;
  dio.options.contentType = ContentType.parse("application/json");
  Response response = await dio.get("/uri/");
  print(response);
}

Body:
Try this..

final response = await dio.get(
      url,
      options: Options(
        headers: {
          'Authorization': 'Bearer $token',
        },
      )
    );


问:
How to delete custom list in Excel by C#
I am trying to delete a list in Excel custom list by C# language. But my program can't delete the list I want. I don't know what's problem with my program. It's don't notice any error.
I hope someone can help me to fix it.
Thank you so much.

```<code>Object customListContents;
for (int i = 5; i <= excelApp.Application.CustomListCount; i++)
    {
        customListContents = excelApp.Application.GetCustomListContents(i);
        foreach (string item in (dynamic)(customListContents))
                if (item == "China" || item == "Taiwan")
                    {
                        excelApp.Application.DeleteCustomList(i);
                         break;
                    }
    }
</code>```

答:
I suppose that all you need is this:  </p>

```<code>Globals.ThisAddIn.Application.DeleteCustomList(Globals.ThisAddIn.Application.GetCustomListNum(new string[] { "China", "Taiwan" }));
</code>```

<p>Here is the same, a bit simpler but also longer:  </p>

```<code>
// get an application object
Excel.Application xlApp = Globals.ThisAddIn.Application;

// assign the list you want to remove to an array
string[] myList = new string[] { "China", "Taiwan" };

// get the number of your list from Excel application
int listNum = xlApp.GetCustomListNum(myList);

// delete the list by its number - it's the only way to delete
// a custom list that I've found
xlApp.DeleteCustomList(listNum);
</code>```

Body:
I am trying to delete a list in Excel custom list by C# language. But my program can't delete the list I want. I don't know what's problem with my program. It's don't notice any error.
I hope someone can help me to fix it.
Thank you so much.

Object customListContents;
for (int i = 5; i <= excelApp.Application.CustomListCount; i++)
    {
        customListContents = excelApp.Application.GetCustomListContents(i);
        foreach (string item in (dynamic)(customListContents))
                if (item == "China" || item == "Taiwan")
                    {
                        excelApp.Application.DeleteCustomList(i);
                         break;
                    }
    }

Body:
I suppose that all you need is this:

Globals.ThisAddIn.Application.DeleteCustomList(Globals.ThisAddIn.Application.GetCustomListNum(new string[] { "China", "Taiwan" }));

Here is the same, a bit simpler but also longer:

// get an application object
Excel.Application xlApp = Globals.ThisAddIn.Application;

// assign the list you want to remove to an array
string[] myList = new string[] { "China", "Taiwan" };

// get the number of your list from Excel application
int listNum = xlApp.GetCustomListNum(myList);

// delete the list by its number - it's the only way to delete
// a custom list that I've found
xlApp.DeleteCustomList(listNum);


问:
set choices in django model
```<code>class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open)
</code>```

so i had to make this changes to the two classes but i still doesnt work

```<code>class LeaveRequestStatus(IntEnum):
    open = (0, 'Open')
    accepted = (1, 'Accepted')
    rejected = (2, 'Rejected')
    closed = (3, 'Closed')

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(choices=LeaveRequestStatus, default=LeaveRequestStatus.open)
</code>```

But it still doesn't work what i missing or what is not supposed to be there

答:
```<code>class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open.value)
</code>```

This was correct just don't forget to use .value when working with enums

Title: set choices in django model

Body:
class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open)

so i had to make this changes to the two classes but i still doesnt work

class LeaveRequestStatus(IntEnum):
    open = (0, 'Open')
    accepted = (1, 'Accepted')
    rejected = (2, 'Rejected')
    closed = (3, 'Closed')

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(choices=LeaveRequestStatus, default=LeaveRequestStatus.open)

But it still doesn't work what i missing or what is not supposed to be there

Body:
class LeaveRequestStatus(IntEnum):
    open = 0
    accepted = 1
    rejected = 2
    closed = 3

class LeaveRequest(models.Model):
    status = models.PositiveSmallIntegerField(default=LeaveRequestStatus.open.value)

This was correct just don't forget to use .value when working with enums


问:
How to transform Flutter web app into a PWA?
I am making a new Web application with Flutter web.
I want to add service workers to my app in order to make it a PWA.

What I need to use to achieve my goal ?

I have tried to do it with dart packages (service_worker or pwa), but they are deprecated for Dart 2.

答:
You currently need to switch to Flutter Channel Dev (at Feb 17th 2020, current Dev version 1.15.3)

For existing projects, use the terminal to hit the command:

flutter create .

For new projects, you would have a 2 files: manifest.json and index.html inside your web folder.

While checking index.html you would notice the following script:

```<code>if ('serviceWorker' in navigator) {
  window.addEventListener('load', function () {
     navigator.serviceWorker.register('/flutter_service_worker.js');
  });
}
</code>```

If the script is not there, added inside

This script creates the PWA support for you and be able to "install" the app on a device (this also includes MacOS)

Follow this GUIDE to complete your PWA functionalities.

Body:
You currently need to switch to Flutter Channel Dev (at Feb 17th 2020, current Dev version 1.15.3)

For existing projects, use the terminal to hit the command:

flutter create .

For new projects, you would have a 2 files: manifest.json and index.html inside your web folder.

While checking index.html you would notice the following script:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function () {
     navigator.serviceWorker.register('/flutter_service_worker.js');
  });
}

If the script is not there, added inside <body></body>

This script creates the PWA support for you and be able to "install" the app on a device (this also includes MacOS)

Follow this GUIDE to complete your PWA functionalities.


问:
How do I set focus on component html tag
I need to set focus on  tag in my functional component when it loads. I cannot make it work properly. Please help! Below is my code;
Detail.js

```<code>import React,{useState,useEffect} from 'react';
const Detail=({course})=>{
const [myfocus]=useState(null);
useEffect(() => {
    setState({
    this.myfocus.focus(); //? how to set id myfocus to this.myfocus.focus()
  });

return (
   <div>
    <h4  tabindex="0"   id="myfocus">
     {course.SUBJECT} {course.CATALOG_NBR}
     </h4>

</div>
);
</code>```

};
export default Detail;

答:
We have autoFocus prop in React, so you can try
.

But you can also solve this with the ref:

```<code>const h4 = useRef()

useEffec(() =>
    h4.current.focus()
)[];

return( <h4 ref={h4} /> )
</code>```

You are right, that tabIndex (use camel case in React) is probably required to make it work for the h4 element.

Body:
I need to set focus on  tag in my functional component when it loads. I cannot make it work properly. Please help! Below is my code;
Detail.js

import React,{useState,useEffect} from 'react';
const Detail=({course})=>{
const [myfocus]=useState(null);
useEffect(() => {
    setState({
    this.myfocus.focus(); //? how to set id myfocus to this.myfocus.focus()
  });

return (

     {course.SUBJECT} {course.CATALOG_NBR}

);

};
export default Detail;

Body:
We have autoFocus prop in React, so you can try <h4 autoFocus />.

But you can also solve this with the ref:

const h4 = useRef()

useEffec(() =>
    h4.current.focus()
)[];

return( <h4 ref={h4} /> )

You are right, that tabIndex (use camel case in React) is probably required to make it work for the h4 element.


问:
I cannot install yum in my docker container
I have a docker container which was built by a keycloak image.

I want to install vim in the container but I found that I need to have yum in order to install the vim. I tried to download yum from the internet and use rpm to install it, but the container didn't have sudo to let me change the file permission.

Following is my linux version:

```<code>NAME="Red Hat Enterprise Linux"
VERSION="8.0 (Ootpa)"
ID="rhel"
ID_LIKE="fedora"
VERSION_ID="8.0"
PLATFORM_ID="platform:el8"
PRETTY_NAME="Red Hat Enterprise Linux 8.0 (Ootpa)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:8.0:GA"
HOME_URL="https://www.redhat.com/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 8"
REDHAT_BUGZILLA_PRODUCT_VERSION=8.0
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="8.0"
</code>```

How can I get any text editor installed in the container?

答:
I ran into the same problem and found a solution. In your Dockerfile, Try:

```<code>FROM jboss/keycloak:8.0.1
USER root
RUN microdnf install <whatever>
</code>```

HTH.

Body:
I have a docker container which was built by a keycloak image.

I want to install vim in the container but I found that I need to have yum in order to install the vim. I tried to download yum from the internet and use rpm to install it, but the container didn't have sudo to let me change the file permission.

Following is my linux version:

NAME="Red Hat Enterprise Linux"
VERSION="8.0 (Ootpa)"
ID="rhel"
ID_LIKE="fedora"
VERSION_ID="8.0"
PLATFORM_ID="platform:el8"
PRETTY_NAME="Red Hat Enterprise Linux 8.0 (Ootpa)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:8.0:GA"
HOME_URL="https://www.redhat.com/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 8"
REDHAT_BUGZILLA_PRODUCT_VERSION=8.0
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="8.0"

How can I get any text editor installed in the container?

Body:
I ran into the same problem and found a solution. In your Dockerfile, Try:

FROM jboss/keycloak:8.0.1
USER root
RUN microdnf install <whatever>

HTH.


问:
re-render component in react to get default props again
I'm using package react-calendar I'm gonna customize it to select just month, for example 2020-02 or 2020-05 , ... and also
It should be hidden first and displayed when I click the button (Icon).  so I wrote a component to toggle it, named Dropdown , plus I set view prop of calendar to show months of year when it appears and when I click on a month, the hide state changes and Dropdown will close and a month would be selected.

However the problem is when I wanna click again on the button select another month , the calendar starts from days not month view because after selecting month it goes to select day. actually it needs to re-render or set again 'year' to it's view props.

Is there any way to re-render Calendar component when state changes.

import section:

```<code>import ReactCalendar from "react-calendar";
</code>```

state section:

```<code>const [hide, sethide] = useState(false);
</code>```

return section:

```<code><Dropdown
    forceHide={hide}
    onChangeShow={() => sethide(false)}
    toggle={
        <Icon name="calendar" size={32} />
    }
  >
    <ReactCalendar
      view={'year'}
      onClickMonth={value => {
        console.log("value", value);
        sethide(true);
      }}
    />
  </Dropdown>
</code>```

any helps is appreciated.

[first toggle dropdown shows months]1

[enter image description here]2

答:
I solve my problem in this way but I'm not sure it's an optimize solution if you have any idea please share with me.

I defined a function to clone it in each render occurs:

```<code>const RenderReactCalendar = ({view})=>{
 let Render = (
    <ReactCalendar
      onClickMonth={value => {
        console.log("value", value);
        sethide(true);
      }}    />
  );

  return React.cloneElement(Render, { view }, {});
};
</code>```

and then refactor my component:

```<code><Dropdown
    forceHide={hide}
    onChangeShow={() => sethide(false)}
    toggle={
        <Icon name="calendar" size={32} />
    }
  >
    <RenderReactCalendar
      view={'year'}
    />
  </Dropdown>
</code>```

Body:
I'm using package react-calendar I'm gonna customize it to select just month, for example 2020-02 or 2020-05 , ... and also
It should be hidden first and displayed when I click the button (Icon).  so I wrote a component to toggle it, named Dropdown , plus I set view prop of calendar to show months of year when it appears and when I click on a month, the hide state changes and Dropdown will close and a month would be selected.

However the problem is when I wanna click again on the button select another month , the calendar starts from days not month view because after selecting month it goes to select day. actually it needs to re-render or set again 'year' to it's view props.

Is there any way to re-render Calendar component when state changes.

import section:

import ReactCalendar from "react-calendar";

state section:

const [hide, sethide] = useState(false);

return section:

<Dropdown
    forceHide={hide}
    onChangeShow={() => sethide(false)}
    toggle={
        <Icon name="calendar" size={32} />
    }
  >
    <ReactCalendar
      view={'year'}
      onClickMonth={value => {
        console.log("value", value);
        sethide(true);
      }}
    />
  </Dropdown>

any helps is appreciated.

[first toggle dropdown shows months]1

[enter image description here]2

Body:
I solve my problem in this way but I'm not sure it's an optimize solution if you have any idea please share with me.

I defined a function to clone it in each render occurs:

const RenderReactCalendar = ({view})=>{
 let Render = (
    <ReactCalendar
      onClickMonth={value => {
        console.log("value", value);
        sethide(true);
      }}    />
  );

  return React.cloneElement(Render, { view }, {});
};

and then refactor my component:

<Dropdown
    forceHide={hide}
    onChangeShow={() => sethide(false)}
    toggle={
        <Icon name="calendar" size={32} />
    }
  >
    <RenderReactCalendar
      view={'year'}
    />
  </Dropdown>


问:
Flutter Outline Shows "Nothing to show" in android studio
I am trying to extract a Widget via Flutter Outline, but I am facing below problem in Android Studio.

Flutter Outline Shows  "Nothing to show"

After running

```<code>flutter doctor -v
</code>```

It shows:

How to overcome this problem?

答:
I have same issues.

I just restart IntelliJ/Android studio and every time it's enough.

Body:
I am trying to extract a Widget via Flutter Outline, but I am facing below problem in Android Studio.

Flutter Outline Shows  "Nothing to show"

After running

flutter doctor -v

It shows:

How to overcome this problem?


问:
CrudRepository Filter By One to Many Relation
I have two entity Customer and Order:

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long id;
  .....
  @OneToMany(mappedBy="customer")
  private Set<Order> orders = new HashSet<Order>();
  .....
}

```

<pre class="lang-java prettyprint-override"><code>@Entity
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    ........
    @ManyToOne()
    private Customer;
    ........
}
</code>```

In the CrudRepository I want to find all customers who have no orders.
How can I write the @Query? Or how can I write the method in CrudRepository Interface?

```<code>@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long>{

  findBy ......

  @Query(".......")
  find.....

}
</code>```

Thanks!

答:
You need to use the empty keyword, that can be used with collection expressions (no need to join).

The JPQL query would be

```<code>select c from Customer c where c.orders is empty
</code>```

Body:
I have two entity Customer and Order:

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long id;
  .....
  @OneToMany(mappedBy="customer")
  private Set<Order> orders = new HashSet<Order>();
  .....
}

@Entity
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    ........
    @ManyToOne()
    private Customer;
    ........
}

In the CrudRepository I want to find all customers who have no orders.
How can I write the @Query? Or how can I write the method in CrudRepository Interface?

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long>{

  findBy ......

  @Query(".......")
  find.....

}

Thanks!

Body:
You need to use the empty keyword, that can be used with collection expressions (no need to join).

The JPQL query would be

select c from Customer c where c.orders is empty


问:
Reply address configuration Issue in bot-authentication-msgraph code
I am using a Microsoft Graph api code to authenticate and get details of user.
I am trying to build and run below project.

console csharp connect msgraph project

After building and running the project , it redirects to a browser and ask to login using my account   and when i select my email account ,it shows the error (AADSTS500113 No reply address is registered for the application) in attached screenshot.

Please Help.

答:
Go to apps.dev.microsoft.com

Click the "Edit Application Manifest" button.

Add https://yourdomain.com/callback to the replyUrls element.

For Azure AD

If this does not fix your problem you might have to look at Azure AD. I am not sure which solution you're looking for since your question was a bit decryptive formulated.


问:
How to create a .Net NuGet package addressing 2.0 and 2.1
Our company has multiple applications that are .Net Framework 4.8 and we also are growing the number of applications that are .Net Core 3.1.

We have written a whole library of NuGet packages (in a private repository) written in .Net STANDARD 2.0 that are currently consumed by both the 4.8 and Core 3.1 applications mentioned above.

Standard 2.1 offers many new language features, such as Nullables, and we want to start to migrating our NuGet packages over to Standard 2.1, but obviously need to continue to support those applications still on .Net 4.8 (which can't consume Standard 2.1).

Obviously we need to branch our source code, but what is the convention for publishing two almost identical NuGet packages, one written in 2.0 and the other 2.1?

答: NuGet supports multiple-target-frameworks for a package. Please refer to doc to learn more.</p>


问:
use same elements in v-if and v-else
I'm creating a login/register page with Vue ,
and I have a tab for login and a tab for register .

this is my Template Code :

```<code> <transition v-bind:name="TabEffect">
          <div key="1" class="login" v-if="LoginTab">
            <div>
              <label class="inputText" for="email">Email Address</label>
              <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>
            </div>
            <div>
              <label class="inputText" for="password">Password</label>
              <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
            <button>
              {{ LoginTab ? 'Login' : 'Register' }}
            </button>
            <span class="or">or</span>
            <a href="#!" class="steamLogin">
              <i class="fab fa-steam"></i>
              <span>Login with Steam</span>
            </a>
          </div>
          <!-- Register -->
          <div key="2" v-else class="register">
            <div>
              <label class="inputText" for="email">Email Address</label>
              <input type="text" name="email" id="email" placeholder="Test@TestMail.com" />
            </div>
            <div>
              <label class="inputText" for="password">Password</label>
              <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
            <div>
              <label class="inputText" for="Cpassword">Repeat Password</label>
              <input type="password" name="Cpassword" id="Cpassword" placeholder="Repeat Password"/>
            </div>
            <button>{{ LoginTab ? 'Login' : 'Register' }}</button>
            <span class="or">or</span>
            <a href="#!" class="steamLogin">
              <i class="fab fa-steam"></i>
              <span>Login with Steam</span>
            </a>
            <!-- End of Register -->
          </div>
        </transition>
</code>```

code works fine but my problem is code repeating , as you see we have this part of code in both v-if and v-else :

```<code><button>{{ LoginTab ? 'Login' : 'Register' }}</button>
<span class="or">or</span>
<a href="#!" class="steamLogin">
  <i class="fab fa-steam"></i>
  <span>Login with Steam</span>
</a>
</code>```

I want this code to be on the transition , but I don't want to repeat a code twice , I tried to use the code outside of both v-if and v-else , but elements dosen't show at all .

I'm using vue 2.6.11

Update

Transition names are slideLeft and slideRight

SASS Transition Code :

```<code>.slideLeft-enter-active,.slideRight-enter-active
  transition: 0.4s ease-in-out

.slideLeft-leave-active,.slideRight-leave-active
  transition: 0.2s ease-in-out

.slideLeft-enter,.slideRight-leave-to
  transform: translateX(-100px)
  position: relative
  opacity: 0

.slideLeft-enter-to,.slideRight-enter-to,.slideLeft-leave ,.slideRight-leave
  transform: translateX(0)
  position: absolute
  top: 0
  width: 100%

.slideLeft-leave-to,.slideRight-enter
  transform: translateX(100px)
  position: relative
  opacity: 0
</code>```

答:
One way is to use the v-if in a <template> to handle the conditional part, leaving the common part out:

```<code><transition v-bind:name="TabEffect">
    <div v-for="(logTab, i) of [true, false]" v-if="logTab" :key="i+1" :class="LoginTab ? 'login' : 'register'">
        <template v-if="LoginTab">
            <div>
                <label class="inputText" for="email">Email Address</label>
                <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>
            </div>
            <div>
                <label class="inputText" for="password">Password</label>
                <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
        </template>
        <template v-else>
            <div>
                <label class="inputText" for="email">Email Address</label>
                <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>
            </div>
            <div>
                <label class="inputText" for="password">Password</label>
                <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
            <div>
                <label class="inputText" for="Cpassword">Repeat Password</label>
                <input type="password" name="Cpassword" id="Cpassword" placeholder="Repeat Password"/>
            </div>
        </template>

        <button>{{ LoginTab ? 'Login' : 'Register' }}</button>
        <span class="or">or</span>
        <a href="#!" class="steamLogin">
            <i class="fab fa-steam"></i>
            <span>Login with Steam</span>
        </a>
    </div>
</transition>
</code>```

Lastly, as the main div's class also depends on the LoginTab variable, we have to put a :class to handle it.

On a side note, only the Repeat password of your code seems to be the varying part. Still, I left the email/password in the conditional to be more faithful to your original question. (And because to change this would be very easy.)

Title: use same elements in v-if and v-else

Body:
I'm creating a login/register page with Vue ,
and I have a tab for login and a tab for register .

this is my Template Code :

 <transition v-bind:name="TabEffect">

              Email Address
              <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>

              Password
              <input type="password" name="password" id="password" placeholder="Your Password"/>

            <button>
              {{ LoginTab ? 'Login' : 'Register' }}
            </button>
            or

              Login with Steam

              Email Address
              <input type="text" name="email" id="email" placeholder="Test@TestMail.com" />

              Password
              <input type="password" name="password" id="password" placeholder="Your Password"/>

              Repeat Password
              <input type="password" name="Cpassword" id="Cpassword" placeholder="Repeat Password"/>

            <button>{{ LoginTab ? 'Login' : 'Register' }}</button>
            or

              Login with Steam

        </transition>

code works fine but my problem is code repeating , as you see we have this part of code in both v-if and v-else :

<button>{{ LoginTab ? 'Login' : 'Register' }}</button>
or

  Login with Steam

I want this code to be on the transition , but I don't want to repeat a code twice , I tried to use the code outside of both v-if and v-else , but elements dosen't show at all .

I'm using vue 2.6.11

Update

Transition names are slideLeft and slideRight

SASS Transition Code :

.slideLeft-enter-active,.slideRight-enter-active
  transition: 0.4s ease-in-out

.slideLeft-leave-active,.slideRight-leave-active
  transition: 0.2s ease-in-out

.slideLeft-enter,.slideRight-leave-to
  transform: translateX(-100px)
  position: relative
  opacity: 0

.slideLeft-enter-to,.slideRight-enter-to,.slideLeft-leave ,.slideRight-leave
  transform: translateX(0)
  position: absolute
  top: 0
  width: 100%

.slideLeft-leave-to,.slideRight-enter
  transform: translateX(100px)
  position: relative
  opacity: 0

Body:
One way is to use the v-if in a <template> to handle the conditional part, leaving the common part out:

<transition v-bind:name="TabEffect">
    <div v-for="(logTab, i) of [true, false]" v-if="logTab" :key="i+1" :class="LoginTab ? 'login' : 'register'">
        <template v-if="LoginTab">
            <div>
                <label class="inputText" for="email">Email Address</label>
                <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>
            </div>
            <div>
                <label class="inputText" for="password">Password</label>
                <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
        </template>
        <template v-else>
            <div>
                <label class="inputText" for="email">Email Address</label>
                <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>
            </div>
            <div>
                <label class="inputText" for="password">Password</label>
                <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
            <div>
                <label class="inputText" for="Cpassword">Repeat Password</label>
                <input type="password" name="Cpassword" id="Cpassword" placeholder="Repeat Password"/>
            </div>
        </template>

        <button>{{ LoginTab ? 'Login' : 'Register' }}</button>
        <span class="or">or</span>
        <a href="#!" class="steamLogin">
            <i class="fab fa-steam"></i>
            <span>Login with Steam</span>
        </a>
    </div>
</transition>

Lastly, as the main div's class also depends on the LoginTab variable, we have to put a :class to handle it.

On a side note, only the Repeat password of your code seems to be the varying part. Still, I left the email/password in the conditional to be more faithful to your original question. (And because to change this would be very easy.)


问:
golang what's the different between return []*TreeNode{} and return []*TreeNode{nil}
I'm new to golang and confused by the following,

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func test() []*TreeNode {

    return []*TreeNode{}
}

func test1() []*TreeNode {

    return []*TreeNode{nil}
}
```

I'm trying to write a recursion func on TreeNode, however, if I used the test style to represent the leaf node, I will get an empty TreeNode slice from the caller func.

If I use the test1 to represent the leaf node, then the behaviour is what I want.

I feel that for the test1, it's giving me a point to an empty TreeNode, however, the test code, is giving me a point to nil... I'm not sure if I'm getting this right or not. Can you please point me the correct terms or concepts to dig, it will be great.

In addition, if you can let me know more about the underline logic, it would be great.

Thanks in advance.

答:
This returns an empty slice:

```<code>return []*TreeNode{}
</code>```

This returns a slice containing one element, and that element is a nil pointer:

```<code>return []*TreeNode{nil}
</code>```

None of these give you a TreeNode though. The second one gives you a TreeNode pointer that is nil. How you interpret these depends on the rest of the code, but I doubt either is really what you want, since none can have the val field.

Body:
I'm new to golang and confused by the following,

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}

func test() []*TreeNode {

    return []*TreeNode{}
}

func test1() []*TreeNode {

    return []*TreeNode{nil}
}

I'm trying to write a recursion func on TreeNode, however, if I used the test style to represent the leaf node, I will get an empty TreeNode slice from the caller func.

If I use the test1 to represent the leaf node, then the behaviour is what I want.

I feel that for the test1, it's giving me a point to an empty TreeNode, however, the test code, is giving me a point to nil... I'm not sure if I'm getting this right or not. Can you please point me the correct terms or concepts to dig, it will be great.

In addition, if you can let me know more about the underline logic, it would be great.

Thanks in advance.

Body:
This returns an empty slice:

return []*TreeNode{}

This returns a slice containing one element, and that element is a nil pointer:

return []*TreeNode{nil}

None of these give you a TreeNode though. The second one gives you a TreeNode pointer that is nil. How you interpret these depends on the rest of the code, but I doubt either is really what you want, since none can have the val field.


问:
Why are my points are not drawing where my mouse is in OpenGL?
My points will not draw where my mouse is unless I am exactly half the height of the window. If I am below this half way line, it will draw above the line, if I am above, it will draw below.

Attached is a GIF incase it is not clear: https://gyazo.com/407d679430c70c3235d9e5c43e521347

I would like my coordinate system to start at the bottom left of the screen (as well as draw points where my mouse is). I am developing on a VirtualBox instance of Ubuntu if that helps.

```<code>#include <iostream>
#include <vector>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include "Point.h"

const int w = 640;
const int h = 480;

// Prototypes
void display(void);
void myInit(void);
void myMouse(int button, int state, int x, int y);

// Globals
std::vector<Point> points;

int main(int argc, char** argv){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(w, h);
    glutInitWindowPosition(0, 100);
    glutCreateWindow("My First Attempt");
    glutDisplayFunc(display);
    glutMouseFunc(myMouse);
    myInit();
    glutMainLoop();

}

void display(void){
            glClear(GL_COLOR_BUFFER_BIT);
            glBegin(GL_POINTS);
            // for each point in points, draw a point
            for(Point p : points)
                glVertex2i(p._x,p._y);
            glEnd();

            glFlush();
}
void myMouse(int button, int state, int x, int y){
            if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
                Point p;
                p._x = x;
                p._y = y;
                points.push_back(p);
                std::cout << p._x << "   " << p._y << std::endl;
                glutPostRedisplay();

            }
            if(button == GLUT_LEFT_BUTTON && state == GLUT_UP){

            }
}
void myInit(void){

            glClearColor(1.0,1.0,1.0,0.0);
            glColor3f(0,0,0);
            glPointSize(4.0);
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            gluOrtho2D(0.0f,w, 0,h);

}
</code>```

答:
You either need to Y-flip the mouse coordinates or adjust your projection matrix to match their coordinate system:

```<code>// broken
gluOrtho2D( 0.0f, w, 0, h );

// works
gluOrtho2D( 0.0f, w, h, 0 );
</code>```

All together:

```<code>#include <iostream>
#include <vector>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>

struct Point
{
    int _x, _y;
};

const int w = 640;
const int h = 480;

// Prototypes
void display( void );
void myInit( void );
void myMouse( int button, int state, int x, int y );

// Globals
std::vector<Point> points;

int main( int argc, char** argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_SINGLE );
    glutInitWindowSize( w, h );
    glutInitWindowPosition( 0, 100 );
    glutCreateWindow( "My First Attempt" );
    glutDisplayFunc( display );
    glutMouseFunc( myMouse );
    myInit();
    glutMainLoop();
}

void display( void )
{
    glClear( GL_COLOR_BUFFER_BIT );
    glBegin( GL_POINTS );
    // for each point in points, draw a point
    for( Point p : points )
        glVertex2i( p._x, p._y );
    glEnd();

    glFlush();
}

void myMouse( int button, int state, int x, int y )
{
    if( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN )
    {
        Point p;
        p._x = x;
        p._y = y;
        points.push_back( p );
        std::cout << p._x << "   " << p._y << std::endl;
        glutPostRedisplay();
    }
}

void myInit( void )
{
    glClearColor( 1.0, 1.0, 1.0, 0.0 );
    glColor3f( 0, 0, 0 );
    glPointSize( 4.0 );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( 0.0f, w, h, 0 );
}
</code>```

Body:
My points will not draw where my mouse is unless I am exactly half the height of the window. If I am below this half way line, it will draw above the line, if I am above, it will draw below.

Attached is a GIF incase it is not clear: https://gyazo.com/407d679430c70c3235d9e5c43e521347

I would like my coordinate system to start at the bottom left of the screen (as well as draw points where my mouse is). I am developing on a VirtualBox instance of Ubuntu if that helps.

#include <iostream>
#include <vector>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include "Point.h"

const int w = 640;
const int h = 480;

// Prototypes
void display(void);
void myInit(void);
void myMouse(int button, int state, int x, int y);

// Globals
std::vector<Point> points;

int main(int argc, char** argv){
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(w, h);
    glutInitWindowPosition(0, 100);
    glutCreateWindow("My First Attempt");
    glutDisplayFunc(display);
    glutMouseFunc(myMouse);
    myInit();
    glutMainLoop();

}

void display(void){
            glClear(GL_COLOR_BUFFER_BIT);
            glBegin(GL_POINTS);
            // for each point in points, draw a point
            for(Point p : points)
                glVertex2i(p._x,p._y);
            glEnd();

            glFlush();
}
void myMouse(int button, int state, int x, int y){
            if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
                Point p;
                p._x = x;
                p._y = y;
                points.push_back(p);
                std::cout << p._x << "   " << p._y << std::endl;
                glutPostRedisplay();

            }
            if(button == GLUT_LEFT_BUTTON && state == GLUT_UP){

            }
}
void myInit(void){

            glClearColor(1.0,1.0,1.0,0.0);
            glColor3f(0,0,0);
            glPointSize(4.0);
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            gluOrtho2D(0.0f,w, 0,h);

}

Body:
You either need to Y-flip the mouse coordinates or adjust your projection matrix to match their coordinate system:

// broken
gluOrtho2D( 0.0f, w, 0, h );

// works
gluOrtho2D( 0.0f, w, h, 0 );

All together:

#include <iostream>
#include <vector>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>

struct Point
{
    int _x, _y;
};

const int w = 640;
const int h = 480;

// Prototypes
void display( void );
void myInit( void );
void myMouse( int button, int state, int x, int y );

// Globals
std::vector<Point> points;

int main( int argc, char** argv )
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_SINGLE );
    glutInitWindowSize( w, h );
    glutInitWindowPosition( 0, 100 );
    glutCreateWindow( "My First Attempt" );
    glutDisplayFunc( display );
    glutMouseFunc( myMouse );
    myInit();
    glutMainLoop();
}

void display( void )
{
    glClear( GL_COLOR_BUFFER_BIT );
    glBegin( GL_POINTS );
    // for each point in points, draw a point
    for( Point p : points )
        glVertex2i( p._x, p._y );
    glEnd();

    glFlush();
}

void myMouse( int button, int state, int x, int y )
{
    if( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN )
    {
        Point p;
        p._x = x;
        p._y = y;
        points.push_back( p );
        std::cout << p._x << "   " << p._y << std::endl;
        glutPostRedisplay();
    }
}

void myInit( void )
{
    glClearColor( 1.0, 1.0, 1.0, 0.0 );
    glColor3f( 0, 0, 0 );
    glPointSize( 4.0 );
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    gluOrtho2D( 0.0f, w, h, 0 );
}


问:
Using Multiple Asyncio Queues Effectively
I am currently building a project that requires multiple requests made to various endpoints. I am wrapping these requests in Aiohttp to allow for async.

The problem:

I have three Queues: queue1, queue2, and queue3. Additionally, I have three worker functions (worker1, worker2, worker3) that are associated with their respective Queue. The first queue is populated immediately with a list IDs that is known prior to running. When the request is finished and the data is committed to a database, it passes the ID to queue2. A worker2 will take this ID and request more data. From this data it will begin to generate a list of IDs (different from the IDs in queue1/queue2. worker2 will put the IDs in queue3. Finally worker3 will grab this ID from queue3 and request more data before committing to a database.

The issue arises with the fact queue.join() is a blocking call. Each worker is tied to a separate Queue so the join for queue1 will block until its finished. This is fine, but it also defeats the purpose of using async. Without using join() the program is unable to detect when the Queues are totally empty. The other issue is that there may be silent errors when one of the Queues is empty but there is still data that hasn't been added yet.

The basic code outline is as follows:

queue1 = asyncio.Queue()
queue2 = asyncio.Queue()
queue3 = asyncio.Queue()

async with aiohttp.ClientSession() as session:
    for i in range(3):
        tasks.append(asyncio.create_task(worker1(queue1)))

    for i in range(3):
        tasks.append(asyncio.create_task(worker2(queue2)))

    for i in range(10):
        tasks.append(asyncio.create_task(worker3(queue3)))

    for i in IDs:
       queue1.put_nowait(i)

    await asyncio.gather(*tasks)
```

The worker functions sit in an infinite loop waiting for items to enter the queue.

When the data has all been processed there will be no exit and the program will hang.

Is there a way to effectively manage the workers and end properly?

答:
As nicely explained in this answer, Queue.join serves to inform the producer when all the work injected into the queue got completed. Since your first queue doesn't know when a particular item is done (it's multiplied and distributed to other queues), join is not the right tool for you.

Judging from your code, it seems that your workers need to run for only as long as it takes to process the queue's initial items. If that is the case, then you can use a shutdown sentinel to signal the workers to exit. For example:

async with aiohttp.ClientSession() as session:

    # ... create tasks as above ...

    for i in IDs:
       queue1.put_nowait(i)
    queue1.put_nowait(None)  # no more work

    await asyncio.gather(*tasks)
```
<p>This is like your original code, but with an explicit shutdown request. Workers must detect the sentinel and react accordingly: propagate it to the next queue/worker and exit. For example, in <code>worker1</code>:</p>
<pre class="lang-py prettyprint-override"><code>while True:
    item = queue1.get()
    if item is None:
        # done with processing, propagate sentinel to worker2 and exit
        await queue2.put(None)
        break
    # ... process item as usual ...
</code>```

Doing the same in other two workers (except for worker3 which won't propagate because there's no next queue) will result in all three tasks completing once the work is done. Since queues are FIFO, the workers can safely exit after encountering the sentinel, knowing that no items have been dropped. The explicit shutdown also distinguishes a shut-down queue from one that happens to be empty, thus preventing workers from exiting prematurely due to a temporarily empty queue.

Up to Python 3.7, this technique was actually demonstrated in the documentation of Queue, but that example somewhat confusingly shows both the use of Queue.join and the use of a shutdown sentinel. The two are separate and can be used independently of one another. (And it might also make sense to use them together, e.g. to use Queue.join to wait for a "milestone", and then put other stuff in the queue, while reserving the sentinel for stopping the workers.)

Body:
I am currently building a project that requires multiple requests made to various endpoints. I am wrapping these requests in Aiohttp to allow for async.

The problem:

I have three Queues: queue1, queue2, and queue3. Additionally, I have three worker functions (worker1, worker2, worker3) that are associated with their respective Queue. The first queue is populated immediately with a list IDs that is known prior to running. When the request is finished and the data is committed to a database, it passes the ID to queue2. A worker2 will take this ID and request more data. From this data it will begin to generate a list of IDs (different from the IDs in queue1/queue2. worker2 will put the IDs in queue3. Finally worker3 will grab this ID from queue3 and request more data before committing to a database.

The issue arises with the fact queue.join() is a blocking call. Each worker is tied to a separate Queue so the join for queue1 will block until its finished. This is fine, but it also defeats the purpose of using async. Without using join() the program is unable to detect when the Queues are totally empty. The other issue is that there may be silent errors when one of the Queues is empty but there is still data that hasn't been added yet.

The basic code outline is as follows:

queue1 = asyncio.Queue()
queue2 = asyncio.Queue()
queue3 = asyncio.Queue()

async with aiohttp.ClientSession() as session:
    for i in range(3):
        tasks.append(asyncio.create_task(worker1(queue1)))

    for i in range(3):
        tasks.append(asyncio.create_task(worker2(queue2)))

    for i in range(10):
        tasks.append(asyncio.create_task(worker3(queue3)))

    for i in IDs:
       queue1.put_nowait(i)

    await asyncio.gather(*tasks)

The worker functions sit in an infinite loop waiting for items to enter the queue.

When the data has all been processed there will be no exit and the program will hang.

Is there a way to effectively manage the workers and end properly?

Body:
As nicely explained in this answer, Queue.join serves to inform the producer when all the work injected into the queue got completed. Since your first queue doesn't know when a particular item is done (it's multiplied and distributed to other queues), join is not the right tool for you.

Judging from your code, it seems that your workers need to run for only as long as it takes to process the queue's initial items. If that is the case, then you can use a shutdown sentinel to signal the workers to exit. For example:

async with aiohttp.ClientSession() as session:

    # ... create tasks as above ...

    for i in IDs:
       queue1.put_nowait(i)
    queue1.put_nowait(None)  # no more work

    await asyncio.gather(*tasks)

This is like your original code, but with an explicit shutdown request. Workers must detect the sentinel and react accordingly: propagate it to the next queue/worker and exit. For example, in worker1:

while True:
    item = queue1.get()
    if item is None:
        # done with processing, propagate sentinel to worker2 and exit
        await queue2.put(None)
        break
    # ... process item as usual ...

Doing the same in other two workers (except for worker3 which won't propagate because there's no next queue) will result in all three tasks completing once the work is done. Since queues are FIFO, the workers can safely exit after encountering the sentinel, knowing that no items have been dropped. The explicit shutdown also distinguishes a shut-down queue from one that happens to be empty, thus preventing workers from exiting prematurely due to a temporarily empty queue.

Up to Python 3.7, this technique was actually demonstrated in the documentation of Queue, but that example somewhat confusingly shows both the use of Queue.join and the use of a shutdown sentinel. The two are separate and can be used independently of one another. (And it might also make sense to use them together, e.g. to use Queue.join to wait for a "milestone", and then put other stuff in the queue, while reserving the sentinel for stopping the workers.)


问:
Retrieve saved image from app and email
I am succesfully saving an image to my app after the user takes a picture. What I want to do later is, when the user comes back to the app I want them to be able to email the photo as an attachment. I am not having any luck getting the data from the app converted to an image so I can add as an attachment. Can someone point me in the right direction please. Here is where I save the image after they have taken a picture.

```<code>- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    //here is the image returned

        app.aImage2 = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImagePNGRepresentation( app.aImage2 );
        NSString * savedImageName = [NSString stringWithFormat:@"r%@aImage2.png",app.reportNumber];
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSString * dataFilePath;
        dataFilePath = [documentsDirectory stringByAppendingPathComponent:savedImageName];
        [imageData writeToFile:dataFilePath atomically:YES];

    [self dismissModalViewControllerAnimated:YES];

}
</code>```

And here is where I need to attach it.

```<code>//this is inside my method that creates an email composer view
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self; // <- very important step if you want feedbacks on what the user did with your email sheet

    //how would i attach the saved image from above?
</code>```

答:
This includes code that Mike mentions here:

How to add a UIImage in MailComposer Sheet of MFMailComposeViewController

Also, other portions are lifted from Sagar Kothari's answer here:

Sending out HTML email with IMG tag from an iPhone App using MFMailComposeViewController class

```<code>- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // Dismiss image picker modal.
    [picker dismissModalViewControllerAnimated:YES];

    if ([MFMailComposeViewController canSendMail]) {
        // Create a string with HTML formatting for the email body.
        NSMutableString *emailBody = [[NSMutableString alloc] initWithString:@"<html><body>"];

        // Add some text to it.
        [emailBody appendString:@"<p>Body text goes here.</p>"];

        // You could repeat here with more text or images, otherwise
        // close the HTML formatting.
        [emailBody appendString:@"</body></html>"];
        NSLog(@"%@", emailBody);

        // Create the mail composer window.
        MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;

        // Image to insert.
        UIImage *emailImage = [info objectForKey:UIImagePickerControllerOriginalImage];

        if (emailImage != nil) {
            NSData *data = UIImagePNGRepresentation(emailImage);
            [emailDialog addAttachmentData:data mimeType:@"image/png" fileName:@"filename_goes_here.png"];
        }

        [emailDialog setSubject:@"Subject goes here."];
        [emailDialog setMessageBody:emailBody isHTML:YES];

        [self presentModalViewController:emailDialog animated:YES];
        [emailDialog release];
        [emailBody release];
    }
}
</code>```

Title: Retrieve saved image from app and email

Body:
I am succesfully saving an image to my app after the user takes a picture. What I want to do later is, when the user comes back to the app I want them to be able to email the photo as an attachment. I am not having any luck getting the data from the app converted to an image so I can add as an attachment. Can someone point me in the right direction please. Here is where I save the image after they have taken a picture.

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    //here is the image returned

        app.aImage2 = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImagePNGRepresentation( app.aImage2 );
        NSString * savedImageName = [NSString stringWithFormat:@"r%@aImage2.png",app.reportNumber];
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * documentsDirectory = [paths objectAtIndex:0];
        NSString * dataFilePath;
        dataFilePath = [documentsDirectory stringByAppendingPathComponent:savedImageName];
        [imageData writeToFile:dataFilePath atomically:YES];

    [self dismissModalViewControllerAnimated:YES];

}

And here is where I need to attach it.

//this is inside my method that creates an email composer view
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self; // <- very important step if you want feedbacks on what the user did with your email sheet

    //how would i attach the saved image from above?

Body:
This includes code that Mike mentions here:

How to add a UIImage in MailComposer Sheet of MFMailComposeViewController

Also, other portions are lifted from Sagar Kothari's answer here:

Sending out HTML email with IMG tag from an iPhone App using MFMailComposeViewController class

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // Dismiss image picker modal.
    [picker dismissModalViewControllerAnimated:YES];

    if ([MFMailComposeViewController canSendMail]) {
        // Create a string with HTML formatting for the email body.
        NSMutableString *emailBody = [[NSMutableString alloc] initWithString:@"<html><body>"];

        // Add some text to it.
        [emailBody appendString:@"<p>Body text goes here.</p>"];

        // You could repeat here with more text or images, otherwise
        // close the HTML formatting.
        [emailBody appendString:@"</body></html>"];
        NSLog(@"%@", emailBody);

        // Create the mail composer window.
        MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;

        // Image to insert.
        UIImage *emailImage = [info objectForKey:UIImagePickerControllerOriginalImage];

        if (emailImage != nil) {
            NSData *data = UIImagePNGRepresentation(emailImage);
            [emailDialog addAttachmentData:data mimeType:@"image/png" fileName:@"filename_goes_here.png"];
        }

        [emailDialog setSubject:@"Subject goes here."];
        [emailDialog setMessageBody:emailBody isHTML:YES];

        [self presentModalViewController:emailDialog animated:YES];
        [emailDialog release];
        [emailBody release];
    }
}