问:
Copying from one stream to another?
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

```<code>BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();
</code>```

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.

答:
This is a handy function. And yes, the buffer size matters. Increasing it might give you better performance on large files.</p>

```<code>public static void WriteTo(Stream sourceStream, Stream targetStream)
{
       byte[] buffer = new byte[0x10000];
       int n;
       while ((n = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
           targetStream.Write(buffer, 0, n);
}
</code>```

Title: Copying from one stream to another?

Body:
For work, the specification on my project is to use .Net 2.0 so I don't get the handy CopyTo function brought about later on.

I need to copy the response stream from an HttpWebResponse to another stream (most likely a MemoryStream, but it could be any subclass of Stream). My normal tactic has been something along the lines of:

BufferedStream bufferedresponse = new BufferedStream(HttpResponse.GetResponseStream());
int count = 0;
byte[] buffer = new byte[1024];
do {
    count = bufferedresponse.Read(buffer, 0, buffer.Length);
    target.Write(buffer, 0, count);
} while (count > 0);
bufferedresponse.Close();

Are there more efficient ways to do this? Does the size of the buffer really matter? What is the best way to copy from one stream to another in .Net 2.0?

P.S. This is for downloading large, 200+ MB GIS tif images. Of course reliability is paramount.

Body:
This is a handy function. And yes, the buffer size matters. Increasing it might give you better performance on large files.

public static void WriteTo(Stream sourceStream, Stream targetStream)
{
       byte[] buffer = new byte[0x10000];
       int n;
       while ((n = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
           targetStream.Write(buffer, 0, n);
}


来源: stackexchange

问:
Using the lag function with two different columns R
I have data such as this.

```<code>data.input <-read_table2("user.id   problem.id  first.correct   cwa_prob    prob.seq
540995  PRABNBZQ    0   1   problem.id.problem.1
540995  PRABNBZ2    1   0   problem.id.problem.2
540995  PRABNBZK    0   1   problem.id.problem.3
540995  PRABNB2B    0   1   problem.id.problem.4
540995  PRABNBWE    0   1   problem.id.problem.5
565662  PRABNB2B    1   0   problem.id.problem.1
565662  PRABNBZQ    1   1   problem.id.problem.2
565662  PRABNBZ9    1   0   problem.id.problem.3
565662  PRABNBZV    1   0   problem.id.problem.4
565662  PRABNBWG    1   0   problem.id.problem.5
")
</code>```

I am trying to use the lag function to compare the occurrence of a flag in two separate columns. I want to see how a person fairs sequentially from one problem to the next. Specifically, if cwa_prob is 1 for problem.id.problem.1 (user 540995), is it the case that first.correct==1 in problem.id.problem.2 (user 540995).

I tried something like this, but it throws me an error.

```<code>input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1),1,0))
</code>```

I would like my output to look something like this:

```<code>data.output <-read_table2("user.id  problem.id  first.correct   cwa_prob    prob.seq    post.cwa.correct
540995  PRABNBZQ    0   1   problem.id.problem.1    NA
540995  PRABNBZ2    1   0   problem.id.problem.2    1
540995  PRABNBZK    0   1   problem.id.problem.3    NA
540995  PRABNB2B    0   1   problem.id.problem.4    0
540995  PRABNBWE    0   1   problem.id.problem.5    0
565662  PRABNB2B    1   0   problem.id.problem.1    1
565662  PRABNBZQ    1   1   problem.id.problem.2    NA
565662  PRABNBZ9    1   0   problem.id.problem.3    1
565662  PRABNBZV    1   0   problem.id.problem.4    NA
565662  PRABNBWG    1   0   problem.id.problem.5    NA
")
</code>```

Maybe the lag function isn't the best function for this? Any help is appreciated!

答:
Based on your description I think this is what you want :

```<code>library(dplyr)

data.input %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct = as.integer(first.correct == 1 & lag(cwa_prob) == 1))
</code>```

This will give a value of 1 when the current row has first.correct = 1 and the previous row has cwa_prob = 1 .

Note that you don't need ifelse(condition, 1, 0) since you can convert TRUE/FALSE values to 1/0 by converting them to integer. Also in your attempt you have lag(first.correct==1) which is different from lag(first.correct) ==1.

ContentLicense: CC BY-SA 4.0

Body:
I have data such as this.

data.input <-read_table2("user.id   problem.id  first.correct   cwa_prob    prob.seq
540995  PRABNBZQ    0   1   problem.id.problem.1
540995  PRABNBZ2    1   0   problem.id.problem.2
540995  PRABNBZK    0   1   problem.id.problem.3
540995  PRABNB2B    0   1   problem.id.problem.4
540995  PRABNBWE    0   1   problem.id.problem.5
565662  PRABNB2B    1   0   problem.id.problem.1
565662  PRABNBZQ    1   1   problem.id.problem.2
565662  PRABNBZ9    1   0   problem.id.problem.3
565662  PRABNBZV    1   0   problem.id.problem.4
565662  PRABNBWG    1   0   problem.id.problem.5
")

I am trying to use the lag function to compare the occurrence of a flag in two separate columns. I want to see how a person fairs sequentially from one problem to the next. Specifically, if cwa_prob is 1 for problem.id.problem.1 (user 540995), is it the case that first.correct==1 in problem.id.problem.2 (user 540995).

I tried something like this, but it throws me an error.

input.data %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct=ifelse(cwa_prob==1 & lag(first.correct==1),1,0))

I would like my output to look something like this:

data.output <-read_table2("user.id  problem.id  first.correct   cwa_prob    prob.seq    post.cwa.correct
540995  PRABNBZQ    0   1   problem.id.problem.1    NA
540995  PRABNBZ2    1   0   problem.id.problem.2    1
540995  PRABNBZK    0   1   problem.id.problem.3    NA
540995  PRABNB2B    0   1   problem.id.problem.4    0
540995  PRABNBWE    0   1   problem.id.problem.5    0
565662  PRABNB2B    1   0   problem.id.problem.1    1
565662  PRABNBZQ    1   1   problem.id.problem.2    NA
565662  PRABNBZ9    1   0   problem.id.problem.3    1
565662  PRABNBZV    1   0   problem.id.problem.4    NA
565662  PRABNBWG    1   0   problem.id.problem.5    NA
")

Maybe the lag function isn't the best function for this? Any help is appreciated!

Body:
Based on your description I think this is what you want :

library(dplyr)

data.input %>%
  group_by(user.id) %>%
  mutate(post.cwa.correct = as.integer(first.correct == 1 & lag(cwa_prob) == 1))

This will give a value of 1 when the current row has first.correct = 1 and the previous row has cwa_prob = 1 .

Note that you don't need ifelse(condition, 1, 0) since you can convert TRUE/FALSE values to 1/0 by converting them to integer. Also in your attempt you have lag(first.correct==1) which is different from lag(first.correct) ==1.


问:
Picker result is always nil
Here is my picker controller coordinator. On my device, I can select a video but when it breaks in the debugger, url is always nil. Do I need to ask for permission?

```<code>class ImagePickerCoordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @Binding var isShown: Bool
    @Binding var url: URL?

    init(isShown: Binding<Bool>, url: Binding<URL?>) {

        _isShown = isShown
        _url = url
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        let url = info[UIImagePickerController.InfoKey.mediaURL]

        isShown = false
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        isShown = false
    }
}
</code>```

EDIT:

The error is that the url must be cast using as! URL. No cast or as? URL doesn't work. Why is this? The original value is Any?.

答:
Here it is</p>

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    if let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
         self.url = url
    }

    isShown = false
}
</code>```

Title: Picker result is always nil

Body:
Here is my picker controller coordinator. On my device, I can select a video but when it breaks in the debugger, url is always nil. Do I need to ask for permission?

class ImagePickerCoordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @Binding var isShown: Bool
    @Binding var url: URL?

    init(isShown: Binding<Bool>, url: Binding<URL?>) {

        _isShown = isShown
        _url = url
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        let url = info[UIImagePickerController.InfoKey.mediaURL]

        isShown = false
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        isShown = false
    }
}

EDIT:

The error is that the url must be cast using as! URL. No cast or as? URL doesn't work. Why is this? The original value is Any?.

Body:
Here it is

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    if let url = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
         self.url = url
    }

    isShown = false
}


问:
C++ Restrict or make user input invisible (std::cin)
I have a function that waits until a user presses enter to continue:

```<code>std::cout << "Press ENTER to continue..." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
std::cin.clear();
</code>```

It works fine, but it allows the user to type anything on the console line before pressing enter. It's not a big deal but it looks kind of ugly. Was just wondering if there was a way to make the input invisible or just ignore any keystroke except enter? Needs to work cross-platform so some of the solutions I've found won't work.

Thanks

答:
The best option would be just to clear the console then reprint everything again.

```<code>std::cout << "Press ENTER to continue..." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
std::cin.clear();

clearScreenFunc();
displayOldInformation();
displayNewInformation();

</code>```

Also about clearing the screen, you could use a combination of output characters to clear the screen, or the platform-specific options, both work and look clean if you do it right. E.G. :

```<code>void clearScreenFunc()
{
#if defined _WIN32
    system("cls");
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
    system("clear");
#elif defined (__APPLE__)
    system("clear");
#endif
}
</code>```

Body:
I have a function that waits until a user presses enter to continue:

std::cout << "Press ENTER to continue..." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
std::cin.clear();

It works fine, but it allows the user to type anything on the console line before pressing enter. It's not a big deal but it looks kind of ugly. Was just wondering if there was a way to make the input invisible or just ignore any keystroke except enter? Needs to work cross-platform so some of the solutions I've found won't work.

Thanks

Body:
The best option would be just to clear the console then reprint everything again.

std::cout << "Press ENTER to continue..." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
std::cin.clear();

clearScreenFunc();
displayOldInformation();
displayNewInformation();

Also about clearing the screen, you could use a combination of output characters to clear the screen, or the platform-specific options, both work and look clean if you do it right. E.G. :

void clearScreenFunc()
{
#if defined _WIN32
    system("cls");
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
    system("clear");
#elif defined (__APPLE__)
    system("clear");
#endif
}


问:
How to get iOS's unique identifier from app?
I have checked online that getting IMEI must use private methods and thus violate the agreement and might be rejected. What I need is not the IMEI number, but any unique identifier of the phone, it can be meaning less or do</p>

答:
```<code>[[UIDevice currentDevice] uniqueIdentifier]
</code>```

ContentLicense: CC BY-SA 3.0


问:
ICS will adjust date when add to calendar base on timezone
I've downloaded a PHP script that allow me to generate downloadable ICS for a scheduled webinar. Date & time is set to WP ACF post. Also, WordPress timezone was set to America/Los_Angeles. But my timezone is based in Manila, PH.

Here's the code.

```<code>// ACF Date
$wdate = get_sub_field('date'); // Tuesday, June 16, 2020
$stime = get_sub_field('start_time'); // 11:00 am
$etime = get_sub_field('end_time'); // 11:30 am

// Prepare Date using date_i18n()
// Starting DateTime
$st_gmt = $wdate.' '.$stime;
$st = get_date_from_gmt($st_gmt, 'Y-m-d H:i:s');
$date_start = date_i18n(get_option('date_format').' '.get_option('time_format'), strtotime($st));
// Output: June 16, 2020 11:00 AM

// Ending DateTime
$et_gmt = $wdate.' '.$etime;
$et = get_date_from_gmt($et_gmt, 'Y-m-d H:i:s');
$date_end = date_i18n(get_option('date_format').' '.get_option('time_format'), strtotime($et));
// Output: June 16, 2020 11:30 AM
</code>```

Whenever I test downloading the .ics calendar file, which it should be June 17, 2020 2:00 AM & June 17, 2020 2:30 AM but the output is always set to June 16, 2020 7:00 PM & June 16, 2020 7:30 PM since I am based from Manila, PH while the event was set to Los Angeles.

Here's the output from actual ICS file.

```<code>BEGIN:VCALENDAR
VERSION:2.0
X-WR-TIMEZONE:America/Los_Angeles
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:America/Los_Angeles
END:VTIMEZONE
BEGIN:VEVENT
LOCATION:Webinar Zoom
DESCRIPTION:This is my description
DTSTART:20200616T110000Z
DTEND:20200616T113000Z
SUMMARY:This is my summary
URL;VALUE=URI:
DTSTAMP:20200603T051015Z
UID:5ed6c0375fbf6
END:VEVENT
END:VCALENDAR
</code>```

Question: How can I output the ics file to match users timezone when they download the file and add to their calendar?

答:
I assume the question that you have not yet explicitly asked is how the times relate.

Note first that an ics VTIMEZONE is intended for a timezone definition ie when the actual daylight saving changes are, it is not used to say that the event is in LA time.  IT should actually contain a series of daylight saving dates IF DST is relevant in that timezone. See https://icalendar.org/iCalendar-RFC-5545/3-6-5-time-zone-component.html

A VTIMEZONE says nothing about the VEVENTS start and end times.

In this file the event DTSTART is defined in UTC time (see the Z?) of 11 am
This is the equivalent of LA at 4am and Manila at 7pm.
See Form 2 of DATETIME:
https://icalendar.org/iCalendar-RFC-5545/3-3-5-date-time.html

and here for time differences
https://www.timeanddate.com/worldclock/meetingdetails.html?year=2020&month=6&day=16&hour=11&min=0&sec=0&p1=137&p2=145

How the times appear in an application depend then on the timezone of the user and application.  The application should convert the ics event time to the users timezone.

Body:
I've downloaded a PHP script that allow me to generate downloadable ICS for a scheduled webinar. Date & time is set to WP ACF post. Also, WordPress timezone was set to America/Los_Angeles. But my timezone is based in Manila, PH.

Here's the code.

// ACF Date
$wdate = get_sub_field('date'); // Tuesday, June 16, 2020
$stime = get_sub_field('start_time'); // 11:00 am
$etime = get_sub_field('end_time'); // 11:30 am

// Prepare Date using date_i18n()
// Starting DateTime
$st_gmt = $wdate.' '.$stime;
$st = get_date_from_gmt($st_gmt, 'Y-m-d H:i:s');
$date_start = date_i18n(get_option('date_format').' '.get_option('time_format'), strtotime($st));
// Output: June 16, 2020 11:00 AM

// Ending DateTime
$et_gmt = $wdate.' '.$etime;
$et = get_date_from_gmt($et_gmt, 'Y-m-d H:i:s');
$date_end = date_i18n(get_option('date_format').' '.get_option('time_format'), strtotime($et));
// Output: June 16, 2020 11:30 AM

Whenever I test downloading the .ics calendar file, which it should be June 17, 2020 2:00 AM & June 17, 2020 2:30 AM but the output is always set to June 16, 2020 7:00 PM & June 16, 2020 7:30 PM since I am based from Manila, PH while the event was set to Los Angeles.

Here's the output from actual ICS file.

BEGIN:VCALENDAR
VERSION:2.0
X-WR-TIMEZONE:America/Los_Angeles
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:America/Los_Angeles
END:VTIMEZONE
BEGIN:VEVENT
LOCATION:Webinar Zoom
DESCRIPTION:This is my description
DTSTART:20200616T110000Z
DTEND:20200616T113000Z
SUMMARY:This is my summary
URL;VALUE=URI:
DTSTAMP:20200603T051015Z
UID:5ed6c0375fbf6
END:VEVENT
END:VCALENDAR

Question: How can I output the ics file to match users timezone when they download the file and add to their calendar?


问:
How to change specific lines in a text file and enforce this change when writing output file
I'm having an issue with implementing a change on specific files in a text file. I have looped over the lines and identified the ones starting with a specific character (N2).

I'm trying to wrap a paragraph so it only allows for 100 characters per line for the abstract of this output from an online source, numerous abstracts are contained in the file all starting with N2 prefixed to the string.

The information appears as separate lines in the text file, ForEoin.txt:

```<code><!-- language: lang-none -->
TY  - JOUR
ID  - 31513460
T1  - Systematic Review: Clinical Metabolomics to Forecast Outcomes in Liver Transplantation Surgery.
A1  - Attard, Joseph A
A1  - Dunn, Warwick B
A1  - Mergental, Hynek
A1  - Mirza, Darius F
A1  - Afford, Simon C
A1  - Perera, M Thamara P R
Y1  - 2019//
N2  - Liver transplantation is an effective intervention for end-stage liver disease, fulminant hepatic failure, and early hepatocellular carcinoma. Yet, there is marked patient-to-patient variation in liver transplantation outcomes. This calls for novel diagnostics to enable rational deployment of donor livers. Metabolomics is a postgenomic high-throughput systems biology approach to diagnostic innovation in clinical medicine. We report here an original systematic review of the metabolomic studies that have identified putative biomarkers in the context of liver transplantation. Eighteen studies met the inclusion criteria that involved sampling of blood (n = 4), dialysate fluid (n = 4), bile (n = 5), and liver tissue (n = 5). Metabolites of amino acid and nitrogen metabolism, anaerobic glycolysis, lipid breakdown products, and bile acid metabolism were significantly different in transplanted livers with and without graft dysfunction. However, criteria for defining the graft dysfunction varied across studies. This systematic review demonstrates that metabolomics can be deployed in identification of metabolic indicators of graft dysfunction with a view to implicated molecular mechanisms. We conclude the article with a horizon scanning of metabolomics technology in liver transplantation and its future prospects and challenges in research and clinical practice.
KW  - *Biomarkers
KW  - Genotype
</code>```

So far I have iterated over the lines of the file and called upon the textwrap module to wrap this for me but I cant get my head around writing over the existing lines with this new wrapped lines in the output file.

```<code>#!/usr/bin/env python

import textwrap

filename_org = 'ForEoin.txt'
filename_new = 'Eoin_Shortline_v2'

with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)

                wf.write(new_line)
