We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
ARM Data API Returns Text when File not Available 
I tried to download gucceilpblhtM1.a0 but it's not available through the webservice due to it being an a0-level file.  Instead the API returned text that was included in the file.  We should put in a check to ensure that these cases are caught and files are not produced.

```
This data file is not available on /data/archive.  To download this file, please an order via Data Discovery. https://adc.arm.gov/discovery
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `act/discovery/get_armfiles.py`
Content:
```
1 """
2 Script for downloading data from ARM's Live Data Webservice
3 
4 """
5 
6 import argparse
7 import json
8 import os
9 import sys
10 from datetime import timedelta
11 
12 try:
13     from urllib.request import urlopen
14 except ImportError:
15     from urllib import urlopen
16 
17 from act.utils import date_parser
18 
19 
20 def download_data(username, token, datastream, startdate, enddate, time=None, output=None):
21     """
22     This tool will help users utilize the ARM Live Data Webservice to download
23     ARM data.
24 
25     Parameters
26     ----------
27     username : str
28         The username to use for logging into the ADC archive.
29     token : str
30         The access token for accessing the ADC archive.
31     datastream : str
32         The name of the datastream to acquire.
33     startdate : str
34         The start date of the data to acquire. Formats accepted are
35         YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, YYYYMMDD, YYYY/MM/DD or
36         any of the previous formats with THH:MM:SS added onto the end
37         (ex. 2020-09-15T12:00:00).
38     enddate : str
39         The end date of the data to acquire. Formats accepted are
40         YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, YYYYMMDD or YYYY/MM/DD, or
41         any of the previous formats with THH:MM:SS added onto the end
42         (ex. 2020-09-15T13:00:00).
43     time: str or None
44         The specific time. Format is HHMMSS. Set to None to download all files
45         in the given date interval.
46     output : str
47         The output directory for the data. Set to None to make a folder in the
48         current working directory with the same name as *datastream* to place
49         the files in.
50 
51     Returns
52     -------
53     files : list
54         Returns list of files retrieved
55 
56     Notes
57     -----
58     This programmatic interface allows users to query and automate
59     machine-to-machine downloads of ARM data. This tool uses a REST URL and
60     specific parameters (saveData, query), user ID and access token, a
61     datastream name, a start date, and an end date, and data files matching
62     the criteria will be returned to the user and downloaded.
63 
64     By using this web service, users can setup cron jobs and automatically
65     download data from /data/archive into their workspace. This will also
66     eliminate the manual step of following a link in an email to download data.
67     All other data files, which are not on the spinning
68     disk (on HPSS), will have to go through the regular ordering process.
69     More information about this REST API and tools can be found on `ARM Live
70     <https://adc.arm.gov/armlive/#scripts>`_.
71 
72     To login/register for an access token click `here
73     <https://adc.arm.gov/armlive/livedata/home>`_.
74 
75     Author: Michael Giansiracusa
76     Email: giansiracumt@ornl.gov
77 
78     Web Tools Contact: Ranjeet Devarakonda zzr@ornl.gov
79 
80     Examples
81     --------
82     This code will download the netCDF files from the sgpmetE13.b1 datastream
83     and place them in a directory named sgpmetE13.b1. The data from 14 Jan to
84     20 Jan 2017 will be downloaded. Replace *userName* and *XXXXXXXXXXXXXXXX*
85     with your username and token for ARM Data Discovery. See the Notes for
86     information on how to obtain a username and token.
87 
88     .. code-block:: python
89 
90         act.discovery.download_data(
91             "userName", "XXXXXXXXXXXXXXXX", "sgpmetE13.b1", "2017-01-14", "2017-01-20"
92         )
93 
94     """
95     # default start and end are empty
96     start, end = '', ''
97     # start and end strings for query_url are constructed
98     # if the arguments were provided
99     if startdate:
100         start_datetime = date_parser(startdate, return_datetime=True)
101         start = start_datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
102         start = f'&start={start}'
103     if enddate:
104         end_datetime = date_parser(enddate, return_datetime=True)
105         # If the start and end date are the same, and a day to the end date
106         if start_datetime == end_datetime:
107             end_datetime += timedelta(hours=23, minutes=59, seconds=59)
108         end = end_datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
109         end = f'&end={end}'
110     # build the url to query the web service using the arguments provided
111     query_url = (
112         'https://adc.arm.gov/armlive/livedata/query?' + 'user={0}&ds={1}{2}{3}&wt=json'
113     ).format(':'.join([username, token]), datastream, start, end)
114 
115     # get url response, read the body of the message,
116     # and decode from bytes type to utf-8 string
117     response_body = urlopen(query_url).read().decode('utf-8')
118     # if the response is an html doc, then there was an error with the user
119     if response_body[1:14] == '!DOCTYPE html':
120         raise ConnectionRefusedError('Error with user. Check username or token.')
121 
122     # parse into json object
123     response_body_json = json.loads(response_body)
124 
125     # construct output directory
126     if output:
127         # output files to directory specified
128         output_dir = os.path.join(output)
129     else:
130         # if no folder given, add datastream folder
131         # to current working dir to prevent file mix-up
132         output_dir = os.path.join(os.getcwd(), datastream)
133 
134     # not testing, response is successful and files were returned
135     if response_body_json is None:
136         print('ARM Data Live Webservice does not appear to be functioning')
137         return []
138 
139     num_files = len(response_body_json['files'])
140     file_names = []
141     if response_body_json['status'] == 'success' and num_files > 0:
142         for fname in response_body_json['files']:
143             if time is not None:
144                 if time not in fname:
145                     continue
146             print(f'[DOWNLOADING] {fname}')
147             # construct link to web service saveData function
148             save_data_url = (
149                 'https://adc.arm.gov/armlive/livedata/' + 'saveData?user={0}&file={1}'
150             ).format(':'.join([username, token]), fname)
151             output_file = os.path.join(output_dir, fname)
152             # make directory if it doesn't exist
153             if not os.path.isdir(output_dir):
154                 os.makedirs(output_dir)
155             # create file and write bytes to file
156             with open(output_file, 'wb') as open_bytes_file:
157                 open_bytes_file.write(urlopen(save_data_url).read())
158             file_names.append(output_file)
159     else:
160         print(
161             'No files returned or url status error.\n' 'Check datastream name, start, and end date.'
162         )
163 
164     return file_names
165
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/act/discovery/get_armfiles.py b/act/discovery/get_armfiles.py
--- a/act/discovery/get_armfiles.py
+++ b/act/discovery/get_armfiles.py
@@ -4,6 +4,7 @@
 """
 
 import argparse
+import contextlib
 import json
 import os
 import sys
@@ -143,17 +144,28 @@
             if time is not None:
                 if time not in fname:
                     continue
-            print(f'[DOWNLOADING] {fname}')
             # construct link to web service saveData function
             save_data_url = (
                 'https://adc.arm.gov/armlive/livedata/' + 'saveData?user={0}&file={1}'
             ).format(':'.join([username, token]), fname)
             output_file = os.path.join(output_dir, fname)
+
+            # if datastream is not in data archive, return error
+            with contextlib.closing(urlopen(save_data_url).read().decode().lower()) as check:
+                if 'this data file is not available' in check:
+                    raise OSError(
+                        "The datastream '" + datastream
+                        + "' is not available on /data/archive. To download "
+                        + "this file, place an order via Data Discovery. "
+                        + "https://adc.arm.gov/discovery")
+
             # make directory if it doesn't exist
             if not os.path.isdir(output_dir):
                 os.makedirs(output_dir)
+
             # create file and write bytes to file
             with open(output_file, 'wb') as open_bytes_file:
+                print(f'[DOWNLOADING] {fname}')
                 open_bytes_file.write(urlopen(save_data_url).read())
             file_names.append(output_file)
     else:

{"golden_diff": "diff --git a/act/discovery/get_armfiles.py b/act/discovery/get_armfiles.py\n--- a/act/discovery/get_armfiles.py\n+++ b/act/discovery/get_armfiles.py\n@@ -4,6 +4,7 @@\n \"\"\"\n \n import argparse\n+import contextlib\n import json\n import os\n import sys\n@@ -143,17 +144,28 @@\n             if time is not None:\n                 if time not in fname:\n                     continue\n-            print(f'[DOWNLOADING] {fname}')\n             # construct link to web service saveData function\n             save_data_url = (\n                 'https://adc.arm.gov/armlive/livedata/' + 'saveData?user={0}&file={1}'\n             ).format(':'.join([username, token]), fname)\n             output_file = os.path.join(output_dir, fname)\n+\n+            # if datastream is not in data archive, return error\n+            with contextlib.closing(urlopen(save_data_url).read().decode().lower()) as check:\n+                if 'this data file is not available' in check:\n+                    raise OSError(\n+                        \"The datastream '\" + datastream\n+                        + \"' is not available on /data/archive. To download \"\n+                        + \"this file, place an order via Data Discovery. \"\n+                        + \"https://adc.arm.gov/discovery\")\n+\n             # make directory if it doesn't exist\n             if not os.path.isdir(output_dir):\n                 os.makedirs(output_dir)\n+\n             # create file and write bytes to file\n             with open(output_file, 'wb') as open_bytes_file:\n+                print(f'[DOWNLOADING] {fname}')\n                 open_bytes_file.write(urlopen(save_data_url).read())\n             file_names.append(output_file)\n     else:\n", "issue": "ARM Data API Returns Text when File not Available \nI tried to download gucceilpblhtM1.a0 but it's not available through the webservice due to it being an a0-level file.  Instead the API returned text that was included in the file.  We should put in a check to ensure that these cases are caught and files are not produced.\r\n\r\n```\r\nThis data file is not available on /data/archive.  To download this file, please an order via Data Discovery. https://adc.arm.gov/discovery\r\n```\n", "before_files": [{"content": "\"\"\"\nScript for downloading data from ARM's Live Data Webservice\n\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport sys\nfrom datetime import timedelta\n\ntry:\n    from urllib.request import urlopen\nexcept ImportError:\n    from urllib import urlopen\n\nfrom act.utils import date_parser\n\n\ndef download_data(username, token, datastream, startdate, enddate, time=None, output=None):\n    \"\"\"\n    This tool will help users utilize the ARM Live Data Webservice to download\n    ARM data.\n\n    Parameters\n    ----------\n    username : str\n        The username to use for logging into the ADC archive.\n    token : str\n        The access token for accessing the ADC archive.\n    datastream : str\n        The name of the datastream to acquire.\n    startdate : str\n        The start date of the data to acquire. Formats accepted are\n        YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, YYYYMMDD, YYYY/MM/DD or\n        any of the previous formats with THH:MM:SS added onto the end\n        (ex. 2020-09-15T12:00:00).\n    enddate : str\n        The end date of the data to acquire. Formats accepted are\n        YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, YYYYMMDD or YYYY/MM/DD, or\n        any of the previous formats with THH:MM:SS added onto the end\n        (ex. 2020-09-15T13:00:00).\n    time: str or None\n        The specific time. Format is HHMMSS. Set to None to download all files\n        in the given date interval.\n    output : str\n        The output directory for the data. Set to None to make a folder in the\n        current working directory with the same name as *datastream* to place\n        the files in.\n\n    Returns\n    -------\n    files : list\n        Returns list of files retrieved\n\n    Notes\n    -----\n    This programmatic interface allows users to query and automate\n    machine-to-machine downloads of ARM data. This tool uses a REST URL and\n    specific parameters (saveData, query), user ID and access token, a\n    datastream name, a start date, and an end date, and data files matching\n    the criteria will be returned to the user and downloaded.\n\n    By using this web service, users can setup cron jobs and automatically\n    download data from /data/archive into their workspace. This will also\n    eliminate the manual step of following a link in an email to download data.\n    All other data files, which are not on the spinning\n    disk (on HPSS), will have to go through the regular ordering process.\n    More information about this REST API and tools can be found on `ARM Live\n    <https://adc.arm.gov/armlive/#scripts>`_.\n\n    To login/register for an access token click `here\n    <https://adc.arm.gov/armlive/livedata/home>`_.\n\n    Author: Michael Giansiracusa\n    Email: giansiracumt@ornl.gov\n\n    Web Tools Contact: Ranjeet Devarakonda zzr@ornl.gov\n\n    Examples\n    --------\n    This code will download the netCDF files from the sgpmetE13.b1 datastream\n    and place them in a directory named sgpmetE13.b1. The data from 14 Jan to\n    20 Jan 2017 will be downloaded. Replace *userName* and *XXXXXXXXXXXXXXXX*\n    with your username and token for ARM Data Discovery. See the Notes for\n    information on how to obtain a username and token.\n\n    .. code-block:: python\n\n        act.discovery.download_data(\n            \"userName\", \"XXXXXXXXXXXXXXXX\", \"sgpmetE13.b1\", \"2017-01-14\", \"2017-01-20\"\n        )\n\n    \"\"\"\n    # default start and end are empty\n    start, end = '', ''\n    # start and end strings for query_url are constructed\n    # if the arguments were provided\n    if startdate:\n        start_datetime = date_parser(startdate, return_datetime=True)\n        start = start_datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'\n        start = f'&start={start}'\n    if enddate:\n        end_datetime = date_parser(enddate, return_datetime=True)\n        # If the start and end date are the same, and a day to the end date\n        if start_datetime == end_datetime:\n            end_datetime += timedelta(hours=23, minutes=59, seconds=59)\n        end = end_datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'\n        end = f'&end={end}'\n    # build the url to query the web service using the arguments provided\n    query_url = (\n        'https://adc.arm.gov/armlive/livedata/query?' + 'user={0}&ds={1}{2}{3}&wt=json'\n    ).format(':'.join([username, token]), datastream, start, end)\n\n    # get url response, read the body of the message,\n    # and decode from bytes type to utf-8 string\n    response_body = urlopen(query_url).read().decode('utf-8')\n    # if the response is an html doc, then there was an error with the user\n    if response_body[1:14] == '!DOCTYPE html':\n        raise ConnectionRefusedError('Error with user. Check username or token.')\n\n    # parse into json object\n    response_body_json = json.loads(response_body)\n\n    # construct output directory\n    if output:\n        # output files to directory specified\n        output_dir = os.path.join(output)\n    else:\n        # if no folder given, add datastream folder\n        # to current working dir to prevent file mix-up\n        output_dir = os.path.join(os.getcwd(), datastream)\n\n    # not testing, response is successful and files were returned\n    if response_body_json is None:\n        print('ARM Data Live Webservice does not appear to be functioning')\n        return []\n\n    num_files = len(response_body_json['files'])\n    file_names = []\n    if response_body_json['status'] == 'success' and num_files > 0:\n        for fname in response_body_json['files']:\n            if time is not None:\n                if time not in fname:\n                    continue\n            print(f'[DOWNLOADING] {fname}')\n            # construct link to web service saveData function\n            save_data_url = (\n                'https://adc.arm.gov/armlive/livedata/' + 'saveData?user={0}&file={1}'\n            ).format(':'.join([username, token]), fname)\n            output_file = os.path.join(output_dir, fname)\n            # make directory if it doesn't exist\n            if not os.path.isdir(output_dir):\n                os.makedirs(output_dir)\n            # create file and write bytes to file\n            with open(output_file, 'wb') as open_bytes_file:\n                open_bytes_file.write(urlopen(save_data_url).read())\n            file_names.append(output_file)\n    else:\n        print(\n            'No files returned or url status error.\\n' 'Check datastream name, start, and end date.'\n        )\n\n    return file_names\n", "path": "act/discovery/get_armfiles.py"}], "after_files": [{"content": "\"\"\"\nScript for downloading data from ARM's Live Data Webservice\n\n\"\"\"\n\nimport argparse\nimport contextlib\nimport json\nimport os\nimport sys\nfrom datetime import timedelta\n\ntry:\n    from urllib.request import urlopen\nexcept ImportError:\n    from urllib import urlopen\n\nfrom act.utils import date_parser\n\n\ndef download_data(username, token, datastream, startdate, enddate, time=None, output=None):\n    \"\"\"\n    This tool will help users utilize the ARM Live Data Webservice to download\n    ARM data.\n\n    Parameters\n    ----------\n    username : str\n        The username to use for logging into the ADC archive.\n    token : str\n        The access token for accessing the ADC archive.\n    datastream : str\n        The name of the datastream to acquire.\n    startdate : str\n        The start date of the data to acquire. Formats accepted are\n        YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, YYYYMMDD, YYYY/MM/DD or\n        any of the previous formats with THH:MM:SS added onto the end\n        (ex. 2020-09-15T12:00:00).\n    enddate : str\n        The end date of the data to acquire. Formats accepted are\n        YYYY-MM-DD, DD.MM.YYYY, DD/MM/YYYY, YYYYMMDD or YYYY/MM/DD, or\n        any of the previous formats with THH:MM:SS added onto the end\n        (ex. 2020-09-15T13:00:00).\n    time: str or None\n        The specific time. Format is HHMMSS. Set to None to download all files\n        in the given date interval.\n    output : str\n        The output directory for the data. Set to None to make a folder in the\n        current working directory with the same name as *datastream* to place\n        the files in.\n\n    Returns\n    -------\n    files : list\n        Returns list of files retrieved\n\n    Notes\n    -----\n    This programmatic interface allows users to query and automate\n    machine-to-machine downloads of ARM data. This tool uses a REST URL and\n    specific parameters (saveData, query), user ID and access token, a\n    datastream name, a start date, and an end date, and data files matching\n    the criteria will be returned to the user and downloaded.\n\n    By using this web service, users can setup cron jobs and automatically\n    download data from /data/archive into their workspace. This will also\n    eliminate the manual step of following a link in an email to download data.\n    All other data files, which are not on the spinning\n    disk (on HPSS), will have to go through the regular ordering process.\n    More information about this REST API and tools can be found on `ARM Live\n    <https://adc.arm.gov/armlive/#scripts>`_.\n\n    To login/register for an access token click `here\n    <https://adc.arm.gov/armlive/livedata/home>`_.\n\n    Author: Michael Giansiracusa\n    Email: giansiracumt@ornl.gov\n\n    Web Tools Contact: Ranjeet Devarakonda zzr@ornl.gov\n\n    Examples\n    --------\n    This code will download the netCDF files from the sgpmetE13.b1 datastream\n    and place them in a directory named sgpmetE13.b1. The data from 14 Jan to\n    20 Jan 2017 will be downloaded. Replace *userName* and *XXXXXXXXXXXXXXXX*\n    with your username and token for ARM Data Discovery. See the Notes for\n    information on how to obtain a username and token.\n\n    .. code-block:: python\n\n        act.discovery.download_data(\n            \"userName\", \"XXXXXXXXXXXXXXXX\", \"sgpmetE13.b1\", \"2017-01-14\", \"2017-01-20\"\n        )\n\n    \"\"\"\n    # default start and end are empty\n    start, end = '', ''\n    # start and end strings for query_url are constructed\n    # if the arguments were provided\n    if startdate:\n        start_datetime = date_parser(startdate, return_datetime=True)\n        start = start_datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'\n        start = f'&start={start}'\n    if enddate:\n        end_datetime = date_parser(enddate, return_datetime=True)\n        # If the start and end date are the same, and a day to the end date\n        if start_datetime == end_datetime:\n            end_datetime += timedelta(hours=23, minutes=59, seconds=59)\n        end = end_datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'\n        end = f'&end={end}'\n    # build the url to query the web service using the arguments provided\n    query_url = (\n        'https://adc.arm.gov/armlive/livedata/query?' + 'user={0}&ds={1}{2}{3}&wt=json'\n    ).format(':'.join([username, token]), datastream, start, end)\n\n    # get url response, read the body of the message,\n    # and decode from bytes type to utf-8 string\n    response_body = urlopen(query_url).read().decode('utf-8')\n    # if the response is an html doc, then there was an error with the user\n    if response_body[1:14] == '!DOCTYPE html':\n        raise ConnectionRefusedError('Error with user. Check username or token.')\n\n    # parse into json object\n    response_body_json = json.loads(response_body)\n\n    # construct output directory\n    if output:\n        # output files to directory specified\n        output_dir = os.path.join(output)\n    else:\n        # if no folder given, add datastream folder\n        # to current working dir to prevent file mix-up\n        output_dir = os.path.join(os.getcwd(), datastream)\n\n    # not testing, response is successful and files were returned\n    if response_body_json is None:\n        print('ARM Data Live Webservice does not appear to be functioning')\n        return []\n\n    num_files = len(response_body_json['files'])\n    file_names = []\n    if response_body_json['status'] == 'success' and num_files > 0:\n        for fname in response_body_json['files']:\n            if time is not None:\n                if time not in fname:\n                    continue\n            # construct link to web service saveData function\n            save_data_url = (\n                'https://adc.arm.gov/armlive/livedata/' + 'saveData?user={0}&file={1}'\n            ).format(':'.join([username, token]), fname)\n            output_file = os.path.join(output_dir, fname)\n\n            # if datastream is not in data archive, return error\n            with contextlib.closing(urlopen(save_data_url).read().decode().lower()) as check:\n                if 'this data file is not available' in check:\n                    raise OSError(\n                        \"The datastream '\" + datastream\n                        + \"' is not available on /data/archive. To download \"\n                        + \"this file, place an order via Data Discovery. \"\n                        + \"https://adc.arm.gov/discovery\")\n\n            # make directory if it doesn't exist\n            if not os.path.isdir(output_dir):\n                os.makedirs(output_dir)\n\n            # create file and write bytes to file\n            with open(output_file, 'wb') as open_bytes_file:\n                print(f'[DOWNLOADING] {fname}')\n                open_bytes_file.write(urlopen(save_data_url).read())\n            file_names.append(output_file)\n    else:\n        print(\n            'No files returned or url status error.\\n' 'Check datastream name, start, and end date.'\n        )\n\n    return file_names\n", "path": "act/discovery/get_armfiles.py"}]}