after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def reload(self):
if self.closed:
return
self.reader.buffer.wait_free()
log.debug(
"Reloading manifest ({0}:{1})".format(
self.reader.representation_id, self.reader.mime_type
)
)
res = self.session.http.get(self.mpd.url, exception=StreamError, **self.stream.args)
new_mpd = MPD(
self.session.http.xml(res, ignore_ns=True),
base_url=self.mpd.base_url,
url=self.mpd.url,
timelines=self.mpd.timelines,
)
new_rep = self.get_representation(
new_mpd, self.reader.representation_id, self.reader.mime_type
)
with freeze_timeline(new_mpd):
changed = len(list(itertools.islice(new_rep.segments(), 1))) > 0
if changed:
self.mpd = new_mpd
return changed
|
def reload(self):
if self.closed:
return
self.reader.buffer.wait_free()
log.debug(
"Reloading manifest ({0}:{1})".format(
self.reader.representation_id, self.reader.mime_type
)
)
res = self.session.http.get(self.mpd.url, exception=StreamError)
new_mpd = MPD(
self.session.http.xml(res, ignore_ns=True),
base_url=self.mpd.base_url,
url=self.mpd.url,
timelines=self.mpd.timelines,
)
new_rep = self.get_representation(
new_mpd, self.reader.representation_id, self.reader.mime_type
)
with freeze_timeline(new_mpd):
changed = len(list(itertools.islice(new_rep.segments(), 1))) > 0
if changed:
self.mpd = new_mpd
return changed
|
https://github.com/streamlink/streamlink/issues/2291
|
$ streamlink https://www.tf1.fr/lci/direct 576p_dash
[cli][debug] OS: Linux
[cli][debug] Python: 3.6.7
[cli][debug] Streamlink: 1.0.0+3.g4100688.dirty
[cli][debug] Requests(2.21.0), Socks(1.6.7), Websocket(0.54.0)
[cli][info] Found matching plugin tf1 for URL https://www.tf1.fr/lci/direct
[plugin.tf1][debug] Found channel lci
[plugin.tf1][debug] Got dash stream https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
[utils.l10n][debug] Language code: en_US
[stream.dash][debug] Available languages for DASH audio streams: NONE (using: n/a)
[plugin.tf1][debug] Got hls stream https://lci-hls-live-ssl.tf1.fr/lci/1/hls/master_4000000.m3u8?e=&st=
[utils.l10n][debug] Language code: en_US
[cli][info] Available streams: 234p_dash, 360p_dash, 576p_dash, 234p (worst), 360p, 576p_alt, 576p, 720p (best)
[cli][info] Opening stream: 576p_dash (dash)
[stream.dash][debug] Opening DASH reader for: live_1828_H264 (video/mp4)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_1828_H264))
[stream.dash][debug] Reloading manifest (live_1828_H264:video/mp4)
[stream.dash][debug] Opening DASH reader for: live_2328_AAC (audio/mp4)
[stream.dash_manifest][debug] Generating segment timeline for dynamic playlist (id=live_2328_AAC))
[stream.dash][debug] Reloading manifest (live_2328_AAC:audio/mp4)
[stream.mp4mux-ffmpeg][debug] ffmpeg command: /usr/bin/ffmpeg -nostats -y -i /tmp/ffmpeg-2811-460 -i /tmp/ffmpeg-2811-532 -c:v copy -c:a copy -copyts -f matroska pipe:1
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-460
[stream.ffmpegmux][debug] Starting copy to pipe: /tmp/ffmpeg-2811-532
[cli][debug] Pre-buffering 8192 bytes
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/init.m4v complete
Exception in thread Thread-DASHStreamWorker:
Traceback (most recent call last):
File "src/streamlink/plugin/api/http_session.py", line 166, in request
res.raise_for_status()
File "env/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "src/streamlink/stream/segmented.py", line 59, in run
for segment in self.iter_segments():
File "src/streamlink/stream/dash.py", line 97, in iter_segments
if not self.reload():
File "src/streamlink/stream/dash.py", line 111, in reload
res = self.session.http.get(self.mpd.url, exception=StreamError)
File "env/lib/python3.6/site-packages/requests/sessions.py", line 546, in get
return self.request('GET', url, **kwargs)
File "src/streamlink/plugin/api/http_session.py", line 175, in request
raise err
streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)
Exception in thread Thread-DASHStreamWorker:
Traceback (most recent call last):
File "src/streamlink/plugin/api/http_session.py", line 166, in request
res.raise_for_status()
File "env/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "src/streamlink/stream/segmented.py", line 59, in run
for segment in self.iter_segments():
File "src/streamlink/stream/dash.py", line 97, in iter_segments
if not self.reload():
File "src/streamlink/stream/dash.py", line 111, in reload
res = self.session.http.get(self.mpd.url, exception=StreamError)
File "env/lib/python3.6/site-packages/requests/sessions.py", line 546, in get
return self.request('GET', url, **kwargs)
File "src/streamlink/plugin/api/http_session.py", line 175, in request
raise err
streamlink.exceptions.StreamError: Unable to open URL: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=
(403 Client Error: Forbidden for url: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2000000.mpd?e=&st=)
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/init.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65796000.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65800000.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_2328/65804000.m4a complete
[stream.dash][debug] Download of segment: https://lci-das-live-ssl.tf1.fr/lci/1/dash/live_1828/65792000.m4v complete
|
requests.exceptions.HTTPError
|
def _get_streams(self):
match = _url_re.match(self.url)
if not match:
return
channel, media_id = match.group("channel", "media_id")
self.logger.debug(
"Matched URL: channel={0}, media_id={1}".format(channel, media_id)
)
if not media_id:
res = http.get(LIVE_API.format(channel))
livestream = http.json(res, schema=_live_schema)
if livestream.get("media_hosted_media"):
hosted = _live_schema.validate(livestream["media_hosted_media"])
self.logger.info(
"{0} is hosting {1}",
livestream["media_user_name"],
hosted["media_user_name"],
)
livestream = hosted
if not livestream["media_is_live"]:
return
media_id = livestream["media_id"]
media_type = "live"
else:
media_type = "video"
res = http.get(PLAYER_API.format(media_type, media_id))
player = http.json(res, schema=_player_schema)
if media_type == "live":
return self._get_live_streams(player)
else:
return self._get_video_streams(player)
|
def _get_streams(self):
match = _url_re.match(self.url)
if not match:
return
channel, media_id = match.group("channel", "media_id")
self.logger.debug(
"Matched URL: channel={0}, media_id={1}".format(channel, media_id)
)
if not media_id:
res = http.get(LIVE_API.format(channel))
livestream = http.json(res, schema=_live_schema)
if livestream["media_hosted_media"]:
hosted = _live_schema.validate(livestream["media_hosted_media"])
self.logger.info(
"{0} is hosting {1}",
livestream["media_user_name"],
hosted["media_user_name"],
)
livestream = hosted
if not livestream["media_is_live"]:
return
media_id = livestream["media_id"]
media_type = "live"
else:
media_type = "video"
res = http.get(PLAYER_API.format(media_type, media_id))
player = http.json(res, schema=_player_schema)
if media_type == "live":
return self._get_live_streams(player)
else:
return self._get_video_streams(player)
|
https://github.com/streamlink/streamlink/issues/1078
|
streamlink smashcast.tv/greatvaluesmash best
[cli][info] Found matching plugin hitbox for URL smashcast.tv/greatvaluesmash
Traceback (most recent call last):
File "C:\Program Files (x86)\Streamlink\bin\streamlink-script.py", line 15, in
<module>
main()
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 103
8, in main
handle_url()
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 482
, in handle_url
streams = fetch_streams(plugin)
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 394
, in fetch_streams
sorting_excludes=args.stream_sorting_excludes)
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugin\plugin.py", lin
e 345, in get_streams
return self.streams(*args, **kwargs)
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugin\plugin.py", lin
e 248, in streams
ostreams = self._get_streams()
File "C:\Program Files (x86)\Streamlink\pkgs\streamlink\plugins\hitbox.py", li
ne 181, in _get_streams
if livestream["media_hosted_media"]:
KeyError: 'media_hosted_media'
|
KeyError
|
def close(self, client_only=False):
if self.conn:
self.conn.close()
if not client_only:
try:
self.socket.shutdown(2)
except (OSError, socket.error):
pass
self.socket.close()
|
def close(self, client_only=False):
if self.conn:
self.conn.close()
if not client_only:
try:
self.socket.shutdown(2)
except OSError:
pass
self.socket.close()
|
https://github.com/streamlink/streamlink/issues/919
|
[cli][info] Closing currently open stream...
Traceback (most recent call last):
File "/usr/local/bin/streamlink", line 11, in <module>
load_entry_point('streamlink==0.6.0', 'console_scripts', 'streamlink')()
File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 1027, in main
handle_url()
File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 502, in handle_url
handle_stream(plugin, streams, stream_name)
File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 380, in handle_stream
return output_stream_http(plugin, streams)
File "/usr/local/lib/python2.7/site-packages/streamlink_cli/main.py", line 192, in output_stream_http
server.close()
File "/usr/local/lib/python2.7/site-packages/streamlink_cli/utils/http_server.py", line 116, in close
self.socket.shutdown(2)
File "/usr/local/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 57] Socket is not connected
|
socket.error
|
def close(self, client_only=False):
if self.conn:
self.conn.close()
if not client_only:
try:
self.socket.shutdown(2)
except OSError:
pass
self.socket.close()
|
def close(self, client_only=False):
if self.conn:
self.conn.close()
if not client_only:
self.socket.shutdown(2)
self.socket.close()
|
https://github.com/streamlink/streamlink/issues/604
|
[cli][info] Player closed
[cli][info] Stream ended
[cli][info] Closing currently open stream...
Traceback (most recent call last):
File "d:\Program Files (x86)\Streamlink\bin\streamlink-script.py", line 12, in
<module>
main()
File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 952
, in main
handle_url()
File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 499
, in handle_url
handle_stream(plugin, streams, stream_name)
File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 381
, in handle_stream
success = output_stream(stream)
File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\main.py", line 270
, in output_stream
read_stream(stream_fd, output, prebuffer)
File "contextlib.py", line 159, in __exit__
File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\output.py", line 2
8, in close
self._close()
File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\output.py", line 1
58, in _close
self.http.close()
File "d:\Program Files (x86)\Streamlink\pkgs\streamlink_cli\utils\http_server.
py", line 115, in close
self.socket.shutdown(2)
OSError: [WinError 10057] A request to send or receive data was disallowed becau
se the socket is not connected and (when sending on a datagram socket using a se
ndto call) no address was supplied
|
OSError
|
def write(self, sequence, res, chunk_size=8192, retries=None):
retries = retries or self.retries
if retries == 0:
self.logger.error("Failed to open segment {0}", sequence.num)
return
try:
if sequence.segment.key and sequence.segment.key.method != "NONE":
try:
decryptor = self.create_decryptor(sequence.segment.key, sequence.num)
except StreamError as err:
self.logger.error("Failed to create decryptor: {0}", err)
self.close()
return
for chunk in res.iter_content(chunk_size):
# If the input data is not a multiple of 16, cut off any garbage
garbage_len = len(chunk) % 16
if garbage_len:
self.logger.debug(
"Cutting off {0} bytes of garbage before decrypting",
garbage_len,
)
decrypted_chunk = decryptor.decrypt(chunk[:-garbage_len])
else:
decrypted_chunk = decryptor.decrypt(chunk)
self.reader.buffer.write(decrypted_chunk)
else:
for chunk in res.iter_content(chunk_size):
self.reader.buffer.write(chunk)
except StreamError as err:
self.logger.error("Failed to open segment {0}: {1}", sequence.num, err)
return self.write(
sequence,
self.fetch(sequence, retries=self.retries),
chunk_size=chunk_size,
retries=retries - 1,
)
self.logger.debug("Download of segment {0} complete", sequence.num)
|
def write(self, sequence, res, chunk_size=8192):
if sequence.segment.key and sequence.segment.key.method != "NONE":
try:
decryptor = self.create_decryptor(sequence.segment.key, sequence.num)
except StreamError as err:
self.logger.error("Failed to create decryptor: {0}", err)
self.close()
return
for chunk in res.iter_content(chunk_size):
# If the input data is not a multiple of 16, cut off any garbage
garbage_len = len(chunk) % 16
if garbage_len:
self.logger.debug(
"Cutting off {0} bytes of garbage before decrypting", garbage_len
)
decrypted_chunk = decryptor.decrypt(chunk[:-garbage_len])
else:
decrypted_chunk = decryptor.decrypt(chunk)
self.reader.buffer.write(decrypted_chunk)
else:
for chunk in res.iter_content(chunk_size):
self.reader.buffer.write(chunk)
self.logger.debug("Download of segment {0} complete", sequence.num)
|
https://github.com/streamlink/streamlink/issues/332
|
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 232, in _error_catcher
yield
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 314, in read
data = self._fp.read(amt)
File "/usr/local/lib/python3.5/http/client.py", line 448, in read
n = self.readinto(b)
File "/usr/local/lib/python3.5/http/client.py", line 488, in readinto
n = self.fp.readinto(b)
File "/usr/local/lib/python3.5/socket.py", line 575, in readinto
return self._sock.recv_into(b)
File "/usr/local/lib/python3.5/ssl.py", line 929, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/lib/python3.5/ssl.py", line 791, in read
return self._sslobj.read(len, buffer)
File "/usr/local/lib/python3.5/ssl.py", line 575, in read
v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/requests/models.py", line 676, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 357, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 324, in read
flush_decoder = True
File "/usr/local/lib/python3.5/contextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "/usr/local/lib/python3.5/site-packages/requests/packages/urllib3/response.py", line 237, in _error_catcher
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='video-edge-835ef0.ord02.hls.ttvnw.net', port=443): Read timed out.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.5/site-packages/streamlink/stream/segmented.py", line 160, in run
self.write(segment, result)
File "/usr/local/lib/python3.5/site-packages/streamlink/stream/hls.py", line 111, in write
for chunk in res.iter_content(chunk_size):
File "/usr/local/lib/python3.5/site-packages/requests/models.py", line 683, in generate
raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='video-edge-835ef0.ord02.hls.ttvnw.net', port=443): Read timed out.
|
requests.packages.urllib3.exceptions.ReadTimeoutError
|
def write(self, vals):
res = super(OpStudent, self).write(vals)
if vals.get("parent_ids", False):
user_ids = []
if self.parent_ids:
for parent in self.parent_ids:
if parent.user_id:
user_ids = [x.user_id.id for x in parent.student_ids if x.user_id]
parent.user_id.child_ids = [(6, 0, user_ids)]
else:
user_ids = self.env["res.users"].search(
[("child_ids", "in", self.user_id.id)]
)
for user_id in user_ids:
child_ids = user_id.child_ids.ids
child_ids.remove(self.user_id.id)
user_id.child_ids = [(6, 0, child_ids)]
if vals.get("user_id", False):
for parent_id in self.parent_ids:
if parent_id.user_id:
child_ids = parent_id.user_id.child_ids.ids
child_ids.append(vals["user_id"])
parent_id.name.user_id.child_ids = [(6, 0, child_ids)]
self.clear_caches()
return res
|
def write(self, vals):
res = super(OpStudent, self).write(vals)
if vals.get("parent_ids", False):
user_ids = []
if self.parent_ids:
for parent in self.parent_ids:
if parent.user_id:
user_ids = [x.user_id.id for x in parent.student_ids if x.user_id]
parent.user_id.child_ids = [(6, 0, user_ids)]
else:
user_ids = self.env["res.users"].search(
[("child_ids", "in", self.user_id.id)]
)
for user_id in user_ids:
child_ids = user_id.child_ids.ids
child_ids.remove(self.user_id.id)
user_id.child_ids = [(6, 0, child_ids)]
if vals.get("user_id", False):
for parent_id in self.parent_ids:
child_ids = parent_id.user_id.child_ids.ids
child_ids.append(vals["user_id"])
parent_id.name.user_id.child_ids = [(6, 0, child_ids)]
self.clear_caches()
return res
|
https://github.com/openeducat/openeducat_erp/issues/302
|
Traceback (most recent call last):
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/models.py", line 4718, in ensure_one
_id, = self._ids
ValueError: not enough values to unpack (expected 1, got 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py", line 656, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py", line 314, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/tools/pycompat.py", line 87, in reraise
raise value
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py", line 698, in dispatch
result = self._call_function(**self.params)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py", line 346, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/service/model.py", line 97, in wrapper
return f(dbname, *args, **kwargs)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py", line 339, in checked_call
result = self.endpoint(*a, **kw)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py", line 941, in __call__
return self.method(*args, **kw)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/http.py", line 519, in response_wrap
response = f(*args, **kw)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/addons/web/controllers/main.py", line 966, in call_button
action = self._call_kw(model, method, args, {})
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/addons/web/controllers/main.py", line 954, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/api.py", line 749, in call_kw
return _call_kw_multi(method, model, args, kwargs)
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/api.py", line 736, in _call_kw_multi
result = method(recs, *args, **kwargs)
File "/media/linux_data/progetti/odoo/odoo12-dev/openeducat/openeducat_core/models/student.py", line 118, in create_student_user
record.user_id = user_id
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/fields.py", line 1024, in __set__
record.write({self.name: write_value})
File "/media/linux_data/progetti/odoo/odoo12-dev/openeducat/openeducat_parent/models/parent.py", line 134, in write
parent_id.name.user_id.child_ids = [(6, 0, child_ids)]
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/fields.py", line 1000, in __set__
record.ensure_one()
File "/media/linux_data/progetti/odoo/odoo12-dev/OCB/odoo/models.py", line 4721, in ensure_one
raise ValueError("Expected singleton: %s" % self)
ValueError: Expected singleton: res.users()
|
ValueError
|
def parse_exif_values(self, _path_file):
# Disable exifread log
logging.getLogger("exifread").setLevel(logging.CRITICAL)
with open(_path_file, "rb") as f:
tags = exifread.process_file(f, details=False)
try:
if "Image Make" in tags:
try:
self.camera_make = tags["Image Make"].values
except UnicodeDecodeError:
log.ODM_WARNING("EXIF Image Make might be corrupted")
self.camera_make = "unknown"
if "Image Model" in tags:
try:
self.camera_model = tags["Image Model"].values
except UnicodeDecodeError:
log.ODM_WARNING("EXIF Image Model might be corrupted")
self.camera_model = "unknown"
if "GPS GPSAltitude" in tags:
self.altitude = self.float_value(tags["GPS GPSAltitude"])
if (
"GPS GPSAltitudeRef" in tags
and self.int_value(tags["GPS GPSAltitudeRef"]) > 0
):
self.altitude *= -1
if "GPS GPSLatitude" in tags and "GPS GPSLatitudeRef" in tags:
self.latitude = self.dms_to_decimal(
tags["GPS GPSLatitude"], tags["GPS GPSLatitudeRef"]
)
if "GPS GPSLongitude" in tags and "GPS GPSLongitudeRef" in tags:
self.longitude = self.dms_to_decimal(
tags["GPS GPSLongitude"], tags["GPS GPSLongitudeRef"]
)
except IndexError as e:
log.ODM_WARNING(
"Cannot read basic EXIF tags for %s: %s" % (_path_file, str(e))
)
try:
if "Image Tag 0xC61A" in tags:
self.black_level = self.list_values(tags["Image Tag 0xC61A"])
elif "BlackLevel" in tags:
self.black_level = self.list_values(tags["BlackLevel"])
if "EXIF ExposureTime" in tags:
self.exposure_time = self.float_value(tags["EXIF ExposureTime"])
if "EXIF FNumber" in tags:
self.fnumber = self.float_value(tags["EXIF FNumber"])
if "EXIF ISOSpeed" in tags:
self.iso_speed = self.int_value(tags["EXIF ISOSpeed"])
elif "EXIF PhotographicSensitivity" in tags:
self.iso_speed = self.int_value(tags["EXIF PhotographicSensitivity"])
elif "EXIF ISOSpeedRatings" in tags:
self.iso_speed = self.int_value(tags["EXIF ISOSpeedRatings"])
if "Image BitsPerSample" in tags:
self.bits_per_sample = self.int_value(tags["Image BitsPerSample"])
if "EXIF DateTimeOriginal" in tags:
str_time = tags["EXIF DateTimeOriginal"].values
utc_time = datetime.strptime(str_time, "%Y:%m:%d %H:%M:%S")
subsec = 0
if "EXIF SubSecTime" in tags:
subsec = self.int_value(tags["EXIF SubSecTime"])
negative = 1.0
if subsec < 0:
negative = -1.0
subsec *= -1.0
subsec = float("0.{}".format(int(subsec)))
subsec *= negative
ms = subsec * 1e3
utc_time += timedelta(milliseconds=ms)
timezone = pytz.timezone("UTC")
epoch = timezone.localize(datetime.utcfromtimestamp(0))
self.utc_time = (
timezone.localize(utc_time) - epoch
).total_seconds() * 1000.0
except Exception as e:
log.ODM_WARNING(
"Cannot read extended EXIF tags for %s: %s" % (_path_file, str(e))
)
# Extract XMP tags
f.seek(0)
xmp = self.get_xmp(f)
for tags in xmp:
try:
band_name = self.get_xmp_tag(
tags, ["Camera:BandName", "@Camera:BandName"]
)
if band_name is not None:
self.band_name = band_name.replace(" ", "")
self.set_attr_from_xmp_tag(
"band_index",
tags,
[
"DLS:SensorId", # Micasense RedEdge
"@Camera:RigCameraIndex", # Parrot Sequoia, Sentera 21244-00_3.2MP-GS-0001
"Camera:RigCameraIndex", # MicaSense Altum
],
)
self.set_attr_from_xmp_tag(
"radiometric_calibration",
tags,
[
"MicaSense:RadiometricCalibration",
],
)
self.set_attr_from_xmp_tag(
"vignetting_center",
tags,
[
"Camera:VignettingCenter",
"Sentera:VignettingCenter",
],
)
self.set_attr_from_xmp_tag(
"vignetting_polynomial",
tags,
[
"Camera:VignettingPolynomial",
"Sentera:VignettingPolynomial",
],
)
self.set_attr_from_xmp_tag(
"horizontal_irradiance",
tags,
["Camera:HorizontalIrradiance"],
float,
)
self.set_attr_from_xmp_tag(
"irradiance_scale_to_si",
tags,
["Camera:IrradianceScaleToSIUnits"],
float,
)
self.set_attr_from_xmp_tag(
"sun_sensor",
tags,
[
"Camera:SunSensor",
],
float,
)
self.set_attr_from_xmp_tag(
"spectral_irradiance",
tags,
[
"Camera:SpectralIrradiance",
"Camera:Irradiance",
],
float,
)
# Phantom 4 RTK
if "@drone-dji:RtkStdLon" in tags:
y = float(self.get_xmp_tag(tags, "@drone-dji:RtkStdLon"))
x = float(self.get_xmp_tag(tags, "@drone-dji:RtkStdLat"))
self.gps_xy_stddev = max(x, y)
if "@drone-dji:RtkStdHgt" in tags:
self.gps_z_stddev = float(
self.get_xmp_tag(tags, "@drone-dji:RtkStdHgt")
)
else:
self.set_attr_from_xmp_tag(
"gps_xy_stddev",
tags,
["@Camera:GPSXYAccuracy", "GPSXYAccuracy"],
float,
)
self.set_attr_from_xmp_tag(
"gps_z_stddev",
tags,
["@Camera:GPSZAccuracy", "GPSZAccuracy"],
float,
)
if "DLS:Yaw" in tags:
self.set_attr_from_xmp_tag("dls_yaw", tags, ["DLS:Yaw"], float)
self.set_attr_from_xmp_tag("dls_pitch", tags, ["DLS:Pitch"], float)
self.set_attr_from_xmp_tag("dls_roll", tags, ["DLS:Roll"], float)
except Exception as e:
log.ODM_WARNING(
"Cannot read XMP tags for %s: %s" % (_path_file, str(e))
)
# self.set_attr_from_xmp_tag('center_wavelength', tags, [
# 'Camera:CentralWavelength'
# ], float)
# self.set_attr_from_xmp_tag('bandwidth', tags, [
# 'Camera:WavelengthFWHM'
# ], float)
self.width, self.height = get_image_size.get_image_size(_path_file)
# Sanitize band name since we use it in folder paths
self.band_name = re.sub("[^A-Za-z0-9]+", "", self.band_name)
|
def parse_exif_values(self, _path_file):
# Disable exifread log
logging.getLogger("exifread").setLevel(logging.CRITICAL)
with open(_path_file, "rb") as f:
tags = exifread.process_file(f, details=False)
try:
if "Image Make" in tags:
try:
self.camera_make = tags["Image Make"].values
except UnicodeDecodeError:
log.ODM_WARNING("EXIF Image Make might be corrupted")
self.camera_make = "unknown"
if "Image Model" in tags:
try:
self.camera_model = tags["Image Model"].values
except UnicodeDecodeError:
log.ODM_WARNING("EXIF Image Model might be corrupted")
self.camera_model = "unknown"
if "GPS GPSAltitude" in tags:
self.altitude = self.float_value(tags["GPS GPSAltitude"])
if (
"GPS GPSAltitudeRef" in tags
and self.int_value(tags["GPS GPSAltitudeRef"]) > 0
):
self.altitude *= -1
if "GPS GPSLatitude" in tags and "GPS GPSLatitudeRef" in tags:
self.latitude = self.dms_to_decimal(
tags["GPS GPSLatitude"], tags["GPS GPSLatitudeRef"]
)
if "GPS GPSLongitude" in tags and "GPS GPSLongitudeRef" in tags:
self.longitude = self.dms_to_decimal(
tags["GPS GPSLongitude"], tags["GPS GPSLongitudeRef"]
)
except IndexError as e:
log.ODM_WARNING(
"Cannot read basic EXIF tags for %s: %s" % (_path_file, e.message)
)
try:
if "Image Tag 0xC61A" in tags:
self.black_level = self.list_values(tags["Image Tag 0xC61A"])
elif "BlackLevel" in tags:
self.black_level = self.list_values(tags["BlackLevel"])
if "EXIF ExposureTime" in tags:
self.exposure_time = self.float_value(tags["EXIF ExposureTime"])
if "EXIF FNumber" in tags:
self.fnumber = self.float_value(tags["EXIF FNumber"])
if "EXIF ISOSpeed" in tags:
self.iso_speed = self.int_value(tags["EXIF ISOSpeed"])
elif "EXIF PhotographicSensitivity" in tags:
self.iso_speed = self.int_value(tags["EXIF PhotographicSensitivity"])
elif "EXIF ISOSpeedRatings" in tags:
self.iso_speed = self.int_value(tags["EXIF ISOSpeedRatings"])
if "Image BitsPerSample" in tags:
self.bits_per_sample = self.int_value(tags["Image BitsPerSample"])
if "EXIF DateTimeOriginal" in tags:
str_time = tags["EXIF DateTimeOriginal"].values
utc_time = datetime.strptime(str_time, "%Y:%m:%d %H:%M:%S")
subsec = 0
if "EXIF SubSecTime" in tags:
subsec = self.int_value(tags["EXIF SubSecTime"])
negative = 1.0
if subsec < 0:
negative = -1.0
subsec *= -1.0
subsec = float("0.{}".format(int(subsec)))
subsec *= negative
ms = subsec * 1e3
utc_time += timedelta(milliseconds=ms)
timezone = pytz.timezone("UTC")
epoch = timezone.localize(datetime.utcfromtimestamp(0))
self.utc_time = (
timezone.localize(utc_time) - epoch
).total_seconds() * 1000.0
except Exception as e:
log.ODM_WARNING(
"Cannot read extended EXIF tags for %s: %s" % (_path_file, str(e))
)
# Extract XMP tags
f.seek(0)
xmp = self.get_xmp(f)
for tags in xmp:
try:
band_name = self.get_xmp_tag(
tags, ["Camera:BandName", "@Camera:BandName"]
)
if band_name is not None:
self.band_name = band_name.replace(" ", "")
self.set_attr_from_xmp_tag(
"band_index",
tags,
[
"DLS:SensorId", # Micasense RedEdge
"@Camera:RigCameraIndex", # Parrot Sequoia, Sentera 21244-00_3.2MP-GS-0001
"Camera:RigCameraIndex", # MicaSense Altum
],
)
self.set_attr_from_xmp_tag(
"radiometric_calibration",
tags,
[
"MicaSense:RadiometricCalibration",
],
)
self.set_attr_from_xmp_tag(
"vignetting_center",
tags,
[
"Camera:VignettingCenter",
"Sentera:VignettingCenter",
],
)
self.set_attr_from_xmp_tag(
"vignetting_polynomial",
tags,
[
"Camera:VignettingPolynomial",
"Sentera:VignettingPolynomial",
],
)
self.set_attr_from_xmp_tag(
"horizontal_irradiance",
tags,
["Camera:HorizontalIrradiance"],
float,
)
self.set_attr_from_xmp_tag(
"irradiance_scale_to_si",
tags,
["Camera:IrradianceScaleToSIUnits"],
float,
)
self.set_attr_from_xmp_tag(
"sun_sensor",
tags,
[
"Camera:SunSensor",
],
float,
)
self.set_attr_from_xmp_tag(
"spectral_irradiance",
tags,
[
"Camera:SpectralIrradiance",
"Camera:Irradiance",
],
float,
)
# Phantom 4 RTK
if "@drone-dji:RtkStdLon" in tags:
y = float(self.get_xmp_tag(tags, "@drone-dji:RtkStdLon"))
x = float(self.get_xmp_tag(tags, "@drone-dji:RtkStdLat"))
self.gps_xy_stddev = max(x, y)
if "@drone-dji:RtkStdHgt" in tags:
self.gps_z_stddev = float(
self.get_xmp_tag(tags, "@drone-dji:RtkStdHgt")
)
else:
self.set_attr_from_xmp_tag(
"gps_xy_stddev",
tags,
["@Camera:GPSXYAccuracy", "GPSXYAccuracy"],
float,
)
self.set_attr_from_xmp_tag(
"gps_z_stddev",
tags,
["@Camera:GPSZAccuracy", "GPSZAccuracy"],
float,
)
if "DLS:Yaw" in tags:
self.set_attr_from_xmp_tag("dls_yaw", tags, ["DLS:Yaw"], float)
self.set_attr_from_xmp_tag("dls_pitch", tags, ["DLS:Pitch"], float)
self.set_attr_from_xmp_tag("dls_roll", tags, ["DLS:Roll"], float)
except Exception as e:
log.ODM_WARNING(
"Cannot read XMP tags for %s: %s" % (_path_file, e.message)
)
# self.set_attr_from_xmp_tag('center_wavelength', tags, [
# 'Camera:CentralWavelength'
# ], float)
# self.set_attr_from_xmp_tag('bandwidth', tags, [
# 'Camera:WavelengthFWHM'
# ], float)
self.width, self.height = get_image_size.get_image_size(_path_file)
# Sanitize band name since we use it in folder paths
self.band_name = re.sub("[^A-Za-z0-9]+", "", self.band_name)
|
https://github.com/OpenDroneMap/ODM/issues/1163
|
[INFO] Loading 4 images
Traceback (most recent call last):
File "/code/opendm/photo.py", line 225, in parse_exif_values
], float)
File "/code/opendm/photo.py", line 256, in set_attr_from_xmp_tag
setattr(self, attr, cast(v))
ValueError: could not convert string to float: '610/1000'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/code/run.py", line 68, in <module>
app.execute()
File "/code/stages/odm_app.py", line 95, in execute
self.first_stage.run()
File "/code/opendm/types.py", line 337, in run
self.process(self.args, outputs)
File "/code/stages/dataset.py", line 109, in process
p = types.ODM_Photo(f)
File "/code/opendm/photo.py", line 70, in __init__
self.parse_exif_values(path_file)
File "/code/opendm/photo.py", line 236, in parse_exif_values
log.ODM_WARNING("Cannot read XMP tags for %s: %s" % (_path_file, e.message))
AttributeError: 'ValueError' object has no attribute 'message'
|
ValueError
|
def set_attr_from_xmp_tag(self, attr, xmp_tags, tags, cast=None):
v = self.get_xmp_tag(xmp_tags, tags)
if v is not None:
if cast is None:
setattr(self, attr, v)
else:
# Handle fractions
if (cast == float or cast == int) and "/" in v:
v = self.try_parse_fraction(v)
setattr(self, attr, cast(v))
|
def set_attr_from_xmp_tag(self, attr, xmp_tags, tags, cast=None):
v = self.get_xmp_tag(xmp_tags, tags)
if v is not None:
if cast is None:
setattr(self, attr, v)
else:
setattr(self, attr, cast(v))
|
https://github.com/OpenDroneMap/ODM/issues/1163
|
[INFO] Loading 4 images
Traceback (most recent call last):
File "/code/opendm/photo.py", line 225, in parse_exif_values
], float)
File "/code/opendm/photo.py", line 256, in set_attr_from_xmp_tag
setattr(self, attr, cast(v))
ValueError: could not convert string to float: '610/1000'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/code/run.py", line 68, in <module>
app.execute()
File "/code/stages/odm_app.py", line 95, in execute
self.first_stage.run()
File "/code/opendm/types.py", line 337, in run
self.process(self.args, outputs)
File "/code/stages/dataset.py", line 109, in process
p = types.ODM_Photo(f)
File "/code/opendm/photo.py", line 70, in __init__
self.parse_exif_values(path_file)
File "/code/opendm/photo.py", line 236, in parse_exif_values
log.ODM_WARNING("Cannot read XMP tags for %s: %s" % (_path_file, e.message))
AttributeError: 'ValueError' object has no attribute 'message'
|
ValueError
|
def process(self, args, outputs):
tree = outputs["tree"]
reconstruction = outputs["reconstruction"]
photos = reconstruction.photos
if not photos:
log.ODM_ERROR("Not enough photos in photos array to start OpenSfM")
exit(1)
octx = OSFMContext(tree.opensfm)
octx.setup(
args,
tree.dataset_raw,
photos,
reconstruction=reconstruction,
rerun=self.rerun(),
)
octx.extract_metadata(self.rerun())
self.update_progress(20)
octx.feature_matching(self.rerun())
self.update_progress(30)
octx.reconstruct(self.rerun())
octx.extract_cameras(tree.path("cameras.json"), self.rerun())
self.update_progress(70)
if args.optimize_disk_space:
for folder in ["features", "matches", "exif", "reports"]:
folder_path = octx.path(folder)
if os.path.islink(folder_path):
os.unlink(folder_path)
else:
shutil.rmtree(folder_path)
# If we find a special flag file for split/merge we stop right here
if os.path.exists(octx.path("split_merge_stop_at_reconstruction.txt")):
log.ODM_INFO(
"Stopping OpenSfM early because we found: %s"
% octx.path("split_merge_stop_at_reconstruction.txt")
)
self.next_stage = None
return
if args.fast_orthophoto:
output_file = octx.path("reconstruction.ply")
elif args.use_opensfm_dense:
output_file = tree.opensfm_model
else:
output_file = tree.opensfm_reconstruction
updated_config_flag_file = octx.path("updated_config.txt")
# Make sure it's capped by the depthmap-resolution arg,
# since the undistorted images are used for MVS
outputs["undist_image_max_size"] = max(
gsd.image_max_size(
photos,
args.orthophoto_resolution,
tree.opensfm_reconstruction,
ignore_gsd=args.ignore_gsd,
has_gcp=reconstruction.has_gcp(),
),
args.depthmap_resolution,
)
if not io.file_exists(updated_config_flag_file) or self.rerun():
octx.update_config(
{"undistorted_image_max_size": outputs["undist_image_max_size"]}
)
octx.touch(updated_config_flag_file)
# These will be used for texturing / MVS
if args.radiometric_calibration == "none":
octx.convert_and_undistort(self.rerun())
else:
def radiometric_calibrate(shot_id, image):
photo = reconstruction.get_photo(shot_id)
return multispectral.dn_to_reflectance(
photo,
image,
use_sun_sensor=args.radiometric_calibration == "camera+sun",
)
octx.convert_and_undistort(self.rerun(), radiometric_calibrate)
self.update_progress(80)
if reconstruction.multi_camera:
# Dump band image lists
log.ODM_INFO("Multiple bands found")
for band in reconstruction.multi_camera:
log.ODM_INFO("Exporting %s band" % band["name"])
image_list_file = octx.path("image_list_%s.txt" % band["name"].lower())
if not io.file_exists(image_list_file) or self.rerun():
with open(image_list_file, "w") as f:
f.write("\n".join([p.filename for p in band["photos"]]))
log.ODM_INFO("Wrote %s" % image_list_file)
else:
log.ODM_WARNING(
"Found a valid image list in %s for %s band"
% (image_list_file, band["name"])
)
nvm_file = octx.path(
"undistorted", "reconstruction_%s.nvm" % band["name"].lower()
)
if not io.file_exists(nvm_file) or self.rerun():
octx.run(
'export_visualsfm --points --image_list "%s"' % image_list_file
)
os.rename(tree.opensfm_reconstruction_nvm, nvm_file)
else:
log.ODM_WARNING(
"Found a valid NVM file in %s for %s band"
% (nvm_file, band["name"])
)
if not io.file_exists(tree.opensfm_reconstruction_nvm) or self.rerun():
octx.run("export_visualsfm --points")
else:
log.ODM_WARNING(
"Found a valid OpenSfM NVM reconstruction file in: %s"
% tree.opensfm_reconstruction_nvm
)
self.update_progress(85)
# Skip dense reconstruction if necessary and export
# sparse reconstruction instead
if args.fast_orthophoto:
if not io.file_exists(output_file) or self.rerun():
octx.run("export_ply --no-cameras")
else:
log.ODM_WARNING("Found a valid PLY reconstruction in %s" % output_file)
elif args.use_opensfm_dense:
if not io.file_exists(output_file) or self.rerun():
octx.run("compute_depthmaps")
else:
log.ODM_WARNING("Found a valid dense reconstruction in %s" % output_file)
self.update_progress(90)
if reconstruction.is_georeferenced() and (
not io.file_exists(tree.opensfm_transformation) or self.rerun()
):
octx.run(
"export_geocoords --transformation --proj '%s'"
% reconstruction.georef.proj4()
)
else:
log.ODM_WARNING("Will skip exporting %s" % tree.opensfm_transformation)
if args.optimize_disk_space:
os.remove(octx.path("tracks.csv"))
os.remove(octx.path("undistorted", "tracks.csv"))
os.remove(octx.path("undistorted", "reconstruction.json"))
if io.dir_exists(octx.path("undistorted", "depthmaps")):
files = glob.glob(octx.path("undistorted", "depthmaps", "*.npz"))
for f in files:
os.remove(f)
|
def process(self, args, outputs):
tree = outputs["tree"]
reconstruction = outputs["reconstruction"]
photos = reconstruction.photos
if not photos:
log.ODM_ERROR("Not enough photos in photos array to start OpenSfM")
exit(1)
octx = OSFMContext(tree.opensfm)
octx.setup(
args,
tree.dataset_raw,
photos,
reconstruction=reconstruction,
rerun=self.rerun(),
)
octx.extract_metadata(self.rerun())
self.update_progress(20)
octx.feature_matching(self.rerun())
self.update_progress(30)
octx.reconstruct(self.rerun())
octx.extract_cameras(tree.path("cameras.json"), self.rerun())
self.update_progress(70)
if args.optimize_disk_space:
shutil.rmtree(octx.path("features"))
shutil.rmtree(octx.path("matches"))
shutil.rmtree(octx.path("exif"))
shutil.rmtree(octx.path("reports"))
# If we find a special flag file for split/merge we stop right here
if os.path.exists(octx.path("split_merge_stop_at_reconstruction.txt")):
log.ODM_INFO(
"Stopping OpenSfM early because we found: %s"
% octx.path("split_merge_stop_at_reconstruction.txt")
)
self.next_stage = None
return
if args.fast_orthophoto:
output_file = octx.path("reconstruction.ply")
elif args.use_opensfm_dense:
output_file = tree.opensfm_model
else:
output_file = tree.opensfm_reconstruction
updated_config_flag_file = octx.path("updated_config.txt")
# Make sure it's capped by the depthmap-resolution arg,
# since the undistorted images are used for MVS
outputs["undist_image_max_size"] = max(
gsd.image_max_size(
photos,
args.orthophoto_resolution,
tree.opensfm_reconstruction,
ignore_gsd=args.ignore_gsd,
has_gcp=reconstruction.has_gcp(),
),
args.depthmap_resolution,
)
if not io.file_exists(updated_config_flag_file) or self.rerun():
octx.update_config(
{"undistorted_image_max_size": outputs["undist_image_max_size"]}
)
octx.touch(updated_config_flag_file)
# These will be used for texturing / MVS
if args.radiometric_calibration == "none":
octx.convert_and_undistort(self.rerun())
else:
def radiometric_calibrate(shot_id, image):
photo = reconstruction.get_photo(shot_id)
return multispectral.dn_to_reflectance(
photo,
image,
use_sun_sensor=args.radiometric_calibration == "camera+sun",
)
octx.convert_and_undistort(self.rerun(), radiometric_calibrate)
self.update_progress(80)
if reconstruction.multi_camera:
# Dump band image lists
log.ODM_INFO("Multiple bands found")
for band in reconstruction.multi_camera:
log.ODM_INFO("Exporting %s band" % band["name"])
image_list_file = octx.path("image_list_%s.txt" % band["name"].lower())
if not io.file_exists(image_list_file) or self.rerun():
with open(image_list_file, "w") as f:
f.write("\n".join([p.filename for p in band["photos"]]))
log.ODM_INFO("Wrote %s" % image_list_file)
else:
log.ODM_WARNING(
"Found a valid image list in %s for %s band"
% (image_list_file, band["name"])
)
nvm_file = octx.path(
"undistorted", "reconstruction_%s.nvm" % band["name"].lower()
)
if not io.file_exists(nvm_file) or self.rerun():
octx.run(
'export_visualsfm --points --image_list "%s"' % image_list_file
)
os.rename(tree.opensfm_reconstruction_nvm, nvm_file)
else:
log.ODM_WARNING(
"Found a valid NVM file in %s for %s band"
% (nvm_file, band["name"])
)
if not io.file_exists(tree.opensfm_reconstruction_nvm) or self.rerun():
octx.run("export_visualsfm --points")
else:
log.ODM_WARNING(
"Found a valid OpenSfM NVM reconstruction file in: %s"
% tree.opensfm_reconstruction_nvm
)
self.update_progress(85)
# Skip dense reconstruction if necessary and export
# sparse reconstruction instead
if args.fast_orthophoto:
if not io.file_exists(output_file) or self.rerun():
octx.run("export_ply --no-cameras")
else:
log.ODM_WARNING("Found a valid PLY reconstruction in %s" % output_file)
elif args.use_opensfm_dense:
if not io.file_exists(output_file) or self.rerun():
octx.run("compute_depthmaps")
else:
log.ODM_WARNING("Found a valid dense reconstruction in %s" % output_file)
self.update_progress(90)
if reconstruction.is_georeferenced() and (
not io.file_exists(tree.opensfm_transformation) or self.rerun()
):
octx.run(
"export_geocoords --transformation --proj '%s'"
% reconstruction.georef.proj4()
)
else:
log.ODM_WARNING("Will skip exporting %s" % tree.opensfm_transformation)
if args.optimize_disk_space:
os.remove(octx.path("tracks.csv"))
os.remove(octx.path("undistorted", "tracks.csv"))
os.remove(octx.path("undistorted", "reconstruction.json"))
if io.dir_exists(octx.path("undistorted", "depthmaps")):
files = glob.glob(octx.path("undistorted", "depthmaps", "*.npz"))
for f in files:
os.remove(f)
|
https://github.com/OpenDroneMap/ODM/issues/1151
|
[INFO] Finished dataset stage
[INFO] Running split stage
[INFO] Normal dataset, will process all at once.
[INFO] Finished split stage
[INFO] Running merge stage
[INFO] Normal dataset, nothing to merge.
[INFO] Finished merge stage
[INFO] Running opensfm stage
[WARNING] /datasets/project/submodels/submodel_0000/opensfm/image_list.txt already exists, not rerunning OpenSfM setup
[WARNING] Detect features already done: /datasets/project/submodels/submodel_0000/opensfm/features exists
[WARNING] Match features already done: /datasets/project/submodels/submodel_0000/opensfm/matches exists
[WARNING] Found a valid OpenSfM tracks file in: /datasets/project/submodels/submodel_0000/opensfm/tracks.csv
[WARNING] Found a valid OpenSfM reconstruction file in: /datasets/project/submodels/submodel_0000/opensfm/reconstruction.json
[INFO] Already extracted cameras Traceback (most recent call last):
File "/code/run.py", line 62, in <module>
app.execute()
File "/code/stages/odm_app.py", line 95, in execute
self.first_stage.run()
File "/code/opendm/types.py", line 350, in run
self.next_stage.run(outputs)
File "/code/opendm/types.py", line 350, in run
self.next_stage.run(outputs)
File "/code/opendm/types.py", line 350, in run
self.next_stage.run(outputs)
File "/code/opendm/types.py", line 331, in run
self.process(self.args, outputs)
File "/code/stages/run_opensfm.py", line 37, in process
shutil.rmtree(octx.path("features"))
File "/usr/lib/python2.7/shutil.py", line 232, in rmtree
onerror(os.path.islink, path, sys.exc_info())
File "/usr/lib/python2.7/shutil.py", line 230, in rmtree
raise OSError("Cannot call rmtree on a symbolic link")
OSError: Cannot call rmtree on a symbolic link
Traceback (most recent call last):
File "/code/run.py", line 62, in <module>
app.execute()
File "/code/stages/odm_app.py", line 95, in execute
self.first_stage.run()
File "/code/opendm/types.py", line 350, in run
self.next_stage.run(outputs)
File "/code/opendm/types.py", line 331, in run
self.process(self.args, outputs)
File "/code/stages/splitmerge.py", line 219, in process
system.run(" ".join(map(quote, argv)), env_vars=os.environ.copy())
File "/code/opendm/system.py", line 76, in run
raise Exception("Child returned {}".format(retcode))
Exception: Child returned 1
|
OSError
|
def build_block_parser(md, **kwargs):
"""Build the default block parser used by Markdown."""
parser = BlockParser(md)
parser.blockprocessors.register(EmptyBlockProcessor(parser), "empty", 100)
parser.blockprocessors.register(ListIndentProcessor(parser), "indent", 90)
parser.blockprocessors.register(CodeBlockProcessor(parser), "code", 80)
parser.blockprocessors.register(HashHeaderProcessor(parser), "hashheader", 70)
parser.blockprocessors.register(SetextHeaderProcessor(parser), "setextheader", 60)
parser.blockprocessors.register(HRProcessor(parser), "hr", 50)
parser.blockprocessors.register(OListProcessor(parser), "olist", 40)
parser.blockprocessors.register(UListProcessor(parser), "ulist", 30)
parser.blockprocessors.register(BlockQuoteProcessor(parser), "quote", 20)
parser.blockprocessors.register(ReferenceProcessor(parser), "reference", 15)
parser.blockprocessors.register(ParagraphProcessor(parser), "paragraph", 10)
return parser
|
def build_block_parser(md, **kwargs):
"""Build the default block parser used by Markdown."""
parser = BlockParser(md)
parser.blockprocessors.register(EmptyBlockProcessor(parser), "empty", 100)
parser.blockprocessors.register(ListIndentProcessor(parser), "indent", 90)
parser.blockprocessors.register(CodeBlockProcessor(parser), "code", 80)
parser.blockprocessors.register(HashHeaderProcessor(parser), "hashheader", 70)
parser.blockprocessors.register(SetextHeaderProcessor(parser), "setextheader", 60)
parser.blockprocessors.register(HRProcessor(parser), "hr", 50)
parser.blockprocessors.register(OListProcessor(parser), "olist", 40)
parser.blockprocessors.register(UListProcessor(parser), "ulist", 30)
parser.blockprocessors.register(BlockQuoteProcessor(parser), "quote", 20)
parser.blockprocessors.register(ParagraphProcessor(parser), "paragraph", 10)
return parser
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def extendMarkdown(self, md):
"""Insert AbbrPreprocessor before ReferencePreprocessor."""
md.parser.blockprocessors.register(AbbrPreprocessor(md.parser), "abbr", 16)
|
def extendMarkdown(self, md):
"""Insert AbbrPreprocessor before ReferencePreprocessor."""
md.preprocessors.register(AbbrPreprocessor(md), "abbr", 12)
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def run(self, parent, blocks):
"""
Find and remove all Abbreviation references from the text.
Each reference is set as a new AbbrPattern in the markdown instance.
"""
block = blocks.pop(0)
m = self.RE.search(block)
if m:
abbr = m.group("abbr").strip()
title = m.group("title").strip()
self.parser.md.inlinePatterns.register(
AbbrInlineProcessor(self._generate_pattern(abbr), title),
"abbr-%s" % abbr,
2,
)
if block[m.end() :].strip():
# Add any content after match back to blocks as separate block
blocks.insert(0, block[m.end() :].lstrip("\n"))
if block[: m.start()].strip():
# Add any content before match back to blocks as separate block
blocks.insert(0, block[: m.start()].rstrip("\n"))
return True
# No match. Restore block.
blocks.insert(0, block)
return False
|
def run(self, lines):
"""
Find and remove all Abbreviation references from the text.
Each reference is set as a new AbbrPattern in the markdown instance.
"""
new_text = []
for line in lines:
m = ABBR_REF_RE.match(line)
if m:
abbr = m.group("abbr").strip()
title = m.group("title").strip()
self.md.inlinePatterns.register(
AbbrInlineProcessor(self._generate_pattern(abbr), title),
"abbr-%s" % abbr,
2,
)
# Preserve the line to prevent raw HTML indexing issue.
# https://github.com/Python-Markdown/markdown/issues/584
new_text.append("")
else:
new_text.append(line)
return new_text
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def extendMarkdown(self, md):
"""Add pieces to Markdown."""
md.registerExtension(self)
self.parser = md.parser
self.md = md
# Insert a blockprocessor before ReferencePreprocessor
md.parser.blockprocessors.register(FootnoteBlockProcessor(self), "footnote", 17)
# Insert an inline pattern before ImageReferencePattern
FOOTNOTE_RE = r"\[\^([^\]]*)\]" # blah blah [^1] blah
md.inlinePatterns.register(
FootnoteInlineProcessor(FOOTNOTE_RE, self), "footnote", 175
)
# Insert a tree-processor that would actually add the footnote div
# This must be before all other treeprocessors (i.e., inline and
# codehilite) so they can run on the the contents of the div.
md.treeprocessors.register(FootnoteTreeprocessor(self), "footnote", 50)
# Insert a tree-processor that will run after inline is done.
# In this tree-processor we want to check our duplicate footnote tracker
# And add additional backrefs to the footnote pointing back to the
# duplicated references.
md.treeprocessors.register(
FootnotePostTreeprocessor(self), "footnote-duplicate", 15
)
# Insert a postprocessor after amp_substitute processor
md.postprocessors.register(FootnotePostprocessor(self), "footnote", 25)
|
def extendMarkdown(self, md):
"""Add pieces to Markdown."""
md.registerExtension(self)
self.parser = md.parser
self.md = md
# Insert a preprocessor before ReferencePreprocessor
md.preprocessors.register(FootnotePreprocessor(self), "footnote", 15)
# Insert an inline pattern before ImageReferencePattern
FOOTNOTE_RE = r"\[\^([^\]]*)\]" # blah blah [^1] blah
md.inlinePatterns.register(
FootnoteInlineProcessor(FOOTNOTE_RE, self), "footnote", 175
)
# Insert a tree-processor that would actually add the footnote div
# This must be before all other treeprocessors (i.e., inline and
# codehilite) so they can run on the the contents of the div.
md.treeprocessors.register(FootnoteTreeprocessor(self), "footnote", 50)
# Insert a tree-processor that will run after inline is done.
# In this tree-processor we want to check our duplicate footnote tracker
# And add additional backrefs to the footnote pointing back to the
# duplicated references.
md.treeprocessors.register(
FootnotePostTreeprocessor(self), "footnote-duplicate", 15
)
# Insert a postprocessor after amp_substitute processor
md.postprocessors.register(FootnotePostprocessor(self), "footnote", 25)
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def detectTabbed(self, blocks):
"""Find indented text and remove indent before further proccesing.
Returns: a list of blocks with indentation removed.
"""
fn_blocks = []
while blocks:
if blocks[0].startswith(" " * 4):
block = blocks.pop(0)
# Check for new footnotes within this block and split at new footnote.
m = self.RE.search(block)
if m:
# Another footnote exists in this block.
# Any content before match is continuation of this footnote, which may be lazily indented.
before = block[: m.start()].rstrip("\n")
fn_blocks.append(self.detab(before))
# Add back to blocks everything from begining of match forward for next iteration.
blocks.insert(0, block[m.start() :])
# End of this footnote.
break
else:
# Entire block is part of this footnote.
fn_blocks.append(self.detab(block))
else:
# End of this footnote.
break
return fn_blocks
|
def detectTabbed(self, lines):
"""Find indented text and remove indent before further proccesing.
Keyword arguments:
* lines: an array of strings
Returns: a list of post processed items and the index of last line.
"""
items = []
blank_line = False # have we encountered a blank line yet?
i = 0 # to keep track of where we are
def detab(line):
match = TABBED_RE.match(line)
if match:
return match.group(4)
for line in lines:
if line.strip(): # Non-blank line
detabbed_line = detab(line)
if detabbed_line:
items.append(detabbed_line)
i += 1
continue
elif not blank_line and not DEF_RE.match(line):
# not tabbed but still part of first par.
items.append(line)
i += 1
continue
else:
return items, i + 1
else: # Blank line: _maybe_ we are done.
blank_line = True
i += 1 # advance
# Find the next non-blank line
for j in range(i, len(lines)):
if lines[j].strip():
next_line = lines[j]
break
else:
# Include extreaneous padding to prevent raw HTML
# parsing issue: https://github.com/Python-Markdown/markdown/issues/584
items.append("")
i += 1
else:
break # There is no more text; we are done.
# Check if the next non-blank line is tabbed
if detab(next_line): # Yes, more work to do.
items.append("")
continue
else:
break # No, we are done.
else:
i += 1
return items, i
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def detab(self, block):
"""Remove one level of indent from a block.
Preserve lazily indented blocks by only removing indent from indented lines.
"""
lines = block.split("\n")
for i, line in enumerate(lines):
if line.startswith(" " * 4):
lines[i] = line[4:]
return "\n".join(lines)
|
def detab(line):
match = TABBED_RE.match(line)
if match:
return match.group(4)
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def run(self, parent, blocks):
m = util.HTML_PLACEHOLDER_RE.match(blocks[0])
if m:
index = int(m.group(1))
element = self.parser.md.htmlStash.rawHtmlBlocks[index]
if isinstance(element, etree.Element):
# We have a matched element. Process it.
blocks.pop(0)
self.parse_element_content(element)
parent.append(element)
# Cleanup stash. Replace element with empty string to avoid confusing postprocessor.
self.parser.md.htmlStash.rawHtmlBlocks.pop(index)
self.parser.md.htmlStash.rawHtmlBlocks.insert(index, "")
# Comfirm the match to the blockparser.
return True
# No match found.
return False
|
def run(self, parent, blocks, tail=None, nest=False):
self._tag_data = self.parser.md.htmlStash.tag_data
self.parser.blockprocessors.tag_counter += 1
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
# Create Element
markdown_value = tag["attrs"].pop("markdown")
element = etree.SubElement(parent, tag["tag"], tag["attrs"])
# Slice Off Block
if nest:
self.parser.parseBlocks(parent, tail) # Process Tail
block = blocks[1:]
else: # includes nests since a third level of nesting isn't supported
block = blocks[tag["left_index"] + 1 : tag["right_index"]]
del blocks[: tag["right_index"]]
# Process Text
if (
self.parser.blockprocessors.contain_span_tags.match( # Span Mode
tag["tag"]
)
and markdown_value != "block"
) or markdown_value == "span":
element.text = "\n".join(block)
else: # Block Mode
i = self.parser.blockprocessors.tag_counter + 1
if len(self._tag_data) > i and self._tag_data[i]["left_index"]:
first_subelement_index = self._tag_data[i]["left_index"] - 1
self.parser.parseBlocks(element, block[:first_subelement_index])
if not nest:
block = self._process_nests(element, block)
else:
self.parser.parseBlocks(element, block)
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def extendMarkdown(self, md):
"""Register extension instances."""
# Replace raw HTML preprocessor
md.preprocessors.register(HtmlBlockPreprocessor(md), "html_block", 20)
# Add blockprocessor which handles the placeholders for etree elements
md.parser.blockprocessors.register(
MarkdownInHtmlProcessor(md.parser), "markdown_block", 105
)
|
def extendMarkdown(self, md):
"""Register extension instances."""
# Turn on processing of markdown text within raw html
md.preprocessors["html_block"].markdown_in_raw = True
md.parser.blockprocessors.register(
MarkdownInHtmlProcessor(md.parser), "markdown_block", 105
)
md.parser.blockprocessors.tag_counter = -1
md.parser.blockprocessors.contain_span_tags = re.compile(
r"^(p|h[1-6]|li|dd|dt|td|th|legend|address)$", re.IGNORECASE
)
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def run(self, text):
"""Iterate over html stash and restore html."""
replacements = OrderedDict()
for i in range(self.md.htmlStash.html_counter):
html = self.md.htmlStash.rawHtmlBlocks[i]
if self.isblocklevel(html):
replacements["<p>{}</p>".format(self.md.htmlStash.get_placeholder(i))] = (
html
)
replacements[self.md.htmlStash.get_placeholder(i)] = html
if replacements:
pattern = re.compile("|".join(re.escape(k) for k in replacements))
processed_text = pattern.sub(lambda m: replacements[m.group(0)], text)
else:
return text
if processed_text == text:
return processed_text
else:
return self.run(processed_text)
|
def run(self, text):
"""Iterate over html stash and restore html."""
replacements = OrderedDict()
for i in range(self.md.htmlStash.html_counter):
html = self.md.htmlStash.rawHtmlBlocks[i]
if self.isblocklevel(html):
replacements["<p>%s</p>" % (self.md.htmlStash.get_placeholder(i))] = (
html + "\n"
)
replacements[self.md.htmlStash.get_placeholder(i)] = html
if replacements:
pattern = re.compile("|".join(re.escape(k) for k in replacements))
processed_text = pattern.sub(lambda m: replacements[m.group(0)], text)
else:
return text
if processed_text == text:
return processed_text
else:
return self.run(processed_text)
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def build_preprocessors(md, **kwargs):
"""Build the default set of preprocessors used by Markdown."""
preprocessors = util.Registry()
preprocessors.register(NormalizeWhitespace(md), "normalize_whitespace", 30)
preprocessors.register(HtmlBlockPreprocessor(md), "html_block", 20)
return preprocessors
|
def build_preprocessors(md, **kwargs):
"""Build the default set of preprocessors used by Markdown."""
preprocessors = util.Registry()
preprocessors.register(NormalizeWhitespace(md), "normalize_whitespace", 30)
preprocessors.register(HtmlBlockPreprocessor(md), "html_block", 20)
preprocessors.register(ReferencePreprocessor(md), "reference", 10)
return preprocessors
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def run(self, lines):
source = "\n".join(lines)
parser = HTMLExtractor(self.md)
parser.feed(source)
parser.close()
return "".join(parser.cleandoc).split("\n")
|
def run(self, lines):
text = "\n".join(lines)
new_blocks = []
text = text.rsplit("\n\n")
items = []
left_tag = ""
right_tag = ""
in_tag = False # flag
while text:
block = text[0]
if block.startswith("\n"):
block = block[1:]
text = text[1:]
if block.startswith("\n"):
block = block[1:]
if not in_tag:
if block.startswith("<") and len(block.strip()) > 1:
if block[1:4] == "!--":
# is a comment block
left_tag, left_index, attrs = "--", 2, {}
else:
left_tag, left_index, attrs = self._get_left_tag(block)
right_tag, data_index = self._get_right_tag(left_tag, left_index, block)
# keep checking conditions below and maybe just append
if data_index < len(block) and (
self.md.is_block_level(left_tag) or left_tag == "--"
):
text.insert(0, block[data_index:])
block = block[:data_index]
if not (
self.md.is_block_level(left_tag) or block[1] in ["!", "?", "@", "%"]
):
new_blocks.append(block)
continue
if self._is_oneliner(left_tag):
new_blocks.append(block.strip())
continue
if block.rstrip().endswith(">") and self._equal_tags(
left_tag, right_tag
):
if self.markdown_in_raw and "markdown" in attrs.keys():
block = block[left_index : -len(right_tag) - 2]
new_blocks.append(
self.md.htmlStash.store_tag(left_tag, attrs, 0, 2)
)
new_blocks.extend([block])
else:
new_blocks.append(self.md.htmlStash.store(block.strip()))
continue
else:
# if is block level tag and is not complete
if (not self._equal_tags(left_tag, right_tag)) and (
self.md.is_block_level(left_tag) or left_tag == "--"
):
items.append(block.strip())
in_tag = True
else:
new_blocks.append(self.md.htmlStash.store(block.strip()))
continue
else:
new_blocks.append(block)
else:
items.append(block)
# Need to evaluate all items so we can calculate relative to the left index.
right_tag, data_index = self._get_right_tag(
left_tag, left_index, "".join(items)
)
# Adjust data_index: relative to items -> relative to last block
prev_block_length = 0
for item in items[:-1]:
prev_block_length += len(item)
data_index -= prev_block_length
if self._equal_tags(left_tag, right_tag):
# if find closing tag
if data_index < len(block):
# we have more text after right_tag
items[-1] = block[:data_index]
text.insert(0, block[data_index:])
in_tag = False
if self.markdown_in_raw and "markdown" in attrs.keys():
items[0] = items[0][left_index:]
items[-1] = items[-1][: -len(right_tag) - 2]
if items[len(items) - 1]: # not a newline/empty string
right_index = len(items) + 3
else:
right_index = len(items) + 2
new_blocks.append(
self.md.htmlStash.store_tag(left_tag, attrs, 0, right_index)
)
placeholderslen = len(self.md.htmlStash.tag_data)
new_blocks.extend(self._nested_markdown_in_html(items))
nests = len(self.md.htmlStash.tag_data) - placeholderslen
self.md.htmlStash.tag_data[-1 - nests]["right_index"] += nests - 2
else:
new_blocks.append(self.md.htmlStash.store("\n\n".join(items)))
items = []
if items:
if self.markdown_in_raw and "markdown" in attrs.keys():
items[0] = items[0][left_index:]
items[-1] = items[-1][: -len(right_tag) - 2]
if items[len(items) - 1]: # not a newline/empty string
right_index = len(items) + 3
else:
right_index = len(items) + 2
new_blocks.append(
self.md.htmlStash.store_tag(left_tag, attrs, 0, right_index)
)
placeholderslen = len(self.md.htmlStash.tag_data)
new_blocks.extend(self._nested_markdown_in_html(items))
nests = len(self.md.htmlStash.tag_data) - placeholderslen
self.md.htmlStash.tag_data[-1 - nests]["right_index"] += nests - 2
else:
new_blocks.append(self.md.htmlStash.store("\n\n".join(items)))
new_blocks.append("\n")
new_text = "\n\n".join(new_blocks)
return new_text.split("\n")
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def run(self, lines):
source = "\n".join(lines)
parser = HTMLExtractor(self.md)
parser.feed(source)
parser.close()
return "".join(parser.cleandoc).split("\n")
|
def run(self, lines):
new_text = []
while lines:
line = lines.pop(0)
m = self.RE.match(line)
if m:
id = m.group(1).strip().lower()
link = m.group(2).lstrip("<").rstrip(">")
t = m.group(5) or m.group(6) or m.group(7)
if not t:
# Check next line for title
tm = self.TITLE_RE.match(lines[0])
if tm:
lines.pop(0)
t = tm.group(2) or tm.group(3) or tm.group(4)
self.md.references[id] = (link, t)
# Preserve the line to prevent raw HTML indexing issue.
# https://github.com/Python-Markdown/markdown/issues/584
new_text.append("")
else:
new_text.append(line)
return new_text # + "\n"
|
https://github.com/Python-Markdown/markdown/issues/780
|
Traceback (most recent call last):
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/test_tools.py", line 117, in test
output = markdown(input, **kwargs)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 391, in markdown
return md.convert(text)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/core.py", line 268, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 92, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 107, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/blockparser.py", line 125, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 127, in run
block = self._process_nests(element, block)
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 95, in _process_nests
block[nest_index[-1][1]:], True) # nest
File "/home/ikus060/workspace/PDSL/markdown.git/markdown/extensions/extra.py", line 101, in run
tag = self._tag_data[self.parser.blockprocessors.tag_counter]
IndexError: list index out of range
|
IndexError
|
def run(self, lines):
"""
Find and remove all Abbreviation references from the text.
Each reference is set as a new AbbrPattern in the markdown instance.
"""
new_text = []
for line in lines:
m = ABBR_REF_RE.match(line)
if m:
abbr = m.group("abbr").strip()
title = m.group("title").strip()
self.markdown.inlinePatterns["abbr-%s" % abbr] = AbbrPattern(
self._generate_pattern(abbr), title
)
# Preserve the line to prevent raw HTML indexing issue.
# https://github.com/Python-Markdown/markdown/issues/584
new_text.append("")
else:
new_text.append(line)
return new_text
|
def run(self, lines):
"""
Find and remove all Abbreviation references from the text.
Each reference is set as a new AbbrPattern in the markdown instance.
"""
new_text = []
for line in lines:
m = ABBR_REF_RE.match(line)
if m:
abbr = m.group("abbr").strip()
title = m.group("title").strip()
self.markdown.inlinePatterns["abbr-%s" % abbr] = AbbrPattern(
self._generate_pattern(abbr), title
)
else:
new_text.append(line)
return new_text
|
https://github.com/Python-Markdown/markdown/issues/584
|
doc-pelican (0.7)$ python3 test.py
Markdown 2.6.9
Traceback (most recent call last):
File "test.py", line 22, in <module>
print(md.convert(text))
File "/usr/lib/python3/dist-packages/markdown/__init__.py", line 371, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 65, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 80, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 98, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 130, in run
block = self._process_nests(element, block)
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 97, in _process_nests
self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last
IndexError: list index out of range
|
IndexError
|
def run(self, lines):
"""
Loop through lines and find, set, and remove footnote definitions.
Keywords:
* lines: A list of lines of text
Return: A list of lines of text with footnote definitions removed.
"""
newlines = []
i = 0
while True:
m = DEF_RE.match(lines[i])
if m:
fn, _i = self.detectTabbed(lines[i + 1 :])
fn.insert(0, m.group(2))
i += _i - 1 # skip past footnote
footnote = "\n".join(fn)
self.footnotes.setFootnote(m.group(1), footnote.rstrip())
# Preserve a line for each block to prevent raw HTML indexing issue.
# https://github.com/Python-Markdown/markdown/issues/584
num_blocks = len(footnote.split("\n\n")) * 2
newlines.extend([""] * (num_blocks))
else:
newlines.append(lines[i])
if len(lines) > i + 1:
i += 1
else:
break
return newlines
|
def run(self, lines):
"""
Loop through lines and find, set, and remove footnote definitions.
Keywords:
* lines: A list of lines of text
Return: A list of lines of text with footnote definitions removed.
"""
newlines = []
i = 0
while True:
m = DEF_RE.match(lines[i])
if m:
fn, _i = self.detectTabbed(lines[i + 1 :])
fn.insert(0, m.group(2))
i += _i - 1 # skip past footnote
self.footnotes.setFootnote(m.group(1), "\n".join(fn))
else:
newlines.append(lines[i])
if len(lines) > i + 1:
i += 1
else:
break
return newlines
|
https://github.com/Python-Markdown/markdown/issues/584
|
doc-pelican (0.7)$ python3 test.py
Markdown 2.6.9
Traceback (most recent call last):
File "test.py", line 22, in <module>
print(md.convert(text))
File "/usr/lib/python3/dist-packages/markdown/__init__.py", line 371, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 65, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 80, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 98, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 130, in run
block = self._process_nests(element, block)
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 97, in _process_nests
self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last
IndexError: list index out of range
|
IndexError
|
def detectTabbed(self, lines):
"""Find indented text and remove indent before further proccesing.
Keyword arguments:
* lines: an array of strings
Returns: a list of post processed items and the index of last line.
"""
items = []
blank_line = False # have we encountered a blank line yet?
i = 0 # to keep track of where we are
def detab(line):
match = TABBED_RE.match(line)
if match:
return match.group(4)
for line in lines:
if line.strip(): # Non-blank line
detabbed_line = detab(line)
if detabbed_line:
items.append(detabbed_line)
i += 1
continue
elif not blank_line and not DEF_RE.match(line):
# not tabbed but still part of first par.
items.append(line)
i += 1
continue
else:
return items, i + 1
else: # Blank line: _maybe_ we are done.
blank_line = True
i += 1 # advance
# Find the next non-blank line
for j in range(i, len(lines)):
if lines[j].strip():
next_line = lines[j]
break
else:
# Include extreaneous padding to prevent raw HTML
# parsing issue: https://github.com/Python-Markdown/markdown/issues/584
items.append("")
i += 1
else:
break # There is no more text; we are done.
# Check if the next non-blank line is tabbed
if detab(next_line): # Yes, more work to do.
items.append("")
continue
else:
break # No, we are done.
else:
i += 1
return items, i
|
def detectTabbed(self, lines):
"""Find indented text and remove indent before further proccesing.
Keyword arguments:
* lines: an array of strings
Returns: a list of post processed items and the index of last line.
"""
items = []
blank_line = False # have we encountered a blank line yet?
i = 0 # to keep track of where we are
def detab(line):
match = TABBED_RE.match(line)
if match:
return match.group(4)
for line in lines:
if line.strip(): # Non-blank line
detabbed_line = detab(line)
if detabbed_line:
items.append(detabbed_line)
i += 1
continue
elif not blank_line and not DEF_RE.match(line):
# not tabbed but still part of first par.
items.append(line)
i += 1
continue
else:
return items, i + 1
else: # Blank line: _maybe_ we are done.
blank_line = True
i += 1 # advance
# Find the next non-blank line
for j in range(i, len(lines)):
if lines[j].strip():
next_line = lines[j]
break
else:
break # There is no more text; we are done.
# Check if the next non-blank line is tabbed
if detab(next_line): # Yes, more work to do.
items.append("")
continue
else:
break # No, we are done.
else:
i += 1
return items, i
|
https://github.com/Python-Markdown/markdown/issues/584
|
doc-pelican (0.7)$ python3 test.py
Markdown 2.6.9
Traceback (most recent call last):
File "test.py", line 22, in <module>
print(md.convert(text))
File "/usr/lib/python3/dist-packages/markdown/__init__.py", line 371, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 65, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 80, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 98, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 130, in run
block = self._process_nests(element, block)
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 97, in _process_nests
self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last
IndexError: list index out of range
|
IndexError
|
def run(self, lines):
new_text = []
while lines:
line = lines.pop(0)
m = self.RE.match(line)
if m:
id = m.group(1).strip().lower()
link = m.group(2).lstrip("<").rstrip(">")
t = m.group(5) or m.group(6) or m.group(7)
if not t:
# Check next line for title
tm = self.TITLE_RE.match(lines[0])
if tm:
lines.pop(0)
t = tm.group(2) or tm.group(3) or tm.group(4)
self.markdown.references[id] = (link, t)
# Preserve the line to prevent raw HTML indexing issue.
# https://github.com/Python-Markdown/markdown/issues/584
new_text.append("")
else:
new_text.append(line)
return new_text # + "\n"
|
def run(self, lines):
new_text = []
while lines:
line = lines.pop(0)
m = self.RE.match(line)
if m:
id = m.group(1).strip().lower()
link = m.group(2).lstrip("<").rstrip(">")
t = m.group(5) or m.group(6) or m.group(7)
if not t:
# Check next line for title
tm = self.TITLE_RE.match(lines[0])
if tm:
lines.pop(0)
t = tm.group(2) or tm.group(3) or tm.group(4)
self.markdown.references[id] = (link, t)
else:
new_text.append(line)
return new_text # + "\n"
|
https://github.com/Python-Markdown/markdown/issues/584
|
doc-pelican (0.7)$ python3 test.py
Markdown 2.6.9
Traceback (most recent call last):
File "test.py", line 22, in <module>
print(md.convert(text))
File "/usr/lib/python3/dist-packages/markdown/__init__.py", line 371, in convert
root = self.parser.parseDocument(self.lines).getroot()
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 65, in parseDocument
self.parseChunk(self.root, '\n'.join(lines))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 80, in parseChunk
self.parseBlocks(parent, text.split('\n\n'))
File "/usr/lib/python3/dist-packages/markdown/blockparser.py", line 98, in parseBlocks
if processor.run(parent, blocks) is not False:
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 130, in run
block = self._process_nests(element, block)
File "/usr/lib/python3/dist-packages/markdown/extensions/extra.py", line 97, in _process_nests
self.run(element, block[nest_index[-1][0]:nest_index[-1][1]], # last
IndexError: list index out of range
|
IndexError
|
def run(self, root):
"""Add linebreaks to ElementTree root object."""
self._prettifyETree(root)
# Do <br />'s seperately as they are often in the middle of
# inline content and missed by _prettifyETree.
brs = root.iter("br")
for br in brs:
if not br.tail or not br.tail.strip():
br.tail = "\n"
else:
br.tail = "\n%s" % br.tail
# Clean up extra empty lines at end of code blocks.
pres = root.iter("pre")
for pre in pres:
if len(pre) and pre[0].tag == "code":
pre[0].text = util.AtomicString(pre[0].text.rstrip() + "\n")
|
def run(self, root):
"""Add linebreaks to ElementTree root object."""
self._prettifyETree(root)
# Do <br />'s seperately as they are often in the middle of
# inline content and missed by _prettifyETree.
brs = root.getiterator("br")
for br in brs:
if not br.tail or not br.tail.strip():
br.tail = "\n"
else:
br.tail = "\n%s" % br.tail
# Clean up extra empty lines at end of code blocks.
pres = root.getiterator("pre")
for pre in pres:
if len(pre) and pre[0].tag == "code":
pre[0].text = util.AtomicString(pre[0].text.rstrip() + "\n")
|
https://github.com/Python-Markdown/markdown/issues/499
|
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-hiv4fz31/Markdown/setup.py", line 270, in <module>
'Topic :: Text Processing :: Markup :: HTML'
File "/usr/local/lib/python3.6/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/local/lib/python3.6/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/usr/local/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/usr/local/lib/python3.6/site-packages/setuptools/command/install.py", line 61, in run
return orig.install.run(self)
File "/usr/local/lib/python3.6/distutils/command/install.py", line 545, in run
self.run_command('build')
File "/usr/local/lib/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/usr/local/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/usr/local/lib/python3.6/distutils/command/build.py", line 135, in run
self.run_command(cmd_name)
File "/usr/local/lib/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/usr/local/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/tmp/pip-build-hiv4fz31/Markdown/setup.py", line 184, in run
out = template % self._get_context(src, outfile)
File "/tmp/pip-build-hiv4fz31/Markdown/setup.py", line 116, in _get_context
c['body'] = self.md.convert(src)
File "build/lib/markdown/__init__.py", line 375, in convert
newRoot = treeprocessor.run(root)
File "build/lib/markdown/treeprocessors.py", line 361, in run
brs = root.getiterator('br')
SystemError: Python/getargs.c:1508: bad argument to internal function
|
SystemError
|
def unescape(self, text):
"""Return unescaped text given text with an inline placeholder."""
try:
stash = self.markdown.treeprocessors["inline"].stashed_nodes
except KeyError:
return text
def get_stash(m):
id = m.group(1)
if id in stash:
text = stash.get(id)
if isinstance(text, basestring):
return text
else:
return self.markdown.serializer(text)
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
|
def unescape(self, text):
"""Return unescaped text given text with an inline placeholder."""
try:
stash = self.markdown.treeprocessors["inline"].stashed_nodes
except KeyError:
return text
def get_stash(m):
id = m.group(1)
if id in stash:
return stash.get(id)
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
|
https://github.com/Python-Markdown/markdown/issues/155
|
In [1]: import markdown
In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1401fbb3dfde> in <module>()
----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>')
Python-Markdown/markdown/__init__.pyc in convert(self, source)
300 # Run the tree-processors
301 for treeprocessor in self.treeprocessors.values():
--> 302 newRoot = treeprocessor.run(root)
303 if newRoot:
304 root = newRoot
Python-Markdown/markdown/treeprocessors.pyc in run(self, tree)
287 child.text = None
288 lst = self.__processPlaceholders(self.__handleInline(
--> 289 text), child)
290 stack += lst
291 insertQueue.append((child, lst))
Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)
108 data, matched, startIndex = self.__applyPattern(
109 self.markdown.inlinePatterns.value_for_index(patternIndex),
--> 110 data, patternIndex, startIndex)
111 if not matched:
112 patternIndex += 1
Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)
235 return data, False, 0
236
--> 237 node = pattern.handleMatch(match)
238
239 if node is None:
Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)
436 def handleMatch(self, m):
437 el = util.etree.Element('a')
--> 438 email = self.unescape(m.group(2))
439 if email.startswith("mailto:"):
440 email = email[len("mailto:"):]
Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)
196 if id in stash:
197 return stash.get(id)
--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
199
200
TypeError: sequence item 1: expected string or Unicode, Element found
|
TypeError
|
def get_stash(m):
id = m.group(1)
if id in stash:
text = stash.get(id)
if isinstance(text, basestring):
return text
else:
return self.markdown.serializer(text)
|
def get_stash(m):
id = m.group(1)
if id in stash:
return stash.get(id)
|
https://github.com/Python-Markdown/markdown/issues/155
|
In [1]: import markdown
In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1401fbb3dfde> in <module>()
----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>')
Python-Markdown/markdown/__init__.pyc in convert(self, source)
300 # Run the tree-processors
301 for treeprocessor in self.treeprocessors.values():
--> 302 newRoot = treeprocessor.run(root)
303 if newRoot:
304 root = newRoot
Python-Markdown/markdown/treeprocessors.pyc in run(self, tree)
287 child.text = None
288 lst = self.__processPlaceholders(self.__handleInline(
--> 289 text), child)
290 stack += lst
291 insertQueue.append((child, lst))
Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)
108 data, matched, startIndex = self.__applyPattern(
109 self.markdown.inlinePatterns.value_for_index(patternIndex),
--> 110 data, patternIndex, startIndex)
111 if not matched:
112 patternIndex += 1
Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)
235 return data, False, 0
236
--> 237 node = pattern.handleMatch(match)
238
239 if node is None:
Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)
436 def handleMatch(self, m):
437 el = util.etree.Element('a')
--> 438 email = self.unescape(m.group(2))
439 if email.startswith("mailto:"):
440 email = email[len("mailto:"):]
Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)
196 if id in stash:
197 return stash.get(id)
--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
199
200
TypeError: sequence item 1: expected string or Unicode, Element found
|
TypeError
|
def unescape(self, text):
"""Return unescaped text given text with an inline placeholder."""
try:
stash = self.markdown.treeprocessors["inline"].stashed_nodes
except KeyError:
return text
def itertext(el):
"Reimplement Element.itertext for older python versions"
tag = el.tag
if not isinstance(tag, basestring) and tag is not None:
return
if el.text:
yield el.text
for e in el:
for s in itertext(e):
yield s
if e.tail:
yield e.tail
def get_stash(m):
id = m.group(1)
if id in stash:
value = stash.get(id)
if isinstance(value, basestring):
return value
else:
# An etree Element - return text content only
return "".join(itertext(value))
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
|
def unescape(self, text):
"""Return unescaped text given text with an inline placeholder."""
try:
stash = self.markdown.treeprocessors["inline"].stashed_nodes
except KeyError:
return text
def get_stash(m):
id = m.group(1)
if id in stash:
text = stash.get(id)
if isinstance(text, basestring):
return text
else:
return self.markdown.serializer(text)
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
|
https://github.com/Python-Markdown/markdown/issues/155
|
In [1]: import markdown
In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1401fbb3dfde> in <module>()
----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>')
Python-Markdown/markdown/__init__.pyc in convert(self, source)
300 # Run the tree-processors
301 for treeprocessor in self.treeprocessors.values():
--> 302 newRoot = treeprocessor.run(root)
303 if newRoot:
304 root = newRoot
Python-Markdown/markdown/treeprocessors.pyc in run(self, tree)
287 child.text = None
288 lst = self.__processPlaceholders(self.__handleInline(
--> 289 text), child)
290 stack += lst
291 insertQueue.append((child, lst))
Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)
108 data, matched, startIndex = self.__applyPattern(
109 self.markdown.inlinePatterns.value_for_index(patternIndex),
--> 110 data, patternIndex, startIndex)
111 if not matched:
112 patternIndex += 1
Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)
235 return data, False, 0
236
--> 237 node = pattern.handleMatch(match)
238
239 if node is None:
Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)
436 def handleMatch(self, m):
437 el = util.etree.Element('a')
--> 438 email = self.unescape(m.group(2))
439 if email.startswith("mailto:"):
440 email = email[len("mailto:"):]
Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)
196 if id in stash:
197 return stash.get(id)
--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
199
200
TypeError: sequence item 1: expected string or Unicode, Element found
|
TypeError
|
def get_stash(m):
id = m.group(1)
value = stash.get(id)
if value is not None:
try:
return self.markdown.serializer(text)
except:
return "\%s" % value
|
def get_stash(m):
id = m.group(1)
value = stash.get(id)
if value is not None:
try:
return self.markdown.serializer(value)
except:
return "\%s" % value
|
https://github.com/Python-Markdown/markdown/issues/155
|
In [1]: import markdown
In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1401fbb3dfde> in <module>()
----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>')
Python-Markdown/markdown/__init__.pyc in convert(self, source)
300 # Run the tree-processors
301 for treeprocessor in self.treeprocessors.values():
--> 302 newRoot = treeprocessor.run(root)
303 if newRoot:
304 root = newRoot
Python-Markdown/markdown/treeprocessors.pyc in run(self, tree)
287 child.text = None
288 lst = self.__processPlaceholders(self.__handleInline(
--> 289 text), child)
290 stack += lst
291 insertQueue.append((child, lst))
Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)
108 data, matched, startIndex = self.__applyPattern(
109 self.markdown.inlinePatterns.value_for_index(patternIndex),
--> 110 data, patternIndex, startIndex)
111 if not matched:
112 patternIndex += 1
Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)
235 return data, False, 0
236
--> 237 node = pattern.handleMatch(match)
238
239 if node is None:
Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)
436 def handleMatch(self, m):
437 el = util.etree.Element('a')
--> 438 email = self.unescape(m.group(2))
439 if email.startswith("mailto:"):
440 email = email[len("mailto:"):]
Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)
196 if id in stash:
197 return stash.get(id)
--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
199
200
TypeError: sequence item 1: expected string or Unicode, Element found
|
TypeError
|
def get_stash(m):
id = m.group(1)
if id in stash:
value = stash.get(id)
if isinstance(value, basestring):
return value
else:
# An etree Element - return text content only
return "".join(itertext(value))
|
def get_stash(m):
id = m.group(1)
if id in stash:
text = stash.get(id)
if isinstance(text, basestring):
return text
else:
return self.markdown.serializer(text)
|
https://github.com/Python-Markdown/markdown/issues/155
|
In [1]: import markdown
In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1401fbb3dfde> in <module>()
----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>')
Python-Markdown/markdown/__init__.pyc in convert(self, source)
300 # Run the tree-processors
301 for treeprocessor in self.treeprocessors.values():
--> 302 newRoot = treeprocessor.run(root)
303 if newRoot:
304 root = newRoot
Python-Markdown/markdown/treeprocessors.pyc in run(self, tree)
287 child.text = None
288 lst = self.__processPlaceholders(self.__handleInline(
--> 289 text), child)
290 stack += lst
291 insertQueue.append((child, lst))
Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)
108 data, matched, startIndex = self.__applyPattern(
109 self.markdown.inlinePatterns.value_for_index(patternIndex),
--> 110 data, patternIndex, startIndex)
111 if not matched:
112 patternIndex += 1
Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)
235 return data, False, 0
236
--> 237 node = pattern.handleMatch(match)
238
239 if node is None:
Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)
436 def handleMatch(self, m):
437 el = util.etree.Element('a')
--> 438 email = self.unescape(m.group(2))
439 if email.startswith("mailto:"):
440 email = email[len("mailto:"):]
Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)
196 if id in stash:
197 return stash.get(id)
--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
199
200
TypeError: sequence item 1: expected string or Unicode, Element found
|
TypeError
|
def unescape(self, text):
"""Return unescaped text given text with an inline placeholder."""
try:
stash = self.markdown.treeprocessors["inline"].stashed_nodes
except KeyError:
return text
def get_stash(m):
id = m.group(1)
value = stash.get(id)
if value is not None:
try:
return self.markdown.serializer(text)
except:
return "\%s" % value
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
|
def unescape(self, text):
"""Return unescaped text given text with an inline placeholder."""
try:
stash = self.markdown.treeprocessors["inline"].stashed_nodes
except KeyError:
return text
def get_stash(m):
id = m.group(1)
value = stash.get(id)
if value is not None:
try:
return self.markdown.serializer(value)
except:
return "\%s" % value
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
|
https://github.com/Python-Markdown/markdown/issues/155
|
In [1]: import markdown
In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1401fbb3dfde> in <module>()
----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>')
Python-Markdown/markdown/__init__.pyc in convert(self, source)
300 # Run the tree-processors
301 for treeprocessor in self.treeprocessors.values():
--> 302 newRoot = treeprocessor.run(root)
303 if newRoot:
304 root = newRoot
Python-Markdown/markdown/treeprocessors.pyc in run(self, tree)
287 child.text = None
288 lst = self.__processPlaceholders(self.__handleInline(
--> 289 text), child)
290 stack += lst
291 insertQueue.append((child, lst))
Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)
108 data, matched, startIndex = self.__applyPattern(
109 self.markdown.inlinePatterns.value_for_index(patternIndex),
--> 110 data, patternIndex, startIndex)
111 if not matched:
112 patternIndex += 1
Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)
235 return data, False, 0
236
--> 237 node = pattern.handleMatch(match)
238
239 if node is None:
Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)
436 def handleMatch(self, m):
437 el = util.etree.Element('a')
--> 438 email = self.unescape(m.group(2))
439 if email.startswith("mailto:"):
440 email = email[len("mailto:"):]
Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)
196 if id in stash:
197 return stash.get(id)
--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
199
200
TypeError: sequence item 1: expected string or Unicode, Element found
|
TypeError
|
def makeTag(self, href, title, text):
el = util.etree.Element("img")
el.set("src", self.sanitize_url(href))
if title:
el.set("title", title)
el.set("alt", self.unescape(text))
return el
|
def makeTag(self, href, title, text):
el = util.etree.Element("img")
el.set("src", self.sanitize_url(href))
if title:
el.set("title", title)
el.set("alt", text)
return el
|
https://github.com/Python-Markdown/markdown/issues/155
|
In [1]: import markdown
In [2]: markdown.Markdown(safe_mode='escape').convert('<@`x`>')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1401fbb3dfde> in <module>()
----> 1 markdown.Markdown(safe_mode='escape').convert('<@`x`>')
Python-Markdown/markdown/__init__.pyc in convert(self, source)
300 # Run the tree-processors
301 for treeprocessor in self.treeprocessors.values():
--> 302 newRoot = treeprocessor.run(root)
303 if newRoot:
304 root = newRoot
Python-Markdown/markdown/treeprocessors.pyc in run(self, tree)
287 child.text = None
288 lst = self.__processPlaceholders(self.__handleInline(
--> 289 text), child)
290 stack += lst
291 insertQueue.append((child, lst))
Python-Markdown/markdown/treeprocessors.pyc in __handleInline(self, data, patternIndex)
108 data, matched, startIndex = self.__applyPattern(
109 self.markdown.inlinePatterns.value_for_index(patternIndex),
--> 110 data, patternIndex, startIndex)
111 if not matched:
112 patternIndex += 1
Python-Markdown/markdown/treeprocessors.pyc in __applyPattern(self, pattern, data, patternIndex, startIndex)
235 return data, False, 0
236
--> 237 node = pattern.handleMatch(match)
238
239 if node is None:
Python-Markdown/markdown/inlinepatterns.pyc in handleMatch(self, m)
436 def handleMatch(self, m):
437 el = util.etree.Element('a')
--> 438 email = self.unescape(m.group(2))
439 if email.startswith("mailto:"):
440 email = email[len("mailto:"):]
Python-Markdown/markdown/inlinepatterns.pyc in unescape(self, text)
196 if id in stash:
197 return stash.get(id)
--> 198 return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
199
200
TypeError: sequence item 1: expected string or Unicode, Element found
|
TypeError
|
def _get_left_tag(self, block):
m = self.left_tag_re.match(block)
if m:
tag = m.group("tag")
raw_attrs = m.group("attrs")
attrs = {}
if raw_attrs:
for ma in self.attrs_re.finditer(raw_attrs):
if ma.group("attr"):
if ma.group("value"):
attrs[ma.group("attr").strip()] = ma.group("value")
else:
attrs[ma.group("attr").strip()] = ""
elif ma.group("attr1"):
if ma.group("value1"):
attrs[ma.group("attr1").strip()] = ma.group("value1")
else:
attrs[ma.group("attr1").strip()] = ""
elif ma.group("attr2"):
attrs[ma.group("attr2").strip()] = ""
return tag, len(m.group(0)), attrs
else:
tag = block[1:].split(">", 1)[0].lower()
return tag, len(tag) + 2, {}
|
def _get_left_tag(self, block):
m = self.left_tag_re.match(block)
if m:
tag = m.group("tag")
raw_attrs = m.group("attrs")
attrs = {}
if raw_attrs:
for ma in self.attrs_re.finditer(raw_attrs):
if ma.group("attr"):
if ma.group("value"):
attrs[ma.group("attr").strip()] = ma.group("value")
else:
attrs[ma.group("attr").strip()] = ""
elif ma.group("attr1"):
if ma.group("value1"):
attrs[ma.group("attr1").strip()] = ma.group("value1")
else:
attrs[ma.group("attr1").strip()] = ""
elif ma.group("attr2"):
attrs[ma.group("attr2").strip()] = ""
return tag, len(m.group(0)), attrs
else:
tag = block[1:].replace(">", " ", 1).split()[0].lower()
return tag, len(tag) + 2, {}
|
https://github.com/Python-Markdown/markdown/issues/70
|
markdown.markdown('<>')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/__init__.py", line 386, in markdown
return md.convert(text)
File "/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/__init__.py", line 280, in convert
self.lines = prep.run(self.lines)
File "/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/preprocessors.py", line 146, in run
left_tag, left_index, attrs = self._get_left_tag(block)
File "/Users/aaronsw/Code/infohacks/jottit/code/env/lib/python2.7/site-packages/markdown/preprocessors.py", line 81, in _get_left_tag
tag = block[1:].replace(">", " ", 1).split()[0].lower()
IndexError: list index out of range
|
IndexError
|
def sort_imports(
file_name: str,
config: Config,
check: bool = False,
ask_to_apply: bool = False,
write_to_stdout: bool = False,
**kwargs: Any,
) -> Optional[SortAttempt]:
incorrectly_sorted: bool = False
skipped: bool = False
try:
if check:
try:
incorrectly_sorted = not api.check_file(
file_name, config=config, **kwargs
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped, True)
try:
incorrectly_sorted = not api.sort_file(
file_name,
config=config,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
**kwargs,
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped, True)
except (OSError, ValueError) as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
except UnsupportedEncoding:
if config.verbose:
warn(f"Encoding not supported for {file_name}")
return SortAttempt(incorrectly_sorted, skipped, False)
except KeyError as error:
if error.args[0] not in DEFAULT_CONFIG.sections:
_print_hard_fail(config, offending_file=file_name)
raise
msg = (
f"Found {error} imports while parsing, but {error} was not included "
"in the `sections` setting of your config. Please add it before continuing\n"
"See https://pycqa.github.io/isort/#custom-sections-and-ordering "
"for more info."
)
_print_hard_fail(config, message=msg)
sys.exit(os.EX_CONFIG)
except Exception:
_print_hard_fail(config, offending_file=file_name)
raise
|
def sort_imports(
file_name: str,
config: Config,
check: bool = False,
ask_to_apply: bool = False,
write_to_stdout: bool = False,
**kwargs: Any,
) -> Optional[SortAttempt]:
incorrectly_sorted: bool = False
skipped: bool = False
try:
if check:
try:
incorrectly_sorted = not api.check_file(
file_name, config=config, **kwargs
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped, True)
try:
incorrectly_sorted = not api.sort_file(
file_name,
config=config,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
**kwargs,
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped, True)
except (OSError, ValueError) as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
except UnsupportedEncoding:
if config.verbose:
warn(f"Encoding not supported for {file_name}")
return SortAttempt(incorrectly_sorted, skipped, False)
except Exception:
printer = create_terminal_printer(color=config.color_output)
printer.error(
f"Unrecoverable exception thrown when parsing {file_name}! "
"This should NEVER happen.\n"
"If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"
)
raise
|
https://github.com/PyCQA/isort/issues/1570
|
ERROR: Unrecoverable exception thrown when parsing src/eduid_webapp/eidas/app.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/home/lundberg/python-environments/eduid-webapp/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py", line 953, in main
for sort_attempt in attempt_iterator:
File "/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py", line 939, in <genexpr>
sort_imports( # type: ignore
File "/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/main.py", line 95, in sort_imports
incorrectly_sorted = not api.sort_file(
File "/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/api.py", line 324, in sort_file
changed = sort_stream(
File "/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/api.py", line 158, in sort_stream
changed = core.process(
File "/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/core.py", line 332, in process
parsed_content = parse.file_contents(import_section, config=config)
File "/home/lundberg/python-environments/eduid-webapp/lib/python3.8/site-packages/isort/parse.py", line 432, in file_contents
root = imports[placed_module][type_of_import] # type: ignore
KeyError: 'LOCALFOLDER'
|
KeyError
|
def __init__(
self,
filename: Union[str, Path],
):
super().__init__(f"Unknown or unsupported encoding in {filename}")
self.filename = filename
|
def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]):
errors = "\n".join(
self._format_option(name, **option)
for name, option in unsupported_settings.items()
)
super().__init__(
"isort was provided settings that it doesn't support:\n\n"
f"{errors}\n\n"
"For a complete and up-to-date listing of supported settings see: "
"https://pycqa.github.io/isort/docs/configuration/options/.\n"
)
self.unsupported_settings = unsupported_settings
|
https://github.com/PyCQA/isort/issues/1487
|
ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/usr/lib/python3.8/tokenize.py", line 342, in find_cookie
codec = lookup(encoding)
LookupError: unknown encoding: IBO-8859-1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 886, in main
for sort_attempt in attempt_iterator:
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 875, in <genexpr>
sort_imports( # type: ignore
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 94, in sort_imports
incorrectly_sorted = not api.sort_file(
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py", line 300, in sort_file
with io.File.read(filename) as source_file:
File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 48, in read
stream = File._open(file_path)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 33, in _open
encoding, _ = tokenize.detect_encoding(buffer.readline)
File "/usr/lib/python3.8/tokenize.py", line 381, in detect_encoding
encoding = find_cookie(second)
File "/usr/lib/python3.8/tokenize.py", line 350, in find_cookie
raise SyntaxError(msg)
SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1
|
LookupError
|
def from_contents(contents: str, filename: str) -> "File":
encoding = File.detect_encoding(
filename, BytesIO(contents.encode("utf-8")).readline
)
return File(StringIO(contents), path=Path(filename).resolve(), encoding=encoding)
|
def from_contents(contents: str, filename: str) -> "File":
encoding, _ = tokenize.detect_encoding(BytesIO(contents.encode("utf-8")).readline)
return File(StringIO(contents), path=Path(filename).resolve(), encoding=encoding)
|
https://github.com/PyCQA/isort/issues/1487
|
ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/usr/lib/python3.8/tokenize.py", line 342, in find_cookie
codec = lookup(encoding)
LookupError: unknown encoding: IBO-8859-1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 886, in main
for sort_attempt in attempt_iterator:
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 875, in <genexpr>
sort_imports( # type: ignore
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 94, in sort_imports
incorrectly_sorted = not api.sort_file(
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py", line 300, in sort_file
with io.File.read(filename) as source_file:
File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 48, in read
stream = File._open(file_path)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 33, in _open
encoding, _ = tokenize.detect_encoding(buffer.readline)
File "/usr/lib/python3.8/tokenize.py", line 381, in detect_encoding
encoding = find_cookie(second)
File "/usr/lib/python3.8/tokenize.py", line 350, in find_cookie
raise SyntaxError(msg)
SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1
|
LookupError
|
def _open(filename):
"""Open a file in read only mode using the encoding detected by
detect_encoding().
"""
buffer = open(filename, "rb")
try:
encoding = File.detect_encoding(filename, buffer.readline)
buffer.seek(0)
text = TextIOWrapper(buffer, encoding, line_buffering=True, newline="")
text.mode = "r" # type: ignore
return text
except Exception:
buffer.close()
raise
|
def _open(filename):
"""Open a file in read only mode using the encoding detected by
detect_encoding().
"""
buffer = open(filename, "rb")
try:
encoding, _ = tokenize.detect_encoding(buffer.readline)
buffer.seek(0)
text = TextIOWrapper(buffer, encoding, line_buffering=True, newline="")
text.mode = "r" # type: ignore
return text
except Exception:
buffer.close()
raise
|
https://github.com/PyCQA/isort/issues/1487
|
ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/usr/lib/python3.8/tokenize.py", line 342, in find_cookie
codec = lookup(encoding)
LookupError: unknown encoding: IBO-8859-1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 886, in main
for sort_attempt in attempt_iterator:
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 875, in <genexpr>
sort_imports( # type: ignore
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 94, in sort_imports
incorrectly_sorted = not api.sort_file(
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py", line 300, in sort_file
with io.File.read(filename) as source_file:
File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 48, in read
stream = File._open(file_path)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 33, in _open
encoding, _ = tokenize.detect_encoding(buffer.readline)
File "/usr/lib/python3.8/tokenize.py", line 381, in detect_encoding
encoding = find_cookie(second)
File "/usr/lib/python3.8/tokenize.py", line 350, in find_cookie
raise SyntaxError(msg)
SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1
|
LookupError
|
def __init__(
self, incorrectly_sorted: bool, skipped: bool, supported_encoding: bool
) -> None:
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
self.supported_encoding = supported_encoding
|
def __init__(self, incorrectly_sorted: bool, skipped: bool) -> None:
self.incorrectly_sorted = incorrectly_sorted
self.skipped = skipped
|
https://github.com/PyCQA/isort/issues/1487
|
ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/usr/lib/python3.8/tokenize.py", line 342, in find_cookie
codec = lookup(encoding)
LookupError: unknown encoding: IBO-8859-1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 886, in main
for sort_attempt in attempt_iterator:
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 875, in <genexpr>
sort_imports( # type: ignore
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 94, in sort_imports
incorrectly_sorted = not api.sort_file(
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py", line 300, in sort_file
with io.File.read(filename) as source_file:
File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 48, in read
stream = File._open(file_path)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 33, in _open
encoding, _ = tokenize.detect_encoding(buffer.readline)
File "/usr/lib/python3.8/tokenize.py", line 381, in detect_encoding
encoding = find_cookie(second)
File "/usr/lib/python3.8/tokenize.py", line 350, in find_cookie
raise SyntaxError(msg)
SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1
|
LookupError
|
def sort_imports(
file_name: str,
config: Config,
check: bool = False,
ask_to_apply: bool = False,
write_to_stdout: bool = False,
**kwargs: Any,
) -> Optional[SortAttempt]:
try:
incorrectly_sorted: bool = False
skipped: bool = False
if check:
try:
incorrectly_sorted = not api.check_file(
file_name, config=config, **kwargs
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped, True)
else:
try:
incorrectly_sorted = not api.sort_file(
file_name,
config=config,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
**kwargs,
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped, True)
except (OSError, ValueError) as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
except UnsupportedEncoding:
if config.verbose:
warn(f"Encoding not supported for {file_name}")
return SortAttempt(incorrectly_sorted, skipped, False)
except Exception:
printer = create_terminal_printer(color=config.color_output)
printer.error(
f"Unrecoverable exception thrown when parsing {file_name}! "
"This should NEVER happen.\n"
"If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"
)
raise
|
def sort_imports(
file_name: str,
config: Config,
check: bool = False,
ask_to_apply: bool = False,
write_to_stdout: bool = False,
**kwargs: Any,
) -> Optional[SortAttempt]:
try:
incorrectly_sorted: bool = False
skipped: bool = False
if check:
try:
incorrectly_sorted = not api.check_file(
file_name, config=config, **kwargs
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped)
else:
try:
incorrectly_sorted = not api.sort_file(
file_name,
config=config,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
**kwargs,
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped)
except (OSError, ValueError) as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
except Exception:
printer = create_terminal_printer(color=config.color_output)
printer.error(
f"Unrecoverable exception thrown when parsing {file_name}! "
"This should NEVER happen.\n"
"If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"
)
raise
|
https://github.com/PyCQA/isort/issues/1487
|
ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/usr/lib/python3.8/tokenize.py", line 342, in find_cookie
codec = lookup(encoding)
LookupError: unknown encoding: IBO-8859-1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 886, in main
for sort_attempt in attempt_iterator:
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 875, in <genexpr>
sort_imports( # type: ignore
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 94, in sort_imports
incorrectly_sorted = not api.sort_file(
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py", line 300, in sort_file
with io.File.read(filename) as source_file:
File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 48, in read
stream = File._open(file_path)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 33, in _open
encoding, _ = tokenize.detect_encoding(buffer.readline)
File "/usr/lib/python3.8/tokenize.py", line 381, in detect_encoding
encoding = find_cookie(second)
File "/usr/lib/python3.8/tokenize.py", line 350, in find_cookie
raise SyntaxError(msg)
SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1
|
LookupError
|
def main(
argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None
) -> None:
arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
show_files: bool = arguments.pop("show_files", False)
if show_config and show_files:
sys.exit("Error: either specify show-config or show-files not both.")
if "settings_path" in arguments:
if os.path.isfile(arguments["settings_path"]):
arguments["settings_file"] = os.path.abspath(arguments["settings_path"])
arguments["settings_path"] = os.path.dirname(arguments["settings_file"])
else:
arguments["settings_path"] = os.path.abspath(arguments["settings_path"])
if "virtual_env" in arguments:
venv = arguments["virtual_env"]
arguments["virtual_env"] = os.path.abspath(venv)
if not os.path.isdir(arguments["virtual_env"]):
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")
file_names = arguments.pop("files", [])
if not file_names and not show_config:
print(QUICK_GUIDE)
if arguments:
sys.exit("Error: arguments passed in without any paths or content.")
else:
return
if "settings_path" not in arguments:
arguments["settings_path"] = (
os.path.abspath(file_names[0] if file_names else ".") or os.getcwd()
)
if not os.path.isdir(arguments["settings_path"]):
arguments["settings_path"] = os.path.dirname(arguments["settings_path"])
config_dict = arguments.copy()
ask_to_apply = config_dict.pop("ask_to_apply", False)
jobs = config_dict.pop("jobs", ())
check = config_dict.pop("check", False)
show_diff = config_dict.pop("show_diff", False)
write_to_stdout = config_dict.pop("write_to_stdout", False)
deprecated_flags = config_dict.pop("deprecated_flags", False)
remapped_deprecated_args = config_dict.pop("remapped_deprecated_args", False)
wrong_sorted_files = False
all_attempt_broken = False
no_valid_encodings = False
if "src_paths" in config_dict:
config_dict["src_paths"] = {
Path(src_path).resolve() for src_path in config_dict.get("src_paths", ())
}
config = Config(**config_dict)
if show_config:
print(
json.dumps(
config.__dict__, indent=4, separators=(",", ": "), default=_preconvert
)
)
return
elif file_names == ["-"]:
if show_files:
sys.exit("Error: can't show files for streaming input.")
if check:
incorrectly_sorted = not api.check_stream(
input_stream=sys.stdin if stdin is None else stdin,
config=config,
show_diff=show_diff,
)
wrong_sorted_files = incorrectly_sorted
else:
api.sort_stream(
input_stream=sys.stdin if stdin is None else stdin,
output_stream=sys.stdout,
config=config,
show_diff=show_diff,
)
else:
skipped: List[str] = []
broken: List[str] = []
if config.filter_files:
filtered_files = []
for file_name in file_names:
if config.is_skipped(Path(file_name)):
skipped.append(file_name)
else:
filtered_files.append(file_name)
file_names = filtered_files
file_names = iter_source_code(file_names, config, skipped, broken)
if show_files:
for file_name in file_names:
print(file_name)
return
num_skipped = 0
num_broken = 0
num_invalid_encoding = 0
if config.verbose:
print(ASCII_ART)
if jobs:
import multiprocessing
executor = multiprocessing.Pool(jobs)
attempt_iterator = executor.imap(
functools.partial(
sort_imports,
config=config,
check=check,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
),
file_names,
)
else:
# https://github.com/python/typeshed/pull/2814
attempt_iterator = (
sort_imports( # type: ignore
file_name,
config=config,
check=check,
ask_to_apply=ask_to_apply,
show_diff=show_diff,
write_to_stdout=write_to_stdout,
)
for file_name in file_names
)
# If any files passed in are missing considered as error, should be removed
is_no_attempt = True
any_encoding_valid = False
for sort_attempt in attempt_iterator:
if not sort_attempt:
continue # pragma: no cover - shouldn't happen, satisfies type constraint
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get("check", False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code
if not sort_attempt.supported_encoding:
num_invalid_encoding += 1
else:
any_encoding_valid = True
is_no_attempt = False
num_skipped += len(skipped)
if num_skipped and not arguments.get("quiet", False):
if config.verbose:
for was_skipped in skipped:
warn(
f"{was_skipped} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting"
)
print(f"Skipped {num_skipped} files")
num_broken += len(broken)
if num_broken and not arguments.get("quite", False):
if config.verbose:
for was_broken in broken:
warn(f"{was_broken} was broken path, make sure it exists correctly")
print(f"Broken {num_broken} paths")
if num_broken > 0 and is_no_attempt:
all_attempt_broken = True
if num_invalid_encoding > 0 and not any_encoding_valid:
no_valid_encodings = True
if not config.quiet and (remapped_deprecated_args or deprecated_flags):
if remapped_deprecated_args:
warn(
"W0502: The following deprecated single dash CLI flags were used and translated: "
f"{', '.join(remapped_deprecated_args)}!"
)
if deprecated_flags:
warn(
"W0501: The following deprecated CLI flags were used and ignored: "
f"{', '.join(deprecated_flags)}!"
)
warn(
"W0500: Please see the 5.0.0 Upgrade guide: "
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"
)
if wrong_sorted_files:
sys.exit(1)
if all_attempt_broken:
sys.exit(1)
if no_valid_encodings:
printer = create_terminal_printer(color=config.color_output)
printer.error("No valid encodings.")
sys.exit(1)
|
def main(
argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None
) -> None:
arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
show_files: bool = arguments.pop("show_files", False)
if show_config and show_files:
sys.exit("Error: either specify show-config or show-files not both.")
if "settings_path" in arguments:
if os.path.isfile(arguments["settings_path"]):
arguments["settings_file"] = os.path.abspath(arguments["settings_path"])
arguments["settings_path"] = os.path.dirname(arguments["settings_file"])
else:
arguments["settings_path"] = os.path.abspath(arguments["settings_path"])
if "virtual_env" in arguments:
venv = arguments["virtual_env"]
arguments["virtual_env"] = os.path.abspath(venv)
if not os.path.isdir(arguments["virtual_env"]):
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")
file_names = arguments.pop("files", [])
if not file_names and not show_config:
print(QUICK_GUIDE)
if arguments:
sys.exit("Error: arguments passed in without any paths or content.")
else:
return
if "settings_path" not in arguments:
arguments["settings_path"] = (
os.path.abspath(file_names[0] if file_names else ".") or os.getcwd()
)
if not os.path.isdir(arguments["settings_path"]):
arguments["settings_path"] = os.path.dirname(arguments["settings_path"])
config_dict = arguments.copy()
ask_to_apply = config_dict.pop("ask_to_apply", False)
jobs = config_dict.pop("jobs", ())
check = config_dict.pop("check", False)
show_diff = config_dict.pop("show_diff", False)
write_to_stdout = config_dict.pop("write_to_stdout", False)
deprecated_flags = config_dict.pop("deprecated_flags", False)
remapped_deprecated_args = config_dict.pop("remapped_deprecated_args", False)
wrong_sorted_files = False
all_attempt_broken = False
if "src_paths" in config_dict:
config_dict["src_paths"] = {
Path(src_path).resolve() for src_path in config_dict.get("src_paths", ())
}
config = Config(**config_dict)
if show_config:
print(
json.dumps(
config.__dict__, indent=4, separators=(",", ": "), default=_preconvert
)
)
return
elif file_names == ["-"]:
if show_files:
sys.exit("Error: can't show files for streaming input.")
if check:
incorrectly_sorted = not api.check_stream(
input_stream=sys.stdin if stdin is None else stdin,
config=config,
show_diff=show_diff,
)
wrong_sorted_files = incorrectly_sorted
else:
api.sort_stream(
input_stream=sys.stdin if stdin is None else stdin,
output_stream=sys.stdout,
config=config,
show_diff=show_diff,
)
else:
skipped: List[str] = []
broken: List[str] = []
if config.filter_files:
filtered_files = []
for file_name in file_names:
if config.is_skipped(Path(file_name)):
skipped.append(file_name)
else:
filtered_files.append(file_name)
file_names = filtered_files
file_names = iter_source_code(file_names, config, skipped, broken)
if show_files:
for file_name in file_names:
print(file_name)
return
num_skipped = 0
num_broken = 0
if config.verbose:
print(ASCII_ART)
if jobs:
import multiprocessing
executor = multiprocessing.Pool(jobs)
attempt_iterator = executor.imap(
functools.partial(
sort_imports,
config=config,
check=check,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
),
file_names,
)
else:
# https://github.com/python/typeshed/pull/2814
attempt_iterator = (
sort_imports( # type: ignore
file_name,
config=config,
check=check,
ask_to_apply=ask_to_apply,
show_diff=show_diff,
write_to_stdout=write_to_stdout,
)
for file_name in file_names
)
# If any files passed in are missing considered as error, should be removed
is_no_attempt = True
for sort_attempt in attempt_iterator:
if not sort_attempt:
continue # pragma: no cover - shouldn't happen, satisfies type constraint
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get("check", False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code
is_no_attempt = False
num_skipped += len(skipped)
if num_skipped and not arguments.get("quiet", False):
if config.verbose:
for was_skipped in skipped:
warn(
f"{was_skipped} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting"
)
print(f"Skipped {num_skipped} files")
num_broken += len(broken)
if num_broken and not arguments.get("quite", False):
if config.verbose:
for was_broken in broken:
warn(f"{was_broken} was broken path, make sure it exists correctly")
print(f"Broken {num_broken} paths")
if num_broken > 0 and is_no_attempt:
all_attempt_broken = True
if not config.quiet and (remapped_deprecated_args or deprecated_flags):
if remapped_deprecated_args:
warn(
"W0502: The following deprecated single dash CLI flags were used and translated: "
f"{', '.join(remapped_deprecated_args)}!"
)
if deprecated_flags:
warn(
"W0501: The following deprecated CLI flags were used and ignored: "
f"{', '.join(deprecated_flags)}!"
)
warn(
"W0500: Please see the 5.0.0 Upgrade guide: "
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"
)
if wrong_sorted_files:
sys.exit(1)
if all_attempt_broken:
sys.exit(1)
|
https://github.com/PyCQA/isort/issues/1487
|
ERROR: Unrecoverable exception thrown when parsing tests/functional/u/unknown_encoding_py29.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/usr/lib/python3.8/tokenize.py", line 342, in find_cookie
codec = lookup(encoding)
LookupError: unknown encoding: IBO-8859-1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 886, in main
for sort_attempt in attempt_iterator:
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 875, in <genexpr>
sort_imports( # type: ignore
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/main.py", line 94, in sort_imports
incorrectly_sorted = not api.sort_file(
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/api.py", line 300, in sort_file
with io.File.read(filename) as source_file:
File "/usr/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 48, in read
stream = File._open(file_path)
File "/home/pierre/.cache/pre-commit/reposvah2k04/py_env-python3/lib/python3.8/site-packages/isort/io.py", line 33, in _open
encoding, _ = tokenize.detect_encoding(buffer.readline)
File "/usr/lib/python3.8/tokenize.py", line 381, in detect_encoding
encoding = find_cookie(second)
File "/usr/lib/python3.8/tokenize.py", line 350, in find_cookie
raise SyntaxError(msg)
SyntaxError: unknown encoding for '/home/pierre/pylint/tests/functional/u/unknown_encoding_py29.py': IBO-8859-1
|
LookupError
|
def _known_pattern(name: str, config: Config) -> Optional[Tuple[str, str]]:
parts = name.split(".")
module_names_to_check = (
".".join(parts[:first_k]) for first_k in range(len(parts), 0, -1)
)
for module_name_to_check in module_names_to_check:
for pattern, placement in config.known_patterns:
if placement in config.sections and pattern.match(module_name_to_check):
return (placement, f"Matched configured known pattern {pattern}")
return None
|
def _known_pattern(name: str, config: Config) -> Optional[Tuple[str, str]]:
parts = name.split(".")
module_names_to_check = (
".".join(parts[:first_k]) for first_k in range(len(parts), 0, -1)
)
for module_name_to_check in module_names_to_check:
for pattern, placement in config.known_patterns:
if pattern.match(module_name_to_check):
return (placement, f"Matched configured known pattern {pattern}")
return None
|
https://github.com/PyCQA/isort/issues/1505
|
lint installed: appdirs==1.4.4,black==20.8b1,bleach==3.2.1,check-manifest==0.43,click==7.1.2,docutils==0.16,flake8==3.8.3,isort==5.5.3,mccabe==0.6.1,mypy-extensions==0.4.3,packaging==20.4,pathspec==0.8.0,pep517==0.8.2,pycodestyle==2.6.0,pyflakes==2.2.0,Pygments==2.7.1,pyparsing==2.4.7,readme-renderer==26.0,regex==2020.9.27,six==1.15.0,toml==0.10.1,typed-ast==1.4.1,typing-extensions==3.7.4.3,webencodings==0.5.1
lint run-test-pre: PYTHONHASHSEED='979047687'
lint run-test: commands[0] | flake8 src/pyramid tests setup.py
lint run-test: commands[1] | isort --check-only --df src/pyramid tests setup.py
ERROR: Unrecoverable exception thrown when parsing src/pyramid/predicates.py! This should NEVER happen.
If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
Traceback (most recent call last):
File "/home/runner/work/pyramid/pyramid/.tox/lint/bin/isort", line 8, in <module>
sys.exit(main())
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py", line 886, in main
for sort_attempt in attempt_iterator:
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py", line 875, in <genexpr>
sort_imports( # type: ignore
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/main.py", line 88, in sort_imports
incorrectly_sorted = not api.check_file(file_name, config=config, **kwargs)
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py", line 264, in check_file
return check_stream(
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py", line 203, in check_stream
changed: bool = sort_stream(
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/api.py", line 158, in sort_stream
changed = core.process(
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/core.py", line 326, in process
parse.file_contents(import_section, config=config),
File "/home/runner/work/pyramid/pyramid/.tox/lint/lib/python3.8/site-packages/isort/parse.py", line 474, in file_contents
straight_import |= imports[placed_module][type_of_import].get( # type: ignore
KeyError: 'STDLIB'
ERROR: InvocationError for command /home/runner/work/pyramid/pyramid/.tox/lint/bin/isort --check-only --df src/pyramid tests setup.py (exited with code 1)
___________________________________ summary ____________________________________
ERROR: lint: commands failed
Error: Process completed with exit code 1.
|
KeyError
|
def process(
input_stream: TextIO,
output_stream: TextIO,
extension: str = "py",
config: Config = DEFAULT_CONFIG,
) -> bool:
"""Parses stream identifying sections of contiguous imports and sorting them
Code with unsorted imports is read from the provided `input_stream`, sorted and then
outputted to the specified `output_stream`.
- `input_stream`: Text stream with unsorted import sections.
- `output_stream`: Text stream to output sorted inputs into.
- `config`: Config settings to use when sorting imports. Defaults settings.
- *Default*: `isort.settings.DEFAULT_CONFIG`.
- `extension`: The file extension or file extension rules that should be used.
- *Default*: `"py"`.
- *Choices*: `["py", "pyi", "pyx"]`.
Returns `True` if there were changes that needed to be made (errors present) from what
was provided in the input_stream, otherwise `False`.
"""
line_separator: str = config.line_ending
add_imports: List[str] = [
format_natural(addition) for addition in config.add_imports
]
import_section: str = ""
next_import_section: str = ""
next_cimports: bool = False
in_quote: str = ""
first_comment_index_start: int = -1
first_comment_index_end: int = -1
contains_imports: bool = False
in_top_comment: bool = False
first_import_section: bool = True
section_comments = [f"# {heading}" for heading in config.import_headings.values()]
indent: str = ""
isort_off: bool = False
code_sorting: Union[bool, str] = False
code_sorting_section: str = ""
code_sorting_indent: str = ""
cimports: bool = False
made_changes: bool = False
stripped_line: str = ""
end_of_file: bool = False
if config.float_to_top:
new_input = ""
current = ""
isort_off = False
for line in chain(input_stream, (None,)):
if isort_off and line is not None:
if line == "# isort: on\n":
isort_off = False
new_input += line
elif line in ("# isort: split\n", "# isort: off\n", None) or str(
line
).endswith("# isort: split\n"):
if line == "# isort: off\n":
isort_off = True
if current:
parsed = parse.file_contents(current, config=config)
extra_space = ""
while current and current[-1] == "\n":
extra_space += "\n"
current = current[:-1]
extra_space = extra_space.replace("\n", "", 1)
sorted_output = output.sorted_imports(
parsed, config, extension, import_type="import"
)
made_changes = made_changes or _has_changed(
before=current,
after=sorted_output,
line_separator=parsed.line_separator,
ignore_whitespace=config.ignore_whitespace,
)
new_input += sorted_output
new_input += extra_space
current = ""
new_input += line or ""
else:
current += line or ""
input_stream = StringIO(new_input)
for index, line in enumerate(chain(input_stream, (None,))):
if line is None:
if index == 0 and not config.force_adds:
return False
not_imports = True
end_of_file = True
line = ""
if not line_separator:
line_separator = "\n"
if code_sorting and code_sorting_section:
output_stream.write(
textwrap.indent(
isort.literal.assignment(
code_sorting_section,
str(code_sorting),
extension,
config=_indented_config(config, indent),
),
code_sorting_indent,
)
)
else:
stripped_line = line.strip()
if stripped_line and not line_separator:
line_separator = (
line[len(line.rstrip()) :].replace(" ", "").replace("\t", "")
)
for file_skip_comment in FILE_SKIP_COMMENTS:
if file_skip_comment in line:
raise FileSkipComment("Passed in content")
if not in_quote and stripped_line == "# isort: off":
isort_off = True
if (
(index == 0 or (index in (1, 2) and not contains_imports))
and stripped_line.startswith("#")
and stripped_line not in section_comments
):
in_top_comment = True
elif in_top_comment:
if not line.startswith("#") or stripped_line in section_comments:
in_top_comment = False
first_comment_index_end = index - 1
if (
(not stripped_line.startswith("#") or in_quote)
and '"' in line
or "'" in line
):
char_index = 0
if first_comment_index_start == -1 and (
line.startswith('"') or line.startswith("'")
):
first_comment_index_start = index
while char_index < len(line):
if line[char_index] == "\\":
char_index += 1
elif in_quote:
if line[char_index : char_index + len(in_quote)] == in_quote:
in_quote = ""
if first_comment_index_end < first_comment_index_start:
first_comment_index_end = index
elif line[char_index] in ("'", '"'):
long_quote = line[char_index : char_index + 3]
if long_quote in ('"""', "'''"):
in_quote = long_quote
char_index += 2
else:
in_quote = line[char_index]
elif line[char_index] == "#":
break
char_index += 1
not_imports = bool(in_quote) or in_top_comment or isort_off
if not (in_quote or in_top_comment):
if isort_off:
if stripped_line == "# isort: on":
isort_off = False
elif stripped_line.endswith("# isort: split"):
not_imports = True
elif stripped_line in CODE_SORT_COMMENTS:
code_sorting = stripped_line.split("isort: ")[1].strip()
code_sorting_indent = line[: -len(line.lstrip())]
not_imports = True
elif code_sorting:
if not stripped_line:
output_stream.write(
textwrap.indent(
isort.literal.assignment(
code_sorting_section,
str(code_sorting),
extension,
config=_indented_config(config, indent),
),
code_sorting_indent,
)
)
not_imports = True
code_sorting = False
code_sorting_section = ""
code_sorting_indent = ""
else:
code_sorting_section += line
line = ""
elif stripped_line in config.section_comments and not import_section:
import_section += line
indent = line[: -len(line.lstrip())]
elif not (stripped_line or contains_imports):
not_imports = True
elif (
not stripped_line
or stripped_line.startswith("#")
and (not indent or indent + line.lstrip() == line)
and not config.treat_all_comments_as_code
and stripped_line not in config.treat_comments_as_code
):
import_section += line
elif stripped_line.startswith(IMPORT_START_IDENTIFIERS):
contains_imports = True
new_indent = line[: -len(line.lstrip())]
import_statement = line
stripped_line = line.strip().split("#")[0]
while stripped_line.endswith("\\") or (
"(" in stripped_line and ")" not in stripped_line
):
if stripped_line.endswith("\\"):
while stripped_line and stripped_line.endswith("\\"):
line = input_stream.readline()
stripped_line = line.strip().split("#")[0]
import_statement += line
else:
while ")" not in stripped_line:
line = input_stream.readline()
stripped_line = line.strip().split("#")[0]
import_statement += line
cimport_statement: bool = False
if (
import_statement.lstrip().startswith(CIMPORT_IDENTIFIERS)
or " cimport " in import_statement
or " cimport*" in import_statement
or " cimport(" in import_statement
or ".cimport" in import_statement
):
cimport_statement = True
if cimport_statement != cimports or (
new_indent != indent and import_section
):
if import_section:
next_cimports = cimport_statement
next_import_section = import_statement
import_statement = ""
not_imports = True
line = ""
else:
cimports = cimport_statement
indent = new_indent
import_section += import_statement
else:
not_imports = True
if not_imports:
raw_import_section: str = import_section
if (
add_imports
and (stripped_line or end_of_file)
and not config.append_only
and not in_top_comment
and not in_quote
and not import_section
and not line.lstrip().startswith(COMMENT_INDICATORS)
):
import_section = line_separator.join(add_imports) + line_separator
if end_of_file and index != 0:
output_stream.write(line_separator)
contains_imports = True
add_imports = []
if next_import_section and not import_section: # pragma: no cover
raw_import_section = import_section = next_import_section
next_import_section = ""
if import_section:
if add_imports and not indent:
import_section = (
line_separator.join(add_imports)
+ line_separator
+ import_section
)
contains_imports = True
add_imports = []
if not indent:
import_section += line
raw_import_section += line
if not contains_imports:
output_stream.write(import_section)
else:
leading_whitespace = import_section[: -len(import_section.lstrip())]
trailing_whitespace = import_section[len(import_section.rstrip()) :]
if first_import_section and not import_section.lstrip(
line_separator
).startswith(COMMENT_INDICATORS):
import_section = import_section.lstrip(line_separator)
raw_import_section = raw_import_section.lstrip(line_separator)
first_import_section = False
if indent:
import_section = "".join(
line[len(indent) :]
for line in import_section.splitlines(keepends=True)
)
sorted_import_section = output.sorted_imports(
parse.file_contents(import_section, config=config),
_indented_config(config, indent),
extension,
import_type="cimport" if cimports else "import",
)
if not (import_section.strip() and not sorted_import_section):
if indent:
sorted_import_section = (
leading_whitespace
+ textwrap.indent(sorted_import_section, indent).strip()
+ trailing_whitespace
)
made_changes = made_changes or _has_changed(
before=raw_import_section,
after=sorted_import_section,
line_separator=line_separator,
ignore_whitespace=config.ignore_whitespace,
)
output_stream.write(sorted_import_section)
if not line and not indent and next_import_section:
output_stream.write(line_separator)
if indent:
output_stream.write(line)
if not next_import_section:
indent = ""
if next_import_section:
cimports = next_cimports
contains_imports = True
else:
contains_imports = False
import_section = next_import_section
next_import_section = ""
else:
output_stream.write(line)
not_imports = False
return made_changes
|
def process(
input_stream: TextIO,
output_stream: TextIO,
extension: str = "py",
config: Config = DEFAULT_CONFIG,
) -> bool:
"""Parses stream identifying sections of contiguous imports and sorting them
Code with unsorted imports is read from the provided `input_stream`, sorted and then
outputted to the specified `output_stream`.
- `input_stream`: Text stream with unsorted import sections.
- `output_stream`: Text stream to output sorted inputs into.
- `config`: Config settings to use when sorting imports. Defaults settings.
- *Default*: `isort.settings.DEFAULT_CONFIG`.
- `extension`: The file extension or file extension rules that should be used.
- *Default*: `"py"`.
- *Choices*: `["py", "pyi", "pyx"]`.
Returns `True` if there were changes that needed to be made (errors present) from what
was provided in the input_stream, otherwise `False`.
"""
line_separator: str = config.line_ending
add_imports: List[str] = [
format_natural(addition) for addition in config.add_imports
]
import_section: str = ""
next_import_section: str = ""
next_cimports: bool = False
in_quote: str = ""
first_comment_index_start: int = -1
first_comment_index_end: int = -1
contains_imports: bool = False
in_top_comment: bool = False
first_import_section: bool = True
section_comments = [f"# {heading}" for heading in config.import_headings.values()]
indent: str = ""
isort_off: bool = False
code_sorting: Union[bool, str] = False
code_sorting_section: str = ""
code_sorting_indent: str = ""
cimports: bool = False
made_changes: bool = False
stripped_line: str = ""
end_of_file: bool = False
if config.float_to_top:
new_input = ""
current = ""
isort_off = False
for line in chain(input_stream, (None,)):
if isort_off and line is not None:
if line == "# isort: on\n":
isort_off = False
new_input += line
elif line in ("# isort: split\n", "# isort: off\n", None) or str(
line
).endswith("# isort: split\n"):
if line == "# isort: off\n":
isort_off = True
if current:
parsed = parse.file_contents(current, config=config)
extra_space = ""
while current[-1] == "\n":
extra_space += "\n"
current = current[:-1]
extra_space = extra_space.replace("\n", "", 1)
sorted_output = output.sorted_imports(
parsed, config, extension, import_type="import"
)
made_changes = made_changes or _has_changed(
before=current,
after=sorted_output,
line_separator=parsed.line_separator,
ignore_whitespace=config.ignore_whitespace,
)
new_input += sorted_output
new_input += extra_space
current = ""
new_input += line or ""
else:
current += line or ""
input_stream = StringIO(new_input)
for index, line in enumerate(chain(input_stream, (None,))):
if line is None:
if index == 0 and not config.force_adds:
return False
not_imports = True
end_of_file = True
line = ""
if not line_separator:
line_separator = "\n"
if code_sorting and code_sorting_section:
output_stream.write(
textwrap.indent(
isort.literal.assignment(
code_sorting_section,
str(code_sorting),
extension,
config=_indented_config(config, indent),
),
code_sorting_indent,
)
)
else:
stripped_line = line.strip()
if stripped_line and not line_separator:
line_separator = (
line[len(line.rstrip()) :].replace(" ", "").replace("\t", "")
)
for file_skip_comment in FILE_SKIP_COMMENTS:
if file_skip_comment in line:
raise FileSkipComment("Passed in content")
if not in_quote and stripped_line == "# isort: off":
isort_off = True
if (
(index == 0 or (index in (1, 2) and not contains_imports))
and stripped_line.startswith("#")
and stripped_line not in section_comments
):
in_top_comment = True
elif in_top_comment:
if not line.startswith("#") or stripped_line in section_comments:
in_top_comment = False
first_comment_index_end = index - 1
if (
(not stripped_line.startswith("#") or in_quote)
and '"' in line
or "'" in line
):
char_index = 0
if first_comment_index_start == -1 and (
line.startswith('"') or line.startswith("'")
):
first_comment_index_start = index
while char_index < len(line):
if line[char_index] == "\\":
char_index += 1
elif in_quote:
if line[char_index : char_index + len(in_quote)] == in_quote:
in_quote = ""
if first_comment_index_end < first_comment_index_start:
first_comment_index_end = index
elif line[char_index] in ("'", '"'):
long_quote = line[char_index : char_index + 3]
if long_quote in ('"""', "'''"):
in_quote = long_quote
char_index += 2
else:
in_quote = line[char_index]
elif line[char_index] == "#":
break
char_index += 1
not_imports = bool(in_quote) or in_top_comment or isort_off
if not (in_quote or in_top_comment):
if isort_off:
if stripped_line == "# isort: on":
isort_off = False
elif stripped_line.endswith("# isort: split"):
not_imports = True
elif stripped_line in CODE_SORT_COMMENTS:
code_sorting = stripped_line.split("isort: ")[1].strip()
code_sorting_indent = line[: -len(line.lstrip())]
not_imports = True
elif code_sorting:
if not stripped_line:
output_stream.write(
textwrap.indent(
isort.literal.assignment(
code_sorting_section,
str(code_sorting),
extension,
config=_indented_config(config, indent),
),
code_sorting_indent,
)
)
not_imports = True
code_sorting = False
code_sorting_section = ""
code_sorting_indent = ""
else:
code_sorting_section += line
line = ""
elif stripped_line in config.section_comments and not import_section:
import_section += line
indent = line[: -len(line.lstrip())]
elif not (stripped_line or contains_imports):
not_imports = True
elif (
not stripped_line
or stripped_line.startswith("#")
and (not indent or indent + line.lstrip() == line)
and not config.treat_all_comments_as_code
and stripped_line not in config.treat_comments_as_code
):
import_section += line
elif stripped_line.startswith(IMPORT_START_IDENTIFIERS):
contains_imports = True
new_indent = line[: -len(line.lstrip())]
import_statement = line
stripped_line = line.strip().split("#")[0]
while stripped_line.endswith("\\") or (
"(" in stripped_line and ")" not in stripped_line
):
if stripped_line.endswith("\\"):
while stripped_line and stripped_line.endswith("\\"):
line = input_stream.readline()
stripped_line = line.strip().split("#")[0]
import_statement += line
else:
while ")" not in stripped_line:
line = input_stream.readline()
stripped_line = line.strip().split("#")[0]
import_statement += line
cimport_statement: bool = False
if (
import_statement.lstrip().startswith(CIMPORT_IDENTIFIERS)
or " cimport " in import_statement
or " cimport*" in import_statement
or " cimport(" in import_statement
or ".cimport" in import_statement
):
cimport_statement = True
if cimport_statement != cimports or (
new_indent != indent and import_section
):
if import_section:
next_cimports = cimport_statement
next_import_section = import_statement
import_statement = ""
not_imports = True
line = ""
else:
cimports = cimport_statement
indent = new_indent
import_section += import_statement
else:
not_imports = True
if not_imports:
raw_import_section: str = import_section
if (
add_imports
and (stripped_line or end_of_file)
and not config.append_only
and not in_top_comment
and not in_quote
and not import_section
and not line.lstrip().startswith(COMMENT_INDICATORS)
):
import_section = line_separator.join(add_imports) + line_separator
if end_of_file and index != 0:
output_stream.write(line_separator)
contains_imports = True
add_imports = []
if next_import_section and not import_section: # pragma: no cover
raw_import_section = import_section = next_import_section
next_import_section = ""
if import_section:
if add_imports and not indent:
import_section = (
line_separator.join(add_imports)
+ line_separator
+ import_section
)
contains_imports = True
add_imports = []
if not indent:
import_section += line
raw_import_section += line
if not contains_imports:
output_stream.write(import_section)
else:
leading_whitespace = import_section[: -len(import_section.lstrip())]
trailing_whitespace = import_section[len(import_section.rstrip()) :]
if first_import_section and not import_section.lstrip(
line_separator
).startswith(COMMENT_INDICATORS):
import_section = import_section.lstrip(line_separator)
raw_import_section = raw_import_section.lstrip(line_separator)
first_import_section = False
if indent:
import_section = "".join(
line[len(indent) :]
for line in import_section.splitlines(keepends=True)
)
sorted_import_section = output.sorted_imports(
parse.file_contents(import_section, config=config),
_indented_config(config, indent),
extension,
import_type="cimport" if cimports else "import",
)
if not (import_section.strip() and not sorted_import_section):
if indent:
sorted_import_section = (
leading_whitespace
+ textwrap.indent(sorted_import_section, indent).strip()
+ trailing_whitespace
)
made_changes = made_changes or _has_changed(
before=raw_import_section,
after=sorted_import_section,
line_separator=line_separator,
ignore_whitespace=config.ignore_whitespace,
)
output_stream.write(sorted_import_section)
if not line and not indent and next_import_section:
output_stream.write(line_separator)
if indent:
output_stream.write(line)
if not next_import_section:
indent = ""
if next_import_section:
cimports = next_cimports
contains_imports = True
else:
contains_imports = False
import_section = next_import_section
next_import_section = ""
else:
output_stream.write(line)
not_imports = False
return made_changes
|
https://github.com/PyCQA/isort/issues/1453
|
$ echo "\n" > example.py
$ .venv/bin/isort --float-to-top example.py
Traceback (most recent call last):
File ".venv/bin/isort", line 10, in <module>
sys.exit(main())
File ".venv/lib/python3.8/site-packages/isort/main.py", line 876, in main
for sort_attempt in attempt_iterator:
File ".venv/lib/python3.8/site-packages/isort/main.py", line 865, in <genexpr>
sort_imports( # type: ignore
File ".venv/lib/python3.8/site-packages/isort/main.py", line 93, in sort_imports
incorrectly_sorted = not api.sort_file(
File ".venv/lib/python3.8/site-packages/isort/api.py", line 321, in sort_file
changed = sort_stream(
File ".venv/lib/python3.8/site-packages/isort/api.py", line 158, in sort_stream
changed = core.process(
File ".venv/lib/python3.8/site-packages/isort/core.py", line 89, in process
while current[-1] == "\n":
IndexError: string index out of range
|
IndexError
|
def sort_imports(
file_name: str,
config: Config,
check: bool = False,
ask_to_apply: bool = False,
write_to_stdout: bool = False,
**kwargs: Any,
) -> Optional[SortAttempt]:
try:
incorrectly_sorted: bool = False
skipped: bool = False
if check:
try:
incorrectly_sorted = not api.check_file(
file_name, config=config, **kwargs
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped)
else:
try:
incorrectly_sorted = not api.sort_file(
file_name,
config=config,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
**kwargs,
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped)
except (OSError, ValueError) as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
except Exception:
printer = create_terminal_printer(color=config.color_output)
printer.error(
f"Unrecoverable exception thrown when parsing {file_name}! "
"This should NEVER happen.\n"
"If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new"
)
raise
|
def sort_imports(
file_name: str,
config: Config,
check: bool = False,
ask_to_apply: bool = False,
write_to_stdout: bool = False,
**kwargs: Any,
) -> Optional[SortAttempt]:
try:
incorrectly_sorted: bool = False
skipped: bool = False
if check:
try:
incorrectly_sorted = not api.check_file(
file_name, config=config, **kwargs
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped)
else:
try:
incorrectly_sorted = not api.sort_file(
file_name,
config=config,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
**kwargs,
)
except FileSkipped:
skipped = True
return SortAttempt(incorrectly_sorted, skipped)
except (OSError, ValueError) as error:
warn(f"Unable to parse file {file_name} due to {error}")
return None
|
https://github.com/PyCQA/isort/issues/1453
|
$ echo "\n" > example.py
$ .venv/bin/isort --float-to-top example.py
Traceback (most recent call last):
File ".venv/bin/isort", line 10, in <module>
sys.exit(main())
File ".venv/lib/python3.8/site-packages/isort/main.py", line 876, in main
for sort_attempt in attempt_iterator:
File ".venv/lib/python3.8/site-packages/isort/main.py", line 865, in <genexpr>
sort_imports( # type: ignore
File ".venv/lib/python3.8/site-packages/isort/main.py", line 93, in sort_imports
incorrectly_sorted = not api.sort_file(
File ".venv/lib/python3.8/site-packages/isort/api.py", line 321, in sort_file
changed = sort_stream(
File ".venv/lib/python3.8/site-packages/isort/api.py", line 158, in sort_stream
changed = core.process(
File ".venv/lib/python3.8/site-packages/isort/core.py", line 89, in process
while current[-1] == "\n":
IndexError: string index out of range
|
IndexError
|
def main(
argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None
) -> None:
arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
if "settings_path" in arguments:
if os.path.isfile(arguments["settings_path"]):
arguments["settings_file"] = os.path.abspath(arguments["settings_path"])
arguments["settings_path"] = os.path.dirname(arguments["settings_file"])
else:
arguments["settings_path"] = os.path.abspath(arguments["settings_path"])
if "virtual_env" in arguments:
venv = arguments["virtual_env"]
arguments["virtual_env"] = os.path.abspath(venv)
if not os.path.isdir(arguments["virtual_env"]):
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")
file_names = arguments.pop("files", [])
if not file_names and not show_config:
print(QUICK_GUIDE)
if arguments:
sys.exit("Error: arguments passed in without any paths or content.")
else:
return
if "settings_path" not in arguments:
arguments["settings_path"] = (
os.path.abspath(file_names[0] if file_names else ".") or os.getcwd()
)
if not os.path.isdir(arguments["settings_path"]):
arguments["settings_path"] = os.path.dirname(arguments["settings_path"])
config_dict = arguments.copy()
ask_to_apply = config_dict.pop("ask_to_apply", False)
jobs = config_dict.pop("jobs", ())
check = config_dict.pop("check", False)
show_diff = config_dict.pop("show_diff", False)
write_to_stdout = config_dict.pop("write_to_stdout", False)
deprecated_flags = config_dict.pop("deprecated_flags", False)
remapped_deprecated_args = config_dict.pop("remapped_deprecated_args", False)
wrong_sorted_files = False
if "src_paths" in config_dict:
config_dict["src_paths"] = {
Path(src_path).resolve() for src_path in config_dict.get("src_paths", ())
}
config = Config(**config_dict)
if show_config:
print(
json.dumps(
config.__dict__, indent=4, separators=(",", ": "), default=_preconvert
)
)
return
elif file_names == ["-"]:
api.sort_stream(
input_stream=sys.stdin if stdin is None else stdin,
output_stream=sys.stdout,
config=config,
)
else:
skipped: List[str] = []
if config.filter_files:
filtered_files = []
for file_name in file_names:
if config.is_skipped(Path(file_name)):
skipped.append(file_name)
else:
filtered_files.append(file_name)
file_names = filtered_files
file_names = iter_source_code(file_names, config, skipped)
num_skipped = 0
if config.verbose:
print(ASCII_ART)
if jobs:
import multiprocessing
executor = multiprocessing.Pool(jobs)
attempt_iterator = executor.imap(
functools.partial(
sort_imports,
config=config,
check=check,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
),
file_names,
)
else:
# https://github.com/python/typeshed/pull/2814
attempt_iterator = (
sort_imports( # type: ignore
file_name,
config=config,
check=check,
ask_to_apply=ask_to_apply,
show_diff=show_diff,
write_to_stdout=write_to_stdout,
)
for file_name in file_names
)
for sort_attempt in attempt_iterator:
if not sort_attempt:
continue # pragma: no cover - shouldn't happen, satisfies type constraint
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get("check", False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code
num_skipped += len(skipped)
if num_skipped and not arguments.get("quiet", False):
if config.verbose:
for was_skipped in skipped:
warn(
f"{was_skipped} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting"
)
print(f"Skipped {num_skipped} files")
if not config.quiet and (remapped_deprecated_args or deprecated_flags):
if remapped_deprecated_args:
warn(
"W0502: The following deprecated single dash CLI flags were used and translated: "
f"{', '.join(remapped_deprecated_args)}!"
)
if deprecated_flags:
warn(
"W0501: The following deprecated CLI flags were used and ignored: "
f"{', '.join(deprecated_flags)}!"
)
warn(
"W0500: Please see the 5.0.0 Upgrade guide: "
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"
)
if wrong_sorted_files:
sys.exit(1)
|
def main(
argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None
) -> None:
arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
if "settings_path" in arguments:
if os.path.isfile(arguments["settings_path"]):
arguments["settings_file"] = os.path.abspath(arguments["settings_path"])
arguments["settings_path"] = os.path.dirname(arguments["settings_file"])
else:
arguments["settings_path"] = os.path.abspath(arguments["settings_path"])
if "virtual_env" in arguments:
venv = arguments["virtual_env"]
arguments["virtual_env"] = os.path.abspath(venv)
if not os.path.isdir(arguments["virtual_env"]):
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")
file_names = arguments.pop("files", [])
if not file_names and not show_config:
print(QUICK_GUIDE)
if arguments:
sys.exit("Error: arguments passed in without any paths or content.")
else:
return
if "settings_path" not in arguments:
arguments["settings_path"] = (
os.path.abspath(file_names[0] if file_names else ".") or os.getcwd()
)
if not os.path.isdir(arguments["settings_path"]):
arguments["settings_path"] = os.path.dirname(arguments["settings_path"])
config_dict = arguments.copy()
ask_to_apply = config_dict.pop("ask_to_apply", False)
jobs = config_dict.pop("jobs", ())
check = config_dict.pop("check", False)
show_diff = config_dict.pop("show_diff", False)
write_to_stdout = config_dict.pop("write_to_stdout", False)
deprecated_flags = config_dict.pop("deprecated_flags", False)
remapped_deprecated_args = config_dict.pop("remapped_deprecated_args", False)
wrong_sorted_files = False
if "src_paths" in config_dict:
config_dict["src_paths"] = {
Path(src_path).resolve() for src_path in config_dict.get("src_paths", ())
}
config = Config(**config_dict)
if show_config:
print(
json.dumps(
config.__dict__, indent=4, separators=(",", ": "), default=_preconvert
)
)
return
elif file_names == ["-"]:
arguments.setdefault("settings_path", os.getcwd())
api.sort_stream(
input_stream=sys.stdin if stdin is None else stdin,
output_stream=sys.stdout,
**arguments,
)
else:
skipped: List[str] = []
if config.filter_files:
filtered_files = []
for file_name in file_names:
if config.is_skipped(Path(file_name)):
skipped.append(file_name)
else:
filtered_files.append(file_name)
file_names = filtered_files
file_names = iter_source_code(file_names, config, skipped)
num_skipped = 0
if config.verbose:
print(ASCII_ART)
if jobs:
import multiprocessing
executor = multiprocessing.Pool(jobs)
attempt_iterator = executor.imap(
functools.partial(
sort_imports,
config=config,
check=check,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
),
file_names,
)
else:
# https://github.com/python/typeshed/pull/2814
attempt_iterator = (
sort_imports( # type: ignore
file_name,
config=config,
check=check,
ask_to_apply=ask_to_apply,
show_diff=show_diff,
write_to_stdout=write_to_stdout,
)
for file_name in file_names
)
for sort_attempt in attempt_iterator:
if not sort_attempt:
continue # pragma: no cover - shouldn't happen, satisfies type constraint
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get("check", False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code
num_skipped += len(skipped)
if num_skipped and not arguments.get("quiet", False):
if config.verbose:
for was_skipped in skipped:
warn(
f"{was_skipped} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting"
)
print(f"Skipped {num_skipped} files")
if not config.quiet and (remapped_deprecated_args or deprecated_flags):
if remapped_deprecated_args:
warn(
"W0502: The following deprecated single dash CLI flags were used and translated: "
f"{', '.join(remapped_deprecated_args)}!"
)
if deprecated_flags:
warn(
"W0501: The following deprecated CLI flags were used and ignored: "
f"{', '.join(deprecated_flags)}!"
)
warn(
"W0500: Please see the 5.0.0 Upgrade guide: "
"https://pycqa.github.io/isort/docs/upgrade_guides/5.0.0/"
)
if wrong_sorted_files:
sys.exit(1)
|
https://github.com/PyCQA/isort/issues/1447
|
Traceback (most recent call last):
File "C:\Users\karraj\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 193, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\karraj\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "C:\Users\karraj\Desktop\imports\.isort5\Scripts\isort.exe\__main__.py", line 9, in <module>
File "c:\users\karraj\desktop\imports\.isort5\lib\site-packages\isort\main.py", line 828, in main
api.sort_stream(
File "c:\users\karraj\desktop\imports\.isort5\lib\site-packages\isort\api.py", line 118, in sort_stream
changed = sort_stream(
File "c:\users\karraj\desktop\imports\.isort5\lib\site-packages\isort\api.py", line 137, in sort_stream
config = _config(path=file_path, config=config, **config_kwargs)
File "c:\users\karraj\desktop\imports\.isort5\lib\site-packages\isort\api.py", line 381, in _config
config = Config(**config_kwargs)
File "c:\users\karraj\desktop\imports\.isort5\lib\site-packages\isort\settings.py", line 423, in __init__
super().__init__(sources=tuple(sources), **combined_config) # type: ignore
TypeError: __init__() got an unexpected keyword argument 'remapped_deprecated_args'
|
TypeError
|
def parse_args(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]:
argv = sys.argv[1:] if argv is None else list(argv)
remapped_deprecated_args = []
for index, arg in enumerate(argv):
if arg in DEPRECATED_SINGLE_DASH_ARGS:
remapped_deprecated_args.append(arg)
argv[index] = f"-{arg}"
parser = _build_arg_parser()
arguments = {
key: value for key, value in vars(parser.parse_args(argv)).items() if value
}
if remapped_deprecated_args:
arguments["remapped_deprecated_args"] = remapped_deprecated_args
if "dont_order_by_type" in arguments:
arguments["order_by_type"] = False
del arguments["dont_order_by_type"]
multi_line_output = arguments.get("multi_line_output", None)
if multi_line_output:
if multi_line_output.isdigit():
arguments["multi_line_output"] = WrapModes(int(multi_line_output))
else:
arguments["multi_line_output"] = WrapModes[multi_line_output]
return arguments
|
def parse_args(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]:
argv = sys.argv[1:] if argv is None else list(argv)
remapped_deprecated_args = []
for index, arg in enumerate(argv):
if arg in DEPRECATED_SINGLE_DASH_ARGS:
remapped_deprecated_args.append(arg)
argv[index] = f"-{arg}"
parser = _build_arg_parser()
arguments = {
key: value for key, value in vars(parser.parse_args(argv)).items() if value
}
if remapped_deprecated_args:
arguments["remapped_deprecated_args"] = remapped_deprecated_args
if "dont_order_by_type" in arguments:
arguments["order_by_type"] = False
multi_line_output = arguments.get("multi_line_output", None)
if multi_line_output:
if multi_line_output.isdigit():
arguments["multi_line_output"] = WrapModes(int(multi_line_output))
else:
arguments["multi_line_output"] = WrapModes[multi_line_output]
return arguments
|
https://github.com/PyCQA/isort/issues/1375
|
✗ isort myfile.py --dont-order-by-type
Traceback (most recent call last):
File "/usr/local/bin/isort", line 8, in <module>
sys.exit(main())
File "/usr/local/lib/python3.7/site-packages/isort/main.py", line 812, in main
config = Config(**config_dict)
File "/usr/local/lib/python3.7/site-packages/isort/settings.py", line 422, in __init__
super().__init__(sources=tuple(sources), **combined_config) # type: ignore
TypeError: __init__() got an unexpected keyword argument 'dont_order_by_type'
|
TypeError
|
def sort_stream(
input_stream: TextIO,
output_stream: TextIO,
extension: Optional[str] = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
disregard_skip: bool = False,
show_diff: bool = False,
**config_kwargs,
):
"""Sorts any imports within the provided code stream, outputs to the provided output stream.
Directly returns nothing.
- **input_stream**: The stream of code with imports that need to be sorted.
- **output_stream**: The stream where sorted imports should be written to.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- ****config_kwargs**: Any config modifications.
"""
if show_diff:
_output_stream = StringIO()
_input_stream = StringIO(input_stream.read())
changed = sort_stream(
input_stream=_input_stream,
output_stream=_output_stream,
extension=extension,
config=config,
file_path=file_path,
disregard_skip=disregard_skip,
**config_kwargs,
)
_output_stream.seek(0)
_input_stream.seek(0)
show_unified_diff(
file_input=_input_stream.read(),
file_output=_output_stream.read(),
file_path=file_path,
output=output_stream,
)
return changed
config = _config(path=file_path, config=config, **config_kwargs)
content_source = str(file_path or "Passed in content")
if not disregard_skip:
if file_path and config.is_skipped(file_path):
raise FileSkipSetting(content_source)
_internal_output = output_stream
if config.atomic:
try:
file_content = input_stream.read()
compile(file_content, content_source, "exec", 0, 1)
input_stream = StringIO(file_content)
except SyntaxError:
raise ExistingSyntaxErrors(content_source)
if not output_stream.readable():
_internal_output = StringIO()
try:
changed = _sort_imports(
input_stream,
_internal_output,
extension=extension or (file_path and file_path.suffix.lstrip(".")) or "py",
config=config,
)
except FileSkipComment:
raise FileSkipComment(content_source)
if config.atomic:
_internal_output.seek(0)
try:
compile(_internal_output.read(), content_source, "exec", 0, 1)
_internal_output.seek(0)
if _internal_output != output_stream:
output_stream.write(_internal_output.read())
except SyntaxError: # pragma: no cover
raise IntroducedSyntaxErrors(content_source)
return changed
|
def sort_stream(
input_stream: TextIO,
output_stream: TextIO,
extension: Optional[str] = None,
config: Config = DEFAULT_CONFIG,
file_path: Optional[Path] = None,
disregard_skip: bool = False,
**config_kwargs,
):
"""Sorts any imports within the provided code stream, outputs to the provided output stream.
Directly returns nothing.
- **input_stream**: The stream of code with imports that need to be sorted.
- **output_stream**: The stream where sorted imports should be written to.
- **extension**: The file extension that contains imports. Defaults to filename extension or py.
- **config**: The config object to use when sorting imports.
- **file_path**: The disk location where the code string was pulled from.
- **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.
- ****config_kwargs**: Any config modifications.
"""
config = _config(path=file_path, config=config, **config_kwargs)
content_source = str(file_path or "Passed in content")
if not disregard_skip:
if file_path and config.is_skipped(file_path):
raise FileSkipSetting(content_source)
_internal_output = output_stream
if config.atomic:
try:
file_content = input_stream.read()
compile(file_content, content_source, "exec", 0, 1)
input_stream = StringIO(file_content)
except SyntaxError:
raise ExistingSyntaxErrors(content_source)
if not output_stream.readable():
_internal_output = StringIO()
try:
changed = _sort_imports(
input_stream,
_internal_output,
extension=extension or (file_path and file_path.suffix.lstrip(".")) or "py",
config=config,
)
except FileSkipComment:
raise FileSkipComment(content_source)
if config.atomic:
_internal_output.seek(0)
try:
compile(_internal_output.read(), content_source, "exec", 0, 1)
_internal_output.seek(0)
if _internal_output != output_stream:
output_stream.write(_internal_output.read())
except SyntaxError: # pragma: no cover
raise IntroducedSyntaxErrors(content_source)
return changed
|
https://github.com/PyCQA/isort/issues/1189
|
$ cat demo.py
import os, sys, collections
$ isort --diff - < demo.py
Traceback (most recent call last):
File "/home/peter/.virtualenvs/isort/bin/isort", line 11, in <module>
load_entry_point('isort', 'console_scripts', 'isort')()
File "/home/play/isort/isort/main.py", line 600, in main
**arguments,
File "/home/play/isort/isort/api.py", line 104, in sorted_imports
config = _config(path=file_path, config=config, **config_kwargs)
File "/home/play/isort/isort/api.py", line 47, in _config
config = Config(**config_kwargs)
File "/home/play/isort/isort/settings.py", line 300, in __init__
super().__init__(sources=tuple(sources), **combined_config) # type: ignore
TypeError: __init__() got an unexpected keyword argument 'show_diff'
|
TypeError
|
def show_unified_diff(
*, file_input: str, file_output: str, file_path: Optional[Path], output=sys.stdout
):
file_name = "" if file_path is None else str(file_path)
file_mtime = str(
datetime.now()
if file_path is None
else datetime.fromtimestamp(file_path.stat().st_mtime)
)
unified_diff_lines = unified_diff(
file_input.splitlines(keepends=True),
file_output.splitlines(keepends=True),
fromfile=file_name + ":before",
tofile=file_name + ":after",
fromfiledate=file_mtime,
tofiledate=str(datetime.now()),
)
for line in unified_diff_lines:
output.write(line)
|
def show_unified_diff(*, file_input: str, file_output: str, file_path: Optional[Path]):
file_name = "" if file_path is None else str(file_path)
file_mtime = str(
datetime.now()
if file_path is None
else datetime.fromtimestamp(file_path.stat().st_mtime)
)
unified_diff_lines = unified_diff(
file_input.splitlines(keepends=True),
file_output.splitlines(keepends=True),
fromfile=file_name + ":before",
tofile=file_name + ":after",
fromfiledate=file_mtime,
tofiledate=str(datetime.now()),
)
for line in unified_diff_lines:
sys.stdout.write(line)
|
https://github.com/PyCQA/isort/issues/1189
|
$ cat demo.py
import os, sys, collections
$ isort --diff - < demo.py
Traceback (most recent call last):
File "/home/peter/.virtualenvs/isort/bin/isort", line 11, in <module>
load_entry_point('isort', 'console_scripts', 'isort')()
File "/home/play/isort/isort/main.py", line 600, in main
**arguments,
File "/home/play/isort/isort/api.py", line 104, in sorted_imports
config = _config(path=file_path, config=config, **config_kwargs)
File "/home/play/isort/isort/api.py", line 47, in _config
config = Config(**config_kwargs)
File "/home/play/isort/isort/settings.py", line 300, in __init__
super().__init__(sources=tuple(sources), **combined_config) # type: ignore
TypeError: __init__() got an unexpected keyword argument 'show_diff'
|
TypeError
|
def _build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Sort Python import definitions alphabetically "
"within logical sections. Run with no arguments to run "
"interactively. Run with `-` as the first argument to read from "
"stdin. Otherwise provide a list of files to sort."
)
inline_args_group = parser.add_mutually_exclusive_group()
parser.add_argument(
"--src",
"--src-path",
dest="src_paths",
action="append",
help="Add an explicitly defined source path "
"(modules within src paths have their imports automatically catorgorized as first_party).",
)
parser.add_argument(
"-a",
"--add-import",
dest="add_imports",
action="append",
help="Adds the specified import line to all files, "
"automatically determining correct placement.",
)
parser.add_argument(
"--ac",
"--atomic",
dest="atomic",
action="store_true",
help="Ensures the output doesn't save if the resulting file contains syntax errors.",
)
parser.add_argument(
"--af",
"--force-adds",
dest="force_adds",
action="store_true",
help="Forces import adds even if the original file is empty.",
)
parser.add_argument(
"-b",
"--builtin",
dest="known_standard_library",
action="append",
help="Force isort to recognize a module as part of the python standard library.",
)
parser.add_argument(
"-c",
"--check-only",
"--check",
action="store_true",
dest="check",
help="Checks the file for unsorted / unformatted imports and prints them to the "
"command line without modifying the file.",
)
parser.add_argument(
"--ca",
"--combine-as",
dest="combine_as_imports",
action="store_true",
help="Combines as imports on the same line.",
)
parser.add_argument(
"--cs",
"--combine-star",
dest="combine_star",
action="store_true",
help="Ensures that if a star import is present, "
"nothing else is imported from that namespace.",
)
parser.add_argument(
"-d",
"--stdout",
help="Force resulting output to stdout, instead of in-place.",
dest="write_to_stdout",
action="store_true",
)
parser.add_argument(
"--df",
"--diff",
dest="show_diff",
action="store_true",
help="Prints a diff of all the changes isort would make to a file, instead of "
"changing it in place",
)
parser.add_argument(
"--ds",
"--no-sections",
help="Put all imports into the same section bucket",
dest="no_sections",
action="store_true",
)
parser.add_argument(
"-e",
"--balanced",
dest="balanced_wrapping",
action="store_true",
help="Balances wrapping to produce the most consistent line length possible",
)
parser.add_argument(
"-f",
"--future",
dest="known_future_library",
action="append",
help="Force isort to recognize a module as part of the future compatibility libraries.",
)
parser.add_argument(
"--fas",
"--force-alphabetical-sort",
action="store_true",
dest="force_alphabetical_sort",
help="Force all imports to be sorted as a single section",
)
parser.add_argument(
"--fass",
"--force-alphabetical-sort-within-sections",
action="store_true",
dest="force_alphabetical_sort",
help="Force all imports to be sorted alphabetically within a section",
)
parser.add_argument(
"--ff",
"--from-first",
dest="from_first",
help="Switches the typical ordering preference, "
"showing from imports first then straight ones.",
)
parser.add_argument(
"--fgw",
"--force-grid-wrap",
nargs="?",
const=2,
type=int,
dest="force_grid_wrap",
help="Force number of from imports (defaults to 2) to be grid wrapped regardless of line "
"length",
)
parser.add_argument(
"--fss",
"--force-sort-within-sections",
action="store_true",
dest="force_sort_within_sections",
help="Force imports to be sorted by module, independent of import_type",
)
parser.add_argument(
"-i",
"--indent",
help='String to place for indents defaults to " " (4 spaces).',
dest="indent",
type=str,
)
parser.add_argument(
"-j",
"--jobs",
help="Number of files to process in parallel.",
dest="jobs",
type=int,
)
parser.add_argument(
"-k",
"--keep-direct-and-as",
dest="keep_direct_and_as_imports",
action="store_true",
help="Turns off default behavior that removes direct imports when as imports exist.",
)
parser.add_argument(
"--lai", "--lines-after-imports", dest="lines_after_imports", type=int
)
parser.add_argument(
"--lbt", "--lines-between-types", dest="lines_between_types", type=int
)
parser.add_argument(
"--le",
"--line-ending",
dest="line_ending",
help="Forces line endings to the specified value. "
"If not set, values will be guessed per-file.",
)
parser.add_argument(
"--ls",
"--length-sort",
help="Sort imports by their string length.",
dest="length_sort",
action="store_true",
)
parser.add_argument(
"-m",
"--multi-line",
dest="multi_line_output",
choices=list(WrapModes.__members__.keys())
+ [str(mode.value) for mode in WrapModes.__members__.values()],
type=str,
help="Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, "
"5-vert-grid-grouped, 6-vert-grid-grouped-no-comma).",
)
parser.add_argument(
"-n",
"--ensure-newline-before-comments",
dest="ensure_newline_before_comments",
action="store_true",
help="Inserts a blank line before a comment following an import.",
)
inline_args_group.add_argument(
"--nis",
"--no-inline-sort",
dest="no_inline_sort",
action="store_true",
help="Leaves `from` imports with multiple imports 'as-is' "
"(e.g. `from foo import a, c ,b`).",
)
parser.add_argument(
"--nlb",
"--no-lines-before",
help="Sections which should not be split with previous by empty lines",
dest="no_lines_before",
action="append",
)
parser.add_argument(
"-o",
"--thirdparty",
dest="known_third_party",
action="append",
help="Force isort to recognize a module as being part of a third party library.",
)
parser.add_argument(
"--ot",
"--order-by-type",
dest="order_by_type",
action="store_true",
help="Order imports by type in addition to alphabetically",
)
parser.add_argument(
"--dt",
"--dont-order-by-type",
dest="dont_order_by_type",
action="store_true",
help="Don't order imports by type in addition to alphabetically",
)
parser.add_argument(
"-p",
"--project",
dest="known_first_party",
action="append",
help="Force isort to recognize a module as being part of the current python project.",
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
dest="quiet",
help="Shows extra quiet output, only errors are outputted.",
)
parser.add_argument(
"--rm",
"--remove-import",
dest="remove_imports",
action="append",
help="Removes the specified import from all files.",
)
parser.add_argument(
"--rr",
"--reverse-relative",
dest="reverse_relative",
action="store_true",
help="Reverse order of relative imports.",
)
parser.add_argument(
"-s",
"--skip",
help="Files that sort imports should skip over. If you want to skip multiple "
"files you should specify twice: --skip file1 --skip file2.",
dest="skip",
action="append",
)
parser.add_argument(
"--sd",
"--section-default",
dest="default_section",
help="Sets the default section for imports (by default FIRSTPARTY) options: "
+ str(sections.DEFAULT),
)
parser.add_argument(
"--sg",
"--skip-glob",
help="Files that sort imports should skip over.",
dest="skip_glob",
action="append",
)
inline_args_group.add_argument(
"--sl",
"--force-single-line-imports",
dest="force_single_line",
action="store_true",
help="Forces all from imports to appear on their own line",
)
parser.add_argument(
"--nsl",
"--single-line-exclusions",
help="One or more modules to exclude from the single line rule.",
dest="single_line_exclusions",
action="append",
)
parser.add_argument(
"--sp",
"--settings-path",
"--settings-file",
"--settings",
dest="settings_path",
help="Explicitly set the settings path or file instead of auto determining "
"based on file location.",
)
parser.add_argument(
"-t",
"--top",
help="Force specific imports to the top of their appropriate section.",
dest="force_to_top",
action="append",
)
parser.add_argument(
"--tc",
"--trailing-comma",
dest="include_trailing_comma",
action="store_true",
help="Includes a trailing comma on multi line imports that include parentheses.",
)
parser.add_argument(
"--up",
"--use-parentheses",
dest="use_parentheses",
action="store_true",
help="Use parenthesis for line continuation on length limit instead of slashes.",
)
parser.add_argument(
"-V",
"--version",
action="store_true",
dest="show_version",
help="Displays the currently installed version of isort.",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
dest="verbose",
help="Shows verbose output, such as when files are skipped or when a check is successful.",
)
parser.add_argument(
"--virtual-env",
dest="virtual_env",
help="Virtual environment to use for determining whether a package is third-party",
)
parser.add_argument(
"--conda-env",
dest="conda_env",
help="Conda environment to use for determining whether a package is third-party",
)
parser.add_argument(
"--vn",
"--version-number",
action="version",
version=__version__,
help="Returns just the current version number without the logo",
)
parser.add_argument(
"-l",
"-w",
"--line-length",
"--line-width",
help="The max length of an import line (used for wrapping long imports).",
dest="line_length",
type=int,
)
parser.add_argument(
"--wl",
"--wrap-length",
dest="wrap_length",
type=int,
help="Specifies how long lines that are wrapped should be, if not set line_length is used."
"\nNOTE: wrap_length must be LOWER than or equal to line_length.",
)
parser.add_argument(
"--ws",
"--ignore-whitespace",
action="store_true",
dest="ignore_whitespace",
help="Tells isort to ignore whitespace differences when --check-only is being used.",
)
parser.add_argument(
"--case-sensitive",
dest="case_sensitive",
action="store_true",
help="Tells isort to include casing when sorting module names",
)
parser.add_argument(
"--filter-files",
dest="filter_files",
action="store_true",
help="Tells isort to filter files even when they are explicitly passed in as "
"part of the command",
)
parser.add_argument(
"files",
nargs="*",
help="One or more Python source files that need their imports sorted.",
)
parser.add_argument(
"--py",
"--python-version",
action="store",
dest="py_version",
choices=tuple(VALID_PY_TARGETS) + ("auto",),
help="Tells isort to set the known standard library based on the the specified Python "
"version. Default is to assume any Python 3 version could be the target, and use a union "
"off all stdlib modules across versions. If auto is specified, the version of the "
"interpreter used to run isort "
f"(currently: {sys.version_info.major}{sys.version_info.minor}) will be used.",
)
parser.add_argument(
"--profile",
dest="profile",
choices=list(profiles.keys()),
type=str,
help="Base profile type to use for configuration.",
)
parser.add_argument(
"--interactive",
dest="ask_to_apply",
action="store_true",
help="Tells isort to apply changes interactively.",
)
parser.add_argument(
"--old-finders",
"--magic",
dest="old_finders",
action="store_true",
help="Use the old deprecated finder logic that relies on environment introspection magic.",
)
parser.add_argument(
"--show-config",
dest="show_config",
action="store_true",
help="See isort's determined config, as well as sources of config options.",
)
return parser
|
def _build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Sort Python import definitions alphabetically "
"within logical sections. Run with no arguments to run "
"interactively. Run with `-` as the first argument to read from "
"stdin. Otherwise provide a list of files to sort."
)
inline_args_group = parser.add_mutually_exclusive_group()
parser.add_argument(
"--src",
"--src-path",
dest="source_paths",
action="append",
help="Add an explicitly defined source path "
"(modules within src paths have their imports automatically catorgorized as first_party).",
)
parser.add_argument(
"-a",
"--add-import",
dest="add_imports",
action="append",
help="Adds the specified import line to all files, "
"automatically determining correct placement.",
)
parser.add_argument(
"--ac",
"--atomic",
dest="atomic",
action="store_true",
help="Ensures the output doesn't save if the resulting file contains syntax errors.",
)
parser.add_argument(
"--af",
"--force-adds",
dest="force_adds",
action="store_true",
help="Forces import adds even if the original file is empty.",
)
parser.add_argument(
"-b",
"--builtin",
dest="known_standard_library",
action="append",
help="Force isort to recognize a module as part of the python standard library.",
)
parser.add_argument(
"-c",
"--check-only",
"--check",
action="store_true",
dest="check",
help="Checks the file for unsorted / unformatted imports and prints them to the "
"command line without modifying the file.",
)
parser.add_argument(
"--ca",
"--combine-as",
dest="combine_as_imports",
action="store_true",
help="Combines as imports on the same line.",
)
parser.add_argument(
"--cs",
"--combine-star",
dest="combine_star",
action="store_true",
help="Ensures that if a star import is present, "
"nothing else is imported from that namespace.",
)
parser.add_argument(
"-d",
"--stdout",
help="Force resulting output to stdout, instead of in-place.",
dest="write_to_stdout",
action="store_true",
)
parser.add_argument(
"--df",
"--diff",
dest="show_diff",
action="store_true",
help="Prints a diff of all the changes isort would make to a file, instead of "
"changing it in place",
)
parser.add_argument(
"--ds",
"--no-sections",
help="Put all imports into the same section bucket",
dest="no_sections",
action="store_true",
)
parser.add_argument(
"-e",
"--balanced",
dest="balanced_wrapping",
action="store_true",
help="Balances wrapping to produce the most consistent line length possible",
)
parser.add_argument(
"-f",
"--future",
dest="known_future_library",
action="append",
help="Force isort to recognize a module as part of the future compatibility libraries.",
)
parser.add_argument(
"--fas",
"--force-alphabetical-sort",
action="store_true",
dest="force_alphabetical_sort",
help="Force all imports to be sorted as a single section",
)
parser.add_argument(
"--fass",
"--force-alphabetical-sort-within-sections",
action="store_true",
dest="force_alphabetical_sort",
help="Force all imports to be sorted alphabetically within a section",
)
parser.add_argument(
"--ff",
"--from-first",
dest="from_first",
help="Switches the typical ordering preference, "
"showing from imports first then straight ones.",
)
parser.add_argument(
"--fgw",
"--force-grid-wrap",
nargs="?",
const=2,
type=int,
dest="force_grid_wrap",
help="Force number of from imports (defaults to 2) to be grid wrapped regardless of line "
"length",
)
parser.add_argument(
"--fss",
"--force-sort-within-sections",
action="store_true",
dest="force_sort_within_sections",
help="Force imports to be sorted by module, independent of import_type",
)
parser.add_argument(
"-i",
"--indent",
help='String to place for indents defaults to " " (4 spaces).',
dest="indent",
type=str,
)
parser.add_argument(
"-j",
"--jobs",
help="Number of files to process in parallel.",
dest="jobs",
type=int,
)
parser.add_argument(
"-k",
"--keep-direct-and-as",
dest="keep_direct_and_as_imports",
action="store_true",
help="Turns off default behavior that removes direct imports when as imports exist.",
)
parser.add_argument(
"--lai", "--lines-after-imports", dest="lines_after_imports", type=int
)
parser.add_argument(
"--lbt", "--lines-between-types", dest="lines_between_types", type=int
)
parser.add_argument(
"--le",
"--line-ending",
dest="line_ending",
help="Forces line endings to the specified value. "
"If not set, values will be guessed per-file.",
)
parser.add_argument(
"--ls",
"--length-sort",
help="Sort imports by their string length.",
dest="length_sort",
action="store_true",
)
parser.add_argument(
"-m",
"--multi-line",
dest="multi_line_output",
choices=list(WrapModes.__members__.keys())
+ [str(mode.value) for mode in WrapModes.__members__.values()],
type=str,
help="Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, "
"5-vert-grid-grouped, 6-vert-grid-grouped-no-comma).",
)
parser.add_argument(
"-n",
"--ensure-newline-before-comments",
dest="ensure_newline_before_comments",
action="store_true",
help="Inserts a blank line before a comment following an import.",
)
inline_args_group.add_argument(
"--nis",
"--no-inline-sort",
dest="no_inline_sort",
action="store_true",
help="Leaves `from` imports with multiple imports 'as-is' "
"(e.g. `from foo import a, c ,b`).",
)
parser.add_argument(
"--nlb",
"--no-lines-before",
help="Sections which should not be split with previous by empty lines",
dest="no_lines_before",
action="append",
)
parser.add_argument(
"-o",
"--thirdparty",
dest="known_third_party",
action="append",
help="Force isort to recognize a module as being part of a third party library.",
)
parser.add_argument(
"--ot",
"--order-by-type",
dest="order_by_type",
action="store_true",
help="Order imports by type in addition to alphabetically",
)
parser.add_argument(
"--dt",
"--dont-order-by-type",
dest="dont_order_by_type",
action="store_true",
help="Don't order imports by type in addition to alphabetically",
)
parser.add_argument(
"-p",
"--project",
dest="known_first_party",
action="append",
help="Force isort to recognize a module as being part of the current python project.",
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
dest="quiet",
help="Shows extra quiet output, only errors are outputted.",
)
parser.add_argument(
"--rm",
"--remove-import",
dest="remove_imports",
action="append",
help="Removes the specified import from all files.",
)
parser.add_argument(
"--rr",
"--reverse-relative",
dest="reverse_relative",
action="store_true",
help="Reverse order of relative imports.",
)
parser.add_argument(
"-s",
"--skip",
help="Files that sort imports should skip over. If you want to skip multiple "
"files you should specify twice: --skip file1 --skip file2.",
dest="skip",
action="append",
)
parser.add_argument(
"--sd",
"--section-default",
dest="default_section",
help="Sets the default section for imports (by default FIRSTPARTY) options: "
+ str(sections.DEFAULT),
)
parser.add_argument(
"--sg",
"--skip-glob",
help="Files that sort imports should skip over.",
dest="skip_glob",
action="append",
)
inline_args_group.add_argument(
"--sl",
"--force-single-line-imports",
dest="force_single_line",
action="store_true",
help="Forces all from imports to appear on their own line",
)
parser.add_argument(
"--nsl",
"--single-line-exclusions",
help="One or more modules to exclude from the single line rule.",
dest="single_line_exclusions",
action="append",
)
parser.add_argument(
"--sp",
"--settings-path",
"--settings-file",
"--settings",
dest="settings_path",
help="Explicitly set the settings path or file instead of auto determining "
"based on file location.",
)
parser.add_argument(
"-t",
"--top",
help="Force specific imports to the top of their appropriate section.",
dest="force_to_top",
action="append",
)
parser.add_argument(
"--tc",
"--trailing-comma",
dest="include_trailing_comma",
action="store_true",
help="Includes a trailing comma on multi line imports that include parentheses.",
)
parser.add_argument(
"--up",
"--use-parentheses",
dest="use_parentheses",
action="store_true",
help="Use parenthesis for line continuation on length limit instead of slashes.",
)
parser.add_argument(
"-V",
"--version",
action="store_true",
dest="show_version",
help="Displays the currently installed version of isort.",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
dest="verbose",
help="Shows verbose output, such as when files are skipped or when a check is successful.",
)
parser.add_argument(
"--virtual-env",
dest="virtual_env",
help="Virtual environment to use for determining whether a package is third-party",
)
parser.add_argument(
"--conda-env",
dest="conda_env",
help="Conda environment to use for determining whether a package is third-party",
)
parser.add_argument(
"--vn",
"--version-number",
action="version",
version=__version__,
help="Returns just the current version number without the logo",
)
parser.add_argument(
"-l",
"-w",
"--line-length",
"--line-width",
help="The max length of an import line (used for wrapping long imports).",
dest="line_length",
type=int,
)
parser.add_argument(
"--wl",
"--wrap-length",
dest="wrap_length",
type=int,
help="Specifies how long lines that are wrapped should be, if not set line_length is used."
"\nNOTE: wrap_length must be LOWER than or equal to line_length.",
)
parser.add_argument(
"--ws",
"--ignore-whitespace",
action="store_true",
dest="ignore_whitespace",
help="Tells isort to ignore whitespace differences when --check-only is being used.",
)
parser.add_argument(
"--case-sensitive",
dest="case_sensitive",
action="store_true",
help="Tells isort to include casing when sorting module names",
)
parser.add_argument(
"--filter-files",
dest="filter_files",
action="store_true",
help="Tells isort to filter files even when they are explicitly passed in as "
"part of the command",
)
parser.add_argument(
"files",
nargs="*",
help="One or more Python source files that need their imports sorted.",
)
parser.add_argument(
"--py",
"--python-version",
action="store",
dest="py_version",
choices=tuple(VALID_PY_TARGETS) + ("auto",),
help="Tells isort to set the known standard library based on the the specified Python "
"version. Default is to assume any Python 3 version could be the target, and use a union "
"off all stdlib modules across versions. If auto is specified, the version of the "
"interpreter used to run isort "
f"(currently: {sys.version_info.major}{sys.version_info.minor}) will be used.",
)
parser.add_argument(
"--profile",
dest="profile",
choices=list(profiles.keys()),
type=str,
help="Base profile type to use for configuration.",
)
parser.add_argument(
"--interactive",
dest="ask_to_apply",
action="store_true",
help="Tells isort to apply changes interactively.",
)
parser.add_argument(
"--old-finders",
"--magic",
dest="old_finders",
action="store_true",
help="Use the old deprecated finder logic that relies on environment introspection magic.",
)
parser.add_argument(
"--show-config",
dest="show_config",
action="store_true",
help="See isort's determined config, as well as sources of config options.",
)
return parser
|
https://github.com/PyCQA/isort/issues/1241
|
$ isort --src-path=. .
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/anders/python/isort/isort/main.py", line 647, in main
config = Config(**config_dict)
File "/home/anders/python/isort/isort/settings.py", line 329, in __init__
super().__init__(sources=tuple(sources), **combined_config) # type: ignore
TypeError: __init__() got an unexpected keyword argument 'source_paths'
|
TypeError
|
def main(
argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None
) -> None:
arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
if "settings_path" in arguments:
if os.path.isfile(arguments["settings_path"]):
arguments["settings_file"] = os.path.abspath(arguments["settings_path"])
arguments["settings_path"] = os.path.dirname(arguments["settings_file"])
elif not os.path.isdir(arguments["settings_path"]):
warn(f"settings_path dir does not exist: {arguments['settings_path']}")
else:
arguments["settings_path"] = os.path.abspath(arguments["settings_path"])
if "virtual_env" in arguments:
venv = arguments["virtual_env"]
arguments["virtual_env"] = os.path.abspath(venv)
if not os.path.isdir(arguments["virtual_env"]):
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")
file_names = arguments.pop("files", [])
if not file_names and not show_config:
print(QUICK_GUIDE)
return
elif file_names == ["-"] and not show_config:
api.sort_stream(
input_stream=sys.stdin if stdin is None else stdin,
output_stream=sys.stdout,
**arguments,
)
return
if "settings_path" not in arguments:
arguments["settings_path"] = (
os.path.abspath(file_names[0] if file_names else ".") or os.getcwd()
)
if not os.path.isdir(arguments["settings_path"]):
arguments["settings_path"] = os.path.dirname(arguments["settings_path"])
config_dict = arguments.copy()
ask_to_apply = config_dict.pop("ask_to_apply", False)
jobs = config_dict.pop("jobs", ())
filter_files = config_dict.pop("filter_files", False)
check = config_dict.pop("check", False)
show_diff = config_dict.pop("show_diff", False)
write_to_stdout = config_dict.pop("write_to_stdout", False)
src_paths = set(config_dict.setdefault("src_paths", ()))
for file_name in file_names:
if os.path.isdir(file_name):
src_paths.add(Path(file_name).resolve())
else:
src_paths.add(Path(file_name).parent.resolve())
config = Config(**config_dict)
if show_config:
print(
json.dumps(
config.__dict__, indent=4, separators=(",", ": "), default=_preconvert
)
)
return
wrong_sorted_files = False
skipped: List[str] = []
if filter_files:
filtered_files = []
for file_name in file_names:
if config.is_skipped(Path(file_name)):
skipped.append(file_name)
else:
filtered_files.append(file_name)
file_names = filtered_files
file_names = iter_source_code(file_names, config, skipped)
num_skipped = 0
if config.verbose:
print(ASCII_ART)
if jobs:
import multiprocessing
executor = multiprocessing.Pool(jobs)
attempt_iterator = executor.imap(
functools.partial(
sort_imports,
config=config,
check=check,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
),
file_names,
)
else:
# https://github.com/python/typeshed/pull/2814
attempt_iterator = (
sort_imports( # type: ignore
file_name,
config=config,
check=check,
ask_to_apply=ask_to_apply,
show_diff=show_diff,
write_to_stdout=write_to_stdout,
)
for file_name in file_names
)
for sort_attempt in attempt_iterator:
if not sort_attempt:
continue # pragma: no cover - shouldn't happen, satisfies type constraint
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get("check", False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code
if wrong_sorted_files:
sys.exit(1)
num_skipped += len(skipped)
if num_skipped and not arguments.get("quiet", False):
if config.verbose:
for was_skipped in skipped:
warn(
f"{was_skipped} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting"
)
print(f"Skipped {num_skipped} files")
|
def main(
argv: Optional[Sequence[str]] = None, stdin: Optional[TextIOWrapper] = None
) -> None:
arguments = parse_args(argv)
if arguments.get("show_version"):
print(ASCII_ART)
return
show_config: bool = arguments.pop("show_config", False)
if "settings_path" in arguments:
if os.path.isfile(arguments["settings_path"]):
arguments["settings_file"] = os.path.abspath(arguments["settings_path"])
arguments["settings_path"] = os.path.dirname(arguments["settings_file"])
elif not os.path.isdir(arguments["settings_path"]):
warn(f"settings_path dir does not exist: {arguments['settings_path']}")
else:
arguments["settings_path"] = os.path.abspath(arguments["settings_path"])
if "virtual_env" in arguments:
venv = arguments["virtual_env"]
arguments["virtual_env"] = os.path.abspath(venv)
if not os.path.isdir(arguments["virtual_env"]):
warn(f"virtual_env dir does not exist: {arguments['virtual_env']}")
file_names = arguments.pop("files", [])
if not file_names and not show_config:
print(QUICK_GUIDE)
return
elif file_names == ["-"] and not show_config:
api.sort_stream(
input_stream=sys.stdin if stdin is None else stdin,
output_stream=sys.stdout,
**arguments,
)
return
if "settings_path" not in arguments:
arguments["settings_path"] = (
os.path.abspath(file_names[0] if file_names else ".") or os.getcwd()
)
if not os.path.isdir(arguments["settings_path"]):
arguments["settings_path"] = os.path.dirname(arguments["settings_path"])
config_dict = arguments.copy()
ask_to_apply = config_dict.pop("ask_to_apply", False)
jobs = config_dict.pop("jobs", ())
filter_files = config_dict.pop("filter_files", False)
check = config_dict.pop("check", False)
show_diff = config_dict.pop("show_diff", False)
write_to_stdout = config_dict.pop("write_to_stdout", False)
src_paths = config_dict.setdefault("src_paths", set())
for file_name in file_names:
if os.path.isdir(file_name):
src_paths.add(Path(file_name).resolve())
else:
src_paths.add(Path(file_name).parent.resolve())
config = Config(**config_dict)
if show_config:
print(
json.dumps(
config.__dict__, indent=4, separators=(",", ": "), default=_preconvert
)
)
return
wrong_sorted_files = False
skipped: List[str] = []
if filter_files:
filtered_files = []
for file_name in file_names:
if config.is_skipped(Path(file_name)):
skipped.append(file_name)
else:
filtered_files.append(file_name)
file_names = filtered_files
file_names = iter_source_code(file_names, config, skipped)
num_skipped = 0
if config.verbose:
print(ASCII_ART)
if jobs:
import multiprocessing
executor = multiprocessing.Pool(jobs)
attempt_iterator = executor.imap(
functools.partial(
sort_imports,
config=config,
check=check,
ask_to_apply=ask_to_apply,
write_to_stdout=write_to_stdout,
),
file_names,
)
else:
# https://github.com/python/typeshed/pull/2814
attempt_iterator = (
sort_imports( # type: ignore
file_name,
config=config,
check=check,
ask_to_apply=ask_to_apply,
show_diff=show_diff,
write_to_stdout=write_to_stdout,
)
for file_name in file_names
)
for sort_attempt in attempt_iterator:
if not sort_attempt:
continue # pragma: no cover - shouldn't happen, satisfies type constraint
incorrectly_sorted = sort_attempt.incorrectly_sorted
if arguments.get("check", False) and incorrectly_sorted:
wrong_sorted_files = True
if sort_attempt.skipped:
num_skipped += 1 # pragma: no cover - shouldn't happen, due to skip in iter_source_code
if wrong_sorted_files:
sys.exit(1)
num_skipped += len(skipped)
if num_skipped and not arguments.get("quiet", False):
if config.verbose:
for was_skipped in skipped:
warn(
f"{was_skipped} was skipped as it's listed in 'skip' setting"
" or matches a glob in 'skip_glob' setting"
)
print(f"Skipped {num_skipped} files")
|
https://github.com/PyCQA/isort/issues/1241
|
$ isort --src-path=. .
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/anders/python/isort/isort/main.py", line 647, in main
config = Config(**config_dict)
File "/home/anders/python/isort/isort/settings.py", line 329, in __init__
super().__init__(sources=tuple(sources), **combined_config) # type: ignore
TypeError: __init__() got an unexpected keyword argument 'source_paths'
|
TypeError
|
def find(self, module_name):
for finder in self.finders:
try:
section = finder.find(module_name)
except Exception as exception:
# isort has to be able to keep trying to identify the correct import section even if one approach fails
if config.get("verbose", False):
print(
"{} encountered an error ({}) while trying to identify the {} module".format(
finder.__name__, str(exception), module_name
)
)
if section is not None:
return section
|
def find(self, module_name):
for finder in self.finders:
section = finder.find(module_name)
if section is not None:
return section
|
https://github.com/PyCQA/isort/issues/827
|
$ isort
Traceback (most recent call last):
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/packaging/requirements.py", line 93, in __init__
req = REQUIREMENT.parseString(requirement_string)
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py", line 1814, in parseString
raise exc
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py", line 1804, in parseString
loc, tokens = self._parse( instring, 0 )
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py", line 1548, in _parseNoCache
loc,tokens = self.parseImpl( instring, preloc, doActions )
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py", line 3722, in parseImpl
loc, exprtokens = e._parse( instring, loc, doActions )
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py", line 1552, in _parseNoCache
loc,tokens = self.parseImpl( instring, preloc, doActions )
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/pyparsing.py", line 3502, in parseImpl
raise ParseException(instring, loc, self.errmsg, self)
pip._vendor.pyparsing.ParseException: Expected stringEnd (at char 7), (line:1, col:8)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 285, in install_req_from_line
req = Requirement(req_as_string)
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_vendor/packaging/requirements.py", line 97, in __init__
requirement_string[e.loc : e.loc + 8], e.msg
pip._vendor.packaging.requirements.InvalidRequirement: Parse error at "'otherwis'": Expected stringEnd
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/vagrant/python/bin/isort", line 10, in <module>
sys.exit(main())
File "/home/vagrant/python/lib/python3.6/site-packages/isort/main.py", line 348, in main
for sort_attempt in attempt_iterator:
File "/home/vagrant/python/lib/python3.6/site-packages/isort/main.py", line 346, in <genexpr>
attempt_iterator = (sort_imports(file_name, **arguments) for file_name in file_names)
File "/home/vagrant/python/lib/python3.6/site-packages/isort/main.py", line 86, in sort_imports
result = SortImports(file_name, **arguments)
File "/home/vagrant/python/lib/python3.6/site-packages/isort/isort.py", line 141, in __init__
self.finder = FindersManager(config=self.config, sections=self.sections)
File "/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py", line 326, in __init__
self.finders = tuple(finder(config, sections) for finder in self.finders)
File "/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py", line 326, in <genexpr>
self.finders = tuple(finder(config, sections) for finder in self.finders)
File "/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py", line 184, in __init__
self.names = self._load_names()
File "/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py", line 206, in _load_names
for name in self._get_names(path):
File "/home/vagrant/python/lib/python3.6/site-packages/isort/finders.py", line 288, in _get_names
for req in requirements:
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/req_file.py", line 112, in parse_requirements
for req in req_iter:
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/req_file.py", line 193, in process_line
isolated=isolated, options=req_options, wheel_cache=wheel_cache
File "/home/vagrant/python/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 296, in install_req_from_line
"Invalid requirement: '%s'\n%s" % (req_as_string, add_msg)
pip._internal.exceptions.InstallationError: Invalid requirement: 'Unless otherwise stated, this license applies to all files contained'
|
pip._internal.exceptions.InstallationError
|
def create_domain_name(
self,
protocol, # type: str
domain_name, # type: str
endpoint_type, # type: str
certificate_arn, # type: str
security_policy=None, # type: Optional[str]
tags=None, # type: StrMap
):
# type: (...) -> DomainNameResponse
if protocol == "HTTP":
kwargs = {
"domainName": domain_name,
"endpointConfiguration": {
"types": [endpoint_type],
},
}
if security_policy is not None:
kwargs["securityPolicy"] = security_policy
if endpoint_type == "EDGE":
kwargs["certificateArn"] = certificate_arn
else:
kwargs["regionalCertificateArn"] = certificate_arn
if tags is not None:
kwargs["tags"] = tags
created_domain_name = self._create_domain_name(kwargs)
elif protocol == "WEBSOCKET":
kwargs = self.get_custom_domain_params_v2(
domain_name=domain_name,
endpoint_type=endpoint_type,
security_policy=security_policy,
certificate_arn=certificate_arn,
tags=tags,
)
created_domain_name = self._create_domain_name_v2(kwargs)
else:
raise ValueError("Unsupported protocol value.")
return created_domain_name
|
def create_domain_name(
self,
protocol, # type: str
domain_name, # type: str
endpoint_type, # type: str
certificate_arn, # type: str
security_policy=None, # type: Optional[str]
tags=None, # type: StrMap
):
# type: (...) -> Dict[str, Any]
if protocol == "HTTP":
kwargs = {
"domainName": domain_name,
"endpointConfiguration": {
"types": [endpoint_type],
},
}
if security_policy is not None:
kwargs["securityPolicy"] = security_policy
if endpoint_type == "EDGE":
kwargs["certificateArn"] = certificate_arn
else:
kwargs["regionalCertificateArn"] = certificate_arn
if tags is not None:
kwargs["tags"] = tags
created_domain_name = self._create_domain_name(kwargs)
elif protocol == "WEBSOCKET":
kwargs = self.get_custom_domain_params_v2(
domain_name=domain_name,
endpoint_type=endpoint_type,
security_policy=security_policy,
certificate_arn=certificate_arn,
tags=tags,
)
created_domain_name = self._create_domain_name_v2(kwargs)
else:
raise ValueError("Unsupported protocol value.")
return created_domain_name
|
https://github.com/aws/chalice/issues/1531
|
Updating custom domain name: api.transferbank.com.br
Traceback (most recent call last):
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 646, in main
return cli(obj={})
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 206, in deploy
deployed_values = d.deploy(config, chalice_stage_name=stage)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 374, in deploy
return self._deploy(config, chalice_stage_name)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 390, in _deploy
self._executor.execute(plan)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 42, in execute
getattr(self, '_do_%s' % instruction.__class__.__name__.lower(),
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 55, in _do_apicall
result = method(**final_kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 702, in update_domain_name
updated_domain_name = self._update_domain_name_v2(kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 802, in _update_domain_name_v2
'hosted_zone_id': result_data['HostedZoneId'],
KeyError: 'HostedZoneId'
|
KeyError
|
def _create_domain_name(self, api_args):
# type: (Dict[str, Any]) -> DomainNameResponse
client = self._client("apigateway")
exceptions = (client.exceptions.TooManyRequestsException,)
result = self._call_client_method_with_retries(
client.create_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
if result.get("regionalHostedZoneId"):
hosted_zone_id = result["regionalHostedZoneId"]
else:
hosted_zone_id = result["distributionHostedZoneId"]
if result.get("regionalCertificateArn"):
certificate_arn = result["regionalCertificateArn"]
else:
certificate_arn = result["certificateArn"]
if result.get("regionalDomainName") is not None:
alias_domain_name = result["regionalDomainName"]
else:
alias_domain_name = result["distributionDomainName"]
domain_name = {
"domain_name": result["domainName"],
"security_policy": result["securityPolicy"],
"hosted_zone_id": hosted_zone_id,
"certificate_arn": certificate_arn,
"alias_domain_name": alias_domain_name,
} # type: DomainNameResponse
return domain_name
|
def _create_domain_name(self, api_args):
# type: (Dict[str, Any]) -> Dict[str, Any]
client = self._client("apigateway")
exceptions = (client.exceptions.TooManyRequestsException,)
result = self._call_client_method_with_retries(
client.create_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
domain_name = {
"domain_name": result["domainName"],
"endpoint_configuration": result["endpointConfiguration"],
"security_policy": result["securityPolicy"],
}
if result.get("regionalHostedZoneId"):
domain_name["hosted_zone_id"] = result["regionalHostedZoneId"]
else:
domain_name["hosted_zone_id"] = result["distributionHostedZoneId"]
if result.get("regionalCertificateArn"):
domain_name["certificate_arn"] = result["regionalCertificateArn"]
else:
domain_name["certificate_arn"] = result["certificateArn"]
if result.get("regionalDomainName") is not None:
domain_name["alias_domain_name"] = result["regionalDomainName"]
else:
domain_name["alias_domain_name"] = result["distributionDomainName"]
return domain_name
|
https://github.com/aws/chalice/issues/1531
|
Updating custom domain name: api.transferbank.com.br
Traceback (most recent call last):
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 646, in main
return cli(obj={})
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 206, in deploy
deployed_values = d.deploy(config, chalice_stage_name=stage)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 374, in deploy
return self._deploy(config, chalice_stage_name)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 390, in _deploy
self._executor.execute(plan)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 42, in execute
getattr(self, '_do_%s' % instruction.__class__.__name__.lower(),
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 55, in _do_apicall
result = method(**final_kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 702, in update_domain_name
updated_domain_name = self._update_domain_name_v2(kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 802, in _update_domain_name_v2
'hosted_zone_id': result_data['HostedZoneId'],
KeyError: 'HostedZoneId'
|
KeyError
|
def _create_domain_name_v2(self, api_args):
# type: (Dict[str, Any]) -> DomainNameResponse
client = self._client("apigatewayv2")
exceptions = (client.exceptions.TooManyRequestsException,)
result = self._call_client_method_with_retries(
client.create_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
result_data = result["DomainNameConfigurations"][0]
domain_name = {
"domain_name": result["DomainName"],
"alias_domain_name": result_data["ApiGatewayDomainName"],
"security_policy": result_data["SecurityPolicy"],
"hosted_zone_id": result_data["HostedZoneId"],
"certificate_arn": result_data["CertificateArn"],
} # type: DomainNameResponse
return domain_name
|
def _create_domain_name_v2(self, api_args):
# type: (Dict[str, Any]) -> Dict[str, Any]
client = self._client("apigatewayv2")
exceptions = (client.exceptions.TooManyRequestsException,)
result = self._call_client_method_with_retries(
client.create_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
result_data = result["DomainNameConfigurations"][0]
domain_name = {
"domain_name": result_data["ApiGatewayDomainName"],
"endpoint_type": result_data["EndpointType"],
"security_policy": result_data["SecurityPolicy"],
"hosted_zone_id": result_data["HostedZoneId"],
"certificate_arn": result_data["CertificateArn"],
}
return domain_name
|
https://github.com/aws/chalice/issues/1531
|
Updating custom domain name: api.transferbank.com.br
Traceback (most recent call last):
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 646, in main
return cli(obj={})
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 206, in deploy
deployed_values = d.deploy(config, chalice_stage_name=stage)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 374, in deploy
return self._deploy(config, chalice_stage_name)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 390, in _deploy
self._executor.execute(plan)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 42, in execute
getattr(self, '_do_%s' % instruction.__class__.__name__.lower(),
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 55, in _do_apicall
result = method(**final_kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 702, in update_domain_name
updated_domain_name = self._update_domain_name_v2(kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 802, in _update_domain_name_v2
'hosted_zone_id': result_data['HostedZoneId'],
KeyError: 'HostedZoneId'
|
KeyError
|
def update_domain_name(
self,
protocol, # type: str
domain_name, # type: str
endpoint_type, # type: str
certificate_arn, # type: str
security_policy=None, # type: Optional[str]
tags=None, # type: StrMap
):
# type: (...) -> DomainNameResponse
if protocol == "HTTP":
patch_operations = self.get_custom_domain_patch_operations(
certificate_arn,
endpoint_type,
security_policy,
)
updated_domain_name = self._update_domain_name(domain_name, patch_operations)
elif protocol == "WEBSOCKET":
kwargs = self.get_custom_domain_params_v2(
domain_name=domain_name,
endpoint_type=endpoint_type,
security_policy=security_policy,
certificate_arn=certificate_arn,
)
updated_domain_name = self._update_domain_name_v2(kwargs)
else:
raise ValueError("Unsupported protocol value.")
resource_arn = (
"arn:aws:apigateway:{region_name}::/domainnames/{domain_name}".format(
region_name=self.region_name, domain_name=domain_name
)
)
self._update_resource_tags(resource_arn, tags)
return updated_domain_name
|
def update_domain_name(
self,
protocol, # type: str
domain_name, # type: str
endpoint_type, # type: str
certificate_arn, # type: str
security_policy=None, # type: Optional[str]
tags=None, # type: StrMap
):
# type: (...) -> Dict[str, Any]
if protocol == "HTTP":
patch_operations = self.get_custom_domain_patch_operations(
certificate_arn,
endpoint_type,
security_policy,
)
updated_domain_name = self._update_domain_name(domain_name, patch_operations)
elif protocol == "WEBSOCKET":
kwargs = self.get_custom_domain_params_v2(
domain_name=domain_name,
endpoint_type=endpoint_type,
security_policy=security_policy,
certificate_arn=certificate_arn,
)
updated_domain_name = self._update_domain_name_v2(kwargs)
else:
raise ValueError("Unsupported protocol value.")
resource_arn = (
"arn:aws:apigateway:{region_name}::/domainnames/{domain_name}".format(
region_name=self.region_name, domain_name=domain_name
)
)
self._update_resource_tags(resource_arn, tags)
return updated_domain_name
|
https://github.com/aws/chalice/issues/1531
|
Updating custom domain name: api.transferbank.com.br
Traceback (most recent call last):
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 646, in main
return cli(obj={})
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 206, in deploy
deployed_values = d.deploy(config, chalice_stage_name=stage)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 374, in deploy
return self._deploy(config, chalice_stage_name)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 390, in _deploy
self._executor.execute(plan)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 42, in execute
getattr(self, '_do_%s' % instruction.__class__.__name__.lower(),
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 55, in _do_apicall
result = method(**final_kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 702, in update_domain_name
updated_domain_name = self._update_domain_name_v2(kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 802, in _update_domain_name_v2
'hosted_zone_id': result_data['HostedZoneId'],
KeyError: 'HostedZoneId'
|
KeyError
|
def _update_domain_name(self, custom_domain_name, patch_operations):
# type: (str, List[Dict[str, str]]) -> DomainNameResponse
client = self._client("apigateway")
exceptions = (client.exceptions.TooManyRequestsException,)
result = {}
for patch_operation in patch_operations:
api_args = {
"domainName": custom_domain_name,
"patchOperations": [patch_operation],
}
response = self._call_client_method_with_retries(
client.update_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
result.update(response)
if result.get("regionalCertificateArn"):
certificate_arn = result["regionalCertificateArn"]
else:
certificate_arn = result["certificateArn"]
if result.get("regionalHostedZoneId"):
hosted_zone_id = result["regionalHostedZoneId"]
else:
hosted_zone_id = result["distributionHostedZoneId"]
if result.get("regionalDomainName") is not None:
alias_domain_name = result["regionalDomainName"]
else:
alias_domain_name = result["distributionDomainName"]
domain_name = {
"domain_name": result["domainName"],
"security_policy": result["securityPolicy"],
"certificate_arn": certificate_arn,
"hosted_zone_id": hosted_zone_id,
"alias_domain_name": alias_domain_name,
} # type: DomainNameResponse
return domain_name
|
def _update_domain_name(self, custom_domain_name, patch_operations):
# type: (str, List[Dict[str, str]]) -> Dict[str, Any]
client = self._client("apigateway")
exceptions = (client.exceptions.TooManyRequestsException,)
result = {}
for patch_operation in patch_operations:
api_args = {
"domainName": custom_domain_name,
"patchOperations": [patch_operation],
}
response = self._call_client_method_with_retries(
client.update_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
result.update(response)
domain_name = {
"domain_name": result["domainName"],
"endpoint_configuration": result["endpointConfiguration"],
"security_policy": result["securityPolicy"],
}
if result.get("regionalCertificateArn"):
domain_name["certificate_arn"] = result["regionalCertificateArn"]
else:
domain_name["certificate_arn"] = result["certificateArn"]
if result.get("regionalHostedZoneId"):
domain_name["hosted_zone_id"] = result["regionalHostedZoneId"]
else:
domain_name["hosted_zone_id"] = result["distributionHostedZoneId"]
if result.get("regionalDomainName") is not None:
domain_name["alias_domain_name"] = result["regionalDomainName"]
else:
domain_name["alias_domain_name"] = result["distributionDomainName"]
return domain_name
|
https://github.com/aws/chalice/issues/1531
|
Updating custom domain name: api.transferbank.com.br
Traceback (most recent call last):
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 646, in main
return cli(obj={})
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 206, in deploy
deployed_values = d.deploy(config, chalice_stage_name=stage)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 374, in deploy
return self._deploy(config, chalice_stage_name)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 390, in _deploy
self._executor.execute(plan)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 42, in execute
getattr(self, '_do_%s' % instruction.__class__.__name__.lower(),
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 55, in _do_apicall
result = method(**final_kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 702, in update_domain_name
updated_domain_name = self._update_domain_name_v2(kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 802, in _update_domain_name_v2
'hosted_zone_id': result_data['HostedZoneId'],
KeyError: 'HostedZoneId'
|
KeyError
|
def _update_domain_name_v2(self, api_args):
# type: (Dict[str, Any]) -> DomainNameResponse
client = self._client("apigatewayv2")
exceptions = (client.exceptions.TooManyRequestsException,)
result = self._call_client_method_with_retries(
client.update_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
result_data = result["DomainNameConfigurations"][0]
domain_name = {
"domain_name": result["DomainName"],
"alias_domain_name": result_data["ApiGatewayDomainName"],
"security_policy": result_data["SecurityPolicy"],
"hosted_zone_id": result_data["HostedZoneId"],
"certificate_arn": result_data["CertificateArn"],
} # type: DomainNameResponse
return domain_name
|
def _update_domain_name_v2(self, api_args):
# type: (Dict[str, Any]) -> Dict[str, Any]
client = self._client("apigatewayv2")
exceptions = (client.exceptions.TooManyRequestsException,)
result = self._call_client_method_with_retries(
client.update_domain_name,
api_args,
max_attempts=6,
should_retry=lambda x: True,
retryable_exceptions=exceptions,
)
result_data = result["DomainNameConfigurations"][0]
domain_name = {
"domain_name": result["DomainName"],
"endpoint_configuration": result_data["EndpointType"],
"security_policy": result_data["SecurityPolicy"],
"hosted_zone_id": result_data["HostedZoneId"],
"certificate_arn": result_data["CertificateArn"],
}
return domain_name
|
https://github.com/aws/chalice/issues/1531
|
Updating custom domain name: api.transferbank.com.br
Traceback (most recent call last):
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 646, in main
return cli(obj={})
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
return f(get_current_context(), *args, **kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/cli/__init__.py", line 206, in deploy
deployed_values = d.deploy(config, chalice_stage_name=stage)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 374, in deploy
return self._deploy(config, chalice_stage_name)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/deployer.py", line 390, in _deploy
self._executor.execute(plan)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 42, in execute
getattr(self, '_do_%s' % instruction.__class__.__name__.lower(),
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/deploy/executor.py", line 55, in _do_apicall
result = method(**final_kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 702, in update_domain_name
updated_domain_name = self._update_domain_name_v2(kwargs)
File "/Users/rafagan/.virtualenvs/tb-websocket-ws/lib/python3.8/site-packages/chalice/awsclient.py", line 802, in _update_domain_name_v2
'hosted_zone_id': result_data['HostedZoneId'],
KeyError: 'HostedZoneId'
|
KeyError
|
def iter_log_events(self, log_group_name, interleaved=True):
# type: (str, bool) -> Iterator[Dict[str, Any]]
logs = self._client("logs")
paginator = logs.get_paginator("filter_log_events")
pages = paginator.paginate(logGroupName=log_group_name, interleaved=True)
try:
for log_message in self._iter_log_messages(pages):
yield log_message
except logs.exceptions.ResourceNotFoundException:
# If the lambda function exists but has not been invoked yet,
# it's possible that the log group does not exist and we'll get
# a ResourceNotFoundException. If this happens we return instead
# of propagating an exception back to the user.
pass
|
def iter_log_events(self, log_group_name, interleaved=True):
# type: (str, bool) -> Iterator[Dict[str, Any]]
logs = self._client("logs")
paginator = logs.get_paginator("filter_log_events")
for page in paginator.paginate(logGroupName=log_group_name, interleaved=True):
events = page["events"]
for event in events:
# timestamp is modeled as a 'long', so we'll
# convert to a datetime to make it easier to use
# in python.
event["ingestionTime"] = self._convert_to_datetime(event["ingestionTime"])
event["timestamp"] = self._convert_to_datetime(event["timestamp"])
yield event
|
https://github.com/aws/chalice/issues/1252
|
$ cat app.py
from chalice import Chalice
app = Chalice(app_name='testlambda')
@app.lambda_function()
def index(event, context):
print("foo bar baz")
return {'hello': 'world'}
$ chalice deploy
...
$ chalice logs -n index
Traceback (most recent call last):
File "chalice/chalice/cli/__init__.py", line 485, in main
return cli(obj={})
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/click/decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "chalice/chalice/cli/__init__.py", line 292, in logs
sys.stdout)
File "chalice/chalice/logs.py", line 19, in display_logs
for event in events:
File "S File "S File "S File "S File "S File "rc File "/Users/jamessarient.py", line 677, in iter_log_events
for log_message in self._iter_log_messages(pages):
File "chalice/chalice/awsclient.py", line 681, in _iter_log_messages
for page in pages:
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/paginate.py", line 255, in __iter__
response = self._make_request(current_kwargs)
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/paginate.py", line 332, in _make_request
return self._method(**current_kwargs)
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File ".virtualenvs/chalice-37/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the FilterLogEvents operation: The specified log group does not exist.
|
botocore.errorfactory.ResourceNotFoundException
|
def __init__(self, osutils=None, import_string=None):
# type: (Optional[OSUtils], OptStr) -> None
if osutils is None:
osutils = OSUtils()
self._osutils = osutils
if import_string is None:
import_string = pip_import_string()
self._import_string = import_string
|
def __init__(self, osutils=None):
# type: (Optional[OSUtils]) -> None
if osutils is None:
osutils = OSUtils()
self._osutils = osutils
|
https://github.com/aws/chalice/issues/808
|
chalice.deploy.packager.PackageDownloadError: Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: module 'pip' has no attribute 'main'
|
AttributeError
|
def main(self, args, env_vars=None, shim=None):
# type: (List[str], EnvVars, OptStr) -> Tuple[int, Optional[bytes]]
if env_vars is None:
env_vars = self._osutils.environ()
if shim is None:
shim = ""
python_exe = sys.executable
run_pip = ("import sys; %s; sys.exit(main(%s))") % (self._import_string, args)
exec_string = "%s%s" % (shim, run_pip)
invoke_pip = [python_exe, "-c", exec_string]
p = self._osutils.popen(
invoke_pip, stdout=self._osutils.pipe, stderr=self._osutils.pipe, env=env_vars
)
_, err = p.communicate()
rc = p.returncode
return rc, err
|
def main(self, args, env_vars=None, shim=None):
# type: (List[str], EnvVars, OptStr) -> Tuple[int, Optional[bytes]]
if env_vars is None:
env_vars = self._osutils.environ()
if shim is None:
shim = ""
python_exe = sys.executable
run_pip = "import pip, sys; sys.exit(pip.main(%s))" % args
exec_string = "%s%s" % (shim, run_pip)
invoke_pip = [python_exe, "-c", exec_string]
p = subprocess.Popen(
invoke_pip, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env_vars
)
_, err = p.communicate()
rc = p.returncode
return rc, err
|
https://github.com/aws/chalice/issues/808
|
chalice.deploy.packager.PackageDownloadError: Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: module 'pip' has no attribute 'main'
|
AttributeError
|
def index(self, locale):
if locale not in self.appbuilder.bm.languages:
abort(404, description="Locale not supported.")
session["locale"] = locale
refresh()
self.update_redirect()
return redirect(self.get_redirect())
|
def index(self, locale):
session["locale"] = locale
refresh()
self.update_redirect()
return redirect(self.get_redirect())
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/1459
|
Traceback (most recent call last):
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_appbuilder\views.py", line 41, in index
return self.render_template(self.index_template, appbuilder=self.appbuilder)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_appbuilder\baseviews.py", line 280, in render_template
return render_template(
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\templating.py", line 137, in render_template
return _render(
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask\templating.py", line 120, in _render
rv = template.render(context)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\jinja2\environment.py", line 1090, in render
self.environment.handle_exception()
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\jinja2\environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\jinja2\_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\app\templates\index.html", line 1, in top-level template code
{% extends "appbuilder/base.html" %}
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_appbuilder\templates\appbuilder\base.html", line 1, in top-level template code
{% extends base_template %}
File "C:\Users\myuser\PycharmProjects\FAB-test-site\app\templates\mybase.html", line 1, in top-level template code
{% extends 'appbuilder/baselayout.html' %}
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_appbuilder\templates\appbuilder\baselayout.html", line 2, in top-level template code
{% import 'appbuilder/baselib.html' as baselib %}
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_appbuilder\templates\appbuilder\init.html", line 46, in top-level template code
{% block body %}
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_appbuilder\templates\appbuilder\baselayout.html", line 5, in block "body"
{% include 'appbuilder/general/confirm.html' %}
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_appbuilder\templates\appbuilder\general\confirm.html", line 6, in top-level template code
{{_('User confirmation needed')}}
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\jinja2\ext.py", line 144, in _gettext_alias
return __context.call(__context.resolve("gettext"), *args, **kwargs)
File "C:\Users\myuserPycharmProjects\FAB-test-site\venv\Lib\site-packages\jinja2\ext.py", line 150, in gettext
rv = __context.call(func, __string)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_babel\__init__.py", line 110, in <lambda>
lambda x: get_translations().ugettext(x),
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_babel\__init__.py", line 221, in get_translations
[get_locale()],
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\flask_babel\__init__.py", line 255, in get_locale
locale = Locale.parse(rv)
File "C:\Users\myuser\PycharmProjects\FAB-test-site\venv\Lib\site-packages\babel\core.py", line 331, in parse
raise UnknownLocaleError(input_id)
babel.core.UnknownLocaleError: unknown locale 'nonexistentlanguage'
|
babel.core.UnknownLocaleError
|
def login(self, flag=True):
@self.appbuilder.sm.oid.loginhandler
def login_handler(self):
if g.user is not None and g.user.is_authenticated:
return redirect(self.appbuilder.get_url_for_index)
form = LoginForm_oid()
if form.validate_on_submit():
session["remember_me"] = form.remember_me.data
return self.appbuilder.sm.oid.try_login(
form.openid.data,
ask_for=self.oid_ask_for,
ask_for_optional=self.oid_ask_for_optional,
)
return self.render_template(
self.login_template,
title=self.title,
form=form,
providers=self.appbuilder.sm.openid_providers,
appbuilder=self.appbuilder,
)
@self.appbuilder.sm.oid.after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash(as_unicode(self.invalid_login_message), "warning")
return redirect(self.appbuilder.get_url_for_login)
user = self.appbuilder.sm.auth_user_oid(resp.email)
if user is None:
flash(as_unicode(self.invalid_login_message), "warning")
return redirect(self.appbuilder.get_url_for_login)
remember_me = False
if "remember_me" in session:
remember_me = session["remember_me"]
session.pop("remember_me", None)
login_user(user, remember=remember_me)
return redirect(self.appbuilder.get_url_for_index)
return login_handler(self)
|
def login(self, flag=True):
@self.appbuilder.sm.oid.loginhandler
def login_handler(self):
if g.user is not None and g.user.is_authenticated:
return redirect(self.appbuilder.get_url_for_index)
form = LoginForm_oid()
if form.validate_on_submit():
session["remember_me"] = form.remember_me.data
return self.appbuilder.sm.oid.try_login(
form.openid.data,
ask_for=self.oid_ask_for,
ask_for_optional=self.oid_ask_for_optional,
)
return self.render_template(
self.login_template,
title=self.title,
form=form,
providers=self.appbuilder.sm.openid_providers,
appbuilder=self.appbuilder,
)
@self.appbuilder.sm.oid.after_login
def after_login(resp):
if resp.email is None or resp.email == "":
flash(as_unicode(self.invalid_login_message), "warning")
return redirect("login")
user = self.appbuilder.sm.auth_user_oid(resp.email)
if user is None:
flash(as_unicode(self.invalid_login_message), "warning")
return redirect("login")
remember_me = False
if "remember_me" in session:
remember_me = session["remember_me"]
session.pop("remember_me", None)
login_user(user, remember=remember_me)
return redirect(self.appbuilder.get_url_for_index)
return login_handler(self)
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/1260
|
File "/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py", line 678, in oauth_authorized
resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()
KeyError: 'login'
|
KeyError
|
def after_login(resp):
if resp.email is None or resp.email == "":
flash(as_unicode(self.invalid_login_message), "warning")
return redirect(self.appbuilder.get_url_for_login)
user = self.appbuilder.sm.auth_user_oid(resp.email)
if user is None:
flash(as_unicode(self.invalid_login_message), "warning")
return redirect(self.appbuilder.get_url_for_login)
remember_me = False
if "remember_me" in session:
remember_me = session["remember_me"]
session.pop("remember_me", None)
login_user(user, remember=remember_me)
return redirect(self.appbuilder.get_url_for_index)
|
def after_login(resp):
if resp.email is None or resp.email == "":
flash(as_unicode(self.invalid_login_message), "warning")
return redirect("login")
user = self.appbuilder.sm.auth_user_oid(resp.email)
if user is None:
flash(as_unicode(self.invalid_login_message), "warning")
return redirect("login")
remember_me = False
if "remember_me" in session:
remember_me = session["remember_me"]
session.pop("remember_me", None)
login_user(user, remember=remember_me)
return redirect(self.appbuilder.get_url_for_index)
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/1260
|
File "/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py", line 678, in oauth_authorized
resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()
KeyError: 'login'
|
KeyError
|
def oauth_authorized(self, provider):
log.debug("Authorized init")
resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()
if resp is None:
flash("You denied the request to sign in.", "warning")
return redirect(self.appbuilder.get_url_for_login)
log.debug("OAUTH Authorized resp: {0}".format(resp))
# Retrieves specific user info from the provider
try:
self.appbuilder.sm.set_oauth_session(provider, resp)
userinfo = self.appbuilder.sm.oauth_user_info(provider, resp)
except Exception as e:
log.error("Error returning OAuth user info: {0}".format(e))
user = None
else:
log.debug("User info retrieved from {0}: {1}".format(provider, userinfo))
# User email is not whitelisted
if provider in self.appbuilder.sm.oauth_whitelists:
whitelist = self.appbuilder.sm.oauth_whitelists[provider]
allow = False
for e in whitelist:
if re.search(e, userinfo["email"]):
allow = True
break
if not allow:
flash("You are not authorized.", "warning")
return redirect(self.appbuilder.get_url_for_login)
else:
log.debug("No whitelist for OAuth provider")
user = self.appbuilder.sm.auth_user_oauth(userinfo)
if user is None:
flash(as_unicode(self.invalid_login_message), "warning")
return redirect(self.appbuilder.get_url_for_login)
else:
login_user(user)
try:
state = jwt.decode(
request.args["state"],
self.appbuilder.app.config["SECRET_KEY"],
algorithms=["HS256"],
)
except jwt.InvalidTokenError:
raise Exception("State signature is not valid!")
try:
next_url = state["next"][0] or self.appbuilder.get_url_for_index
except (KeyError, IndexError):
next_url = self.appbuilder.get_url_for_index
return redirect(next_url)
|
def oauth_authorized(self, provider):
log.debug("Authorized init")
resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()
if resp is None:
flash("You denied the request to sign in.", "warning")
return redirect("login")
log.debug("OAUTH Authorized resp: {0}".format(resp))
# Retrieves specific user info from the provider
try:
self.appbuilder.sm.set_oauth_session(provider, resp)
userinfo = self.appbuilder.sm.oauth_user_info(provider, resp)
except Exception as e:
log.error("Error returning OAuth user info: {0}".format(e))
user = None
else:
log.debug("User info retrieved from {0}: {1}".format(provider, userinfo))
# User email is not whitelisted
if provider in self.appbuilder.sm.oauth_whitelists:
whitelist = self.appbuilder.sm.oauth_whitelists[provider]
allow = False
for e in whitelist:
if re.search(e, userinfo["email"]):
allow = True
break
if not allow:
flash("You are not authorized.", "warning")
return redirect("login")
else:
log.debug("No whitelist for OAuth provider")
user = self.appbuilder.sm.auth_user_oauth(userinfo)
if user is None:
flash(as_unicode(self.invalid_login_message), "warning")
return redirect("login")
else:
login_user(user)
try:
state = jwt.decode(
request.args["state"],
self.appbuilder.app.config["SECRET_KEY"],
algorithms=["HS256"],
)
except jwt.InvalidTokenError:
raise Exception("State signature is not valid!")
try:
next_url = state["next"][0] or self.appbuilder.get_url_for_index
except (KeyError, IndexError):
next_url = self.appbuilder.get_url_for_index
return redirect(next_url)
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/1260
|
File "/home/aman/superset/lib/python3.6/site-packages/flask_appbuilder/security/views.py", line 678, in oauth_authorized
resp = self.appbuilder.sm.oauth_remotes[provider].authorized_response()
KeyError: 'login'
|
KeyError
|
def _query_select_options(self, query, select_columns=None):
"""
Add select load options to query. The goal
is to only SQL select what is requested
:param query: SQLAlchemy Query obj
:param select_columns: (list) of columns
:return: SQLAlchemy Query obj
"""
if select_columns:
_load_options = list()
for column in select_columns:
query, relation_tuple = self._query_join_dotted_column(
query,
column,
)
model_relation, relation_join = relation_tuple or (None, None)
if model_relation:
_load_options.append(
Load(model_relation).load_only(column.split(".")[1])
)
else:
# is a custom property method field?
if hasattr(getattr(self.obj, column), "fget"):
pass
# is not a relation and not a function?
elif not self.is_relation(column) and not hasattr(
getattr(self.obj, column), "__call__"
):
_load_options.append(Load(self.obj).load_only(column))
else:
_load_options.append(Load(self.obj))
query = query.options(*tuple(_load_options))
return query
|
def _query_select_options(self, query, select_columns=None):
"""
Add select load options to query. The goal
is to only SQL select what is requested
:param query: SQLAlchemy Query obj
:param select_columns: (list) of columns
:return: SQLAlchemy Query obj
"""
if select_columns:
_load_options = list()
for column in select_columns:
if "." in column:
model_relation = self.get_related_model(column.split(".")[0])
if not self.is_model_already_joinded(query, model_relation):
query = query.join(model_relation)
_load_options.append(
Load(model_relation).load_only(column.split(".")[1])
)
else:
# is a custom property method field?
if hasattr(getattr(self.obj, column), "fget"):
pass
# is not a relation and not a function?
elif not self.is_relation(column) and not hasattr(
getattr(self.obj, column), "__call__"
):
_load_options.append(Load(self.obj).load_only(column))
else:
_load_options.append(Load(self.obj))
query = query.options(*tuple(_load_options))
return query
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/1026
|
sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
|
sqlalchemy.exc.AmbiguousForeignKeysError
|
def query(
self,
filters=None,
order_column="",
order_direction="",
page=None,
page_size=None,
select_columns=None,
):
"""
QUERY
:param filters:
dict with filters {<col_name>:<value,...}
:param order_column:
name of the column to order
:param order_direction:
the direction to order <'asc'|'desc'>
:param page:
the current page
:param page_size:
the current page size
"""
query = self.session.query(self.obj)
query, relation_tuple = self._query_join_dotted_column(query, order_column)
query = self._query_select_options(query, select_columns)
query_count = self.session.query(func.count("*")).select_from(self.obj)
query_count = self._get_base_query(query=query_count, filters=filters)
query = self._get_base_query(
query=query,
filters=filters,
order_column=order_column,
order_direction=order_direction,
)
count = query_count.scalar()
if page:
query = query.offset(page * page_size)
if page_size:
query = query.limit(page_size)
return count, query.all()
|
def query(
self,
filters=None,
order_column="",
order_direction="",
page=None,
page_size=None,
select_columns=None,
):
"""
QUERY
:param filters:
dict with filters {<col_name>:<value,...}
:param order_column:
name of the column to order
:param order_direction:
the direction to order <'asc'|'desc'>
:param page:
the current page
:param page_size:
the current page size
"""
query = self.session.query(self.obj)
query = self._query_select_options(query, select_columns)
if len(order_column.split(".")) >= 2:
for join_relation in order_column.split(".")[:-1]:
relation_tuple = self.get_related_model_and_join(join_relation)
model_relation, relation_join = relation_tuple
if not self.is_model_already_joinded(query, model_relation):
query = query.join(model_relation, relation_join, isouter=True)
query_count = self.session.query(func.count("*")).select_from(self.obj)
query_count = self._get_base_query(query=query_count, filters=filters)
query = self._get_base_query(
query=query,
filters=filters,
order_column=order_column,
order_direction=order_direction,
)
count = query_count.scalar()
if page:
query = query.offset(page * page_size)
if page_size:
query = query.limit(page_size)
return count, query.all()
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/1026
|
sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'project' and 'ab_user'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
|
sqlalchemy.exc.AmbiguousForeignKeysError
|
def auth_user_ldap(self, username, password):
"""
Method for authenticating user, auth LDAP style.
depends on ldap module that is not mandatory requirement
for F.A.B.
:param username:
The username
:param password:
The password
"""
if username is None or username == "":
return None
user = self.find_user(username=username)
if user is not None and (not user.is_active()):
return None
else:
try:
import ldap
except:
raise Exception("No ldap library for python.")
try:
if self.auth_ldap_allow_self_signed:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
con = ldap.initialize(self.auth_ldap_server)
con.set_option(ldap.OPT_REFERRALS, 0)
if self.auth_ldap_use_tls:
try:
con.start_tls_s()
except Exception:
log.info(LOGMSG_ERR_SEC_AUTH_LDAP_TLS.format(self.auth_ldap_server))
return None
# Authenticate user
if not self._bind_ldap(ldap, con, username, password):
if user:
self.update_user_auth_stat(user, False)
log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
return None
# If user does not exist on the DB and not self user registration, go away
if not user and not self.auth_user_registration:
return None
# User does not exist, create one if self registration.
elif not user and self.auth_user_registration:
new_user = self._search_ldap(ldap, con, username)
if not new_user:
log.warning(LOGMSG_WAR_SEC_NOLDAP_OBJ.format(username))
return None
ldap_user_info = new_user[0][1]
if self.auth_user_registration and user is None:
user = self.add_user(
username=username,
first_name=self.ldap_extract(
ldap_user_info, self.auth_ldap_firstname_field, username
),
last_name=self.ldap_extract(
ldap_user_info, self.auth_ldap_lastname_field, username
),
email=self.ldap_extract(
ldap_user_info,
self.auth_ldap_email_field,
username + "@email.notfound",
),
role=self.find_role(self.auth_user_registration_role),
)
self.update_user_auth_stat(user)
return user
except ldap.LDAPError as e:
if type(e.message) == dict and "desc" in e.message:
log.error(LOGMSG_ERR_SEC_AUTH_LDAP.format(e.message["desc"]))
return None
else:
log.error(e)
return None
|
def auth_user_ldap(self, username, password):
"""
Method for authenticating user, auth LDAP style.
depends on ldap module that is not mandatory requirement
for F.A.B.
:param username:
The username
:param password:
The password
"""
if username is None or username == "":
return None
user = self.find_user(username=username)
if user is not None and (not user.is_active()):
return None
else:
try:
import ldap
except:
raise Exception("No ldap library for python.")
try:
if self.auth_ldap_allow_self_signed:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
con = ldap.initialize(self.auth_ldap_server)
con.set_option(ldap.OPT_REFERRALS, 0)
if self.auth_ldap_use_tls:
try:
con.start_tls_s()
except Exception:
log.info(LOGMSG_ERR_SEC_AUTH_LDAP_TLS.format(self.auth_ldap_server))
return None
# Authenticate user
if not self._bind_ldap(ldap, con, username, password):
if user:
self.update_user_auth_stat(user, False)
log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
return None
# If user does not exist on the DB and not self user registration, go away
if not user and not self.auth_user_registration:
return None
# User does not exist, create one if self registration.
elif not user and self.auth_user_registration:
new_user = self._search_ldap(ldap, con, username)
if not new_user:
log.warning(LOGMSG_WAR_SEC_NOLDAP_OBJ.format(username))
return None
ldap_user_info = new_user[0][1]
if self.auth_user_registration and user is None:
user = self.add_user(
username=username,
first_name=ldap_user_info.get(
self.auth_ldap_firstname_field, [username]
)[0],
last_name=ldap_user_info.get(
self.auth_ldap_lastname_field, [username]
)[0],
email=ldap_user_info.get(
self.auth_ldap_email_field, [username + "@email.notfound"]
)[0],
role=self.find_role(self.auth_user_registration_role),
)
self.update_user_auth_stat(user)
return user
except ldap.LDAPError as e:
if type(e.message) == dict and "desc" in e.message:
log.error(LOGMSG_ERR_SEC_AUTH_LDAP.format(e.message["desc"]))
return None
else:
log.error(e)
return None
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/544
|
Sorry, something went wrong
500 - Internal Server Error
Stacktrace
Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found
|
TypeError
|
def _get_base_query(
self, query=None, filters=None, order_column="", order_direction=""
):
if filters:
query = filters.apply_all(query)
if order_column != "":
# if Model has custom decorator **renders('<COL_NAME>')**
# this decorator will add a property to the method named *_col_name*
if hasattr(self.obj, order_column):
if hasattr(getattr(self.obj, order_column), "_col_name"):
order_column = getattr(getattr(self.obj, order_column), "_col_name")
query = query.order_by("%s %s" % (order_column, order_direction))
return query
|
def _get_base_query(
self, query=None, filters=None, order_column="", order_direction=""
):
if filters:
query = filters.apply_all(query)
if order_column != "":
# if Model has custom decorator **renders('<COL_NAME>')**
# this decorator will add a property to the method named *_col_name*
if hasattr(self.obj, order_column):
if hasattr(getattr(self.obj, order_column), "_col_name"):
order_column = getattr(getattr(self.obj, order_column), "_col_name")
query = query.order_by(order_column + " " + order_direction)
return query
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/544
|
Sorry, something went wrong
500 - Internal Server Error
Stacktrace
Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found
|
TypeError
|
def get_order_args():
"""
Get order arguments, return a dictionary
{ <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) }
Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
"""
orders = {}
for arg in request.args:
re_match = re.findall("_oc_(.*)", arg)
if re_match:
order_direction = request.args.get("_od_" + re_match[0])
if order_direction in ("asc", "desc"):
orders[re_match[0]] = (request.args.get(arg), order_direction)
return orders
|
def get_order_args():
"""
Get order arguments, return a dictionary
{ <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) }
Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
"""
orders = {}
for arg in request.args:
re_match = re.findall("_oc_(.*)", arg)
if re_match:
orders[re_match[0]] = (
request.args.get(arg),
request.args.get("_od_" + re_match[0]),
)
return orders
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/544
|
Sorry, something went wrong
500 - Internal Server Error
Stacktrace
Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found
|
TypeError
|
def _get_attr_value(item, col):
if not hasattr(item, col):
# it's an inner obj attr
try:
return reduce(getattr, col.split("."), item)
except Exception as e:
return ""
if hasattr(getattr(item, col), "__call__"):
# its a function
return getattr(item, col)()
else:
# its an attribute
value = getattr(item, col)
# if value is an Enum instance than list and show widgets should display
# its .value rather than its .name:
if _has_enum and isinstance(value, enum.Enum):
return value.value
return value
|
def _get_attr_value(self, item, col):
if not hasattr(item, col):
# it's an inner obj attr
try:
return reduce(getattr, col.split("."), item)
except Exception as e:
return ""
if hasattr(getattr(item, col), "__call__"):
# its a function
return getattr(item, col)()
else:
# its an attribute
value = getattr(item, col)
# if value is an Enum instance than list and show widgets should display
# its .value rather than its .name:
if _has_enum and isinstance(value, enum.Enum):
return value.value
return value
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/544
|
Sorry, something went wrong
500 - Internal Server Error
Stacktrace
Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found
|
TypeError
|
def _get_base_query(
self, query=None, filters=None, order_column="", order_direction=""
):
if filters:
query = filters.apply_all(query)
if order_column != "":
# if Model has custom decorator **renders('<COL_NAME>')**
# this decorator will add a property to the method named *_col_name*
if hasattr(self.obj, order_column):
if hasattr(getattr(self.obj, order_column), "_col_name"):
order_column = getattr(self._get_attr(order_column), "_col_name")
if order_direction == "asc":
query = query.order_by(self._get_attr(order_column).asc())
else:
query = query.order_by(self._get_attr(order_column).desc())
return query
|
def _get_base_query(
self, query=None, filters=None, order_column="", order_direction=""
):
if filters:
query = filters.apply_all(query)
if order_column != "":
# if Model has custom decorator **renders('<COL_NAME>')**
# this decorator will add a property to the method named *_col_name*
if hasattr(self.obj, order_column):
if hasattr(getattr(self.obj, order_column), "_col_name"):
order_column = getattr(getattr(self.obj, order_column), "_col_name")
query = query.order_by("%s %s" % (order_column, order_direction))
return query
|
https://github.com/dpgaspar/Flask-AppBuilder/issues/544
|
Sorry, something went wrong
500 - Internal Server Error
Stacktrace
Traceback (most recent call last):
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/superset/.env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/security/decorators.py", line 26, in wraps
return f(self, *args, **kwargs)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/views.py", line 450, in list
widgets = self._list()
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 870, in _list
page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/baseviews.py", line 786, in _get_list_widget
count, lst = self.datamodel.query(joined_filters, order_column, order_direction, page=page, page_size=page_size)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 103, in query
order_direction=order_direction)
File "/opt/superset/.env/lib/python2.7/site-packages/flask_appbuilder/models/sqla/interface.py", line 67, in _get_base_query
query = query.order_by(order_column + ' ' + order_direction)
TypeError: coercing to Unicode: need string or buffer, NoneType found
|
TypeError
|
def solve(self, problem: QuadraticProgram) -> ADMMOptimizationResult:
"""Tries to solves the given problem using ADMM algorithm.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
QiskitOptimizationError: If the problem is not compatible with the ADMM optimizer.
"""
self._verify_compatibility(problem)
# debug
self._log.debug("Initial problem: %s", problem.export_as_lp_string())
# map integer variables to binary variables
from ..converters.integer_to_binary import IntegerToBinary
int2bin = IntegerToBinary()
original_problem = problem
problem = int2bin.convert(problem)
# we deal with minimization in the optimizer, so turn the problem to minimization
problem, sense = self._turn_to_minimization(problem)
# create our computation state.
self._state = ADMMState(problem, self._params.rho_initial)
# parse problem and convert to an ADMM specific representation.
self._state.binary_indices = self._get_variable_indices(
problem, Variable.Type.BINARY
)
self._state.continuous_indices = self._get_variable_indices(
problem, Variable.Type.CONTINUOUS
)
if self._params.warm_start:
# warm start injection for the initial values of the variables
self._warm_start(problem)
# convert optimization problem to a set of matrices and vector that are used
# at each iteration.
self._convert_problem_representation()
start_time = time.time()
# we have not stated our computations yet, so elapsed time initialized as zero.
elapsed_time = 0.0
iteration = 0
residual = 1.0e2
while (iteration < self._params.maxiter and residual > self._params.tol) and (
elapsed_time < self._params.max_time
):
if self._state.step1_absolute_indices:
op1 = self._create_step1_problem()
self._state.x0 = self._update_x0(op1)
# debug
self._log.debug("Step 1 sub-problem: %s", op1.export_as_lp_string())
# else, no binary variables exist, and no update to be done in this case.
# debug
self._log.debug("x0=%s", self._state.x0)
op2 = self._create_step2_problem()
self._state.u, self._state.z = self._update_x1(op2)
# debug
self._log.debug("Step 2 sub-problem: %s", op2.export_as_lp_string())
self._log.debug("u=%s", self._state.u)
self._log.debug("z=%s", self._state.z)
if self._params.three_block:
if self._state.binary_indices:
op3 = self._create_step3_problem()
self._state.y = self._update_y(op3)
# debug
self._log.debug("Step 3 sub-problem: %s", op3.export_as_lp_string())
# debug
self._log.debug("y=%s", self._state.y)
self._state.lambda_mult = self._update_lambda_mult()
# debug
self._log.debug("lambda: %s", self._state.lambda_mult)
cost_iterate = self._get_objective_value()
constraint_residual = self._get_constraint_residual()
residual, dual_residual = self._get_solution_residuals(iteration)
merit = self._get_merit(cost_iterate, constraint_residual)
# debug
self._log.debug(
"cost_iterate=%s, cr=%s, merit=%s", cost_iterate, constraint_residual, merit
)
# costs are saved with their original sign.
self._state.cost_iterates.append(cost_iterate)
self._state.residuals.append(residual)
self._state.dual_residuals.append(dual_residual)
self._state.cons_r.append(constraint_residual)
self._state.merits.append(merit)
self._state.lambdas.append(np.linalg.norm(self._state.lambda_mult))
self._state.x0_saved.append(self._state.x0)
self._state.u_saved.append(self._state.u)
self._state.z_saved.append(self._state.z)
self._state.z_saved.append(self._state.y)
self._update_rho(residual, dual_residual)
iteration += 1
elapsed_time = time.time() - start_time
binary_vars, continuous_vars, objective_value = self._get_best_merit_solution()
solution = self._revert_solution_indexes(binary_vars, continuous_vars)
# flip the objective sign again if required
objective_value = objective_value * sense
# convert back integer to binary
base_result = OptimizationResult(
solution, objective_value, problem.variables, OptimizationResultStatus.SUCCESS
)
base_result = int2bin.interpret(base_result)
# third parameter is our internal state of computations.
result = ADMMOptimizationResult(
x=base_result.x,
fval=base_result.fval,
variables=original_problem.variables,
state=self._state,
status=self._get_feasibility_status(original_problem, base_result.x),
)
# debug
self._log.debug(
"solution=%s, objective=%s at iteration=%s",
solution,
objective_value,
iteration,
)
return result
|
def solve(self, problem: QuadraticProgram) -> ADMMOptimizationResult:
"""Tries to solves the given problem using ADMM algorithm.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
QiskitOptimizationError: If the problem is not compatible with the ADMM optimizer.
"""
self._verify_compatibility(problem)
# debug
self._log.debug("Initial problem: %s", problem.export_as_lp_string())
# map integer variables to binary variables
from ..converters.integer_to_binary import IntegerToBinary
int2bin = IntegerToBinary()
original_variables = problem.variables
problem = int2bin.convert(problem)
# we deal with minimization in the optimizer, so turn the problem to minimization
problem, sense = self._turn_to_minimization(problem)
# create our computation state.
self._state = ADMMState(problem, self._params.rho_initial)
# parse problem and convert to an ADMM specific representation.
self._state.binary_indices = self._get_variable_indices(
problem, Variable.Type.BINARY
)
self._state.continuous_indices = self._get_variable_indices(
problem, Variable.Type.CONTINUOUS
)
if self._params.warm_start:
# warm start injection for the initial values of the variables
self._warm_start(problem)
# convert optimization problem to a set of matrices and vector that are used
# at each iteration.
self._convert_problem_representation()
start_time = time.time()
# we have not stated our computations yet, so elapsed time initialized as zero.
elapsed_time = 0.0
iteration = 0
residual = 1.0e2
while (iteration < self._params.maxiter and residual > self._params.tol) and (
elapsed_time < self._params.max_time
):
if self._state.step1_absolute_indices:
op1 = self._create_step1_problem()
self._state.x0 = self._update_x0(op1)
# debug
self._log.debug("Step 1 sub-problem: %s", op1.export_as_lp_string())
# else, no binary variables exist, and no update to be done in this case.
# debug
self._log.debug("x0=%s", self._state.x0)
op2 = self._create_step2_problem()
self._state.u, self._state.z = self._update_x1(op2)
# debug
self._log.debug("Step 2 sub-problem: %s", op2.export_as_lp_string())
self._log.debug("u=%s", self._state.u)
self._log.debug("z=%s", self._state.z)
if self._params.three_block:
if self._state.binary_indices:
op3 = self._create_step3_problem()
self._state.y = self._update_y(op3)
# debug
self._log.debug("Step 3 sub-problem: %s", op3.export_as_lp_string())
# debug
self._log.debug("y=%s", self._state.y)
self._state.lambda_mult = self._update_lambda_mult()
# debug
self._log.debug("lambda: %s", self._state.lambda_mult)
cost_iterate = self._get_objective_value()
constraint_residual = self._get_constraint_residual()
residual, dual_residual = self._get_solution_residuals(iteration)
merit = self._get_merit(cost_iterate, constraint_residual)
# debug
self._log.debug(
"cost_iterate=%s, cr=%s, merit=%s", cost_iterate, constraint_residual, merit
)
# costs are saved with their original sign.
self._state.cost_iterates.append(cost_iterate)
self._state.residuals.append(residual)
self._state.dual_residuals.append(dual_residual)
self._state.cons_r.append(constraint_residual)
self._state.merits.append(merit)
self._state.lambdas.append(np.linalg.norm(self._state.lambda_mult))
self._state.x0_saved.append(self._state.x0)
self._state.u_saved.append(self._state.u)
self._state.z_saved.append(self._state.z)
self._state.z_saved.append(self._state.y)
self._update_rho(residual, dual_residual)
iteration += 1
elapsed_time = time.time() - start_time
binary_vars, continuous_vars, objective_value = self._get_best_merit_solution()
solution = self._revert_solution_indexes(binary_vars, continuous_vars)
# flip the objective sign again if required
objective_value = objective_value * sense
# convert back integer to binary
base_result = OptimizationResult(
solution, objective_value, original_variables, OptimizationResultStatus.SUCCESS
)
base_result = int2bin.interpret(base_result)
# third parameter is our internal state of computations.
result = ADMMOptimizationResult(
x=base_result.x,
fval=base_result.fval,
variables=base_result.variables,
state=self._state,
status=self._get_feasibility_status(problem, base_result.x),
)
# debug
self._log.debug(
"solution=%s, objective=%s at iteration=%s",
solution,
objective_value,
iteration,
)
return result
|
https://github.com/Qiskit/qiskit-aqua/issues/1392
|
Traceback (most recent call last):
File ".../admmprove.py", line 53, in <module>
result_q = admm_q.solve(qp)
File ".../qiskit-aqua/qiskit/optimization/algorithms/admm_optimizer.py", line 381, in solve
OptimizationResultStatus.SUCCESS)
File ".../qiskit-aqua/qiskit/optimization/algorithms/optimization_algorithm.py", line 106, in __init__
[v.name for v in variables]))
qiskit.optimization.exceptions.QiskitOptimizationError: "Inconsistent size of optimal value and variables. x: size 6 [0. 0. 0. 0. 0. 0.], variables: size 4 ['v', 'w', 't', 'u']"
|
qiskit.optimization.exceptions.QiskitOptimizationError
|
def solve(self, problem: QuadraticProgram) -> OptimizationResult:
"""Tries to solves the given problem using the grover optimizer.
Runs the optimizer to try to solve the optimization problem. If the problem cannot be,
converted to a QUBO, this optimizer raises an exception due to incompatibility.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
AttributeError: If the quantum instance has not been set.
QiskitOptimizationError: If the problem is incompatible with the optimizer.
"""
if self.quantum_instance is None:
raise AttributeError("The quantum instance or backend has not been set.")
self._verify_compatibility(problem)
# convert problem to QUBO
problem_ = self._convert(problem, self._converters)
problem_init = deepcopy(problem_)
# convert to minimization problem
sense = problem_.objective.sense
if sense == problem_.objective.Sense.MAXIMIZE:
problem_.objective.sense = problem_.objective.Sense.MINIMIZE
problem_.objective.constant = -problem_.objective.constant
for i, val in problem_.objective.linear.to_dict().items():
problem_.objective.linear[i] = -val
for (i, j), val in problem_.objective.quadratic.to_dict().items():
problem_.objective.quadratic[i, j] = -val
self._num_key_qubits = len(problem_.objective.linear.to_array()) # type: ignore
# Variables for tracking the optimum.
optimum_found = False
optimum_key = math.inf
optimum_value = math.inf
threshold = 0
n_key = len(problem_.variables)
n_value = self._num_value_qubits
# Variables for tracking the solutions encountered.
num_solutions = 2**n_key
keys_measured = []
# Variables for result object.
operation_count = {}
iteration = 0
# Variables for stopping if we've hit the rotation max.
rotations = 0
max_rotations = int(np.ceil(100 * np.pi / 4))
# Initialize oracle helper object.
qr_key_value = QuantumRegister(self._num_key_qubits + self._num_value_qubits)
orig_constant = problem_.objective.constant
measurement = not self.quantum_instance.is_statevector
oracle, is_good_state = self._get_oracle(qr_key_value)
while not optimum_found:
m = 1
improvement_found = False
# Get oracle O and the state preparation operator A for the current threshold.
problem_.objective.constant = orig_constant - threshold
a_operator = self._get_a_operator(qr_key_value, problem_)
# Iterate until we measure a negative.
loops_with_no_improvement = 0
while not improvement_found:
# Determine the number of rotations.
loops_with_no_improvement += 1
rotation_count = int(np.ceil(aqua_globals.random.uniform(0, m - 1)))
rotations += rotation_count
# Apply Grover's Algorithm to find values below the threshold.
# TODO: Utilize Grover's incremental feature - requires changes to Grover.
grover = Grover(
oracle, state_preparation=a_operator, good_state=is_good_state
)
circuit = grover.construct_circuit(rotation_count, measurement=measurement)
# Get the next outcome.
outcome = self._measure(circuit)
k = int(outcome[0:n_key], 2)
v = outcome[n_key : n_key + n_value]
int_v = self._bin_to_int(v, n_value) + threshold
v = self._twos_complement(int_v, n_value)
logger.info("Outcome: %s", outcome)
logger.info("Value: %s = %s", v, int_v)
# If the value is an improvement, we update the iteration parameters (e.g. oracle).
if int_v < optimum_value:
optimum_key = k
optimum_value = int_v
logger.info("Current Optimum Key: %s", optimum_key)
logger.info("Current Optimum Value: %s", optimum_value)
if v.startswith("1"):
improvement_found = True
threshold = optimum_value
else:
# Using Durr and Hoyer method, increase m.
m = int(np.ceil(min(m * 8 / 7, 2 ** (n_key / 2))))
logger.info("No Improvement. M: %s", m)
# Check if we've already seen this value.
if k not in keys_measured:
keys_measured.append(k)
# Assume the optimal if any of the stop parameters are true.
if (
loops_with_no_improvement >= self._n_iterations
or len(keys_measured) == num_solutions
or rotations >= max_rotations
):
improvement_found = True
optimum_found = True
# Track the operation count.
operations = circuit.count_ops()
operation_count[iteration] = operations
iteration += 1
logger.info("Operation Count: %s\n", operations)
# If the constant is 0 and we didn't find a negative, the answer is likely 0.
if optimum_value >= 0 and orig_constant == 0:
optimum_key = 0
opt_x = np.array(
[1 if s == "1" else 0 for s in ("{0:%sb}" % n_key).format(optimum_key)]
)
# Compute function value
fval = problem_init.objective.evaluate(opt_x)
result = OptimizationResult(
x=opt_x,
fval=fval,
variables=problem_.variables,
status=OptimizationResultStatus.SUCCESS,
)
# cast binaries back to integers
result = self._interpret(result, self._converters)
return GroverOptimizationResult(
x=result.x,
fval=result.fval,
variables=result.variables,
operation_counts=operation_count,
n_input_qubits=n_key,
n_output_qubits=n_value,
intermediate_fval=fval,
threshold=threshold,
status=self._get_feasibility_status(problem, result.x),
)
|
def solve(self, problem: QuadraticProgram) -> OptimizationResult:
"""Tries to solves the given problem using the grover optimizer.
Runs the optimizer to try to solve the optimization problem. If the problem cannot be,
converted to a QUBO, this optimizer raises an exception due to incompatibility.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
AttributeError: If the quantum instance has not been set.
QiskitOptimizationError: If the problem is incompatible with the optimizer.
"""
if self.quantum_instance is None:
raise AttributeError("The quantum instance or backend has not been set.")
self._verify_compatibility(problem)
# convert problem to QUBO
problem_ = self._convert(problem, self._converters)
problem_init = deepcopy(problem_)
# convert to minimization problem
sense = problem_.objective.sense
if sense == problem_.objective.Sense.MAXIMIZE:
problem_.objective.sense = problem_.objective.Sense.MINIMIZE
problem_.objective.constant = -problem_.objective.constant
for i, val in problem_.objective.linear.to_dict().items():
problem_.objective.linear[i] = -val
for (i, j), val in problem_.objective.quadratic.to_dict().items():
problem_.objective.quadratic[i, j] = -val
self._num_key_qubits = len(problem_.objective.linear.to_array()) # type: ignore
# Variables for tracking the optimum.
optimum_found = False
optimum_key = math.inf
optimum_value = math.inf
threshold = 0
n_key = len(problem_.variables)
n_value = self._num_value_qubits
# Variables for tracking the solutions encountered.
num_solutions = 2**n_key
keys_measured = []
# Variables for result object.
operation_count = {}
iteration = 0
# Variables for stopping if we've hit the rotation max.
rotations = 0
max_rotations = int(np.ceil(100 * np.pi / 4))
# Initialize oracle helper object.
qr_key_value = QuantumRegister(self._num_key_qubits + self._num_value_qubits)
orig_constant = problem_.objective.constant
measurement = not self.quantum_instance.is_statevector
oracle, is_good_state = self._get_oracle(qr_key_value)
while not optimum_found:
m = 1
improvement_found = False
# Get oracle O and the state preparation operator A for the current threshold.
problem_.objective.constant = orig_constant - threshold
a_operator = self._get_a_operator(qr_key_value, problem_)
# Iterate until we measure a negative.
loops_with_no_improvement = 0
while not improvement_found:
# Determine the number of rotations.
loops_with_no_improvement += 1
rotation_count = int(np.ceil(aqua_globals.random.uniform(0, m - 1)))
rotations += rotation_count
# Apply Grover's Algorithm to find values below the threshold.
if rotation_count > 0:
# TODO: Utilize Grover's incremental feature - requires changes to Grover.
grover = Grover(
oracle, state_preparation=a_operator, good_state=is_good_state
)
circuit = grover.construct_circuit(
rotation_count, measurement=measurement
)
else:
circuit = a_operator
# Get the next outcome.
outcome = self._measure(circuit)
k = int(outcome[0:n_key], 2)
v = outcome[n_key : n_key + n_value]
int_v = self._bin_to_int(v, n_value) + threshold
v = self._twos_complement(int_v, n_value)
logger.info("Outcome: %s", outcome)
logger.info("Value: %s = %s", v, int_v)
# If the value is an improvement, we update the iteration parameters (e.g. oracle).
if int_v < optimum_value:
optimum_key = k
optimum_value = int_v
logger.info("Current Optimum Key: %s", optimum_key)
logger.info("Current Optimum Value: %s", optimum_value)
if v.startswith("1"):
improvement_found = True
threshold = optimum_value
else:
# Using Durr and Hoyer method, increase m.
m = int(np.ceil(min(m * 8 / 7, 2 ** (n_key / 2))))
logger.info("No Improvement. M: %s", m)
# Check if we've already seen this value.
if k not in keys_measured:
keys_measured.append(k)
# Assume the optimal if any of the stop parameters are true.
if (
loops_with_no_improvement >= self._n_iterations
or len(keys_measured) == num_solutions
or rotations >= max_rotations
):
improvement_found = True
optimum_found = True
# Track the operation count.
operations = circuit.count_ops()
operation_count[iteration] = operations
iteration += 1
logger.info("Operation Count: %s\n", operations)
# If the constant is 0 and we didn't find a negative, the answer is likely 0.
if optimum_value >= 0 and orig_constant == 0:
optimum_key = 0
opt_x = np.array(
[1 if s == "1" else 0 for s in ("{0:%sb}" % n_key).format(optimum_key)]
)
# Compute function value
fval = problem_init.objective.evaluate(opt_x)
result = OptimizationResult(
x=opt_x,
fval=fval,
variables=problem_.variables,
status=OptimizationResultStatus.SUCCESS,
)
# cast binaries back to integers
result = self._interpret(result, self._converters)
return GroverOptimizationResult(
x=result.x,
fval=result.fval,
variables=result.variables,
operation_counts=operation_count,
n_input_qubits=n_key,
n_output_qubits=n_value,
intermediate_fval=fval,
threshold=threshold,
status=self._get_feasibility_status(problem, result.x),
)
|
https://github.com/Qiskit/qiskit-aqua/issues/1279
|
No classical registers in circuit "circuit9", counts will be empty.
Traceback (most recent call last):
File "scratch.py", line 101, in <module>
results = grover_optimizer.solve(qp)
File "/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py", line 218, in solve
outcome = self._measure(circuit)
File "/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py", line 283, in _measure
freq[-1] = (freq[-1][0], 1.0 - sum(x[1] for x in freq[0:len(freq) - 1]))
IndexError: list index out of range
|
IndexError
|
def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]:
"""Gets probabilities from a given backend."""
# Execute job and filter results.
result = self.quantum_instance.execute(qc)
if self.quantum_instance.is_statevector:
state = np.round(result.get_statevector(qc), 5)
keys = [
bin(i)[2::].rjust(int(np.log2(len(state))), "0")[::-1]
for i in range(0, len(state))
]
probs = [np.round(abs(a) * abs(a), 5) for a in state]
hist = dict(zip(keys, probs))
else:
state = result.get_counts(qc)
shots = self.quantum_instance.run_config.shots
hist = {}
for key in state:
hist[key[::-1]] = state[key] / shots
hist = dict(filter(lambda p: p[1] > 0, hist.items()))
return hist
|
def _get_probs(self, qc: QuantumCircuit) -> Dict[str, float]:
"""Gets probabilities from a given backend."""
# Execute job and filter results.
result = self.quantum_instance.execute(qc)
if self.quantum_instance.is_statevector:
state = np.round(result.get_statevector(qc), 5)
keys = [
bin(i)[2::].rjust(int(np.log2(len(state))), "0")[::-1]
for i in range(0, len(state))
]
probs = [np.round(abs(a) * abs(a), 5) for a in state]
hist = dict(zip(keys, probs))
else:
state = result.get_counts(qc)
shots = self.quantum_instance.run_config.shots
hist = {}
for key in state:
hist[key] = state[key] / shots
hist = dict(filter(lambda p: p[1] > 0, hist.items()))
return hist
|
https://github.com/Qiskit/qiskit-aqua/issues/1279
|
No classical registers in circuit "circuit9", counts will be empty.
Traceback (most recent call last):
File "scratch.py", line 101, in <module>
results = grover_optimizer.solve(qp)
File "/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py", line 218, in solve
outcome = self._measure(circuit)
File "/home/will/miniconda3/envs/dev/lib/python3.8/site-packages/qiskit/optimization/algorithms/grover_optimizer.py", line 283, in _measure
freq[-1] = (freq[-1][0], 1.0 - sum(x[1] for x in freq[0:len(freq) - 1]))
IndexError: list index out of range
|
IndexError
|
def get_kernel_matrix(
quantum_instance, feature_map, x1_vec, x2_vec=None, enforce_psd=True
):
"""
Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted.
Notes:
When using `statevector_simulator`,
we only build the circuits for Psi(x1)|0> rather than
Psi(x2)^dagger Psi(x1)|0>, and then we perform the inner product classically.
That is, for `statevector_simulator`,
the total number of circuits will be O(N) rather than
O(N^2) for `qasm_simulator`.
Args:
quantum_instance (QuantumInstance): quantum backend with all settings
feature_map (FeatureMap): a feature map that maps data to feature space
x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data,
D is the feature dimension
x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data,
D is the feature dimension
enforce_psd (bool): enforces that the kernel matrix is positive semi-definite by setting
negative eigenvalues to zero. This is only applied in the symmetric
case, i.e., if `x2_vec == None`.
Returns:
numpy.ndarray: 2-D matrix, N1xN2
"""
if isinstance(feature_map, QuantumCircuit):
use_parameterized_circuits = True
else:
use_parameterized_circuits = feature_map.support_parameterized_circuit
if x2_vec is None:
is_symmetric = True
x2_vec = x1_vec
else:
is_symmetric = False
is_statevector_sim = quantum_instance.is_statevector
measurement = not is_statevector_sim
measurement_basis = "0" * feature_map.num_qubits
mat = np.ones((x1_vec.shape[0], x2_vec.shape[0]))
# get all indices
if is_symmetric:
mus, nus = np.triu_indices(x1_vec.shape[0], k=1) # remove diagonal term
else:
mus, nus = np.indices((x1_vec.shape[0], x2_vec.shape[0]))
mus = np.asarray(mus.flat)
nus = np.asarray(nus.flat)
if is_statevector_sim:
if is_symmetric:
to_be_computed_data = x1_vec
else:
to_be_computed_data = np.concatenate((x1_vec, x2_vec))
if use_parameterized_circuits:
# build parameterized circuits, it could be slower for building circuit
# but overall it should be faster since it only transpile one circuit
feature_map_params = ParameterVector("x", feature_map.feature_dimension)
parameterized_circuit = QSVM._construct_circuit(
(feature_map_params, feature_map_params),
feature_map,
measurement,
is_statevector_sim=is_statevector_sim,
)
parameterized_circuit = quantum_instance.transpile(parameterized_circuit)[0]
circuits = [
parameterized_circuit.assign_parameters({feature_map_params: x})
for x in to_be_computed_data
]
else:
# the second x is redundant
to_be_computed_data_pair = [(x, x) for x in to_be_computed_data]
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Building circuits:")
TextProgressBar(sys.stderr)
circuits = parallel_map(
QSVM._construct_circuit,
to_be_computed_data_pair,
task_args=(feature_map, measurement, is_statevector_sim),
num_processes=aqua_globals.num_processes,
)
results = quantum_instance.execute(
circuits, had_transpiled=use_parameterized_circuits
)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculating overlap:")
TextProgressBar(sys.stderr)
offset = 0 if is_symmetric else len(x1_vec)
matrix_elements = parallel_map(
QSVM._compute_overlap,
list(zip(mus, nus + offset)),
task_args=(results, is_statevector_sim, measurement_basis),
num_processes=aqua_globals.num_processes,
)
for i, j, value in zip(mus, nus, matrix_elements):
mat[i, j] = value
if is_symmetric:
mat[j, i] = mat[i, j]
else:
for idx in range(0, len(mus), QSVM.BATCH_SIZE):
to_be_computed_data_pair = []
to_be_computed_index = []
for sub_idx in range(idx, min(idx + QSVM.BATCH_SIZE, len(mus))):
i = mus[sub_idx]
j = nus[sub_idx]
x1 = x1_vec[i]
x2 = x2_vec[j]
if not np.all(x1 == x2):
to_be_computed_data_pair.append((x1, x2))
to_be_computed_index.append((i, j))
if use_parameterized_circuits:
# build parameterized circuits, it could be slower for building circuit
# but overall it should be faster since it only transpile one circuit
feature_map_params_x = ParameterVector(
"x", feature_map.feature_dimension
)
feature_map_params_y = ParameterVector(
"y", feature_map.feature_dimension
)
parameterized_circuit = QSVM._construct_circuit(
(feature_map_params_x, feature_map_params_y),
feature_map,
measurement,
is_statevector_sim=is_statevector_sim,
)
parameterized_circuit = quantum_instance.transpile(
parameterized_circuit
)[0]
circuits = [
parameterized_circuit.assign_parameters(
{feature_map_params_x: x, feature_map_params_y: y}
)
for x, y in to_be_computed_data_pair
]
else:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Building circuits:")
TextProgressBar(sys.stderr)
circuits = parallel_map(
QSVM._construct_circuit,
to_be_computed_data_pair,
task_args=(feature_map, measurement),
num_processes=aqua_globals.num_processes,
)
results = quantum_instance.execute(
circuits, had_transpiled=use_parameterized_circuits
)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculating overlap:")
TextProgressBar(sys.stderr)
matrix_elements = parallel_map(
QSVM._compute_overlap,
range(len(circuits)),
task_args=(results, is_statevector_sim, measurement_basis),
num_processes=aqua_globals.num_processes,
)
for (i, j), value in zip(to_be_computed_index, matrix_elements):
mat[i, j] = value
if is_symmetric:
mat[j, i] = mat[i, j]
if enforce_psd and is_symmetric and not is_statevector_sim:
# Find the closest positive semi-definite approximation to kernel matrix, in case it is
# symmetric. The (symmetric) matrix should always be positive semi-definite by
# construction, but this can be violated in case of noise, such as sampling noise, thus,
# the adjustment is only done if NOT using the statevector simulation.
D, U = np.linalg.eig(mat)
mat = U @ np.diag(np.maximum(0, D)) @ U.transpose()
return mat
|
def get_kernel_matrix(quantum_instance, feature_map, x1_vec, x2_vec=None):
"""
Construct kernel matrix, if x2_vec is None, self-innerproduct is conducted.
Notes:
When using `statevector_simulator`,
we only build the circuits for Psi(x1)|0> rather than
Psi(x2)^dagger Psi(x1)|0>, and then we perform the inner product classically.
That is, for `statevector_simulator`,
the total number of circuits will be O(N) rather than
O(N^2) for `qasm_simulator`.
Args:
quantum_instance (QuantumInstance): quantum backend with all settings
feature_map (FeatureMap): a feature map that maps data to feature space
x1_vec (numpy.ndarray): data points, 2-D array, N1xD, where N1 is the number of data,
D is the feature dimension
x2_vec (numpy.ndarray): data points, 2-D array, N2xD, where N2 is the number of data,
D is the feature dimension
Returns:
numpy.ndarray: 2-D matrix, N1xN2
"""
if isinstance(feature_map, QuantumCircuit):
use_parameterized_circuits = True
else:
use_parameterized_circuits = feature_map.support_parameterized_circuit
if x2_vec is None:
is_symmetric = True
x2_vec = x1_vec
else:
is_symmetric = False
is_statevector_sim = quantum_instance.is_statevector
measurement = not is_statevector_sim
measurement_basis = "0" * feature_map.num_qubits
mat = np.ones((x1_vec.shape[0], x2_vec.shape[0]))
# get all indices
if is_symmetric:
mus, nus = np.triu_indices(x1_vec.shape[0], k=1) # remove diagonal term
else:
mus, nus = np.indices((x1_vec.shape[0], x2_vec.shape[0]))
mus = np.asarray(mus.flat)
nus = np.asarray(nus.flat)
if is_statevector_sim:
if is_symmetric:
to_be_computed_data = x1_vec
else:
to_be_computed_data = np.concatenate((x1_vec, x2_vec))
if use_parameterized_circuits:
# build parameterized circuits, it could be slower for building circuit
# but overall it should be faster since it only transpile one circuit
feature_map_params = ParameterVector("x", feature_map.feature_dimension)
parameterized_circuit = QSVM._construct_circuit(
(feature_map_params, feature_map_params),
feature_map,
measurement,
is_statevector_sim=is_statevector_sim,
)
parameterized_circuit = quantum_instance.transpile(parameterized_circuit)[0]
circuits = [
parameterized_circuit.assign_parameters({feature_map_params: x})
for x in to_be_computed_data
]
else:
# the second x is redundant
to_be_computed_data_pair = [(x, x) for x in to_be_computed_data]
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Building circuits:")
TextProgressBar(sys.stderr)
circuits = parallel_map(
QSVM._construct_circuit,
to_be_computed_data_pair,
task_args=(feature_map, measurement, is_statevector_sim),
num_processes=aqua_globals.num_processes,
)
results = quantum_instance.execute(
circuits, had_transpiled=use_parameterized_circuits
)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculating overlap:")
TextProgressBar(sys.stderr)
offset = 0 if is_symmetric else len(x1_vec)
matrix_elements = parallel_map(
QSVM._compute_overlap,
list(zip(mus, nus + offset)),
task_args=(results, is_statevector_sim, measurement_basis),
num_processes=aqua_globals.num_processes,
)
for i, j, value in zip(mus, nus, matrix_elements):
mat[i, j] = value
if is_symmetric:
mat[j, i] = mat[i, j]
else:
for idx in range(0, len(mus), QSVM.BATCH_SIZE):
to_be_computed_data_pair = []
to_be_computed_index = []
for sub_idx in range(idx, min(idx + QSVM.BATCH_SIZE, len(mus))):
i = mus[sub_idx]
j = nus[sub_idx]
x1 = x1_vec[i]
x2 = x2_vec[j]
if not np.all(x1 == x2):
to_be_computed_data_pair.append((x1, x2))
to_be_computed_index.append((i, j))
if use_parameterized_circuits:
# build parameterized circuits, it could be slower for building circuit
# but overall it should be faster since it only transpile one circuit
feature_map_params_x = ParameterVector(
"x", feature_map.feature_dimension
)
feature_map_params_y = ParameterVector(
"y", feature_map.feature_dimension
)
parameterized_circuit = QSVM._construct_circuit(
(feature_map_params_x, feature_map_params_y),
feature_map,
measurement,
is_statevector_sim=is_statevector_sim,
)
parameterized_circuit = quantum_instance.transpile(
parameterized_circuit
)[0]
circuits = [
parameterized_circuit.assign_parameters(
{feature_map_params_x: x, feature_map_params_y: y}
)
for x, y in to_be_computed_data_pair
]
else:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Building circuits:")
TextProgressBar(sys.stderr)
circuits = parallel_map(
QSVM._construct_circuit,
to_be_computed_data_pair,
task_args=(feature_map, measurement),
num_processes=aqua_globals.num_processes,
)
results = quantum_instance.execute(
circuits, had_transpiled=use_parameterized_circuits
)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculating overlap:")
TextProgressBar(sys.stderr)
matrix_elements = parallel_map(
QSVM._compute_overlap,
range(len(circuits)),
task_args=(results, is_statevector_sim, measurement_basis),
num_processes=aqua_globals.num_processes,
)
for (i, j), value in zip(to_be_computed_index, matrix_elements):
mat[i, j] = value
if is_symmetric:
mat[j, i] = mat[i, j]
return mat
|
https://github.com/Qiskit/qiskit-aqua/issues/1106
|
---------------------------------------------------------------------------
DQCPError Traceback (most recent call last)
in
7 quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)
8
----> 9 result = qsvm.run(quantum_instance)
10
11 print("testing success ratio: {}".format(result['testing_accuracy']))
~/github/qiskit/aqua/qiskit/aqua/algorithms/quantum_algorithm.py in run(self, quantum_instance, **kwargs)
68 self.quantum_instance = quantum_instance
69
---> 70 return self._run()
71
72 @abstractmethod
~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/qsvm.py in _run(self)
456
457 def _run(self):
--> 458 return self.instance.run()
459
460 @property
~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py in run(self)
134 def run(self):
135 """Put the train, test, predict together."""
--> 136 self.train(self._qalgo.training_dataset[0], self._qalgo.training_dataset[1])
137 if self._qalgo.test_dataset is not None:
138 self.test(self._qalgo.test_dataset[0], self._qalgo.test_dataset[1])
~/github/qiskit/aqua/qiskit/aqua/algorithms/classifiers/qsvm/_qsvm_binary.py in train(self, data, labels)
81 labels = labels * 2 - 1 # map label from 0 --> -1 and 1 --> 1
82 labels = labels.astype(np.float)
---> 83 [alpha, b, support] = optimize_svm(kernel_matrix, labels, scaling=scaling)
84 support_index = np.where(support)
85 alphas = alpha[support_index]
~/github/qiskit/aqua/qiskit/aqua/utils/qp_solver.py in optimize_svm(kernel_matrix, y, scaling, maxiter, show_progress, max_iters)
88 [G@x <= h,
89 A@x == b])
---> 90 prob.solve(verbose=show_progress, qcp=True)
91 result = np.asarray(x.value).reshape((n, 1))
92 alpha = result * scaling
~/envs/qopt/lib/python3.7/site-packages/cvxpy/problems/problem.py in solve(self, *args, **kwargs)
393 else:
394 solve_func = Problem._solve
--> 395 return solve_func(self, *args, **kwargs)
396
397 @classmethod
~/envs/qopt/lib/python3.7/site-packages/cvxpy/problems/problem.py in _solve(self, solver, warm_start, verbose, gp, qcp, requires_grad, enforce_dpp, **kwargs)
731 if qcp and not self.is_dcp():
732 if not self.is_dqcp():
--> 733 raise error.DQCPError("The problem is not DQCP.")
734 reductions = [dqcp2dcp.Dqcp2Dcp()]
735 if type(self.objective) == Maximize:
DQCPError: The problem is not DQCP.
|
DQCPError
|
def optimize(
self,
num_vars,
objective_function,
gradient_function=None,
variable_bounds=None,
initial_point=None,
):
num_procs = multiprocessing.cpu_count() - 1
num_procs = (
num_procs
if self._max_processes is None
else min(num_procs, self._max_processes)
)
num_procs = num_procs if num_procs >= 0 else 0
if platform.system() == "Darwin":
# Changed in version 3.8: On macOS, the spawn start method is now the
# default. The fork start method should be considered unsafe as it can
# lead to crashes.
# However P_BFGS doesn't support spawn, so we revert to single process.
major, minor, _ = platform.python_version_tuple()
if major > "3" or (major == "3" and minor >= "8"):
num_procs = 0
logger.warning(
"For MacOS, python >= 3.8, using only current process. "
"Multiple core use not supported."
)
elif platform.system() == "Windows":
num_procs = 0
logger.warning(
"For Windows, using only current process. Multiple core use not supported."
)
queue = multiprocessing.Queue()
# bounds for additional initial points in case bounds has any None values
threshold = 2 * np.pi
if variable_bounds is None:
variable_bounds = [(-threshold, threshold)] * num_vars
low = [(l if l is not None else -threshold) for (l, u) in variable_bounds]
high = [(u if u is not None else threshold) for (l, u) in variable_bounds]
def optimize_runner(_queue, _i_pt): # Multi-process sampling
_sol, _opt, _nfev = self._optimize(
num_vars, objective_function, gradient_function, variable_bounds, _i_pt
)
_queue.put((_sol, _opt, _nfev))
# Start off as many other processes running the optimize (can be 0)
processes = []
for _ in range(num_procs):
i_pt = aqua_globals.random.uniform(low, high) # Another random point in bounds
p = multiprocessing.Process(target=optimize_runner, args=(queue, i_pt))
processes.append(p)
p.start()
# While the one _optimize in this process below runs the other processes will
# be running to. This one runs
# with the supplied initial point. The process ones have their own random one
sol, opt, nfev = self._optimize(
num_vars, objective_function, gradient_function, variable_bounds, initial_point
)
for p in processes:
# For each other process we wait now for it to finish and see if it has
# a better result than above
p.join()
p_sol, p_opt, p_nfev = queue.get()
if p_opt < opt:
sol, opt = p_sol, p_opt
nfev += p_nfev
return sol, opt, nfev
|
def optimize(
self,
num_vars,
objective_function,
gradient_function=None,
variable_bounds=None,
initial_point=None,
):
num_procs = multiprocessing.cpu_count() - 1
num_procs = (
num_procs
if self._max_processes is None
else min(num_procs, self._max_processes)
)
num_procs = num_procs if num_procs >= 0 else 0
if platform.system() == "Windows":
num_procs = 0
logger.warning(
"Using only current process. Multiple core use not supported in Windows"
)
queue = multiprocessing.Queue()
# bounds for additional initial points in case bounds has any None values
threshold = 2 * np.pi
if variable_bounds is None:
variable_bounds = [(-threshold, threshold)] * num_vars
low = [(l if l is not None else -threshold) for (l, u) in variable_bounds]
high = [(u if u is not None else threshold) for (l, u) in variable_bounds]
def optimize_runner(_queue, _i_pt): # Multi-process sampling
_sol, _opt, _nfev = self._optimize(
num_vars, objective_function, gradient_function, variable_bounds, _i_pt
)
_queue.put((_sol, _opt, _nfev))
# Start off as many other processes running the optimize (can be 0)
processes = []
for _ in range(num_procs):
i_pt = aqua_globals.random.uniform(low, high) # Another random point in bounds
p = multiprocessing.Process(target=optimize_runner, args=(queue, i_pt))
processes.append(p)
p.start()
# While the one _optimize in this process below runs the other processes will
# be running to. This one runs
# with the supplied initial point. The process ones have their own random one
sol, opt, nfev = self._optimize(
num_vars, objective_function, gradient_function, variable_bounds, initial_point
)
for p in processes:
# For each other process we wait now for it to finish and see if it has
# a better result than above
p.join()
p_sol, p_opt, p_nfev = queue.get()
if p_opt < opt:
sol, opt = p_sol, p_opt
nfev += p_nfev
return sol, opt, nfev
|
https://github.com/Qiskit/qiskit-aqua/issues/1109
|
Traceback (most recent call last):
File "<pathToAqua>/qiskit-aqua/test/aqua/test_optimizers.py", line 68, in test_p_bfgs
res = self._optimize(optimizer)
File "<pathToAqua>/qiskit-aqua/test/aqua/test_optimizers.py", line 37, in _optimize
res = optimizer.optimize(len(x_0), rosen, initial_point=x_0)
File "<pathToAqua>/qiskit-aqua/qiskit/aqua/components/optimizers/p_bfgs.py", line 120, in optimize
p.start()
File "<pathToMultiprocessing>/multiprocessing/process.py", line 121, in start
self._popen = self._Popen(self)
File "<pathToMultiprocessing>/multiprocessing/context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "<pathToMultiprocessing>/multiprocessing/context.py", line 283, in _Popen
return Popen(process_obj)
File "<pathToMultiprocessing>/multiprocessing/popen_spawn_posix.py", line 32, in __init__
super().__init__(process_obj)
File "<pathToMultiprocessing>/multiprocessing/popen_fork.py", line 19, in __init__
self._launch(process_obj)
File "<pathToMultiprocessing>/multiprocessing/popen_spawn_posix.py", line 47, in _launch
reduction.dump(process_obj, fp)
File "<pathToMultiprocessing>/multiprocessing/reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'P_BFGS.optimize.<locals>.optimize_runner'
|
AttributeError
|
def solve(self, problem: QuadraticProgram) -> MinimumEigenOptimizerResult:
"""Tries to solves the given problem using the optimizer.
Runs the optimizer to try to solve the optimization problem.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
QiskitOptimizationError: If problem not compatible.
"""
# check compatibility and raise exception if incompatible
msg = self.get_compatibility_msg(problem)
if len(msg) > 0:
raise QiskitOptimizationError("Incompatible problem: {}".format(msg))
# convert problem to QUBO
qubo_converter = QuadraticProgramToQubo()
problem_ = qubo_converter.encode(problem)
# construct operator and offset
operator_converter = QuadraticProgramToIsing()
operator, offset = operator_converter.encode(problem_)
# only try to solve non-empty Ising Hamiltonians
if operator.num_qubits > 0:
# approximate ground state of operator using min eigen solver
eigen_results = self._min_eigen_solver.compute_minimum_eigenvalue(operator)
# analyze results
samples = eigenvector_to_solutions(eigen_results.eigenstate, operator)
samples = [
(res[0], problem_.objective.sense.value * (res[1] + offset), res[2])
for res in samples
]
samples.sort(key=lambda x: problem_.objective.sense.value * x[1])
x = samples[0][0]
fval = samples[0][1]
# if Hamiltonian is empty, then the objective function is constant to the offset
else:
x = [0] * problem_.get_num_binary_vars()
fval = offset
x_str = "0" * problem_.get_num_binary_vars()
samples = [(x_str, offset, 1.0)]
# translate result back to integers
opt_res = MinimumEigenOptimizerResult(x, fval, samples, qubo_converter)
opt_res = qubo_converter.decode(opt_res)
# translate results back to original problem
return opt_res
|
def solve(self, problem: QuadraticProgram) -> MinimumEigenOptimizerResult:
"""Tries to solves the given problem using the optimizer.
Runs the optimizer to try to solve the optimization problem.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
QiskitOptimizationError: If problem not compatible.
"""
# check compatibility and raise exception if incompatible
msg = self.get_compatibility_msg(problem)
if len(msg) > 0:
raise QiskitOptimizationError("Incompatible problem: {}".format(msg))
# convert problem to QUBO
qubo_converter = QuadraticProgramToQubo()
problem_ = qubo_converter.encode(problem)
# construct operator and offset
operator_converter = QuadraticProgramToIsing()
operator, offset = operator_converter.encode(problem_)
# approximate ground state of operator using min eigen solver
eigen_results = self._min_eigen_solver.compute_minimum_eigenvalue(operator)
# analyze results
samples = eigenvector_to_solutions(eigen_results.eigenstate, operator)
samples = [
(res[0], problem_.objective.sense.value * (res[1] + offset), res[2])
for res in samples
]
samples.sort(key=lambda x: problem_.objective.sense.value * x[1])
# translate result back to integers
opt_res = MinimumEigenOptimizerResult(
samples[0][0], samples[0][1], samples, qubo_converter
)
opt_res = qubo_converter.decode(opt_res)
# translate results back to original problem
return opt_res
|
https://github.com/Qiskit/qiskit-aqua/issues/969
|
------------------
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result)
------------------
---------------------------------------------------------------------------
QiskitOptimizationError Traceback (most recent call last)
<ipython-input-11-6852684b0186> in <module>
----> 1 rqaoa_result = rqaoa.solve(qubo)
2 print(rqaoa_result)
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem)
171
172 # 2. replace x_i by -x_j
--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)})
174 if problem_.status == QuadraticProgram.Status.INFEASIBLE:
175 raise QiskitOptimizationError('Infeasible due to variable substitution')
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables)
856 - Coefficient of variable substitution is zero.
857 """
--> 858 return SubstituteVariables().substitute_variables(self, constants, variables)
859
860
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables)
901 self._src = src
902 self._dst = QuadraticProgram(src.name)
--> 903 self._subs_dict(constants, variables)
904 results = [
905 self._variables(),
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables)
960 j_2 = self._src.get_variable(j).name
961 if i_2 == j_2:
--> 962 raise QiskitOptimizationError(
963 'Cannot substitute the same variable: {} <- {} {}'.format(i, j, v))
964 if i_2 in subs:
QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'
QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'
|
QiskitOptimizationError
|
def solve(self, problem: QuadraticProgram) -> OptimizationResult:
"""Tries to solve the given problem using the recursive optimizer.
Runs the optimizer to try to solve the optimization problem.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
QiskitOptimizationError: Incompatible problem.
QiskitOptimizationError: Infeasible due to variable substitution
"""
# check compatibility and raise exception if incompatible
msg = self.get_compatibility_msg(problem)
if len(msg) > 0:
raise QiskitOptimizationError("Incompatible problem: {}".format(msg))
# convert problem to QUBO, this implicitly checks if the problem is compatible
qubo_converter = QuadraticProgramToQubo()
problem_ = qubo_converter.encode(problem)
problem_ref = deepcopy(problem_)
# run recursive optimization until the resulting problem is small enough
replacements = {}
while problem_.get_num_vars() > self._min_num_vars:
# solve current problem with optimizer
result = self._min_eigen_optimizer.solve(problem_)
# analyze results to get strongest correlation
correlations = result.get_correlations()
i, j = self._find_strongest_correlation(correlations)
x_i = problem_.variables[i].name
x_j = problem_.variables[j].name
if correlations[i, j] > 0:
# set x_i = x_j
problem_ = problem_.substitute_variables(variables={i: (j, 1)})
if problem_.status == QuadraticProgram.Status.INFEASIBLE:
raise QiskitOptimizationError("Infeasible due to variable substitution")
replacements[x_i] = (x_j, 1)
else:
# set x_i = 1 - x_j, this is done in two steps:
# 1. set x_i = 1 + x_i
# 2. set x_i = -x_j
# 1a. get additional offset
constant = problem_.objective.constant
constant += problem_.objective.linear[i]
constant += problem_.objective.quadratic[i, i]
problem_.objective.constant = constant
# 1b. get additional linear part
for k in range(problem_.get_num_vars()):
coeff = problem_.objective.linear[k]
if k == i:
coeff += 2 * problem_.objective.quadratic[i, k]
else:
coeff += problem_.objective.quadratic[i, k]
# set new coefficient if not too small
if np.abs(coeff) > 1e-10:
problem_.objective.linear[k] = coeff
else:
problem_.objective.linear[k] = 0
# 2. replace x_i by -x_j
problem_ = problem_.substitute_variables(variables={i: (j, -1)})
if problem_.status == QuadraticProgram.Status.INFEASIBLE:
raise QiskitOptimizationError("Infeasible due to variable substitution")
replacements[x_i] = (x_j, -1)
# solve remaining problem
result = self._min_num_vars_optimizer.solve(problem_)
# unroll replacements
var_values = {}
for i, x in enumerate(problem_.variables):
var_values[x.name] = result.x[i]
def find_value(x, replacements, var_values):
if x in var_values:
# if value for variable is known, return it
return var_values[x]
elif x in replacements:
# get replacement for variable
(y, sgn) = replacements[x]
# find details for replacing variable
value = find_value(y, replacements, var_values)
# construct, set, and return new value
var_values[x] = value if sgn == 1 else 1 - value
return var_values[x]
else:
raise QiskitOptimizationError("Invalid values!")
# loop over all variables to set their values
for x_i in problem_ref.variables:
if x_i.name not in var_values:
find_value(x_i.name, replacements, var_values)
# construct result
x = [var_values[x_aux.name] for x_aux in problem_ref.variables]
fval = result.fval
results = OptimizationResult(x, fval, (replacements, qubo_converter))
results = qubo_converter.decode(results)
return results
|
def solve(self, problem: QuadraticProgram) -> OptimizationResult:
"""Tries to solve the given problem using the recursive optimizer.
Runs the optimizer to try to solve the optimization problem.
Args:
problem: The problem to be solved.
Returns:
The result of the optimizer applied to the problem.
Raises:
QiskitOptimizationError: Incompatible problem.
QiskitOptimizationError: Infeasible due to variable substitution
"""
# check compatibility and raise exception if incompatible
msg = self.get_compatibility_msg(problem)
if len(msg) > 0:
raise QiskitOptimizationError("Incompatible problem: {}".format(msg))
# convert problem to QUBO, this implicitly checks if the problem is compatible
qubo_converter = QuadraticProgramToQubo()
problem_ = qubo_converter.encode(problem)
problem_ref = deepcopy(problem_)
# run recursive optimization until the resulting problem is small enough
replacements = {}
while problem_.get_num_vars() > self._min_num_vars:
# solve current problem with optimizer
result = self._min_eigen_optimizer.solve(problem_)
# analyze results to get strongest correlation
correlations = result.get_correlations()
i, j = self._find_strongest_correlation(correlations)
x_i = problem_.variables[i].name
x_j = problem_.variables[j].name
if correlations[i, j] > 0:
# set x_i = x_j
problem_.substitute_variables()
problem_ = problem_.substitute_variables(variables={i: (j, 1)})
if problem_.status == QuadraticProgram.Status.INFEASIBLE:
raise QiskitOptimizationError("Infeasible due to variable substitution")
replacements[x_i] = (x_j, 1)
else:
# set x_i = 1 - x_j, this is done in two steps:
# 1. set x_i = 1 + x_i
# 2. set x_i = -x_j
# 1a. get additional offset
constant = problem_.objective.constant
constant += problem_.objective.quadratic[i, i]
constant += problem_.objective.linear[i]
problem_.objective.constant = constant
# 1b. get additional linear part
for k in range(problem_.get_num_vars()):
coeff = problem_.objective.quadratic[i, k]
if np.abs(coeff) > 1e-10:
coeff += problem_.objective.linear[k]
problem_.objective.linear[k] = coeff
# 2. replace x_i by -x_j
problem_ = problem_.substitute_variables(variables={i: (j, -1)})
if problem_.status == QuadraticProgram.Status.INFEASIBLE:
raise QiskitOptimizationError("Infeasible due to variable substitution")
replacements[x_i] = (x_j, -1)
# solve remaining problem
result = self._min_num_vars_optimizer.solve(problem_)
# unroll replacements
var_values = {}
for i, x in enumerate(problem_.variables):
var_values[x.name] = result.x[i]
def find_value(x, replacements, var_values):
if x in var_values:
# if value for variable is known, return it
return var_values[x]
elif x in replacements:
# get replacement for variable
(y, sgn) = replacements[x]
# find details for replacing variable
value = find_value(y, replacements, var_values)
# construct, set, and return new value
var_values[x] = value if sgn == 1 else 1 - value
return var_values[x]
else:
raise QiskitOptimizationError("Invalid values!")
# loop over all variables to set their values
for x_i in problem_ref.variables:
if x_i.name not in var_values:
find_value(x_i.name, replacements, var_values)
# construct result
x = [var_values[x_aux.name] for x_aux in problem_ref.variables]
fval = result.fval
results = OptimizationResult(x, fval, (replacements, qubo_converter))
results = qubo_converter.decode(results)
return results
|
https://github.com/Qiskit/qiskit-aqua/issues/969
|
------------------
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result)
------------------
---------------------------------------------------------------------------
QiskitOptimizationError Traceback (most recent call last)
<ipython-input-11-6852684b0186> in <module>
----> 1 rqaoa_result = rqaoa.solve(qubo)
2 print(rqaoa_result)
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem)
171
172 # 2. replace x_i by -x_j
--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)})
174 if problem_.status == QuadraticProgram.Status.INFEASIBLE:
175 raise QiskitOptimizationError('Infeasible due to variable substitution')
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables)
856 - Coefficient of variable substitution is zero.
857 """
--> 858 return SubstituteVariables().substitute_variables(self, constants, variables)
859
860
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables)
901 self._src = src
902 self._dst = QuadraticProgram(src.name)
--> 903 self._subs_dict(constants, variables)
904 results = [
905 self._variables(),
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables)
960 j_2 = self._src.get_variable(j).name
961 if i_2 == j_2:
--> 962 raise QiskitOptimizationError(
963 'Cannot substitute the same variable: {} <- {} {}'.format(i, j, v))
964 if i_2 in subs:
QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'
QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'
|
QiskitOptimizationError
|
def _find_strongest_correlation(self, correlations):
# get absolute values and set diagonal to -1 to make sure maximum is always on off-diagonal
abs_correlations = np.abs(correlations)
for i in range(len(correlations)):
abs_correlations[i, i] = -1
# get index of maximum (by construction on off-diagonal)
m_max = np.argmax(abs_correlations.flatten())
# translate back to indices
i = int(m_max // len(correlations))
j = int(m_max - i * len(correlations))
return (i, j)
|
def _find_strongest_correlation(self, correlations):
m_max = np.argmax(np.abs(correlations.flatten()))
i = int(m_max // len(correlations))
j = int(m_max - i * len(correlations))
return (i, j)
|
https://github.com/Qiskit/qiskit-aqua/issues/969
|
------------------
rqaoa_result = rqaoa.solve(qubo)
print(rqaoa_result)
------------------
---------------------------------------------------------------------------
QiskitOptimizationError Traceback (most recent call last)
<ipython-input-11-6852684b0186> in <module>
----> 1 rqaoa_result = rqaoa.solve(qubo)
2 print(rqaoa_result)
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py in solve(self, problem)
171
172 # 2. replace x_i by -x_j
--> 173 problem_ = problem_.substitute_variables(variables={i: (j, -1)})
174 if problem_.status == QuadraticProgram.Status.INFEASIBLE:
175 raise QiskitOptimizationError('Infeasible due to variable substitution')
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, constants, variables)
856 - Coefficient of variable substitution is zero.
857 """
--> 858 return SubstituteVariables().substitute_variables(self, constants, variables)
859
860
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in substitute_variables(self, src, constants, variables)
901 self._src = src
902 self._dst = QuadraticProgram(src.name)
--> 903 self._subs_dict(constants, variables)
904 results = [
905 self._variables(),
/tmp/docs_build/lib/python3.8/site-packages/qiskit/optimization/problems/quadratic_program.py in _subs_dict(self, constants, variables)
960 j_2 = self._src.get_variable(j).name
961 if i_2 == j_2:
--> 962 raise QiskitOptimizationError(
963 'Cannot substitute the same variable: {} <- {} {}'.format(i, j, v))
964 if i_2 in subs:
QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'
QiskitOptimizationError: 'Cannot substitute the same variable: 0 <- 0 -1'
|
QiskitOptimizationError
|
def _livereload(host, port, config, builder, site_dir):
# We are importing here for anyone that has issues with livereload. Even if
# this fails, the --no-livereload alternative should still work.
_init_asyncio_patch()
from livereload import Server
import livereload.handlers
class LiveReloadServer(Server):
def get_web_handlers(self, script):
handlers = super(LiveReloadServer, self).get_web_handlers(script)
# replace livereload handler
return [
(
handlers[0][0],
_get_handler(site_dir, livereload.handlers.StaticFileHandler),
handlers[0][2],
)
]
server = LiveReloadServer()
# Watch the documentation files, the config file and the theme files.
server.watch(config["docs_dir"], builder)
server.watch(config["config_file_path"], builder)
for d in config["theme"].dirs:
server.watch(d, builder)
# Run `serve` plugin events.
server = config["plugins"].run_event("serve", server, config=config)
server.serve(root=site_dir, host=host, port=port, restart_delay=0)
|
def _livereload(host, port, config, builder, site_dir):
# We are importing here for anyone that has issues with livereload. Even if
# this fails, the --no-livereload alternative should still work.
from livereload import Server
import livereload.handlers
class LiveReloadServer(Server):
def get_web_handlers(self, script):
handlers = super(LiveReloadServer, self).get_web_handlers(script)
# replace livereload handler
return [
(
handlers[0][0],
_get_handler(site_dir, livereload.handlers.StaticFileHandler),
handlers[0][2],
)
]
server = LiveReloadServer()
# Watch the documentation files, the config file and the theme files.
server.watch(config["docs_dir"], builder)
server.watch(config["config_file_path"], builder)
for d in config["theme"].dirs:
server.watch(d, builder)
# Run `serve` plugin events.
server = config["plugins"].run_event("serve", server, config=config)
server.serve(root=site_dir, host=host, port=port, restart_delay=0)
|
https://github.com/mkdocs/mkdocs/issues/1885
|
C:\dev\testing
λ mkdocs serve
INFO - Building documentation...
INFO - Cleaning site directory
[I 191017 14:49:48 server:296] Serving on http://127.0.0.1:8000
Traceback (most recent call last):
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\runpy.py", line 192, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aleksandr.skobelev\AppData\Local\Programs\Python\Python38\Scripts\mkdocs.exe\__main__.py", line 9, in <module>
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 717, in main
rv = self.invoke(ctx)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\mkdocs\__main__.py", line 128, in serve_command
serve.serve(
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\mkdocs\commands\serve.py", line 124, in serve
_livereload(host, port, config, builder, site_dir)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\mkdocs\commands\serve.py", line 58, in _livereload
server.serve(root=site_dir, host=host, port=port, restart_delay=0)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\livereload\server.py", line 298, in serve
self.application(
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\livereload\server.py", line 253, in application
app.listen(port, address=host)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\web.py", line 2112, in listen
server.listen(port, address)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\tcpserver.py", line 152, in listen
self.add_sockets(sockets)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
self._handlers[sock.fileno()] = add_accept_handler(
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
io_loop.add_handler(sock, accept_handler, IOLoop.READ)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\platform\asyncio.py", line 99, in add_handler
self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\asyncio\events.py", line 501, in add_reader
raise NotImplementedError
NotImplementedError
|
NotImplementedError
|
def _static_server(host, port, site_dir):
# Importing here to seperate the code paths from the --livereload
# alternative.
_init_asyncio_patch()
from tornado import ioloop
from tornado import web
application = web.Application(
[
(
r"/(.*)",
_get_handler(site_dir, web.StaticFileHandler),
{"path": site_dir, "default_filename": "index.html"},
),
]
)
application.listen(port=port, address=host)
log.info("Running at: http://%s:%s/", host, port)
log.info("Hold ctrl+c to quit.")
try:
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
log.info("Stopping server...")
|
def _static_server(host, port, site_dir):
# Importing here to seperate the code paths from the --livereload
# alternative.
from tornado import ioloop
from tornado import web
application = web.Application(
[
(
r"/(.*)",
_get_handler(site_dir, web.StaticFileHandler),
{"path": site_dir, "default_filename": "index.html"},
),
]
)
application.listen(port=port, address=host)
log.info("Running at: http://%s:%s/", host, port)
log.info("Hold ctrl+c to quit.")
try:
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
log.info("Stopping server...")
|
https://github.com/mkdocs/mkdocs/issues/1885
|
C:\dev\testing
λ mkdocs serve
INFO - Building documentation...
INFO - Cleaning site directory
[I 191017 14:49:48 server:296] Serving on http://127.0.0.1:8000
Traceback (most recent call last):
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\runpy.py", line 192, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\aleksandr.skobelev\AppData\Local\Programs\Python\Python38\Scripts\mkdocs.exe\__main__.py", line 9, in <module>
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 717, in main
rv = self.invoke(ctx)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\mkdocs\__main__.py", line 128, in serve_command
serve.serve(
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\mkdocs\commands\serve.py", line 124, in serve
_livereload(host, port, config, builder, site_dir)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\mkdocs\commands\serve.py", line 58, in _livereload
server.serve(root=site_dir, host=host, port=port, restart_delay=0)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\livereload\server.py", line 298, in serve
self.application(
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\livereload\server.py", line 253, in application
app.listen(port, address=host)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\web.py", line 2112, in listen
server.listen(port, address)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\tcpserver.py", line 152, in listen
self.add_sockets(sockets)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\tcpserver.py", line 165, in add_sockets
self._handlers[sock.fileno()] = add_accept_handler(
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\netutil.py", line 279, in add_accept_handler
io_loop.add_handler(sock, accept_handler, IOLoop.READ)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\site-packages\tornado\platform\asyncio.py", line 99, in add_handler
self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ)
File "c:\users\aleksandr.skobelev\appdata\local\programs\python\python38\lib\asyncio\events.py", line 501, in add_reader
raise NotImplementedError
NotImplementedError
|
NotImplementedError
|
def serve(
config_file=None,
dev_addr=None,
strict=None,
theme=None,
theme_dir=None,
livereload="livereload",
):
"""
Start the MkDocs development server
By default it will serve the documentation on http://localhost:8000/ and
it will rebuild the documentation and refresh the page automatically
whenever a file is edited.
"""
# Create a temporary build directory, and set some options to serve it
# PY2 returns a byte string by default. The Unicode prefix ensures a Unicode
# string is returned. And it makes MkDocs temp dirs easier to identify.
site_dir = tempfile.mkdtemp(prefix="mkdocs_")
def builder():
log.info("Building documentation...")
config = load_config(
config_file=config_file,
dev_addr=dev_addr,
strict=strict,
theme=theme,
theme_dir=theme_dir,
site_dir=site_dir,
)
# Override a few config settings after validation
config["site_url"] = "http://{0}/".format(config["dev_addr"])
live_server = livereload in ["dirty", "livereload"]
dirty = livereload == "dirty"
build(config, live_server=live_server, dirty=dirty)
return config
try:
# Perform the initial build
config = builder()
host, port = config["dev_addr"]
if livereload in ["livereload", "dirty"]:
_livereload(host, port, config, builder, site_dir)
else:
_static_server(host, port, site_dir)
finally:
shutil.rmtree(site_dir)
|
def serve(
config_file=None,
dev_addr=None,
strict=None,
theme=None,
theme_dir=None,
livereload="livereload",
):
"""
Start the MkDocs development server
By default it will serve the documentation on http://localhost:8000/ and
it will rebuild the documentation and refresh the page automatically
whenever a file is edited.
"""
# Create a temporary build directory, and set some options to serve it
tempdir = tempfile.mkdtemp()
def builder():
log.info("Building documentation...")
config = load_config(
config_file=config_file,
dev_addr=dev_addr,
strict=strict,
theme=theme,
theme_dir=theme_dir,
)
# Override a few config settings after validation
config["site_dir"] = tempdir
config["site_url"] = "http://{0}/".format(config["dev_addr"])
live_server = livereload in ["dirty", "livereload"]
dirty = livereload == "dirty"
build(config, live_server=live_server, dirty=dirty)
return config
try:
# Perform the initial build
config = builder()
host, port = config["dev_addr"]
if livereload in ["livereload", "dirty"]:
_livereload(host, port, config, builder, tempdir)
else:
_static_server(host, port, tempdir)
finally:
shutil.rmtree(tempdir)
|
https://github.com/mkdocs/mkdocs/issues/1516
|
Exception in callback <bound method type.poll_tasks of <class 'livereload.handlers.LiveReloadHandler'>>
Traceback (most recent call last):
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/tornado/ioloop.py", line 1209, in _run
return self.callback()
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/handlers.py", line 67, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/watcher.py", line 73, in examine
func and func()
File "/Users/waylan/Code/mkdocs/mkdocs/commands/serve.py", line 112, in builder
build(config, live_server=live_server, dirty=dirty)
File "/Users/waylan/Code/mkdocs/mkdocs/commands/build.py", line 265, in build
utils.clean_directory(config['site_dir'])
File "/Users/waylan/Code/mkdocs/mkdocs/utils/__init__.py", line 144, in clean_directory
if entry.startswith('.'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 1: ordinal not in range(128)
|
UnicodeDecodeError
|
def builder():
log.info("Building documentation...")
config = load_config(
config_file=config_file,
dev_addr=dev_addr,
strict=strict,
theme=theme,
theme_dir=theme_dir,
site_dir=site_dir,
)
# Override a few config settings after validation
config["site_url"] = "http://{0}/".format(config["dev_addr"])
live_server = livereload in ["dirty", "livereload"]
dirty = livereload == "dirty"
build(config, live_server=live_server, dirty=dirty)
return config
|
def builder():
log.info("Building documentation...")
config = load_config(
config_file=config_file,
dev_addr=dev_addr,
strict=strict,
theme=theme,
theme_dir=theme_dir,
)
# Override a few config settings after validation
config["site_dir"] = tempdir
config["site_url"] = "http://{0}/".format(config["dev_addr"])
live_server = livereload in ["dirty", "livereload"]
dirty = livereload == "dirty"
build(config, live_server=live_server, dirty=dirty)
return config
|
https://github.com/mkdocs/mkdocs/issues/1516
|
Exception in callback <bound method type.poll_tasks of <class 'livereload.handlers.LiveReloadHandler'>>
Traceback (most recent call last):
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/tornado/ioloop.py", line 1209, in _run
return self.callback()
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/handlers.py", line 67, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/Users/waylan/VirtualEnvs/mkdocs/lib/python2.7/site-packages/livereload/watcher.py", line 73, in examine
func and func()
File "/Users/waylan/Code/mkdocs/mkdocs/commands/serve.py", line 112, in builder
build(config, live_server=live_server, dirty=dirty)
File "/Users/waylan/Code/mkdocs/mkdocs/commands/build.py", line 265, in build
utils.clean_directory(config['site_dir'])
File "/Users/waylan/Code/mkdocs/mkdocs/utils/__init__.py", line 144, in clean_directory
if entry.startswith('.'):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 1: ordinal not in range(128)
|
UnicodeDecodeError
|
def copy_file(source_path, output_path):
"""
Copy source_path to output_path, making sure any parent directories exist.
The output_path may be a directory.
"""
output_dir = os.path.dirname(output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
if os.path.isdir(output_path):
output_path = os.path.join(output_path, os.path.basename(source_path))
shutil.copyfile(source_path, output_path)
|
def copy_file(source_path, output_path):
"""
Copy source_path to output_path, making sure any parent directories exist.
"""
output_dir = os.path.dirname(output_path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
shutil.copy(source_path, output_path)
|
https://github.com/mkdocs/mkdocs/issues/1292
|
$ mkdocs build
WARNING - Config value: 'extra_javascript'. Warning: The following files have been automatically included in the documentation build and will be added to the HTML: highlight/theme/js/highlight.pack.js. This behavior is deprecated. In version 1.0 and later they will need to be explicitly listed in the 'extra_javascript' config setting.
INFO - Cleaning site directory
INFO - Building documentation to directory: <project path>/build/site
Traceback (most recent call last):
File "/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/bin/.mkdocs-wrapped", line 12, in <module>
sys.exit(cli())
File "/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/nix/store/cjhms7xja78pbh5gnh9ii7hlxizq2iy7-python2.7-click-6.7/lib/python2.7/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/__main__.py", line 156, in build_command
), dirty=not clean)
File "/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/commands/build.py", line 373, in build
theme_dir, config['site_dir'], exclude=['*.py', '*.pyc', '*.html'], dirty=dirty
File "/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/utils/__init__.py", line 175, in copy_media_files
copy_file(source_path, output_path)
File "/nix/store/2zkwsgan90gl63pqnq01vrdrpf11fm1m-mkdocs-0.16.3/lib/python2.7/site-packages/mkdocs/utils/__init__.py", line 110, in copy_file
shutil.copy(source_path, output_path)
File "/nix/store/w8zld7z4gq4b36z0szgrh6yv5zi30915-python-2.7.13/lib/python2.7/shutil.py", line 119, in copy
copyfile(src, dst)
File "/nix/store/w8zld7z4gq4b36z0szgrh6yv5zi30915-python-2.7.13/lib/python2.7/shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: u'<project path>/build/site/js/highlight.pack.js'
$ ls -l build/site/js/
total 396
-r--r--r-- 1 kirelagin staff 300764 Sep 26 16:03 highlight.pack.js
-r--r--r-- 1 kirelagin staff 84245 Sep 26 16:03 jquery-2.1.1.min.js
-r--r--r-- 1 kirelagin staff 11084 Sep 26 16:03 modernizr-2.8.3.min.js
-r--r--r-- 1 kirelagin staff 2676 Sep 26 16:03 theme.js
$ ls -ld build/site/js/
drwxr-xr-x 6 kirelagin staff 204 Sep 26 16:03 build/site/js/
|
IOError
|
def _livereload(host, port, config, builder, site_dir):
# We are importing here for anyone that has issues with livereload. Even if
# this fails, the --no-livereload alternative should still work.
from livereload import Server
import livereload.handlers
class LiveReloadServer(Server):
def get_web_handlers(self, script):
handlers = super(LiveReloadServer, self).get_web_handlers(script)
# replace livereload handler
return [
(
handlers[0][0],
_get_handler(site_dir, livereload.handlers.StaticFileHandler),
handlers[0][2],
)
]
server = LiveReloadServer()
# Watch the documentation files, the config file and the theme files.
server.watch(config["docs_dir"], builder)
server.watch(config["config_file_path"], builder)
for d in config["theme_dir"]:
server.watch(d, builder)
server.serve(root=site_dir, host=host, port=port, restart_delay=0)
|
def _livereload(host, port, config, builder, site_dir):
# We are importing here for anyone that has issues with livereload. Even if
# this fails, the --no-livereload alternative should still work.
from livereload import Server
import livereload.handlers
class LiveReloadServer(Server):
def get_web_handlers(self, script):
handlers = super(LiveReloadServer, self).get_web_handlers(script)
# replace livereload handler
return [
(
handlers[0][0],
_get_handler(site_dir, livereload.handlers.StaticFileHandler),
handlers[0][2],
)
]
server = LiveReloadServer()
# Watch the documentation files, the config file and the theme files.
server.watch(config["docs_dir"], builder)
server.watch(config["config_file_path"], builder)
for d in config["theme_dir"]:
server.watch(d, builder)
server.serve(root=site_dir, host=host, port=int(port), restart_delay=0)
|
https://github.com/mkdocs/mkdocs/issues/1237
|
INFO - Building documentation...
INFO - Cleaning site directory
Traceback (most recent call last):
File "/home/sybren/.virtualenvs/flamenco/bin/mkdocs", line 11, in <module>
sys.exit(cli())
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py", line 127, in serve_command
livereload=livereload
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 116, in serve
_livereload(host, port, config, builder, tempdir)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 55, in _livereload
server.serve(root=site_dir, host=host, port=int(port), restart_delay=0)
ValueError: invalid literal for int() with base 10: ':0]:8081'
|
ValueError
|
def _static_server(host, port, site_dir):
# Importing here to seperate the code paths from the --livereload
# alternative.
from tornado import ioloop
from tornado import web
application = web.Application(
[
(
r"/(.*)",
_get_handler(site_dir, web.StaticFileHandler),
{"path": site_dir, "default_filename": "index.html"},
),
]
)
application.listen(port=port, address=host)
log.info("Running at: http://%s:%s/", host, port)
log.info("Hold ctrl+c to quit.")
try:
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
log.info("Stopping server...")
|
def _static_server(host, port, site_dir):
# Importing here to seperate the code paths from the --livereload
# alternative.
from tornado import ioloop
from tornado import web
application = web.Application(
[
(
r"/(.*)",
_get_handler(site_dir, web.StaticFileHandler),
{"path": site_dir, "default_filename": "index.html"},
),
]
)
application.listen(port=int(port), address=host)
log.info("Running at: http://%s:%s/", host, port)
log.info("Hold ctrl+c to quit.")
try:
ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
log.info("Stopping server...")
|
https://github.com/mkdocs/mkdocs/issues/1237
|
INFO - Building documentation...
INFO - Cleaning site directory
Traceback (most recent call last):
File "/home/sybren/.virtualenvs/flamenco/bin/mkdocs", line 11, in <module>
sys.exit(cli())
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py", line 127, in serve_command
livereload=livereload
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 116, in serve
_livereload(host, port, config, builder, tempdir)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 55, in _livereload
server.serve(root=site_dir, host=host, port=int(port), restart_delay=0)
ValueError: invalid literal for int() with base 10: ':0]:8081'
|
ValueError
|
def serve(
config_file=None,
dev_addr=None,
strict=None,
theme=None,
theme_dir=None,
livereload="livereload",
):
"""
Start the MkDocs development server
By default it will serve the documentation on http://localhost:8000/ and
it will rebuild the documentation and refresh the page automatically
whenever a file is edited.
"""
# Create a temporary build directory, and set some options to serve it
tempdir = tempfile.mkdtemp()
def builder():
log.info("Building documentation...")
config = load_config(
config_file=config_file,
dev_addr=dev_addr,
strict=strict,
theme=theme,
theme_dir=theme_dir,
)
config["site_dir"] = tempdir
live_server = livereload in ["dirty", "livereload"]
dirty = livereload == "dirty"
build(config, live_server=live_server, dirty=dirty)
return config
try:
# Perform the initial build
config = builder()
host, port = config["dev_addr"]
if livereload in ["livereload", "dirty"]:
_livereload(host, port, config, builder, tempdir)
else:
_static_server(host, port, tempdir)
finally:
shutil.rmtree(tempdir)
|
def serve(
config_file=None,
dev_addr=None,
strict=None,
theme=None,
theme_dir=None,
livereload="livereload",
):
"""
Start the MkDocs development server
By default it will serve the documentation on http://localhost:8000/ and
it will rebuild the documentation and refresh the page automatically
whenever a file is edited.
"""
# Create a temporary build directory, and set some options to serve it
tempdir = tempfile.mkdtemp()
def builder():
log.info("Building documentation...")
config = load_config(
config_file=config_file,
dev_addr=dev_addr,
strict=strict,
theme=theme,
theme_dir=theme_dir,
)
config["site_dir"] = tempdir
live_server = livereload in ["dirty", "livereload"]
dirty = livereload == "dirty"
build(config, live_server=live_server, dirty=dirty)
return config
# Perform the initial build
config = builder()
host, port = config["dev_addr"].split(":", 1)
try:
if livereload in ["livereload", "dirty"]:
_livereload(host, port, config, builder, tempdir)
else:
_static_server(host, port, tempdir)
finally:
shutil.rmtree(tempdir)
|
https://github.com/mkdocs/mkdocs/issues/1237
|
INFO - Building documentation...
INFO - Cleaning site directory
Traceback (most recent call last):
File "/home/sybren/.virtualenvs/flamenco/bin/mkdocs", line 11, in <module>
sys.exit(cli())
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 722, in __call__
return self.main(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/click/core.py", line 535, in invoke
return callback(*args, **kwargs)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/__main__.py", line 127, in serve_command
livereload=livereload
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 116, in serve
_livereload(host, port, config, builder, tempdir)
File "/home/sybren/.virtualenvs/flamenco/lib/python3.6/site-packages/mkdocs/commands/serve.py", line 55, in _livereload
server.serve(root=site_dir, host=host, port=int(port), restart_delay=0)
ValueError: invalid literal for int() with base 10: ':0]:8081'
|
ValueError
|
def try_rebase(remote, branch):
cmd = ["git", "rev-list", "--max-count=1", "%s/%s" % (remote, branch)]
p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
(rev, _) = p.communicate()
if p.wait() != 0:
return True
cmd = ["git", "update-ref", "refs/heads/%s" % branch, dec(rev.strip())]
if sp.call(cmd) != 0:
return False
return True
|
def try_rebase(remote, branch):
cmd = ["git", "rev-list", "--max-count=1", "%s/%s" % (remote, branch)]
p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
(rev, _) = p.communicate()
if p.wait() != 0:
return True
cmd = ["git", "update-ref", "refs/heads/%s" % branch, rev.strip()]
if sp.call(cmd) != 0:
return False
return True
|
https://github.com/mkdocs/mkdocs/issues/722
|
c:\docs>mkdocs gh-deploy --clean
INFO - Cleaning site directory
INFO - Building documentation to directory: c:\docs\site
INFO - Copying 'c:\docs\site' to 'gh-pages' branch and pushing to GitHub.
Traceback (most recent call last):
File "C:\Python34\lib\runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "C:\Python34\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "c:\Python34\Scripts\mkdocs.exe\__main__.py", line 9, in <module>
File "C:\Python34\lib\site-packages\click\core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "C:\Python34\lib\site-packages\click\core.py", line 644, in main
rv = self.invoke(ctx)
File "C:\Python34\lib\site-packages\click\core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Python34\lib\site-packages\click\core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Python34\lib\site-packages\click\core.py", line 464, in invoke
return callback(*args, **kwargs)
File "C:\Python34\lib\site-packages\mkdocs\cli.py", line 186, in gh_deploy_command
gh_deploy.gh_deploy(config, message=message)
File "C:\Python34\lib\site-packages\mkdocs\gh_deploy.py", line 69, in gh_deploy
remote_branch)
File "C:\Python34\lib\site-packages\mkdocs\utils\ghp_import.py", line 163, in ghp_import
if not try_rebase(remote, branch):
File "C:\Python34\lib\site-packages\mkdocs\utils\ghp_import.py", line 78, in try_rebase
if sp.call(cmd) != 0:
File "C:\Python34\lib\subprocess.py", line 537, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Python34\lib\subprocess.py", line 859, in __init__
restore_signals, start_new_session)
File "C:\Python34\lib\subprocess.py", line 1086, in _execute_child
args = list2cmdline(args)
File "C:\Python34\lib\subprocess.py", line 663, in list2cmdline
needquote = (" " in arg) or ("\t" in arg) or not arg
TypeError: 'str' does not support the buffer interface
|
TypeError
|
def path_to_url(path):
"""Convert a system path to a URL."""
if os.path.sep == "/":
return path
if sys.version_info < (3, 0):
path = path.encode("utf8")
return pathname2url(path)
|
def path_to_url(path):
"""Convert a system path to a URL."""
if os.path.sep == "/":
return path
return pathname2url(path)
|
https://github.com/mkdocs/mkdocs/issues/833
|
C:\Python27\lib\urllib.py:1303: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
return ''.join(map(quoter, s))
ERROR - Error building page Allgemeines\1. Richtlinien.md
Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "C:\Python27\Scripts\mkdocs.exe\__main__.py", line 9, in <module>
File "C:\Python27\lib\site-packages\click\core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "C:\Python27\lib\site-packages\click\core.py", line 696, in main
rv = self.invoke(ctx)
File "C:\Python27\lib\site-packages\click\core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Python27\lib\site-packages\click\core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Python27\lib\site-packages\click\core.py", line 534, in invoke
return callback(*args, **kwargs)
File "C:\Python27\lib\site-packages\mkdocs\__main__.py", line 115, in serve_command
livereload=livereload,
File "C:\Python27\lib\site-packages\mkdocs\commands\serve.py", line 78, in serve
config = builder()
File "C:\Python27\lib\site-packages\mkdocs\commands\serve.py", line 74, in builder
build(config, live_server=True, clean_site_dir=True)
File "C:\Python27\lib\site-packages\mkdocs\commands\build.py", line 289, in build
build_pages(config)
File "C:\Python27\lib\site-packages\mkdocs\commands\build.py", line 249, in build_pages
dump_json)
File "C:\Python27\lib\site-packages\mkdocs\commands\build.py", line 184, in _build_page
output_content = template.render(context)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\material\base.html", line 102, in top-level template code
{% include "drawer.html" %}
File "C:\Python27\lib\site-packages\material\drawer.html", line 41, in top-level template code
{% include "nav.html" %}
File "C:\Python27\lib\site-packages\material\nav.html", line 6, in top-level template code
{% include 'nav.html' %}
File "C:\Python27\lib\site-packages\material\nav.html", line 12, in top-level template code
<a class="{% if nav_item.active %}current{% endif %}" title="{{ nav_item.title }}" href="{{ nav_item.url }}">
File "C:\Python27\lib\site-packages\jinja2\environment.py", line 408, in getattr
return getattr(obj, attribute)
File "C:\Python27\lib\site-packages\mkdocs\nav.py", line 153, in url
return self.url_context.make_relative(self.abs_url)
File "C:\Python27\lib\site-packages\mkdocs\nav.py", line 105, in make_relative
return utils.path_to_url(relative_path)
File "C:\Python27\lib\site-packages\mkdocs\utils\__init__.py", line 324, in path_to_url
return pathname2url(path)
File "C:\Python27\lib\nturl2path.py", line 54, in pathname2url
return urllib.quote('/'.join(components))
File "C:\Python27\lib\urllib.py", line 1303, in quote
return ''.join(map(quoter, s))
KeyError: u'\xdc'
|
KeyError
|
def walk_docs_dir(self, docs_dir):
if self.file_match is None:
raise StopIteration
for dirpath, dirs, filenames in os.walk(docs_dir):
dirs.sort()
for filename in sorted(filenames):
fullpath = os.path.join(dirpath, filename)
# Some editors (namely Emacs) will create temporary symlinks
# for internal magic. We can just ignore these files.
if os.path.islink(fullpath):
if not os.path.exists(os.readlink(fullpath)):
continue
relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
if self.file_match(relpath):
yield relpath
|
def walk_docs_dir(self, docs_dir):
if self.file_match is None:
raise StopIteration
for dirpath, dirs, filenames in os.walk(docs_dir):
dirs.sort()
for filename in sorted(filenames):
fullpath = os.path.join(dirpath, filename)
relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
if self.file_match(relpath):
yield relpath
|
https://github.com/mkdocs/mkdocs/issues/639
|
INFO - Building documentation...
ERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md
ERROR - Error building page .#index.md
[E 150617 17:22:21 ioloop:612] Exception in callback (3, <function null_wrapper at 0x7fc883190500>)
Traceback (most recent call last):
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py", line 866, in start
handler_func(fd_obj, events)
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1604, in handle_read
self.process_events()
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1321, in process_events
self._default_proc_fun(revent)
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 152, in inotify_event
self.callback()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py", line 65, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 72, in examine
func and func()
File "/usr/lib/python2.7/dist-packages/mkdocs/serve.py", line 74, in builder
build(config, live_server=True)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 299, in build
build_pages(config)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 259, in build_pages
dump_json)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 171, in _build_page
input_content = io.open(input_path, 'r', encoding='utf-8').read()
IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md'
|
IOError
|
def walk_docs_dir(self, docs_dir):
if self.file_match is None:
raise StopIteration
for dirpath, dirs, filenames in os.walk(docs_dir):
dirs.sort()
for filename in sorted(filenames):
fullpath = os.path.join(dirpath, filename)
# Some editors (namely Emacs) will create temporary symlinks
# for internal magic. We can just ignore these files.
if os.path.islink(fullpath):
fp = os.path.join(dirpath, os.readlink(fullpath))
if not os.path.exists(fp):
continue
relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
if self.file_match(relpath):
yield relpath
|
def walk_docs_dir(self, docs_dir):
if self.file_match is None:
raise StopIteration
for dirpath, dirs, filenames in os.walk(docs_dir):
dirs.sort()
for filename in sorted(filenames):
fullpath = os.path.join(dirpath, filename)
# Some editors (namely Emacs) will create temporary symlinks
# for internal magic. We can just ignore these files.
if os.path.islink(fullpath):
if not os.path.exists(os.readlink(fullpath)):
continue
relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
if self.file_match(relpath):
yield relpath
|
https://github.com/mkdocs/mkdocs/issues/639
|
INFO - Building documentation...
ERROR - file not found: /home/paulproteus/projects/sandstorm/docs/.#index.md
ERROR - Error building page .#index.md
[E 150617 17:22:21 ioloop:612] Exception in callback (3, <function null_wrapper at 0x7fc883190500>)
Traceback (most recent call last):
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/ioloop.py", line 866, in start
handler_func(fd_obj, events)
File "/home/paulproteus/.local/lib/python2.7/site-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1604, in handle_read
self.process_events()
File "/usr/lib/python2.7/dist-packages/pyinotify.py", line 1321, in process_events
self._default_proc_fun(revent)
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 152, in inotify_event
self.callback()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/handlers.py", line 65, in poll_tasks
filepath, delay = cls.watcher.examine()
File "/home/paulproteus/.local/lib/python2.7/site-packages/livereload/watcher.py", line 72, in examine
func and func()
File "/usr/lib/python2.7/dist-packages/mkdocs/serve.py", line 74, in builder
build(config, live_server=True)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 299, in build
build_pages(config)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 259, in build_pages
dump_json)
File "/usr/lib/python2.7/dist-packages/mkdocs/build.py", line 171, in _build_page
input_content = io.open(input_path, 'r', encoding='utf-8').read()
IOError: [Errno 2] No such file or directory: '/home/paulproteus/projects/sandstorm/docs/.#index.md'
|
IOError
|
def __init__(self, file_match=None, **kwargs):
super(Extras, self).__init__(**kwargs)
self.file_match = file_match
|
def __init__(self, file_match, **kwargs):
super(Extras, self).__init__(**kwargs)
self.file_match = file_match
|
https://github.com/mkdocs/mkdocs/issues/616
|
Traceback (most recent call last):
File "/srv/mkdocs_head/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.14.0.dev', 'console_scripts', 'mkdocs')()
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/home/zmousm/mkdocs/mkdocs/cli.py", line 134, in build_command
), clean_site_dir=clean)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 299, in build
build_pages(config)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 252, in build_pages
build_extra_templates(config['extra_templates'], config, site_navigation)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 230, in build_extra_templates
output_content = template.render(context)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 44, in top-level template code
TypeError: no loader for this environment specified
|
TypeError
|
def walk_docs_dir(self, docs_dir):
if self.file_match is None:
raise StopIteration
for dirpath, _, filenames in os.walk(docs_dir):
for filename in sorted(filenames):
fullpath = os.path.join(dirpath, filename)
relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
if self.file_match(relpath):
yield relpath
|
def walk_docs_dir(self, docs_dir):
for dirpath, _, filenames in os.walk(docs_dir):
for filename in sorted(filenames):
fullpath = os.path.join(dirpath, filename)
relpath = os.path.normpath(os.path.relpath(fullpath, docs_dir))
if self.file_match(relpath):
yield relpath
|
https://github.com/mkdocs/mkdocs/issues/616
|
Traceback (most recent call last):
File "/srv/mkdocs_head/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.14.0.dev', 'console_scripts', 'mkdocs')()
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/home/zmousm/mkdocs/mkdocs/cli.py", line 134, in build_command
), clean_site_dir=clean)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 299, in build
build_pages(config)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 252, in build_pages
build_extra_templates(config['extra_templates'], config, site_navigation)
File "/home/zmousm/mkdocs/mkdocs/build.py", line 230, in build_extra_templates
output_content = template.render(context)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/srv/mkdocs_head/local/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 44, in top-level template code
TypeError: no loader for this environment specified
|
TypeError
|
def run_validation(self, value):
if not isinstance(value, list):
raise ValidationError("Expected a list, got {0}".format(type(value)))
if len(value) == 0:
return
# TODO: Remove in 1.0
config_types = set(type(l) for l in value)
if config_types.issubset(
set(
[
six.text_type,
dict,
]
)
):
return value
if config_types.issubset(
set(
[
six.text_type,
list,
]
)
):
return legacy.pages_compat_shim(value)
raise ValidationError(
"Invalid pages config. {0} {1}".format(
config_types,
set(
[
six.text_type,
dict,
]
),
)
)
|
def run_validation(self, value):
if not isinstance(value, list):
raise ValidationError("Expected a list, got {0}".format(type(value)))
if len(value) == 0:
return
# TODO: Remove in 1.0
config_types = set(type(l) for l in value)
if config_types.issubset(
set(
[
str,
dict,
]
)
):
return value
if config_types.issubset(
set(
[
str,
list,
]
)
):
return legacy.pages_compat_shim(value)
raise ValidationError("Invalid pages config.")
|
https://github.com/mkdocs/mkdocs/issues/532
|
Traceback (most recent call last):
File "/Users/maemual/Workspace/mkdocs/env/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.13.0.dev0', 'console_scripts', 'mkdocs')()
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/Users/maemual/Workspace/mkdocs/mkdocs/cli.py", line 83, in serve_command
livereload=livereload,
File "/Users/maemual/Workspace/mkdocs/mkdocs/serve.py", line 77, in serve
config = builder()
File "/Users/maemual/Workspace/mkdocs/mkdocs/serve.py", line 73, in builder
build(config, live_server=True)
File "/Users/maemual/Workspace/mkdocs/mkdocs/build.py", line 306, in build
build_pages(config)
File "/Users/maemual/Workspace/mkdocs/mkdocs/build.py", line 252, in build_pages
if not build_template('search.html', env, config, site_navigation):
File "/Users/maemual/Workspace/mkdocs/mkdocs/build.py", line 166, in build_template
output_content = template.render(context)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/maemual/Workspace/mkdocs/mkdocs/themes/readthedocs/search.html", line 1, in top-level template code
{% extends "base.html" %}
File "/Users/maemual/Workspace/mkdocs/mkdocs/themes/readthedocs/base.html", line 62, in top-level template code
<li>{% include "toc.html" %}<li>
File "/Users/maemual/Workspace/mkdocs/mkdocs/themes/readthedocs/toc.html", line 3, in top-level template code
<li><span>{{ nav_item.title }}</span></li>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
|
UnicodeDecodeError
|
def _follow(config_line, url_context, use_dir_urls, header=None, title=None):
if isinstance(config_line, six.string_types):
path = os.path.normpath(config_line)
page = _path_to_page(path, title, url_context, use_dir_urls)
if header:
page.ancestors = [header]
header.children.append(page)
yield page
raise StopIteration
elif not isinstance(config_line, dict):
msg = (
"Line in 'page' config is of type {0}, dict or string expected. Config: {1}"
).format(type(config_line), config_line)
raise exceptions.ConfigurationError(msg)
if len(config_line) > 1:
raise exceptions.ConfigurationError(
"Page configs should be in the format 'name: markdown.md'. The "
"config contains an invalid entry: {0}".format(config_line)
)
elif len(config_line) == 0:
log.warning("Ignoring empty line in the pages config.")
raise StopIteration
next_cat_or_title, subpages_or_path = next(iter(config_line.items()))
if isinstance(subpages_or_path, six.string_types):
path = subpages_or_path
for sub in _follow(
path, url_context, use_dir_urls, header=header, title=next_cat_or_title
):
yield sub
raise StopIteration
elif not isinstance(subpages_or_path, list):
msg = (
"Line in 'page' config is of type {0}, list or string "
"expected for sub pages. Config: {1}"
).format(type(config_line), config_line)
raise exceptions.ConfigurationError(msg)
next_header = Header(title=next_cat_or_title, children=[])
if header:
next_header.ancestors = [header]
header.children.append(next_header)
yield next_header
subpages = subpages_or_path
for subpage in subpages:
for sub in _follow(subpage, url_context, use_dir_urls, next_header):
yield sub
|
def _follow(config_line, url_context, use_dir_urls, header=None, title=None):
if isinstance(config_line, str):
path = os.path.normpath(config_line)
page = _path_to_page(path, title, url_context, use_dir_urls)
if header:
page.ancestors = [header]
header.children.append(page)
yield page
raise StopIteration
elif not isinstance(config_line, dict):
msg = (
"Line in 'page' config is of type {0}, dict or string expected. Config: {1}"
).format(type(config_line), config_line)
raise exceptions.ConfigurationError(msg)
if len(config_line) > 1:
raise exceptions.ConfigurationError(
"Page configs should be in the format 'name: markdown.md'. The "
"config contains an invalid entry: {0}".format(config_line)
)
elif len(config_line) == 0:
log.warning("Ignoring empty line in the pages config.")
raise StopIteration
next_cat_or_title, subpages_or_path = next(iter(config_line.items()))
if isinstance(subpages_or_path, str):
path = subpages_or_path
for sub in _follow(
path, url_context, use_dir_urls, header=header, title=next_cat_or_title
):
yield sub
raise StopIteration
elif not isinstance(subpages_or_path, list):
msg = (
"Line in 'page' config is of type {0}, list or string "
"expected for sub pages. Config: {1}"
).format(type(config_line), config_line)
raise exceptions.ConfigurationError(msg)
next_header = Header(title=next_cat_or_title, children=[])
if header:
next_header.ancestors = [header]
header.children.append(next_header)
yield next_header
subpages = subpages_or_path
for subpage in subpages:
for sub in _follow(subpage, url_context, use_dir_urls, next_header):
yield sub
|
https://github.com/mkdocs/mkdocs/issues/532
|
Traceback (most recent call last):
File "/Users/maemual/Workspace/mkdocs/env/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.13.0.dev0', 'console_scripts', 'mkdocs')()
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 664, in __call__
return self.main(*args, **kwargs)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 644, in main
rv = self.invoke(ctx)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 991, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 837, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/click/core.py", line 464, in invoke
return callback(*args, **kwargs)
File "/Users/maemual/Workspace/mkdocs/mkdocs/cli.py", line 83, in serve_command
livereload=livereload,
File "/Users/maemual/Workspace/mkdocs/mkdocs/serve.py", line 77, in serve
config = builder()
File "/Users/maemual/Workspace/mkdocs/mkdocs/serve.py", line 73, in builder
build(config, live_server=True)
File "/Users/maemual/Workspace/mkdocs/mkdocs/build.py", line 306, in build
build_pages(config)
File "/Users/maemual/Workspace/mkdocs/mkdocs/build.py", line 252, in build_pages
if not build_template('search.html', env, config, site_navigation):
File "/Users/maemual/Workspace/mkdocs/mkdocs/build.py", line 166, in build_template
output_content = template.render(context)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/Users/maemual/Workspace/mkdocs/env/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/maemual/Workspace/mkdocs/mkdocs/themes/readthedocs/search.html", line 1, in top-level template code
{% extends "base.html" %}
File "/Users/maemual/Workspace/mkdocs/mkdocs/themes/readthedocs/base.html", line 62, in top-level template code
<li>{% include "toc.html" %}<li>
File "/Users/maemual/Workspace/mkdocs/mkdocs/themes/readthedocs/toc.html", line 3, in top-level template code
<li><span>{{ nav_item.title }}</span></li>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
|
UnicodeDecodeError
|
def _generate_site_navigation(pages_config, url_context, use_directory_urls=True):
"""
Returns a list of Page and Header instances that represent the
top level site navigation.
"""
nav_items = []
pages = []
previous = None
for config_line in pages_config:
if isinstance(config_line, str):
path = os.path.normpath(config_line)
title, child_title = None, None
elif len(config_line) in (1, 2, 3):
# Pad any items that don't exist with 'None'
padded_config = (list(config_line) + [None, None])[:3]
path, title, child_title = padded_config
path = os.path.normpath(path)
else:
msg = (
"Line in 'page' config contained %d items. "
"Expected 1, 2 or 3 strings." % len(config_line)
)
raise exceptions.ConfigurationError(msg)
# If both the title and child_title are None, then we
# have just been given a path. If that path contains a /
# then lets automatically nest it.
if title is None and child_title is None and os.path.sep in path:
filename = path.split(os.path.sep)[-1]
child_title = filename_to_title(filename)
if title is None:
filename = path.split(os.path.sep)[0]
title = filename_to_title(filename)
# If we don't have a child title but the other title is the same, we
# should be within a section and the child title needs to be inferred
# from the filename.
if (
len(nav_items)
and title == nav_items[-1].title == title
and child_title is None
):
filename = path.split(os.path.sep)[-1]
child_title = filename_to_title(filename)
url = utils.get_url_path(path, use_directory_urls)
if not child_title:
# New top level page.
page = Page(title=title, url=url, path=path, url_context=url_context)
nav_items.append(page)
elif not nav_items or (nav_items[-1].title != title):
# New second level page.
page = Page(title=child_title, url=url, path=path, url_context=url_context)
header = Header(title=title, children=[page])
nav_items.append(header)
page.ancestors = [header]
else:
# Additional second level page.
page = Page(title=child_title, url=url, path=path, url_context=url_context)
header = nav_items[-1]
header.children.append(page)
page.ancestors = [header]
# Add in previous and next information.
if previous:
page.previous_page = previous
previous.next_page = page
previous = page
pages.append(page)
return (nav_items, pages)
|
def _generate_site_navigation(pages_config, url_context, use_directory_urls=True):
"""
Returns a list of Page and Header instances that represent the
top level site navigation.
"""
nav_items = []
pages = []
previous = None
for config_line in pages_config:
if isinstance(config_line, str):
path = os.path.normpath(config_line)
title, child_title = None, None
elif len(config_line) in (1, 2, 3):
# Pad any items that don't exist with 'None'
padded_config = (list(config_line) + [None, None])[:3]
path, title, child_title = padded_config
path = os.path.normpath(path)
else:
msg = (
"Line in 'page' config contained %d items. "
"Expected 1, 2 or 3 strings." % len(config_line)
)
raise exceptions.ConfigurationError(msg)
# If both the title and child_title are None, then we
# have just been given a path. If that path contains a /
# then lets automatically nest it.
if title is None and child_title is None and os.path.sep in path:
filename = path.split(os.path.sep)[-1]
child_title = filename_to_title(filename)
if title is None:
filename = path.split(os.path.sep)[0]
title = filename_to_title(filename)
url = utils.get_url_path(path, use_directory_urls)
if not child_title:
# New top level page.
page = Page(title=title, url=url, path=path, url_context=url_context)
nav_items.append(page)
elif not nav_items or (nav_items[-1].title != title):
# New second level page.
page = Page(title=child_title, url=url, path=path, url_context=url_context)
header = Header(title=title, children=[page])
nav_items.append(header)
page.ancestors = [header]
else:
# Additional second level page.
page = Page(title=child_title, url=url, path=path, url_context=url_context)
header = nav_items[-1]
header.children.append(page)
page.ancestors = [header]
# Add in previous and next information.
if previous:
page.previous_page = previous
previous.next_page = page
previous = page
pages.append(page)
return (nav_items, pages)
|
https://github.com/mkdocs/mkdocs/issues/461
|
$ mkdocs build
Building documentation to directory: site
Directory site contains stale files. Use --clean to remove them.
Traceback (most recent call last):
File "/home/dougalmatthews/.virtualenvs/mkdocs/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.12.1', 'console_scripts', 'mkdocs')()
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/main.py", line 77, in run_main
main(cmd, args=sys.argv[2:], options=dict(opts))
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/main.py", line 52, in main
build(config, clean_site_dir=clean_site_dir)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/build.py", line 252, in build
build_pages(config)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/build.py", line 209, in build_pages
site_navigation = nav.SiteNavigation(config['pages'], config['use_directory_urls'])
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/nav.py", line 37, in __init__
_generate_site_navigation(pages_config, self.url_context, use_directory_urls)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python2.7/site-packages/mkdocs/nav.py", line 243, in _generate_site_navigation
header.children.append(page)
AttributeError: 'Page' object has no attribute 'children'
|
AttributeError
|
def convert_markdown(
markdown_source, site_navigation=None, extensions=(), strict=False
):
"""
Convert the Markdown source file to HTML content, and additionally
return the parsed table of contents, and a dictionary of any metadata
that was specified in the Markdown file.
`extensions` is an optional sequence of Python Markdown extensions to add
to the default set.
"""
# Generate the HTML from the markdown source
builtin_extensions = ["meta", "toc", "tables", "fenced_code"]
mkdocs_extensions = [
RelativePathExtension(site_navigation, strict),
]
extensions = builtin_extensions + mkdocs_extensions + list(extensions)
md = markdown.Markdown(extensions=extensions)
html_content = md.convert(markdown_source)
# On completely blank markdown files, no Meta or tox properties are added
# to the generated document.
meta = getattr(md, "Meta", {})
toc_html = getattr(md, "toc", "")
# Post process the generated table of contents into a data structure
table_of_contents = toc.TableOfContents(toc_html)
return (html_content, table_of_contents, meta)
|
def convert_markdown(
markdown_source, site_navigation=None, extensions=(), strict=False
):
"""
Convert the Markdown source file to HTML content, and additionally
return the parsed table of contents, and a dictionary of any metadata
that was specified in the Markdown file.
`extensions` is an optional sequence of Python Markdown extensions to add
to the default set.
"""
# Generate the HTML from the markdown source
builtin_extensions = ["meta", "toc", "tables", "fenced_code"]
mkdocs_extensions = [
RelativePathExtension(site_navigation, strict),
]
extensions = builtin_extensions + mkdocs_extensions + list(extensions)
md = markdown.Markdown(extensions=extensions)
html_content = md.convert(markdown_source)
meta = md.Meta
toc_html = md.toc
# Post process the generated table of contents into a data structure
table_of_contents = toc.TableOfContents(toc_html)
return (html_content, table_of_contents, meta)
|
https://github.com/mkdocs/mkdocs/issues/368
|
$ mkdocs serve
Traceback (most recent call last):
File "/usr/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.11.1', 'console_scripts', 'mkdocs')()
File "/usr/lib/python3.4/site-packages/mkdocs-0.11.1-py3.4.egg/mkdocs/main.py", line 74, in run_main
main(cmd, args=sys.argv[2:], options=dict(opts))
File "/usr/lib/python3.4/site-packages/mkdocs-0.11.1-py3.4.egg/mkdocs/main.py", line 46, in main
serve(config, options=options)
File "/usr/lib/python3.4/site-packages/mkdocs-0.11.1-py3.4.egg/mkdocs/serve.py", line 85, in serve
build(config, live_server=True)
File "/usr/lib/python3.4/site-packages/mkdocs-0.11.1-py3.4.egg/mkdocs/build.py", line 223, in build
build_pages(config)
File "/usr/lib/python3.4/site-packages/mkdocs-0.11.1-py3.4.egg/mkdocs/build.py", line 155, in build_pages
build_404(config, env, site_navigation)
File "/usr/lib/python3.4/site-packages/mkdocs-0.11.1-py3.4.egg/mkdocs/build.py", line 142, in build_404
output_content = template.render(global_context)
File "/usr/lib/python3.4/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python3.4/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3.4/site-packages/jinja2/_compat.py", line 36, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3.4/site-packages/mkdocs-0.11.1-py3.4.egg/mkdocs/themes/mkdocs/404.html", line 1, in <module>
{% extends "base.html" %}
File "mybootstrap/base.html", line 48, in <module>
<div class="col-md-9" role="main">{% include "content.html" %}</div>
File "mybootstrap/content.html", line 1, in <module>
{% if meta.source %}
File "/usr/lib/python3.4/site-packages/jinja2/environment.py", line 397, in getattr
return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'meta' is undefined
|
jinja2.exceptions.UndefinedError
|
def serve(config, options=None):
"""
Start the devserver, and rebuild the docs whenever any changes take effect.
"""
# Create a temporary build directory, and set some options to serve it
tempdir = tempfile.mkdtemp()
options["site_dir"] = tempdir
# Only use user-friendly URLs when running the live server
options["use_directory_urls"] = True
# Perform the initial build
config = load_config(options=options)
build(config, live_server=True)
# Note: We pass any command-line options through so that we
# can re-apply them if the config file is reloaded.
event_handler = BuildEventHandler(options)
config_event_handler = ConfigEventHandler(options)
# We could have used `Observer()`, which can be faster, but
# `PollingObserver()` works more universally.
observer = PollingObserver()
observer.schedule(event_handler, config["docs_dir"], recursive=True)
for theme_dir in config["theme_dir"]:
if not os.path.exists(theme_dir):
continue
observer.schedule(event_handler, theme_dir, recursive=True)
observer.schedule(config_event_handler, ".")
observer.start()
class TCPServer(socketserver.TCPServer):
allow_reuse_address = True
class DocsDirectoryHandler(FixedDirectoryHandler):
base_dir = config["site_dir"]
host, port = config["dev_addr"].split(":", 1)
server = TCPServer((host, int(port)), DocsDirectoryHandler)
print("Running at: http://%s:%s/" % (host, port))
print("Live reload enabled.")
print("Hold ctrl+c to quit.")
try:
server.serve_forever()
except KeyboardInterrupt:
print("Stopping server...")
# Clean up
observer.stop()
observer.join()
shutil.rmtree(tempdir)
print("Quit complete")
|
def serve(config, options=None):
"""
Start the devserver, and rebuild the docs whenever any changes take effect.
"""
# Create a temporary build directory, and set some options to serve it
tempdir = tempfile.mkdtemp()
options["site_dir"] = tempdir
# Only use user-friendly URLs when running the live server
options["use_directory_urls"] = True
# Perform the initial build
config = load_config(options=options)
build(config, live_server=True)
# Note: We pass any command-line options through so that we
# can re-apply them if the config file is reloaded.
event_handler = BuildEventHandler(options)
config_event_handler = ConfigEventHandler(options)
# We could have used `Observer()`, which can be faster, but
# `PollingObserver()` works more universally.
observer = PollingObserver()
observer.schedule(event_handler, config["docs_dir"], recursive=True)
for theme_dir in config["theme_dir"]:
observer.schedule(event_handler, theme_dir, recursive=True)
observer.schedule(config_event_handler, ".")
observer.start()
class TCPServer(socketserver.TCPServer):
allow_reuse_address = True
class DocsDirectoryHandler(FixedDirectoryHandler):
base_dir = config["site_dir"]
host, port = config["dev_addr"].split(":", 1)
server = TCPServer((host, int(port)), DocsDirectoryHandler)
print("Running at: http://%s:%s/" % (host, port))
print("Live reload enabled.")
print("Hold ctrl+c to quit.")
try:
server.serve_forever()
except KeyboardInterrupt:
print("Stopping server...")
# Clean up
observer.stop()
observer.join()
shutil.rmtree(tempdir)
print("Quit complete")
|
https://github.com/mkdocs/mkdocs/issues/373
|
Traceback (most recent call last):
File "/home/pi/.virtualenvs/face/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.11.1', 'console_scripts', 'mkdocs')()
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/mkdocs/main.py", line 60, in run_main
main(cmd, args=sys.argv[2:], options=dict(opts))
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/mkdocs/main.py", line 33, in main
serve(config, options=options)
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/mkdocs/serve.py", line 96, in serve
observer.start()
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/observers/api.py", line 255, in start
emitter.start()
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/utils/__init__.py", line 111, in start
self.on_thread_start()
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/observers/polling.py", line 77, in on_thread_start
self._snapshot = self._take_snapshot()
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/observers/polling.py", line 74, in <lambda>
self.watch.path, self.watch.is_recursive, stat=stat, listdir=listdir)
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/utils/dirsnapshot.py", line 207, in __init__
st = stat(path)
OSError: [Errno 2] No such file or directory: '/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/mkdocs/themes/face'
Exception in thread Thread-3 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/observers/api.py", line 146, in run
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/observers/polling.py", line 91, in queue_events
File "/home/pi/.virtualenvs/face/local/lib/python2.7/site-packages/watchdog/observers/polling.py", line 74, in <lambda>
<type 'exceptions.TypeError'>: 'NoneType' object is not callable
|
OSError
|
def load_config(filename="mkdocs.yml", options=None):
user_config = options or {}
if "config" in user_config:
filename = user_config.pop("config")
if not os.path.exists(filename):
raise ConfigurationError("Config file '%s' does not exist." % filename)
with open(filename, "r") as fp:
local_config = yaml.load(fp)
if local_config:
user_config.update(local_config)
return validate_config(user_config)
|
def load_config(filename="mkdocs.yml", options=None):
options = options or {}
if "config" in options:
filename = options["config"]
if not os.path.exists(filename):
raise ConfigurationError("Config file '%s' does not exist." % filename)
with open(filename, "r") as fp:
user_config = yaml.load(fp)
user_config.update(options)
return validate_config(user_config)
|
https://github.com/mkdocs/mkdocs/issues/283
|
Traceback (most recent call last):
File "/home/dougalmatthews/.virtualenvs/mkdocs/bin/mkdocs", line 9, in <module>
load_entry_point('mkdocs==0.11.1', 'console_scripts', 'mkdocs')()
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python3.4/site-packages/mkdocs/main.py", line 60, in run_main
main(cmd, args=sys.argv[2:], options=dict(opts))
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python3.4/site-packages/mkdocs/main.py", line 32, in main
config = load_config(options=options)
File "/home/dougalmatthews/.virtualenvs/mkdocs/lib/python3.4/site-packages/mkdocs/config.py", line 82, in load_config
user_config.update(options)
AttributeError: 'NoneType' object has no attribute 'update'
|
AttributeError
|
def base(
net: network.TensorNetwork,
algorithm: Callable[[List[Set[int]], Set[int], Dict[int, int]], List],
) -> network.TensorNetwork:
"""Base method for all `opt_einsum` contractors.
Args:
net: a TensorNetwork object. Should be connected.
algorithm: `opt_einsum` contraction method to use.
Returns:
The network after full contraction.
"""
net.check_connected()
# First contract all trace edges
edges = net.get_all_nondangling()
for edge in edges:
if edge in net and edge.is_trace():
net.contract_parallel(edge)
if not net.get_all_nondangling():
# There's nothing to contract.
return net
# Then apply `opt_einsum`'s algorithm
nodes = sorted(net.nodes_set)
input_sets = utils.get_input_sets(net)
output_set = utils.get_output_set(net)
size_dict = utils.get_size_dict(net)
path = algorithm(input_sets, output_set, size_dict)
for a, b in path:
new_node = nodes[a] @ nodes[b]
nodes.append(new_node)
nodes = utils.multi_remove(nodes, [a, b])
return net
|
def base(
net: network.TensorNetwork,
algorithm: Callable[[List[Set[int]], Set[int], Dict[int, int]], List],
) -> network.TensorNetwork:
"""Base method for all `opt_einsum` contractors.
Args:
net: a TensorNetwork object. Should be connected.
algorithm: `opt_einsum` contraction method to use.
Returns:
The network after full contraction.
"""
net.check_connected()
# First contract all trace edges
edges = net.get_all_nondangling()
for edge in edges:
if edge in net and edge.is_trace():
net.contract_parallel(edge)
# Then apply `opt_einsum`'s algorithm
nodes = sorted(net.nodes_set)
input_sets = utils.get_input_sets(net)
output_set = utils.get_output_set(net)
size_dict = utils.get_size_dict(net)
path = algorithm(input_sets, output_set, size_dict)
for a, b in path:
new_node = nodes[a] @ nodes[b]
nodes.append(new_node)
nodes = utils.multi_remove(nodes, [a, b])
return net
|
https://github.com/google/TensorNetwork/issues/177
|
Traceback (most recent call last):
File "check.py", line 8, in <module>
node = tensornetwork.contractors.optimal(net).get_final_node()
File "/usr/local/google/home/chaseriley/TensorNetwork/tensornetwork/contractors/opt_einsum_paths/path_contractors.py", line 59, in optimal
return base(net, alg)
File "/usr/local/google/home/chaseriley/TensorNetwork/tensornetwork/contractors/opt_einsum_paths/path_contractors.py", line 34, in base
path = algorithm(input_sets, output_set, size_dict)
File "/usr/local/google/home/chaseriley/.local/lib/python3.6/site-packages/opt_einsum/paths.py", line 196, in optimal
return ssa_to_linear(best['path'])
File "/usr/local/google/home/chaseriley/.local/lib/python3.6/site-packages/opt_einsum/paths.py", line 28, in ssa_to_linear
ids = np.arange(1 + max(map(max, ssa_path)), dtype=np.int32)
ValueError: max() arg is an empty sequence
|
ValueError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.