</code>```

答:
Do you just need an else statement, to write the line un-altered if it doesn't start with N2?

```<code>with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)
                wf.write(new_line)
            else:
                wf.write(line)
</code>```

Body:
I'm having an issue with implementing a change on specific files in a text file. I have looped over the lines and identified the ones starting with a specific character (N2).

I'm trying to wrap a paragraph so it only allows for 100 characters per line for the abstract of this output from an online source, numerous abstracts are contained in the file all starting with N2 prefixed to the string.

The information appears as separate lines in the text file, ForEoin.txt:

TY  - JOUR
ID  - 31513460
T1  - Systematic Review: Clinical Metabolomics to Forecast Outcomes in Liver Transplantation Surgery.
A1  - Attard, Joseph A
A1  - Dunn, Warwick B
A1  - Mergental, Hynek
A1  - Mirza, Darius F
A1  - Afford, Simon C
A1  - Perera, M Thamara P R
Y1  - 2019//
N2  - Liver transplantation is an effective intervention for end-stage liver disease, fulminant hepatic failure, and early hepatocellular carcinoma. Yet, there is marked patient-to-patient variation in liver transplantation outcomes. This calls for novel diagnostics to enable rational deployment of donor livers. Metabolomics is a postgenomic high-throughput systems biology approach to diagnostic innovation in clinical medicine. We report here an original systematic review of the metabolomic studies that have identified putative biomarkers in the context of liver transplantation. Eighteen studies met the inclusion criteria that involved sampling of blood (n = 4), dialysate fluid (n = 4), bile (n = 5), and liver tissue (n = 5). Metabolites of amino acid and nitrogen metabolism, anaerobic glycolysis, lipid breakdown products, and bile acid metabolism were significantly different in transplanted livers with and without graft dysfunction. However, criteria for defining the graft dysfunction varied across studies. This systematic review demonstrates that metabolomics can be deployed in identification of metabolic indicators of graft dysfunction with a view to implicated molecular mechanisms. We conclude the article with a horizon scanning of metabolomics technology in liver transplantation and its future prospects and challenges in research and clinical practice.
KW  - *Biomarkers
KW  - Genotype

So far I have iterated over the lines of the file and called upon the textwrap module to wrap this for me but I cant get my head around writing over the existing lines with this new wrapped lines in the output file.

#!/usr/bin/env python

import textwrap

filename_org = 'ForEoin.txt'
filename_new = 'Eoin_Shortline_v2'

with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)

                wf.write(new_line)

Body:
Do you just need an else statement, to write the line un-altered if it doesn't start with N2?

with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)
                wf.write(new_line)
            else:
                wf.write(line)


问:
How to Calling C# Base Class Default Construtor From Derived Class
Hi i am novice to c# programming and try to learn it form a website  which is called tutlane.com . today i am going to practice this code but it shown error , i want to access base class default constructor from the derived class but it shown an error . so please help me to find out the error in the following code:</p>

```<code>using System;

