Skip to content

Sourcery refactored master branch #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
'Refactored by Sourcery'
  • Loading branch information
Sourcery AI committed Jul 26, 2023
commit ede96517ad3fc04641cac589d0893b71991995df
12 changes: 4 additions & 8 deletions doc/apidoc/helper_go_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,8 @@
# print(classes_str)

submodules_str = "\n".join(submodules)
# print(submodules_str)

autosubmodule = ""

for submodule in submodules:
autosubmodule += (
".. automodule:: plotly.graph_objects.%s\n :members:\n\n" % submodule
)
autosubmodule = "".join(
(".. automodule:: plotly.graph_objects.%s\n :members:\n\n" % submodule)
for submodule in submodules
)
Comment on lines -28 to +31
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 28-35 refactored with the following changes:

  • Use str.join() instead of for loop (use-join)

This removes the following comments ( why? ):

# print(submodules_str)

print(autosubmodule)
8 changes: 2 additions & 6 deletions packages/python/chart-studio/chart_studio/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
def _to_native_string(string, encoding):
if isinstance(string, builtin_str):
return string
if is_py2:
return string.encode(encoding)
return string.decode(encoding)
return string.encode(encoding) if is_py2 else string.decode(encoding)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _to_native_string refactored with the following changes:



def to_native_utf8_string(string):
Expand Down Expand Up @@ -36,6 +34,4 @@ def basic_auth(username, password):
if isinstance(password, str):
password = password.encode("latin1")

return "Basic " + to_native_ascii_string(
b64encode(b":".join((username, password))).strip()
)
return f'Basic {to_native_ascii_string(b64encode(b":".join((username, password))).strip())}'
Comment on lines -39 to +37
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function basic_auth refactored with the following changes:

25 changes: 11 additions & 14 deletions packages/python/chart-studio/chart_studio/api/v2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,15 @@ def build_url(resource, id="", route=""):
# can refer to a 'list' or a 'detail' route. Since it cannot refer to
# both at the same time, it's overloaded in this function.
if id:
if route:
url = "{base}/v2/{resource}/{id}/{route}".format(**formatter)
else:
url = "{base}/v2/{resource}/{id}".format(**formatter)
return (
"{base}/v2/{resource}/{id}/{route}".format(**formatter)
if route
else "{base}/v2/{resource}/{id}".format(**formatter)
)
elif route:
return "{base}/v2/{resource}/{route}".format(**formatter)
else:
if route:
url = "{base}/v2/{resource}/{route}".format(**formatter)
else:
url = "{base}/v2/{resource}".format(**formatter)

return url
return "{base}/v2/{resource}".format(**formatter)
Comment on lines -41 to +49
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_url refactored with the following changes:



def validate_response(response):
Expand Down Expand Up @@ -98,7 +96,7 @@ def get_headers():
creds = config.get_credentials()

headers = {
"plotly-client-platform": "python {}".format(version.stable_semver()),
"plotly-client-platform": f"python {version.stable_semver()}",
Comment on lines -101 to +99
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_headers refactored with the following changes:

"content-type": "application/json",
}

Expand All @@ -109,9 +107,8 @@ def get_headers():
headers["authorization"] = proxy_auth
if creds["username"] and creds["api_key"]:
headers["plotly-authorization"] = plotly_auth
else:
if creds["username"] and creds["api_key"]:
headers["authorization"] = plotly_auth
elif creds["username"] and creds["api_key"]:
headers["authorization"] = plotly_auth

return headers

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,17 @@


def _empty_box():
empty_box = {"type": "box", "boxType": "empty"}
return empty_box
return {"type": "box", "boxType": "empty"}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _empty_box refactored with the following changes:



