repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
stbraun/fuzzing | features/steps/ft_singleton.py | step_impl07 | def step_impl07(context):
"""Test for singleton property.
:param context: test context.
"""
assert context.st_1 is context.st_2
assert context.st_2 is context.st_3 | python | def step_impl07(context):
"""Test for singleton property.
:param context: test context.
"""
assert context.st_1 is context.st_2
assert context.st_2 is context.st_3 | [
"def",
"step_impl07",
"(",
"context",
")",
":",
"assert",
"context",
".",
"st_1",
"is",
"context",
".",
"st_2",
"assert",
"context",
".",
"st_2",
"is",
"context",
".",
"st_3"
] | Test for singleton property.
:param context: test context. | [
"Test",
"for",
"singleton",
"property",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/steps/ft_singleton.py#L74-L80 |
idlesign/dbf_light | dbf_light/light.py | open_db | def open_db(db, zipped=None, encoding=None, fieldnames_lower=True, case_sensitive=True):
"""Context manager. Allows reading DBF file (maybe even from zip).
:param str|unicode|file db: .dbf file name or a file-like object.
:param str|unicode zipped: .zip file path or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf
"""
kwargs = dict(
encoding=encoding,
fieldnames_lower=fieldnames_lower,
case_sensitive=case_sensitive,
)
if zipped:
with Dbf.open_zip(db, zipped, **kwargs) as dbf:
yield dbf
else:
with Dbf.open(db, **kwargs) as dbf:
yield dbf | python | def open_db(db, zipped=None, encoding=None, fieldnames_lower=True, case_sensitive=True):
"""Context manager. Allows reading DBF file (maybe even from zip).
:param str|unicode|file db: .dbf file name or a file-like object.
:param str|unicode zipped: .zip file path or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf
"""
kwargs = dict(
encoding=encoding,
fieldnames_lower=fieldnames_lower,
case_sensitive=case_sensitive,
)
if zipped:
with Dbf.open_zip(db, zipped, **kwargs) as dbf:
yield dbf
else:
with Dbf.open(db, **kwargs) as dbf:
yield dbf | [
"def",
"open_db",
"(",
"db",
",",
"zipped",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"fieldnames_lower",
"=",
"True",
",",
"case_sensitive",
"=",
"True",
")",
":",
"kwargs",
"=",
"dict",
"(",
"encoding",
"=",
"encoding",
",",
"fieldnames_lower",
"... | Context manager. Allows reading DBF file (maybe even from zip).
:param str|unicode|file db: .dbf file name or a file-like object.
:param str|unicode zipped: .zip file path or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf | [
"Context",
"manager",
".",
"Allows",
"reading",
"DBF",
"file",
"(",
"maybe",
"even",
"from",
"zip",
")",
"."
] | train | https://github.com/idlesign/dbf_light/blob/59487bcdf92893a8a4b24239371dc0e4722c4c37/dbf_light/light.py#L167-L195 |
idlesign/dbf_light | dbf_light/light.py | Dbf.open | def open(cls, dbfile, encoding=None, fieldnames_lower=True, case_sensitive=True):
"""Context manager. Allows opening a .dbf file.
.. code-block::
with Dbf.open('some.dbf') as dbf:
...
:param str|unicode|file dbfile: .dbf filepath or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf
"""
if not case_sensitive:
if isinstance(dbfile, string_types):
dbfile = pick_name(dbfile, listdir(path.dirname(dbfile)))
with open(dbfile, 'rb') as f:
yield cls(f, encoding=encoding, fieldnames_lower=fieldnames_lower) | python | def open(cls, dbfile, encoding=None, fieldnames_lower=True, case_sensitive=True):
"""Context manager. Allows opening a .dbf file.
.. code-block::
with Dbf.open('some.dbf') as dbf:
...
:param str|unicode|file dbfile: .dbf filepath or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf
"""
if not case_sensitive:
if isinstance(dbfile, string_types):
dbfile = pick_name(dbfile, listdir(path.dirname(dbfile)))
with open(dbfile, 'rb') as f:
yield cls(f, encoding=encoding, fieldnames_lower=fieldnames_lower) | [
"def",
"open",
"(",
"cls",
",",
"dbfile",
",",
"encoding",
"=",
"None",
",",
"fieldnames_lower",
"=",
"True",
",",
"case_sensitive",
"=",
"True",
")",
":",
"if",
"not",
"case_sensitive",
":",
"if",
"isinstance",
"(",
"dbfile",
",",
"string_types",
")",
"... | Context manager. Allows opening a .dbf file.
.. code-block::
with Dbf.open('some.dbf') as dbf:
...
:param str|unicode|file dbfile: .dbf filepath or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf | [
"Context",
"manager",
".",
"Allows",
"opening",
"a",
".",
"dbf",
"file",
"."
] | train | https://github.com/idlesign/dbf_light/blob/59487bcdf92893a8a4b24239371dc0e4722c4c37/dbf_light/light.py#L52-L76 |
idlesign/dbf_light | dbf_light/light.py | Dbf.open_zip | def open_zip(cls, dbname, zipped, encoding=None, fieldnames_lower=True, case_sensitive=True):
"""Context manager. Allows opening a .dbf file from zip archive.
.. code-block::
with Dbf.open_zip('some.dbf', 'myarch.zip') as dbf:
...
:param str|unicode dbname: .dbf file name
:param str|unicode|file zipped: .zip file path or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf
"""
with ZipFile(zipped, 'r') as zip_:
if not case_sensitive:
dbname = pick_name(dbname, zip_.namelist())
with zip_.open(dbname) as f:
yield cls(f, encoding=encoding, fieldnames_lower=fieldnames_lower) | python | def open_zip(cls, dbname, zipped, encoding=None, fieldnames_lower=True, case_sensitive=True):
"""Context manager. Allows opening a .dbf file from zip archive.
.. code-block::
with Dbf.open_zip('some.dbf', 'myarch.zip') as dbf:
...
:param str|unicode dbname: .dbf file name
:param str|unicode|file zipped: .zip file path or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf
"""
with ZipFile(zipped, 'r') as zip_:
if not case_sensitive:
dbname = pick_name(dbname, zip_.namelist())
with zip_.open(dbname) as f:
yield cls(f, encoding=encoding, fieldnames_lower=fieldnames_lower) | [
"def",
"open_zip",
"(",
"cls",
",",
"dbname",
",",
"zipped",
",",
"encoding",
"=",
"None",
",",
"fieldnames_lower",
"=",
"True",
",",
"case_sensitive",
"=",
"True",
")",
":",
"with",
"ZipFile",
"(",
"zipped",
",",
"'r'",
")",
"as",
"zip_",
":",
"if",
... | Context manager. Allows opening a .dbf file from zip archive.
.. code-block::
with Dbf.open_zip('some.dbf', 'myarch.zip') as dbf:
...
:param str|unicode dbname: .dbf file name
:param str|unicode|file zipped: .zip file path or a file-like object.
:param str|unicode encoding: Encoding used by DB.
This will be used if there's no encoding information in the DB itself.
:param bool fieldnames_lower: Lowercase field names.
:param bool case_sensitive: Whether DB filename is case sensitive.
:rtype: Dbf | [
"Context",
"manager",
".",
"Allows",
"opening",
"a",
".",
"dbf",
"file",
"from",
"zip",
"archive",
"."
] | train | https://github.com/idlesign/dbf_light/blob/59487bcdf92893a8a4b24239371dc0e4722c4c37/dbf_light/light.py#L80-L107 |
idlesign/dbf_light | dbf_light/light.py | Dbf.iter_rows | def iter_rows(self):
"""Generator reading .dbf row one by one.
Yields named tuple Row object.
:rtype: Row
"""
fileobj = self._fileobj
cls_row = self.cls_row
fields = self.fields
for idx in range(self.prolog.records_count):
data = fileobj.read(1)
marker = struct.unpack('<1s', data)[0]
is_deleted = marker == b'*'
if is_deleted:
continue
row_values = []
for field in fields:
val = field.cast(fileobj.read(field.len))
row_values.append(val)
yield cls_row(*row_values) | python | def iter_rows(self):
"""Generator reading .dbf row one by one.
Yields named tuple Row object.
:rtype: Row
"""
fileobj = self._fileobj
cls_row = self.cls_row
fields = self.fields
for idx in range(self.prolog.records_count):
data = fileobj.read(1)
marker = struct.unpack('<1s', data)[0]
is_deleted = marker == b'*'
if is_deleted:
continue
row_values = []
for field in fields:
val = field.cast(fileobj.read(field.len))
row_values.append(val)
yield cls_row(*row_values) | [
"def",
"iter_rows",
"(",
"self",
")",
":",
"fileobj",
"=",
"self",
".",
"_fileobj",
"cls_row",
"=",
"self",
".",
"cls_row",
"fields",
"=",
"self",
".",
"fields",
"for",
"idx",
"in",
"range",
"(",
"self",
".",
"prolog",
".",
"records_count",
")",
":",
... | Generator reading .dbf row one by one.
Yields named tuple Row object.
:rtype: Row | [
"Generator",
"reading",
".",
"dbf",
"row",
"one",
"by",
"one",
"."
] | train | https://github.com/idlesign/dbf_light/blob/59487bcdf92893a8a4b24239371dc0e4722c4c37/dbf_light/light.py#L109-L134 |
mikekatz04/BOWIE | bowie/plotutils/baseplot.py | CreateSinglePlot.setup_plot | def setup_plot(self):
"""Set up limits and labels.
For all plot types, this method is used to setup the basic features of each plot.
"""
if self.tick_label_fontsize is not None:
self.x_tick_label_fontsize = self.tick_label_fontsize
self.y_tick_label_fontsize = self.tick_label_fontsize
# setup xticks and yticks and limits
# if logspaced, the log values are used.
xticks = np.arange(float(self.xlims[0]),
float(self.xlims[1])
+ float(self.dx),
float(self.dx))
yticks = np.arange(float(self.ylims[0]),
float(self.ylims[1])
+ float(self.dy),
float(self.dy))
xlim = [xticks.min(), xticks.max()]
ylim = [yticks.min(), yticks.max()]
if self.reverse_x_axis:
xticks = xticks[::-1]
xlim = [xticks.max(), xticks.min()]
if self.reverse_y_axis:
yticks = yticks[::-1]
ylim = [yticks.max(), yticks.min()]
self.axis.set_xlim(xlim)
self.axis.set_ylim(ylim)
# adjust ticks for spacing. If 'wide' then show all labels, if 'tight' remove end labels.
if self.spacing == 'wide':
x_inds = np.arange(len(xticks))
y_inds = np.arange(len(yticks))
else:
# remove end labels
x_inds = np.arange(1, len(xticks)-1)
y_inds = np.arange(1, len(yticks)-1)
self.axis.set_xticks(xticks[x_inds])
self.axis.set_yticks(yticks[y_inds])
# set tick labels based on scale
if self.xscale == 'log':
self.axis.set_xticklabels([r'$10^{%i}$' % int(i)
for i in xticks[x_inds]], fontsize=self.x_tick_label_fontsize)
else:
self.axis.set_xticklabels([r'$%.3g$' % (i)
for i in xticks[x_inds]], fontsize=self.x_tick_label_fontsize)
if self.yscale == 'log':
self.axis.set_yticklabels([r'$10^{%i}$' % int(i)
for i in yticks[y_inds]], fontsize=self.y_tick_label_fontsize)
else:
self.axis.set_yticklabels([r'$%.3g$' % (i)
for i in yticks[y_inds]], fontsize=self.y_tick_label_fontsize)
# add grid
if self.add_grid:
self.axis.grid(True, linestyle='-', color='0.75')
# add title
if 'title' in self.__dict__.keys():
self.axis.set_title(r'{}'.format(self.title), **self.title_kwargs)
if 'xlabel' in self.__dict__.keys():
self.axis.set_xlabel(r'{}'.format(self.xlabel), **self.xlabel_kwargs)
if 'ylabel' in self.__dict__.keys():
self.axis.set_ylabel(r'{}'.format(self.ylabel), **self.ylabel_kwargs)
return | python | def setup_plot(self):
"""Set up limits and labels.
For all plot types, this method is used to setup the basic features of each plot.
"""
if self.tick_label_fontsize is not None:
self.x_tick_label_fontsize = self.tick_label_fontsize
self.y_tick_label_fontsize = self.tick_label_fontsize
# setup xticks and yticks and limits
# if logspaced, the log values are used.
xticks = np.arange(float(self.xlims[0]),
float(self.xlims[1])
+ float(self.dx),
float(self.dx))
yticks = np.arange(float(self.ylims[0]),
float(self.ylims[1])
+ float(self.dy),
float(self.dy))
xlim = [xticks.min(), xticks.max()]
ylim = [yticks.min(), yticks.max()]
if self.reverse_x_axis:
xticks = xticks[::-1]
xlim = [xticks.max(), xticks.min()]
if self.reverse_y_axis:
yticks = yticks[::-1]
ylim = [yticks.max(), yticks.min()]
self.axis.set_xlim(xlim)
self.axis.set_ylim(ylim)
# adjust ticks for spacing. If 'wide' then show all labels, if 'tight' remove end labels.
if self.spacing == 'wide':
x_inds = np.arange(len(xticks))
y_inds = np.arange(len(yticks))
else:
# remove end labels
x_inds = np.arange(1, len(xticks)-1)
y_inds = np.arange(1, len(yticks)-1)
self.axis.set_xticks(xticks[x_inds])
self.axis.set_yticks(yticks[y_inds])
# set tick labels based on scale
if self.xscale == 'log':
self.axis.set_xticklabels([r'$10^{%i}$' % int(i)
for i in xticks[x_inds]], fontsize=self.x_tick_label_fontsize)
else:
self.axis.set_xticklabels([r'$%.3g$' % (i)
for i in xticks[x_inds]], fontsize=self.x_tick_label_fontsize)
if self.yscale == 'log':
self.axis.set_yticklabels([r'$10^{%i}$' % int(i)
for i in yticks[y_inds]], fontsize=self.y_tick_label_fontsize)
else:
self.axis.set_yticklabels([r'$%.3g$' % (i)
for i in yticks[y_inds]], fontsize=self.y_tick_label_fontsize)
# add grid
if self.add_grid:
self.axis.grid(True, linestyle='-', color='0.75')
# add title
if 'title' in self.__dict__.keys():
self.axis.set_title(r'{}'.format(self.title), **self.title_kwargs)
if 'xlabel' in self.__dict__.keys():
self.axis.set_xlabel(r'{}'.format(self.xlabel), **self.xlabel_kwargs)
if 'ylabel' in self.__dict__.keys():
self.axis.set_ylabel(r'{}'.format(self.ylabel), **self.ylabel_kwargs)
return | [
"def",
"setup_plot",
"(",
"self",
")",
":",
"if",
"self",
".",
"tick_label_fontsize",
"is",
"not",
"None",
":",
"self",
".",
"x_tick_label_fontsize",
"=",
"self",
".",
"tick_label_fontsize",
"self",
".",
"y_tick_label_fontsize",
"=",
"self",
".",
"tick_label_fon... | Set up limits and labels.
For all plot types, this method is used to setup the basic features of each plot. | [
"Set",
"up",
"limits",
"and",
"labels",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/baseplot.py#L147-L223 |
mikekatz04/BOWIE | bowie/plotutils/baseplot.py | FigColorbar.setup_colorbars | def setup_colorbars(self, plot_call_sign):
"""Setup colorbars for each type of plot.
Take all of the optional performed during ``__init__`` method and makes the colorbar.
Args:
plot_call_sign (obj): Plot instance of ax.contourf with colormapping to
add as a colorbar.
"""
self.fig.colorbar(plot_call_sign, cax=self.cbar_ax,
ticks=self.cbar_ticks, orientation=self.cbar_orientation)
# setup colorbar ticks
(getattr(self.cbar_ax, 'set_' + self.cbar_var + 'ticklabels')
(self.cbar_tick_labels, fontsize=self.cbar_ticks_fontsize))
(getattr(self.cbar_ax, 'set_' + self.cbar_var + 'label')
(self.cbar_label, fontsize=self.cbar_label_fontsize, labelpad=self.cbar_label_pad))
return | python | def setup_colorbars(self, plot_call_sign):
"""Setup colorbars for each type of plot.
Take all of the optional performed during ``__init__`` method and makes the colorbar.
Args:
plot_call_sign (obj): Plot instance of ax.contourf with colormapping to
add as a colorbar.
"""
self.fig.colorbar(plot_call_sign, cax=self.cbar_ax,
ticks=self.cbar_ticks, orientation=self.cbar_orientation)
# setup colorbar ticks
(getattr(self.cbar_ax, 'set_' + self.cbar_var + 'ticklabels')
(self.cbar_tick_labels, fontsize=self.cbar_ticks_fontsize))
(getattr(self.cbar_ax, 'set_' + self.cbar_var + 'label')
(self.cbar_label, fontsize=self.cbar_label_fontsize, labelpad=self.cbar_label_pad))
return | [
"def",
"setup_colorbars",
"(",
"self",
",",
"plot_call_sign",
")",
":",
"self",
".",
"fig",
".",
"colorbar",
"(",
"plot_call_sign",
",",
"cax",
"=",
"self",
".",
"cbar_ax",
",",
"ticks",
"=",
"self",
".",
"cbar_ticks",
",",
"orientation",
"=",
"self",
".... | Setup colorbars for each type of plot.
Take all of the optional performed during ``__init__`` method and makes the colorbar.
Args:
plot_call_sign (obj): Plot instance of ax.contourf with colormapping to
add as a colorbar. | [
"Setup",
"colorbars",
"for",
"each",
"type",
"of",
"plot",
"."
] | train | https://github.com/mikekatz04/BOWIE/blob/a941342a3536cb57c817a1643896d99a3f354a86/bowie/plotutils/baseplot.py#L338-L356 |
gautammishra/lyft-rides-python-sdk | lyft_rides/errors.py | HTTPError._adapt_response | def _adapt_response(self, response):
"""Convert error responses to standardized ErrorDetails."""
if 'application/json' in response.headers['content-type']:
body = response.json()
status = response.status_code
if body.get('error'):
return self._simple_response_to_error_adapter(status, body)
raise UnknownHttpError(response) | python | def _adapt_response(self, response):
"""Convert error responses to standardized ErrorDetails."""
if 'application/json' in response.headers['content-type']:
body = response.json()
status = response.status_code
if body.get('error'):
return self._simple_response_to_error_adapter(status, body)
raise UnknownHttpError(response) | [
"def",
"_adapt_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"'application/json'",
"in",
"response",
".",
"headers",
"[",
"'content-type'",
"]",
":",
"body",
"=",
"response",
".",
"json",
"(",
")",
"status",
"=",
"response",
".",
"status_code",
... | Convert error responses to standardized ErrorDetails. | [
"Convert",
"error",
"responses",
"to",
"standardized",
"ErrorDetails",
"."
] | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/errors.py#L23-L32 |
gautammishra/lyft-rides-python-sdk | lyft_rides/errors.py | HTTPError._simple_response_to_error_adapter | def _simple_response_to_error_adapter(self, status, original_body):
"""Convert a single error response."""
meta = original_body.get('error')
e = []
if 'error_detail' in original_body:
errors = original_body.get('error_detail')
for error in errors:
if type(error) == dict:
for parameter, title in error.iteritems():
e.append(ErrorDetails(parameter, title))
elif 'error_description' in original_body:
e.append(original_body.get('error_description'))
return e, meta | python | def _simple_response_to_error_adapter(self, status, original_body):
"""Convert a single error response."""
meta = original_body.get('error')
e = []
if 'error_detail' in original_body:
errors = original_body.get('error_detail')
for error in errors:
if type(error) == dict:
for parameter, title in error.iteritems():
e.append(ErrorDetails(parameter, title))
elif 'error_description' in original_body:
e.append(original_body.get('error_description'))
return e, meta | [
"def",
"_simple_response_to_error_adapter",
"(",
"self",
",",
"status",
",",
"original_body",
")",
":",
"meta",
"=",
"original_body",
".",
"get",
"(",
"'error'",
")",
"e",
"=",
"[",
"]",
"if",
"'error_detail'",
"in",
"original_body",
":",
"errors",
"=",
"ori... | Convert a single error response. | [
"Convert",
"a",
"single",
"error",
"response",
"."
] | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/errors.py#L34-L49 |
mozilla/funfactory | funfactory/manage.py | setup_environ | def setup_environ(manage_file, settings=None, more_pythonic=False):
"""Sets up a Django app within a manage.py file.
Keyword Arguments
**settings**
An imported settings module. Without this, playdoh tries to import
these modules (in order): DJANGO_SETTINGS_MODULE, settings
**more_pythonic**
When True, does not do any path hackery besides adding the vendor dirs.
This requires a newer Playdoh layout without top level apps, lib, etc.
"""
# sys is global to avoid undefined local
global sys, current_settings, execute_from_command_line, ROOT
ROOT = os.path.dirname(os.path.abspath(manage_file))
# Adjust the python path and put local packages in front.
prev_sys_path = list(sys.path)
# Make root application importable without the need for
# python setup.py install|develop
sys.path.append(ROOT)
if not more_pythonic:
warnings.warn("You're using an old-style Playdoh layout with a top "
"level __init__.py and apps directories. This is error "
"prone and fights the Zen of Python. "
"See http://playdoh.readthedocs.org/en/latest/"
"getting-started/upgrading.html")
# Give precedence to your app's parent dir, which contains __init__.py
sys.path.append(os.path.abspath(os.path.join(ROOT, os.pardir)))
site.addsitedir(path('apps'))
site.addsitedir(path('lib'))
# Local (project) vendor library
site.addsitedir(path('vendor-local'))
site.addsitedir(path('vendor-local/lib/python'))
# Global (upstream) vendor library
site.addsitedir(path('vendor'))
site.addsitedir(path('vendor/lib/python'))
# Move the new items to the front of sys.path. (via virtualenv)
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
from django.core.management import execute_from_command_line # noqa
if not settings:
if 'DJANGO_SETTINGS_MODULE' in os.environ:
settings = import_mod_by_name(os.environ['DJANGO_SETTINGS_MODULE'])
elif os.path.isfile(os.path.join(ROOT, 'settings_local.py')):
import settings_local as settings
warnings.warn("Using settings_local.py is deprecated. See "
"http://playdoh.readthedocs.org/en/latest/upgrading.html",
DeprecationWarning)
else:
import settings
current_settings = settings
validate_settings(settings) | python | def setup_environ(manage_file, settings=None, more_pythonic=False):
"""Sets up a Django app within a manage.py file.
Keyword Arguments
**settings**
An imported settings module. Without this, playdoh tries to import
these modules (in order): DJANGO_SETTINGS_MODULE, settings
**more_pythonic**
When True, does not do any path hackery besides adding the vendor dirs.
This requires a newer Playdoh layout without top level apps, lib, etc.
"""
# sys is global to avoid undefined local
global sys, current_settings, execute_from_command_line, ROOT
ROOT = os.path.dirname(os.path.abspath(manage_file))
# Adjust the python path and put local packages in front.
prev_sys_path = list(sys.path)
# Make root application importable without the need for
# python setup.py install|develop
sys.path.append(ROOT)
if not more_pythonic:
warnings.warn("You're using an old-style Playdoh layout with a top "
"level __init__.py and apps directories. This is error "
"prone and fights the Zen of Python. "
"See http://playdoh.readthedocs.org/en/latest/"
"getting-started/upgrading.html")
# Give precedence to your app's parent dir, which contains __init__.py
sys.path.append(os.path.abspath(os.path.join(ROOT, os.pardir)))
site.addsitedir(path('apps'))
site.addsitedir(path('lib'))
# Local (project) vendor library
site.addsitedir(path('vendor-local'))
site.addsitedir(path('vendor-local/lib/python'))
# Global (upstream) vendor library
site.addsitedir(path('vendor'))
site.addsitedir(path('vendor/lib/python'))
# Move the new items to the front of sys.path. (via virtualenv)
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
from django.core.management import execute_from_command_line # noqa
if not settings:
if 'DJANGO_SETTINGS_MODULE' in os.environ:
settings = import_mod_by_name(os.environ['DJANGO_SETTINGS_MODULE'])
elif os.path.isfile(os.path.join(ROOT, 'settings_local.py')):
import settings_local as settings
warnings.warn("Using settings_local.py is deprecated. See "
"http://playdoh.readthedocs.org/en/latest/upgrading.html",
DeprecationWarning)
else:
import settings
current_settings = settings
validate_settings(settings) | [
"def",
"setup_environ",
"(",
"manage_file",
",",
"settings",
"=",
"None",
",",
"more_pythonic",
"=",
"False",
")",
":",
"# sys is global to avoid undefined local",
"global",
"sys",
",",
"current_settings",
",",
"execute_from_command_line",
",",
"ROOT",
"ROOT",
"=",
... | Sets up a Django app within a manage.py file.
Keyword Arguments
**settings**
An imported settings module. Without this, playdoh tries to import
these modules (in order): DJANGO_SETTINGS_MODULE, settings
**more_pythonic**
When True, does not do any path hackery besides adding the vendor dirs.
This requires a newer Playdoh layout without top level apps, lib, etc. | [
"Sets",
"up",
"a",
"Django",
"app",
"within",
"a",
"manage",
".",
"py",
"file",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/manage.py#L21-L86 |
mozilla/funfactory | funfactory/manage.py | validate_settings | def validate_settings(settings):
"""
Raise an error in prod if we see any insecure settings.
This used to warn during development but that was changed in
71718bec324c2561da6cc3990c927ee87362f0f7
"""
from django.core.exceptions import ImproperlyConfigured
if settings.SECRET_KEY == '':
msg = 'settings.SECRET_KEY cannot be blank! Check your local settings'
if not settings.DEBUG:
raise ImproperlyConfigured(msg)
if getattr(settings, 'SESSION_COOKIE_SECURE', None) is None:
msg = ('settings.SESSION_COOKIE_SECURE should be set to True; '
'otherwise, your session ids can be intercepted over HTTP!')
if not settings.DEBUG:
raise ImproperlyConfigured(msg)
hmac = getattr(settings, 'HMAC_KEYS', {})
if not len(hmac.keys()):
msg = 'settings.HMAC_KEYS cannot be empty! Check your local settings'
if not settings.DEBUG:
raise ImproperlyConfigured(msg) | python | def validate_settings(settings):
"""
Raise an error in prod if we see any insecure settings.
This used to warn during development but that was changed in
71718bec324c2561da6cc3990c927ee87362f0f7
"""
from django.core.exceptions import ImproperlyConfigured
if settings.SECRET_KEY == '':
msg = 'settings.SECRET_KEY cannot be blank! Check your local settings'
if not settings.DEBUG:
raise ImproperlyConfigured(msg)
if getattr(settings, 'SESSION_COOKIE_SECURE', None) is None:
msg = ('settings.SESSION_COOKIE_SECURE should be set to True; '
'otherwise, your session ids can be intercepted over HTTP!')
if not settings.DEBUG:
raise ImproperlyConfigured(msg)
hmac = getattr(settings, 'HMAC_KEYS', {})
if not len(hmac.keys()):
msg = 'settings.HMAC_KEYS cannot be empty! Check your local settings'
if not settings.DEBUG:
raise ImproperlyConfigured(msg) | [
"def",
"validate_settings",
"(",
"settings",
")",
":",
"from",
"django",
".",
"core",
".",
"exceptions",
"import",
"ImproperlyConfigured",
"if",
"settings",
".",
"SECRET_KEY",
"==",
"''",
":",
"msg",
"=",
"'settings.SECRET_KEY cannot be blank! Check your local settings'... | Raise an error in prod if we see any insecure settings.
This used to warn during development but that was changed in
71718bec324c2561da6cc3990c927ee87362f0f7 | [
"Raise",
"an",
"error",
"in",
"prod",
"if",
"we",
"see",
"any",
"insecure",
"settings",
"."
] | train | https://github.com/mozilla/funfactory/blob/c9bbf1c534eaa15641265bc75fa87afca52b7dd6/funfactory/manage.py#L89-L112 |
limix/limix-core | limix_core/util/cobj.py | cached | def cached(method):
""" this function is used as a decorator for caching """
_cache_attr_name = '_cache_'+method.__name__
_bool_attr_name = '_cached_'+method.__name__
def method_wrapper(self,*args,**kwargs):
is_cached = getattr(self,_bool_attr_name)
if not is_cached:
result = method(self, *args, **kwargs)
setattr(self, _cache_attr_name, result)
setattr(self, _bool_attr_name, True)
return getattr(self,'_cache_'+method.__name__)
return method_wrapper | python | def cached(method):
""" this function is used as a decorator for caching """
_cache_attr_name = '_cache_'+method.__name__
_bool_attr_name = '_cached_'+method.__name__
def method_wrapper(self,*args,**kwargs):
is_cached = getattr(self,_bool_attr_name)
if not is_cached:
result = method(self, *args, **kwargs)
setattr(self, _cache_attr_name, result)
setattr(self, _bool_attr_name, True)
return getattr(self,'_cache_'+method.__name__)
return method_wrapper | [
"def",
"cached",
"(",
"method",
")",
":",
"_cache_attr_name",
"=",
"'_cache_'",
"+",
"method",
".",
"__name__",
"_bool_attr_name",
"=",
"'_cached_'",
"+",
"method",
".",
"__name__",
"def",
"method_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw... | this function is used as a decorator for caching | [
"this",
"function",
"is",
"used",
"as",
"a",
"decorator",
"for",
"caching"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/cobj.py#L29-L40 |
limix/limix-core | limix_core/util/cobj.py | cached_idxs | def cached_idxs(method):
""" this function is used as a decorator for caching """
def method_wrapper(self,*args,**kwargs):
tail = '_'.join(str(idx) for idx in args)
_cache_attr_name = '_cache_'+method.__name__+'_'+tail
_bool_attr_name = '_cached_'+method.__name__+'_'+tail
is_cached = getattr(self,_bool_attr_name)
if not is_cached:
result = method(self, *args, **kwargs)
setattr(self, _cache_attr_name, result)
setattr(self, _bool_attr_name, True)
return getattr(self,_cache_attr_name)
return method_wrapper | python | def cached_idxs(method):
""" this function is used as a decorator for caching """
def method_wrapper(self,*args,**kwargs):
tail = '_'.join(str(idx) for idx in args)
_cache_attr_name = '_cache_'+method.__name__+'_'+tail
_bool_attr_name = '_cached_'+method.__name__+'_'+tail
is_cached = getattr(self,_bool_attr_name)
if not is_cached:
result = method(self, *args, **kwargs)
setattr(self, _cache_attr_name, result)
setattr(self, _bool_attr_name, True)
return getattr(self,_cache_attr_name)
return method_wrapper | [
"def",
"cached_idxs",
"(",
"method",
")",
":",
"def",
"method_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tail",
"=",
"'_'",
".",
"join",
"(",
"str",
"(",
"idx",
")",
"for",
"idx",
"in",
"args",
")",
"_cache_attr_na... | this function is used as a decorator for caching | [
"this",
"function",
"is",
"used",
"as",
"a",
"decorator",
"for",
"caching"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/util/cobj.py#L42-L54 |
all-umass/graphs | graphs/construction/incremental.py | incremental_neighbor_graph | def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None,
weighting='none'):
'''See neighbor_graph.'''
assert ((k is not None) or (epsilon is not None)
), "Must provide `k` or `epsilon`"
assert (_issequence(k) ^ _issequence(epsilon)
), "Exactly one of `k` or `epsilon` must be a sequence."
assert weighting in ('binary','none'), "Invalid weighting param: " + weighting
is_weighted = weighting == 'none'
if precomputed:
D = X
else:
D = pairwise_distances(X, metric='euclidean')
# pre-sort for efficiency
order = np.argsort(D)[:,1:]
if k is None:
k = D.shape[0]
# generate the sequence of graphs
# TODO: convert the core of these loops to Cython for speed
W = np.zeros_like(D)
I = np.arange(D.shape[0])
if _issequence(k):
# varied k, fixed epsilon
if epsilon is not None:
D[D > epsilon] = 0
old_k = 0
for new_k in k:
idx = order[:, old_k:new_k]
dist = D[I, idx.T]
W[I, idx.T] = dist if is_weighted else 1
yield Graph.from_adj_matrix(W)
old_k = new_k
else:
# varied epsilon, fixed k
idx = order[:,:k]
dist = D[I, idx.T].T
old_i = np.zeros(D.shape[0], dtype=int)
for eps in epsilon:
for i, row in enumerate(dist):
oi = old_i[i]
ni = oi + np.searchsorted(row[oi:], eps)
rr = row[oi:ni]
W[i, idx[i,oi:ni]] = rr if is_weighted else 1
old_i[i] = ni
yield Graph.from_adj_matrix(W) | python | def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None,
weighting='none'):
'''See neighbor_graph.'''
assert ((k is not None) or (epsilon is not None)
), "Must provide `k` or `epsilon`"
assert (_issequence(k) ^ _issequence(epsilon)
), "Exactly one of `k` or `epsilon` must be a sequence."
assert weighting in ('binary','none'), "Invalid weighting param: " + weighting
is_weighted = weighting == 'none'
if precomputed:
D = X
else:
D = pairwise_distances(X, metric='euclidean')
# pre-sort for efficiency
order = np.argsort(D)[:,1:]
if k is None:
k = D.shape[0]
# generate the sequence of graphs
# TODO: convert the core of these loops to Cython for speed
W = np.zeros_like(D)
I = np.arange(D.shape[0])
if _issequence(k):
# varied k, fixed epsilon
if epsilon is not None:
D[D > epsilon] = 0
old_k = 0
for new_k in k:
idx = order[:, old_k:new_k]
dist = D[I, idx.T]
W[I, idx.T] = dist if is_weighted else 1
yield Graph.from_adj_matrix(W)
old_k = new_k
else:
# varied epsilon, fixed k
idx = order[:,:k]
dist = D[I, idx.T].T
old_i = np.zeros(D.shape[0], dtype=int)
for eps in epsilon:
for i, row in enumerate(dist):
oi = old_i[i]
ni = oi + np.searchsorted(row[oi:], eps)
rr = row[oi:ni]
W[i, idx[i,oi:ni]] = rr if is_weighted else 1
old_i[i] = ni
yield Graph.from_adj_matrix(W) | [
"def",
"incremental_neighbor_graph",
"(",
"X",
",",
"precomputed",
"=",
"False",
",",
"k",
"=",
"None",
",",
"epsilon",
"=",
"None",
",",
"weighting",
"=",
"'none'",
")",
":",
"assert",
"(",
"(",
"k",
"is",
"not",
"None",
")",
"or",
"(",
"epsilon",
"... | See neighbor_graph. | [
"See",
"neighbor_graph",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/construction/incremental.py#L11-L58 |
jbloomlab/phydms | phydmslib/file_io.py | Versions | def Versions():
"""Returns a string with version information.
You would call this function if you want a string giving detailed information
on the version of ``phydms`` and the associated packages that it uses.
"""
s = [\
'Version information:',
'\tTime and date: %s' % time.asctime(),
'\tPlatform: %s' % platform.platform(),
'\tPython version: %s' % sys.version.replace('\n', ' '),
'\tphydms version: %s' % phydmslib.__version__,
]
for modname in ['Bio', 'cython', 'numpy', 'scipy', 'matplotlib',
'natsort', 'sympy', 'six', 'pandas', 'pyvolve', 'statsmodels',
'weblogolib', 'PyPDF2']:
try:
v = importlib.import_module(modname).__version__
s.append('\t%s version: %s' % (modname, v))
except ImportError:
s.append('\t%s cannot be imported into Python' % modname)
return '\n'.join(s) | python | def Versions():
"""Returns a string with version information.
You would call this function if you want a string giving detailed information
on the version of ``phydms`` and the associated packages that it uses.
"""
s = [\
'Version information:',
'\tTime and date: %s' % time.asctime(),
'\tPlatform: %s' % platform.platform(),
'\tPython version: %s' % sys.version.replace('\n', ' '),
'\tphydms version: %s' % phydmslib.__version__,
]
for modname in ['Bio', 'cython', 'numpy', 'scipy', 'matplotlib',
'natsort', 'sympy', 'six', 'pandas', 'pyvolve', 'statsmodels',
'weblogolib', 'PyPDF2']:
try:
v = importlib.import_module(modname).__version__
s.append('\t%s version: %s' % (modname, v))
except ImportError:
s.append('\t%s cannot be imported into Python' % modname)
return '\n'.join(s) | [
"def",
"Versions",
"(",
")",
":",
"s",
"=",
"[",
"'Version information:'",
",",
"'\\tTime and date: %s'",
"%",
"time",
".",
"asctime",
"(",
")",
",",
"'\\tPlatform: %s'",
"%",
"platform",
".",
"platform",
"(",
")",
",",
"'\\tPython version: %s'",
"%",
"sys",
... | Returns a string with version information.
You would call this function if you want a string giving detailed information
on the version of ``phydms`` and the associated packages that it uses. | [
"Returns",
"a",
"string",
"with",
"version",
"information",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/file_io.py#L22-L43 |
jbloomlab/phydms | phydmslib/file_io.py | ReadCodonAlignment | def ReadCodonAlignment(fastafile, checknewickvalid):
"""Reads codon alignment from file.
*fastafile* is the name of an existing FASTA file.
*checknewickvalid* : if *True*, we require that names are unique and do
**not** contain spaces, commas, colons, semicolons, parentheses, square
brackets, or single or double quotation marks.
If any of these disallowed characters are present, raises an Exception.
Reads the alignment from the *fastafile* and returns the aligned
sequences as a list of 2-tuple of strings *(header, sequence)*
where *sequence* is upper case.
If the terminal codon is a stop codon for **all** sequences, then
this terminal codon is trimmed. Raises an exception if the sequences
are not aligned codon sequences that are free of stop codons (with
the exception of a shared terminal stop) and free of ambiguous nucleotides.
Read aligned sequences in this example:
>>> seqs = [('seq1', 'ATGGAA'), ('seq2', 'ATGAAA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> seqs == a
True
Trim stop codons from all sequences in this example:
>>> seqs = [('seq1', 'ATGTAA'), ('seq2', 'ATGTGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> [(head, seq[ : -3]) for (head, seq) in seqs] == a
True
Read sequences with gap:
>>> seqs = [('seq1', 'ATG---'), ('seq2', 'ATGAGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> [(head, seq) for (head, seq) in seqs] == a
True
Premature stop codon gives error:
>>> seqs = [('seq1', 'TGAATG'), ('seq2', 'ATGAGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError:
"""
codonmatch = re.compile('^[ATCG]{3}$')
gapmatch = re.compile('^-+^')
seqs = [(seq.description.strip(), str(seq.seq).upper()) for seq
in Bio.SeqIO.parse(fastafile, 'fasta')]
assert seqs, "{0} failed to specify any sequences".format(fastafile)
seqlen = len(seqs[0][1])
if not all([len(seq) == seqlen for (head, seq) in seqs]):
raise ValueError(("All sequences in {0} are not of the same length; "
"they must not be properly aligned").format(fastafile))
if (seqlen < 3) or (seqlen % 3 != 0):
raise ValueError(("The length of the sequences in {0} is {1} which "
"is not divisible by 3; they are not valid codon sequences"
).format(fastafile, seqlen))
terminalcodon = []
codons_by_position = dict([(icodon, []) for icodon in range(seqlen // 3)])
for (head, seq) in seqs:
assert len(seq) % 3 == 0
for icodon in range(seqlen // 3):
codon = seq[3 * icodon : 3 * icodon + 3]
codons_by_position[icodon].append(codon)
if codonmatch.search(codon):
aa = str(Bio.Seq.Seq(codon).translate())
if aa == '*':
if icodon + 1 != len(seq) // 3:
raise ValueError(("In {0}, sequence {1}, non-terminal "
"codon {2} is stop codon: {3}").format(
fastafile, head, icodon + 1, codon))
elif codon == '---':
aa = '-'
else:
raise ValueError(("In {0}, sequence {1}, codon {2} is invalid: "
"{3}").format(fastafile, head, icodon + 1, codon))
terminalcodon.append(aa)
for (icodon, codonlist) in codons_by_position.items():
if all([codon == '---' for codon in codonlist]):
raise ValueError(("In {0}, all codons are gaps at position {1}"
).format(fastafile, icodon + 1))
if all([aa in ['*', '-'] for aa in terminalcodon]):
if len(seq) == 3:
raise ValueError(("The only codon is a terminal stop codon for "
"the sequences in {0}").format(fastafile))
seqs = [(head, seq[ : -3]) for (head, seq) in seqs]
elif any([aa == '*' for aa in terminalcodon]):
raise ValueError(("Only some sequences in {0} have a terminal stop "
"codon. All or none must have terminal stop.").format(fastafile))
if any([gapmatch.search(seq) for (head, seq) in seqs]):
raise ValueError(("In {0}, at least one sequence is entirely composed "
"of gaps.").format(fastafile))
if checknewickvalid:
if len(set([head for (head, seq) in seqs])) != len(seqs):
raise ValueError("Headers in {0} not all unique".format(fastafile))
disallowedheader = re.compile('[\s\:\;\(\)\[\]\,\'\"]')
for (head, seq) in seqs:
if disallowedheader.search(head):
raise ValueError(("Invalid character in header in {0}:"
"\n{2}").format(fastafile, head))
return seqs | python | def ReadCodonAlignment(fastafile, checknewickvalid):
"""Reads codon alignment from file.
*fastafile* is the name of an existing FASTA file.
*checknewickvalid* : if *True*, we require that names are unique and do
**not** contain spaces, commas, colons, semicolons, parentheses, square
brackets, or single or double quotation marks.
If any of these disallowed characters are present, raises an Exception.
Reads the alignment from the *fastafile* and returns the aligned
sequences as a list of 2-tuple of strings *(header, sequence)*
where *sequence* is upper case.
If the terminal codon is a stop codon for **all** sequences, then
this terminal codon is trimmed. Raises an exception if the sequences
are not aligned codon sequences that are free of stop codons (with
the exception of a shared terminal stop) and free of ambiguous nucleotides.
Read aligned sequences in this example:
>>> seqs = [('seq1', 'ATGGAA'), ('seq2', 'ATGAAA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> seqs == a
True
Trim stop codons from all sequences in this example:
>>> seqs = [('seq1', 'ATGTAA'), ('seq2', 'ATGTGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> [(head, seq[ : -3]) for (head, seq) in seqs] == a
True
Read sequences with gap:
>>> seqs = [('seq1', 'ATG---'), ('seq2', 'ATGAGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> [(head, seq) for (head, seq) in seqs] == a
True
Premature stop codon gives error:
>>> seqs = [('seq1', 'TGAATG'), ('seq2', 'ATGAGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError:
"""
codonmatch = re.compile('^[ATCG]{3}$')
gapmatch = re.compile('^-+^')
seqs = [(seq.description.strip(), str(seq.seq).upper()) for seq
in Bio.SeqIO.parse(fastafile, 'fasta')]
assert seqs, "{0} failed to specify any sequences".format(fastafile)
seqlen = len(seqs[0][1])
if not all([len(seq) == seqlen for (head, seq) in seqs]):
raise ValueError(("All sequences in {0} are not of the same length; "
"they must not be properly aligned").format(fastafile))
if (seqlen < 3) or (seqlen % 3 != 0):
raise ValueError(("The length of the sequences in {0} is {1} which "
"is not divisible by 3; they are not valid codon sequences"
).format(fastafile, seqlen))
terminalcodon = []
codons_by_position = dict([(icodon, []) for icodon in range(seqlen // 3)])
for (head, seq) in seqs:
assert len(seq) % 3 == 0
for icodon in range(seqlen // 3):
codon = seq[3 * icodon : 3 * icodon + 3]
codons_by_position[icodon].append(codon)
if codonmatch.search(codon):
aa = str(Bio.Seq.Seq(codon).translate())
if aa == '*':
if icodon + 1 != len(seq) // 3:
raise ValueError(("In {0}, sequence {1}, non-terminal "
"codon {2} is stop codon: {3}").format(
fastafile, head, icodon + 1, codon))
elif codon == '---':
aa = '-'
else:
raise ValueError(("In {0}, sequence {1}, codon {2} is invalid: "
"{3}").format(fastafile, head, icodon + 1, codon))
terminalcodon.append(aa)
for (icodon, codonlist) in codons_by_position.items():
if all([codon == '---' for codon in codonlist]):
raise ValueError(("In {0}, all codons are gaps at position {1}"
).format(fastafile, icodon + 1))
if all([aa in ['*', '-'] for aa in terminalcodon]):
if len(seq) == 3:
raise ValueError(("The only codon is a terminal stop codon for "
"the sequences in {0}").format(fastafile))
seqs = [(head, seq[ : -3]) for (head, seq) in seqs]
elif any([aa == '*' for aa in terminalcodon]):
raise ValueError(("Only some sequences in {0} have a terminal stop "
"codon. All or none must have terminal stop.").format(fastafile))
if any([gapmatch.search(seq) for (head, seq) in seqs]):
raise ValueError(("In {0}, at least one sequence is entirely composed "
"of gaps.").format(fastafile))
if checknewickvalid:
if len(set([head for (head, seq) in seqs])) != len(seqs):
raise ValueError("Headers in {0} not all unique".format(fastafile))
disallowedheader = re.compile('[\s\:\;\(\)\[\]\,\'\"]')
for (head, seq) in seqs:
if disallowedheader.search(head):
raise ValueError(("Invalid character in header in {0}:"
"\n{2}").format(fastafile, head))
return seqs | [
"def",
"ReadCodonAlignment",
"(",
"fastafile",
",",
"checknewickvalid",
")",
":",
"codonmatch",
"=",
"re",
".",
"compile",
"(",
"'^[ATCG]{3}$'",
")",
"gapmatch",
"=",
"re",
".",
"compile",
"(",
"'^-+^'",
")",
"seqs",
"=",
"[",
"(",
"seq",
".",
"description... | Reads codon alignment from file.
*fastafile* is the name of an existing FASTA file.
*checknewickvalid* : if *True*, we require that names are unique and do
**not** contain spaces, commas, colons, semicolons, parentheses, square
brackets, or single or double quotation marks.
If any of these disallowed characters are present, raises an Exception.
Reads the alignment from the *fastafile* and returns the aligned
sequences as a list of 2-tuple of strings *(header, sequence)*
where *sequence* is upper case.
If the terminal codon is a stop codon for **all** sequences, then
this terminal codon is trimmed. Raises an exception if the sequences
are not aligned codon sequences that are free of stop codons (with
the exception of a shared terminal stop) and free of ambiguous nucleotides.
Read aligned sequences in this example:
>>> seqs = [('seq1', 'ATGGAA'), ('seq2', 'ATGAAA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> seqs == a
True
Trim stop codons from all sequences in this example:
>>> seqs = [('seq1', 'ATGTAA'), ('seq2', 'ATGTGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> [(head, seq[ : -3]) for (head, seq) in seqs] == a
True
Read sequences with gap:
>>> seqs = [('seq1', 'ATG---'), ('seq2', 'ATGAGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True)
>>> [(head, seq) for (head, seq) in seqs] == a
True
Premature stop codon gives error:
>>> seqs = [('seq1', 'TGAATG'), ('seq2', 'ATGAGA')]
>>> f = io.StringIO()
>>> n = f.write(u'\\n'.join(['>{0}\\n{1}'.format(*tup) for tup in seqs]))
>>> n = f.seek(0)
>>> a = ReadCodonAlignment(f, True) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError: | [
"Reads",
"codon",
"alignment",
"from",
"file",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/file_io.py#L46-L168 |
jbloomlab/phydms | phydmslib/file_io.py | readPrefs | def readPrefs(prefsfile, minpref=0, avgprefs=False, randprefs=False,
seed=1, sites_as_strings=False):
"""Read preferences from file with some error checking.
Args:
`prefsfile` (string or readable file-like object)
File holding amino-acid preferences. Can be
comma-, space-, or tab-separated file with column
headers of `site` and then all one-letter amino-acid
codes, or can be in the more complex format written
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
Must be prefs for consecutively numbered sites starting at 1.
Stop codon prefs can be present (stop codons are indicated by
``*``); if so they are removed and prefs re-normalized to sum to 1.
`minpref` (float >= 0)
Adjust all preferences to be >= this number.
`avgprefs`, `randprefs` (bool)
Mutually exclusive options specifying to average or
randomize prefs across sites.
`seed` (int)
Seed used to sort random number generator for `randprefs`.
`sites_as_strings` (bool)
By default, the site numers are coerced to integers.
If this option is `True`, then they are kept as strings.
Returns:
`prefs` (dict)
`prefs[r][a]` is the preference of site `r` for amino-acid `a`.
`r` is an `int` unless `sites_as_strings=True`.
"""
assert minpref >= 0, 'minpref must be >= 0'
aas = set(phydmslib.constants.AA_TO_INDEX.keys())
try:
df = pandas.read_csv(prefsfile, sep=None, engine='python')
pandasformat = True
except ValueError:
pandasformat = False
if pandasformat and (set(df.columns) == aas.union(set(['site'])) or
set(df.columns) == aas.union(set(['site', '*']))):
# read valid preferences as data frame
sites = df['site'].tolist()
prefs = {}
for r in sites:
rdf = df[df['site'] == r]
prefs[r] = {}
for aa in df.columns:
if aa != 'site':
prefs[r][aa] = float(rdf[aa])
else:
# try reading as dms_tools format
prefs = phydmslib.file_io.readPrefs_dms_tools_format(prefsfile)[2]
sites = list(prefs.keys())
# error check prefs
if not sites_as_strings:
try:
sites = [int(r) for r in sites]
except ValueError:
raise ValueError("sites not int in prefsfile {0}".format(prefsfile))
assert (min(sites) == 1 and max(sites) - min(sites) == len(sites) - 1),\
"Sites not consecutive starting at 1"
prefs = dict([(int(r), rprefs) for (r, rprefs) in prefs.items()])
else:
sites = [str(r) for r in sites]
prefs = dict([(str(r), rprefs) for (r, rprefs) in prefs.items()])
assert len(set(sites)) == len(sites), "Non-unique sites in prefsfiles"
assert all([all([pi >= 0 for pi in rprefs.values()]) for rprefs in
prefs.values()]), "prefs < 0 in prefsfile {0}".format(prefsfile)
for r in list(prefs.keys()):
rprefs = prefs[r]
assert sum(rprefs.values()) - 1 <= 0.01, (
"Prefs in prefsfile {0} don't sum to one".format(prefsfile))
if '*' in rprefs:
del rprefs['*']
assert aas == set(rprefs.keys()), ("prefsfile {0} does not include "
"all amino acids at site {1}").format(prefsfile, r)
rsum = float(sum(rprefs.values()))
prefs[r] = dict([(aa, pi / rsum) for (aa, pi) in rprefs.items()])
assert set(sites) == set(prefs.keys())
# Iteratively adjust until all prefs exceed minpref after re-scaling.
for r in list(prefs.keys()):
rprefs = prefs[r]
iterations = 0
while any([pi < minpref for pi in rprefs.values()]):
rprefs = dict([(aa, max(1.1 * minpref,
pi)) for (aa, pi) in rprefs.items()])
newsum = float(sum(rprefs.values()))
rprefs = dict([(aa, pi / newsum) for (aa, pi) in rprefs.items()])
iterations += 1
assert iterations <= 3, "minpref adjustment not converging."
prefs[r] = rprefs
if randprefs:
assert not avgprefs, "randprefs and avgprefs are incompatible"
random.seed(seed)
sites = sorted([r for r in prefs.keys()])
prefs = [prefs[r] for r in sites]
random.shuffle(sites)
prefs = dict(zip(sites, prefs))
elif avgprefs:
avg_prefs = dict([(aa, 0.0) for aa in aas])
for rprefs in prefs.values():
for aa in aas:
avg_prefs[aa] += rprefs[aa]
for aa in aas:
avg_prefs[aa] /= float(len(prefs))
for r in list(prefs.keys()):
prefs[r] = avg_prefs
return prefs | python | def readPrefs(prefsfile, minpref=0, avgprefs=False, randprefs=False,
seed=1, sites_as_strings=False):
"""Read preferences from file with some error checking.
Args:
`prefsfile` (string or readable file-like object)
File holding amino-acid preferences. Can be
comma-, space-, or tab-separated file with column
headers of `site` and then all one-letter amino-acid
codes, or can be in the more complex format written
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
Must be prefs for consecutively numbered sites starting at 1.
Stop codon prefs can be present (stop codons are indicated by
``*``); if so they are removed and prefs re-normalized to sum to 1.
`minpref` (float >= 0)
Adjust all preferences to be >= this number.
`avgprefs`, `randprefs` (bool)
Mutually exclusive options specifying to average or
randomize prefs across sites.
`seed` (int)
Seed used to sort random number generator for `randprefs`.
`sites_as_strings` (bool)
By default, the site numers are coerced to integers.
If this option is `True`, then they are kept as strings.
Returns:
`prefs` (dict)
`prefs[r][a]` is the preference of site `r` for amino-acid `a`.
`r` is an `int` unless `sites_as_strings=True`.
"""
assert minpref >= 0, 'minpref must be >= 0'
aas = set(phydmslib.constants.AA_TO_INDEX.keys())
try:
df = pandas.read_csv(prefsfile, sep=None, engine='python')
pandasformat = True
except ValueError:
pandasformat = False
if pandasformat and (set(df.columns) == aas.union(set(['site'])) or
set(df.columns) == aas.union(set(['site', '*']))):
# read valid preferences as data frame
sites = df['site'].tolist()
prefs = {}
for r in sites:
rdf = df[df['site'] == r]
prefs[r] = {}
for aa in df.columns:
if aa != 'site':
prefs[r][aa] = float(rdf[aa])
else:
# try reading as dms_tools format
prefs = phydmslib.file_io.readPrefs_dms_tools_format(prefsfile)[2]
sites = list(prefs.keys())
# error check prefs
if not sites_as_strings:
try:
sites = [int(r) for r in sites]
except ValueError:
raise ValueError("sites not int in prefsfile {0}".format(prefsfile))
assert (min(sites) == 1 and max(sites) - min(sites) == len(sites) - 1),\
"Sites not consecutive starting at 1"
prefs = dict([(int(r), rprefs) for (r, rprefs) in prefs.items()])
else:
sites = [str(r) for r in sites]
prefs = dict([(str(r), rprefs) for (r, rprefs) in prefs.items()])
assert len(set(sites)) == len(sites), "Non-unique sites in prefsfiles"
assert all([all([pi >= 0 for pi in rprefs.values()]) for rprefs in
prefs.values()]), "prefs < 0 in prefsfile {0}".format(prefsfile)
for r in list(prefs.keys()):
rprefs = prefs[r]
assert sum(rprefs.values()) - 1 <= 0.01, (
"Prefs in prefsfile {0} don't sum to one".format(prefsfile))
if '*' in rprefs:
del rprefs['*']
assert aas == set(rprefs.keys()), ("prefsfile {0} does not include "
"all amino acids at site {1}").format(prefsfile, r)
rsum = float(sum(rprefs.values()))
prefs[r] = dict([(aa, pi / rsum) for (aa, pi) in rprefs.items()])
assert set(sites) == set(prefs.keys())
# Iteratively adjust until all prefs exceed minpref after re-scaling.
for r in list(prefs.keys()):
rprefs = prefs[r]
iterations = 0
while any([pi < minpref for pi in rprefs.values()]):
rprefs = dict([(aa, max(1.1 * minpref,
pi)) for (aa, pi) in rprefs.items()])
newsum = float(sum(rprefs.values()))
rprefs = dict([(aa, pi / newsum) for (aa, pi) in rprefs.items()])
iterations += 1
assert iterations <= 3, "minpref adjustment not converging."
prefs[r] = rprefs
if randprefs:
assert not avgprefs, "randprefs and avgprefs are incompatible"
random.seed(seed)
sites = sorted([r for r in prefs.keys()])
prefs = [prefs[r] for r in sites]
random.shuffle(sites)
prefs = dict(zip(sites, prefs))
elif avgprefs:
avg_prefs = dict([(aa, 0.0) for aa in aas])
for rprefs in prefs.values():
for aa in aas:
avg_prefs[aa] += rprefs[aa]
for aa in aas:
avg_prefs[aa] /= float(len(prefs))
for r in list(prefs.keys()):
prefs[r] = avg_prefs
return prefs | [
"def",
"readPrefs",
"(",
"prefsfile",
",",
"minpref",
"=",
"0",
",",
"avgprefs",
"=",
"False",
",",
"randprefs",
"=",
"False",
",",
"seed",
"=",
"1",
",",
"sites_as_strings",
"=",
"False",
")",
":",
"assert",
"minpref",
">=",
"0",
",",
"'minpref must be ... | Read preferences from file with some error checking.
Args:
`prefsfile` (string or readable file-like object)
File holding amino-acid preferences. Can be
comma-, space-, or tab-separated file with column
headers of `site` and then all one-letter amino-acid
codes, or can be in the more complex format written
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
Must be prefs for consecutively numbered sites starting at 1.
Stop codon prefs can be present (stop codons are indicated by
``*``); if so they are removed and prefs re-normalized to sum to 1.
`minpref` (float >= 0)
Adjust all preferences to be >= this number.
`avgprefs`, `randprefs` (bool)
Mutually exclusive options specifying to average or
randomize prefs across sites.
`seed` (int)
Seed used to sort random number generator for `randprefs`.
`sites_as_strings` (bool)
By default, the site numers are coerced to integers.
If this option is `True`, then they are kept as strings.
Returns:
`prefs` (dict)
`prefs[r][a]` is the preference of site `r` for amino-acid `a`.
`r` is an `int` unless `sites_as_strings=True`. | [
"Read",
"preferences",
"from",
"file",
"with",
"some",
"error",
"checking",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/file_io.py#L171-L284 |
jbloomlab/phydms | phydmslib/file_io.py | readPrefs_dms_tools_format | def readPrefs_dms_tools_format(f):
"""Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
This is an exact copy of the same code from
`dms_tools.file_io.ReadPreferences`. It is copied because
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_ is currently
only compatible with `python2`, and we needed something that also works
with `python3`.
*f* is the name of an existing file or a readable file-like object.
It should be in the format written by
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
The return value is the tuple: *(sites, wts, pi_means, pi_95credint, h)*
where *sites*, *wts*, *pi_means*, and *pi_95credint* will all
have the same values used to write the file with *WritePreferences*,
and *h* is a dictionary with *h[r]* giving the site entropy (log base
2) for each *r* in *sites*.
"""
charmatch = re.compile('^PI_([A-z\*\-]+)$')
if isinstance(f, str):
f = open(f)
lines = f.readlines()
f.close()
else:
lines = f.readlines()
characters = []
sites = []
wts = {}
pi_means = {}
pi_95credint = {}
h = {}
for line in lines:
if line.isspace():
continue
elif line[0] == '#' and not characters:
entries = line[1 : ].strip().split()
if len(entries) < 4:
raise ValueError("Insufficient entries in header:\n%s" % line)
if not (entries[0] in ['POSITION', 'SITE'] and entries[1][ : 2] == 'WT' and entries[2] == 'SITE_ENTROPY'):
raise ValueError("Not the correct first three header columns:\n%s" % line)
i = 3
while i < len(entries) and charmatch.search(entries[i]):
characters.append(charmatch.search(entries[i]).group(1))
i += 1
if i == len(entries):
pi_95credint = None
linelength = len(characters) + 3
else:
if not len(entries) - i == len(characters):
raise ValueError("Header line does not have valid credible interval format:\n%s" % line)
if not all([entries[i + j] == 'PI_%s_95' % characters[j] for j in range(len(characters))]):
raise ValueError("mean and credible interval character mismatch in header:\n%s" % line)
linelength = 2 * len(characters) + 3
elif line[0] == '#':
continue
elif not characters:
raise ValueError("Found data lines before encountering a valid header")
else:
entries = line.strip().split()
if len(entries) != linelength:
raise ValueError("Line does not have expected %d entries:\n%s" % (linelength, line))
r = entries[0]
assert r not in sites, "Duplicate site of %s" % r
sites.append(r)
wts[r] = entries[1]
assert entries[1] in characters or entries[1] == '?', "Character %s is not one of the valid ones in header. Valid possibilities: %s" % (entries[1], ', '.join(characters))
h[r] = float(entries[2])
pi_means[r] = dict([(x, float(entries[3 + i])) for (i, x) in enumerate(characters)])
if pi_95credint != None:
pi_95credint[r] = dict([(x, (float(entries[3 + len(characters) + i].split(',')[0]), float(entries[3 + len(characters) + i].split(',')[1]))) for (i, x) in enumerate(characters)])
return (sites, wts, pi_means, pi_95credint, h) | python | def readPrefs_dms_tools_format(f):
"""Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
This is an exact copy of the same code from
`dms_tools.file_io.ReadPreferences`. It is copied because
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_ is currently
only compatible with `python2`, and we needed something that also works
with `python3`.
*f* is the name of an existing file or a readable file-like object.
It should be in the format written by
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
The return value is the tuple: *(sites, wts, pi_means, pi_95credint, h)*
where *sites*, *wts*, *pi_means*, and *pi_95credint* will all
have the same values used to write the file with *WritePreferences*,
and *h* is a dictionary with *h[r]* giving the site entropy (log base
2) for each *r* in *sites*.
"""
charmatch = re.compile('^PI_([A-z\*\-]+)$')
if isinstance(f, str):
f = open(f)
lines = f.readlines()
f.close()
else:
lines = f.readlines()
characters = []
sites = []
wts = {}
pi_means = {}
pi_95credint = {}
h = {}
for line in lines:
if line.isspace():
continue
elif line[0] == '#' and not characters:
entries = line[1 : ].strip().split()
if len(entries) < 4:
raise ValueError("Insufficient entries in header:\n%s" % line)
if not (entries[0] in ['POSITION', 'SITE'] and entries[1][ : 2] == 'WT' and entries[2] == 'SITE_ENTROPY'):
raise ValueError("Not the correct first three header columns:\n%s" % line)
i = 3
while i < len(entries) and charmatch.search(entries[i]):
characters.append(charmatch.search(entries[i]).group(1))
i += 1
if i == len(entries):
pi_95credint = None
linelength = len(characters) + 3
else:
if not len(entries) - i == len(characters):
raise ValueError("Header line does not have valid credible interval format:\n%s" % line)
if not all([entries[i + j] == 'PI_%s_95' % characters[j] for j in range(len(characters))]):
raise ValueError("mean and credible interval character mismatch in header:\n%s" % line)
linelength = 2 * len(characters) + 3
elif line[0] == '#':
continue
elif not characters:
raise ValueError("Found data lines before encountering a valid header")
else:
entries = line.strip().split()
if len(entries) != linelength:
raise ValueError("Line does not have expected %d entries:\n%s" % (linelength, line))
r = entries[0]
assert r not in sites, "Duplicate site of %s" % r
sites.append(r)
wts[r] = entries[1]
assert entries[1] in characters or entries[1] == '?', "Character %s is not one of the valid ones in header. Valid possibilities: %s" % (entries[1], ', '.join(characters))
h[r] = float(entries[2])
pi_means[r] = dict([(x, float(entries[3 + i])) for (i, x) in enumerate(characters)])
if pi_95credint != None:
pi_95credint[r] = dict([(x, (float(entries[3 + len(characters) + i].split(',')[0]), float(entries[3 + len(characters) + i].split(',')[1]))) for (i, x) in enumerate(characters)])
return (sites, wts, pi_means, pi_95credint, h) | [
"def",
"readPrefs_dms_tools_format",
"(",
"f",
")",
":",
"charmatch",
"=",
"re",
".",
"compile",
"(",
"'^PI_([A-z\\*\\-]+)$'",
")",
"if",
"isinstance",
"(",
"f",
",",
"str",
")",
":",
"f",
"=",
"open",
"(",
"f",
")",
"lines",
"=",
"f",
".",
"readlines"... | Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
This is an exact copy of the same code from
`dms_tools.file_io.ReadPreferences`. It is copied because
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_ is currently
only compatible with `python2`, and we needed something that also works
with `python3`.
*f* is the name of an existing file or a readable file-like object.
It should be in the format written by
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
The return value is the tuple: *(sites, wts, pi_means, pi_95credint, h)*
where *sites*, *wts*, *pi_means*, and *pi_95credint* will all
have the same values used to write the file with *WritePreferences*,
and *h* is a dictionary with *h[r]* giving the site entropy (log base
2) for each *r* in *sites*. | [
"Reads",
"the",
"amino",
"-",
"acid",
"preferences",
"written",
"by",
"dms_tools",
"v1",
"<http",
":",
"//",
"jbloomlab",
".",
"github",
".",
"io",
"/",
"dms_tools",
"/",
">",
"_",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/file_io.py#L287-L358 |
jbloomlab/phydms | phydmslib/file_io.py | readDivPressure | def readDivPressure(fileName):
"""Reads in diversifying pressures from some file.
Scale diversifying pressure values so absolute value of the max value is 1,
unless all values are zero.
Args:
`fileName` (string or readable file-like object)
File holding diversifying pressure values. Can be
comma-, space-, or tab-separated file. The first column
is the site (consecutively numbered, sites starting
with one) and the second column is the diversifying pressure values.
Returns:
`divPressure` (dict keyed by ints)
`divPressure[r][v]` is the diversifying pressure value of site `r`.
"""
try:
df = pandas.read_csv(fileName, sep=None, engine='python')
pandasformat = True
except ValueError:
pandasformat = False
df.columns = ['site', 'divPressureValue']
scaleFactor = max(df["divPressureValue"].abs())
if scaleFactor > 0:
df["divPressureValue"] = [x / scaleFactor for x in df["divPressureValue"]]
assert len(df['site'].tolist()) == len(set(df['site'].tolist())),"There is at least one non-unique site in {0}".format(fileName)
assert max(df["divPressureValue"].abs()) <= 1, "The scaling produced a diversifying pressure value with an absolute value greater than one."
sites = df['site'].tolist()
divPressure = {}
for r in sites:
divPressure[r] = df[df['site'] == r]["divPressureValue"].tolist()[0]
return divPressure | python | def readDivPressure(fileName):
"""Reads in diversifying pressures from some file.
Scale diversifying pressure values so absolute value of the max value is 1,
unless all values are zero.
Args:
`fileName` (string or readable file-like object)
File holding diversifying pressure values. Can be
comma-, space-, or tab-separated file. The first column
is the site (consecutively numbered, sites starting
with one) and the second column is the diversifying pressure values.
Returns:
`divPressure` (dict keyed by ints)
`divPressure[r][v]` is the diversifying pressure value of site `r`.
"""
try:
df = pandas.read_csv(fileName, sep=None, engine='python')
pandasformat = True
except ValueError:
pandasformat = False
df.columns = ['site', 'divPressureValue']
scaleFactor = max(df["divPressureValue"].abs())
if scaleFactor > 0:
df["divPressureValue"] = [x / scaleFactor for x in df["divPressureValue"]]
assert len(df['site'].tolist()) == len(set(df['site'].tolist())),"There is at least one non-unique site in {0}".format(fileName)
assert max(df["divPressureValue"].abs()) <= 1, "The scaling produced a diversifying pressure value with an absolute value greater than one."
sites = df['site'].tolist()
divPressure = {}
for r in sites:
divPressure[r] = df[df['site'] == r]["divPressureValue"].tolist()[0]
return divPressure | [
"def",
"readDivPressure",
"(",
"fileName",
")",
":",
"try",
":",
"df",
"=",
"pandas",
".",
"read_csv",
"(",
"fileName",
",",
"sep",
"=",
"None",
",",
"engine",
"=",
"'python'",
")",
"pandasformat",
"=",
"True",
"except",
"ValueError",
":",
"pandasformat",
... | Reads in diversifying pressures from some file.
Scale diversifying pressure values so absolute value of the max value is 1,
unless all values are zero.
Args:
`fileName` (string or readable file-like object)
File holding diversifying pressure values. Can be
comma-, space-, or tab-separated file. The first column
is the site (consecutively numbered, sites starting
with one) and the second column is the diversifying pressure values.
Returns:
`divPressure` (dict keyed by ints)
`divPressure[r][v]` is the diversifying pressure value of site `r`. | [
"Reads",
"in",
"diversifying",
"pressures",
"from",
"some",
"file",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/file_io.py#L360-L392 |
stbraun/fuzzing | run_fuzzer.py | load_configuration | def load_configuration(conf_path):
"""Load and validate test configuration.
:param conf_path: path to YAML configuration file.
:return: configuration as dict.
"""
with open(conf_path) as f:
conf_dict = yaml.load(f)
validate_config(conf_dict)
return conf_dict | python | def load_configuration(conf_path):
"""Load and validate test configuration.
:param conf_path: path to YAML configuration file.
:return: configuration as dict.
"""
with open(conf_path) as f:
conf_dict = yaml.load(f)
validate_config(conf_dict)
return conf_dict | [
"def",
"load_configuration",
"(",
"conf_path",
")",
":",
"with",
"open",
"(",
"conf_path",
")",
"as",
"f",
":",
"conf_dict",
"=",
"yaml",
".",
"load",
"(",
"f",
")",
"validate_config",
"(",
"conf_dict",
")",
"return",
"conf_dict"
] | Load and validate test configuration.
:param conf_path: path to YAML configuration file.
:return: configuration as dict. | [
"Load",
"and",
"validate",
"test",
"configuration",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/run_fuzzer.py#L61-L70 |
stbraun/fuzzing | run_fuzzer.py | validate_config | def validate_config(conf_dict):
"""Validate configuration.
:param conf_dict: test configuration.
:type conf_dict: {}
:raise InvalidConfigurationError:
"""
# TASK improve validation
if APPLICATIONS not in conf_dict.keys():
raise InvalidConfigurationError('Missing application configuration.')
if SEED_FILES not in conf_dict.keys():
raise InvalidConfigurationError('Missing seed file configuration.')
if RUNS not in conf_dict.keys():
conf_dict[RUNS] = DEFAULT_RUNS
if PROCESSES not in conf_dict.keys():
conf_dict[PROCESSES] = DEFAULT_PROCESSES
if PROCESSORS not in conf_dict.keys():
conf_dict[PROCESSORS] = DEFAULT_PROCESSORS
return | python | def validate_config(conf_dict):
"""Validate configuration.
:param conf_dict: test configuration.
:type conf_dict: {}
:raise InvalidConfigurationError:
"""
# TASK improve validation
if APPLICATIONS not in conf_dict.keys():
raise InvalidConfigurationError('Missing application configuration.')
if SEED_FILES not in conf_dict.keys():
raise InvalidConfigurationError('Missing seed file configuration.')
if RUNS not in conf_dict.keys():
conf_dict[RUNS] = DEFAULT_RUNS
if PROCESSES not in conf_dict.keys():
conf_dict[PROCESSES] = DEFAULT_PROCESSES
if PROCESSORS not in conf_dict.keys():
conf_dict[PROCESSORS] = DEFAULT_PROCESSORS
return | [
"def",
"validate_config",
"(",
"conf_dict",
")",
":",
"# TASK improve validation",
"if",
"APPLICATIONS",
"not",
"in",
"conf_dict",
".",
"keys",
"(",
")",
":",
"raise",
"InvalidConfigurationError",
"(",
"'Missing application configuration.'",
")",
"if",
"SEED_FILES",
"... | Validate configuration.
:param conf_dict: test configuration.
:type conf_dict: {}
:raise InvalidConfigurationError: | [
"Validate",
"configuration",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/run_fuzzer.py#L73-L91 |
stbraun/fuzzing | run_fuzzer.py | main | def main():
"""Read configuration and execute test runs."""
parser = argparse.ArgumentParser(description='Stress test applications.')
parser.add_argument('config_path', help='Path to configuration file.')
args = parser.parse_args()
try:
configuration = load_configuration(args.config_path)
except InvalidConfigurationError:
print("\nConfiguration is not valid.")
print('Example:\n{}'.format(help_configuration))
return 1
print("Starting up ...")
futures = []
with ProcessPoolExecutor(configuration[PROCESSORS]) as executor:
for _ in range(configuration[PROCESSES]):
futures.append(executor.submit(execute_test, configuration))
print("... finished")
test_stats = combine_test_stats([f.result() for f in futures])
show_test_stats(test_stats)
return 0 | python | def main():
"""Read configuration and execute test runs."""
parser = argparse.ArgumentParser(description='Stress test applications.')
parser.add_argument('config_path', help='Path to configuration file.')
args = parser.parse_args()
try:
configuration = load_configuration(args.config_path)
except InvalidConfigurationError:
print("\nConfiguration is not valid.")
print('Example:\n{}'.format(help_configuration))
return 1
print("Starting up ...")
futures = []
with ProcessPoolExecutor(configuration[PROCESSORS]) as executor:
for _ in range(configuration[PROCESSES]):
futures.append(executor.submit(execute_test, configuration))
print("... finished")
test_stats = combine_test_stats([f.result() for f in futures])
show_test_stats(test_stats)
return 0 | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Stress test applications.'",
")",
"parser",
".",
"add_argument",
"(",
"'config_path'",
",",
"help",
"=",
"'Path to configuration file.'",
")",
"args",
"=",
... | Read configuration and execute test runs. | [
"Read",
"configuration",
"and",
"execute",
"test",
"runs",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/run_fuzzer.py#L135-L154 |
hayd/ctox | ctox/main.py | main | def main(arguments, toxinidir=None):
"ctox: tox with conda."
try: # pragma: no cover
# Exit on broken pipe.
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError: # pragma: no cover
# SIGPIPE is not available on Windows.
pass
try:
import sys
sys.exit(ctox(arguments, toxinidir))
except CalledProcessError as c:
print(c.output)
return 1
except NotImplementedError as e:
gh = "https://github.com/hayd/ctox/issues"
from colorama import Style
cprint(Style.BRIGHT + str(e), 'err')
cprint("If this is a valid tox.ini substitution, please open an issue on\n"
"github and request support: %s." % gh, 'warn')
return 1
except KeyboardInterrupt: # pragma: no cover
return 1 | python | def main(arguments, toxinidir=None):
"ctox: tox with conda."
try: # pragma: no cover
# Exit on broken pipe.
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError: # pragma: no cover
# SIGPIPE is not available on Windows.
pass
try:
import sys
sys.exit(ctox(arguments, toxinidir))
except CalledProcessError as c:
print(c.output)
return 1
except NotImplementedError as e:
gh = "https://github.com/hayd/ctox/issues"
from colorama import Style
cprint(Style.BRIGHT + str(e), 'err')
cprint("If this is a valid tox.ini substitution, please open an issue on\n"
"github and request support: %s." % gh, 'warn')
return 1
except KeyboardInterrupt: # pragma: no cover
return 1 | [
"def",
"main",
"(",
"arguments",
",",
"toxinidir",
"=",
"None",
")",
":",
"try",
":",
"# pragma: no cover",
"# Exit on broken pipe.",
"import",
"signal",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
"signal",
".",
"SIG_DFL",
")",
"except",
"A... | ctox: tox with conda. | [
"ctox",
":",
"tox",
"with",
"conda",
"."
] | train | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/main.py#L159-L186 |
hayd/ctox | ctox/main.py | ctox | def ctox(arguments, toxinidir):
"""Sets up conda environments, and sets up and runs each environment based
on the project's tox.ini configuration file.
Returns 1 if either the build or running the commands failed or 0 if
all commmands ran successfully.
"""
if arguments is None:
arguments = []
if toxinidir is None:
toxinidir = os.getcwd()
args, options = parse_args(arguments)
if args.version:
print(version)
return 0
# if no conda trigger OSError
try:
with open(os.devnull, "w") as fnull:
check_output(['conda', '--version'], stderr=fnull)
except OSError:
cprint("conda not found, you need to install it to use ctox.\n"
"The recommended way is to download miniconda,\n"
"Do not install conda via pip.", 'err')
return 1
toxinifile = os.path.join(toxinidir, "tox.ini")
from ctox.config import read_config, get_envlist
config = read_config(toxinifile)
if args.e == 'ALL':
envlist = get_envlist(config)
else:
envlist = args.e.split(',')
# TODO configure with option
toxdir = os.path.join(toxinidir, ".tox")
# create a zip file for the project
from ctox.pkg import make_dist, package_name
cprint("GLOB sdist-make: %s" % os.path.join(toxinidir, "setup.py"))
package = package_name(toxinidir)
if not make_dist(toxinidir, toxdir, package):
cprint(" setup.py sdist failed", 'err')
return 1
# setup each environment and run ctox
failing = {}
for env_name in envlist:
env = Env(name=env_name, config=config, options=options,
toxdir=toxdir, toxinidir=toxinidir, package=package)
failing[env_name] = env.ctox()
# print summary of the outcomes of ctox for each environment
cprint('Summary')
print("-" * 23)
for env_name in envlist:
n = failing[env_name]
outcome = ('succeeded', 'failed', 'skipped')[n]
status = ('ok', 'err', 'warn')[n]
cprint("%s commands %s" % (env_name, outcome), status)
return any(1 == v for v in failing.values()) | python | def ctox(arguments, toxinidir):
"""Sets up conda environments, and sets up and runs each environment based
on the project's tox.ini configuration file.
Returns 1 if either the build or running the commands failed or 0 if
all commmands ran successfully.
"""
if arguments is None:
arguments = []
if toxinidir is None:
toxinidir = os.getcwd()
args, options = parse_args(arguments)
if args.version:
print(version)
return 0
# if no conda trigger OSError
try:
with open(os.devnull, "w") as fnull:
check_output(['conda', '--version'], stderr=fnull)
except OSError:
cprint("conda not found, you need to install it to use ctox.\n"
"The recommended way is to download miniconda,\n"
"Do not install conda via pip.", 'err')
return 1
toxinifile = os.path.join(toxinidir, "tox.ini")
from ctox.config import read_config, get_envlist
config = read_config(toxinifile)
if args.e == 'ALL':
envlist = get_envlist(config)
else:
envlist = args.e.split(',')
# TODO configure with option
toxdir = os.path.join(toxinidir, ".tox")
# create a zip file for the project
from ctox.pkg import make_dist, package_name
cprint("GLOB sdist-make: %s" % os.path.join(toxinidir, "setup.py"))
package = package_name(toxinidir)
if not make_dist(toxinidir, toxdir, package):
cprint(" setup.py sdist failed", 'err')
return 1
# setup each environment and run ctox
failing = {}
for env_name in envlist:
env = Env(name=env_name, config=config, options=options,
toxdir=toxdir, toxinidir=toxinidir, package=package)
failing[env_name] = env.ctox()
# print summary of the outcomes of ctox for each environment
cprint('Summary')
print("-" * 23)
for env_name in envlist:
n = failing[env_name]
outcome = ('succeeded', 'failed', 'skipped')[n]
status = ('ok', 'err', 'warn')[n]
cprint("%s commands %s" % (env_name, outcome), status)
return any(1 == v for v in failing.values()) | [
"def",
"ctox",
"(",
"arguments",
",",
"toxinidir",
")",
":",
"if",
"arguments",
"is",
"None",
":",
"arguments",
"=",
"[",
"]",
"if",
"toxinidir",
"is",
"None",
":",
"toxinidir",
"=",
"os",
".",
"getcwd",
"(",
")",
"args",
",",
"options",
"=",
"parse_... | Sets up conda environments, and sets up and runs each environment based
on the project's tox.ini configuration file.
Returns 1 if either the build or running the commands failed or 0 if
all commmands ran successfully. | [
"Sets",
"up",
"conda",
"environments",
"and",
"sets",
"up",
"and",
"runs",
"each",
"environment",
"based",
"on",
"the",
"project",
"s",
"tox",
".",
"ini",
"configuration",
"file",
"."
] | train | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/main.py#L206-L271 |
hayd/ctox | ctox/main.py | positional_args | def positional_args(arguments):
""""Generator for position arguments.
Example
-------
>>> list(positional_args(["arg1", "arg2", "--kwarg"]))
["arg1", "arg2"]
>>> list(positional_args(["--", "arg1", "--kwarg"]))
["arg1", "kwarg"]
"""
# TODO this behaviour probably isn't quite right.
if arguments and arguments[0] == '--':
for a in arguments[1:]:
yield a
else:
for a in arguments:
if a.startswith('-'):
break
yield a | python | def positional_args(arguments):
""""Generator for position arguments.
Example
-------
>>> list(positional_args(["arg1", "arg2", "--kwarg"]))
["arg1", "arg2"]
>>> list(positional_args(["--", "arg1", "--kwarg"]))
["arg1", "kwarg"]
"""
# TODO this behaviour probably isn't quite right.
if arguments and arguments[0] == '--':
for a in arguments[1:]:
yield a
else:
for a in arguments:
if a.startswith('-'):
break
yield a | [
"def",
"positional_args",
"(",
"arguments",
")",
":",
"# TODO this behaviour probably isn't quite right.",
"if",
"arguments",
"and",
"arguments",
"[",
"0",
"]",
"==",
"'--'",
":",
"for",
"a",
"in",
"arguments",
"[",
"1",
":",
"]",
":",
"yield",
"a",
"else",
... | Generator for position arguments.
Example
-------
>>> list(positional_args(["arg1", "arg2", "--kwarg"]))
["arg1", "arg2"]
>>> list(positional_args(["--", "arg1", "--kwarg"]))
["arg1", "kwarg"] | [
"Generator",
"for",
"position",
"arguments",
"."
] | train | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/main.py#L274-L293 |
hayd/ctox | ctox/main.py | _main | def _main():
"ctox: tox with conda"
from sys import argv
arguments = argv[1:]
toxinidir = os.getcwd()
return main(arguments, toxinidir) | python | def _main():
"ctox: tox with conda"
from sys import argv
arguments = argv[1:]
toxinidir = os.getcwd()
return main(arguments, toxinidir) | [
"def",
"_main",
"(",
")",
":",
"from",
"sys",
"import",
"argv",
"arguments",
"=",
"argv",
"[",
"1",
":",
"]",
"toxinidir",
"=",
"os",
".",
"getcwd",
"(",
")",
"return",
"main",
"(",
"arguments",
",",
"toxinidir",
")"
] | ctox: tox with conda | [
"ctox",
":",
"tox",
"with",
"conda"
] | train | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/main.py#L296-L303 |
hayd/ctox | ctox/main.py | Env.ctox | def ctox(self):
"""Main method for the environment.
Parse the tox.ini config, install the dependancies and run the
commands. The output of the commands is printed.
Returns 0 if they ran successfully, 1 if there was an error
(either in setup or whilst running the commands), 2 if the build
was skipped.
"""
# TODO make this less of a hack e.g. using basepython from config
# if it exists (and use an attribute directly).
if self.name[:4] not in SUPPORTED_ENVS:
from colorama import Style
cprint(Style.BRIGHT +
"Skipping unsupported python version %s\n" % self.name,
'warn')
return 2
# TODO don't remove env if there's a dependancy mis-match
# rather "clean" it to the empty state (the hope being to keep
# the dist build around - so not all files need to be rebuilt)
# TODO extract this as a method (for readability)
if not self.env_exists() or self.reusableable():
cprint("%s create: %s" % (self.name, self.envdir))
self.create_env(force_remove=True)
cprint("%s installdeps: %s" % (self.name, ', '.join(self.deps)))
if not self.install_deps():
cprint(" deps installation failed, aborted.\n", 'err')
return 1
else:
cprint("%s cached (deps unchanged): %s" % (self.name, self.envdir))
# install the project from the zipped file
# TODO think more carefully about where it should be installed
# specifically we want to be able this to include the test files (which
# are not always unpacked when installed so as to run the tests there)
# if there are build files (e.g. cython) then tests must run where
# the build was. Also, reinstalling should not overwrite the builds
# e.g. setup.py will skip rebuilding cython files if they are unchanged
cprint("%s inst: %s" % (self.name, self.envdistdir))
if not self.install_dist():
cprint(" install failed.\n", 'err')
return 1
cprint("%s runtests" % self.name)
# return False if all commands were successfully run
# otherwise returns True if at least one command exited badly
return self.run_commands() | python | def ctox(self):
"""Main method for the environment.
Parse the tox.ini config, install the dependancies and run the
commands. The output of the commands is printed.
Returns 0 if they ran successfully, 1 if there was an error
(either in setup or whilst running the commands), 2 if the build
was skipped.
"""
# TODO make this less of a hack e.g. using basepython from config
# if it exists (and use an attribute directly).
if self.name[:4] not in SUPPORTED_ENVS:
from colorama import Style
cprint(Style.BRIGHT +
"Skipping unsupported python version %s\n" % self.name,
'warn')
return 2
# TODO don't remove env if there's a dependancy mis-match
# rather "clean" it to the empty state (the hope being to keep
# the dist build around - so not all files need to be rebuilt)
# TODO extract this as a method (for readability)
if not self.env_exists() or self.reusableable():
cprint("%s create: %s" % (self.name, self.envdir))
self.create_env(force_remove=True)
cprint("%s installdeps: %s" % (self.name, ', '.join(self.deps)))
if not self.install_deps():
cprint(" deps installation failed, aborted.\n", 'err')
return 1
else:
cprint("%s cached (deps unchanged): %s" % (self.name, self.envdir))
# install the project from the zipped file
# TODO think more carefully about where it should be installed
# specifically we want to be able this to include the test files (which
# are not always unpacked when installed so as to run the tests there)
# if there are build files (e.g. cython) then tests must run where
# the build was. Also, reinstalling should not overwrite the builds
# e.g. setup.py will skip rebuilding cython files if they are unchanged
cprint("%s inst: %s" % (self.name, self.envdistdir))
if not self.install_dist():
cprint(" install failed.\n", 'err')
return 1
cprint("%s runtests" % self.name)
# return False if all commands were successfully run
# otherwise returns True if at least one command exited badly
return self.run_commands() | [
"def",
"ctox",
"(",
"self",
")",
":",
"# TODO make this less of a hack e.g. using basepython from config",
"# if it exists (and use an attribute directly).",
"if",
"self",
".",
"name",
"[",
":",
"4",
"]",
"not",
"in",
"SUPPORTED_ENVS",
":",
"from",
"colorama",
"import",
... | Main method for the environment.
Parse the tox.ini config, install the dependancies and run the
commands. The output of the commands is printed.
Returns 0 if they ran successfully, 1 if there was an error
(either in setup or whilst running the commands), 2 if the build
was skipped. | [
"Main",
"method",
"for",
"the",
"environment",
"."
] | train | https://github.com/hayd/ctox/blob/6f032488ad67170d57d025a830d7b967075b0d7f/ctox/main.py#L63-L113 |
chbrown/argv | argv/flags.py | parse_tokens | def parse_tokens(tokens):
'''Read tokens strings into (is_flag, value) tuples:
For this value of `tokens`:
['-f', 'pets.txt', '-v', 'cut', '-cz', '--lost', '--delete=sam', '--', 'lester', 'jack']
`flatten(tokens)` yields an iterable:
[
(True, 'f'),
(False, 'pets.txt'),
(True, 'v'),
(False, 'cut'),
(True, 'c'),
(True, 'z'),
(True, 'lost'),
(True, 'delete'),
(False, 'sam'),
(False, 'lester'),
(False, 'jack'),
]
Todo:
ensure that 'verbose' in '--verbose -- a b c' is treated as a boolean even if not marked as one.
'''
# one pass max
tokens = iter(tokens)
for token in tokens:
if token == '--':
# bleed out tokens without breaking, since tokens is an iterator
for token in tokens:
yield False, token
elif token.startswith('-'):
# this handles both --last=man.txt and -czf=file.tgz
# str.partition produces a 3-tuple whether or not the separator is found
token, sep, value = token.partition('=')
for flag in split_flag_token(token):
yield True, flag
if sep:
# we don't re-flatten the 'value' from '--token=value'
yield False, value
else:
yield False, token | python | def parse_tokens(tokens):
'''Read tokens strings into (is_flag, value) tuples:
For this value of `tokens`:
['-f', 'pets.txt', '-v', 'cut', '-cz', '--lost', '--delete=sam', '--', 'lester', 'jack']
`flatten(tokens)` yields an iterable:
[
(True, 'f'),
(False, 'pets.txt'),
(True, 'v'),
(False, 'cut'),
(True, 'c'),
(True, 'z'),
(True, 'lost'),
(True, 'delete'),
(False, 'sam'),
(False, 'lester'),
(False, 'jack'),
]
Todo:
ensure that 'verbose' in '--verbose -- a b c' is treated as a boolean even if not marked as one.
'''
# one pass max
tokens = iter(tokens)
for token in tokens:
if token == '--':
# bleed out tokens without breaking, since tokens is an iterator
for token in tokens:
yield False, token
elif token.startswith('-'):
# this handles both --last=man.txt and -czf=file.tgz
# str.partition produces a 3-tuple whether or not the separator is found
token, sep, value = token.partition('=')
for flag in split_flag_token(token):
yield True, flag
if sep:
# we don't re-flatten the 'value' from '--token=value'
yield False, value
else:
yield False, token | [
"def",
"parse_tokens",
"(",
"tokens",
")",
":",
"# one pass max",
"tokens",
"=",
"iter",
"(",
"tokens",
")",
"for",
"token",
"in",
"tokens",
":",
"if",
"token",
"==",
"'--'",
":",
"# bleed out tokens without breaking, since tokens is an iterator",
"for",
"token",
... | Read tokens strings into (is_flag, value) tuples:
For this value of `tokens`:
['-f', 'pets.txt', '-v', 'cut', '-cz', '--lost', '--delete=sam', '--', 'lester', 'jack']
`flatten(tokens)` yields an iterable:
[
(True, 'f'),
(False, 'pets.txt'),
(True, 'v'),
(False, 'cut'),
(True, 'c'),
(True, 'z'),
(True, 'lost'),
(True, 'delete'),
(False, 'sam'),
(False, 'lester'),
(False, 'jack'),
]
Todo:
ensure that 'verbose' in '--verbose -- a b c' is treated as a boolean even if not marked as one. | [
"Read",
"tokens",
"strings",
"into",
"(",
"is_flag",
"value",
")",
"tuples",
":"
] | train | https://github.com/chbrown/argv/blob/5e2b0424a060027c029ad9c16d90bd14a2ff53f8/argv/flags.py#L4-L49 |
cidles/pressagio | src/pressagio/tokenizer.py | Tokenizer.is_blankspace | def is_blankspace(self, char):
"""
Test if a character is a blankspace.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a blankspace, False otherwise.
"""
if len(char) > 1:
raise TypeError("Expected a char.")
if char in self.blankspaces:
return True
return False | python | def is_blankspace(self, char):
"""
Test if a character is a blankspace.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a blankspace, False otherwise.
"""
if len(char) > 1:
raise TypeError("Expected a char.")
if char in self.blankspaces:
return True
return False | [
"def",
"is_blankspace",
"(",
"self",
",",
"char",
")",
":",
"if",
"len",
"(",
"char",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"Expected a char.\"",
")",
"if",
"char",
"in",
"self",
".",
"blankspaces",
":",
"return",
"True",
"return",
"False"
] | Test if a character is a blankspace.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a blankspace, False otherwise. | [
"Test",
"if",
"a",
"character",
"is",
"a",
"blankspace",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/tokenizer.py#L56-L75 |
cidles/pressagio | src/pressagio/tokenizer.py | Tokenizer.is_separator | def is_separator(self, char):
"""
Test if a character is a separator.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a separator, False otherwise.
"""
if len(char) > 1:
raise TypeError("Expected a char.")
if char in self.separators:
return True
return False | python | def is_separator(self, char):
"""
Test if a character is a separator.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a separator, False otherwise.
"""
if len(char) > 1:
raise TypeError("Expected a char.")
if char in self.separators:
return True
return False | [
"def",
"is_separator",
"(",
"self",
",",
"char",
")",
":",
"if",
"len",
"(",
"char",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"Expected a char.\"",
")",
"if",
"char",
"in",
"self",
".",
"separators",
":",
"return",
"True",
"return",
"False"
] | Test if a character is a separator.
Parameters
----------
char : str
The character to test.
Returns
-------
ret : bool
True if character is a separator, False otherwise. | [
"Test",
"if",
"a",
"character",
"is",
"a",
"separator",
"."
] | train | https://github.com/cidles/pressagio/blob/2b3b89ae82316b929244e4c63e393682b2a57e57/src/pressagio/tokenizer.py#L77-L96 |
limix/limix-core | limix_core/linalg/linalg_matrix.py | solve_chol | def solve_chol(A,B):
"""
Solve cholesky decomposition::
return A\(A'\B)
"""
# X = linalg.solve(A,linalg.solve(A.transpose(),B))
# much faster version
X = linalg.cho_solve((A, True), B)
return X | python | def solve_chol(A,B):
"""
Solve cholesky decomposition::
return A\(A'\B)
"""
# X = linalg.solve(A,linalg.solve(A.transpose(),B))
# much faster version
X = linalg.cho_solve((A, True), B)
return X | [
"def",
"solve_chol",
"(",
"A",
",",
"B",
")",
":",
"# X = linalg.solve(A,linalg.solve(A.transpose(),B))",
"# much faster version",
"X",
"=",
"linalg",
".",
"cho_solve",
"(",
"(",
"A",
",",
"True",
")",
",",
"B",
")",
"return",
"X"
] | Solve cholesky decomposition::
return A\(A'\B) | [
"Solve",
"cholesky",
"decomposition",
"::"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/linalg/linalg_matrix.py#L29-L39 |
limix/limix-core | limix_core/linalg/linalg_matrix.py | jitChol | def jitChol(A, maxTries=10, warning=True):
"""Do a Cholesky decomposition with jitter.
Description:
U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky
decomposition on the given matrix, if matrix isn't positive
definite the function adds 'jitter' and tries again. Thereafter
the amount of jitter is multiplied by 10 each time it is added
again. This is continued for a maximum of 10 times. The amount of
jitter added is returned.
Returns:
U - the Cholesky decomposition for the matrix.
jitter - the amount of jitter that was added to the matrix.
Arguments:
A - the matrix for which the Cholesky decomposition is required.
maxTries - the maximum number of times that jitter is added before
giving up (default 10).
warning - whether to give a warning for adding jitter (default is True)
See also
CHOL, PDINV, LOGDET
Copyright (c) 2005, 2006 Neil D. Lawrence
"""
jitter = 0
i = 0
while(True):
try:
# Try --- need to check A is positive definite
if jitter == 0:
jitter = abs(SP.trace(A))/A.shape[0]*1e-6
LC = linalg.cholesky(A, lower=True)
return LC.T, 0.0
else:
if warning:
# pdb.set_trace()
# plt.figure()
# plt.imshow(A, interpolation="nearest")
# plt.colorbar()
# plt.show()
logging.error("Adding jitter of %f in jitChol()." % jitter)
LC = linalg.cholesky(A+jitter*SP.eye(A.shape[0]), lower=True)
return LC.T, jitter
except linalg.LinAlgError:
# Seems to have been non-positive definite.
if i<maxTries:
jitter = jitter*10
else:
raise linalg.LinAlgError("Matrix non positive definite, jitter of " + str(jitter) + " added but failed after " + str(i) + " trials.")
i += 1
return LC | python | def jitChol(A, maxTries=10, warning=True):
"""Do a Cholesky decomposition with jitter.
Description:
U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky
decomposition on the given matrix, if matrix isn't positive
definite the function adds 'jitter' and tries again. Thereafter
the amount of jitter is multiplied by 10 each time it is added
again. This is continued for a maximum of 10 times. The amount of
jitter added is returned.
Returns:
U - the Cholesky decomposition for the matrix.
jitter - the amount of jitter that was added to the matrix.
Arguments:
A - the matrix for which the Cholesky decomposition is required.
maxTries - the maximum number of times that jitter is added before
giving up (default 10).
warning - whether to give a warning for adding jitter (default is True)
See also
CHOL, PDINV, LOGDET
Copyright (c) 2005, 2006 Neil D. Lawrence
"""
jitter = 0
i = 0
while(True):
try:
# Try --- need to check A is positive definite
if jitter == 0:
jitter = abs(SP.trace(A))/A.shape[0]*1e-6
LC = linalg.cholesky(A, lower=True)
return LC.T, 0.0
else:
if warning:
# pdb.set_trace()
# plt.figure()
# plt.imshow(A, interpolation="nearest")
# plt.colorbar()
# plt.show()
logging.error("Adding jitter of %f in jitChol()." % jitter)
LC = linalg.cholesky(A+jitter*SP.eye(A.shape[0]), lower=True)
return LC.T, jitter
except linalg.LinAlgError:
# Seems to have been non-positive definite.
if i<maxTries:
jitter = jitter*10
else:
raise linalg.LinAlgError("Matrix non positive definite, jitter of " + str(jitter) + " added but failed after " + str(i) + " trials.")
i += 1
return LC | [
"def",
"jitChol",
"(",
"A",
",",
"maxTries",
"=",
"10",
",",
"warning",
"=",
"True",
")",
":",
"jitter",
"=",
"0",
"i",
"=",
"0",
"while",
"(",
"True",
")",
":",
"try",
":",
"# Try --- need to check A is positive definite",
"if",
"jitter",
"==",
"0",
"... | Do a Cholesky decomposition with jitter.
Description:
U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky
decomposition on the given matrix, if matrix isn't positive
definite the function adds 'jitter' and tries again. Thereafter
the amount of jitter is multiplied by 10 each time it is added
again. This is continued for a maximum of 10 times. The amount of
jitter added is returned.
Returns:
U - the Cholesky decomposition for the matrix.
jitter - the amount of jitter that was added to the matrix.
Arguments:
A - the matrix for which the Cholesky decomposition is required.
maxTries - the maximum number of times that jitter is added before
giving up (default 10).
warning - whether to give a warning for adding jitter (default is True)
See also
CHOL, PDINV, LOGDET
Copyright (c) 2005, 2006 Neil D. Lawrence | [
"Do",
"a",
"Cholesky",
"decomposition",
"with",
"jitter",
"."
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/linalg/linalg_matrix.py#L46-L103 |
limix/limix-core | limix_core/linalg/linalg_matrix.py | jitEigh | def jitEigh(A,maxTries=10,warning=True):
"""
Do a Eigenvalue Decomposition with Jitter,
works as jitChol
"""
warning = True
jitter = 0
i = 0
while(True):
if jitter == 0:
jitter = abs(SP.trace(A))/A.shape[0]*1e-6
S,U = linalg.eigh(A)
else:
if warning:
# pdb.set_trace()
# plt.figure()
# plt.imshow(A, interpolation="nearest")
# plt.colorbar()
# plt.show()
logging.error("Adding jitter of %f in jitEigh()." % jitter)
S,U = linalg.eigh(A+jitter*SP.eye(A.shape[0]))
if S.min()>1E-10:
return S,U
if i<maxTries:
jitter = jitter*10
i += 1
raise linalg.LinAlgError("Matrix non positive definite, jitter of " + str(jitter) + " added but failed after " + str(i) + " trials.") | python | def jitEigh(A,maxTries=10,warning=True):
"""
Do a Eigenvalue Decomposition with Jitter,
works as jitChol
"""
warning = True
jitter = 0
i = 0
while(True):
if jitter == 0:
jitter = abs(SP.trace(A))/A.shape[0]*1e-6
S,U = linalg.eigh(A)
else:
if warning:
# pdb.set_trace()
# plt.figure()
# plt.imshow(A, interpolation="nearest")
# plt.colorbar()
# plt.show()
logging.error("Adding jitter of %f in jitEigh()." % jitter)
S,U = linalg.eigh(A+jitter*SP.eye(A.shape[0]))
if S.min()>1E-10:
return S,U
if i<maxTries:
jitter = jitter*10
i += 1
raise linalg.LinAlgError("Matrix non positive definite, jitter of " + str(jitter) + " added but failed after " + str(i) + " trials.") | [
"def",
"jitEigh",
"(",
"A",
",",
"maxTries",
"=",
"10",
",",
"warning",
"=",
"True",
")",
":",
"warning",
"=",
"True",
"jitter",
"=",
"0",
"i",
"=",
"0",
"while",
"(",
"True",
")",
":",
"if",
"jitter",
"==",
"0",
":",
"jitter",
"=",
"abs",
"(",... | Do a Eigenvalue Decomposition with Jitter,
works as jitChol | [
"Do",
"a",
"Eigenvalue",
"Decomposition",
"with",
"Jitter"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/linalg/linalg_matrix.py#L106-L138 |
inveniosoftware/invenio-config | invenio_config/entrypoint.py | InvenioConfigEntryPointModule.init_app | def init_app(self, app):
"""Initialize Flask application."""
if self.entry_point_group:
eps = sorted(pkg_resources.iter_entry_points(
self.entry_point_group), key=attrgetter('name'))
for ep in eps:
app.logger.debug("Loading config for entry point {}".format(
ep))
app.config.from_object(ep.load()) | python | def init_app(self, app):
"""Initialize Flask application."""
if self.entry_point_group:
eps = sorted(pkg_resources.iter_entry_points(
self.entry_point_group), key=attrgetter('name'))
for ep in eps:
app.logger.debug("Loading config for entry point {}".format(
ep))
app.config.from_object(ep.load()) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"self",
".",
"entry_point_group",
":",
"eps",
"=",
"sorted",
"(",
"pkg_resources",
".",
"iter_entry_points",
"(",
"self",
".",
"entry_point_group",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'name'... | Initialize Flask application. | [
"Initialize",
"Flask",
"application",
"."
] | train | https://github.com/inveniosoftware/invenio-config/blob/8d1e63ac045cd9c58a3399c6b58845e6daa06102/invenio_config/entrypoint.py#L37-L45 |
jbloomlab/phydms | phydmslib/utils.py | modelComparisonDataFrame | def modelComparisonDataFrame(modelcomparisonfile, splitparams):
"""Converts ``modelcomparison.md`` file to `pandas` DataFrame.
Running ``phydms_comprehensive`` creates a file with the suffix
``modelcomparison.md``. This function converts that file into a
DataFrame that is easy to handle for downstream analysis.
Args:
`modelcomparisonfile` (str)
The name of the ``modelcomparison.md`` file.
`splitparams` (bool)
If `True`, create a new column for each model param in
the `ParamValues` column, with values of `NaN` if that
model does not have such a parameter.
Returns:
A `pandas` DataFrame with the information in the model
comparison file.
>>> with tempfile.NamedTemporaryFile(mode='w') as f:
... _ = f.write('\\n'.join([
... '| Model | deltaAIC | LogLikelihood | nParams | ParamValues |',
... '|-------|----------|---------------|---------|--------------|',
... '| ExpCM | 0.00 | -1000.00 | 7 | x=1.0, y=2.0 |',
... '| YNGKP | 10.2 | -1005.10 | 7 | x=1.3, z=0.1 |',
... ]))
... f.flush()
... df_split = modelComparisonDataFrame(f.name, splitparams=True)
... df_nosplit = modelComparisonDataFrame(f.name, splitparams=False)
>>> df_nosplit.equals(pandas.DataFrame.from_records(
... [['ExpCM', 0, -1000, 7, 'x=1.0, y=2.0'],
... ['YNGKP', 10.2, -1005.1, 7, 'x=1.3, z=0.1']],
... columns=['Model', 'deltaAIC', 'LogLikelihood',
... 'nParams', 'ParamValues']))
True
>>> df_split.equals(pandas.DataFrame.from_records(
... [['ExpCM', 0, -1000, 7, 1.0, 2.0, numpy.nan],
... ['YNGKP', 10.2, -1005.1, 7, 1.3, numpy.nan, 0.1]],
... columns=['Model', 'deltaAIC', 'LogLikelihood',
... 'nParams', 'x', 'y', 'z']))
True
"""
df = (pandas.read_csv(modelcomparisonfile, sep='|', skiprows=[1])
.select(lambda x: 'Unnamed' not in x, axis=1)
)
# strip whitespace
df.columns = df.columns.str.strip()
for col in df.columns:
if pandas.api.types.is_string_dtype(df[col]):
df[col] = df[col].str.strip()
paramsdict = {}
if splitparams:
for (i, paramstr) in df['ParamValues'].iteritems():
paramsdict[i] = dict(map(lambda tup: (tup[0], float(tup[1])),
[param.strip().split('=') for param in paramstr.split(',')]))
params_df = pandas.DataFrame.from_dict(paramsdict, orient='index')
params_df = params_df[sorted(params_df.columns)]
df = (df.join(params_df)
.drop('ParamValues', axis=1)
)
return df | python | def modelComparisonDataFrame(modelcomparisonfile, splitparams):
"""Converts ``modelcomparison.md`` file to `pandas` DataFrame.
Running ``phydms_comprehensive`` creates a file with the suffix
``modelcomparison.md``. This function converts that file into a
DataFrame that is easy to handle for downstream analysis.
Args:
`modelcomparisonfile` (str)
The name of the ``modelcomparison.md`` file.
`splitparams` (bool)
If `True`, create a new column for each model param in
the `ParamValues` column, with values of `NaN` if that
model does not have such a parameter.
Returns:
A `pandas` DataFrame with the information in the model
comparison file.
>>> with tempfile.NamedTemporaryFile(mode='w') as f:
... _ = f.write('\\n'.join([
... '| Model | deltaAIC | LogLikelihood | nParams | ParamValues |',
... '|-------|----------|---------------|---------|--------------|',
... '| ExpCM | 0.00 | -1000.00 | 7 | x=1.0, y=2.0 |',
... '| YNGKP | 10.2 | -1005.10 | 7 | x=1.3, z=0.1 |',
... ]))
... f.flush()
... df_split = modelComparisonDataFrame(f.name, splitparams=True)
... df_nosplit = modelComparisonDataFrame(f.name, splitparams=False)
>>> df_nosplit.equals(pandas.DataFrame.from_records(
... [['ExpCM', 0, -1000, 7, 'x=1.0, y=2.0'],
... ['YNGKP', 10.2, -1005.1, 7, 'x=1.3, z=0.1']],
... columns=['Model', 'deltaAIC', 'LogLikelihood',
... 'nParams', 'ParamValues']))
True
>>> df_split.equals(pandas.DataFrame.from_records(
... [['ExpCM', 0, -1000, 7, 1.0, 2.0, numpy.nan],
... ['YNGKP', 10.2, -1005.1, 7, 1.3, numpy.nan, 0.1]],
... columns=['Model', 'deltaAIC', 'LogLikelihood',
... 'nParams', 'x', 'y', 'z']))
True
"""
df = (pandas.read_csv(modelcomparisonfile, sep='|', skiprows=[1])
.select(lambda x: 'Unnamed' not in x, axis=1)
)
# strip whitespace
df.columns = df.columns.str.strip()
for col in df.columns:
if pandas.api.types.is_string_dtype(df[col]):
df[col] = df[col].str.strip()
paramsdict = {}
if splitparams:
for (i, paramstr) in df['ParamValues'].iteritems():
paramsdict[i] = dict(map(lambda tup: (tup[0], float(tup[1])),
[param.strip().split('=') for param in paramstr.split(',')]))
params_df = pandas.DataFrame.from_dict(paramsdict, orient='index')
params_df = params_df[sorted(params_df.columns)]
df = (df.join(params_df)
.drop('ParamValues', axis=1)
)
return df | [
"def",
"modelComparisonDataFrame",
"(",
"modelcomparisonfile",
",",
"splitparams",
")",
":",
"df",
"=",
"(",
"pandas",
".",
"read_csv",
"(",
"modelcomparisonfile",
",",
"sep",
"=",
"'|'",
",",
"skiprows",
"=",
"[",
"1",
"]",
")",
".",
"select",
"(",
"lambd... | Converts ``modelcomparison.md`` file to `pandas` DataFrame.
Running ``phydms_comprehensive`` creates a file with the suffix
``modelcomparison.md``. This function converts that file into a
DataFrame that is easy to handle for downstream analysis.
Args:
`modelcomparisonfile` (str)
The name of the ``modelcomparison.md`` file.
`splitparams` (bool)
If `True`, create a new column for each model param in
the `ParamValues` column, with values of `NaN` if that
model does not have such a parameter.
Returns:
A `pandas` DataFrame with the information in the model
comparison file.
>>> with tempfile.NamedTemporaryFile(mode='w') as f:
... _ = f.write('\\n'.join([
... '| Model | deltaAIC | LogLikelihood | nParams | ParamValues |',
... '|-------|----------|---------------|---------|--------------|',
... '| ExpCM | 0.00 | -1000.00 | 7 | x=1.0, y=2.0 |',
... '| YNGKP | 10.2 | -1005.10 | 7 | x=1.3, z=0.1 |',
... ]))
... f.flush()
... df_split = modelComparisonDataFrame(f.name, splitparams=True)
... df_nosplit = modelComparisonDataFrame(f.name, splitparams=False)
>>> df_nosplit.equals(pandas.DataFrame.from_records(
... [['ExpCM', 0, -1000, 7, 'x=1.0, y=2.0'],
... ['YNGKP', 10.2, -1005.1, 7, 'x=1.3, z=0.1']],
... columns=['Model', 'deltaAIC', 'LogLikelihood',
... 'nParams', 'ParamValues']))
True
>>> df_split.equals(pandas.DataFrame.from_records(
... [['ExpCM', 0, -1000, 7, 1.0, 2.0, numpy.nan],
... ['YNGKP', 10.2, -1005.1, 7, 1.3, numpy.nan, 0.1]],
... columns=['Model', 'deltaAIC', 'LogLikelihood',
... 'nParams', 'x', 'y', 'z']))
True | [
"Converts",
"modelcomparison",
".",
"md",
"file",
"to",
"pandas",
"DataFrame",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/utils.py#L10-L73 |
jbloomlab/phydms | phydmslib/utils.py | BenjaminiHochbergCorrection | def BenjaminiHochbergCorrection(pvals, fdr):
"""Benjamini-Hochberg procedure to control false discovery rate.
Calling arguments:
*pvals* : a list of tuples of *(label, p)* where *label* is some label assigned
to each data point, and *p* is the corresponding *P-value*.
*fdr* : the desired false discovery rate
The return value is the 2-tuple *(pcutoff, significantlabels)*. After applying
the algorithm, all data points with *p <= pcutoff* are declared significant.
The labels for these data points are in *significantlabels*. If there are no
significant sites, *pcutoff* is returned as the maximum P-value that would
have made a single point significant.
"""
num_tests = len(pvals)
# sort by p-value
sorted_tests = sorted(pvals, key=lambda tup: tup[1])
# find maximum rank for which p <= (rank/num_tests)*FDR
max_rank = 0
pcutoff = None
for (rank, (label, p)) in enumerate(sorted_tests):
rank = rank + 1 # rank beginning with 1 for smallest p-value (there is no rank 0)
bh_threshold = fdr * float(rank) / num_tests
if p <= bh_threshold:
assert rank > max_rank
max_rank = rank
pcutoff = bh_threshold
# pcutoff to have one significant site if there are none
if pcutoff == None:
pcutoff = 1.0 / num_tests * fdr
# collect significant ranks:
significantlabels = []
for (rank, (label, p)) in enumerate(sorted_tests):
rank = rank + 1 # rank beginning with 1 for site with smallest p-vaalue
if rank <= max_rank:
assert p <= pcutoff
significantlabels.append(label)
return (pcutoff, significantlabels) | python | def BenjaminiHochbergCorrection(pvals, fdr):
"""Benjamini-Hochberg procedure to control false discovery rate.
Calling arguments:
*pvals* : a list of tuples of *(label, p)* where *label* is some label assigned
to each data point, and *p* is the corresponding *P-value*.
*fdr* : the desired false discovery rate
The return value is the 2-tuple *(pcutoff, significantlabels)*. After applying
the algorithm, all data points with *p <= pcutoff* are declared significant.
The labels for these data points are in *significantlabels*. If there are no
significant sites, *pcutoff* is returned as the maximum P-value that would
have made a single point significant.
"""
num_tests = len(pvals)
# sort by p-value
sorted_tests = sorted(pvals, key=lambda tup: tup[1])
# find maximum rank for which p <= (rank/num_tests)*FDR
max_rank = 0
pcutoff = None
for (rank, (label, p)) in enumerate(sorted_tests):
rank = rank + 1 # rank beginning with 1 for smallest p-value (there is no rank 0)
bh_threshold = fdr * float(rank) / num_tests
if p <= bh_threshold:
assert rank > max_rank
max_rank = rank
pcutoff = bh_threshold
# pcutoff to have one significant site if there are none
if pcutoff == None:
pcutoff = 1.0 / num_tests * fdr
# collect significant ranks:
significantlabels = []
for (rank, (label, p)) in enumerate(sorted_tests):
rank = rank + 1 # rank beginning with 1 for site with smallest p-vaalue
if rank <= max_rank:
assert p <= pcutoff
significantlabels.append(label)
return (pcutoff, significantlabels) | [
"def",
"BenjaminiHochbergCorrection",
"(",
"pvals",
",",
"fdr",
")",
":",
"num_tests",
"=",
"len",
"(",
"pvals",
")",
"# sort by p-value",
"sorted_tests",
"=",
"sorted",
"(",
"pvals",
",",
"key",
"=",
"lambda",
"tup",
":",
"tup",
"[",
"1",
"]",
")",
"# f... | Benjamini-Hochberg procedure to control false discovery rate.
Calling arguments:
*pvals* : a list of tuples of *(label, p)* where *label* is some label assigned
to each data point, and *p* is the corresponding *P-value*.
*fdr* : the desired false discovery rate
The return value is the 2-tuple *(pcutoff, significantlabels)*. After applying
the algorithm, all data points with *p <= pcutoff* are declared significant.
The labels for these data points are in *significantlabels*. If there are no
significant sites, *pcutoff* is returned as the maximum P-value that would
have made a single point significant. | [
"Benjamini",
"-",
"Hochberg",
"procedure",
"to",
"control",
"false",
"discovery",
"rate",
"."
] | train | https://github.com/jbloomlab/phydms/blob/9cdebc10bafbe543c552d79486c7f950780ed3c0/phydmslib/utils.py#L76-L120 |
limix/limix-core | limix_core/optimize/optimize_bfgs.py | param_dict_to_list | def param_dict_to_list(dict,skeys=None):
"""convert from param dictionary to list"""
#sort keys
RV = SP.concatenate([dict[key].flatten() for key in skeys])
return RV
pass | python | def param_dict_to_list(dict,skeys=None):
"""convert from param dictionary to list"""
#sort keys
RV = SP.concatenate([dict[key].flatten() for key in skeys])
return RV
pass | [
"def",
"param_dict_to_list",
"(",
"dict",
",",
"skeys",
"=",
"None",
")",
":",
"#sort keys",
"RV",
"=",
"SP",
".",
"concatenate",
"(",
"[",
"dict",
"[",
"key",
"]",
".",
"flatten",
"(",
")",
"for",
"key",
"in",
"skeys",
"]",
")",
"return",
"RV",
"p... | convert from param dictionary to list | [
"convert",
"from",
"param",
"dictionary",
"to",
"list"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/optimize/optimize_bfgs.py#L8-L13 |
limix/limix-core | limix_core/optimize/optimize_bfgs.py | param_list_to_dict | def param_list_to_dict(list,param_struct,skeys):
"""convert from param dictionary to list
param_struct: structure of parameter array
"""
RV = []
i0= 0
for key in skeys:
val = param_struct[key]
shape = SP.array(val)
np = shape.prod()
i1 = i0+np
params = list[i0:i1].reshape(shape)
RV.append((key,params))
i0 = i1
return dict(RV) | python | def param_list_to_dict(list,param_struct,skeys):
"""convert from param dictionary to list
param_struct: structure of parameter array
"""
RV = []
i0= 0
for key in skeys:
val = param_struct[key]
shape = SP.array(val)
np = shape.prod()
i1 = i0+np
params = list[i0:i1].reshape(shape)
RV.append((key,params))
i0 = i1
return dict(RV) | [
"def",
"param_list_to_dict",
"(",
"list",
",",
"param_struct",
",",
"skeys",
")",
":",
"RV",
"=",
"[",
"]",
"i0",
"=",
"0",
"for",
"key",
"in",
"skeys",
":",
"val",
"=",
"param_struct",
"[",
"key",
"]",
"shape",
"=",
"SP",
".",
"array",
"(",
"val",... | convert from param dictionary to list
param_struct: structure of parameter array | [
"convert",
"from",
"param",
"dictionary",
"to",
"list",
"param_struct",
":",
"structure",
"of",
"parameter",
"array"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/optimize/optimize_bfgs.py#L15-L29 |
limix/limix-core | limix_core/optimize/optimize_bfgs.py | checkgrad | def checkgrad(f, fprime, x, *args,**kw_args):
"""
Analytical gradient calculation using a 3-point method
"""
LG.debug("Checking gradient ...")
import numpy as np
# using machine precision to choose h
eps = np.finfo(float).eps
step = np.sqrt(eps)*(x.min())
# shake things up a bit by taking random steps for each x dimension
h = step*np.sign(np.random.uniform(-1, 1, x.size))
f_ph = f(x+h, *args, **kw_args)
f_mh = f(x-h, *args, **kw_args)
numerical_gradient = (f_ph - f_mh)/(2*h)
analytical_gradient = fprime(x, *args, **kw_args)
ratio = (f_ph - f_mh)/(2*np.dot(h, analytical_gradient))
h = np.zeros_like(x)
for i in range(len(x)):
pdb.set_trace()
h[i] = step
f_ph = f(x+h, *args, **kw_args)
f_mh = f(x-h, *args, **kw_args)
numerical_gradient = (f_ph - f_mh)/(2*step)
analytical_gradient = fprime(x, *args, **kw_args)[i]
ratio = (f_ph - f_mh)/(2*step*analytical_gradient)
h[i] = 0
LG.debug("[%d] numerical: %f, analytical: %f, ratio: %f" % (i, numerical_gradient,analytical_gradient,ratio)) | python | def checkgrad(f, fprime, x, *args,**kw_args):
"""
Analytical gradient calculation using a 3-point method
"""
LG.debug("Checking gradient ...")
import numpy as np
# using machine precision to choose h
eps = np.finfo(float).eps
step = np.sqrt(eps)*(x.min())
# shake things up a bit by taking random steps for each x dimension
h = step*np.sign(np.random.uniform(-1, 1, x.size))
f_ph = f(x+h, *args, **kw_args)
f_mh = f(x-h, *args, **kw_args)
numerical_gradient = (f_ph - f_mh)/(2*h)
analytical_gradient = fprime(x, *args, **kw_args)
ratio = (f_ph - f_mh)/(2*np.dot(h, analytical_gradient))
h = np.zeros_like(x)
for i in range(len(x)):
pdb.set_trace()
h[i] = step
f_ph = f(x+h, *args, **kw_args)
f_mh = f(x-h, *args, **kw_args)
numerical_gradient = (f_ph - f_mh)/(2*step)
analytical_gradient = fprime(x, *args, **kw_args)[i]
ratio = (f_ph - f_mh)/(2*step*analytical_gradient)
h[i] = 0
LG.debug("[%d] numerical: %f, analytical: %f, ratio: %f" % (i, numerical_gradient,analytical_gradient,ratio)) | [
"def",
"checkgrad",
"(",
"f",
",",
"fprime",
",",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kw_args",
")",
":",
"LG",
".",
"debug",
"(",
"\"Checking gradient ...\"",
")",
"import",
"numpy",
"as",
"np",
"# using machine precision to choose h",
"eps",
"=",
"np"... | Analytical gradient calculation using a 3-point method | [
"Analytical",
"gradient",
"calculation",
"using",
"a",
"3",
"-",
"point",
"method"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/optimize/optimize_bfgs.py#L31-L62 |
limix/limix-core | limix_core/optimize/optimize_bfgs.py | opt_hyper | def opt_hyper(gpr,Ifilter=None,bounds=None,opts={},*args,**kw_args):
"""
optimize params
Input:
gpr: GP regression class
params0: dictionary filled with starting hyperparameters
opts: options for optimizer
"""
if 'gradcheck' in opts:
gradcheck = opts['gradcheck']
else:
gradcheck = False
if 'max_iter_opt' in opts:
max_iter = opts['max_iter_opt']
else:
max_iter = 5000
if 'pgtol' in opts:
pgtol = opts['pgtol']
else:
pgtol = 1e-10
params0 = gpr.getParams()
def f(x):
x_ = X0
x_[Ifilter_x] = x
gpr.setParams(param_list_to_dict(x_,param_struct,skeys))
lml = gpr.LML()
if SP.isnan(lml):
lml=1E6
lml_grad = gpr.LML_grad()
lml_grad = param_dict_to_list(lml_grad,skeys)
if (~SP.isfinite(lml_grad)).any():
idx = (~SP.isfinite(lml_grad))
lml_grad[idx] = 1E6
return lml, lml_grad[Ifilter_x]
skeys = SP.sort(list(params0.keys()))
param_struct = dict([(name,params0[name].shape) for name in skeys])
# mask params that should not be optimized
X0 = param_dict_to_list(params0,skeys)
if Ifilter is not None:
Ifilter_x = SP.array(param_dict_to_list(Ifilter,skeys),dtype=bool)
else:
Ifilter_x = SP.ones(len(X0),dtype='bool')
# add bounds if necessary
if bounds is not None:
_b = []
for key in skeys:
if key in list(bounds.keys()):
_b.extend(bounds[key])
else:
_b.extend([[-SP.inf,+SP.inf]]*params0[key].size)
bounds = SP.array(_b)
bounds = bounds[Ifilter_x]
LG.info('Starting optimization ...')
t = time.time()
x = X0.copy()[Ifilter_x]
RV = optimize(f,x,maxfun=int(max_iter),pgtol=pgtol,bounds=bounds,**kw_args)
#RVopt = optimize(f,x,messages=True,maxfun=int(max_iter),pgtol=pgtol,bounds=bounds)
#LG.info('%s'%OPT.tnc.RCSTRINGS[RVopt[2]])
#LG.info('Optimization is converged at iteration %d'%RVopt[1])
#LG.info('Total time: %.2fs'%(time.time()-t))
info = RV[2]
conv = info['warnflag']==0
if gradcheck:
err = OPT.check_grad(f,df,xopt)
LG.info("check_grad (post): %.2f"%err)
return conv,info | python | def opt_hyper(gpr,Ifilter=None,bounds=None,opts={},*args,**kw_args):
"""
optimize params
Input:
gpr: GP regression class
params0: dictionary filled with starting hyperparameters
opts: options for optimizer
"""
if 'gradcheck' in opts:
gradcheck = opts['gradcheck']
else:
gradcheck = False
if 'max_iter_opt' in opts:
max_iter = opts['max_iter_opt']
else:
max_iter = 5000
if 'pgtol' in opts:
pgtol = opts['pgtol']
else:
pgtol = 1e-10
params0 = gpr.getParams()
def f(x):
x_ = X0
x_[Ifilter_x] = x
gpr.setParams(param_list_to_dict(x_,param_struct,skeys))
lml = gpr.LML()
if SP.isnan(lml):
lml=1E6
lml_grad = gpr.LML_grad()
lml_grad = param_dict_to_list(lml_grad,skeys)
if (~SP.isfinite(lml_grad)).any():
idx = (~SP.isfinite(lml_grad))
lml_grad[idx] = 1E6
return lml, lml_grad[Ifilter_x]
skeys = SP.sort(list(params0.keys()))
param_struct = dict([(name,params0[name].shape) for name in skeys])
# mask params that should not be optimized
X0 = param_dict_to_list(params0,skeys)
if Ifilter is not None:
Ifilter_x = SP.array(param_dict_to_list(Ifilter,skeys),dtype=bool)
else:
Ifilter_x = SP.ones(len(X0),dtype='bool')
# add bounds if necessary
if bounds is not None:
_b = []
for key in skeys:
if key in list(bounds.keys()):
_b.extend(bounds[key])
else:
_b.extend([[-SP.inf,+SP.inf]]*params0[key].size)
bounds = SP.array(_b)
bounds = bounds[Ifilter_x]
LG.info('Starting optimization ...')
t = time.time()
x = X0.copy()[Ifilter_x]
RV = optimize(f,x,maxfun=int(max_iter),pgtol=pgtol,bounds=bounds,**kw_args)
#RVopt = optimize(f,x,messages=True,maxfun=int(max_iter),pgtol=pgtol,bounds=bounds)
#LG.info('%s'%OPT.tnc.RCSTRINGS[RVopt[2]])
#LG.info('Optimization is converged at iteration %d'%RVopt[1])
#LG.info('Total time: %.2fs'%(time.time()-t))
info = RV[2]
conv = info['warnflag']==0
if gradcheck:
err = OPT.check_grad(f,df,xopt)
LG.info("check_grad (post): %.2f"%err)
return conv,info | [
"def",
"opt_hyper",
"(",
"gpr",
",",
"Ifilter",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"opts",
"=",
"{",
"}",
",",
"*",
"args",
",",
"*",
"*",
"kw_args",
")",
":",
"if",
"'gradcheck'",
"in",
"opts",
":",
"gradcheck",
"=",
"opts",
"[",
"'gr... | optimize params
Input:
gpr: GP regression class
params0: dictionary filled with starting hyperparameters
opts: options for optimizer | [
"optimize",
"params"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/optimize/optimize_bfgs.py#L66-L142 |
ubccr/pinky | pinky/mol/atom.py | Atom.chival | def chival(self, bonds):
"""compute the chiral value around an atom given a list of bonds"""
# XXX I'm not sure how this works?
order = [bond.xatom(self) for bond in bonds]
return self._chirality(order) | python | def chival(self, bonds):
"""compute the chiral value around an atom given a list of bonds"""
# XXX I'm not sure how this works?
order = [bond.xatom(self) for bond in bonds]
return self._chirality(order) | [
"def",
"chival",
"(",
"self",
",",
"bonds",
")",
":",
"# XXX I'm not sure how this works?",
"order",
"=",
"[",
"bond",
".",
"xatom",
"(",
"self",
")",
"for",
"bond",
"in",
"bonds",
"]",
"return",
"self",
".",
"_chirality",
"(",
"order",
")"
] | compute the chiral value around an atom given a list of bonds | [
"compute",
"the",
"chiral",
"value",
"around",
"an",
"atom",
"given",
"a",
"list",
"of",
"bonds"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/mol/atom.py#L131-L135 |
ubccr/pinky | pinky/mol/atom.py | Atom.setchival | def setchival(self, bondorder, rotation):
"""compute chiral ordering of surrounding atoms"""
rotation = [None, "@", "@@"][(rotation % 2)]
# check to see if the bonds are attached
if not bondorder: # use the default xatoms
if len(self.oatoms) < 3 and self.explicit_hcount != 1:
raise PinkyError("Need to have an explicit hydrogen when specifying "\
"chirality with less than three bonds")
self._chirality = chirality.T(self.oatoms,
rotation)
return
if len(bondorder) != len(self.bonds):
raise AtomError("The order of all bonds must be specified")
for bond in bondorder:
if bond not in self.bonds:
raise AtomError("Specified bonds to assign chirality are not attatched to atom")
order = [bond.xatom(self) for bond in bonds]
self._chirality = chirality.T(order, rotation) | python | def setchival(self, bondorder, rotation):
"""compute chiral ordering of surrounding atoms"""
rotation = [None, "@", "@@"][(rotation % 2)]
# check to see if the bonds are attached
if not bondorder: # use the default xatoms
if len(self.oatoms) < 3 and self.explicit_hcount != 1:
raise PinkyError("Need to have an explicit hydrogen when specifying "\
"chirality with less than three bonds")
self._chirality = chirality.T(self.oatoms,
rotation)
return
if len(bondorder) != len(self.bonds):
raise AtomError("The order of all bonds must be specified")
for bond in bondorder:
if bond not in self.bonds:
raise AtomError("Specified bonds to assign chirality are not attatched to atom")
order = [bond.xatom(self) for bond in bonds]
self._chirality = chirality.T(order, rotation) | [
"def",
"setchival",
"(",
"self",
",",
"bondorder",
",",
"rotation",
")",
":",
"rotation",
"=",
"[",
"None",
",",
"\"@\"",
",",
"\"@@\"",
"]",
"[",
"(",
"rotation",
"%",
"2",
")",
"]",
"# check to see if the bonds are attached",
"if",
"not",
"bondorder",
":... | compute chiral ordering of surrounding atoms | [
"compute",
"chiral",
"ordering",
"of",
"surrounding",
"atoms"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/mol/atom.py#L137-L158 |
ubccr/pinky | pinky/canonicalization/disambiguate.py | FreedDisambiguate.disambiguate | def disambiguate(self, symclasses):
"""Use the connection to the atoms around a given vertex
as a multiplication function to disambiguate a vertex"""
offsets = self.offsets
result = symclasses[:]
for index in self.range:
try:
val = 1
for offset, bondtype in offsets[index]:
val *= symclasses[offset] * bondtype
except OverflowError:
# Hmm, how often does this occur?
val = 1L
for offset, bondtype in offsets[index]:
val *= symclasses[offset] * bondtype
result[index] = val
return result | python | def disambiguate(self, symclasses):
"""Use the connection to the atoms around a given vertex
as a multiplication function to disambiguate a vertex"""
offsets = self.offsets
result = symclasses[:]
for index in self.range:
try:
val = 1
for offset, bondtype in offsets[index]:
val *= symclasses[offset] * bondtype
except OverflowError:
# Hmm, how often does this occur?
val = 1L
for offset, bondtype in offsets[index]:
val *= symclasses[offset] * bondtype
result[index] = val
return result | [
"def",
"disambiguate",
"(",
"self",
",",
"symclasses",
")",
":",
"offsets",
"=",
"self",
".",
"offsets",
"result",
"=",
"symclasses",
"[",
":",
"]",
"for",
"index",
"in",
"self",
".",
"range",
":",
"try",
":",
"val",
"=",
"1",
"for",
"offset",
",",
... | Use the connection to the atoms around a given vertex
as a multiplication function to disambiguate a vertex | [
"Use",
"the",
"connection",
"to",
"the",
"atoms",
"around",
"a",
"given",
"vertex",
"as",
"a",
"multiplication",
"function",
"to",
"disambiguate",
"a",
"vertex"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/disambiguate.py#L138-L154 |
ubccr/pinky | pinky/canonicalization/disambiguate.py | FreedDisambiguate.rank | def rank(self):
"""convert a list of integers so that the lowest integer
is 0, the next lowest is 1 ...
note: modifies list in place"""
# XXX FIX ME, should the lowest value be 1 or 0?
symclasses = self.symclasses
stableSort = map(None, symclasses, range(len(symclasses)))
stableSort.sort()
last = None
x = -1
for order, i in stableSort:
if order != last:
x += 1
last = order
symclasses[i] = x | python | def rank(self):
"""convert a list of integers so that the lowest integer
is 0, the next lowest is 1 ...
note: modifies list in place"""
# XXX FIX ME, should the lowest value be 1 or 0?
symclasses = self.symclasses
stableSort = map(None, symclasses, range(len(symclasses)))
stableSort.sort()
last = None
x = -1
for order, i in stableSort:
if order != last:
x += 1
last = order
symclasses[i] = x | [
"def",
"rank",
"(",
"self",
")",
":",
"# XXX FIX ME, should the lowest value be 1 or 0?",
"symclasses",
"=",
"self",
".",
"symclasses",
"stableSort",
"=",
"map",
"(",
"None",
",",
"symclasses",
",",
"range",
"(",
"len",
"(",
"symclasses",
")",
")",
")",
"stabl... | convert a list of integers so that the lowest integer
is 0, the next lowest is 1 ...
note: modifies list in place | [
"convert",
"a",
"list",
"of",
"integers",
"so",
"that",
"the",
"lowest",
"integer",
"is",
"0",
"the",
"next",
"lowest",
"is",
"1",
"...",
"note",
":",
"modifies",
"list",
"in",
"place"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/disambiguate.py#L156-L171 |
ubccr/pinky | pinky/canonicalization/disambiguate.py | FreedDisambiguate.breakRankTies | def breakRankTies(self, oldsym, newsym):
"""break Ties to form a new list with the same integer ordering
from high to low
Example
old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4)
new = [60, 2 61,90,99]
res = [ 4, 0, 3, 1, 2]
* * This tie is broken in this case
"""
stableSort = map(None, oldsym, newsym, range(len(oldsym)))
stableSort.sort()
lastOld, lastNew = None, None
x = -1
for old, new, index in stableSort:
if old != lastOld:
x += 1
# the last old value was changed, so update both
lastOld = old
lastNew = new
elif new != lastNew:
# break the tie based on the new info (update lastNew)
x += 1
lastNew = new
newsym[index] = x | python | def breakRankTies(self, oldsym, newsym):
"""break Ties to form a new list with the same integer ordering
from high to low
Example
old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4)
new = [60, 2 61,90,99]
res = [ 4, 0, 3, 1, 2]
* * This tie is broken in this case
"""
stableSort = map(None, oldsym, newsym, range(len(oldsym)))
stableSort.sort()
lastOld, lastNew = None, None
x = -1
for old, new, index in stableSort:
if old != lastOld:
x += 1
# the last old value was changed, so update both
lastOld = old
lastNew = new
elif new != lastNew:
# break the tie based on the new info (update lastNew)
x += 1
lastNew = new
newsym[index] = x | [
"def",
"breakRankTies",
"(",
"self",
",",
"oldsym",
",",
"newsym",
")",
":",
"stableSort",
"=",
"map",
"(",
"None",
",",
"oldsym",
",",
"newsym",
",",
"range",
"(",
"len",
"(",
"oldsym",
")",
")",
")",
"stableSort",
".",
"sort",
"(",
")",
"lastOld",
... | break Ties to form a new list with the same integer ordering
from high to low
Example
old = [ 4, 2, 4, 7, 8] (Two ties, 4 and 4)
new = [60, 2 61,90,99]
res = [ 4, 0, 3, 1, 2]
* * This tie is broken in this case | [
"break",
"Ties",
"to",
"form",
"a",
"new",
"list",
"with",
"the",
"same",
"integer",
"ordering",
"from",
"high",
"to",
"low"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/disambiguate.py#L173-L198 |
ubccr/pinky | pinky/canonicalization/disambiguate.py | FreedDisambiguate.findLowest | def findLowest(self, symorders):
"""Find the position of the first lowest tie in a
symorder or -1 if there are no ties"""
_range = range(len(symorders))
stableSymorders = map(None, symorders, _range)
# XXX FIX ME
# Do I need to sort?
stableSymorders.sort()
lowest = None
for index in _range:
if stableSymorders[index][0] == lowest:
return stableSymorders[index-1][1]
lowest = stableSymorders[index][0]
return -1 | python | def findLowest(self, symorders):
"""Find the position of the first lowest tie in a
symorder or -1 if there are no ties"""
_range = range(len(symorders))
stableSymorders = map(None, symorders, _range)
# XXX FIX ME
# Do I need to sort?
stableSymorders.sort()
lowest = None
for index in _range:
if stableSymorders[index][0] == lowest:
return stableSymorders[index-1][1]
lowest = stableSymorders[index][0]
return -1 | [
"def",
"findLowest",
"(",
"self",
",",
"symorders",
")",
":",
"_range",
"=",
"range",
"(",
"len",
"(",
"symorders",
")",
")",
"stableSymorders",
"=",
"map",
"(",
"None",
",",
"symorders",
",",
"_range",
")",
"# XXX FIX ME",
"# Do I need to sort?",
"stableSym... | Find the position of the first lowest tie in a
symorder or -1 if there are no ties | [
"Find",
"the",
"position",
"of",
"the",
"first",
"lowest",
"tie",
"in",
"a",
"symorder",
"or",
"-",
"1",
"if",
"there",
"are",
"no",
"ties"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/disambiguate.py#L200-L214 |
ubccr/pinky | pinky/canonicalization/disambiguate.py | FreedDisambiguate.findInvariant | def findInvariant(self, symclasses):
"""(symclasses) -> converge the disambiguity function
until we have an invariant"""
get = primes.primes.get
disambiguate = self.disambiguate
breakRankTies = self.breakRankTies
while 1:
newSyms = map(get, symclasses)
newSyms = disambiguate(newSyms)
breakRankTies(symclasses, newSyms)
if symclasses == newSyms:
return newSyms
symclasses = newSyms | python | def findInvariant(self, symclasses):
"""(symclasses) -> converge the disambiguity function
until we have an invariant"""
get = primes.primes.get
disambiguate = self.disambiguate
breakRankTies = self.breakRankTies
while 1:
newSyms = map(get, symclasses)
newSyms = disambiguate(newSyms)
breakRankTies(symclasses, newSyms)
if symclasses == newSyms:
return newSyms
symclasses = newSyms | [
"def",
"findInvariant",
"(",
"self",
",",
"symclasses",
")",
":",
"get",
"=",
"primes",
".",
"primes",
".",
"get",
"disambiguate",
"=",
"self",
".",
"disambiguate",
"breakRankTies",
"=",
"self",
".",
"breakRankTies",
"while",
"1",
":",
"newSyms",
"=",
"map... | (symclasses) -> converge the disambiguity function
until we have an invariant | [
"(",
"symclasses",
")",
"-",
">",
"converge",
"the",
"disambiguity",
"function",
"until",
"we",
"have",
"an",
"invariant"
] | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/disambiguate.py#L216-L229 |
ubccr/pinky | pinky/canonicalization/disambiguate.py | FreedDisambiguate.findInvariantPartitioning | def findInvariantPartitioning(self):
"""Keep the initial ordering of the symmetry orders
but make all values unique. For example, if there are
two symmetry orders equal to 0, convert them to 0 and 1
and add 1 to the remaining orders
[0, 1, 0, 1]
should become
[0, 2, 1, 3]"""
symorders = self.symorders[:]
_range = range(len(symorders))
while 1:
pos = self.findLowest(symorders)
if pos == -1:
self.symorders = symorders
return
for i in _range:
symorders[i] = symorders[i] * 2 + 1
symorders[pos] = symorders[pos] - 1
symorders = self.findInvariant(symorders) | python | def findInvariantPartitioning(self):
"""Keep the initial ordering of the symmetry orders
but make all values unique. For example, if there are
two symmetry orders equal to 0, convert them to 0 and 1
and add 1 to the remaining orders
[0, 1, 0, 1]
should become
[0, 2, 1, 3]"""
symorders = self.symorders[:]
_range = range(len(symorders))
while 1:
pos = self.findLowest(symorders)
if pos == -1:
self.symorders = symorders
return
for i in _range:
symorders[i] = symorders[i] * 2 + 1
symorders[pos] = symorders[pos] - 1
symorders = self.findInvariant(symorders) | [
"def",
"findInvariantPartitioning",
"(",
"self",
")",
":",
"symorders",
"=",
"self",
".",
"symorders",
"[",
":",
"]",
"_range",
"=",
"range",
"(",
"len",
"(",
"symorders",
")",
")",
"while",
"1",
":",
"pos",
"=",
"self",
".",
"findLowest",
"(",
"symord... | Keep the initial ordering of the symmetry orders
but make all values unique. For example, if there are
two symmetry orders equal to 0, convert them to 0 and 1
and add 1 to the remaining orders
[0, 1, 0, 1]
should become
[0, 2, 1, 3] | [
"Keep",
"the",
"initial",
"ordering",
"of",
"the",
"symmetry",
"orders",
"but",
"make",
"all",
"values",
"unique",
".",
"For",
"example",
"if",
"there",
"are",
"two",
"symmetry",
"orders",
"equal",
"to",
"0",
"convert",
"them",
"to",
"0",
"and",
"1",
"an... | train | https://github.com/ubccr/pinky/blob/e9d6e8ff72aa7f670b591e3bd3629cb879db1a93/pinky/canonicalization/disambiguate.py#L231-L252 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient._api_call | def _api_call(self, method, target, args=None):
"""Create a Request object and execute the call to the API Server.
Parameters
method (str)
HTTP request (e.g. 'POST').
target (str)
The target URL with leading slash (e.g. '/v1/products').
args (dict)
Optional dictionary of arguments to attach to the request.
Returns
(Response)
The server's response to an HTTP request.
"""
self.refresh_oauth_credential()
request = Request(
auth_session=self.session,
api_host=self.api_host,
method=method,
path=target,
args=args,
)
return request.execute() | python | def _api_call(self, method, target, args=None):
"""Create a Request object and execute the call to the API Server.
Parameters
method (str)
HTTP request (e.g. 'POST').
target (str)
The target URL with leading slash (e.g. '/v1/products').
args (dict)
Optional dictionary of arguments to attach to the request.
Returns
(Response)
The server's response to an HTTP request.
"""
self.refresh_oauth_credential()
request = Request(
auth_session=self.session,
api_host=self.api_host,
method=method,
path=target,
args=args,
)
return request.execute() | [
"def",
"_api_call",
"(",
"self",
",",
"method",
",",
"target",
",",
"args",
"=",
"None",
")",
":",
"self",
".",
"refresh_oauth_credential",
"(",
")",
"request",
"=",
"Request",
"(",
"auth_session",
"=",
"self",
".",
"session",
",",
"api_host",
"=",
"self... | Create a Request object and execute the call to the API Server.
Parameters
method (str)
HTTP request (e.g. 'POST').
target (str)
The target URL with leading slash (e.g. '/v1/products').
args (dict)
Optional dictionary of arguments to attach to the request.
Returns
(Response)
The server's response to an HTTP request. | [
"Create",
"a",
"Request",
"object",
"and",
"execute",
"the",
"call",
"to",
"the",
"API",
"Server",
".",
"Parameters",
"method",
"(",
"str",
")",
"HTTP",
"request",
"(",
"e",
".",
"g",
".",
"POST",
")",
".",
"target",
"(",
"str",
")",
"The",
"target",... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L54-L77 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.get_ride_types | def get_ride_types(self, latitude, longitude, ride_type=None):
"""Get information about the Ride Types offered by Lyft at a given location.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
ride_type (str)
Optional specific ride type information only.
Returns
(Response)
A Response object containing available ride_type(s) information.
"""
args = OrderedDict([
('lat', latitude),
('lng', longitude),
('ride_type', ride_type),
])
return self._api_call('GET', 'v1/ridetypes', args=args) | python | def get_ride_types(self, latitude, longitude, ride_type=None):
"""Get information about the Ride Types offered by Lyft at a given location.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
ride_type (str)
Optional specific ride type information only.
Returns
(Response)
A Response object containing available ride_type(s) information.
"""
args = OrderedDict([
('lat', latitude),
('lng', longitude),
('ride_type', ride_type),
])
return self._api_call('GET', 'v1/ridetypes', args=args) | [
"def",
"get_ride_types",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"ride_type",
"=",
"None",
")",
":",
"args",
"=",
"OrderedDict",
"(",
"[",
"(",
"'lat'",
",",
"latitude",
")",
",",
"(",
"'lng'",
",",
"longitude",
")",
",",
"(",
"'ride_type'... | Get information about the Ride Types offered by Lyft at a given location.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
ride_type (str)
Optional specific ride type information only.
Returns
(Response)
A Response object containing available ride_type(s) information. | [
"Get",
"information",
"about",
"the",
"Ride",
"Types",
"offered",
"by",
"Lyft",
"at",
"a",
"given",
"location",
".",
"Parameters",
"latitude",
"(",
"float",
")",
"The",
"latitude",
"component",
"of",
"a",
"location",
".",
"longitude",
"(",
"float",
")",
"T... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L79-L98 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.get_pickup_time_estimates | def get_pickup_time_estimates(self, latitude, longitude, ride_type=None):
"""Get pickup time estimates (ETA) for products at a given location.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
ride_type (str)
Optional specific ride type pickup estimate only.
Returns
(Response)
A Response containing each product's pickup time estimates.
"""
args = OrderedDict([
('lat', latitude),
('lng', longitude),
('ride_type', ride_type),
])
return self._api_call('GET', 'v1/eta', args=args) | python | def get_pickup_time_estimates(self, latitude, longitude, ride_type=None):
"""Get pickup time estimates (ETA) for products at a given location.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
ride_type (str)
Optional specific ride type pickup estimate only.
Returns
(Response)
A Response containing each product's pickup time estimates.
"""
args = OrderedDict([
('lat', latitude),
('lng', longitude),
('ride_type', ride_type),
])
return self._api_call('GET', 'v1/eta', args=args) | [
"def",
"get_pickup_time_estimates",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"ride_type",
"=",
"None",
")",
":",
"args",
"=",
"OrderedDict",
"(",
"[",
"(",
"'lat'",
",",
"latitude",
")",
",",
"(",
"'lng'",
",",
"longitude",
")",
",",
"(",
"... | Get pickup time estimates (ETA) for products at a given location.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
ride_type (str)
Optional specific ride type pickup estimate only.
Returns
(Response)
A Response containing each product's pickup time estimates. | [
"Get",
"pickup",
"time",
"estimates",
"(",
"ETA",
")",
"for",
"products",
"at",
"a",
"given",
"location",
".",
"Parameters",
"latitude",
"(",
"float",
")",
"The",
"latitude",
"component",
"of",
"a",
"location",
".",
"longitude",
"(",
"float",
")",
"The",
... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L100-L119 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.get_cost_estimates | def get_cost_estimates(
self,
start_latitude,
start_longitude,
end_latitude=None,
end_longitude=None,
ride_type=None,
):
"""Get cost estimates (in cents) for rides at a given location.
Parameters
start_latitude (float)
The latitude component of a start location.
start_longitude (float)
The longitude component of a start location.
end_latitude (float)
Optional latitude component of a end location.
If the destination parameters are not supplied, the endpoint will
simply return the Prime Time pricing at the specified location.
end_longitude (float)
Optional longitude component of a end location.
If the destination parameters are not supplied, the endpoint will
simply return the Prime Time pricing at the specified location.
ride_type (str)
Optional specific ride type price estimate only.
Returns
(Response)
A Response object containing each product's price estimates.
"""
args = OrderedDict([
('start_lat', start_latitude),
('start_lng', start_longitude),
('end_lat', end_latitude),
('end_lng', end_longitude),
('ride_type', ride_type),
])
return self._api_call('GET', 'v1/cost', args=args) | python | def get_cost_estimates(
self,
start_latitude,
start_longitude,
end_latitude=None,
end_longitude=None,
ride_type=None,
):
"""Get cost estimates (in cents) for rides at a given location.
Parameters
start_latitude (float)
The latitude component of a start location.
start_longitude (float)
The longitude component of a start location.
end_latitude (float)
Optional latitude component of a end location.
If the destination parameters are not supplied, the endpoint will
simply return the Prime Time pricing at the specified location.
end_longitude (float)
Optional longitude component of a end location.
If the destination parameters are not supplied, the endpoint will
simply return the Prime Time pricing at the specified location.
ride_type (str)
Optional specific ride type price estimate only.
Returns
(Response)
A Response object containing each product's price estimates.
"""
args = OrderedDict([
('start_lat', start_latitude),
('start_lng', start_longitude),
('end_lat', end_latitude),
('end_lng', end_longitude),
('ride_type', ride_type),
])
return self._api_call('GET', 'v1/cost', args=args) | [
"def",
"get_cost_estimates",
"(",
"self",
",",
"start_latitude",
",",
"start_longitude",
",",
"end_latitude",
"=",
"None",
",",
"end_longitude",
"=",
"None",
",",
"ride_type",
"=",
"None",
",",
")",
":",
"args",
"=",
"OrderedDict",
"(",
"[",
"(",
"'start_lat... | Get cost estimates (in cents) for rides at a given location.
Parameters
start_latitude (float)
The latitude component of a start location.
start_longitude (float)
The longitude component of a start location.
end_latitude (float)
Optional latitude component of a end location.
If the destination parameters are not supplied, the endpoint will
simply return the Prime Time pricing at the specified location.
end_longitude (float)
Optional longitude component of a end location.
If the destination parameters are not supplied, the endpoint will
simply return the Prime Time pricing at the specified location.
ride_type (str)
Optional specific ride type price estimate only.
Returns
(Response)
A Response object containing each product's price estimates. | [
"Get",
"cost",
"estimates",
"(",
"in",
"cents",
")",
"for",
"rides",
"at",
"a",
"given",
"location",
".",
"Parameters",
"start_latitude",
"(",
"float",
")",
"The",
"latitude",
"component",
"of",
"a",
"start",
"location",
".",
"start_longitude",
"(",
"float",... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L121-L157 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.get_drivers | def get_drivers(self, latitude, longitude):
"""Get information about the location of drivers available near a location.
A list of 5 locations for a sample of drivers for each ride type will be provided.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
Returns
(Response)
A Response object containing available drivers information
near the specified location.
"""
args = OrderedDict([
('lat', latitude),
('lng', longitude),
])
return self._api_call('GET', 'v1/drivers', args=args) | python | def get_drivers(self, latitude, longitude):
"""Get information about the location of drivers available near a location.
A list of 5 locations for a sample of drivers for each ride type will be provided.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
Returns
(Response)
A Response object containing available drivers information
near the specified location.
"""
args = OrderedDict([
('lat', latitude),
('lng', longitude),
])
return self._api_call('GET', 'v1/drivers', args=args) | [
"def",
"get_drivers",
"(",
"self",
",",
"latitude",
",",
"longitude",
")",
":",
"args",
"=",
"OrderedDict",
"(",
"[",
"(",
"'lat'",
",",
"latitude",
")",
",",
"(",
"'lng'",
",",
"longitude",
")",
",",
"]",
")",
"return",
"self",
".",
"_api_call",
"("... | Get information about the location of drivers available near a location.
A list of 5 locations for a sample of drivers for each ride type will be provided.
Parameters
latitude (float)
The latitude component of a location.
longitude (float)
The longitude component of a location.
Returns
(Response)
A Response object containing available drivers information
near the specified location. | [
"Get",
"information",
"about",
"the",
"location",
"of",
"drivers",
"available",
"near",
"a",
"location",
".",
"A",
"list",
"of",
"5",
"locations",
"for",
"a",
"sample",
"of",
"drivers",
"for",
"each",
"ride",
"type",
"will",
"be",
"provided",
".",
"Paramet... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L159-L177 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.request_ride | def request_ride(
self,
ride_type=None,
start_latitude=None,
start_longitude=None,
start_address=None,
end_latitude=None,
end_longitude=None,
end_address=None,
primetime_confirmation_token=None,
):
"""Request a ride on behalf of an Lyft user.
Parameters
ride_type (str)
Name of the type of ride you're requesting.
E.g., lyft, lyft_plus
start_latitude (float)
Latitude component of a start location.
start_longitude (float)
Longitude component of a start location.
start_address (str)
Optional pickup address.
end_latitude (float)
Optional latitude component of a end location.
Destination would be NULL in this case.
end_longitude (float)
Optional longitude component of a end location.
Destination would be NULL in this case.
end_address (str)
Optional destination address.
primetime_confirmation_token (str)
Optional string containing the Prime Time confirmation token
to book rides having Prime Time Pricing.
Returns
(Response)
A Response object containing the ride request ID and other
details about the requested ride..
"""
args = {
'ride_type': ride_type,
'origin': {
'lat': start_latitude,
'lng': start_longitude,
'address': start_address,
},
'destination': {
'lat': end_latitude,
'lng': end_longitude,
'address': end_address,
},
'primetime_confirmation_token': primetime_confirmation_token,
}
return self._api_call('POST', 'v1/rides', args=args) | python | def request_ride(
self,
ride_type=None,
start_latitude=None,
start_longitude=None,
start_address=None,
end_latitude=None,
end_longitude=None,
end_address=None,
primetime_confirmation_token=None,
):
"""Request a ride on behalf of an Lyft user.
Parameters
ride_type (str)
Name of the type of ride you're requesting.
E.g., lyft, lyft_plus
start_latitude (float)
Latitude component of a start location.
start_longitude (float)
Longitude component of a start location.
start_address (str)
Optional pickup address.
end_latitude (float)
Optional latitude component of a end location.
Destination would be NULL in this case.
end_longitude (float)
Optional longitude component of a end location.
Destination would be NULL in this case.
end_address (str)
Optional destination address.
primetime_confirmation_token (str)
Optional string containing the Prime Time confirmation token
to book rides having Prime Time Pricing.
Returns
(Response)
A Response object containing the ride request ID and other
details about the requested ride..
"""
args = {
'ride_type': ride_type,
'origin': {
'lat': start_latitude,
'lng': start_longitude,
'address': start_address,
},
'destination': {
'lat': end_latitude,
'lng': end_longitude,
'address': end_address,
},
'primetime_confirmation_token': primetime_confirmation_token,
}
return self._api_call('POST', 'v1/rides', args=args) | [
"def",
"request_ride",
"(",
"self",
",",
"ride_type",
"=",
"None",
",",
"start_latitude",
"=",
"None",
",",
"start_longitude",
"=",
"None",
",",
"start_address",
"=",
"None",
",",
"end_latitude",
"=",
"None",
",",
"end_longitude",
"=",
"None",
",",
"end_addr... | Request a ride on behalf of an Lyft user.
Parameters
ride_type (str)
Name of the type of ride you're requesting.
E.g., lyft, lyft_plus
start_latitude (float)
Latitude component of a start location.
start_longitude (float)
Longitude component of a start location.
start_address (str)
Optional pickup address.
end_latitude (float)
Optional latitude component of a end location.
Destination would be NULL in this case.
end_longitude (float)
Optional longitude component of a end location.
Destination would be NULL in this case.
end_address (str)
Optional destination address.
primetime_confirmation_token (str)
Optional string containing the Prime Time confirmation token
to book rides having Prime Time Pricing.
Returns
(Response)
A Response object containing the ride request ID and other
details about the requested ride.. | [
"Request",
"a",
"ride",
"on",
"behalf",
"of",
"an",
"Lyft",
"user",
".",
"Parameters",
"ride_type",
"(",
"str",
")",
"Name",
"of",
"the",
"type",
"of",
"ride",
"you",
"re",
"requesting",
".",
"E",
".",
"g",
".",
"lyft",
"lyft_plus",
"start_latitude",
"... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L179-L232 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.cancel_ride | def cancel_ride(self, ride_id, cancel_confirmation_token=None):
"""Cancel an ongoing ride on behalf of a user.
Params
ride_id (str)
The unique ID of the Ride Request.
cancel_confirmation_token (str)
Optional string containing the cancellation confirmation token.
Returns
(Response)
A Response object with successful status_code
if ride was canceled.
"""
args = {
"cancel_confirmation_token": cancel_confirmation_token
}
endpoint = 'v1/rides/{}/cancel'.format(ride_id)
return self._api_call('POST', endpoint, args=args) | python | def cancel_ride(self, ride_id, cancel_confirmation_token=None):
"""Cancel an ongoing ride on behalf of a user.
Params
ride_id (str)
The unique ID of the Ride Request.
cancel_confirmation_token (str)
Optional string containing the cancellation confirmation token.
Returns
(Response)
A Response object with successful status_code
if ride was canceled.
"""
args = {
"cancel_confirmation_token": cancel_confirmation_token
}
endpoint = 'v1/rides/{}/cancel'.format(ride_id)
return self._api_call('POST', endpoint, args=args) | [
"def",
"cancel_ride",
"(",
"self",
",",
"ride_id",
",",
"cancel_confirmation_token",
"=",
"None",
")",
":",
"args",
"=",
"{",
"\"cancel_confirmation_token\"",
":",
"cancel_confirmation_token",
"}",
"endpoint",
"=",
"'v1/rides/{}/cancel'",
".",
"format",
"(",
"ride_i... | Cancel an ongoing ride on behalf of a user.
Params
ride_id (str)
The unique ID of the Ride Request.
cancel_confirmation_token (str)
Optional string containing the cancellation confirmation token.
Returns
(Response)
A Response object with successful status_code
if ride was canceled. | [
"Cancel",
"an",
"ongoing",
"ride",
"on",
"behalf",
"of",
"a",
"user",
".",
"Params",
"ride_id",
"(",
"str",
")",
"The",
"unique",
"ID",
"of",
"the",
"Ride",
"Request",
".",
"cancel_confirmation_token",
"(",
"str",
")",
"Optional",
"string",
"containing",
"... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L247-L263 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.rate_tip_ride | def rate_tip_ride(self,
ride_id,
rating,
tip_amount=None,
tip_currency=None,
feedback=None
):
"""Provide a rating, tip or feedback for the specified ride.
Params
ride_id (str)
The unique ID of the Ride Request.
rating (int)
An integer between 1 and 5
tip_amount
Optional integer amount greater than 0 in minor currency units e.g. 200 for $2
tip_currency
Optional 3-character currency code e.g. 'USD'
feedback
Optional feedback message
Returns
(Response)
A Response object with successful status_code
if rating was submitted.
"""
args = {
"rating": rating,
"tip.amount": tip_amount,
"tip.currency": tip_currency,
"feedback": feedback,
}
endpoint = 'v1/rides/{}/rating'.format(ride_id)
return self._api_call('PUT', endpoint, args=args) | python | def rate_tip_ride(self,
ride_id,
rating,
tip_amount=None,
tip_currency=None,
feedback=None
):
"""Provide a rating, tip or feedback for the specified ride.
Params
ride_id (str)
The unique ID of the Ride Request.
rating (int)
An integer between 1 and 5
tip_amount
Optional integer amount greater than 0 in minor currency units e.g. 200 for $2
tip_currency
Optional 3-character currency code e.g. 'USD'
feedback
Optional feedback message
Returns
(Response)
A Response object with successful status_code
if rating was submitted.
"""
args = {
"rating": rating,
"tip.amount": tip_amount,
"tip.currency": tip_currency,
"feedback": feedback,
}
endpoint = 'v1/rides/{}/rating'.format(ride_id)
return self._api_call('PUT', endpoint, args=args) | [
"def",
"rate_tip_ride",
"(",
"self",
",",
"ride_id",
",",
"rating",
",",
"tip_amount",
"=",
"None",
",",
"tip_currency",
"=",
"None",
",",
"feedback",
"=",
"None",
")",
":",
"args",
"=",
"{",
"\"rating\"",
":",
"rating",
",",
"\"tip.amount\"",
":",
"tip_... | Provide a rating, tip or feedback for the specified ride.
Params
ride_id (str)
The unique ID of the Ride Request.
rating (int)
An integer between 1 and 5
tip_amount
Optional integer amount greater than 0 in minor currency units e.g. 200 for $2
tip_currency
Optional 3-character currency code e.g. 'USD'
feedback
Optional feedback message
Returns
(Response)
A Response object with successful status_code
if rating was submitted. | [
"Provide",
"a",
"rating",
"tip",
"or",
"feedback",
"for",
"the",
"specified",
"ride",
".",
"Params",
"ride_id",
"(",
"str",
")",
"The",
"unique",
"ID",
"of",
"the",
"Ride",
"Request",
".",
"rating",
"(",
"int",
")",
"An",
"integer",
"between",
"1",
"an... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L265-L297 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.get_user_ride_history | def get_user_ride_history(self, start_time, end_time, limit=None):
"""Get activity about the user's lifetime activity with Lyft.
Parameters
start_time (datetime)
Restrict to rides starting after this point in time.
The earliest supported date is 2015-01-01T00:00:00Z
end_time (datetime)
Optional Restrict to rides starting before this point in time.
The earliest supported date is 2015-01-01T00:00:00Z
limit (int)
Optional integer amount of results to return. Default is 10.
Returns
(Response)
A Response object containing ride history.
"""
args = {
'start_time': start_time,
'end_time': end_time,
'limit': limit,
}
return self._api_call('GET', 'v1/rides', args=args) | python | def get_user_ride_history(self, start_time, end_time, limit=None):
"""Get activity about the user's lifetime activity with Lyft.
Parameters
start_time (datetime)
Restrict to rides starting after this point in time.
The earliest supported date is 2015-01-01T00:00:00Z
end_time (datetime)
Optional Restrict to rides starting before this point in time.
The earliest supported date is 2015-01-01T00:00:00Z
limit (int)
Optional integer amount of results to return. Default is 10.
Returns
(Response)
A Response object containing ride history.
"""
args = {
'start_time': start_time,
'end_time': end_time,
'limit': limit,
}
return self._api_call('GET', 'v1/rides', args=args) | [
"def",
"get_user_ride_history",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"limit",
"=",
"None",
")",
":",
"args",
"=",
"{",
"'start_time'",
":",
"start_time",
",",
"'end_time'",
":",
"end_time",
",",
"'limit'",
":",
"limit",
",",
"}",
"return",... | Get activity about the user's lifetime activity with Lyft.
Parameters
start_time (datetime)
Restrict to rides starting after this point in time.
The earliest supported date is 2015-01-01T00:00:00Z
end_time (datetime)
Optional Restrict to rides starting before this point in time.
The earliest supported date is 2015-01-01T00:00:00Z
limit (int)
Optional integer amount of results to return. Default is 10.
Returns
(Response)
A Response object containing ride history. | [
"Get",
"activity",
"about",
"the",
"user",
"s",
"lifetime",
"activity",
"with",
"Lyft",
".",
"Parameters",
"start_time",
"(",
"datetime",
")",
"Restrict",
"to",
"rides",
"starting",
"after",
"this",
"point",
"in",
"time",
".",
"The",
"earliest",
"supported",
... | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L312-L333 |
gautammishra/lyft-rides-python-sdk | lyft_rides/client.py | LyftRidesClient.refresh_oauth_credential | def refresh_oauth_credential(self):
"""Refresh session's OAuth 2.0 credentials if they are stale."""
credential = self.session.oauth2credential
if credential.is_stale():
refresh_session = refresh_access_token(credential)
self.session = refresh_session | python | def refresh_oauth_credential(self):
"""Refresh session's OAuth 2.0 credentials if they are stale."""
credential = self.session.oauth2credential
if credential.is_stale():
refresh_session = refresh_access_token(credential)
self.session = refresh_session | [
"def",
"refresh_oauth_credential",
"(",
"self",
")",
":",
"credential",
"=",
"self",
".",
"session",
".",
"oauth2credential",
"if",
"credential",
".",
"is_stale",
"(",
")",
":",
"refresh_session",
"=",
"refresh_access_token",
"(",
"credential",
")",
"self",
".",... | Refresh session's OAuth 2.0 credentials if they are stale. | [
"Refresh",
"session",
"s",
"OAuth",
"2",
".",
"0",
"credentials",
"if",
"they",
"are",
"stale",
"."
] | train | https://github.com/gautammishra/lyft-rides-python-sdk/blob/b6d96a0fceaf7dc3425153c418a8e25c57803431/lyft_rides/client.py#L343-L349 |
limix/limix-core | limix_core/covar/diagonal.py | DiagonalCov.setCovariance | def setCovariance(self,cov):
""" set hyperparameters from given covariance """
self.setParams(sp.log(sp.diagonal(cov))) | python | def setCovariance(self,cov):
""" set hyperparameters from given covariance """
self.setParams(sp.log(sp.diagonal(cov))) | [
"def",
"setCovariance",
"(",
"self",
",",
"cov",
")",
":",
"self",
".",
"setParams",
"(",
"sp",
".",
"log",
"(",
"sp",
".",
"diagonal",
"(",
"cov",
")",
")",
")"
] | set hyperparameters from given covariance | [
"set",
"hyperparameters",
"from",
"given",
"covariance"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/diagonal.py#L81-L83 |
limix/limix-core | limix_core/covar/lowrank.py | LowRankCov.setCovariance | def setCovariance(self, cov):
""" makes lowrank approximation of cov """
assert cov.shape[0]==self.dim, 'Dimension mismatch.'
S, U = la.eigh(cov)
U = U[:,::-1]
S = S[::-1]
_X = U[:, :self.rank] * sp.sqrt(S[:self.rank])
self.X = _X | python | def setCovariance(self, cov):
""" makes lowrank approximation of cov """
assert cov.shape[0]==self.dim, 'Dimension mismatch.'
S, U = la.eigh(cov)
U = U[:,::-1]
S = S[::-1]
_X = U[:, :self.rank] * sp.sqrt(S[:self.rank])
self.X = _X | [
"def",
"setCovariance",
"(",
"self",
",",
"cov",
")",
":",
"assert",
"cov",
".",
"shape",
"[",
"0",
"]",
"==",
"self",
".",
"dim",
",",
"'Dimension mismatch.'",
"S",
",",
"U",
"=",
"la",
".",
"eigh",
"(",
"cov",
")",
"U",
"=",
"U",
"[",
":",
",... | makes lowrank approximation of cov | [
"makes",
"lowrank",
"approximation",
"of",
"cov"
] | train | https://github.com/limix/limix-core/blob/5c590b4d351409f83ca320844b4897ce92203814/limix_core/covar/lowrank.py#L83-L90 |
all-umass/graphs | graphs/datasets/mountain_car.py | mountain_car_trajectories | def mountain_car_trajectories(num_traj):
'''Collect data using random hard-coded policies on MountainCar.
num_traj : int, number of trajectories to collect
Returns (trajectories, traces)
'''
domain = MountainCar()
slopes = np.random.normal(0, 0.01, size=num_traj)
v0s = np.random.normal(0, 0.005, size=num_traj)
trajectories = []
traces = []
norm = np.array((domain.MAX_POS-domain.MIN_POS,
domain.MAX_VEL-domain.MIN_VEL))
for m,b in zip(slopes, v0s):
mcar_policy = lambda s: 0 if s[0]*m + s[1] + b > 0 else 2
start = (np.random.uniform(domain.MIN_POS,domain.MAX_POS),
np.random.uniform(domain.MIN_VEL,domain.MAX_VEL))
samples = _run_episode(mcar_policy, domain, start, max_iters=40)
# normalize
samples.state /= norm
samples.next_state /= norm
traces.append(samples)
if samples.reward[-1] == 0:
# Don't include the warp to the final state.
trajectories.append(samples.state[:-1])
else:
trajectories.append(samples.state)
return trajectories, traces | python | def mountain_car_trajectories(num_traj):
'''Collect data using random hard-coded policies on MountainCar.
num_traj : int, number of trajectories to collect
Returns (trajectories, traces)
'''
domain = MountainCar()
slopes = np.random.normal(0, 0.01, size=num_traj)
v0s = np.random.normal(0, 0.005, size=num_traj)
trajectories = []
traces = []
norm = np.array((domain.MAX_POS-domain.MIN_POS,
domain.MAX_VEL-domain.MIN_VEL))
for m,b in zip(slopes, v0s):
mcar_policy = lambda s: 0 if s[0]*m + s[1] + b > 0 else 2
start = (np.random.uniform(domain.MIN_POS,domain.MAX_POS),
np.random.uniform(domain.MIN_VEL,domain.MAX_VEL))
samples = _run_episode(mcar_policy, domain, start, max_iters=40)
# normalize
samples.state /= norm
samples.next_state /= norm
traces.append(samples)
if samples.reward[-1] == 0:
# Don't include the warp to the final state.
trajectories.append(samples.state[:-1])
else:
trajectories.append(samples.state)
return trajectories, traces | [
"def",
"mountain_car_trajectories",
"(",
"num_traj",
")",
":",
"domain",
"=",
"MountainCar",
"(",
")",
"slopes",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"0.01",
",",
"size",
"=",
"num_traj",
")",
"v0s",
"=",
"np",
".",
"random",
".",
... | Collect data using random hard-coded policies on MountainCar.
num_traj : int, number of trajectories to collect
Returns (trajectories, traces) | [
"Collect",
"data",
"using",
"random",
"hard",
"-",
"coded",
"policies",
"on",
"MountainCar",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/datasets/mountain_car.py#L31-L60 |
stbraun/fuzzing | features/environment.py | before_all | def before_all(context):
"""Setup before all tests.
Initialize the logger framework.
:param context: test context.
"""
lf = LoggerFactory(config_file='../features/resources/test_config.yaml')
lf.initialize()
ll = lf.get_instance('environment')
ll.info('Logger initialized: {}'.format(lf.config))
ll.info('Initial test context: {}'.format(context)) | python | def before_all(context):
"""Setup before all tests.
Initialize the logger framework.
:param context: test context.
"""
lf = LoggerFactory(config_file='../features/resources/test_config.yaml')
lf.initialize()
ll = lf.get_instance('environment')
ll.info('Logger initialized: {}'.format(lf.config))
ll.info('Initial test context: {}'.format(context)) | [
"def",
"before_all",
"(",
"context",
")",
":",
"lf",
"=",
"LoggerFactory",
"(",
"config_file",
"=",
"'../features/resources/test_config.yaml'",
")",
"lf",
".",
"initialize",
"(",
")",
"ll",
"=",
"lf",
".",
"get_instance",
"(",
"'environment'",
")",
"ll",
".",
... | Setup before all tests.
Initialize the logger framework.
:param context: test context. | [
"Setup",
"before",
"all",
"tests",
"."
] | train | https://github.com/stbraun/fuzzing/blob/974a64472732d4e40db919d242149bf0856fe199/features/environment.py#L7-L18 |
pyroscope/pyrobase | src/pyrobase/osutil.py | shell_escape | def shell_escape(text, _safe=re.compile(r"^[-._,+a-zA-Z0-9]+$")):
"""Escape given string according to shell rules."""
if not text or _safe.match(text):
return text
squote = type(text)("'")
return squote + text.replace(squote, type(text)(r"'\''")) + squote | python | def shell_escape(text, _safe=re.compile(r"^[-._,+a-zA-Z0-9]+$")):
"""Escape given string according to shell rules."""
if not text or _safe.match(text):
return text
squote = type(text)("'")
return squote + text.replace(squote, type(text)(r"'\''")) + squote | [
"def",
"shell_escape",
"(",
"text",
",",
"_safe",
"=",
"re",
".",
"compile",
"(",
"r\"^[-._,+a-zA-Z0-9]+$\"",
")",
")",
":",
"if",
"not",
"text",
"or",
"_safe",
".",
"match",
"(",
"text",
")",
":",
"return",
"text",
"squote",
"=",
"type",
"(",
"text",
... | Escape given string according to shell rules. | [
"Escape",
"given",
"string",
"according",
"to",
"shell",
"rules",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/osutil.py#L25-L31 |
wangsix/vmo | vmo/plot.py | get_pattern_mat | def get_pattern_mat(oracle, pattern):
"""Output a matrix containing patterns in rows from a vmo.
:param oracle: input vmo object
:param pattern: pattern extracted from oracle
:return: a numpy matrix that could be used to visualize the pattern extracted.
"""
pattern_mat = np.zeros((len(pattern), oracle.n_states-1))
for i,p in enumerate(pattern):
length = p[1]
for s in p[0]:
pattern_mat[i][s-length:s-1] = 1
return pattern_mat | python | def get_pattern_mat(oracle, pattern):
"""Output a matrix containing patterns in rows from a vmo.
:param oracle: input vmo object
:param pattern: pattern extracted from oracle
:return: a numpy matrix that could be used to visualize the pattern extracted.
"""
pattern_mat = np.zeros((len(pattern), oracle.n_states-1))
for i,p in enumerate(pattern):
length = p[1]
for s in p[0]:
pattern_mat[i][s-length:s-1] = 1
return pattern_mat | [
"def",
"get_pattern_mat",
"(",
"oracle",
",",
"pattern",
")",
":",
"pattern_mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"pattern",
")",
",",
"oracle",
".",
"n_states",
"-",
"1",
")",
")",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"patt... | Output a matrix containing patterns in rows from a vmo.
:param oracle: input vmo object
:param pattern: pattern extracted from oracle
:return: a numpy matrix that could be used to visualize the pattern extracted. | [
"Output",
"a",
"matrix",
"containing",
"patterns",
"in",
"rows",
"from",
"a",
"vmo",
"."
] | train | https://github.com/wangsix/vmo/blob/bb1cc4cf1f33f0bb49e38c91126c1be1a0cdd09d/vmo/plot.py#L113-L127 |
pyroscope/pyrobase | src/pyrobase/webservice/imgur.py | fake_upload_from_url | def fake_upload_from_url(url):
""" Return a 'fake' upload data record, so that upload errors
can be mitigated by using an original / alternative URL,
especially when cross-loading from the web.
"""
return parts.Bunch(
image=parts.Bunch(
animated='false', bandwidth=0, caption=None, views=0, deletehash=None, hash=None,
name=(url.rsplit('/', 1) + [url])[1], title=None, type='image/*', width=0, height=0, size=0,
datetime=int(time.time()), # XXX was fmt.iso_datetime() - in API v2 this is a UNIX timestamp
id='xxxxxxx', link=url, account_id=0, account_url=None, ad_type=0, ad_url='',
description=None, favorite=False, in_gallery=False, in_most_viral=False,
is_ad=False, nsfw=None, section=None, tags=[], vote=None,
),
links=parts.Bunch(
delete_page=None, imgur_page=None,
original=url, large_thumbnail=url, small_square=url,
)) | python | def fake_upload_from_url(url):
""" Return a 'fake' upload data record, so that upload errors
can be mitigated by using an original / alternative URL,
especially when cross-loading from the web.
"""
return parts.Bunch(
image=parts.Bunch(
animated='false', bandwidth=0, caption=None, views=0, deletehash=None, hash=None,
name=(url.rsplit('/', 1) + [url])[1], title=None, type='image/*', width=0, height=0, size=0,
datetime=int(time.time()), # XXX was fmt.iso_datetime() - in API v2 this is a UNIX timestamp
id='xxxxxxx', link=url, account_id=0, account_url=None, ad_type=0, ad_url='',
description=None, favorite=False, in_gallery=False, in_most_viral=False,
is_ad=False, nsfw=None, section=None, tags=[], vote=None,
),
links=parts.Bunch(
delete_page=None, imgur_page=None,
original=url, large_thumbnail=url, small_square=url,
)) | [
"def",
"fake_upload_from_url",
"(",
"url",
")",
":",
"return",
"parts",
".",
"Bunch",
"(",
"image",
"=",
"parts",
".",
"Bunch",
"(",
"animated",
"=",
"'false'",
",",
"bandwidth",
"=",
"0",
",",
"caption",
"=",
"None",
",",
"views",
"=",
"0",
",",
"de... | Return a 'fake' upload data record, so that upload errors
can be mitigated by using an original / alternative URL,
especially when cross-loading from the web. | [
"Return",
"a",
"fake",
"upload",
"data",
"record",
"so",
"that",
"upload",
"errors",
"can",
"be",
"mitigated",
"by",
"using",
"an",
"original",
"/",
"alternative",
"URL",
"especially",
"when",
"cross",
"-",
"loading",
"from",
"the",
"web",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/webservice/imgur.py#L119-L136 |
pyroscope/pyrobase | src/pyrobase/webservice/imgur.py | cache_image_data | def cache_image_data(cache_dir, cache_key, uploader, *args, **kwargs):
""" Call uploader and cache its results.
"""
use_cache = True
if "use_cache" in kwargs:
use_cache = kwargs["use_cache"]
del kwargs["use_cache"]
json_path = None
if cache_dir:
json_path = os.path.join(cache_dir, "cached-img-%s.json" % cache_key)
if use_cache and os.path.exists(json_path):
LOG.info("Fetching %r from cache..." % (args,))
try:
with closing(open(json_path, "r")) as handle:
img_data = json.load(handle)
return parts.Bunch([(key, parts.Bunch(val))
for key, val in img_data.items() # BOGUS pylint: disable=E1103
])
except (EnvironmentError, TypeError, ValueError) as exc:
LOG.warn("Problem reading cached data from '%s', ignoring cache... (%s)" % (json_path, exc))
LOG.info("Copying %r..." % (args,))
img_data = uploader(*args, **kwargs)
if json_path:
with closing(open(json_path, "w")) as handle:
json.dump(img_data, handle)
return img_data | python | def cache_image_data(cache_dir, cache_key, uploader, *args, **kwargs):
""" Call uploader and cache its results.
"""
use_cache = True
if "use_cache" in kwargs:
use_cache = kwargs["use_cache"]
del kwargs["use_cache"]
json_path = None
if cache_dir:
json_path = os.path.join(cache_dir, "cached-img-%s.json" % cache_key)
if use_cache and os.path.exists(json_path):
LOG.info("Fetching %r from cache..." % (args,))
try:
with closing(open(json_path, "r")) as handle:
img_data = json.load(handle)
return parts.Bunch([(key, parts.Bunch(val))
for key, val in img_data.items() # BOGUS pylint: disable=E1103
])
except (EnvironmentError, TypeError, ValueError) as exc:
LOG.warn("Problem reading cached data from '%s', ignoring cache... (%s)" % (json_path, exc))
LOG.info("Copying %r..." % (args,))
img_data = uploader(*args, **kwargs)
if json_path:
with closing(open(json_path, "w")) as handle:
json.dump(img_data, handle)
return img_data | [
"def",
"cache_image_data",
"(",
"cache_dir",
",",
"cache_key",
",",
"uploader",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"use_cache",
"=",
"True",
"if",
"\"use_cache\"",
"in",
"kwargs",
":",
"use_cache",
"=",
"kwargs",
"[",
"\"use_cache\"",
"]"... | Call uploader and cache its results. | [
"Call",
"uploader",
"and",
"cache",
"its",
"results",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/webservice/imgur.py#L139-L169 |
pyroscope/pyrobase | src/pyrobase/webservice/imgur.py | copy_image_from_url | def copy_image_from_url(url, cache_dir=None, use_cache=True):
""" Copy image from given URL and return upload metadata.
"""
return cache_image_data(cache_dir, hashlib.sha1(url).hexdigest(), ImgurUploader().upload, url, use_cache=use_cache) | python | def copy_image_from_url(url, cache_dir=None, use_cache=True):
""" Copy image from given URL and return upload metadata.
"""
return cache_image_data(cache_dir, hashlib.sha1(url).hexdigest(), ImgurUploader().upload, url, use_cache=use_cache) | [
"def",
"copy_image_from_url",
"(",
"url",
",",
"cache_dir",
"=",
"None",
",",
"use_cache",
"=",
"True",
")",
":",
"return",
"cache_image_data",
"(",
"cache_dir",
",",
"hashlib",
".",
"sha1",
"(",
"url",
")",
".",
"hexdigest",
"(",
")",
",",
"ImgurUploader"... | Copy image from given URL and return upload metadata. | [
"Copy",
"image",
"from",
"given",
"URL",
"and",
"return",
"upload",
"metadata",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/webservice/imgur.py#L172-L175 |
pyroscope/pyrobase | src/pyrobase/webservice/imgur.py | _main | def _main():
""" Command line interface for testing.
"""
import pprint
import tempfile
try:
image = sys.argv[1]
except IndexError:
print("Usage: python -m pyrobase.webservice.imgur <url>")
else:
try:
pprint.pprint(copy_image_from_url(image, cache_dir=tempfile.gettempdir()))
except UploadError as exc:
print("Upload error. %s" % exc) | python | def _main():
""" Command line interface for testing.
"""
import pprint
import tempfile
try:
image = sys.argv[1]
except IndexError:
print("Usage: python -m pyrobase.webservice.imgur <url>")
else:
try:
pprint.pprint(copy_image_from_url(image, cache_dir=tempfile.gettempdir()))
except UploadError as exc:
print("Upload error. %s" % exc) | [
"def",
"_main",
"(",
")",
":",
"import",
"pprint",
"import",
"tempfile",
"try",
":",
"image",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"except",
"IndexError",
":",
"print",
"(",
"\"Usage: python -m pyrobase.webservice.imgur <url>\"",
")",
"else",
":",
"try",
... | Command line interface for testing. | [
"Command",
"line",
"interface",
"for",
"testing",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/webservice/imgur.py#L178-L192 |
pyroscope/pyrobase | src/pyrobase/webservice/imgur.py | ImgurUploader.upload | def upload(self, image, name=None):
""" Upload the given image, which can be a http[s] URL, a path to an existing file,
binary image data, or an open file handle.
"""
assert self.client_id, "imgur client ID is not set! Export the IMGUR_CLIENT_ID environment variable..."
assert self.client_secret, "imgur client secret is not set! Export the IMGUR_CLIENT_SECRET environment variable..."
# Prepare image
try:
image_data = (image + '')
except (TypeError, ValueError):
assert hasattr(image, "read"), "Image is neither a string nor an open file handle"
image_type = "file"
image_data = image # XXX are streams supported? need a temp file?
image_repr = repr(image)
else:
if image.startswith("http:") or image.startswith("https:"):
image_type = "url"
image_data = image
image_repr = image
elif all(ord(i) >= 32 for i in image) and os.path.exists(image):
image_type = "file"
image_data = image # XXX open(image, "rb")
image_repr = "file:" + image
else:
# XXX Not supported anymore (maybe use a temp file?)
image_type = "base64"
image_data = image_data.encode(image_type)
image_repr = "<binary data>"
# Upload image
# XXX "name", name or hashlib.md5(str(image)).hexdigest()),
client = ImgurClient(self.client_id, self.client_secret)
result = (client.upload_from_url if image_type == 'url'
else client.upload_from_path)(image_data) # XXX config=None, anon=True)
if result['link'].startswith('http:'):
result['link'] = 'https:' + result['link'][5:]
result['hash'] = result['id'] # compatibility to API v1
result['caption'] = result['description'] # compatibility to API v1
return parts.Bunch(
image=parts.Bunch(result),
links=parts.Bunch(
delete_page=None,
imgur_page=None,
original=result['link'],
large_thumbnail="{0}s.{1}".format(*result['link'].rsplit('.', 1)),
small_square="{0}l.{1}".format(*result['link'].rsplit('.', 1)),
)) | python | def upload(self, image, name=None):
""" Upload the given image, which can be a http[s] URL, a path to an existing file,
binary image data, or an open file handle.
"""
assert self.client_id, "imgur client ID is not set! Export the IMGUR_CLIENT_ID environment variable..."
assert self.client_secret, "imgur client secret is not set! Export the IMGUR_CLIENT_SECRET environment variable..."
# Prepare image
try:
image_data = (image + '')
except (TypeError, ValueError):
assert hasattr(image, "read"), "Image is neither a string nor an open file handle"
image_type = "file"
image_data = image # XXX are streams supported? need a temp file?
image_repr = repr(image)
else:
if image.startswith("http:") or image.startswith("https:"):
image_type = "url"
image_data = image
image_repr = image
elif all(ord(i) >= 32 for i in image) and os.path.exists(image):
image_type = "file"
image_data = image # XXX open(image, "rb")
image_repr = "file:" + image
else:
# XXX Not supported anymore (maybe use a temp file?)
image_type = "base64"
image_data = image_data.encode(image_type)
image_repr = "<binary data>"
# Upload image
# XXX "name", name or hashlib.md5(str(image)).hexdigest()),
client = ImgurClient(self.client_id, self.client_secret)
result = (client.upload_from_url if image_type == 'url'
else client.upload_from_path)(image_data) # XXX config=None, anon=True)
if result['link'].startswith('http:'):
result['link'] = 'https:' + result['link'][5:]
result['hash'] = result['id'] # compatibility to API v1
result['caption'] = result['description'] # compatibility to API v1
return parts.Bunch(
image=parts.Bunch(result),
links=parts.Bunch(
delete_page=None,
imgur_page=None,
original=result['link'],
large_thumbnail="{0}s.{1}".format(*result['link'].rsplit('.', 1)),
small_square="{0}l.{1}".format(*result['link'].rsplit('.', 1)),
)) | [
"def",
"upload",
"(",
"self",
",",
"image",
",",
"name",
"=",
"None",
")",
":",
"assert",
"self",
".",
"client_id",
",",
"\"imgur client ID is not set! Export the IMGUR_CLIENT_ID environment variable...\"",
"assert",
"self",
".",
"client_secret",
",",
"\"imgur client se... | Upload the given image, which can be a http[s] URL, a path to an existing file,
binary image data, or an open file handle. | [
"Upload",
"the",
"given",
"image",
"which",
"can",
"be",
"a",
"http",
"[",
"s",
"]",
"URL",
"a",
"path",
"to",
"an",
"existing",
"file",
"binary",
"image",
"data",
"or",
"an",
"open",
"file",
"handle",
"."
] | train | https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/webservice/imgur.py#L67-L116 |
all-umass/graphs | graphs/mixins/viz.py | _parse_fmt | def _parse_fmt(fmt, color_key='colors', ls_key='linestyles',
marker_key='marker'):
'''Modified from matplotlib's _process_plot_format function.'''
try: # Is fmt just a colorspec?
color = mcolors.colorConverter.to_rgb(fmt)
except ValueError:
pass # No, not just a color.
else:
# Either a color or a numeric marker style
if fmt not in mlines.lineMarkers:
return {color_key:color}
result = dict()
# handle the multi char special cases and strip them from the string
if fmt.find('--') >= 0:
result[ls_key] = '--'
fmt = fmt.replace('--', '')
if fmt.find('-.') >= 0:
result[ls_key] = '-.'
fmt = fmt.replace('-.', '')
if fmt.find(' ') >= 0:
result[ls_key] = 'None'
fmt = fmt.replace(' ', '')
for c in list(fmt):
if c in mlines.lineStyles:
if ls_key in result:
raise ValueError('Illegal format string; two linestyle symbols')
result[ls_key] = c
elif c in mlines.lineMarkers:
if marker_key in result:
raise ValueError('Illegal format string; two marker symbols')
result[marker_key] = c
elif c in mcolors.colorConverter.colors:
if color_key in result:
raise ValueError('Illegal format string; two color symbols')
result[color_key] = c
else:
raise ValueError('Unrecognized character %c in format string' % c)
return result | python | def _parse_fmt(fmt, color_key='colors', ls_key='linestyles',
marker_key='marker'):
'''Modified from matplotlib's _process_plot_format function.'''
try: # Is fmt just a colorspec?
color = mcolors.colorConverter.to_rgb(fmt)
except ValueError:
pass # No, not just a color.
else:
# Either a color or a numeric marker style
if fmt not in mlines.lineMarkers:
return {color_key:color}
result = dict()
# handle the multi char special cases and strip them from the string
if fmt.find('--') >= 0:
result[ls_key] = '--'
fmt = fmt.replace('--', '')
if fmt.find('-.') >= 0:
result[ls_key] = '-.'
fmt = fmt.replace('-.', '')
if fmt.find(' ') >= 0:
result[ls_key] = 'None'
fmt = fmt.replace(' ', '')
for c in list(fmt):
if c in mlines.lineStyles:
if ls_key in result:
raise ValueError('Illegal format string; two linestyle symbols')
result[ls_key] = c
elif c in mlines.lineMarkers:
if marker_key in result:
raise ValueError('Illegal format string; two marker symbols')
result[marker_key] = c
elif c in mcolors.colorConverter.colors:
if color_key in result:
raise ValueError('Illegal format string; two color symbols')
result[color_key] = c
else:
raise ValueError('Unrecognized character %c in format string' % c)
return result | [
"def",
"_parse_fmt",
"(",
"fmt",
",",
"color_key",
"=",
"'colors'",
",",
"ls_key",
"=",
"'linestyles'",
",",
"marker_key",
"=",
"'marker'",
")",
":",
"try",
":",
"# Is fmt just a colorspec?",
"color",
"=",
"mcolors",
".",
"colorConverter",
".",
"to_rgb",
"(",
... | Modified from matplotlib's _process_plot_format function. | [
"Modified",
"from",
"matplotlib",
"s",
"_process_plot_format",
"function",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/viz.py#L144-L183 |
all-umass/graphs | graphs/mixins/viz.py | VizMixin.plot | def plot(self, coordinates, directed=False, weighted=False, fig='current',
ax=None, edge_style=None, vertex_style=None, title=None, cmap=None):
'''Plot the graph using matplotlib in 2 or 3 dimensions.
coordinates : (n,2) or (n,3) array of vertex coordinates
directed : if True, edges have arrows indicating direction.
weighted : if True, edges are colored by their weight.
fig : a matplotlib Figure to use, or one of {'new','current'}. Defaults to
'current', which will call gcf(). Only used when ax=None.
ax : a matplotlib Axes to use. Defaults to gca()
edge_style : string or dict of styles for edges. Defaults to 'k-'
vertex_style : string or dict of styles for vertices. Defaults to 'ko'
title : string to display as the plot title
cmap : a matplotlib Colormap to use for edge weight coloring
'''
X = np.atleast_2d(coordinates)
assert 0 < X.shape[1] <= 3, 'too many dimensions to plot'
if X.shape[1] == 1:
X = np.column_stack((np.arange(X.shape[0]), X))
is_3d = (X.shape[1] == 3)
if ax is None:
ax = _get_axis(is_3d, fig)
edge_kwargs = dict(colors='k', linestyles='-', linewidths=1, zorder=1)
vertex_kwargs = dict(marker='o', c='k', s=20, edgecolor='none', zorder=2)
if edge_style is not None:
if not isinstance(edge_style, dict):
edge_style = _parse_fmt(edge_style, color_key='colors')
edge_kwargs.update(edge_style)
if vertex_style is not None:
if not isinstance(vertex_style, dict):
vertex_style = _parse_fmt(vertex_style, color_key='c')
vertex_kwargs.update(vertex_style)
if weighted and self.is_weighted():
edge_kwargs['array'] = self.edge_weights()
if directed and self.is_directed():
_directed_edges(self, X, ax, is_3d, edge_kwargs, cmap)
else:
_undirected_edges(self, X, ax, is_3d, edge_kwargs, cmap)
ax.scatter(*X.T, **vertex_kwargs)
ax.autoscale_view()
if title:
ax.set_title(title)
return pyplot.show | python | def plot(self, coordinates, directed=False, weighted=False, fig='current',
ax=None, edge_style=None, vertex_style=None, title=None, cmap=None):
'''Plot the graph using matplotlib in 2 or 3 dimensions.
coordinates : (n,2) or (n,3) array of vertex coordinates
directed : if True, edges have arrows indicating direction.
weighted : if True, edges are colored by their weight.
fig : a matplotlib Figure to use, or one of {'new','current'}. Defaults to
'current', which will call gcf(). Only used when ax=None.
ax : a matplotlib Axes to use. Defaults to gca()
edge_style : string or dict of styles for edges. Defaults to 'k-'
vertex_style : string or dict of styles for vertices. Defaults to 'ko'
title : string to display as the plot title
cmap : a matplotlib Colormap to use for edge weight coloring
'''
X = np.atleast_2d(coordinates)
assert 0 < X.shape[1] <= 3, 'too many dimensions to plot'
if X.shape[1] == 1:
X = np.column_stack((np.arange(X.shape[0]), X))
is_3d = (X.shape[1] == 3)
if ax is None:
ax = _get_axis(is_3d, fig)
edge_kwargs = dict(colors='k', linestyles='-', linewidths=1, zorder=1)
vertex_kwargs = dict(marker='o', c='k', s=20, edgecolor='none', zorder=2)
if edge_style is not None:
if not isinstance(edge_style, dict):
edge_style = _parse_fmt(edge_style, color_key='colors')
edge_kwargs.update(edge_style)
if vertex_style is not None:
if not isinstance(vertex_style, dict):
vertex_style = _parse_fmt(vertex_style, color_key='c')
vertex_kwargs.update(vertex_style)
if weighted and self.is_weighted():
edge_kwargs['array'] = self.edge_weights()
if directed and self.is_directed():
_directed_edges(self, X, ax, is_3d, edge_kwargs, cmap)
else:
_undirected_edges(self, X, ax, is_3d, edge_kwargs, cmap)
ax.scatter(*X.T, **vertex_kwargs)
ax.autoscale_view()
if title:
ax.set_title(title)
return pyplot.show | [
"def",
"plot",
"(",
"self",
",",
"coordinates",
",",
"directed",
"=",
"False",
",",
"weighted",
"=",
"False",
",",
"fig",
"=",
"'current'",
",",
"ax",
"=",
"None",
",",
"edge_style",
"=",
"None",
",",
"vertex_style",
"=",
"None",
",",
"title",
"=",
"... | Plot the graph using matplotlib in 2 or 3 dimensions.
coordinates : (n,2) or (n,3) array of vertex coordinates
directed : if True, edges have arrows indicating direction.
weighted : if True, edges are colored by their weight.
fig : a matplotlib Figure to use, or one of {'new','current'}. Defaults to
'current', which will call gcf(). Only used when ax=None.
ax : a matplotlib Axes to use. Defaults to gca()
edge_style : string or dict of styles for edges. Defaults to 'k-'
vertex_style : string or dict of styles for vertices. Defaults to 'ko'
title : string to display as the plot title
cmap : a matplotlib Colormap to use for edge weight coloring | [
"Plot",
"the",
"graph",
"using",
"matplotlib",
"in",
"2",
"or",
"3",
"dimensions",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/viz.py#L13-L55 |
all-umass/graphs | graphs/mixins/viz.py | VizMixin.to_html | def to_html(self, html_file, directed=False, weighted=False, vertex_ids=None,
vertex_colors=None, vertex_labels=None, width=900, height=600,
title=None, svg_border='1px solid black'):
'''Write the graph as a d3 force-directed layout SVG to an HTML file.
html_file : str|file-like, writeable destination for the output HTML.
vertex_ids : unique IDs for each vertex, defaults to arange(num_vertices).
vertex_colors : numeric color mapping for vertices, optional.
vertex_labels : class labels for vertices, optional.
title : str, written above the SVG as an h1, optional.
svg_border : str, CSS for the 'border' attribute of the SVG element.
'''
if directed:
raise NotImplementedError('Directed graphs are NYI for HTML output.')
if (vertex_colors is not None) and (vertex_labels is not None):
raise ValueError('Supply only one of vertex_colors, vertex_labels')
# set up vertices
if vertex_ids is None:
vertex_ids = np.arange(self.num_vertices())
elif len(vertex_ids) != self.num_vertices():
raise ValueError('len(vertex_ids) != num vertices.')
if vertex_labels is not None:
vlabels, vcolors = np.unique(vertex_labels, return_inverse=True)
if len(vcolors) != len(vertex_ids):
raise ValueError('len(vertex_labels) != num vertices.')
elif vertex_colors is not None:
vcolors = np.array(vertex_colors, dtype=float, copy=False)
if len(vcolors) != len(vertex_ids):
raise ValueError('len(vertex_colors) != num vertices.')
vcolors -= vcolors.min()
vcolors /= vcolors.max()
else:
vcolors = []
node_json = []
for name, c in zip_longest(vertex_ids, vcolors):
if c is not None:
node_json.append('{"id": "%s", "color": %s}' % (name, c))
else:
node_json.append('{"id": "%s"}' % name)
# set up edges
pairs = self.pairs(directed=directed)
if weighted:
weights = self.edge_weights(directed=directed, copy=True).astype(float)
weights -= weights.min()
weights /= weights.max()
else:
weights = np.zeros(len(pairs)) + 0.5
edge_json = []
for (i,j), w in zip(pairs, weights):
edge_json.append('{"source": "%s", "target": "%s", "weight": %f}' % (
vertex_ids[i], vertex_ids[j], w))
# emit self-contained HTML
if not hasattr(html_file, 'write'):
fh = open(html_file, 'w')
else:
fh = html_file
print(u'<!DOCTYPE html><meta charset="utf-8"><style>', file=fh)
print(u'svg { border: %s; }' % svg_border, file=fh)
if weighted:
print(u'.links line { stroke-width: 2px; }', file=fh)
else:
print(u'.links line { stroke: #000; stroke-width: 2px; }', file=fh)
print(u'.nodes circle { stroke: #fff; stroke-width: 1px; }', file=fh)
print(u'</style>', file=fh)
if title:
print(u'<h1>%s</h1>' % title, file=fh)
print(u'<svg width="%d" height="%d"></svg>' % (width, height), file=fh)
print(u'<script src="https://d3js.org/d3.v4.min.js"></script>', file=fh)
print(u'<script>', LAYOUT_JS, sep=u'\n', file=fh)
if vertex_colors is not None:
print(u'var vcolor=d3.scaleSequential(d3.interpolateViridis);', file=fh)
elif vertex_labels is not None:
scale = 'd3.schemeCategory%d' % (10 if len(vlabels) <= 10 else 20)
print(u'var vcolor = d3.scaleOrdinal(%s);' % scale, file=fh)
else:
print(u'function vcolor(){ return "#1776b6"; }', file=fh)
print(u'var sim=layout_graph({"nodes": [%s], "links": [%s]});</script>' % (
',\n'.join(node_json), ',\n'.join(edge_json)), file=fh)
fh.flush() | python | def to_html(self, html_file, directed=False, weighted=False, vertex_ids=None,
vertex_colors=None, vertex_labels=None, width=900, height=600,
title=None, svg_border='1px solid black'):
'''Write the graph as a d3 force-directed layout SVG to an HTML file.
html_file : str|file-like, writeable destination for the output HTML.
vertex_ids : unique IDs for each vertex, defaults to arange(num_vertices).
vertex_colors : numeric color mapping for vertices, optional.
vertex_labels : class labels for vertices, optional.
title : str, written above the SVG as an h1, optional.
svg_border : str, CSS for the 'border' attribute of the SVG element.
'''
if directed:
raise NotImplementedError('Directed graphs are NYI for HTML output.')
if (vertex_colors is not None) and (vertex_labels is not None):
raise ValueError('Supply only one of vertex_colors, vertex_labels')
# set up vertices
if vertex_ids is None:
vertex_ids = np.arange(self.num_vertices())
elif len(vertex_ids) != self.num_vertices():
raise ValueError('len(vertex_ids) != num vertices.')
if vertex_labels is not None:
vlabels, vcolors = np.unique(vertex_labels, return_inverse=True)
if len(vcolors) != len(vertex_ids):
raise ValueError('len(vertex_labels) != num vertices.')
elif vertex_colors is not None:
vcolors = np.array(vertex_colors, dtype=float, copy=False)
if len(vcolors) != len(vertex_ids):
raise ValueError('len(vertex_colors) != num vertices.')
vcolors -= vcolors.min()
vcolors /= vcolors.max()
else:
vcolors = []
node_json = []
for name, c in zip_longest(vertex_ids, vcolors):
if c is not None:
node_json.append('{"id": "%s", "color": %s}' % (name, c))
else:
node_json.append('{"id": "%s"}' % name)
# set up edges
pairs = self.pairs(directed=directed)
if weighted:
weights = self.edge_weights(directed=directed, copy=True).astype(float)
weights -= weights.min()
weights /= weights.max()
else:
weights = np.zeros(len(pairs)) + 0.5
edge_json = []
for (i,j), w in zip(pairs, weights):
edge_json.append('{"source": "%s", "target": "%s", "weight": %f}' % (
vertex_ids[i], vertex_ids[j], w))
# emit self-contained HTML
if not hasattr(html_file, 'write'):
fh = open(html_file, 'w')
else:
fh = html_file
print(u'<!DOCTYPE html><meta charset="utf-8"><style>', file=fh)
print(u'svg { border: %s; }' % svg_border, file=fh)
if weighted:
print(u'.links line { stroke-width: 2px; }', file=fh)
else:
print(u'.links line { stroke: #000; stroke-width: 2px; }', file=fh)
print(u'.nodes circle { stroke: #fff; stroke-width: 1px; }', file=fh)
print(u'</style>', file=fh)
if title:
print(u'<h1>%s</h1>' % title, file=fh)
print(u'<svg width="%d" height="%d"></svg>' % (width, height), file=fh)
print(u'<script src="https://d3js.org/d3.v4.min.js"></script>', file=fh)
print(u'<script>', LAYOUT_JS, sep=u'\n', file=fh)
if vertex_colors is not None:
print(u'var vcolor=d3.scaleSequential(d3.interpolateViridis);', file=fh)
elif vertex_labels is not None:
scale = 'd3.schemeCategory%d' % (10 if len(vlabels) <= 10 else 20)
print(u'var vcolor = d3.scaleOrdinal(%s);' % scale, file=fh)
else:
print(u'function vcolor(){ return "#1776b6"; }', file=fh)
print(u'var sim=layout_graph({"nodes": [%s], "links": [%s]});</script>' % (
',\n'.join(node_json), ',\n'.join(edge_json)), file=fh)
fh.flush() | [
"def",
"to_html",
"(",
"self",
",",
"html_file",
",",
"directed",
"=",
"False",
",",
"weighted",
"=",
"False",
",",
"vertex_ids",
"=",
"None",
",",
"vertex_colors",
"=",
"None",
",",
"vertex_labels",
"=",
"None",
",",
"width",
"=",
"900",
",",
"height",
... | Write the graph as a d3 force-directed layout SVG to an HTML file.
html_file : str|file-like, writeable destination for the output HTML.
vertex_ids : unique IDs for each vertex, defaults to arange(num_vertices).
vertex_colors : numeric color mapping for vertices, optional.
vertex_labels : class labels for vertices, optional.
title : str, written above the SVG as an h1, optional.
svg_border : str, CSS for the 'border' attribute of the SVG element. | [
"Write",
"the",
"graph",
"as",
"a",
"d3",
"force",
"-",
"directed",
"layout",
"SVG",
"to",
"an",
"HTML",
"file",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/mixins/viz.py#L57-L141 |
calmjs/calmjs.parse | src/calmjs/parse/sourcemap.py | normalize_mapping_line | def normalize_mapping_line(mapping_line, previous_source_column=0):
"""
Often times the position will remain stable, such that the naive
process will end up with many redundant values; this function will
iterate through the line and remove all extra values.
"""
if not mapping_line:
return [], previous_source_column
# Note that while the local record here is also done as a 4-tuple,
# element 1 and 2 are never used since they are always provided by
# the segments in the mapping line; they are defined for consistency
# reasons.
def regenerate(segment):
if len(segment) == 5:
result = (record[0], segment[1], segment[2], record[3], segment[4])
else:
result = (record[0], segment[1], segment[2], record[3])
# Ideally the exact location should still be kept, but given
# that the sourcemap format is accumulative and permits a lot
# of inferred positions, resetting all values to 0 is intended.
record[:] = [0, 0, 0, 0]
return result
# first element of the line; sink column (0th element) is always
# the absolute value, so always use the provided value sourced from
# the original mapping_line; the source column (3rd element) is
# never reset, so if a previous counter exists (which is specified
# by the optional argument), make use of it to generate the initial
# normalized segment.
record = [0, 0, 0, previous_source_column]
result = []
regen_next = True
for segment in mapping_line:
if not segment:
# ignore empty records
continue
# if the line has not changed, and that the increases of both
# columns are the same, accumulate the column counter and drop
# the segment.
# accumulate the current record first
record[0] += segment[0]
if len(segment) == 1:
# Mark the termination, as 1-tuple determines the end of the
# previous symbol and denote that whatever follows are not
# in any previous source files. So if it isn't recorded,
# make note of this if it wasn't done already.
if result and len(result[-1]) != 1:
result.append((record[0],))
record[0] = 0
# the next complete segment will require regeneration
regen_next = True
# skip the remaining processing.
continue
record[3] += segment[3]
# 5-tuples are always special case with the remapped identifier
# name element, and to mark the termination the next token must
# also be explicitly written (in our case, regenerated). If the
# filename or source line relative position changed (idx 1 and
# 2), regenerate it too. Finally, if the column offsets differ
# between source and sink, regenerate.
if len(segment) == 5 or regen_next or segment[1] or segment[2] or (
record[0] != record[3]):
result.append(regenerate(segment))
regen_next = len(segment) == 5
# must return the consumed/omitted values.
return result, record[3] | python | def normalize_mapping_line(mapping_line, previous_source_column=0):
"""
Often times the position will remain stable, such that the naive
process will end up with many redundant values; this function will
iterate through the line and remove all extra values.
"""
if not mapping_line:
return [], previous_source_column
# Note that while the local record here is also done as a 4-tuple,
# element 1 and 2 are never used since they are always provided by
# the segments in the mapping line; they are defined for consistency
# reasons.
def regenerate(segment):
if len(segment) == 5:
result = (record[0], segment[1], segment[2], record[3], segment[4])
else:
result = (record[0], segment[1], segment[2], record[3])
# Ideally the exact location should still be kept, but given
# that the sourcemap format is accumulative and permits a lot
# of inferred positions, resetting all values to 0 is intended.
record[:] = [0, 0, 0, 0]
return result
# first element of the line; sink column (0th element) is always
# the absolute value, so always use the provided value sourced from
# the original mapping_line; the source column (3rd element) is
# never reset, so if a previous counter exists (which is specified
# by the optional argument), make use of it to generate the initial
# normalized segment.
record = [0, 0, 0, previous_source_column]
result = []
regen_next = True
for segment in mapping_line:
if not segment:
# ignore empty records
continue
# if the line has not changed, and that the increases of both
# columns are the same, accumulate the column counter and drop
# the segment.
# accumulate the current record first
record[0] += segment[0]
if len(segment) == 1:
# Mark the termination, as 1-tuple determines the end of the
# previous symbol and denote that whatever follows are not
# in any previous source files. So if it isn't recorded,
# make note of this if it wasn't done already.
if result and len(result[-1]) != 1:
result.append((record[0],))
record[0] = 0
# the next complete segment will require regeneration
regen_next = True
# skip the remaining processing.
continue
record[3] += segment[3]
# 5-tuples are always special case with the remapped identifier
# name element, and to mark the termination the next token must
# also be explicitly written (in our case, regenerated). If the
# filename or source line relative position changed (idx 1 and
# 2), regenerate it too. Finally, if the column offsets differ
# between source and sink, regenerate.
if len(segment) == 5 or regen_next or segment[1] or segment[2] or (
record[0] != record[3]):
result.append(regenerate(segment))
regen_next = len(segment) == 5
# must return the consumed/omitted values.
return result, record[3] | [
"def",
"normalize_mapping_line",
"(",
"mapping_line",
",",
"previous_source_column",
"=",
"0",
")",
":",
"if",
"not",
"mapping_line",
":",
"return",
"[",
"]",
",",
"previous_source_column",
"# Note that while the local record here is also done as a 4-tuple,",
"# element 1 and... | Often times the position will remain stable, such that the naive
process will end up with many redundant values; this function will
iterate through the line and remove all extra values. | [
"Often",
"times",
"the",
"position",
"will",
"remain",
"stable",
"such",
"that",
"the",
"naive",
"process",
"will",
"end",
"up",
"with",
"many",
"redundant",
"values",
";",
"this",
"function",
"will",
"iterate",
"through",
"the",
"line",
"and",
"remove",
"al... | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/sourcemap.py#L132-L205 |
calmjs/calmjs.parse | src/calmjs/parse/sourcemap.py | write | def write(
stream_fragments, stream, normalize=True,
book=None, sources=None, names=None, mappings=None):
"""
Given an iterable of stream fragments, write it to the stream object
by using its write method. Returns a 3-tuple, where the first
element is the mapping, second element is the list of sources and
the third being the original names referenced by the given fragment.
Arguments:
stream_fragments
an iterable that only contains StreamFragments
stream
an io.IOBase compatible stream object
normalize
the default True setting will result in the mappings that were
returned be normalized to the minimum form. This will reduce
the size of the generated source map at the expense of slightly
lower quality.
Also, if any of the subsequent arguments are provided (for
instance, for the multiple calls to this function), the usage of
the normalize flag is currently NOT supported.
If multiple sets of outputs are to be produced, the recommended
method is to chain all the stream fragments together before
passing in.
Advanced usage arguments
book
A Book instance; if none is provided an instance will be created
from the default_book constructor. The Bookkeeper instance is
used for tracking the positions of rows and columns of the input
stream.
sources
a Names instance for tracking sources; if None is provided, an
instance will be created for internal use.
names
a Names instance for tracking names; if None is provided, an
instance will be created for internal use.
mappings
a previously produced mappings.
A stream fragment tuple must contain the following
- The string to write to the stream
- Original starting line of the string; None if not present
- Original starting column fo the line; None if not present
- Original string that this fragment represents (i.e. for the case
where this string fragment was an identifier but got mangled into
an alternative form); use None if this was not the case.
- The source of the fragment. If the first fragment is unspecified,
the INVALID_SOURCE url will be used (i.e. about:invalid). After
that, a None value will be treated as the implicit value, and if
NotImplemented is encountered, the INVALID_SOURCE url will be used
also.
If a number of stream_fragments are to be provided, common instances
of Book (constructed via default_book) and Names (for sources and
names) should be provided if they are not chained together.
"""
def push_line():
mappings.append([])
book.keeper._sink_column = 0
if names is None:
names = Names()
if sources is None:
sources = Names()
if book is None:
book = default_book()
if not isinstance(mappings, list):
# note that
mappings = []
# finalize initial states; the most recent list (mappings[-1])
# is the current line
push_line()
for chunk, lineno, colno, original_name, source in stream_fragments:
# note that lineno/colno are assumed to be both provided or none
# provided.
lines = chunk.splitlines(True)
for line in lines:
stream.write(line)
# Two separate checks are done. As per specification, if
# either lineno or colno are unspecified, it is assumed that
# the segment is unmapped - append a termination (1-tuple)
#
# Otherwise, note that if this segment is the beginning of a
# line, and that an implied source colno/linecol were
# provided (i.e. value of 0), and that the string is empty,
# it can be safely skipped, since it is an implied and
# unmapped indentation
if lineno is None or colno is None:
mappings[-1].append((book.keeper.sink_column,))
else:
name_id = names.update(original_name)
# this is a bit of a trick: an unspecified value (None)
# will simply be treated as the implied value, hence 0.
# However, a NotImplemented will be recorded and be
# convereted to the invalid url at the end.
source_id = sources.update(source) or 0
if lineno:
# a new lineno is provided, apply it to the book and
# use the result as the written value.
book.keeper.source_line = lineno
source_line = book.keeper.source_line
else:
# no change in offset, do not calculate and assume
# the value to be written is unchanged.
source_line = 0
# if the provided colno is to be inferred, calculate it
# based on the previous line length plus the previous
# real source column value, otherwise standard value
# for tracking.
# the reason for using the previous lengths is simply
# due to how the bookkeeper class does the calculation
# on-demand, and that the starting column for the
# _current_ text fragment can only be calculated using
# what was written previously, hence the original length
# value being added if the current colno is to be
# inferred.
if colno:
book.keeper.source_column = colno
else:
book.keeper.source_column = (
book.keeper._source_column + book.original_len)
if original_name is not None:
mappings[-1].append((
book.keeper.sink_column, source_id,
source_line, book.keeper.source_column,
name_id
))
else:
mappings[-1].append((
book.keeper.sink_column, source_id,
source_line, book.keeper.source_column
))
# doing this last to update the position for the next line
# or chunk for the relative values based on what was added
if line[-1:] in '\r\n':
# Note: this HAS to be an edge case and should never
# happen, but this has the potential to muck things up.
# Since the parent only provided the start, will need
# to manually track the chunks internal to here.
# This normally shouldn't happen with sane parsers
# and lexers, but this assumes that no further symbols
# aside from the new lines got inserted.
colno = (
colno if colno in (0, None) else
colno + len(line.rstrip()))
book.original_len = book.written_len = 0
push_line()
if line is not lines[-1]:
logger.warning(
'text in the generated document at line %d may be '
'mapped incorrectly due to trailing newline character '
'in provided text fragment.', len(mappings)
)
logger.info(
'text in stream fragments should not have trailing '
'characters after a new line, they should be split '
'off into a separate fragment.'
)
else:
book.written_len = len(line)
book.original_len = (
len(original_name) if original_name else book.written_len)
book.keeper.sink_column = (
book.keeper._sink_column + book.written_len)
# normalize everything
if normalize:
# if this _ever_ supports the multiple usage using existence
# instances of names and book and mappings, it needs to deal
# with NOT normalizing the existing mappings and somehow reuse
# the previously stored value, probably in the book. It is
# most certainly a bad idea to support that use case while also
# supporting the default normalize flag due to the complex
# tracking of all the existing values...
mappings = normalize_mappings(mappings)
list_sources = [
INVALID_SOURCE if s == NotImplemented else s for s in sources
] or [INVALID_SOURCE]
return mappings, list_sources, list(names) | python | def write(
stream_fragments, stream, normalize=True,
book=None, sources=None, names=None, mappings=None):
"""
Given an iterable of stream fragments, write it to the stream object
by using its write method. Returns a 3-tuple, where the first
element is the mapping, second element is the list of sources and
the third being the original names referenced by the given fragment.
Arguments:
stream_fragments
an iterable that only contains StreamFragments
stream
an io.IOBase compatible stream object
normalize
the default True setting will result in the mappings that were
returned be normalized to the minimum form. This will reduce
the size of the generated source map at the expense of slightly
lower quality.
Also, if any of the subsequent arguments are provided (for
instance, for the multiple calls to this function), the usage of
the normalize flag is currently NOT supported.
If multiple sets of outputs are to be produced, the recommended
method is to chain all the stream fragments together before
passing in.
Advanced usage arguments
book
A Book instance; if none is provided an instance will be created
from the default_book constructor. The Bookkeeper instance is
used for tracking the positions of rows and columns of the input
stream.
sources
a Names instance for tracking sources; if None is provided, an
instance will be created for internal use.
names
a Names instance for tracking names; if None is provided, an
instance will be created for internal use.
mappings
a previously produced mappings.
A stream fragment tuple must contain the following
- The string to write to the stream
- Original starting line of the string; None if not present
- Original starting column fo the line; None if not present
- Original string that this fragment represents (i.e. for the case
where this string fragment was an identifier but got mangled into
an alternative form); use None if this was not the case.
- The source of the fragment. If the first fragment is unspecified,
the INVALID_SOURCE url will be used (i.e. about:invalid). After
that, a None value will be treated as the implicit value, and if
NotImplemented is encountered, the INVALID_SOURCE url will be used
also.
If a number of stream_fragments are to be provided, common instances
of Book (constructed via default_book) and Names (for sources and
names) should be provided if they are not chained together.
"""
def push_line():
mappings.append([])
book.keeper._sink_column = 0
if names is None:
names = Names()
if sources is None:
sources = Names()
if book is None:
book = default_book()
if not isinstance(mappings, list):
# note that
mappings = []
# finalize initial states; the most recent list (mappings[-1])
# is the current line
push_line()
for chunk, lineno, colno, original_name, source in stream_fragments:
# note that lineno/colno are assumed to be both provided or none
# provided.
lines = chunk.splitlines(True)
for line in lines:
stream.write(line)
# Two separate checks are done. As per specification, if
# either lineno or colno are unspecified, it is assumed that
# the segment is unmapped - append a termination (1-tuple)
#
# Otherwise, note that if this segment is the beginning of a
# line, and that an implied source colno/linecol were
# provided (i.e. value of 0), and that the string is empty,
# it can be safely skipped, since it is an implied and
# unmapped indentation
if lineno is None or colno is None:
mappings[-1].append((book.keeper.sink_column,))
else:
name_id = names.update(original_name)
# this is a bit of a trick: an unspecified value (None)
# will simply be treated as the implied value, hence 0.
# However, a NotImplemented will be recorded and be
# convereted to the invalid url at the end.
source_id = sources.update(source) or 0
if lineno:
# a new lineno is provided, apply it to the book and
# use the result as the written value.
book.keeper.source_line = lineno
source_line = book.keeper.source_line
else:
# no change in offset, do not calculate and assume
# the value to be written is unchanged.
source_line = 0
# if the provided colno is to be inferred, calculate it
# based on the previous line length plus the previous
# real source column value, otherwise standard value
# for tracking.
# the reason for using the previous lengths is simply
# due to how the bookkeeper class does the calculation
# on-demand, and that the starting column for the
# _current_ text fragment can only be calculated using
# what was written previously, hence the original length
# value being added if the current colno is to be
# inferred.
if colno:
book.keeper.source_column = colno
else:
book.keeper.source_column = (
book.keeper._source_column + book.original_len)
if original_name is not None:
mappings[-1].append((
book.keeper.sink_column, source_id,
source_line, book.keeper.source_column,
name_id
))
else:
mappings[-1].append((
book.keeper.sink_column, source_id,
source_line, book.keeper.source_column
))
# doing this last to update the position for the next line
# or chunk for the relative values based on what was added
if line[-1:] in '\r\n':
# Note: this HAS to be an edge case and should never
# happen, but this has the potential to muck things up.
# Since the parent only provided the start, will need
# to manually track the chunks internal to here.
# This normally shouldn't happen with sane parsers
# and lexers, but this assumes that no further symbols
# aside from the new lines got inserted.
colno = (
colno if colno in (0, None) else
colno + len(line.rstrip()))
book.original_len = book.written_len = 0
push_line()
if line is not lines[-1]:
logger.warning(
'text in the generated document at line %d may be '
'mapped incorrectly due to trailing newline character '
'in provided text fragment.', len(mappings)
)
logger.info(
'text in stream fragments should not have trailing '
'characters after a new line, they should be split '
'off into a separate fragment.'
)
else:
book.written_len = len(line)
book.original_len = (
len(original_name) if original_name else book.written_len)
book.keeper.sink_column = (
book.keeper._sink_column + book.written_len)
# normalize everything
if normalize:
# if this _ever_ supports the multiple usage using existence
# instances of names and book and mappings, it needs to deal
# with NOT normalizing the existing mappings and somehow reuse
# the previously stored value, probably in the book. It is
# most certainly a bad idea to support that use case while also
# supporting the default normalize flag due to the complex
# tracking of all the existing values...
mappings = normalize_mappings(mappings)
list_sources = [
INVALID_SOURCE if s == NotImplemented else s for s in sources
] or [INVALID_SOURCE]
return mappings, list_sources, list(names) | [
"def",
"write",
"(",
"stream_fragments",
",",
"stream",
",",
"normalize",
"=",
"True",
",",
"book",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"names",
"=",
"None",
",",
"mappings",
"=",
"None",
")",
":",
"def",
"push_line",
"(",
")",
":",
"mappi... | Given an iterable of stream fragments, write it to the stream object
by using its write method. Returns a 3-tuple, where the first
element is the mapping, second element is the list of sources and
the third being the original names referenced by the given fragment.
Arguments:
stream_fragments
an iterable that only contains StreamFragments
stream
an io.IOBase compatible stream object
normalize
the default True setting will result in the mappings that were
returned be normalized to the minimum form. This will reduce
the size of the generated source map at the expense of slightly
lower quality.
Also, if any of the subsequent arguments are provided (for
instance, for the multiple calls to this function), the usage of
the normalize flag is currently NOT supported.
If multiple sets of outputs are to be produced, the recommended
method is to chain all the stream fragments together before
passing in.
Advanced usage arguments
book
A Book instance; if none is provided an instance will be created
from the default_book constructor. The Bookkeeper instance is
used for tracking the positions of rows and columns of the input
stream.
sources
a Names instance for tracking sources; if None is provided, an
instance will be created for internal use.
names
a Names instance for tracking names; if None is provided, an
instance will be created for internal use.
mappings
a previously produced mappings.
A stream fragment tuple must contain the following
- The string to write to the stream
- Original starting line of the string; None if not present
- Original starting column fo the line; None if not present
- Original string that this fragment represents (i.e. for the case
where this string fragment was an identifier but got mangled into
an alternative form); use None if this was not the case.
- The source of the fragment. If the first fragment is unspecified,
the INVALID_SOURCE url will be used (i.e. about:invalid). After
that, a None value will be treated as the implicit value, and if
NotImplemented is encountered, the INVALID_SOURCE url will be used
also.
If a number of stream_fragments are to be provided, common instances
of Book (constructed via default_book) and Names (for sources and
names) should be provided if they are not chained together. | [
"Given",
"an",
"iterable",
"of",
"stream",
"fragments",
"write",
"it",
"to",
"the",
"stream",
"object",
"by",
"using",
"its",
"write",
"method",
".",
"Returns",
"a",
"3",
"-",
"tuple",
"where",
"the",
"first",
"element",
"is",
"the",
"mapping",
"second",
... | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/sourcemap.py#L216-L415 |
calmjs/calmjs.parse | src/calmjs/parse/sourcemap.py | encode_sourcemap | def encode_sourcemap(filename, mappings, sources, names=[]):
"""
Take a filename, mappings and names produced from the write function
and sources. As the write function currently does not handle the
tracking of source filenames, the sources should be a list of one
element with the original filename.
Arguments
filename
The target filename that the stream was or to be written to.
The stream being the argument that was supplied to the write
function
mappings
The raw unencoded mappings produced by write, which is returned
as its second element.
sources
List of original source filenames. When used in conjunction
with the above write function, it should be a list of one item,
being the path to the original filename.
names
The list of original names generated by write, which is returned
as its first element.
Returns a dict which can be JSON encoded into a sourcemap file.
Example usage:
>>> from io import StringIO
>>> from calmjs.parse import es5
>>> from calmjs.parse.unparsers.es5 import pretty_printer
>>> from calmjs.parse.sourcemap import write, encode_sourcemap
>>> program = es5(u"var i = 'hello';")
>>> stream = StringIO()
>>> printer = pretty_printer()
>>> sourcemap = encode_sourcemap(
... 'demo.min.js', *write(printer(program), stream))
"""
return {
"version": 3,
"sources": sources,
"names": names,
"mappings": encode_mappings(mappings),
"file": filename,
} | python | def encode_sourcemap(filename, mappings, sources, names=[]):
"""
Take a filename, mappings and names produced from the write function
and sources. As the write function currently does not handle the
tracking of source filenames, the sources should be a list of one
element with the original filename.
Arguments
filename
The target filename that the stream was or to be written to.
The stream being the argument that was supplied to the write
function
mappings
The raw unencoded mappings produced by write, which is returned
as its second element.
sources
List of original source filenames. When used in conjunction
with the above write function, it should be a list of one item,
being the path to the original filename.
names
The list of original names generated by write, which is returned
as its first element.
Returns a dict which can be JSON encoded into a sourcemap file.
Example usage:
>>> from io import StringIO
>>> from calmjs.parse import es5
>>> from calmjs.parse.unparsers.es5 import pretty_printer
>>> from calmjs.parse.sourcemap import write, encode_sourcemap
>>> program = es5(u"var i = 'hello';")
>>> stream = StringIO()
>>> printer = pretty_printer()
>>> sourcemap = encode_sourcemap(
... 'demo.min.js', *write(printer(program), stream))
"""
return {
"version": 3,
"sources": sources,
"names": names,
"mappings": encode_mappings(mappings),
"file": filename,
} | [
"def",
"encode_sourcemap",
"(",
"filename",
",",
"mappings",
",",
"sources",
",",
"names",
"=",
"[",
"]",
")",
":",
"return",
"{",
"\"version\"",
":",
"3",
",",
"\"sources\"",
":",
"sources",
",",
"\"names\"",
":",
"names",
",",
"\"mappings\"",
":",
"enc... | Take a filename, mappings and names produced from the write function
and sources. As the write function currently does not handle the
tracking of source filenames, the sources should be a list of one
element with the original filename.
Arguments
filename
The target filename that the stream was or to be written to.
The stream being the argument that was supplied to the write
function
mappings
The raw unencoded mappings produced by write, which is returned
as its second element.
sources
List of original source filenames. When used in conjunction
with the above write function, it should be a list of one item,
being the path to the original filename.
names
The list of original names generated by write, which is returned
as its first element.
Returns a dict which can be JSON encoded into a sourcemap file.
Example usage:
>>> from io import StringIO
>>> from calmjs.parse import es5
>>> from calmjs.parse.unparsers.es5 import pretty_printer
>>> from calmjs.parse.sourcemap import write, encode_sourcemap
>>> program = es5(u"var i = 'hello';")
>>> stream = StringIO()
>>> printer = pretty_printer()
>>> sourcemap = encode_sourcemap(
... 'demo.min.js', *write(printer(program), stream)) | [
"Take",
"a",
"filename",
"mappings",
"and",
"names",
"produced",
"from",
"the",
"write",
"function",
"and",
"sources",
".",
"As",
"the",
"write",
"function",
"currently",
"does",
"not",
"handle",
"the",
"tracking",
"of",
"source",
"filenames",
"the",
"sources"... | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/sourcemap.py#L418-L463 |
calmjs/calmjs.parse | src/calmjs/parse/sourcemap.py | write_sourcemap | def write_sourcemap(
mappings, sources, names, output_stream, sourcemap_stream,
normalize_paths=True, source_mapping_url=NotImplemented):
"""
Write out the mappings, sources and names (generally produced by
the write function) to the provided sourcemap_stream, and write the
sourceMappingURL to the output_stream.
Arguments
mappings, sources, names
These should be values produced by write function from this
module.
output_stream
The original stream object that was written to; its name will
be used for the file target and if sourceMappingURL is resolved,
it will be writtened to this stream also as a comment.
sourcemap_stream
If one is provided, the sourcemap will be written out to it.
If it is the same stream as the output_stream, the source map
will be written as an encoded 'data:application/json;base64'
url to the sourceMappingURL comment. Note that an appropriate
encoding must be available as an attribute by the output_stream
object so that the correct character set will be used for the
base64 encoded JSON serialized string.
normalize_paths
If set to True, absolute paths found will be turned into
relative paths with relation from the stream being written
to, and the path separator used will become a '/' (forward
slash).
source_mapping_url
If an explicit value is set, this will be written as the
sourceMappingURL into the output_stream. Note that the path
normalization will NOT use this value, so if paths have been
manually provided, ensure that normalize_paths is set to False
if the behavior is unwanted.
"""
encode_sourcemap_args, output_js_map = verify_write_sourcemap_args(
mappings, sources, names, output_stream, sourcemap_stream,
normalize_paths
)
encoded_sourcemap = json.dumps(
encode_sourcemap(*encode_sourcemap_args),
sort_keys=True, ensure_ascii=False,
)
if sourcemap_stream is output_stream:
# encoding will be missing if using StringIO; fall back to
# default_encoding
encoding = getattr(output_stream, 'encoding', None) or default_encoding
output_stream.writelines([
'\n//# sourceMappingURL=data:application/json;base64;charset=',
encoding, ',', base64.b64encode(
encoded_sourcemap.encode(encoding)).decode('ascii'),
])
else:
if source_mapping_url is not None:
output_stream.writelines(['\n//# sourceMappingURL=', (
output_js_map if source_mapping_url is NotImplemented
else source_mapping_url
), '\n'])
sourcemap_stream.write(encoded_sourcemap) | python | def write_sourcemap(
mappings, sources, names, output_stream, sourcemap_stream,
normalize_paths=True, source_mapping_url=NotImplemented):
"""
Write out the mappings, sources and names (generally produced by
the write function) to the provided sourcemap_stream, and write the
sourceMappingURL to the output_stream.
Arguments
mappings, sources, names
These should be values produced by write function from this
module.
output_stream
The original stream object that was written to; its name will
be used for the file target and if sourceMappingURL is resolved,
it will be writtened to this stream also as a comment.
sourcemap_stream
If one is provided, the sourcemap will be written out to it.
If it is the same stream as the output_stream, the source map
will be written as an encoded 'data:application/json;base64'
url to the sourceMappingURL comment. Note that an appropriate
encoding must be available as an attribute by the output_stream
object so that the correct character set will be used for the
base64 encoded JSON serialized string.
normalize_paths
If set to True, absolute paths found will be turned into
relative paths with relation from the stream being written
to, and the path separator used will become a '/' (forward
slash).
source_mapping_url
If an explicit value is set, this will be written as the
sourceMappingURL into the output_stream. Note that the path
normalization will NOT use this value, so if paths have been
manually provided, ensure that normalize_paths is set to False
if the behavior is unwanted.
"""
encode_sourcemap_args, output_js_map = verify_write_sourcemap_args(
mappings, sources, names, output_stream, sourcemap_stream,
normalize_paths
)
encoded_sourcemap = json.dumps(
encode_sourcemap(*encode_sourcemap_args),
sort_keys=True, ensure_ascii=False,
)
if sourcemap_stream is output_stream:
# encoding will be missing if using StringIO; fall back to
# default_encoding
encoding = getattr(output_stream, 'encoding', None) or default_encoding
output_stream.writelines([
'\n//# sourceMappingURL=data:application/json;base64;charset=',
encoding, ',', base64.b64encode(
encoded_sourcemap.encode(encoding)).decode('ascii'),
])
else:
if source_mapping_url is not None:
output_stream.writelines(['\n//# sourceMappingURL=', (
output_js_map if source_mapping_url is NotImplemented
else source_mapping_url
), '\n'])
sourcemap_stream.write(encoded_sourcemap) | [
"def",
"write_sourcemap",
"(",
"mappings",
",",
"sources",
",",
"names",
",",
"output_stream",
",",
"sourcemap_stream",
",",
"normalize_paths",
"=",
"True",
",",
"source_mapping_url",
"=",
"NotImplemented",
")",
":",
"encode_sourcemap_args",
",",
"output_js_map",
"=... | Write out the mappings, sources and names (generally produced by
the write function) to the provided sourcemap_stream, and write the
sourceMappingURL to the output_stream.
Arguments
mappings, sources, names
These should be values produced by write function from this
module.
output_stream
The original stream object that was written to; its name will
be used for the file target and if sourceMappingURL is resolved,
it will be writtened to this stream also as a comment.
sourcemap_stream
If one is provided, the sourcemap will be written out to it.
If it is the same stream as the output_stream, the source map
will be written as an encoded 'data:application/json;base64'
url to the sourceMappingURL comment. Note that an appropriate
encoding must be available as an attribute by the output_stream
object so that the correct character set will be used for the
base64 encoded JSON serialized string.
normalize_paths
If set to True, absolute paths found will be turned into
relative paths with relation from the stream being written
to, and the path separator used will become a '/' (forward
slash).
source_mapping_url
If an explicit value is set, this will be written as the
sourceMappingURL into the output_stream. Note that the path
normalization will NOT use this value, so if paths have been
manually provided, ensure that normalize_paths is set to False
if the behavior is unwanted. | [
"Write",
"out",
"the",
"mappings",
"sources",
"and",
"names",
"(",
"generally",
"produced",
"by",
"the",
"write",
"function",
")",
"to",
"the",
"provided",
"sourcemap_stream",
"and",
"write",
"the",
"sourceMappingURL",
"to",
"the",
"output_stream",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/sourcemap.py#L508-L573 |
calmjs/calmjs.parse | src/calmjs/parse/sourcemap.py | Names.update | def update(self, name):
"""
Query a name for the relative index value to be added into the
source map name field (optional 5th element).
"""
if name is None:
return
if name not in self._names:
# add the name if it isn't already tracked
self._names[name] = len(self._names)
result = self._names[name] - self._current
self._current = self._names[name]
return result | python | def update(self, name):
"""
Query a name for the relative index value to be added into the
source map name field (optional 5th element).
"""
if name is None:
return
if name not in self._names:
# add the name if it isn't already tracked
self._names[name] = len(self._names)
result = self._names[name] - self._current
self._current = self._names[name]
return result | [
"def",
"update",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"is",
"None",
":",
"return",
"if",
"name",
"not",
"in",
"self",
".",
"_names",
":",
"# add the name if it isn't already tracked",
"self",
".",
"_names",
"[",
"name",
"]",
"=",
"len",
"(",... | Query a name for the relative index value to be added into the
source map name field (optional 5th element). | [
"Query",
"a",
"name",
"for",
"the",
"relative",
"index",
"value",
"to",
"be",
"added",
"into",
"the",
"source",
"map",
"name",
"field",
"(",
"optional",
"5th",
"element",
")",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/sourcemap.py#L32-L47 |
calmjs/calmjs.parse | src/calmjs/parse/utils.py | repr_compat | def repr_compat(s):
"""
Since Python 2 is annoying with unicode literals, and that we are
enforcing the usage of unicode, this ensures the repr doesn't spew
out the unicode literal prefix.
"""
if unicode and isinstance(s, unicode):
return repr(s)[1:]
else:
return repr(s) | python | def repr_compat(s):
"""
Since Python 2 is annoying with unicode literals, and that we are
enforcing the usage of unicode, this ensures the repr doesn't spew
out the unicode literal prefix.
"""
if unicode and isinstance(s, unicode):
return repr(s)[1:]
else:
return repr(s) | [
"def",
"repr_compat",
"(",
"s",
")",
":",
"if",
"unicode",
"and",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"repr",
"(",
"s",
")",
"[",
"1",
":",
"]",
"else",
":",
"return",
"repr",
"(",
"s",
")"
] | Since Python 2 is annoying with unicode literals, and that we are
enforcing the usage of unicode, this ensures the repr doesn't spew
out the unicode literal prefix. | [
"Since",
"Python",
"2",
"is",
"annoying",
"with",
"unicode",
"literals",
"and",
"that",
"we",
"are",
"enforcing",
"the",
"usage",
"of",
"unicode",
"this",
"ensures",
"the",
"repr",
"doesn",
"t",
"spew",
"out",
"the",
"unicode",
"literal",
"prefix",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/utils.py#L24-L34 |
calmjs/calmjs.parse | src/calmjs/parse/utils.py | generate_tab_names | def generate_tab_names(name):
"""
Return the names to lextab and yacctab modules for the given module
name. Typical usage should be like so::
>>> lextab, yacctab = generate_tab_names(__name__)
"""
package_name, module_name = name.rsplit('.', 1)
version = ply_dist.version.replace(
'.', '_') if ply_dist is not None else 'unknown'
data = (package_name, module_name, py_major, version)
lextab = '%s.lextab_%s_py%d_ply%s' % data
yacctab = '%s.yacctab_%s_py%d_ply%s' % data
return lextab, yacctab | python | def generate_tab_names(name):
"""
Return the names to lextab and yacctab modules for the given module
name. Typical usage should be like so::
>>> lextab, yacctab = generate_tab_names(__name__)
"""
package_name, module_name = name.rsplit('.', 1)
version = ply_dist.version.replace(
'.', '_') if ply_dist is not None else 'unknown'
data = (package_name, module_name, py_major, version)
lextab = '%s.lextab_%s_py%d_ply%s' % data
yacctab = '%s.yacctab_%s_py%d_ply%s' % data
return lextab, yacctab | [
"def",
"generate_tab_names",
"(",
"name",
")",
":",
"package_name",
",",
"module_name",
"=",
"name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"version",
"=",
"ply_dist",
".",
"version",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
"if",
"ply_dist",
"i... | Return the names to lextab and yacctab modules for the given module
name. Typical usage should be like so::
>>> lextab, yacctab = generate_tab_names(__name__) | [
"Return",
"the",
"names",
"to",
"lextab",
"and",
"yacctab",
"modules",
"for",
"the",
"given",
"module",
"name",
".",
"Typical",
"usage",
"should",
"be",
"like",
"so",
"::"
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/utils.py#L37-L52 |
calmjs/calmjs.parse | src/calmjs/parse/utils.py | normrelpath | def normrelpath(base, target):
"""
This function takes the base and target arguments as paths, and
returns an equivalent relative path from base to the target, if both
provided paths are absolute.
"""
if not all(map(isabs, [base, target])):
return target
return relpath(normpath(target), dirname(normpath(base))) | python | def normrelpath(base, target):
"""
This function takes the base and target arguments as paths, and
returns an equivalent relative path from base to the target, if both
provided paths are absolute.
"""
if not all(map(isabs, [base, target])):
return target
return relpath(normpath(target), dirname(normpath(base))) | [
"def",
"normrelpath",
"(",
"base",
",",
"target",
")",
":",
"if",
"not",
"all",
"(",
"map",
"(",
"isabs",
",",
"[",
"base",
",",
"target",
"]",
")",
")",
":",
"return",
"target",
"return",
"relpath",
"(",
"normpath",
"(",
"target",
")",
",",
"dirna... | This function takes the base and target arguments as paths, and
returns an equivalent relative path from base to the target, if both
provided paths are absolute. | [
"This",
"function",
"takes",
"the",
"base",
"and",
"target",
"arguments",
"as",
"paths",
"and",
"returns",
"an",
"equivalent",
"relative",
"path",
"from",
"base",
"to",
"the",
"target",
"if",
"both",
"provided",
"paths",
"are",
"absolute",
"."
] | train | https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/utils.py#L60-L70 |
all-umass/graphs | graphs/reorder.py | permute_graph | def permute_graph(G, order):
'''Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()).
'''
adj = G.matrix('dense')
adj = adj[np.ix_(order, order)]
return Graph.from_adj_matrix(adj) | python | def permute_graph(G, order):
'''Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()).
'''
adj = G.matrix('dense')
adj = adj[np.ix_(order, order)]
return Graph.from_adj_matrix(adj) | [
"def",
"permute_graph",
"(",
"G",
",",
"order",
")",
":",
"adj",
"=",
"G",
".",
"matrix",
"(",
"'dense'",
")",
"adj",
"=",
"adj",
"[",
"np",
".",
"ix_",
"(",
"order",
",",
"order",
")",
"]",
"return",
"Graph",
".",
"from_adj_matrix",
"(",
"adj",
... | Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()). | [
"Reorder",
"the",
"graph",
"s",
"vertices",
"returning",
"a",
"copy",
"of",
"the",
"input",
"graph",
".",
"order",
":",
"integer",
"array",
"-",
"like",
"some",
"permutation",
"of",
"range",
"(",
"G",
".",
"num_vertices",
"()",
")",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/reorder.py#L24-L30 |
all-umass/graphs | graphs/reorder.py | laplacian_reordering | def laplacian_reordering(G):
'''Reorder vertices using the eigenvector of the graph Laplacian corresponding
to the first positive eigenvalue.'''
L = G.laplacian()
vals, vecs = np.linalg.eigh(L)
min_positive_idx = np.argmax(vals == vals[vals>0].min())
vec = vecs[:, min_positive_idx]
return permute_graph(G, np.argsort(vec)) | python | def laplacian_reordering(G):
'''Reorder vertices using the eigenvector of the graph Laplacian corresponding
to the first positive eigenvalue.'''
L = G.laplacian()
vals, vecs = np.linalg.eigh(L)
min_positive_idx = np.argmax(vals == vals[vals>0].min())
vec = vecs[:, min_positive_idx]
return permute_graph(G, np.argsort(vec)) | [
"def",
"laplacian_reordering",
"(",
"G",
")",
":",
"L",
"=",
"G",
".",
"laplacian",
"(",
")",
"vals",
",",
"vecs",
"=",
"np",
".",
"linalg",
".",
"eigh",
"(",
"L",
")",
"min_positive_idx",
"=",
"np",
".",
"argmax",
"(",
"vals",
"==",
"vals",
"[",
... | Reorder vertices using the eigenvector of the graph Laplacian corresponding
to the first positive eigenvalue. | [
"Reorder",
"vertices",
"using",
"the",
"eigenvector",
"of",
"the",
"graph",
"Laplacian",
"corresponding",
"to",
"the",
"first",
"positive",
"eigenvalue",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/reorder.py#L64-L71 |
all-umass/graphs | graphs/reorder.py | node_centroid_hill_climbing | def node_centroid_hill_climbing(G, relax=1, num_centerings=20, verbose=False):
'''Iterative reordering method based on alternating rounds of node-centering
and hill-climbing search.'''
# Initialize order with BFS from a random start node.
order = _breadth_first_order(G)
for it in range(num_centerings):
B = permute_graph(G, order).bandwidth()
nc_order = _node_center(G, order, relax=relax)
nc_B = permute_graph(G, nc_order).bandwidth()
if nc_B < B:
if verbose: # pragma: no cover
print('post-center', B, nc_B)
order = nc_order
order = _hill_climbing(G, order, verbose=verbose)
return permute_graph(G, order) | python | def node_centroid_hill_climbing(G, relax=1, num_centerings=20, verbose=False):
'''Iterative reordering method based on alternating rounds of node-centering
and hill-climbing search.'''
# Initialize order with BFS from a random start node.
order = _breadth_first_order(G)
for it in range(num_centerings):
B = permute_graph(G, order).bandwidth()
nc_order = _node_center(G, order, relax=relax)
nc_B = permute_graph(G, nc_order).bandwidth()
if nc_B < B:
if verbose: # pragma: no cover
print('post-center', B, nc_B)
order = nc_order
order = _hill_climbing(G, order, verbose=verbose)
return permute_graph(G, order) | [
"def",
"node_centroid_hill_climbing",
"(",
"G",
",",
"relax",
"=",
"1",
",",
"num_centerings",
"=",
"20",
",",
"verbose",
"=",
"False",
")",
":",
"# Initialize order with BFS from a random start node.",
"order",
"=",
"_breadth_first_order",
"(",
"G",
")",
"for",
"... | Iterative reordering method based on alternating rounds of node-centering
and hill-climbing search. | [
"Iterative",
"reordering",
"method",
"based",
"on",
"alternating",
"rounds",
"of",
"node",
"-",
"centering",
"and",
"hill",
"-",
"climbing",
"search",
"."
] | train | https://github.com/all-umass/graphs/blob/4fbeb025dfe33340335f34300f58dd3809228822/graphs/reorder.py#L74-L88 |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.add_column_xsd | def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type, cls):
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, Geometry):
geometry_type = column.type.geometry_type
xsd_type = self.SIMPLE_GEOMETRY_XSD_TYPES[geometry_type]
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Enum):
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction', {'base': 'xsd:string'}) \
as tb:
for enum in column.type.enums:
with tag(tb, 'xsd:enumeration', {'value': enum}):
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Numeric):
if column.type.scale is None and column.type.precision is None:
attrs['type'] = 'xsd:decimal'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:decimal'}) as tb:
if column.type.scale is not None:
with tag(tb, 'xsd:fractionDigits',
{'value': str(column.type.scale)}) \
as tb:
pass
if column.type.precision is not None:
precision = column.type.precision
with tag(tb, 'xsd:totalDigits',
{'value': str(precision)}) \
as tb:
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.String) \
or isinstance(column.type, sqlalchemy.Text) \
or isinstance(column.type, sqlalchemy.Unicode) \
or isinstance(column.type, sqlalchemy.UnicodeText):
if column.type.length is None:
attrs['type'] = 'xsd:string'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:string'}) as tb:
with tag(tb, 'xsd:maxLength',
{'value': str(column.type.length)}):
pass
self.element_callback(tb, column)
return tb
raise UnsupportedColumnTypeError(column.type) | python | def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type, cls):
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, Geometry):
geometry_type = column.type.geometry_type
xsd_type = self.SIMPLE_GEOMETRY_XSD_TYPES[geometry_type]
attrs['type'] = xsd_type
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Enum):
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction', {'base': 'xsd:string'}) \
as tb:
for enum in column.type.enums:
with tag(tb, 'xsd:enumeration', {'value': enum}):
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.Numeric):
if column.type.scale is None and column.type.precision is None:
attrs['type'] = 'xsd:decimal'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:decimal'}) as tb:
if column.type.scale is not None:
with tag(tb, 'xsd:fractionDigits',
{'value': str(column.type.scale)}) \
as tb:
pass
if column.type.precision is not None:
precision = column.type.precision
with tag(tb, 'xsd:totalDigits',
{'value': str(precision)}) \
as tb:
pass
self.element_callback(tb, column)
return tb
if isinstance(column.type, sqlalchemy.String) \
or isinstance(column.type, sqlalchemy.Text) \
or isinstance(column.type, sqlalchemy.Unicode) \
or isinstance(column.type, sqlalchemy.UnicodeText):
if column.type.length is None:
attrs['type'] = 'xsd:string'
with tag(tb, 'xsd:element', attrs) as tb:
self.element_callback(tb, column)
return tb
else:
with tag(tb, 'xsd:element', attrs) as tb:
with tag(tb, 'xsd:simpleType') as tb:
with tag(tb, 'xsd:restriction',
{'base': 'xsd:string'}) as tb:
with tag(tb, 'xsd:maxLength',
{'value': str(column.type.length)}):
pass
self.element_callback(tb, column)
return tb
raise UnsupportedColumnTypeError(column.type) | [
"def",
"add_column_xsd",
"(",
"self",
",",
"tb",
",",
"column",
",",
"attrs",
")",
":",
"if",
"column",
".",
"nullable",
":",
"attrs",
"[",
"'minOccurs'",
"]",
"=",
"str",
"(",
"0",
")",
"attrs",
"[",
"'nillable'",
"]",
"=",
"'true'",
"for",
"cls",
... | Add the XSD for a column to tb (a TreeBuilder) | [
"Add",
"the",
"XSD",
"for",
"a",
"column",
"to",
"tb",
"(",
"a",
"TreeBuilder",
")"
] | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L73-L144 |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.add_column_property_xsd | def add_column_property_xsd(self, tb, column_property):
""" Add the XSD for a column property to the ``TreeBuilder``. """
if len(column_property.columns) != 1:
raise NotImplementedError # pragma: no cover
column = column_property.columns[0]
if column.primary_key and not self.include_primary_keys:
return
if column.foreign_keys and not self.include_foreign_keys:
if len(column.foreign_keys) != 1: # pragma: no cover
# FIXME understand when a column can have multiple
# foreign keys
raise NotImplementedError()
return
attrs = {'name': column_property.key}
self.add_column_xsd(tb, column, attrs) | python | def add_column_property_xsd(self, tb, column_property):
""" Add the XSD for a column property to the ``TreeBuilder``. """
if len(column_property.columns) != 1:
raise NotImplementedError # pragma: no cover
column = column_property.columns[0]
if column.primary_key and not self.include_primary_keys:
return
if column.foreign_keys and not self.include_foreign_keys:
if len(column.foreign_keys) != 1: # pragma: no cover
# FIXME understand when a column can have multiple
# foreign keys
raise NotImplementedError()
return
attrs = {'name': column_property.key}
self.add_column_xsd(tb, column, attrs) | [
"def",
"add_column_property_xsd",
"(",
"self",
",",
"tb",
",",
"column_property",
")",
":",
"if",
"len",
"(",
"column_property",
".",
"columns",
")",
"!=",
"1",
":",
"raise",
"NotImplementedError",
"# pragma: no cover",
"column",
"=",
"column_property",
".",
"co... | Add the XSD for a column property to the ``TreeBuilder``. | [
"Add",
"the",
"XSD",
"for",
"a",
"column",
"property",
"to",
"the",
"TreeBuilder",
"."
] | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L146-L160 |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.add_class_properties_xsd | def add_class_properties_xsd(self, tb, cls):
""" Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. """
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls) | python | def add_class_properties_xsd(self, tb, cls):
""" Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. """
for p in class_mapper(cls).iterate_properties:
if isinstance(p, ColumnProperty):
self.add_column_property_xsd(tb, p)
if self.sequence_callback:
self.sequence_callback(tb, cls) | [
"def",
"add_class_properties_xsd",
"(",
"self",
",",
"tb",
",",
"cls",
")",
":",
"for",
"p",
"in",
"class_mapper",
"(",
"cls",
")",
".",
"iterate_properties",
":",
"if",
"isinstance",
"(",
"p",
",",
"ColumnProperty",
")",
":",
"self",
".",
"add_column_prop... | Add the XSD for the class properties to the ``TreeBuilder``. And
call the user ``sequence_callback``. | [
"Add",
"the",
"XSD",
"for",
"the",
"class",
"properties",
"to",
"the",
"TreeBuilder",
".",
"And",
"call",
"the",
"user",
"sequence_callback",
"."
] | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L162-L169 |
elemoine/papyrus | papyrus/xsd.py | XSDGenerator.get_class_xsd | def get_class_xsd(self, io, cls):
""" Returns the XSD for a mapped class. """
attrs = {}
attrs['xmlns:gml'] = 'http://www.opengis.net/gml'
attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema'
tb = TreeBuilder()
with tag(tb, 'xsd:schema', attrs) as tb:
with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb:
with tag(tb, 'xsd:complexContent') as tb:
with tag(tb, 'xsd:extension',
{'base': 'gml:AbstractFeatureType'}) as tb:
with tag(tb, 'xsd:sequence') as tb:
self.add_class_properties_xsd(tb, cls)
ElementTree(tb.close()).write(io, encoding='utf-8')
return io | python | def get_class_xsd(self, io, cls):
""" Returns the XSD for a mapped class. """
attrs = {}
attrs['xmlns:gml'] = 'http://www.opengis.net/gml'
attrs['xmlns:xsd'] = 'http://www.w3.org/2001/XMLSchema'
tb = TreeBuilder()
with tag(tb, 'xsd:schema', attrs) as tb:
with tag(tb, 'xsd:complexType', {'name': cls.__name__}) as tb:
with tag(tb, 'xsd:complexContent') as tb:
with tag(tb, 'xsd:extension',
{'base': 'gml:AbstractFeatureType'}) as tb:
with tag(tb, 'xsd:sequence') as tb:
self.add_class_properties_xsd(tb, cls)
ElementTree(tb.close()).write(io, encoding='utf-8')
return io | [
"def",
"get_class_xsd",
"(",
"self",
",",
"io",
",",
"cls",
")",
":",
"attrs",
"=",
"{",
"}",
"attrs",
"[",
"'xmlns:gml'",
"]",
"=",
"'http://www.opengis.net/gml'",
"attrs",
"[",
"'xmlns:xsd'",
"]",
"=",
"'http://www.w3.org/2001/XMLSchema'",
"tb",
"=",
"TreeBu... | Returns the XSD for a mapped class. | [
"Returns",
"the",
"XSD",
"for",
"a",
"mapped",
"class",
"."
] | train | https://github.com/elemoine/papyrus/blob/764fb2326105df74fbd3dbcd7e58f4cb21956005/papyrus/xsd.py#L171-L186 |
ryanvarley/ExoData | exodata/database.py | load_db_from_url | def load_db_from_url(url="https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"):
""" Loads the database from a gzipped version of the system folder, by default the one located in the oec_gzip repo
in the OpenExoplanetCatalogue GitHub group.
The database is loaded from the url in memory
:param url: url to load (must be gzipped version of systems folder)
:return: OECDatabase objected initialised with latest OEC Version
"""
catalogue = gzip.GzipFile(fileobj=io.BytesIO(requests.get(url).content))
database = OECDatabase(catalogue, stream=True)
return database | python | def load_db_from_url(url="https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"):
""" Loads the database from a gzipped version of the system folder, by default the one located in the oec_gzip repo
in the OpenExoplanetCatalogue GitHub group.
The database is loaded from the url in memory
:param url: url to load (must be gzipped version of systems folder)
:return: OECDatabase objected initialised with latest OEC Version
"""
catalogue = gzip.GzipFile(fileobj=io.BytesIO(requests.get(url).content))
database = OECDatabase(catalogue, stream=True)
return database | [
"def",
"load_db_from_url",
"(",
"url",
"=",
"\"https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz\"",
")",
":",
"catalogue",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"io",
".",
"BytesIO",
"(",
"requests",
".",
"get",
"(",
"url",
"... | Loads the database from a gzipped version of the system folder, by default the one located in the oec_gzip repo
in the OpenExoplanetCatalogue GitHub group.
The database is loaded from the url in memory
:param url: url to load (must be gzipped version of systems folder)
:return: OECDatabase objected initialised with latest OEC Version | [
"Loads",
"the",
"database",
"from",
"a",
"gzipped",
"version",
"of",
"the",
"system",
"folder",
"by",
"default",
"the",
"one",
"located",
"in",
"the",
"oec_gzip",
"repo",
"in",
"the",
"OpenExoplanetCatalogue",
"GitHub",
"group",
"."
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/database.py#L229-L242 |
ryanvarley/ExoData | exodata/database.py | OECDatabase.searchPlanet | def searchPlanet(self, name):
""" Searches the database for a planet. Input can be complete ie GJ1214b, alternate name variations or even
just 1214.
:param name: the name of the planet to search
:return: dictionary of results as planetname -> planet object
"""
searchName = compactString(name)
returnDict = {}
for altname, planetObj in self._planetSearchDict.iteritems():
if re.search(searchName, altname):
returnDict[planetObj.name] = planetObj
if returnDict:
if len(returnDict) == 1:
return returnDict.values()[0]
else:
return returnDict.values()
else:
return False | python | def searchPlanet(self, name):
""" Searches the database for a planet. Input can be complete ie GJ1214b, alternate name variations or even
just 1214.
:param name: the name of the planet to search
:return: dictionary of results as planetname -> planet object
"""
searchName = compactString(name)
returnDict = {}
for altname, planetObj in self._planetSearchDict.iteritems():
if re.search(searchName, altname):
returnDict[planetObj.name] = planetObj
if returnDict:
if len(returnDict) == 1:
return returnDict.values()[0]
else:
return returnDict.values()
else:
return False | [
"def",
"searchPlanet",
"(",
"self",
",",
"name",
")",
":",
"searchName",
"=",
"compactString",
"(",
"name",
")",
"returnDict",
"=",
"{",
"}",
"for",
"altname",
",",
"planetObj",
"in",
"self",
".",
"_planetSearchDict",
".",
"iteritems",
"(",
")",
":",
"if... | Searches the database for a planet. Input can be complete ie GJ1214b, alternate name variations or even
just 1214.
:param name: the name of the planet to search
:return: dictionary of results as planetname -> planet object | [
"Searches",
"the",
"database",
"for",
"a",
"planet",
".",
"Input",
"can",
"be",
"complete",
"ie",
"GJ1214b",
"alternate",
"name",
"variations",
"or",
"even",
"just",
"1214",
"."
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/database.py#L43-L65 |
ryanvarley/ExoData | exodata/database.py | OECDatabase.transitingPlanets | def transitingPlanets(self):
""" Returns a list of transiting planet objects
"""
transitingPlanets = []
for planet in self.planets:
try:
if planet.isTransiting:
transitingPlanets.append(planet)
except KeyError: # No 'discoverymethod' tag - this also filters Solar System planets
pass
return transitingPlanets | python | def transitingPlanets(self):
""" Returns a list of transiting planet objects
"""
transitingPlanets = []
for planet in self.planets:
try:
if planet.isTransiting:
transitingPlanets.append(planet)
except KeyError: # No 'discoverymethod' tag - this also filters Solar System planets
pass
return transitingPlanets | [
"def",
"transitingPlanets",
"(",
"self",
")",
":",
"transitingPlanets",
"=",
"[",
"]",
"for",
"planet",
"in",
"self",
".",
"planets",
":",
"try",
":",
"if",
"planet",
".",
"isTransiting",
":",
"transitingPlanets",
".",
"append",
"(",
"planet",
")",
"except... | Returns a list of transiting planet objects | [
"Returns",
"a",
"list",
"of",
"transiting",
"planet",
"objects"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/database.py#L68-L81 |
ryanvarley/ExoData | exodata/database.py | OECDatabase._generatePlanetSearchDict | def _generatePlanetSearchDict(self):
""" Generates a search dictionary for planets by taking all names and 'flattening' them to the most compact form
(lowercase, no spaces and dashes)
"""
planetNameDict = {}
for planet in self.planets:
name = planet.name
altnames = planet.params['altnames']
altnames.append(name) # as we also want the default name to be searchable
for altname in altnames:
reducedname = compactString(altname)
planetNameDict[reducedname] = planet
return planetNameDict | python | def _generatePlanetSearchDict(self):
""" Generates a search dictionary for planets by taking all names and 'flattening' them to the most compact form
(lowercase, no spaces and dashes)
"""
planetNameDict = {}
for planet in self.planets:
name = planet.name
altnames = planet.params['altnames']
altnames.append(name) # as we also want the default name to be searchable
for altname in altnames:
reducedname = compactString(altname)
planetNameDict[reducedname] = planet
return planetNameDict | [
"def",
"_generatePlanetSearchDict",
"(",
"self",
")",
":",
"planetNameDict",
"=",
"{",
"}",
"for",
"planet",
"in",
"self",
".",
"planets",
":",
"name",
"=",
"planet",
".",
"name",
"altnames",
"=",
"planet",
".",
"params",
"[",
"'altnames'",
"]",
"altnames"... | Generates a search dictionary for planets by taking all names and 'flattening' them to the most compact form
(lowercase, no spaces and dashes) | [
"Generates",
"a",
"search",
"dictionary",
"for",
"planets",
"by",
"taking",
"all",
"names",
"and",
"flattening",
"them",
"to",
"the",
"most",
"compact",
"form",
"(",
"lowercase",
"no",
"spaces",
"and",
"dashes",
")"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/database.py#L83-L99 |
ryanvarley/ExoData | exodata/database.py | OECDatabase._loadDatabase | def _loadDatabase(self, databaseLocation, stream=False):
""" Loads the database from a given file path in the class
:param databaseLocation: the location on disk or the stream object
:param stream: if true treats the databaseLocation as a stream object
"""
# Initialise Database
self.systems = []
self.binaries = []
self.stars = []
self.planets = []
if stream:
tree = ET.parse(databaseLocation)
for system in tree.findall(".//system"):
self._loadSystem(system)
else:
databaseXML = glob.glob(os.path.join(databaseLocation, '*.xml'))
if not len(databaseXML):
raise LoadDataBaseError('could not find the database xml files. Have you given the correct location '
'to the open exoplanet catalogues /systems folder?')
for filename in databaseXML:
try:
with open(filename, 'r') as f:
tree = ET.parse(f)
except ET.ParseError as e: # this is sometimes raised rather than the root.tag system check
raise LoadDataBaseError(e)
root = tree.getroot()
# Process the system
if not root.tag == 'system':
raise LoadDataBaseError('file {0} does not contain a valid system - could be an error with your version'
' of the catalogue'.format(filename))
self._loadSystem(root) | python | def _loadDatabase(self, databaseLocation, stream=False):
""" Loads the database from a given file path in the class
:param databaseLocation: the location on disk or the stream object
:param stream: if true treats the databaseLocation as a stream object
"""
# Initialise Database
self.systems = []
self.binaries = []
self.stars = []
self.planets = []
if stream:
tree = ET.parse(databaseLocation)
for system in tree.findall(".//system"):
self._loadSystem(system)
else:
databaseXML = glob.glob(os.path.join(databaseLocation, '*.xml'))
if not len(databaseXML):
raise LoadDataBaseError('could not find the database xml files. Have you given the correct location '
'to the open exoplanet catalogues /systems folder?')
for filename in databaseXML:
try:
with open(filename, 'r') as f:
tree = ET.parse(f)
except ET.ParseError as e: # this is sometimes raised rather than the root.tag system check
raise LoadDataBaseError(e)
root = tree.getroot()
# Process the system
if not root.tag == 'system':
raise LoadDataBaseError('file {0} does not contain a valid system - could be an error with your version'
' of the catalogue'.format(filename))
self._loadSystem(root) | [
"def",
"_loadDatabase",
"(",
"self",
",",
"databaseLocation",
",",
"stream",
"=",
"False",
")",
":",
"# Initialise Database",
"self",
".",
"systems",
"=",
"[",
"]",
"self",
".",
"binaries",
"=",
"[",
"]",
"self",
".",
"stars",
"=",
"[",
"]",
"self",
".... | Loads the database from a given file path in the class
:param databaseLocation: the location on disk or the stream object
:param stream: if true treats the databaseLocation as a stream object | [
"Loads",
"the",
"database",
"from",
"a",
"given",
"file",
"path",
"in",
"the",
"class"
] | train | https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/database.py#L101-L138 |
mkrjhnsn/django-randomslugfield | randomslugfield/fields.py | RandomSlugField.generate_slug | def generate_slug(self, model_instance):
"""Returns a unique slug."""
queryset = model_instance.__class__._default_manager.all()
# Only count slugs that match current length to prevent issues
# when pre-existing slugs are a different length.
lookup = {'%s__regex' % self.attname: r'^.{%s}$' % self.length}
if queryset.filter(**lookup).count() >= len(self.chars)**self.length:
raise FieldError("No available slugs remaining.")
slug = get_random_string(self.length, self.chars)
# Exclude the current model instance from the queryset used in
# finding next valid slug.
if model_instance.pk:
queryset = queryset.exclude(pk=model_instance.pk)
# Form a kwarg dict used to impliment any unique_together
# contraints.
kwargs = {}
for params in model_instance._meta.unique_together:
if self.attname in params:
for param in params:
kwargs[param] = getattr(model_instance, param, None)
kwargs[self.attname] = slug
while queryset.filter(**kwargs):
slug = get_random_string(self.length, self.chars)
kwargs[self.attname] = slug
return slug | python | def generate_slug(self, model_instance):
"""Returns a unique slug."""
queryset = model_instance.__class__._default_manager.all()
# Only count slugs that match current length to prevent issues
# when pre-existing slugs are a different length.
lookup = {'%s__regex' % self.attname: r'^.{%s}$' % self.length}
if queryset.filter(**lookup).count() >= len(self.chars)**self.length:
raise FieldError("No available slugs remaining.")
slug = get_random_string(self.length, self.chars)
# Exclude the current model instance from the queryset used in
# finding next valid slug.
if model_instance.pk:
queryset = queryset.exclude(pk=model_instance.pk)
# Form a kwarg dict used to impliment any unique_together
# contraints.
kwargs = {}
for params in model_instance._meta.unique_together:
if self.attname in params:
for param in params:
kwargs[param] = getattr(model_instance, param, None)
kwargs[self.attname] = slug
while queryset.filter(**kwargs):
slug = get_random_string(self.length, self.chars)
kwargs[self.attname] = slug
return slug | [
"def",
"generate_slug",
"(",
"self",
",",
"model_instance",
")",
":",
"queryset",
"=",
"model_instance",
".",
"__class__",
".",
"_default_manager",
".",
"all",
"(",
")",
"# Only count slugs that match current length to prevent issues",
"# when pre-existing slugs are a differe... | Returns a unique slug. | [
"Returns",
"a",
"unique",
"slug",
"."
] | train | https://github.com/mkrjhnsn/django-randomslugfield/blob/50ea1f8980ef3beed610306f47f1776425377494/randomslugfield/fields.py#L71-L101 |
mkrjhnsn/django-randomslugfield | randomslugfield/fields.py | RandomSlugField.south_field_triple | def south_field_triple(self):
"""Returns a suitable description of this field for South."""
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = '%s.%s' % (self.__module__, self.__class__.__name__)
args, kwargs = introspector(self)
kwargs.update({
'length': repr(self.length),
'exclude_upper': repr(self.exclude_upper),
'exclude_lower': repr(self.exclude_lower),
'exclude_digits': repr(self.exclude_digits),
'exclude_vowels': repr(self.exclude_vowels),
})
# That's our definition!
return (field_class, args, kwargs) | python | def south_field_triple(self):
"""Returns a suitable description of this field for South."""
# We'll just introspect the _actual_ field.
from south.modelsinspector import introspector
field_class = '%s.%s' % (self.__module__, self.__class__.__name__)
args, kwargs = introspector(self)
kwargs.update({
'length': repr(self.length),
'exclude_upper': repr(self.exclude_upper),
'exclude_lower': repr(self.exclude_lower),
'exclude_digits': repr(self.exclude_digits),
'exclude_vowels': repr(self.exclude_vowels),
})
# That's our definition!
return (field_class, args, kwargs) | [
"def",
"south_field_triple",
"(",
"self",
")",
":",
"# We'll just introspect the _actual_ field.",
"from",
"south",
".",
"modelsinspector",
"import",
"introspector",
"field_class",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"__module__",
",",
"self",
".",
"__class__",
"... | Returns a suitable description of this field for South. | [
"Returns",
"a",
"suitable",
"description",
"of",
"this",
"field",
"for",
"South",
"."
] | train | https://github.com/mkrjhnsn/django-randomslugfield/blob/50ea1f8980ef3beed610306f47f1776425377494/randomslugfield/fields.py#L124-L138 |
LasLabs/python-helpscout | helpscout/base_api.py | BaseApi.create | def create(cls, session, record, endpoint_override=None, out_type=None,
**add_params):
"""Create an object on HelpScout.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to be created.
endpoint_override (str, optional): Override the default
endpoint using this.
out_type (helpscout.BaseModel, optional): The type of record to
output. This should be provided by child classes, by calling
super.
**add_params (mixed): Add these to the request parameters.
Returns:
helpscout.models.BaseModel: Newly created record. Will be of the
"""
cls._check_implements('create')
data = record.to_api()
params = {
'reload': True,
}
params.update(**add_params)
data.update(params)
return cls(
endpoint_override or '/%s.json' % cls.__endpoint__,
data=data,
request_type=RequestPaginator.POST,
singleton=True,
session=session,
out_type=out_type,
) | python | def create(cls, session, record, endpoint_override=None, out_type=None,
**add_params):
"""Create an object on HelpScout.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to be created.
endpoint_override (str, optional): Override the default
endpoint using this.
out_type (helpscout.BaseModel, optional): The type of record to
output. This should be provided by child classes, by calling
super.
**add_params (mixed): Add these to the request parameters.
Returns:
helpscout.models.BaseModel: Newly created record. Will be of the
"""
cls._check_implements('create')
data = record.to_api()
params = {
'reload': True,
}
params.update(**add_params)
data.update(params)
return cls(
endpoint_override or '/%s.json' % cls.__endpoint__,
data=data,
request_type=RequestPaginator.POST,
singleton=True,
session=session,
out_type=out_type,
) | [
"def",
"create",
"(",
"cls",
",",
"session",
",",
"record",
",",
"endpoint_override",
"=",
"None",
",",
"out_type",
"=",
"None",
",",
"*",
"*",
"add_params",
")",
":",
"cls",
".",
"_check_implements",
"(",
"'create'",
")",
"data",
"=",
"record",
".",
"... | Create an object on HelpScout.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to be created.
endpoint_override (str, optional): Override the default
endpoint using this.
out_type (helpscout.BaseModel, optional): The type of record to
output. This should be provided by child classes, by calling
super.
**add_params (mixed): Add these to the request parameters.
Returns:
helpscout.models.BaseModel: Newly created record. Will be of the | [
"Create",
"an",
"object",
"on",
"HelpScout",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_api.py#L130-L161 |
LasLabs/python-helpscout | helpscout/base_api.py | BaseApi.delete | def delete(cls, session, record, endpoint_override=None, out_type=None):
"""Delete a record.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to be deleted.
endpoint_override (str, optional): Override the default
endpoint using this.
out_type (helpscout.BaseModel, optional): The type of record to
output. This should be provided by child classes, by calling
super.
Returns:
NoneType: Nothing.
"""
cls._check_implements('delete')
return cls(
endpoint_override or '/%s/%s.json' % (
cls.__endpoint__, record.id,
),
request_type=RequestPaginator.DELETE,
singleton=True,
session=session,
out_type=out_type,
) | python | def delete(cls, session, record, endpoint_override=None, out_type=None):
"""Delete a record.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to be deleted.
endpoint_override (str, optional): Override the default
endpoint using this.
out_type (helpscout.BaseModel, optional): The type of record to
output. This should be provided by child classes, by calling
super.
Returns:
NoneType: Nothing.
"""
cls._check_implements('delete')
return cls(
endpoint_override or '/%s/%s.json' % (
cls.__endpoint__, record.id,
),
request_type=RequestPaginator.DELETE,
singleton=True,
session=session,
out_type=out_type,
) | [
"def",
"delete",
"(",
"cls",
",",
"session",
",",
"record",
",",
"endpoint_override",
"=",
"None",
",",
"out_type",
"=",
"None",
")",
":",
"cls",
".",
"_check_implements",
"(",
"'delete'",
")",
"return",
"cls",
"(",
"endpoint_override",
"or",
"'/%s/%s.json'"... | Delete a record.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to be deleted.
endpoint_override (str, optional): Override the default
endpoint using this.
out_type (helpscout.BaseModel, optional): The type of record to
output. This should be provided by child classes, by calling
super.
Returns:
NoneType: Nothing. | [
"Delete",
"a",
"record",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_api.py#L164-L188 |
LasLabs/python-helpscout | helpscout/base_api.py | BaseApi.get | def get(cls, session, record_id, endpoint_override=None):
"""Return a specific record.
Args:
session (requests.sessions.Session): Authenticated session.
record_id (int): The ID of the record to get.
endpoint_override (str, optional): Override the default
endpoint using this.
Returns:
helpscout.BaseModel: A record singleton, if existing. Otherwise
``None``.
"""
cls._check_implements('get')
try:
return cls(
endpoint_override or '/%s/%d.json' % (
cls.__endpoint__, record_id,
),
singleton=True,
session=session,
)
except HelpScoutRemoteException as e:
if e.status_code == 404:
return None
else:
raise | python | def get(cls, session, record_id, endpoint_override=None):
"""Return a specific record.
Args:
session (requests.sessions.Session): Authenticated session.
record_id (int): The ID of the record to get.
endpoint_override (str, optional): Override the default
endpoint using this.
Returns:
helpscout.BaseModel: A record singleton, if existing. Otherwise
``None``.
"""
cls._check_implements('get')
try:
return cls(
endpoint_override or '/%s/%d.json' % (
cls.__endpoint__, record_id,
),
singleton=True,
session=session,
)
except HelpScoutRemoteException as e:
if e.status_code == 404:
return None
else:
raise | [
"def",
"get",
"(",
"cls",
",",
"session",
",",
"record_id",
",",
"endpoint_override",
"=",
"None",
")",
":",
"cls",
".",
"_check_implements",
"(",
"'get'",
")",
"try",
":",
"return",
"cls",
"(",
"endpoint_override",
"or",
"'/%s/%d.json'",
"%",
"(",
"cls",
... | Return a specific record.
Args:
session (requests.sessions.Session): Authenticated session.
record_id (int): The ID of the record to get.
endpoint_override (str, optional): Override the default
endpoint using this.
Returns:
helpscout.BaseModel: A record singleton, if existing. Otherwise
``None``. | [
"Return",
"a",
"specific",
"record",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_api.py#L191-L217 |
LasLabs/python-helpscout | helpscout/base_api.py | BaseApi.list | def list(cls, session, endpoint_override=None, data=None):
"""Return records in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
endpoint_override (str, optional): Override the default
endpoint using this.
data (dict, optional): Data to provide as request parameters.
Returns:
RequestPaginator(output_type=helpscout.BaseModel): Results
iterator.
"""
cls._check_implements('list')
return cls(
endpoint_override or '/%s.json' % cls.__endpoint__,
data=data,
session=session,
) | python | def list(cls, session, endpoint_override=None, data=None):
"""Return records in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
endpoint_override (str, optional): Override the default
endpoint using this.
data (dict, optional): Data to provide as request parameters.
Returns:
RequestPaginator(output_type=helpscout.BaseModel): Results
iterator.
"""
cls._check_implements('list')
return cls(
endpoint_override or '/%s.json' % cls.__endpoint__,
data=data,
session=session,
) | [
"def",
"list",
"(",
"cls",
",",
"session",
",",
"endpoint_override",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"cls",
".",
"_check_implements",
"(",
"'list'",
")",
"return",
"cls",
"(",
"endpoint_override",
"or",
"'/%s.json'",
"%",
"cls",
".",
"__... | Return records in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
endpoint_override (str, optional): Override the default
endpoint using this.
data (dict, optional): Data to provide as request parameters.
Returns:
RequestPaginator(output_type=helpscout.BaseModel): Results
iterator. | [
"Return",
"records",
"in",
"a",
"mailbox",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_api.py#L220-L238 |
LasLabs/python-helpscout | helpscout/base_api.py | BaseApi.search | def search(cls, session, queries, out_type):
"""Search for a record given a domain.
Args:
session (requests.sessions.Session): Authenticated session.
queries (helpscout.models.Domain or iter): The queries for the
domain. If a ``Domain`` object is provided, it will simply be
returned. Otherwise, a ``Domain`` object will be generated
from the complex queries. In this case, the queries should
conform to the interface in
:func:`helpscout.domain.Domain.from_tuple`.
out_type (helpscout.BaseModel): The type of record to output. This
should be provided by child classes, by calling super.
Returns:
RequestPaginator(output_type=helpscout.BaseModel): Results
iterator of the ``out_type`` that is defined.
"""
cls._check_implements('search')
domain = cls.get_search_domain(queries)
return cls(
'/search/%s.json' % cls.__endpoint__,
data={'query': str(domain)},
session=session,
out_type=out_type,
) | python | def search(cls, session, queries, out_type):
"""Search for a record given a domain.
Args:
session (requests.sessions.Session): Authenticated session.
queries (helpscout.models.Domain or iter): The queries for the
domain. If a ``Domain`` object is provided, it will simply be
returned. Otherwise, a ``Domain`` object will be generated
from the complex queries. In this case, the queries should
conform to the interface in
:func:`helpscout.domain.Domain.from_tuple`.
out_type (helpscout.BaseModel): The type of record to output. This
should be provided by child classes, by calling super.
Returns:
RequestPaginator(output_type=helpscout.BaseModel): Results
iterator of the ``out_type`` that is defined.
"""
cls._check_implements('search')
domain = cls.get_search_domain(queries)
return cls(
'/search/%s.json' % cls.__endpoint__,
data={'query': str(domain)},
session=session,
out_type=out_type,
) | [
"def",
"search",
"(",
"cls",
",",
"session",
",",
"queries",
",",
"out_type",
")",
":",
"cls",
".",
"_check_implements",
"(",
"'search'",
")",
"domain",
"=",
"cls",
".",
"get_search_domain",
"(",
"queries",
")",
"return",
"cls",
"(",
"'/search/%s.json'",
"... | Search for a record given a domain.
Args:
session (requests.sessions.Session): Authenticated session.
queries (helpscout.models.Domain or iter): The queries for the
domain. If a ``Domain`` object is provided, it will simply be
returned. Otherwise, a ``Domain`` object will be generated
from the complex queries. In this case, the queries should
conform to the interface in
:func:`helpscout.domain.Domain.from_tuple`.
out_type (helpscout.BaseModel): The type of record to output. This
should be provided by child classes, by calling super.
Returns:
RequestPaginator(output_type=helpscout.BaseModel): Results
iterator of the ``out_type`` that is defined. | [
"Search",
"for",
"a",
"record",
"given",
"a",
"domain",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_api.py#L241-L266 |
LasLabs/python-helpscout | helpscout/base_api.py | BaseApi.update | def update(cls, session, record):
"""Update a record.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to
be updated.
Returns:
helpscout.BaseModel: Freshly updated record.
"""
cls._check_implements('update')
data = record.to_api()
del data['id']
data['reload'] = True
return cls(
'/%s/%s.json' % (cls.__endpoint__, record.id),
data=data,
request_type=RequestPaginator.PUT,
singleton=True,
session=session,
) | python | def update(cls, session, record):
"""Update a record.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to
be updated.
Returns:
helpscout.BaseModel: Freshly updated record.
"""
cls._check_implements('update')
data = record.to_api()
del data['id']
data['reload'] = True
return cls(
'/%s/%s.json' % (cls.__endpoint__, record.id),
data=data,
request_type=RequestPaginator.PUT,
singleton=True,
session=session,
) | [
"def",
"update",
"(",
"cls",
",",
"session",
",",
"record",
")",
":",
"cls",
".",
"_check_implements",
"(",
"'update'",
")",
"data",
"=",
"record",
".",
"to_api",
"(",
")",
"del",
"data",
"[",
"'id'",
"]",
"data",
"[",
"'reload'",
"]",
"=",
"True",
... | Update a record.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.BaseModel): The record to
be updated.
Returns:
helpscout.BaseModel: Freshly updated record. | [
"Update",
"a",
"record",
"."
] | train | https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/base_api.py#L269-L290 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.