namespace Tutlane
{
    // Base Class
    public class BaseClass
    {
        // Variable
        public string name = "ZAHID";
        public string location = "BD";
        public int age = 33;
        public string SomeText = "This is a Base Class Field OR Variable";

        //Base class Default Constructor
        public BaseClass()
        {
            Console.WriteLine("Base Class Default Constructor Called.");
        }
        //Base Class Parmeterized Construtor
        public BaseClass(string a, string b)
        {
            Console.WriteLine("Name: {0}", a);
            Console.WriteLine("Location: {0}", b);
        }

        //Method
        public virtual void GetInfo()
        {
            Console.WriteLine("I am a Base Class Method");
            Console.WriteLine("Name: {0}", name);
            Console.WriteLine("Location: {0}", location);
        }
    }

    // Derived Class
    public class DerivedClass : BaseClass
    {
        //Calling Base Class Default Construtor
        public DerivedClass : base()
          {
          }
    // Calling Base Class Parameterized Construtor
    public DerivedClass(string x, string y) : base(x, y)
    {
    }

    //Method
    public override void GetInfo()
    {
        base.GetInfo();
        Console.WriteLine("I am a Derived Class Method");
        //Accessing Base Class Properties
        Console.WriteLine("Accessing Base Class Field: {0}", base.SomeText);
    }
}

//Main Entry Point Class
class Program
{
    static void Main(string[] args)
    {
        DerivedClass drbd_obj = new DerivedClass();
        DerivedClass drbd_obj1 = new DerivedClass("SHAKIL", "DHK");
        // drbd_obj.GetInfo();
        // BaseClass b = new BaseClass();
        //b.GetInfo();
    }
}
}
</code>```

答:
You're missing the parentheses on the derived class' default constructor:</p>

```<code>public DerivedClass() : base()
</code>```

Body:
Hi i am novice to c# programming and try to learn it form a website  which is called tutlane.com . today i am going to practice this code but it shown error , i want to access base class default constructor from the derived class but it shown an error . so please help me to find out the error in the following code:

using System;

namespace Tutlane
{
    // Base Class
    public class BaseClass
    {
        // Variable
        public string name = "ZAHID";
        public string location = "BD";
        public int age = 33;
        public string SomeText = "This is a Base Class Field OR Variable";

        //Base class Default Constructor
        public BaseClass()
        {
            Console.WriteLine("Base Class Default Constructor Called.");
        }
        //Base Class Parmeterized Construtor
        public BaseClass(string a, string b)
        {
            Console.WriteLine("Name: {0}", a);
            Console.WriteLine("Location: {0}", b);
        }

        //Method
        public virtual void GetInfo()
        {
            Console.WriteLine("I am a Base Class Method");
            Console.WriteLine("Name: {0}", name);
            Console.WriteLine("Location: {0}", location);
        }
    }

    // Derived Class
    public class DerivedClass : BaseClass
    {
        //Calling Base Class Default Construtor
        public DerivedClass : base()
          {
          }
    // Calling Base Class Parameterized Construtor
    public DerivedClass(string x, string y) : base(x, y)
    {
    }

    //Method
    public override void GetInfo()
    {
        base.GetInfo();
        Console.WriteLine("I am a Derived Class Method");
        //Accessing Base Class Properties
        Console.WriteLine("Accessing Base Class Field: {0}", base.SomeText);
    }
}

//Main Entry Point Class
class Program
{
    static void Main(string[] args)
    {
        DerivedClass drbd_obj = new DerivedClass();
        DerivedClass drbd_obj1 = new DerivedClass("SHAKIL", "DHK");
        // drbd_obj.GetInfo();
        // BaseClass b = new BaseClass();
        //b.GetInfo();
    }
}
}

Body:
You're missing the parentheses on the derived class' default constructor:

public DerivedClass() : base()


问:
JFrame resizable height ONLY
JFrame.setResizable(true) lets the user resize both the width and height of a window. Does a method exist which allows the user to ONLY resize the height?

Thanks.

Edit: The solutions below do NOT seem to work. On a 360x600 JFrame,

```<code>setResizable(true);
pack();
setMaximizedBounds(new java.awt.Rectangle(0, 0, 360, 1200));
setMaximumSize(new java.awt.Dimension(360, 1200));
setMinimumSize(new java.awt.Dimension(360, 600));
setPreferredSize(new java.awt.Dimension(360, 600));
setVisible(true);
</code>```

Still allows fully stretching the width of the JFrame, and setting setResizable(false) allows nothing to be stretched.

答:
The code below does the job right.</p>

```<code>addComponentListener(new ComponentAdapter() {

    @Override
    public void componentResized(ComponentEvent e) {
        setSize(new Dimension(preferredWidth, getHeight()));
        super.componentResized(e);
    }

});
</code>```

ContentLicense: CC BY-SA 2.5

Title: JFrame resizable height ONLY

Body:
JFrame.setResizable(true) lets the user resize both the width and height of a window. Does a method exist which allows the user to ONLY resize the height?

Thanks.

Edit: The solutions below do NOT seem to work. On a 360x600 JFrame,

setResizable(true);
pack();
setMaximizedBounds(new java.awt.Rectangle(0, 0, 360, 1200));
setMaximumSize(new java.awt.Dimension(360, 1200));
setMinimumSize(new java.awt.Dimension(360, 600));
setPreferredSize(new java.awt.Dimension(360, 600));
setVisible(true);

Still allows fully stretching the width of the JFrame, and setting setResizable(false) allows nothing to be stretched.

Body:
The code below does the job right.

addComponentListener(new ComponentAdapter() {

    @Override
    public void componentResized(ComponentEvent e) {
        setSize(new Dimension(preferredWidth, getHeight()));
        super.componentResized(e);
    }

});


问:
Unable to download a .png file from shiny
I'm trying to create a download button for my histogram plot.  I have the download button visible, but can't seem to get it to download correctly.  It always downloads a .htm file and not the .png file.  I"m using the ggsave command in my server.R.  I tried using the more traditional method, but that didn't seem to work either.</p>

```<code>library(shiny)
library(plyr)
library(ggplot2)

shinyUI(fluidPage(
  headerPanel(title = "Test"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("input.a", "A", min = 0, max = 100, value = 50),
      sliderInput("input.b", "B", min = 0, max = 100, value = 50),
      sliderInput("input.c", "C", min = 0, max = 100, value = 50)
    ),

    mainPanel(

      tabsetPanel( type = "tabs", #Open panel
                   tabPanel("Distributions",plotOutput("hist.plot")),
                   downloadButton('downloadhist', 'Download Plot'))

) # close mainPanel
) # close sidebarLayout
) # close fluidPage
) # close shinyUI

shinyServer(function(input,output){ # open shiny server

    #output$hist.plot = renderPlot({ # open renderPlot
    make.hist.plot = reactive({

    a = runif(1000,1,(input$input.a))
    b = runif(1000,1,(input$input.b))
    c = runif(1000,1,(input$input.c))

    amount = c(a,b,c)

    cat = c(rep("a",1000), rep("b",1000), rep("c",1000))

    hist.data = data.frame(amount,cat)
    names(hist.data) = c("amount","cat")

    hist.data$cat = factor(hist.data$cat, levels = c("a","b","c"))
    pricedata = ddply(hist.data, c("cat"), summarize, avg = mean(amount), minus.stdev = mean(amount)-sd(amount),
                      plus.stdev = mean(amount) + sd(amount))
    pricedata = pricedata[order(pricedata$avg),]

    ggplot(hist.data, aes(x=amount, fill = cat))+
      geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
      theme_test()+
      geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+

      geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

      geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

      facet_grid(cat ~., scales = "free")+
      scale_y_continuous(expand = c(0,0),name = "Count")+
      scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))

  }) #close renderPlot

   output$hist.plot = renderPlot({
    print(make.hist.plot())
   })

    output$downloadhist = downloadHandler(
      filename = function() { "hist.png" },
      content = function(file) {
        ggsave(file, plot = make.hist.plot(), device = "png")}
    )

}) # close shinyServer

</code>```

答:
This seems to be an issue of scope. Your code does work if you put the download button in the sidebar panel, if you remove the tabsetPanel, or if you put the download button in the same tabPanel. The last solution is shown below:

mainPanel(
  tabsetPanel( type = "tabs", #Open panel
    tabPanel("Distributions",
      plotOutput("hist.plot"),
      downloadButton('downloadhist', 'Download Plot')
    )
  )
) # close mainPanel
```

Body:
I'm trying to create a download button for my histogram plot.  I have the download button visible, but can't seem to get it to download correctly.  It always downloads a .htm file and not the .png file.  I"m using the ggsave command in my server.R.  I tried using the more traditional method, but that didn't seem to work either.

library(shiny)
library(plyr)
library(ggplot2)

shinyUI(fluidPage(
  headerPanel(title = "Test"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("input.a", "A", min = 0, max = 100, value = 50),
      sliderInput("input.b", "B", min = 0, max = 100, value = 50),
      sliderInput("input.c", "C", min = 0, max = 100, value = 50)
    ),

    mainPanel(

      tabsetPanel( type = "tabs", #Open panel
                   tabPanel("Distributions",plotOutput("hist.plot")),
                   downloadButton('downloadhist', 'Download Plot'))

) # close mainPanel
) # close sidebarLayout
) # close fluidPage
) # close shinyUI