def _box(fileId="", shareKey=None, title=""):
box = {
return {
"type": "box",
"boxType": "plot",
"fileId": fileId,
"shareKey": shareKey,
"title": title,
}
return box
Comment on lines -37 to -44
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _box refactored with the following changes:



def _container(box_1=None, box_2=None, size=50, sizeUnit="%", direction="vertical"):
Expand All @@ -50,7 +48,7 @@ def _container(box_1=None, box_2=None, size=50, sizeUnit="%", direction="vertica
if box_2 is None:
box_2 = _empty_box()

container = {
return {
Comment on lines -53 to +51
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _container refactored with the following changes:

"type": "split",
"size": size,
"sizeUnit": sizeUnit,
Expand All @@ -59,8 +57,6 @@ def _container(box_1=None, box_2=None, size=50, sizeUnit="%", direction="vertica
"second": box_2,
}

return container


dashboard_html = """
<!DOCTYPE HTML>
Expand Down Expand Up @@ -295,10 +291,7 @@ def _make_all_nodes_and_paths(self):
all_nodes = list(node_generator(self["layout"]))
all_nodes.sort(key=lambda x: x[1])

# remove path 'second' as it's always an empty box
all_paths = []
for node in all_nodes:
all_paths.append(node[1])
all_paths = [node[1] for node in all_nodes]
Comment on lines -298 to +294
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Dashboard._make_all_nodes_and_paths refactored with the following changes:

This removes the following comments ( why? ):

# remove path 'second' as it's always an empty box

path_second = ("second",)
if path_second in all_paths:
all_paths.remove(path_second)
Expand Down Expand Up @@ -412,10 +405,10 @@ def get_preview(self):
fill_percent=fill_percent,
)

new_top_left_x = top_left_x
new_top_left_y = top_left_y
# determine the specs for resulting two box split
if is_horizontal:
new_top_left_x = top_left_x
new_top_left_y = top_left_y
Comment on lines +408 to -418
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Dashboard.get_preview refactored with the following changes:

new_box_w = box_w * (fill_percent / 100.0)
new_box_h = box_h

Expand All @@ -424,8 +417,6 @@ def get_preview(self):
new_box_w_2 = box_w * ((100 - fill_percent) / 100.0)
new_box_h_2 = box_h
else:
new_top_left_x = top_left_x
new_top_left_y = top_left_y
new_box_w = box_w
new_box_h = box_h * (fill_percent / 100.0)

Expand Down
46 changes: 19 additions & 27 deletions packages/python/chart-studio/chart_studio/grid_objs/grid_objs.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,7 @@ def __init__(self, data, name):
def __str__(self):
max_chars = 10
jdata = _json.dumps(self.data, cls=utils.PlotlyJSONEncoder)
if len(jdata) > max_chars:
data_string = jdata[:max_chars] + "...]"
else:
data_string = jdata
data_string = f"{jdata[:max_chars]}...]" if len(jdata) > max_chars else jdata
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Column.__str__ refactored with the following changes:

string = '<name="{name}", data={data_string}, id={id}>'
return string.format(name=self.name, data=data_string, id=self.id)

Expand Down Expand Up @@ -158,15 +155,16 @@ def __init__(self, columns_or_json, fid=None):
# TODO: verify that columns are actually columns
pd = get_module("pandas")
if pd and isinstance(columns_or_json, pd.DataFrame):
duplicate_name = utils.get_first_duplicate(columns_or_json.columns)
if duplicate_name:
if duplicate_name := utils.get_first_duplicate(
columns_or_json.columns
):
err = exceptions.NON_UNIQUE_COLUMN_MESSAGE.format(duplicate_name)
raise exceptions.InputError(err)

# create columns from dataframe
all_columns = []
for name in columns_or_json.columns:
all_columns.append(Column(columns_or_json[name].tolist(), name))
all_columns = [
Column(columns_or_json[name].tolist(), name)
for name in columns_or_json.columns
]
Comment on lines -161 to +167
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Grid.__init__ refactored with the following changes:

This removes the following comments ( why? ):

# collect and sort all orders in case orders do not start
# create columns from dataframe
# at zero or there are jump discontinuities between them

self._columns = all_columns
self.id = ""

Expand Down Expand Up @@ -197,11 +195,10 @@ def __init__(self, columns_or_json, fid=None):
"Each column name of your dictionary must have "
"'data', 'order' and 'uid' as keys."
)
# collect and sort all orders in case orders do not start
# at zero or there are jump discontinuities between them
all_orders = []
for column_name in columns_or_json["cols"].keys():
all_orders.append(columns_or_json["cols"][column_name]["order"])
all_orders = [
columns_or_json["cols"][column_name]["order"]
for column_name in columns_or_json["cols"].keys()
]
all_orders.sort()

# put columns in order in a list
Expand All @@ -218,12 +215,11 @@ def __init__(self, columns_or_json, fid=None):

# fill in column_ids
for column in self:
column.id = self.id + ":" + columns_or_json["cols"][column.name]["uid"]
column.id = f"{self.id}:" + columns_or_json["cols"][column.name]["uid"]

else:
column_names = [column.name for column in columns_or_json]
duplicate_name = utils.get_first_duplicate(column_names)
if duplicate_name:
if duplicate_name := utils.get_first_duplicate(column_names):
err = exceptions.NON_UNIQUE_COLUMN_MESSAGE.format(duplicate_name)
raise exceptions.InputError(err)

Expand Down Expand Up @@ -283,16 +279,12 @@ def get_column_reference(self, column_name):
Raises an error if the column name is not in the grid. Otherwise,
returns the fid:uid pair, which may be the empty string.
"""
column_id = None
for column in self._columns:
if column.name == column_name:
column_id = column.id
break

column_id = next(
(column.id for column in self._columns if column.name == column_name),
None,
)
if column_id is None:
col_names = []
for column in self._columns:
col_names.append(column.name)
col_names = [column.name for column in self._columns]
Comment on lines -286 to +287
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Grid.get_column_reference refactored with the following changes:

raise _plotly_utils.exceptions.PlotlyError(
"Whoops, that column name doesn't match any of the column "
"names in your grid. You must pick from {cols}".format(cols=col_names)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,11 @@ def _get_ssl_context(self):

"""

context = None

if not self._ssl_verification_enabled:
context = ssl._create_unverified_context()

return context
return (
ssl._create_unverified_context()
if not self._ssl_verification_enabled
else None
)
Comment on lines -135 to +139
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Stream._get_ssl_context refactored with the following changes:


def _connect(self):
""" Initialize an HTTP/HTTPS connection with chunked Transfer-Encoding
Expand All @@ -158,17 +157,13 @@ def _connect(self):
else:
self._conn = http_client.HTTPConnection(proxy_server, proxy_port)

tunnel_headers = None
if proxy_auth:
tunnel_headers = {"Proxy-Authorization": proxy_auth}

tunnel_headers = {"Proxy-Authorization": proxy_auth} if proxy_auth else None
self._conn.set_tunnel(server, port, headers=tunnel_headers)
elif ssl_enabled:
context = self._get_ssl_context()
self._conn = http_client.HTTPSConnection(server, port, context=context)
else:
if ssl_enabled:
context = self._get_ssl_context()
self._conn = http_client.HTTPSConnection(server, port, context=context)
else:
self._conn = http_client.HTTPConnection(server, port)
self._conn = http_client.HTTPConnection(server, port)
Comment on lines -161 to +166
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Stream._connect refactored with the following changes:


self._conn.putrequest("POST", self._url)
self._conn.putheader("Transfer-Encoding", "chunked")
Expand Down Expand Up @@ -276,15 +271,15 @@ def _isconnected(self):
# Windows machines are the error codes
# that start with 1
# (http://msdn.microsoft.com/en-ca/library/windows/desktop/ms740668(v=vs.85).aspx)
if e.errno == 35 or e.errno == 10035:
if e.errno in [35, 10035]:
Comment on lines -279 to +274
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Stream._isconnected refactored with the following changes:

  • Replace multiple comparisons of same variable with in operator [×2] (merge-comparisons)

# This is the "Resource temporarily unavailable" error
# which is thrown cuz there was nothing to receive, i.e.
# the server hasn't returned a response yet.
# This is a non-fatal error and the operation
# should be tried again.
# So, assume that the connection is still open.
return True
elif e.errno == 54 or e.errno == 10054:
elif e.errno in [54, 10054]:
# This is the "Connection reset by peer" error
# which is thrown cuz the server reset the
# socket, so the connection is closed.
Expand Down Expand Up @@ -321,21 +316,19 @@ def _reconnect(self):
try:
self._connect()
except http_client.socket.error as e:
# Attempt to reconnect if the connection was refused
if e.errno == 61 or e.errno == 10061:
# errno 61 is the "Connection Refused" error
time.sleep(self._delay)
self._delay += self._delay # fibonacii delays
self._tries += 1
if self._tries < self.maxtries:
self._reconnect()
else:
self._reset_retries()
raise e
else:
if e.errno not in [61, 10061]:
# Unknown scenario
raise e

# errno 61 is the "Connection Refused" error
time.sleep(self._delay)
self._delay += self._delay # fibonacii delays
self._tries += 1
if self._tries < self.maxtries:
self._reconnect()
else:
self._reset_retries()
raise e
Comment on lines -324 to +331
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Stream._reconnect refactored with the following changes:

This removes the following comments ( why? ):

# Attempt to reconnect if the connection was refused

# Reconnect worked - reset _closed
self._closed = False

Expand Down
Loading