shinyServer(function(input,output){ # open shiny server

    #output$hist.plot = renderPlot({ # open renderPlot
    make.hist.plot = reactive({

    a = runif(1000,1,(input$input.a))
    b = runif(1000,1,(input$input.b))
    c = runif(1000,1,(input$input.c))

    amount = c(a,b,c)

    cat = c(rep("a",1000), rep("b",1000), rep("c",1000))

    hist.data = data.frame(amount,cat)
    names(hist.data) = c("amount","cat")

    hist.data$cat = factor(hist.data$cat, levels = c("a","b","c"))
    pricedata = ddply(hist.data, c("cat"), summarize, avg = mean(amount), minus.stdev = mean(amount)-sd(amount),
                      plus.stdev = mean(amount) + sd(amount))
    pricedata = pricedata[order(pricedata$avg),]

    ggplot(hist.data, aes(x=amount, fill = cat))+
      geom_histogram(color="white", alpha = .8, position = 'identity', binwidth = 5)+
      theme_test()+
      geom_vline(aes(xintercept = avg), data = pricedata, color = "black", size = 1)+

      geom_vline(aes(xintercept = minus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

      geom_vline(aes(xintercept = plus.stdev), data = pricedata, color = "black", size = .75, linetype = "dotted")+

      facet_grid(cat ~., scales = "free")+
      scale_y_continuous(expand = c(0,0),name = "Count")+
      scale_x_continuous(labels = scales::dollar, name="\nAmount", limits = c(0,100))

  }) #close renderPlot

   output$hist.plot = renderPlot({
    print(make.hist.plot())
   })

    output$downloadhist = downloadHandler(
      filename = function() { "hist.png" },
      content = function(file) {
        ggsave(file, plot = make.hist.plot(), device = "png")}
    )

}) # close shinyServer


问:
Laravel 7: Why when I'm logged I can access route for reset password?
I realized can access to reset password route even when I'm logged. I want to can access only if user is logout.

How can I change this?

答:
I suppose you are using the default Laravel Auth routes (Auth::routes() in web routes file). In there, the reset password routes are protected behind the web middleware only. You can check the route list alongwith their middleware using the command: php artisan route:list.

What you have to do here is to add guest middleware to those reset password routes. For Laravel 7, it can be done by following code:

```<code>Auth::routes()
Route::middleware('guest')
    ->group(function () {
        app()->make('router')->resetPassword();
    });
</code>```

Note: the above code must be placed below Auth::routes() call

Body:
I suppose you are using the default Laravel Auth routes (Auth::routes() in web routes file). In there, the reset password routes are protected behind the web middleware only. You can check the route list alongwith their middleware using the command: php artisan route:list.

What you have to do here is to add guest middleware to those reset password routes. For Laravel 7, it can be done by following code:

Auth::routes()
Route::middleware('guest')
    ->group(function () {
        app()->make('router')->resetPassword();
    });

Note: the above code must be placed below Auth::routes() call


问:
check if input equals a specific string without repeating code
So im making a simple console menu for my program.

```<code># Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:
    uinput = input(menu)

    if uinput == "quit": # repetitive code
        break
    elif uinput == "1":
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=1)
    elif uinput == "2:
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=2)
</code>```

Whenever the user types quit into any one of those inputs, the loop breaks.

The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.

答:
I'm not too sure, but is this what it's supposed to do?</p>

```<code>menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:

    print(menu)
    uinput = input("Input parameters: ")

    if uinput == "quit": # repetitive code
        break

    if uinput == "1" or uinput == "2":
        process_params(uinput, option=int(uinput))
</code>```

Body:
So im making a simple console menu for my program.

# Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:
    uinput = input(menu)

    if uinput == "quit": # repetitive code
        break
    elif uinput == "1":
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=1)
    elif uinput == "2:
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=2)

Whenever the user types quit into any one of those inputs, the loop breaks.

The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.

Body:
I'm not too sure, but is this what it's supposed to do?

menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:

    print(menu)
    uinput = input("Input parameters: ")

    if uinput == "quit": # repetitive code
        break

    if uinput == "1" or uinput == "2":
        process_params(uinput, option=int(uinput))


问:
make local copy of global variable
I'm probably missing something really obvious, but how do I create a local copy of a global vaiable with the same name?
I have something like:

d = {"one": 1, "two": 2, "three": 3}

def foo():
    d = d.copy()
    d["four"] = 4
```

I want to create a copy of d in the inner scope that I can modify as I like without affecting the global version. This will complain that d is reference before assignment, which makes perfect sense because it is being interpreted as a local variable. If I declare it global though, this will modify it.

This would be trivial if I didn't mind if it had a different name eg: d_local = d.copy(), but that would be a big hassle in this situation and not just a find and replace one either.

If the only solution is to use a new name and deal with the consequences let me know.

答:
Generally using local and global variables with the same name is a really bad practice as it causes confusion. You could use d as an argument, or simply use a different name. However if you really wanted to leave your code structure untouched (which I do not recommend), you could define a function in the global scope that returns a copy of d. As such :

```<code>d = {"one": 1, "two": 2, "three": 3}

def copyD():
  return d.copy()

def foo():
  d = copyD()
  d["four"] = 4
</code>```

As pointed out by @rici the function could be defined inside the local scope by using the global keyword :

```<code>d = {"one": 1, "two": 2, "three": 3}

def foo():
  def copyD():
    global d
    return d.copy()
  d = copyD()
  d["four"] = 4
</code>```

This code is better, because the copyD function really won't be used anywhere else.

Title: make local copy of global variable

Body:
I'm probably missing something really obvious, but how do I create a local copy of a global vaiable with the same name?
I have something like:

d = {"one": 1, "two": 2, "three": 3}

def foo():
    d = d.copy()
    d["four"] = 4

I want to create a copy of d in the inner scope that I can modify as I like without affecting the global version. This will complain that d is reference before assignment, which makes perfect sense because it is being interpreted as a local variable. If I declare it global though, this will modify it.

This would be trivial if I didn't mind if it had a different name eg: d_local = d.copy(), but that would be a big hassle in this situation and not just a find and replace one either.

If the only solution is to use a new name and deal with the consequences let me know.

Body:
Generally using local and global variables with the same name is a really bad practice as it causes confusion. You could use d as an argument, or simply use a different name. However if you really wanted to leave your code structure untouched (which I do not recommend), you could define a function in the global scope that returns a copy of d. As such :

d = {"one": 1, "two": 2, "three": 3}

def copyD():
  return d.copy()

def foo():
  d = copyD()
  d["four"] = 4

As pointed out by @rici the function could be defined inside the local scope by using the global keyword :

d = {"one": 1, "two": 2, "three": 3}

def foo():
  def copyD():
    global d
    return d.copy()
  d = copyD()
  d["four"] = 4

This code is better, because the copyD function really won't be used anywhere else.


问:
reading bash variable array into python via argparse
I am trying to use argparse to read in a list of values from a bash script. But, it seems to only read 1 value rather than the list.

For example, in train.py

```<code>parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--lr', '--learning-rate', default=[0.1], type=float, nargs='+',
                        metavar='LR', help='initial learning rate', dest='lr')
args=parser.parse_args()
</code>```

my bash script is as follows:

```<code>LR="1e-1 1e-2 1e-3 1e-4 1e-5 1e-6"
python train.py --lr=$LR
</code>```

In train.py, print(args.lr) only outputs 1e-3. What is the correct way to read the list of values via argparse?

答:
Try removing the = from the argument, as follows:

python train.py --lr $LR
```

This will make --lr and each value from $LR into a separate argument for your python script.

Body:
I am trying to use argparse to read in a list of values from a bash script. But, it seems to only read 1 value rather than the list.

For example, in train.py

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--lr', '--learning-rate', default=[0.1], type=float, nargs='+',
                        metavar='LR', help='initial learning rate', dest='lr')
args=parser.parse_args()

my bash script is as follows:

LR="1e-1 1e-2 1e-3 1e-4 1e-5 1e-6"
python train.py --lr=$LR

In train.py, print(args.lr) only outputs 1e-3. What is the correct way to read the list of values via argparse?

Body:
Try removing the = from the argument, as follows:

python train.py --lr $LR

This will make --lr and each value from $LR into a separate argument for your python script.


问:
Disable AJAX Caching
I am in a bit of a pickle right now. I am building a web page that will get data from a CGI backend. I have no control over the CGI backend, nor the server (so no mod_headers or mod_expires). Also, because of the parameters to the script, I cannot append a unique value (like '&089u0af0d98) to each request. The requests are AJAX using the XmlHttpRequest object. I have tried to set the 'If-Modified-Since' and 'Cache-Control' request headers unsuccessfully. Does anybody have any other ideas for how I can prevent the AJAX response from being cached by the browser?</p>

答:
I use this javascript function ( which in turn uses jquery.ajax function )
the cache: false would do the trick.
This works perfectly for me , may be you can give it a try</p>

```<code>    function ajax_call(urlString)
    {
        ret_val="";
        $.ajax
        (
            {
                type: "GET",
                url: urlString,
                async:false,
                cache:false,
                dataType: 'html',
                success: function(msg)
                {
                    ret_val=msg;
                },
                error:function (xhr, textStatus, thrownError)
                {
                    ret_val=xhr.readyState;
                    alert("status=" +xhr.status);
                }
            }
        );
        return ret_val;
    }
</code>```

Title: Disable AJAX Caching

Body:
I use this javascript function ( which in turn uses jquery.ajax function )
the cache: false would do the trick.
This works perfectly for me , may be you can give it a try

    function ajax_call(urlString)
    {
        ret_val="";
        $.ajax
        (
            {
                type: "GET",
                url: urlString,
                async:false,
                cache:false,
                dataType: 'html',
                success: function(msg)
                {
                    ret_val=msg;
                },
                error:function (xhr, textStatus, thrownError)
                {
                    ret_val=xhr.readyState;
                    alert("status=" +xhr.status);
                }
            }
        );
        return ret_val;
    }


问:
Correct place to pass in parameters in Selenium testing?
What is the "proper" way to pass in parameters?

Code snippet below (pieces have been removed that aren't relevant)...

I am passing in the login parameters in the [TestMethod] itself, and not in the LoginPage class object.  Is that the right way to do this?  Or, should I be passing the strings into the LoginPage class itself?  (I realized there are other ways where I don't need to hard-code anywhere, but I am strictly referring to this hard-code scenario)

```<code>class LoginPage
{

    IWebDriver driver;

    By username = By.Id("user_login");
    By password = By.XPath(".//*[@id='user_pass']");
    By loginButton = By.Name("wp-submit");

    public void loginToWordpress(string userid, string pass)
    {
        driver.FindElement(username).SendKeys(userid);
        driver.FindElement(password).SendKeys(pass);
    }

}
</code>```

and the corresponding test....

```<code>   [TestMethod]
        public void assertPageSource()
        {
            LoginPage login = new LoginPage(driver);
            login.loginToWordpress("admin", "demo123");
            login.clickOnLoginButton();
        }
</code>```

答:
Refer to this two articles --

https://raw.githubusercontent.com/wiki/SeleniumHQ/selenium/PageObjects.md

https://www.toolsqa.com/selenium-webdriver/c-sharp/encapsulation-oops-principle/

Body:
What is the "proper" way to pass in parameters?

Code snippet below (pieces have been removed that aren't relevant)...

I am passing in the login parameters in the [TestMethod] itself, and not in the LoginPage class object.  Is that the right way to do this?  Or, should I be passing the strings into the LoginPage class itself?  (I realized there are other ways where I don't need to hard-code anywhere, but I am strictly referring to this hard-code scenario)

class LoginPage
{

    IWebDriver driver;

    By username = By.Id("user_login");
    By password = By.XPath(".//*[@id='user_pass']");
    By loginButton = By.Name("wp-submit");

    public void loginToWordpress(string userid, string pass)
    {
        driver.FindElement(username).SendKeys(userid);
        driver.FindElement(password).SendKeys(pass);
    }

}

and the corresponding test....

   [TestMethod]
        public void assertPageSource()
        {
            LoginPage login = new LoginPage(driver);
            login.loginToWordpress("admin", "demo123");
            login.clickOnLoginButton();
        }


问:
Thymleaf controller request mapping binging issue
I am new to thymleaf and at first i used simple requestmapping and thymleaf th:action and th:object to bind controller methods. But after adding class level requestmapping i cannot view my html.

below is my controller class code where i redirect to login page.

```<code>@Controller
@RequestMapping("/project")
public class MyController {

    @RequestMapping(value = {"/"}, method = RequestMethod.GET)

    public String login(Model model) {
        model.addAttribute("mylogin", new Credentials());
        return "login";

    }
    }
</code>```

below is my html page.

```<code><form class="user" th:action="@{/project/login}" th:object="${mylogin}" method="POST">
                                        <div class="form-group">
                                            <input type="email" id="user_name" name="username"
                                                class="form-control form-control-user"

                                                placeholder="Enter Email Address..." />
                                        </div>
                                        <div class="form-group">
                                            <input type="password" id="password" name="password"
                                                class="form-control form-control-user"
                                                placeholder="Password" />
                                        </div>

                                        <button class="btn btn-primary btn-user btn-block"
                                            name="Submit" value="Login" type="Submit" th:text="Login"></button>
                                    </form>
</code>```

after adding @RequestMapping("/project") in class i cannot fetch html. If i remove this @RequestMapping("/project") and change th:action="@{/project/login}" to th:action="@{/login}" my code works.

What can  be the problem for such issue?

答:
Change This Request mapping this way  /login with class level requestmapping and try again:

```<code> @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
 public String login(Model model) {
        model.addAttribute("mylogin", new Credentials());
        return "login";
    }
</code>```

OR

```<code> @GetMapping("/login")
 public String login(Model model) {
        model.addAttribute("mylogin", new Credentials());
        return "login";
    }
</code>```

Body:
I am new to thymleaf and at first i used simple requestmapping and thymleaf th:action and th:object to bind controller methods. But after adding class level requestmapping i cannot view my html.

below is my controller class code where i redirect to login page.

@Controller
@RequestMapping("/project")
public class MyController {

    @RequestMapping(value = {"/"}, method = RequestMethod.GET)

    public String login(Model model) {
        model.addAttribute("mylogin", new Credentials());
        return "login";

    }
    }

below is my html page.

<form class="user" th:action="@{/project/login}" th:object="${mylogin}" method="POST">

                                            <input type="email" id="user_name" name="username"
                                                class="form-control form-control-user"

                                                placeholder="Enter Email Address..." />

                                            <input type="password" id="password" name="password"
                                                class="form-control form-control-user"
                                                placeholder="Password" />

                                        <button class="btn btn-primary btn-user btn-block"
                                            name="Submit" value="Login" type="Submit" th:text="Login"></button>
                                    </form>

after adding @RequestMapping("/project") in class i cannot fetch html. If i remove this @RequestMapping("/project") and change th:action="@{/project/login}" to th:action="@{/login}" my code works.

What can  be the problem for such issue?

Body:
Change This Request mapping this way  /login with class level requestmapping and try again:

 @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
 public String login(Model model) {
        model.addAttribute("mylogin", new Credentials());
        return "login";
    }

OR

 @GetMapping("/login")
 public String login(Model model) {
        model.addAttribute("mylogin", new Credentials());
        return "login";
    }


问:
Error 6 when injecting DLL using C#
when I try to inject a DLL with C# into a java process (Minecraft specifically) I get an error "ERROR 6", I've been googling this error but couldnt find a solution.
The program is run in administrator mode, and it isnt trying to load from an admin path.
My code:

```<code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace Launcher
{
internal class InjectionUtils
{
    public struct CTX_PROCS
    {
        public Process[] procs;
    }

    private const int PROCESS_CREATE_THREAD = 2;

    private const int PROCESS_QUERY_INFORMATION = 1024;

    private const int PROCESS_VM_OPERATION = 8;

    private const int PROCESS_VM_WRITE = 32;

    private const int PROCESS_VM_READ = 16;

    private const uint MEM_COMMIT = 4096u;

    private const uint MEM_RESERVE = 8192u;

    private const uint PAGE_READWRITE = 4u;

    [DllImport("kernel32.dll")]
    public static extern IntPtr OpenProcess(int dwDesiredAccess, bool        bInheritHandle, int dwProcessId);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr GetModuleHandle(string lpModuleName);

    [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);

    [DllImport("kernel32.dll")]
    private static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern int MessageBox(IntPtr hWnd, string text, string caption, uint option);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr hObject);

    [DllImport("kernel32.dll")]
    private static extern uint GetLastError();

    private void MBox(string text)
    {
        InjectionUtils.MessageBox(IntPtr.Zero, text, "", 0u);
    }

    public void DoInjection(string dllPath)
    {
        InjectionUtils.CTX_PROCS cTX_PROCS = this.FindProcessByNameAndTitle("javaw", "Minecraft 1.7");
        this.InjectDynamicLib(dllPath, cTX_PROCS.procs[0].Id);
    }

    public InjectionUtils.CTX_PROCS FindProcessByNameAndTitle(string processName, string title)
    {
        InjectionUtils.CTX_PROCS result = default(InjectionUtils.CTX_PROCS);
        List<Process> list = new List<Process>();
        Process[] processes = Process.GetProcesses();
        for (int i = 0; i < processes.Length; i++)
        {
            Process process = processes[i];
            if (process.ProcessName.Equals(processName) && process.MainWindowTitle.Contains(title))
            {
                list.Add(process);
            }
        }
        result.procs = list.ToArray();
        return result;
    }

    public void eject()
    {
    }

    private bool InjectDynamicLib(string dllPath, int pId)
    {
        bool result = false;
        IntPtr intPtr = InjectionUtils.OpenProcess(1082, false, pId);
        uint num = (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char)));
        if (intPtr != IntPtr.Zero)
        {
            IntPtr procAddress = InjectionUtils.GetProcAddress(InjectionUtils.GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            IntPtr intPtr2 = InjectionUtils.VirtualAllocEx(intPtr, IntPtr.Zero, num, 12288u, 4u);
            UIntPtr uIntPtr;
            // Write path of dll to remote process
            if (InjectionUtils.WriteProcessMemory(intPtr, intPtr2, Encoding.Default.GetBytes(dllPath), num, out uIntPtr))
            {
                InjectionUtils.CloseHandle(InjectionUtils.CreateRemoteThread(intPtr, IntPtr.Zero, 0u, procAddress, intPtr2, 0u, IntPtr.Zero));
                result = true;
            }
            InjectionUtils.CloseHandle(intPtr);
        }
        if (InjectionUtils.GetLastError() != 0u)
        {
            this.MBox("ERROR " + InjectionUtils.GetLastError());
        }
        return result;
    }
</code>```

If anyone could help I would appreciate it dearly :)
Thanks in advance :D

答:
From MSDN Error Code List:

ERROR_INVALID_HANDLE

0x6

Before you call GetLastError() you call CloseHandle() twice, once on the thread handle and on the process handle.

To find the problem just check the returns from OpenProcess() and CreateRemoteThread() and compare against the info you find in the functions documentation on MSDN.

For a simple no frills C# injector, this is the code I like to use which includes some error checking and uses the managed Process::Dispose() method instead of calling the native CloseHandle() at least on the process handle:

```<code>public static bool InjectDLL(string dllpath, string procname)
{
    Process[] procs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(procname));

    if (procs.Length == 0)
    {
        return false;
    }

    Process proc = procs[0];

    if (proc.Handle != IntPtr.Zero)
    {
        IntPtr loc = VirtualAllocEx(proc.Handle, IntPtr.Zero, MAX_PATH, AllocationType.Commit | AllocationType.Reserve,
            MemoryProtection.ReadWrite);

        if (loc.Equals(0))
        {
            return false;
        }

        IntPtr bytesRead = IntPtr.Zero;

        bool result = WriteProcessMemory(proc.Handle, loc, dllpath.ToCharArray(), dllpath.Length, out bytesRead);

        if (!result || bytesRead.Equals(0))
        {
            return false;
        }

        IntPtr loadlibAddy = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

        IntPtr hThread = CreateRemoteThread(proc.Handle, IntPtr.Zero, 0, loadlibAddy, loc, 0, out _);

        if (!hThread.Equals(0))
        {
            CloseHandle(hThread);
        }
        else return false;
    }
    else return false;

    //this will CloseHandle automatically using the managed method
    proc.Dispose();
    return true;
}
</code>```

Make sure to run as admin and pinvoke any missing definitions.

Title: Error 6 when injecting DLL using C#

Body:
when I try to inject a DLL with C# into a java process (Minecraft specifically) I get an error "ERROR 6", I've been googling this error but couldnt find a solution.
The program is run in administrator mode, and it isnt trying to load from an admin path.
My code:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace Launcher
{
internal class InjectionUtils
{
    public struct CTX_PROCS
    {
        public Process[] procs;
    }

    private const int PROCESS_CREATE_THREAD = 2;

    private const int PROCESS_QUERY_INFORMATION = 1024;

    private const int PROCESS_VM_OPERATION = 8;

    private const int PROCESS_VM_WRITE = 32;

    private const int PROCESS_VM_READ = 16;

    private const uint MEM_COMMIT = 4096u;

    private const uint MEM_RESERVE = 8192u;

    private const uint PAGE_READWRITE = 4u;

    [DllImport("kernel32.dll")]
    public static extern IntPtr OpenProcess(int dwDesiredAccess, bool        bInheritHandle, int dwProcessId);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr GetModuleHandle(string lpModuleName);

    [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten);

    [DllImport("kernel32.dll")]
    private static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern int MessageBox(IntPtr hWnd, string text, string caption, uint option);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr hObject);

    [DllImport("kernel32.dll")]
    private static extern uint GetLastError();

    private void MBox(string text)
    {
        InjectionUtils.MessageBox(IntPtr.Zero, text, "", 0u);
    }

    public void DoInjection(string dllPath)
    {
        InjectionUtils.CTX_PROCS cTX_PROCS = this.FindProcessByNameAndTitle("javaw", "Minecraft 1.7");
        this.InjectDynamicLib(dllPath, cTX_PROCS.procs[0].Id);
    }

    public InjectionUtils.CTX_PROCS FindProcessByNameAndTitle(string processName, string title)
    {
        InjectionUtils.CTX_PROCS result = default(InjectionUtils.CTX_PROCS);
        List<Process> list = new List<Process>();
        Process[] processes = Process.GetProcesses();
        for (int i = 0; i < processes.Length; i++)
        {
            Process process = processes[i];
            if (process.ProcessName.Equals(processName) && process.MainWindowTitle.Contains(title))
            {
                list.Add(process);
            }
        }
        result.procs = list.ToArray();
        return result;
    }

    public void eject()
    {
    }

    private bool InjectDynamicLib(string dllPath, int pId)
    {
        bool result = false;
        IntPtr intPtr = InjectionUtils.OpenProcess(1082, false, pId);
        uint num = (uint)((dllPath.Length + 1) * Marshal.SizeOf(typeof(char)));
        if (intPtr != IntPtr.Zero)
        {
            IntPtr procAddress = InjectionUtils.GetProcAddress(InjectionUtils.GetModuleHandle("kernel32.dll"), "LoadLibraryA");
            IntPtr intPtr2 = InjectionUtils.VirtualAllocEx(intPtr, IntPtr.Zero, num, 12288u, 4u);
            UIntPtr uIntPtr;
            // Write path of dll to remote process
            if (InjectionUtils.WriteProcessMemory(intPtr, intPtr2, Encoding.Default.GetBytes(dllPath), num, out uIntPtr))
            {
                InjectionUtils.CloseHandle(InjectionUtils.CreateRemoteThread(intPtr, IntPtr.Zero, 0u, procAddress, intPtr2, 0u, IntPtr.Zero));
                result = true;
            }
            InjectionUtils.CloseHandle(intPtr);
        }
        if (InjectionUtils.GetLastError() != 0u)
        {
            this.MBox("ERROR " + InjectionUtils.GetLastError());
        }
        return result;
    }

If anyone could help I would appreciate it dearly :)
Thanks in advance :D

Body:
From MSDN Error Code List:

ERROR_INVALID_HANDLE

0x6

Before you call GetLastError() you call CloseHandle() twice, once on the thread handle and on the process handle.

To find the problem just check the returns from OpenProcess() and CreateRemoteThread() and compare against the info you find in the functions documentation on MSDN.

For a simple no frills C# injector, this is the code I like to use which includes some error checking and uses the managed Process::Dispose() method instead of calling the native CloseHandle() at least on the process handle:

public static bool InjectDLL(string dllpath, string procname)
{
    Process[] procs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(procname));

    if (procs.Length == 0)
    {
        return false;
    }

    Process proc = procs[0];

    if (proc.Handle != IntPtr.Zero)
    {
        IntPtr loc = VirtualAllocEx(proc.Handle, IntPtr.Zero, MAX_PATH, AllocationType.Commit | AllocationType.Reserve,
            MemoryProtection.ReadWrite);

        if (loc.Equals(0))
        {
            return false;
        }

        IntPtr bytesRead = IntPtr.Zero;

        bool result = WriteProcessMemory(proc.Handle, loc, dllpath.ToCharArray(), dllpath.Length, out bytesRead);

        if (!result || bytesRead.Equals(0))
        {
            return false;
        }

        IntPtr loadlibAddy = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

        IntPtr hThread = CreateRemoteThread(proc.Handle, IntPtr.Zero, 0, loadlibAddy, loc, 0, out _);

        if (!hThread.Equals(0))
        {
            CloseHandle(hThread);
        }
        else return false;
    }
    else return false;

    //this will CloseHandle automatically using the managed method
    proc.Dispose();
    return true;
}

Make sure to run as admin and pinvoke any missing definitions.


问:
pandas datetime columns problem and i don't know what i am missing
I am a Korean student

Please understand that English is awkward

i want to make columns datetime > year,mounth ....  ,second

```<code>train = pd.read_csv('input/Train.csv')
</code>```

DateTime looks like this
(this is head(20) and I remove other columns easy to see)

```<code>    datetime

0   2011-01-01 00:00:00
1   2011-01-01 01:00:00
2   2011-01-01 02:00:00
3   2011-01-01 03:00:00
4   2011-01-01 04:00:00
5   2011-01-01 05:00:00
6   2011-01-01 06:00:00
7   2011-01-01 07:00:00
8   2011-01-01 08:00:00
9   2011-01-01 09:00:00
10  2011-01-01 10:00:00
11  2011-01-01 11:00:00
12  2011-01-01 12:00:00
13  2011-01-01 13:00:00
14  2011-01-01 14:00:00
15  2011-01-01 15:00:00
16  2011-01-01 16:00:00
17  2011-01-01 17:00:00
18  2011-01-01 18:00:00
19  2011-01-01 19:00:00
</code>```

then I write this code to see each columns (year,month,day,hour,minute,second)

```<code>train['year'] = train['datetime'].dt.year

train['month'] = train['datetime'].dt.month

train['day'] = train['datetime'].dt.day

train['hour'] = train['datetime'].dt.hour

train['minute'] = train['datetime'].dt.minute

train['second'] = train['datetime'].dt.seond
</code>```

and error like this

AttributeError: Can only use .dt accessor with datetimelike values

please help me ㅠㅅㅠ

答:
Note that by default read_csv is able to deduce column type only
for numeric and boolean columns.
Unless explicitely specified (e.g. passing converters or dtype
parameters), all other cases of input are left as strings
and the pandasonic type of such columns is object.

And just this occurred in your case.
So, as this column is of object type, you can not invoke dt accessor
on it, as it works only on columns of datetime type.

Actually, in this case, you can take the following approach:

do not specify any conversion of this column (it will be parsed
just as object),

after that split datetime column into "parts", using str.split
(all 6 columns with a single instruction),

set proper column names in the resulting DataFrame,

join it to the original DataFrame (then drop),

as late as now change the type of the original column.

To do it, you can run:

```<code>wrk = df['datetime'].str.split(r'[- :]', expand=True).astype(int)
wrk.columns = ['year', 'month', 'day', 'hour', 'minute', 'second']
df = df.join(wrk)
del wrk
df['datetime'] = pd.to_datetime(df['datetime'])
</code>```

Note that I added astype(int). Otherwise these columns would be left as
object (actually string) type.

Or maybe this original column is not needed any more (as you have extracted
all date / time components)? In such case drop this column instead of
converting it.

And the last hint: datetime is used rather as a type name (with various
endings).
So it is better when you used some other name here, at least differing
in char case, e.g. DateTime.

Body:
I am a Korean student

Please understand that English is awkward

i want to make columns datetime > year,mounth ....  ,second

train = pd.read_csv('input/Train.csv')

DateTime looks like this
(this is head(20) and I remove other columns easy to see)

    datetime

0   2011-01-01 00:00:00
1   2011-01-01 01:00:00
2   2011-01-01 02:00:00
3   2011-01-01 03:00:00
4   2011-01-01 04:00:00
5   2011-01-01 05:00:00
6   2011-01-01 06:00:00
7   2011-01-01 07:00:00
8   2011-01-01 08:00:00
9   2011-01-01 09:00:00
10  2011-01-01 10:00:00
11  2011-01-01 11:00:00
12  2011-01-01 12:00:00
13  2011-01-01 13:00:00
14  2011-01-01 14:00:00
15  2011-01-01 15:00:00
16  2011-01-01 16:00:00
17  2011-01-01 17:00:00
18  2011-01-01 18:00:00
19  2011-01-01 19:00:00

then I write this code to see each columns (year,month,day,hour,minute,second)

train['year'] = train['datetime'].dt.year

train['month'] = train['datetime'].dt.month

train['day'] = train['datetime'].dt.day

train['hour'] = train['datetime'].dt.hour

train['minute'] = train['datetime'].dt.minute

train['second'] = train['datetime'].dt.seond

and error like this

AttributeError: Can only use .dt accessor with datetimelike values

please help me ㅠㅅㅠ

Body:
Note that by default read_csv is able to deduce column type only
for numeric and boolean columns.
Unless explicitely specified (e.g. passing converters or dtype
parameters), all other cases of input are left as strings
and the pandasonic type of such columns is object.

And just this occurred in your case.
So, as this column is of object type, you can not invoke dt accessor
on it, as it works only on columns of datetime type.

Actually, in this case, you can take the following approach:

do not specify any conversion of this column (it will be parsed
just as object),

after that split datetime column into "parts", using str.split
(all 6 columns with a single instruction),

set proper column names in the resulting DataFrame,

join it to the original DataFrame (then drop),

as late as now change the type of the original column.

To do it, you can run:

wrk = df['datetime'].str.split(r'[- :]', expand=True).astype(int)
wrk.columns = ['year', 'month', 'day', 'hour', 'minute', 'second']
df = df.join(wrk)
del wrk
df['datetime'] = pd.to_datetime(df['datetime'])

Note that I added astype(int). Otherwise these columns would be left as
object (actually string) type.

Or maybe this original column is not needed any more (as you have extracted
all date / time components)? In such case drop this column instead of
converting it.

And the last hint: datetime is used rather as a type name (with various
endings).
So it is better when you used some other name here, at least differing
in char case, e.g. DateTime.


问:
How do I hide a tab in a TabActivity?
I have created three tabs in TabActivity onCreate.

How can I hide one tab at runtime?

答:
If you want to hide the tabWidget you can do so by setting the visibility to GONE/INVISIBLE like:

```<code>getTabWidget().setVisibility(TabWidget.GONE);
</code>```

Title: How do I hide a tab in a TabActivity?

Body:
If you want to hide the tabWidget you can do so by setting the visibility to GONE/INVISIBLE like:

getTabWidget().setVisibility(TabWidget.GONE);


问:
Blazor: Invoking C# static method from JS function called from HTML onclick--why can't the JS find the method?
Inside a Blazor component, I want to call a JS method from the HTML onclick event of an anchor tag, thus:

```<code><a onclick="window.LoadImage();" class="@CssClass">@DisplayName</a>
</code>```

My JS method is:

```<code>window.LoadImage = () => {
    DotNet.invokeMethodAsync('MyProject', 'FireEvent').then();
}
</code>```

Inside the JS method, I want to fire a C# static method to trigger an event, thus:

```<code>[JSInvokable]
public static void FireEvent()
{
   StateEngine.LoadImage(DisplayName, Target);
}
[Parameter]
public string DisplayName { get; set; }
[Parameter]
public string Target { get; set; }

</code>```

I can't get the JS method to find the C# method. I've tried multiple name configurations for the first parameter, like

```<code>MyProject (the assembly name)
MyProject.FolderName.ComponentName
FolderName.ComponentName
ComponentName
</code>```

to name a few. I've also tried shuffling names through the second parameter.

How is this supposed to work? What am I missing?

P.S. Please disregard the bit about the instance properties in the static method.  I've got a workaround for that, but don't want to clutter up the post.

答:
Your code looks good. May be its unable to find your .Net method. Give it a retry..

JS

```<code>window.LoadImage = function () {
DotNet.invokeMethodAsync("MyBlazorProject.UI", "FireEvent").then();}
</code>```

First Parameter must be AssemblyName of your Blazor component. In my case, it is "MyBlazorProject.UI".

Second Parameter must be method name.

HTML

```<code><a onclick="window.LoadImage()" class="btn btn-primary">Call .Net Method FireEvent</a>
</code>```

here onclick is JavaScript event, which is good in your case too.

C# Code

```<code>[JSInvokable]
public static void FireEvent()
{
    //debugger hits here
    //StateEngine.LoadImage(DisplayName, Target);
}
</code>```

This is all working for me fine. Debugger gets hit inside FireEvent .Net method after clicking anchor tag.

Thanks

Body:
Inside a Blazor component, I want to call a JS method from the HTML onclick event of an anchor tag, thus:

@DisplayName

My JS method is:

window.LoadImage = () => {
    DotNet.invokeMethodAsync('MyProject', 'FireEvent').then();
}

Inside the JS method, I want to fire a C# static method to trigger an event, thus:

[JSInvokable]
public static void FireEvent()
{
   StateEngine.LoadImage(DisplayName, Target);
}
[Parameter]
public string DisplayName { get; set; }
[Parameter]
public string Target { get; set; }

I can't get the JS method to find the C# method. I've tried multiple name configurations for the first parameter, like

MyProject (the assembly name)
MyProject.FolderName.ComponentName
FolderName.ComponentName
ComponentName

to name a few. I've also tried shuffling names through the second parameter.

How is this supposed to work? What am I missing?

P.S. Please disregard the bit about the instance properties in the static method.  I've got a workaround for that, but don't want to clutter up the post.

Body:
Your code looks good. May be its unable to find your .Net method. Give it a retry..

JS

window.LoadImage = function () {
DotNet.invokeMethodAsync("MyBlazorProject.UI", "FireEvent").then();}

First Parameter must be AssemblyName of your Blazor component. In my case, it is "MyBlazorProject.UI".

Second Parameter must be method name.

HTML

<a onclick="window.LoadImage()" class="btn btn-primary">Call .Net Method FireEvent</a>

here onclick is JavaScript event, which is good in your case too.

C# Code

[JSInvokable]
public static void FireEvent()
{
    //debugger hits here
    //StateEngine.LoadImage(DisplayName, Target);
}

This is all working for me fine. Debugger gets hit inside FireEvent .Net method after clicking anchor tag.

Thanks


答:
Hopefully this helps. I'm a little unsure what you are requesting. </p>

```<code>User_Input = ""

while User_Input != 'quit':
    User_Input = input('Get Some Input')
</code>```

Title: check if input equals a specific string without repeating code

Body:
So im making a simple console menu for my program.

# Example menu program
menu = """
OPTIONS
1. Option 1
2. Option 2
"""

while True:
    uinput = input(menu)

    if uinput == "quit": # repetitive code
        break
    elif uinput == "1":
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=1)
    elif uinput == "2:
        uinput = input("Input parameters: ")
        if uinput == "quit": # repetitive code
            break
        process_params(uinput, option=2)

Whenever the user types quit into any one of those inputs, the loop breaks.

The problem is my program contains a lot of input functions, and I don't want to check if uinput == "quit" every time have an input function. Is there a way to do this? I thought of making a custom input function that checks the input every time, but you can't call break from another function.

Body:
Hopefully this helps. I'm a little unsure what you are requesting.

User_Input = ""

while User_Input != 'quit':
    User_Input = input('Get Some Input')


问:
Vb.net, I hope to make a small program
I watched many videos on Youtube, Read many articles and topics on this matter,
I've used Stopwatch function to compare between them, could not reach any result.

Which will make my program small?
I know that the second example is easy to understand

Ex 1:

```<code>Dim WB As System.Net.WebClient = New System.Net.WebClient
Dim R As String = WB.DownloadString("")
IO.File.WriteAllText("FinalResult", R)
</code>```

Ex 2:

```<code>Imports System.IO
Imports System.Net

        Dim WB As WebClient = New WebClient
        Dim R As String = WB.DownloadString("")
        File.WriteAllText("FinalResult", R)
</code>```

答:
There is absolutely no difference between those two code snippets once compiled. It is purely a matter of readability. Given that you should always strive for the most readable code, the second option is better from that perspective.

You should also keep in mind that, unlike C#, VB allows you to import namespaces at the project level too. If you want to use types from a namespace in multiple code files, it's generally preferable to import them at the project level, which you do on the References page of the project properties.

Importing namespaces that you use multiple times and importing namespaces at the project level that you use in multiple files are both implementations of the DRY principle, i.e. Don't Repeat Yourself.

Title: Vb.net, I hope to make a small program

Body:
I watched many videos on Youtube, Read many articles and topics on this matter,
I've used Stopwatch function to compare between them, could not reach any result.

Which will make my program small?
I know that the second example is easy to understand

Ex 1:

Dim WB As System.Net.WebClient = New System.Net.WebClient
Dim R As String = WB.DownloadString("")
IO.File.WriteAllText("FinalResult", R)

Ex 2:

Imports System.IO
Imports System.Net

        Dim WB As WebClient = New WebClient
        Dim R As String = WB.DownloadString("")
        File.WriteAllText("FinalResult", R)


问:
How do I import CreateJS into a VueJS .vue component?
I apologize in advance, I'm still very new to Vuejs in general. I'm trying to import CreateJS / SoundJS into a .vue component. I have installed CreateJS via npm. I just don't know how to import the library into the component so I can reference the sound functions. I can't seem to find anything in the CreateJS docs for this type of usage... any code or reference links would be most appreciated. Thanks!</p>

答:
Well, I did an example using the CreateJS/SoundJS library import it from its CDN.

In the public/index.html file, add the tag:

```<code><script src="https://code.createjs.com/1.0.0/soundjs.min.js"></script>
</code>```

Now you have the library in your project, and you have access to it and its functionality.

In the src/main.js add the library to be used with Vue adding it to the Vue prototype:

```<code>import Vue from "vue";
import App from "./App.vue";
const createjs = window.createjs; // Get the createjs instance from window object

Vue.config.productionTip = false;
Vue.prototype.createjs = createjs; // Add the createjs instance to the Vue prototy, to use this.createjs

new Vue({
  render: h => h(App)
}).$mount("#app");
</code>```

In the src/App.vue component (or any component, but App.vue is the entry point of the application, so it's a good place to do it) configure the sounds:

```<code><template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
    <button @click="play">Play</button>
    <!-- button to call the play method -->
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
const hornSound = require("@/assets/hey.mp3"); // Store a mp3 file in a variable, You can add more sounds, here on in another components

export default {
  name: "App",
  components: {
    HelloWorld
  },
  methods: {
    play() {
      this.createjs.Sound.play("Horn"); // Acces and play the sound with the id "Horn"
    }
  },
  created() {
    const soundId = "Horn"; // Id of the sound to be registered
    this.createjs.Sound.registerSound(hornSound, soundId); // Register the sound, using the mp3 and the id
    // You can do this with any amount of sounds, here or in any component
    // Once a sound is registered, you have access to it in all the components
  }
};
</script>
</code>```

Playing the sound from a child component (src/components/HelloWorld.vue):

```<code>    <template>
      <div class="hello">
        <h3>Hello World with createjs/soundjs</h3>
        <button @click="playFromChild">Play inside child component</button>
      </div>
    </template>

    <script>
    export default {
      name: "HelloWorld",
      props: {
        msg: String
      },
      methods: {
        playFromChild() {
          this.createjs.Sound.play("Horn"); // We are accessing to the sound with id "Horn" without import anything
        }
      }
    };
    </script>
</code>```

I hope this help you, I tried to explain how to use it but as you said, there is not documentation about it, so maybe this is tricky but it works.

Body:
Well, I did an example using the CreateJS/SoundJS library import it from its CDN.

In the public/index.html file, add the tag:

<script src="https://code.createjs.com/1.0.0/soundjs.min.js"></script>

Now you have the library in your project, and you have access to it and its functionality.

In the src/main.js add the library to be used with Vue adding it to the Vue prototype:

import Vue from "vue";
import App from "./App.vue";
const createjs = window.createjs; // Get the createjs instance from window object

Vue.config.productionTip = false;
Vue.prototype.createjs = createjs; // Add the createjs instance to the Vue prototy, to use this.createjs

new Vue({
  render: h => h(App)
}).$mount("#app");

In the src/App.vue component (or any component, but App.vue is the entry point of the application, so it's a good place to do it) configure the sounds:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
    <button @click="play">Play</button>
    <!-- button to call the play method -->
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
const hornSound = require("@/assets/hey.mp3"); // Store a mp3 file in a variable, You can add more sounds, here on in another components

export default {
  name: "App",
  components: {
    HelloWorld
  },
  methods: {
    play() {
      this.createjs.Sound.play("Horn"); // Acces and play the sound with the id "Horn"
    }
  },
  created() {
    const soundId = "Horn"; // Id of the sound to be registered
    this.createjs.Sound.registerSound(hornSound, soundId); // Register the sound, using the mp3 and the id
    // You can do this with any amount of sounds, here or in any component
    // Once a sound is registered, you have access to it in all the components
  }
};
</script>

Playing the sound from a child component (src/components/HelloWorld.vue):

    <template>
      <div class="hello">
        <h3>Hello World with createjs/soundjs</h3>
        <button @click="playFromChild">Play inside child component</button>
      </div>
    </template>

    <script>
    export default {
      name: "HelloWorld",
      props: {
        msg: String
      },
      methods: {
        playFromChild() {
          this.createjs.Sound.play("Horn"); // We are accessing to the sound with id "Horn" without import anything
        }
      }
    };
    </script>

I hope this help you, I tried to explain how to use it but as you said, there is not documentation about it, so maybe this is tricky but it works.


问:
E4X : Assigning to root node
I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!

Suppose I have the following XML (using e4x):

```<code>var xml:XML = <root><example>foo</example></root>
</code>```

I can change the contents of the example node using the following code:

```<code>xml.example = "bar";
</code>```

However, if I have this:

```<code>var xml:XML = <root>foo</root>
</code>```

How do i change the contents of the root node?

```<code>xml = "bar";
</code>```

Obviously doesn't work as I'm attempting to assign a string to an XML object.

答:
If you're trying to change the root element of a document, you don't really need to-- just throw out the existing document and replace it. Alternatively, just wrap your  element in a more proper root element (you shouldn't be editing the root node anyway) and you'd be set.

Of course, that doesn't answer your question. There's an ugly JS hack that can do what you want, but bear in mind that it's likely far slower than doing the above. Anyway, here it is:

```<code>var xml = <root>foo</root>; // </fix_syntax_highlighter>
var parser = new DOMParser();
var serializer = new XMLSerializer();

// Parse xml as DOM document
// Must inject "<root></root>" wrapper because
// E4X's toString() method doesn't give it to us
// Not sure if this is expected behaviour.. doesn't seem so to me.
var xmlDoc = parser.parseFromString("<root>" +
  xml.toString() + "</root>", "text/xml");

// Make the change
xmlDoc.documentElement.firstChild.nodeValue = "CHANGED";

// Serialize back to string and then to E4X XML()
xml = new XML(serializer.serializeToString(xmlDoc));
</code>```

You can ignore the fix_syntax_highlighter comment.

OwnerDisplayName: Groky

Title: E4X : Assigning to root node

Body:
I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!

Suppose I have the following XML (using e4x):

var xml:XML = <root><example>foo</example></root>

I can change the contents of the example node using the following code:

xml.example = "bar";

However, if I have this:

var xml:XML = <root>foo</root>

How do i change the contents of the root node?

xml = "bar";

Obviously doesn't work as I'm attempting to assign a string to an XML object.

Body:
If you're trying to change the root element of a document, you don't really need to-- just throw out the existing document and replace it. Alternatively, just wrap your  element in a more proper root element (you shouldn't be editing the root node anyway) and you'd be set.

Of course, that doesn't answer your question. There's an ugly JS hack that can do what you want, but bear in mind that it's likely far slower than doing the above. Anyway, here it is:

var xml = <root>foo</root>; // </fix_syntax_highlighter>
var parser = new DOMParser();
var serializer = new XMLSerializer();

// Parse xml as DOM document
// Must inject "<root></root>" wrapper because
// E4X's toString() method doesn't give it to us
// Not sure if this is expected behaviour.. doesn't seem so to me.
var xmlDoc = parser.parseFromString("<root>" +
  xml.toString() + "</root>", "text/xml");

// Make the change
xmlDoc.documentElement.firstChild.nodeValue = "CHANGED";

// Serialize back to string and then to E4X XML()
xml = new XML(serializer.serializeToString(xmlDoc));

You can ignore the fix_syntax_highlighter comment.


问:
DLL Number and Load Performance
Suppose the overall dll size is 100M, here are the 2 cases:

100M * 1

10M  * 10

Will their be much performance impact when using many small sized DLLs? why?

We did a testing recently but didn't detect much performance difference between the 2 cases, I am not sure if there are some wrong steps with my testing or this is the fact.

答: The only hit you're likely to get with multiple DLLs is a slight startup hit as the OS loader will have to locate the DLLs and resolve and references these DLLs have and rebase them as they're loaded. However, the performance impact is not worth worry about, especially if you've got 10M*10 DLLs</p>

OwnerDisplayName: Baiyan Huang

Title: DLL Number and Load Performance

OwnerDisplayName: Sean


问:
How to change specific lines in a text file and enforce this change when writing output file
I'm having an issue with implementing a change on specific files in a text file. I have looped over the lines and identified the ones starting with a specific character (N2).

I'm trying to wrap a paragraph so it only allows for 100 characters per line for the abstract of this output from an online source, numerous abstracts are contained in the file all starting with N2 prefixed to the string.

The information appears as separate lines in the text file, ForEoin.txt:

```<code><!-- language: lang-none -->
TY  - JOUR
ID  - 31513460
T1  - Systematic Review: Clinical Metabolomics to Forecast Outcomes in Liver Transplantation Surgery.
A1  - Attard, Joseph A
A1  - Dunn, Warwick B
A1  - Mergental, Hynek
A1  - Mirza, Darius F
A1  - Afford, Simon C
A1  - Perera, M Thamara P R
Y1  - 2019//
N2  - Liver transplantation is an effective intervention for end-stage liver disease, fulminant hepatic failure, and early hepatocellular carcinoma. Yet, there is marked patient-to-patient variation in liver transplantation outcomes. This calls for novel diagnostics to enable rational deployment of donor livers. Metabolomics is a postgenomic high-throughput systems biology approach to diagnostic innovation in clinical medicine. We report here an original systematic review of the metabolomic studies that have identified putative biomarkers in the context of liver transplantation. Eighteen studies met the inclusion criteria that involved sampling of blood (n = 4), dialysate fluid (n = 4), bile (n = 5), and liver tissue (n = 5). Metabolites of amino acid and nitrogen metabolism, anaerobic glycolysis, lipid breakdown products, and bile acid metabolism were significantly different in transplanted livers with and without graft dysfunction. However, criteria for defining the graft dysfunction varied across studies. This systematic review demonstrates that metabolomics can be deployed in identification of metabolic indicators of graft dysfunction with a view to implicated molecular mechanisms. We conclude the article with a horizon scanning of metabolomics technology in liver transplantation and its future prospects and challenges in research and clinical practice.
KW  - *Biomarkers
KW  - Genotype
</code>```

So far I have iterated over the lines of the file and called upon the textwrap module to wrap this for me but I cant get my head around writing over the existing lines with this new wrapped lines in the output file.

```<code>#!/usr/bin/env python

import textwrap

filename_org = 'ForEoin.txt'
filename_new = 'Eoin_Shortline_v2'

with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)

                wf.write(new_line)
</code>```

答:
```<code>import textwrap

filename_org = 'ForEoin.txt'
filename_new = 'Eoin_Shortline_v2'

with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)
                wf.write(new_line)
            else:
                wf.write(line)
</code>```

If the line starts with "N2" do the wrapper and then write it to the file in the else part also you have to right it to the file.

Body:
I'm having an issue with implementing a change on specific files in a text file. I have looped over the lines and identified the ones starting with a specific character (N2).

I'm trying to wrap a paragraph so it only allows for 100 characters per line for the abstract of this output from an online source, numerous abstracts are contained in the file all starting with N2 prefixed to the string.

The information appears as separate lines in the text file, ForEoin.txt:

TY  - JOUR
ID  - 31513460
T1  - Systematic Review: Clinical Metabolomics to Forecast Outcomes in Liver Transplantation Surgery.
A1  - Attard, Joseph A
A1  - Dunn, Warwick B
A1  - Mergental, Hynek
A1  - Mirza, Darius F
A1  - Afford, Simon C
A1  - Perera, M Thamara P R
Y1  - 2019//
N2  - Liver transplantation is an effective intervention for end-stage liver disease, fulminant hepatic failure, and early hepatocellular carcinoma. Yet, there is marked patient-to-patient variation in liver transplantation outcomes. This calls for novel diagnostics to enable rational deployment of donor livers. Metabolomics is a postgenomic high-throughput systems biology approach to diagnostic innovation in clinical medicine. We report here an original systematic review of the metabolomic studies that have identified putative biomarkers in the context of liver transplantation. Eighteen studies met the inclusion criteria that involved sampling of blood (n = 4), dialysate fluid (n = 4), bile (n = 5), and liver tissue (n = 5). Metabolites of amino acid and nitrogen metabolism, anaerobic glycolysis, lipid breakdown products, and bile acid metabolism were significantly different in transplanted livers with and without graft dysfunction. However, criteria for defining the graft dysfunction varied across studies. This systematic review demonstrates that metabolomics can be deployed in identification of metabolic indicators of graft dysfunction with a view to implicated molecular mechanisms. We conclude the article with a horizon scanning of metabolomics technology in liver transplantation and its future prospects and challenges in research and clinical practice.
KW  - *Biomarkers
KW  - Genotype

So far I have iterated over the lines of the file and called upon the textwrap module to wrap this for me but I cant get my head around writing over the existing lines with this new wrapped lines in the output file.

#!/usr/bin/env python

import textwrap

filename_org = 'ForEoin.txt'
filename_new = 'Eoin_Shortline_v2'

with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)

                wf.write(new_line)

Body:
import textwrap

filename_org = 'ForEoin.txt'
filename_new = 'Eoin_Shortline_v2'

with open(filename_org, 'r') as rf:
    with open(filename_new, 'w') as wf:
        for line in rf:
            if line.startswith("N2"):
                wrapper = textwrap.TextWrapper(width=100)
                new_line = wrapper.fill(text=line)
                wf.write(new_line)
            else:
                wf.write(line)

If the line starts with "N2" do the wrapper and then write it to the file in the else part also you have to right it to the file.