repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
GibbsConsulting/django-plotly-dash | demo/demo/bootstrap_app.py | session_demo_alert_callback | def session_demo_alert_callback(n_clicks, session_state=None, **kwargs):
'Output text based on both app state and session state'
if session_state is None:
raise NotImplementedError("Cannot handle a missing session state")
csf = session_state.get('bootstrap_demo_state', None)
if not csf:
... | python | def session_demo_alert_callback(n_clicks, session_state=None, **kwargs):
'Output text based on both app state and session state'
if session_state is None:
raise NotImplementedError("Cannot handle a missing session state")
csf = session_state.get('bootstrap_demo_state', None)
if not csf:
... | [
"def",
"session_demo_alert_callback",
"(",
"n_clicks",
",",
"session_state",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"'Output text based on both app state and session state'",
"if",
"session_state",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Cannot han... | Output text based on both app state and session state | [
"Output",
"text",
"based",
"on",
"both",
"app",
"state",
"and",
"session",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/demo/demo/bootstrap_app.py#L69-L79 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | add_usable_app | def add_usable_app(name, app):
'Add app to local registry by name'
name = slugify(name)
global usable_apps # pylint: disable=global-statement
usable_apps[name] = app
return name | python | def add_usable_app(name, app):
'Add app to local registry by name'
name = slugify(name)
global usable_apps # pylint: disable=global-statement
usable_apps[name] = app
return name | [
"def",
"add_usable_app",
"(",
"name",
",",
"app",
")",
":",
"'Add app to local registry by name'",
"name",
"=",
"slugify",
"(",
"name",
")",
"global",
"usable_apps",
"usable_apps",
"[",
"name",
"]",
"=",
"app",
"return",
"name"
] | Add app to local registry by name | [
"Add",
"app",
"to",
"local",
"registry",
"by",
"name"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L49-L54 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.get_base_pathname | def get_base_pathname(self, specific_identifier, cache_id):
'Base path name of this instance, taking into account any state or statelessness'
if not specific_identifier:
app_pathname = "%s:app-%s"% (app_name, main_view_label)
ndid = self._uid
else:
app_pathnam... | python | def get_base_pathname(self, specific_identifier, cache_id):
'Base path name of this instance, taking into account any state or statelessness'
if not specific_identifier:
app_pathname = "%s:app-%s"% (app_name, main_view_label)
ndid = self._uid
else:
app_pathnam... | [
"def",
"get_base_pathname",
"(",
"self",
",",
"specific_identifier",
",",
"cache_id",
")",
":",
"'Base path name of this instance, taking into account any state or statelessness'",
"if",
"not",
"specific_identifier",
":",
"app_pathname",
"=",
"\"%s:app-%s\"",
"%",
"(",
"app_n... | Base path name of this instance, taking into account any state or statelessness | [
"Base",
"path",
"name",
"of",
"this",
"instance",
"taking",
"into",
"account",
"any",
"state",
"or",
"statelessness"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L161-L179 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.do_form_dash_instance | def do_form_dash_instance(self, replacements=None, specific_identifier=None, cache_id=None):
'Perform the act of constructing a Dash instance taking into account state'
ndid, base_pathname = self.get_base_pathname(specific_identifier, cache_id)
return self.form_dash_instance(replacements, ndid,... | python | def do_form_dash_instance(self, replacements=None, specific_identifier=None, cache_id=None):
'Perform the act of constructing a Dash instance taking into account state'
ndid, base_pathname = self.get_base_pathname(specific_identifier, cache_id)
return self.form_dash_instance(replacements, ndid,... | [
"def",
"do_form_dash_instance",
"(",
"self",
",",
"replacements",
"=",
"None",
",",
"specific_identifier",
"=",
"None",
",",
"cache_id",
"=",
"None",
")",
":",
"'Perform the act of constructing a Dash instance taking into account state'",
"ndid",
",",
"base_pathname",
"="... | Perform the act of constructing a Dash instance taking into account state | [
"Perform",
"the",
"act",
"of",
"constructing",
"a",
"Dash",
"instance",
"taking",
"into",
"account",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L181-L185 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.form_dash_instance | def form_dash_instance(self, replacements=None, ndid=None, base_pathname=None):
'Construct a Dash instance taking into account state'
if ndid is None:
ndid = self._uid
rd = WrappedDash(base_pathname=base_pathname,
expanded_callbacks=self._expanded_callbacks... | python | def form_dash_instance(self, replacements=None, ndid=None, base_pathname=None):
'Construct a Dash instance taking into account state'
if ndid is None:
ndid = self._uid
rd = WrappedDash(base_pathname=base_pathname,
expanded_callbacks=self._expanded_callbacks... | [
"def",
"form_dash_instance",
"(",
"self",
",",
"replacements",
"=",
"None",
",",
"ndid",
"=",
"None",
",",
"base_pathname",
"=",
"None",
")",
":",
"'Construct a Dash instance taking into account state'",
"if",
"ndid",
"is",
"None",
":",
"ndid",
"=",
"self",
".",... | Construct a Dash instance taking into account state | [
"Construct",
"a",
"Dash",
"instance",
"taking",
"into",
"account",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L187-L209 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.callback | def callback(self, output, inputs=None, state=None, events=None):
'Form a callback function by wrapping, in the same way as the underlying Dash application would'
callback_set = {'output':output,
'inputs':inputs and inputs or dict(),
'state':state and stat... | python | def callback(self, output, inputs=None, state=None, events=None):
'Form a callback function by wrapping, in the same way as the underlying Dash application would'
callback_set = {'output':output,
'inputs':inputs and inputs or dict(),
'state':state and stat... | [
"def",
"callback",
"(",
"self",
",",
"output",
",",
"inputs",
"=",
"None",
",",
"state",
"=",
"None",
",",
"events",
"=",
"None",
")",
":",
"'Form a callback function by wrapping, in the same way as the underlying Dash application would'",
"callback_set",
"=",
"{",
"'... | Form a callback function by wrapping, in the same way as the underlying Dash application would | [
"Form",
"a",
"callback",
"function",
"by",
"wrapping",
"in",
"the",
"same",
"way",
"as",
"the",
"underlying",
"Dash",
"application",
"would"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L211-L220 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | DjangoDash.expanded_callback | def expanded_callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'''
Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments.
... | python | def expanded_callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'''
Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments.
... | [
"def",
"expanded_callback",
"(",
"self",
",",
"output",
",",
"inputs",
"=",
"[",
"]",
",",
"state",
"=",
"[",
"]",
",",
"events",
"=",
"[",
"]",
")",
":",
"self",
".",
"_expanded_callbacks",
"=",
"True",
"return",
"self",
".",
"callback",
"(",
"outpu... | Form an expanded callback.
This function registers the callback function, and sets an internal flag that mandates that all
callbacks are passed the enhanced arguments. | [
"Form",
"an",
"expanded",
"callback",
"."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L222-L230 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.augment_initial_layout | def augment_initial_layout(self, base_response, initial_arguments=None):
'Add application state to initial values'
if self.use_dash_layout() and not initial_arguments and False:
return base_response.data, base_response.mimetype
# Adjust the base layout response
baseDataInByt... | python | def augment_initial_layout(self, base_response, initial_arguments=None):
'Add application state to initial values'
if self.use_dash_layout() and not initial_arguments and False:
return base_response.data, base_response.mimetype
# Adjust the base layout response
baseDataInByt... | [
"def",
"augment_initial_layout",
"(",
"self",
",",
"base_response",
",",
"initial_arguments",
"=",
"None",
")",
":",
"'Add application state to initial values'",
"if",
"self",
".",
"use_dash_layout",
"(",
")",
"and",
"not",
"initial_arguments",
"and",
"False",
":",
... | Add application state to initial values | [
"Add",
"application",
"state",
"to",
"initial",
"values"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L312-L333 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.walk_tree_and_extract | def walk_tree_and_extract(self, data, target):
'Walk tree of properties and extract identifiers and associated values'
if isinstance(data, dict):
for key in ['children', 'props',]:
self.walk_tree_and_extract(data.get(key, None), target)
ident = data.get('id', None... | python | def walk_tree_and_extract(self, data, target):
'Walk tree of properties and extract identifiers and associated values'
if isinstance(data, dict):
for key in ['children', 'props',]:
self.walk_tree_and_extract(data.get(key, None), target)
ident = data.get('id', None... | [
"def",
"walk_tree_and_extract",
"(",
"self",
",",
"data",
",",
"target",
")",
":",
"'Walk tree of properties and extract identifiers and associated values'",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"for",
"key",
"in",
"[",
"'children'",
",",
"'props'... | Walk tree of properties and extract identifiers and associated values | [
"Walk",
"tree",
"of",
"properties",
"and",
"extract",
"identifiers",
"and",
"associated",
"values"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L335-L350 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.walk_tree_and_replace | def walk_tree_and_replace(self, data, overrides):
'''
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears...
'''
if isinstance(data, dict):
response = {}
replacements = {... | python | def walk_tree_and_replace(self, data, overrides):
'''
Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears...
'''
if isinstance(data, dict):
response = {}
replacements = {... | [
"def",
"walk_tree_and_replace",
"(",
"self",
",",
"data",
",",
"overrides",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"response",
"=",
"{",
"}",
"replacements",
"=",
"{",
"}",
"thisID",
"=",
"data",
".",
"get",
"(",
"'id'",
",... | Walk the tree. Rely on json decoding to insert instances of dict and list
ie we use a dna test for anatine, rather than our eyes and ears... | [
"Walk",
"the",
"tree",
".",
"Rely",
"on",
"json",
"decoding",
"to",
"insert",
"instances",
"of",
"dict",
"and",
"list",
"ie",
"we",
"use",
"a",
"dna",
"test",
"for",
"anatine",
"rather",
"than",
"our",
"eyes",
"and",
"ears",
"..."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L352-L376 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.locate_endpoint_function | def locate_endpoint_function(self, name=None):
'Locate endpoint function given name of view'
if name is not None:
ep = "%s_%s" %(self._base_pathname,
name)
else:
ep = self._base_pathname
return self._notflask.endpoints[ep]['view_func'] | python | def locate_endpoint_function(self, name=None):
'Locate endpoint function given name of view'
if name is not None:
ep = "%s_%s" %(self._base_pathname,
name)
else:
ep = self._base_pathname
return self._notflask.endpoints[ep]['view_func'] | [
"def",
"locate_endpoint_function",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"'Locate endpoint function given name of view'",
"if",
"name",
"is",
"not",
"None",
":",
"ep",
"=",
"\"%s_%s\"",
"%",
"(",
"self",
".",
"_base_pathname",
",",
"name",
")",
"els... | Locate endpoint function given name of view | [
"Locate",
"endpoint",
"function",
"given",
"name",
"of",
"view"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L396-L403 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.layout | def layout(self, value):
'Overloaded layout function to fix component names as needed'
if self._adjust_id:
self._fix_component_id(value)
return Dash.layout.fset(self, value) | python | def layout(self, value):
'Overloaded layout function to fix component names as needed'
if self._adjust_id:
self._fix_component_id(value)
return Dash.layout.fset(self, value) | [
"def",
"layout",
"(",
"self",
",",
"value",
")",
":",
"'Overloaded layout function to fix component names as needed'",
"if",
"self",
".",
"_adjust_id",
":",
"self",
".",
"_fix_component_id",
"(",
"value",
")",
"return",
"Dash",
".",
"layout",
".",
"fset",
"(",
"... | Overloaded layout function to fix component names as needed | [
"Overloaded",
"layout",
"function",
"to",
"fix",
"component",
"names",
"as",
"needed"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L407-L412 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash._fix_component_id | def _fix_component_id(self, component):
'Fix name of component ad all of its children'
theID = getattr(component, "id", None)
if theID is not None:
setattr(component, "id", self._fix_id(theID))
try:
for c in component.children:
self._fix_component... | python | def _fix_component_id(self, component):
'Fix name of component ad all of its children'
theID = getattr(component, "id", None)
if theID is not None:
setattr(component, "id", self._fix_id(theID))
try:
for c in component.children:
self._fix_component... | [
"def",
"_fix_component_id",
"(",
"self",
",",
"component",
")",
":",
"'Fix name of component ad all of its children'",
"theID",
"=",
"getattr",
"(",
"component",
",",
"\"id\"",
",",
"None",
")",
"if",
"theID",
"is",
"not",
"None",
":",
"setattr",
"(",
"component... | Fix name of component ad all of its children | [
"Fix",
"name",
"of",
"component",
"ad",
"all",
"of",
"its",
"children"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L414-L424 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash._fix_callback_item | def _fix_callback_item(self, item):
'Update component identifier'
item.component_id = self._fix_id(item.component_id)
return item | python | def _fix_callback_item(self, item):
'Update component identifier'
item.component_id = self._fix_id(item.component_id)
return item | [
"def",
"_fix_callback_item",
"(",
"self",
",",
"item",
")",
":",
"'Update component identifier'",
"item",
".",
"component_id",
"=",
"self",
".",
"_fix_id",
"(",
"item",
".",
"component_id",
")",
"return",
"item"
] | Update component identifier | [
"Update",
"component",
"identifier"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L433-L436 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.callback | def callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'Invoke callback, adjusting variable names as needed'
if isinstance(output, (list, tuple)):
fixed_outputs = [self._fix_callback_item(x) for x in output]
# Temporary check; can b... | python | def callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'Invoke callback, adjusting variable names as needed'
if isinstance(output, (list, tuple)):
fixed_outputs = [self._fix_callback_item(x) for x in output]
# Temporary check; can b... | [
"def",
"callback",
"(",
"self",
",",
"output",
",",
"inputs",
"=",
"[",
"]",
",",
"state",
"=",
"[",
"]",
",",
"events",
"=",
"[",
"]",
")",
":",
"'Invoke callback, adjusting variable names as needed'",
"if",
"isinstance",
"(",
"output",
",",
"(",
"list",
... | Invoke callback, adjusting variable names as needed | [
"Invoke",
"callback",
"adjusting",
"variable",
"names",
"as",
"needed"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L438-L450 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.dispatch | def dispatch(self):
'Perform dispatch, using request embedded within flask global state'
import flask
body = flask.request.get_json()
return self. dispatch_with_args(body, argMap=dict()) | python | def dispatch(self):
'Perform dispatch, using request embedded within flask global state'
import flask
body = flask.request.get_json()
return self. dispatch_with_args(body, argMap=dict()) | [
"def",
"dispatch",
"(",
"self",
")",
":",
"'Perform dispatch, using request embedded within flask global state'",
"import",
"flask",
"body",
"=",
"flask",
".",
"request",
".",
"get_json",
"(",
")",
"return",
"self",
".",
"dispatch_with_args",
"(",
"body",
",",
"argM... | Perform dispatch, using request embedded within flask global state | [
"Perform",
"dispatch",
"using",
"request",
"embedded",
"within",
"flask",
"global",
"state"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L452-L456 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.dispatch_with_args | def dispatch_with_args(self, body, argMap):
'Perform callback dispatching, with enhanced arguments and recording of response'
inputs = body.get('inputs', [])
state = body.get('state', [])
output = body['output']
try:
output_id = output['id']
output_proper... | python | def dispatch_with_args(self, body, argMap):
'Perform callback dispatching, with enhanced arguments and recording of response'
inputs = body.get('inputs', [])
state = body.get('state', [])
output = body['output']
try:
output_id = output['id']
output_proper... | [
"def",
"dispatch_with_args",
"(",
"self",
",",
"body",
",",
"argMap",
")",
":",
"'Perform callback dispatching, with enhanced arguments and recording of response'",
"inputs",
"=",
"body",
".",
"get",
"(",
"'inputs'",
",",
"[",
"]",
")",
"state",
"=",
"body",
".",
... | Perform callback dispatching, with enhanced arguments and recording of response | [
"Perform",
"callback",
"dispatching",
"with",
"enhanced",
"arguments",
"and",
"recording",
"of",
"response"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L459-L506 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/dash_wrapper.py | WrappedDash.extra_html_properties | def extra_html_properties(self, prefix=None, postfix=None, template_type=None):
'''
Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates.
'''
prefix = prefix if prefix else "d... | python | def extra_html_properties(self, prefix=None, postfix=None, template_type=None):
'''
Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates.
'''
prefix = prefix if prefix else "d... | [
"def",
"extra_html_properties",
"(",
"self",
",",
"prefix",
"=",
"None",
",",
"postfix",
"=",
"None",
",",
"template_type",
"=",
"None",
")",
":",
"prefix",
"=",
"prefix",
"if",
"prefix",
"else",
"\"django-plotly-dash\"",
"post_part",
"=",
"\"-%s\"",
"%",
"p... | Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates. | [
"Return",
"extra",
"html",
"properties",
"to",
"allow",
"individual",
"apps",
"to",
"be",
"styled",
"separately",
"."
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/dash_wrapper.py#L513-L531 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/templatetags/plotly_dash.py | plotly_direct | def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app'
da, app = _locate_daapp(name, slug, da)
view_func = app.locate_endpoint_function()
# Load embedded holder inserted by middleware
eh = context.request.dpd_content_handler.embedded_holder
app.set_embedde... | python | def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app'
da, app = _locate_daapp(name, slug, da)
view_func = app.locate_endpoint_function()
# Load embedded holder inserted by middleware
eh = context.request.dpd_content_handler.embedded_holder
app.set_embedde... | [
"def",
"plotly_direct",
"(",
"context",
",",
"name",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"da",
"=",
"None",
")",
":",
"'Direct insertion of a Dash app'",
"da",
",",
"app",
"=",
"_locate_daapp",
"(",
"name",
",",
"slug",
",",
"da",
")",
"view_func... | Direct insertion of a Dash app | [
"Direct",
"insertion",
"of",
"a",
"Dash",
"app"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/templatetags/plotly_dash.py#L91-L106 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/templatetags/plotly_dash.py | plotly_app_identifier | def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
'Return a slug-friendly identifier'
da, app = _locate_daapp(name, slug, da)
slugified_id = app.slugified_id()
if postfix:
return "%s-%s" %(slugified_id, postfix)
return slugified_id | python | def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
'Return a slug-friendly identifier'
da, app = _locate_daapp(name, slug, da)
slugified_id = app.slugified_id()
if postfix:
return "%s-%s" %(slugified_id, postfix)
return slugified_id | [
"def",
"plotly_app_identifier",
"(",
"name",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"da",
"=",
"None",
",",
"postfix",
"=",
"None",
")",
":",
"'Return a slug-friendly identifier'",
"da",
",",
"app",
"=",
"_locate_daapp",
"(",
"name",
",",
"slug",
",",... | Return a slug-friendly identifier | [
"Return",
"a",
"slug",
"-",
"friendly",
"identifier"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/templatetags/plotly_dash.py#L115-L124 | train |
GibbsConsulting/django-plotly-dash | django_plotly_dash/templatetags/plotly_dash.py | plotly_class | def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
'Return a string of space-separated class names'
da, app = _locate_daapp(name, slug, da)
return app.extra_html_properties(prefix=prefix,
postfix=postfix,
... | python | def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
'Return a string of space-separated class names'
da, app = _locate_daapp(name, slug, da)
return app.extra_html_properties(prefix=prefix,
postfix=postfix,
... | [
"def",
"plotly_class",
"(",
"name",
"=",
"None",
",",
"slug",
"=",
"None",
",",
"da",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"postfix",
"=",
"None",
",",
"template_type",
"=",
"None",
")",
":",
"'Return a string of space-separated class names'",
"da",... | Return a string of space-separated class names | [
"Return",
"a",
"string",
"of",
"space",
"-",
"separated",
"class",
"names"
] | 773ed081fc2ea3cc7607590322a14686a7a79bc5 | https://github.com/GibbsConsulting/django-plotly-dash/blob/773ed081fc2ea3cc7607590322a14686a7a79bc5/django_plotly_dash/templatetags/plotly_dash.py#L127-L134 | train |
atztogo/spglib | database/make_Wyckoff_db.py | parse_wyckoff_csv | def parse_wyckoff_csv(wyckoff_file):
"""Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0):::
"""
rowdata = []
points = []
hP_nums = [433, 436, 444, 450, 452, 458, 460]
for i, line ... | python | def parse_wyckoff_csv(wyckoff_file):
"""Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0):::
"""
rowdata = []
points = []
hP_nums = [433, 436, 444, 450, 452, 458, 460]
for i, line ... | [
"def",
"parse_wyckoff_csv",
"(",
"wyckoff_file",
")",
":",
"rowdata",
"=",
"[",
"]",
"points",
"=",
"[",
"]",
"hP_nums",
"=",
"[",
"433",
",",
"436",
",",
"444",
",",
"450",
",",
"452",
",",
"458",
",",
"460",
"]",
"for",
"i",
",",
"line",
"in",
... | Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0)::: | [
"Parse",
"Wyckoff",
".",
"csv"
] | e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6 | https://github.com/atztogo/spglib/blob/e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6/database/make_Wyckoff_db.py#L179-L251 | train |
atztogo/spglib | database/make_Wyckoff_db.py | get_site_symmetries | def get_site_symmetries(wyckoff):
"""List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6.
"""
ssyms = []
for w in wyckoff:
ssyms += ["\"%-6s\"" % w_s['site_symmetry'] for w_s in w... | python | def get_site_symmetries(wyckoff):
"""List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6.
"""
ssyms = []
for w in wyckoff:
ssyms += ["\"%-6s\"" % w_s['site_symmetry'] for w_s in w... | [
"def",
"get_site_symmetries",
"(",
"wyckoff",
")",
":",
"ssyms",
"=",
"[",
"]",
"for",
"w",
"in",
"wyckoff",
":",
"ssyms",
"+=",
"[",
"\"\\\"%-6s\\\"\"",
"%",
"w_s",
"[",
"'site_symmetry'",
"]",
"for",
"w_s",
"in",
"w",
"[",
"'wyckoff'",
"]",
"]",
"dam... | List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6. | [
"List",
"up",
"site",
"symmetries"
] | e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6 | https://github.com/atztogo/spglib/blob/e10a8f24e6e3bc1adfd8c511073442c0e7fc67b6/database/make_Wyckoff_db.py#L280-L297 | train |
tortoise/tortoise-orm | tortoise/contrib/pylint/__init__.py | transform_model | def transform_model(cls) -> None:
"""
Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class.
"""
if cls.name != "Model":
appname = "models"
for mcls in cls.get_children():
if isinstance(mcls, ClassDe... | python | def transform_model(cls) -> None:
"""
Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class.
"""
if cls.name != "Model":
appname = "models"
for mcls in cls.get_children():
if isinstance(mcls, ClassDe... | [
"def",
"transform_model",
"(",
"cls",
")",
"->",
"None",
":",
"if",
"cls",
".",
"name",
"!=",
"\"Model\"",
":",
"appname",
"=",
"\"models\"",
"for",
"mcls",
"in",
"cls",
".",
"get_children",
"(",
")",
":",
"if",
"isinstance",
"(",
"mcls",
",",
"ClassDe... | Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class. | [
"Anything",
"that",
"uses",
"the",
"ModelMeta",
"needs",
"_meta",
"and",
"id",
".",
"Also",
"keep",
"track",
"of",
"relationships",
"and",
"make",
"them",
"in",
"the",
"related",
"model",
"class",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/contrib/pylint/__init__.py#L32-L95 | train |
tortoise/tortoise-orm | tortoise/contrib/pylint/__init__.py | apply_type_shim | def apply_type_shim(cls, _context=None) -> Iterator:
"""
Morphs model fields to representative type
"""
if cls.name in ["IntField", "SmallIntField"]:
base_nodes = scoped_nodes.builtin_lookup("int")
elif cls.name in ["CharField", "TextField"]:
base_nodes = scoped_nodes.builtin_lookup(... | python | def apply_type_shim(cls, _context=None) -> Iterator:
"""
Morphs model fields to representative type
"""
if cls.name in ["IntField", "SmallIntField"]:
base_nodes = scoped_nodes.builtin_lookup("int")
elif cls.name in ["CharField", "TextField"]:
base_nodes = scoped_nodes.builtin_lookup(... | [
"def",
"apply_type_shim",
"(",
"cls",
",",
"_context",
"=",
"None",
")",
"->",
"Iterator",
":",
"if",
"cls",
".",
"name",
"in",
"[",
"\"IntField\"",
",",
"\"SmallIntField\"",
"]",
":",
"base_nodes",
"=",
"scoped_nodes",
".",
"builtin_lookup",
"(",
"\"int\"",... | Morphs model fields to representative type | [
"Morphs",
"model",
"fields",
"to",
"representative",
"type"
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/contrib/pylint/__init__.py#L105-L132 | train |
tortoise/tortoise-orm | tortoise/filters.py | list_encoder | def list_encoder(values, instance, field: Field):
"""Encodes an iterable of a given field into a database-compatible format."""
return [field.to_db_value(element, instance) for element in values] | python | def list_encoder(values, instance, field: Field):
"""Encodes an iterable of a given field into a database-compatible format."""
return [field.to_db_value(element, instance) for element in values] | [
"def",
"list_encoder",
"(",
"values",
",",
"instance",
",",
"field",
":",
"Field",
")",
":",
"return",
"[",
"field",
".",
"to_db_value",
"(",
"element",
",",
"instance",
")",
"for",
"element",
"in",
"values",
"]"
] | Encodes an iterable of a given field into a database-compatible format. | [
"Encodes",
"an",
"iterable",
"of",
"a",
"given",
"field",
"into",
"a",
"database",
"-",
"compatible",
"format",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/filters.py#L11-L13 | train |
tortoise/tortoise-orm | tortoise/fields.py | ManyToManyRelationManager.add | async def add(self, *instances, using_db=None) -> None:
"""
Adds one or more of ``instances`` to the relation.
If it is already added, it will be silently ignored.
"""
if not instances:
return
if self.instance.id is None:
raise OperationalError(
... | python | async def add(self, *instances, using_db=None) -> None:
"""
Adds one or more of ``instances`` to the relation.
If it is already added, it will be silently ignored.
"""
if not instances:
return
if self.instance.id is None:
raise OperationalError(
... | [
"async",
"def",
"add",
"(",
"self",
",",
"*",
"instances",
",",
"using_db",
"=",
"None",
")",
"->",
"None",
":",
"if",
"not",
"instances",
":",
"return",
"if",
"self",
".",
"instance",
".",
"id",
"is",
"None",
":",
"raise",
"OperationalError",
"(",
"... | Adds one or more of ``instances`` to the relation.
If it is already added, it will be silently ignored. | [
"Adds",
"one",
"or",
"more",
"of",
"instances",
"to",
"the",
"relation",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/fields.py#L539-L589 | train |
tortoise/tortoise-orm | tortoise/fields.py | ManyToManyRelationManager.clear | async def clear(self, using_db=None) -> None:
"""
Clears ALL relations.
"""
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, sel... | python | async def clear(self, using_db=None) -> None:
"""
Clears ALL relations.
"""
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, sel... | [
"async",
"def",
"clear",
"(",
"self",
",",
"using_db",
"=",
"None",
")",
"->",
"None",
":",
"db",
"=",
"using_db",
"if",
"using_db",
"else",
"self",
".",
"model",
".",
"_meta",
".",
"db",
"through_table",
"=",
"Table",
"(",
"self",
".",
"field",
".",... | Clears ALL relations. | [
"Clears",
"ALL",
"relations",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/fields.py#L591-L602 | train |
tortoise/tortoise-orm | tortoise/fields.py | ManyToManyRelationManager.remove | async def remove(self, *instances, using_db=None) -> None:
"""
Removes one or more of ``instances`` from the relation.
"""
db = using_db if using_db else self.model._meta.db
if not instances:
raise OperationalError("remove() called on no instances")
through_ta... | python | async def remove(self, *instances, using_db=None) -> None:
"""
Removes one or more of ``instances`` from the relation.
"""
db = using_db if using_db else self.model._meta.db
if not instances:
raise OperationalError("remove() called on no instances")
through_ta... | [
"async",
"def",
"remove",
"(",
"self",
",",
"*",
"instances",
",",
"using_db",
"=",
"None",
")",
"->",
"None",
":",
"db",
"=",
"using_db",
"if",
"using_db",
"else",
"self",
".",
"model",
".",
"_meta",
".",
"db",
"if",
"not",
"instances",
":",
"raise"... | Removes one or more of ``instances`` from the relation. | [
"Removes",
"one",
"or",
"more",
"of",
"instances",
"from",
"the",
"relation",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/fields.py#L604-L622 | train |
tortoise/tortoise-orm | tortoise/contrib/quart/__init__.py | register_tortoise | def register_tortoise(
app: Quart,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
generate_schemas: bool = False,
) -> None:
"""
Registers ``before_serving`` and ``after_serving`` hooks to se... | python | def register_tortoise(
app: Quart,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
generate_schemas: bool = False,
) -> None:
"""
Registers ``before_serving`` and ``after_serving`` hooks to se... | [
"def",
"register_tortoise",
"(",
"app",
":",
"Quart",
",",
"config",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"config_file",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"db_url",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",... | Registers ``before_serving`` and ``after_serving`` hooks to set-up and tear-down Tortoise-ORM
inside a Quart service.
It also registers a CLI command ``generate_schemas`` that will generate the schemas.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Para... | [
"Registers",
"before_serving",
"and",
"after_serving",
"hooks",
"to",
"set",
"-",
"up",
"and",
"tear",
"-",
"down",
"Tortoise",
"-",
"ORM",
"inside",
"a",
"Quart",
"service",
".",
"It",
"also",
"registers",
"a",
"CLI",
"command",
"generate_schemas",
"that",
... | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/contrib/quart/__init__.py#L13-L105 | train |
tortoise/tortoise-orm | tortoise/__init__.py | run_async | def run_async(coro: Coroutine) -> None:
"""
Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3'... | python | def run_async(coro: Coroutine) -> None:
"""
Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3'... | [
"def",
"run_async",
"(",
"coro",
":",
"Coroutine",
")",
"->",
"None",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"try",
":",
"loop",
".",
"run_until_complete",
"(",
"coro",
")",
"finally",
":",
"loop",
".",
"run_until_complete",
"(",
"... | Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3',
models={'models': ['app.models']}
... | [
"Simple",
"async",
"runner",
"that",
"cleans",
"up",
"DB",
"connections",
"on",
"exit",
".",
"This",
"is",
"meant",
"for",
"simple",
"scripts",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/__init__.py#L381-L404 | train |
tortoise/tortoise-orm | tortoise/__init__.py | Tortoise.init | async def init(
cls,
config: Optional[dict] = None,
config_file: Optional[str] = None,
_create_db: bool = False,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
) -> None:
"""
Sets up Tortoise-ORM.
You can configu... | python | async def init(
cls,
config: Optional[dict] = None,
config_file: Optional[str] = None,
_create_db: bool = False,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
) -> None:
"""
Sets up Tortoise-ORM.
You can configu... | [
"async",
"def",
"init",
"(",
"cls",
",",
"config",
":",
"Optional",
"[",
"dict",
"]",
"=",
"None",
",",
"config_file",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"_create_db",
":",
"bool",
"=",
"False",
",",
"db_url",
":",
"Optional",
"[",
... | Sets up Tortoise-ORM.
You can configure using only one of ``config``, ``config_file``
and ``(db_url, modules)``.
Parameters
----------
config:
Dict containing config:
Example
-------
.. code-block:: python3
{
... | [
"Sets",
"up",
"Tortoise",
"-",
"ORM",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/__init__.py#L231-L332 | train |
tortoise/tortoise-orm | tortoise/transactions.py | in_transaction | def in_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of c... | python | def in_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of c... | [
"def",
"in_transaction",
"(",
"connection_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"BaseTransactionWrapper",
":",
"connection",
"=",
"_get_connection",
"(",
"connection_name",
")",
"return",
"connection",
".",
"_in_transaction",
"(",
")"
] | Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection | [
"Transaction",
"context",
"manager",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/transactions.py#L25-L36 | train |
tortoise/tortoise-orm | tortoise/transactions.py | atomic | def atomic(connection_name: Optional[str] = None) -> Callable:
"""
Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
... | python | def atomic(connection_name: Optional[str] = None) -> Callable:
"""
Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
... | [
"def",
"atomic",
"(",
"connection_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Callable",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"async",
"def",
"wrapped",
"(",
"*",
"args",
",",
"**",
"kw... | Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
one db connection | [
"Transaction",
"decorator",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/transactions.py#L39-L59 | train |
tortoise/tortoise-orm | tortoise/transactions.py | start_transaction | async def start_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending ... | python | async def start_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending ... | [
"async",
"def",
"start_transaction",
"(",
"connection_name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"BaseTransactionWrapper",
":",
"connection",
"=",
"_get_connection",
"(",
"connection_name",
")",
"transaction",
"=",
"connection",
".",
"_in_tra... | Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending transaction with above methods.
:param connection_name: name of connection to run with, optional if y... | [
"Function",
"to",
"manually",
"control",
"your",
"transaction",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/transactions.py#L62-L76 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.limit | def limit(self, limit: int) -> "QuerySet":
"""
Limits QuerySet to given length.
"""
queryset = self._clone()
queryset._limit = limit
return queryset | python | def limit(self, limit: int) -> "QuerySet":
"""
Limits QuerySet to given length.
"""
queryset = self._clone()
queryset._limit = limit
return queryset | [
"def",
"limit",
"(",
"self",
",",
"limit",
":",
"int",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"queryset",
".",
"_limit",
"=",
"limit",
"return",
"queryset"
] | Limits QuerySet to given length. | [
"Limits",
"QuerySet",
"to",
"given",
"length",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L218-L224 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.offset | def offset(self, offset: int) -> "QuerySet":
"""
Query offset for QuerySet.
"""
queryset = self._clone()
queryset._offset = offset
if self.capabilities.requires_limit and queryset._limit is None:
queryset._limit = 1000000
return queryset | python | def offset(self, offset: int) -> "QuerySet":
"""
Query offset for QuerySet.
"""
queryset = self._clone()
queryset._offset = offset
if self.capabilities.requires_limit and queryset._limit is None:
queryset._limit = 1000000
return queryset | [
"def",
"offset",
"(",
"self",
",",
"offset",
":",
"int",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"queryset",
".",
"_offset",
"=",
"offset",
"if",
"self",
".",
"capabilities",
".",
"requires_limit",
"and",
"querys... | Query offset for QuerySet. | [
"Query",
"offset",
"for",
"QuerySet",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L226-L234 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.annotate | def annotate(self, **kwargs) -> "QuerySet":
"""
Annotate result with aggregation result.
"""
queryset = self._clone()
for key, aggregation in kwargs.items():
if not isinstance(aggregation, Aggregate):
raise TypeError("value is expected to be Aggregate ... | python | def annotate(self, **kwargs) -> "QuerySet":
"""
Annotate result with aggregation result.
"""
queryset = self._clone()
for key, aggregation in kwargs.items():
if not isinstance(aggregation, Aggregate):
raise TypeError("value is expected to be Aggregate ... | [
"def",
"annotate",
"(",
"self",
",",
"**",
"kwargs",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"for",
"key",
",",
"aggregation",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"agg... | Annotate result with aggregation result. | [
"Annotate",
"result",
"with",
"aggregation",
"result",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L244-L256 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.values_list | def values_list(
self, *fields_: str, flat: bool = False
) -> "ValuesListQuery": # pylint: disable=W0621
"""
Make QuerySet returns list of tuples for given args instead of objects.
If ```flat=True`` and only one arg is passed can return flat list.
"""
return ValuesLi... | python | def values_list(
self, *fields_: str, flat: bool = False
) -> "ValuesListQuery": # pylint: disable=W0621
"""
Make QuerySet returns list of tuples for given args instead of objects.
If ```flat=True`` and only one arg is passed can return flat list.
"""
return ValuesLi... | [
"def",
"values_list",
"(",
"self",
",",
"*",
"fields_",
":",
"str",
",",
"flat",
":",
"bool",
"=",
"False",
")",
"->",
"\"ValuesListQuery\"",
":",
"return",
"ValuesListQuery",
"(",
"db",
"=",
"self",
".",
"_db",
",",
"model",
"=",
"self",
".",
"model",... | Make QuerySet returns list of tuples for given args instead of objects.
If ```flat=True`` and only one arg is passed can return flat list. | [
"Make",
"QuerySet",
"returns",
"list",
"of",
"tuples",
"for",
"given",
"args",
"instead",
"of",
"objects",
".",
"If",
"flat",
"=",
"True",
"and",
"only",
"one",
"arg",
"is",
"passed",
"can",
"return",
"flat",
"list",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L258-L277 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.values | def values(self, *args: str, **kwargs: str) -> "ValuesQuery":
"""
Make QuerySet return dicts instead of objects.
"""
fields_for_select = {} # type: Dict[str, str]
for field in args:
if field in fields_for_select:
raise FieldError("Duplicate key {}".fo... | python | def values(self, *args: str, **kwargs: str) -> "ValuesQuery":
"""
Make QuerySet return dicts instead of objects.
"""
fields_for_select = {} # type: Dict[str, str]
for field in args:
if field in fields_for_select:
raise FieldError("Duplicate key {}".fo... | [
"def",
"values",
"(",
"self",
",",
"*",
"args",
":",
"str",
",",
"**",
"kwargs",
":",
"str",
")",
"->",
"\"ValuesQuery\"",
":",
"fields_for_select",
"=",
"{",
"}",
"for",
"field",
"in",
"args",
":",
"if",
"field",
"in",
"fields_for_select",
":",
"raise... | Make QuerySet return dicts instead of objects. | [
"Make",
"QuerySet",
"return",
"dicts",
"instead",
"of",
"objects",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L279-L305 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.delete | def delete(self) -> "DeleteQuery":
"""
Delete all objects in QuerySet.
"""
return DeleteQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._custom_filters,
... | python | def delete(self) -> "DeleteQuery":
"""
Delete all objects in QuerySet.
"""
return DeleteQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._custom_filters,
... | [
"def",
"delete",
"(",
"self",
")",
"->",
"\"DeleteQuery\"",
":",
"return",
"DeleteQuery",
"(",
"db",
"=",
"self",
".",
"_db",
",",
"model",
"=",
"self",
".",
"model",
",",
"q_objects",
"=",
"self",
".",
"_q_objects",
",",
"annotations",
"=",
"self",
".... | Delete all objects in QuerySet. | [
"Delete",
"all",
"objects",
"in",
"QuerySet",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L307-L317 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.update | def update(self, **kwargs) -> "UpdateQuery":
"""
Update all objects in QuerySet with given kwargs.
"""
return UpdateQuery(
db=self._db,
model=self.model,
update_kwargs=kwargs,
q_objects=self._q_objects,
annotations=self._annotat... | python | def update(self, **kwargs) -> "UpdateQuery":
"""
Update all objects in QuerySet with given kwargs.
"""
return UpdateQuery(
db=self._db,
model=self.model,
update_kwargs=kwargs,
q_objects=self._q_objects,
annotations=self._annotat... | [
"def",
"update",
"(",
"self",
",",
"**",
"kwargs",
")",
"->",
"\"UpdateQuery\"",
":",
"return",
"UpdateQuery",
"(",
"db",
"=",
"self",
".",
"_db",
",",
"model",
"=",
"self",
".",
"model",
",",
"update_kwargs",
"=",
"kwargs",
",",
"q_objects",
"=",
"sel... | Update all objects in QuerySet with given kwargs. | [
"Update",
"all",
"objects",
"in",
"QuerySet",
"with",
"given",
"kwargs",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L319-L330 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.count | def count(self) -> "CountQuery":
"""
Return count of objects in queryset instead of objects.
"""
return CountQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._cu... | python | def count(self) -> "CountQuery":
"""
Return count of objects in queryset instead of objects.
"""
return CountQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._cu... | [
"def",
"count",
"(",
"self",
")",
"->",
"\"CountQuery\"",
":",
"return",
"CountQuery",
"(",
"db",
"=",
"self",
".",
"_db",
",",
"model",
"=",
"self",
".",
"model",
",",
"q_objects",
"=",
"self",
".",
"_q_objects",
",",
"annotations",
"=",
"self",
".",
... | Return count of objects in queryset instead of objects. | [
"Return",
"count",
"of",
"objects",
"in",
"queryset",
"instead",
"of",
"objects",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L332-L342 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.first | def first(self) -> "QuerySet":
"""
Limit queryset to one object and return one object instead of list.
"""
queryset = self._clone()
queryset._limit = 1
queryset._single = True
return queryset | python | def first(self) -> "QuerySet":
"""
Limit queryset to one object and return one object instead of list.
"""
queryset = self._clone()
queryset._limit = 1
queryset._single = True
return queryset | [
"def",
"first",
"(",
"self",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"queryset",
".",
"_limit",
"=",
"1",
"queryset",
".",
"_single",
"=",
"True",
"return",
"queryset"
] | Limit queryset to one object and return one object instead of list. | [
"Limit",
"queryset",
"to",
"one",
"object",
"and",
"return",
"one",
"object",
"instead",
"of",
"list",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L351-L358 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.get | def get(self, *args, **kwargs) -> "QuerySet":
"""
Fetch exactly one object matching the parameters.
"""
queryset = self.filter(*args, **kwargs)
queryset._limit = 2
queryset._get = True
return queryset | python | def get(self, *args, **kwargs) -> "QuerySet":
"""
Fetch exactly one object matching the parameters.
"""
queryset = self.filter(*args, **kwargs)
queryset._limit = 2
queryset._get = True
return queryset | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"filter",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"queryset",
".",
"_limit",
"=",
"2",
"queryset",
".",
"_get",
"=",... | Fetch exactly one object matching the parameters. | [
"Fetch",
"exactly",
"one",
"object",
"matching",
"the",
"parameters",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L360-L367 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.explain | async def explain(self) -> Any:
"""Fetch and return information about the query execution plan.
This is done by executing an ``EXPLAIN`` query whose exact prefix depends
on the database backend, as documented below.
- PostgreSQL: ``EXPLAIN (FORMAT JSON, VERBOSE) ...``
- SQLite:... | python | async def explain(self) -> Any:
"""Fetch and return information about the query execution plan.
This is done by executing an ``EXPLAIN`` query whose exact prefix depends
on the database backend, as documented below.
- PostgreSQL: ``EXPLAIN (FORMAT JSON, VERBOSE) ...``
- SQLite:... | [
"async",
"def",
"explain",
"(",
"self",
")",
"->",
"Any",
":",
"if",
"self",
".",
"_db",
"is",
"None",
":",
"self",
".",
"_db",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"db",
"return",
"await",
"self",
".",
"_db",
".",
"executor_class",
"(",
... | Fetch and return information about the query execution plan.
This is done by executing an ``EXPLAIN`` query whose exact prefix depends
on the database backend, as documented below.
- PostgreSQL: ``EXPLAIN (FORMAT JSON, VERBOSE) ...``
- SQLite: ``EXPLAIN QUERY PLAN ...``
- MySQL... | [
"Fetch",
"and",
"return",
"information",
"about",
"the",
"query",
"execution",
"plan",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L393-L413 | train |
tortoise/tortoise-orm | tortoise/queryset.py | QuerySet.using_db | def using_db(self, _db: BaseDBAsyncClient) -> "QuerySet":
"""
Executes query in provided db client.
Useful for transactions workaround.
"""
queryset = self._clone()
queryset._db = _db
return queryset | python | def using_db(self, _db: BaseDBAsyncClient) -> "QuerySet":
"""
Executes query in provided db client.
Useful for transactions workaround.
"""
queryset = self._clone()
queryset._db = _db
return queryset | [
"def",
"using_db",
"(",
"self",
",",
"_db",
":",
"BaseDBAsyncClient",
")",
"->",
"\"QuerySet\"",
":",
"queryset",
"=",
"self",
".",
"_clone",
"(",
")",
"queryset",
".",
"_db",
"=",
"_db",
"return",
"queryset"
] | Executes query in provided db client.
Useful for transactions workaround. | [
"Executes",
"query",
"in",
"provided",
"db",
"client",
".",
"Useful",
"for",
"transactions",
"workaround",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L415-L422 | train |
tortoise/tortoise-orm | tortoise/models.py | Model._check_unique_together | def _check_unique_together(cls):
"""Check the value of "unique_together" option."""
if cls._meta.unique_together is None:
return
if not isinstance(cls._meta.unique_together, (tuple, list)):
raise ConfigurationError(
"'{}.unique_together' must be a list or... | python | def _check_unique_together(cls):
"""Check the value of "unique_together" option."""
if cls._meta.unique_together is None:
return
if not isinstance(cls._meta.unique_together, (tuple, list)):
raise ConfigurationError(
"'{}.unique_together' must be a list or... | [
"def",
"_check_unique_together",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_meta",
".",
"unique_together",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"cls",
".",
"_meta",
".",
"unique_together",
",",
"(",
"tuple",
",",
"list",
")",
")",
... | Check the value of "unique_together" option. | [
"Check",
"the",
"value",
"of",
"unique_together",
"option",
"."
] | 7d16457731905e19d4d06ccd5b4ea16d4a9447b2 | https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/models.py#L324-L357 | train |
aerkalov/ebooklib | ebooklib/epub.py | write_epub | def write_epub(name, book, options=None):
"""
Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional)
"""
epub... | python | def write_epub(name, book, options=None):
"""
Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional)
"""
epub... | [
"def",
"write_epub",
"(",
"name",
",",
"book",
",",
"options",
"=",
"None",
")",
":",
"epub",
"=",
"EpubWriter",
"(",
"name",
",",
"book",
",",
"options",
")",
"epub",
".",
"process",
"(",
")",
"try",
":",
"epub",
".",
"write",
"(",
")",
"except",
... | Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional) | [
"Creates",
"epub",
"file",
"with",
"the",
"content",
"defined",
"in",
"EpubBook",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L1705-L1723 | train |
aerkalov/ebooklib | ebooklib/epub.py | read_epub | def read_epub(name, options=None):
"""
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubB... | python | def read_epub(name, options=None):
"""
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubB... | [
"def",
"read_epub",
"(",
"name",
",",
"options",
"=",
"None",
")",
":",
"reader",
"=",
"EpubReader",
"(",
"name",
",",
"options",
")",
"book",
"=",
"reader",
".",
"load",
"(",
")",
"reader",
".",
"process",
"(",
")",
"return",
"book"
] | Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubBook. | [
"Creates",
"new",
"instance",
"of",
"EpubBook",
"with",
"the",
"content",
"defined",
"in",
"the",
"input",
"file",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L1728-L1746 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubItem.get_type | def get_type(self):
"""
Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
... | python | def get_type(self):
"""
Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
... | [
"def",
"get_type",
"(",
"self",
")",
":",
"_",
",",
"ext",
"=",
"zip_path",
".",
"splitext",
"(",
"self",
".",
"get_name",
"(",
")",
")",
"ext",
"=",
"ext",
".",
"lower",
"(",
")",
"for",
"uid",
",",
"ext_list",
"in",
"six",
".",
"iteritems",
"("... | Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
- ITEM_VECTOR = 5
- ... | [
"Guess",
"type",
"according",
"to",
"the",
"file",
"extension",
".",
"Might",
"not",
"be",
"the",
"best",
"way",
"how",
"to",
"do",
"it",
"but",
"it",
"works",
"for",
"now",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L158-L187 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.add_link | def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
i... | python | def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
i... | [
"def",
"add_link",
"(",
"self",
",",
"**",
"kwgs",
")",
":",
"self",
".",
"links",
".",
"append",
"(",
"kwgs",
")",
"if",
"kwgs",
".",
"get",
"(",
"'type'",
")",
"==",
"'text/javascript'",
":",
"if",
"'scripted'",
"not",
"in",
"self",
".",
"propertie... | Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css') | [
"Add",
"additional",
"link",
"to",
"the",
"document",
".",
"Links",
"will",
"be",
"embeded",
"only",
"inside",
"of",
"this",
"document",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L299-L308 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.get_links_of_type | def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type) | python | def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type) | [
"def",
"get_links_of_type",
"(",
"self",
",",
"link_type",
")",
":",
"return",
"(",
"link",
"for",
"link",
"in",
"self",
".",
"links",
"if",
"link",
".",
"get",
"(",
"'type'",
",",
"''",
")",
"==",
"link_type",
")"
] | Returns list of additional links of specific type.
:Returns:
As tuple returns list of links. | [
"Returns",
"list",
"of",
"additional",
"links",
"of",
"specific",
"type",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L319-L326 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubHtml.add_item | def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=i... | python | def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=i... | [
"def",
"add_item",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
".",
"get_type",
"(",
")",
"==",
"ebooklib",
".",
"ITEM_STYLE",
":",
"self",
".",
"add_link",
"(",
"href",
"=",
"item",
".",
"get_name",
"(",
")",
",",
"rel",
"=",
"'stylesheet'",
... | Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem | [
"Add",
"other",
"item",
"to",
"this",
"document",
".",
"It",
"will",
"create",
"additional",
"links",
"according",
"to",
"the",
"item",
"type",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L328-L339 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.reset | def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
... | python | def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
... | [
"def",
"reset",
"(",
"self",
")",
":",
"\"Initialises all needed variables to default values\"",
"self",
".",
"metadata",
"=",
"{",
"}",
"self",
".",
"items",
"=",
"[",
"]",
"self",
".",
"spine",
"=",
"[",
"]",
"self",
".",
"guide",
"=",
"[",
"]",
"self"... | Initialises all needed variables to default values | [
"Initialises",
"all",
"needed",
"variables",
"to",
"default",
"values"
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L554-L592 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.set_identifier | def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) | python | def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) | [
"def",
"set_identifier",
"(",
"self",
",",
"uid",
")",
":",
"self",
".",
"uid",
"=",
"uid",
"self",
".",
"set_unique_metadata",
"(",
"'DC'",
",",
"'identifier'",
",",
"self",
".",
"uid",
",",
"{",
"'id'",
":",
"self",
".",
"IDENTIFIER_ID",
"}",
")"
] | Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book | [
"Sets",
"unique",
"id",
"for",
"this",
"epub"
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L594-L604 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.set_title | def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title) | python | def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title) | [
"def",
"set_title",
"(",
"self",
",",
"title",
")",
":",
"self",
".",
"title",
"=",
"title",
"self",
".",
"add_metadata",
"(",
"'DC'",
",",
"'title'",
",",
"self",
".",
"title",
")"
] | Set title. You can set multiple titles.
:Args:
- title: Title value | [
"Set",
"title",
".",
"You",
"can",
"set",
"multiple",
"titles",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L606-L616 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.set_cover | def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (... | python | def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (... | [
"def",
"set_cover",
"(",
"self",
",",
"file_name",
",",
"content",
",",
"create_page",
"=",
"True",
")",
":",
"c0",
"=",
"EpubCover",
"(",
"file_name",
"=",
"file_name",
")",
"c0",
".",
"content",
"=",
"content",
"self",
".",
"add_item",
"(",
"c0",
")"... | Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (optional). Default value is True. | [
"Set",
"cover",
"and",
"create",
"cover",
"document",
"if",
"needed",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L639-L658 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.add_author | def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
... | python | def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
... | [
"def",
"add_author",
"(",
"self",
",",
"author",
",",
"file_as",
"=",
"None",
",",
"role",
"=",
"None",
",",
"uid",
"=",
"'creator'",
")",
":",
"\"Add author for this document\"",
"self",
".",
"add_metadata",
"(",
"'DC'",
",",
"'creator'",
",",
"author",
"... | Add author for this document | [
"Add",
"author",
"for",
"this",
"document"
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L660-L672 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.add_item | def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().... | python | def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().... | [
"def",
"add_item",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
".",
"media_type",
"==",
"''",
":",
"(",
"has_guessed",
",",
"media_type",
")",
"=",
"guess_type",
"(",
"item",
".",
"get_name",
"(",
")",
".",
"lower",
"(",
")",
")",
"if",
"has_... | Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance | [
"Add",
"additional",
"item",
"to",
"the",
"book",
".",
"If",
"not",
"defined",
"media",
"type",
"and",
"chapter",
"id",
"will",
"be",
"defined",
"for",
"the",
"item",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L707-L743 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_item_with_id | def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
... | python | def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
... | [
"def",
"get_item_with_id",
"(",
"self",
",",
"uid",
")",
":",
"for",
"item",
"in",
"self",
".",
"get_items",
"(",
")",
":",
"if",
"item",
".",
"id",
"==",
"uid",
":",
"return",
"item",
"return",
"None"
] | Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found. | [
"Returns",
"item",
"for",
"defined",
"UID",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L745-L761 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_item_with_href | def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
... | python | def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
... | [
"def",
"get_item_with_href",
"(",
"self",
",",
"href",
")",
":",
"for",
"item",
"in",
"self",
".",
"get_items",
"(",
")",
":",
"if",
"item",
".",
"get_name",
"(",
")",
"==",
"href",
":",
"return",
"item",
"return",
"None"
] | Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found. | [
"Returns",
"item",
"for",
"defined",
"HREF",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L763-L779 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_items_of_type | def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for... | python | def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for... | [
"def",
"get_items_of_type",
"(",
"self",
",",
"item_type",
")",
":",
"return",
"(",
"item",
"for",
"item",
"in",
"self",
".",
"items",
"if",
"item",
".",
"get_type",
"(",
")",
"==",
"item_type",
")"
] | Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple. | [
"Returns",
"all",
"items",
"of",
"specified",
"type",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L790-L802 | train |
aerkalov/ebooklib | ebooklib/epub.py | EpubBook.get_items_of_media_type | def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media... | python | def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media... | [
"def",
"get_items_of_media_type",
"(",
"self",
",",
"media_type",
")",
":",
"return",
"(",
"item",
"for",
"item",
"in",
"self",
".",
"items",
"if",
"item",
".",
"media_type",
"==",
"media_type",
")"
] | Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple. | [
"Returns",
"all",
"items",
"of",
"specified",
"media",
"type",
"."
] | 305f2dd7f02923ffabf9586a5d16266113d00c4a | https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L804-L814 | train |
LuminosoInsight/python-ftfy | ftfy/cli.py | main | def main():
"""
Run ftfy as a command-line utility.
"""
import argparse
parser = argparse.ArgumentParser(
description="ftfy (fixes text for you), version %s" % __version__
)
parser.add_argument('filename', default='-', nargs='?',
help='The file whose Unicode ... | python | def main():
"""
Run ftfy as a command-line utility.
"""
import argparse
parser = argparse.ArgumentParser(
description="ftfy (fixes text for you), version %s" % __version__
)
parser.add_argument('filename', default='-', nargs='?',
help='The file whose Unicode ... | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"ftfy (fixes text for you), version %s\"",
"%",
"__version__",
")",
"parser",
".",
"add_argument",
"(",
"'filename'",
",",
"default",
"... | Run ftfy as a command-line utility. | [
"Run",
"ftfy",
"as",
"a",
"command",
"-",
"line",
"utility",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/cli.py#L42-L114 | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | fix_encoding_and_explain | def fix_encoding_and_explain(text):
"""
Re-decodes text that has been decoded incorrectly, and also return a
"plan" indicating all the steps required to fix it.
The resulting plan could be used with :func:`ftfy.fixes.apply_plan`
to fix additional strings that are broken in the same way.
"""
... | python | def fix_encoding_and_explain(text):
"""
Re-decodes text that has been decoded incorrectly, and also return a
"plan" indicating all the steps required to fix it.
The resulting plan could be used with :func:`ftfy.fixes.apply_plan`
to fix additional strings that are broken in the same way.
"""
... | [
"def",
"fix_encoding_and_explain",
"(",
"text",
")",
":",
"best_version",
"=",
"text",
"best_cost",
"=",
"text_cost",
"(",
"text",
")",
"best_plan",
"=",
"[",
"]",
"plan_so_far",
"=",
"[",
"]",
"while",
"True",
":",
"prevtext",
"=",
"text",
"text",
",",
... | Re-decodes text that has been decoded incorrectly, and also return a
"plan" indicating all the steps required to fix it.
The resulting plan could be used with :func:`ftfy.fixes.apply_plan`
to fix additional strings that are broken in the same way. | [
"Re",
"-",
"decodes",
"text",
"that",
"has",
"been",
"decoded",
"incorrectly",
"and",
"also",
"return",
"a",
"plan",
"indicating",
"all",
"the",
"steps",
"required",
"to",
"fix",
"it",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L133-L158 | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | fix_one_step_and_explain | def fix_one_step_and_explain(text):
"""
Performs a single step of re-decoding text that's been decoded incorrectly.
Returns the decoded text, plus a "plan" for how to reproduce what it did.
"""
if isinstance(text, bytes):
raise UnicodeError(BYTES_ERROR_TEXT)
if len(text) == 0:
r... | python | def fix_one_step_and_explain(text):
"""
Performs a single step of re-decoding text that's been decoded incorrectly.
Returns the decoded text, plus a "plan" for how to reproduce what it did.
"""
if isinstance(text, bytes):
raise UnicodeError(BYTES_ERROR_TEXT)
if len(text) == 0:
r... | [
"def",
"fix_one_step_and_explain",
"(",
"text",
")",
":",
"if",
"isinstance",
"(",
"text",
",",
"bytes",
")",
":",
"raise",
"UnicodeError",
"(",
"BYTES_ERROR_TEXT",
")",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"return",
"text",
",",
"[",
"]",
"i... | Performs a single step of re-decoding text that's been decoded incorrectly.
Returns the decoded text, plus a "plan" for how to reproduce what it did. | [
"Performs",
"a",
"single",
"step",
"of",
"re",
"-",
"decoding",
"text",
"that",
"s",
"been",
"decoded",
"incorrectly",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L161-L259 | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | apply_plan | def apply_plan(text, plan):
"""
Apply a plan for fixing the encoding of text.
The plan is a list of tuples of the form (operation, encoding, cost):
- `operation` is 'encode' if it turns a string into bytes, 'decode' if it
turns bytes into a string, and 'transcode' if it keeps the type the same.
... | python | def apply_plan(text, plan):
"""
Apply a plan for fixing the encoding of text.
The plan is a list of tuples of the form (operation, encoding, cost):
- `operation` is 'encode' if it turns a string into bytes, 'decode' if it
turns bytes into a string, and 'transcode' if it keeps the type the same.
... | [
"def",
"apply_plan",
"(",
"text",
",",
"plan",
")",
":",
"obj",
"=",
"text",
"for",
"operation",
",",
"encoding",
",",
"_",
"in",
"plan",
":",
"if",
"operation",
"==",
"'encode'",
":",
"obj",
"=",
"obj",
".",
"encode",
"(",
"encoding",
")",
"elif",
... | Apply a plan for fixing the encoding of text.
The plan is a list of tuples of the form (operation, encoding, cost):
- `operation` is 'encode' if it turns a string into bytes, 'decode' if it
turns bytes into a string, and 'transcode' if it keeps the type the same.
- `encoding` is the name of the enco... | [
"Apply",
"a",
"plan",
"for",
"fixing",
"the",
"encoding",
"of",
"text",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L262-L290 | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | _unescape_fixup | def _unescape_fixup(match):
"""
Replace one matched HTML entity with the character it represents,
if possible.
"""
text = match.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
codept = int(text[3:-1], 16)
else... | python | def _unescape_fixup(match):
"""
Replace one matched HTML entity with the character it represents,
if possible.
"""
text = match.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
codept = int(text[3:-1], 16)
else... | [
"def",
"_unescape_fixup",
"(",
"match",
")",
":",
"text",
"=",
"match",
".",
"group",
"(",
"0",
")",
"if",
"text",
"[",
":",
"2",
"]",
"==",
"\"&#\"",
":",
"try",
":",
"if",
"text",
"[",
":",
"3",
"]",
"==",
"\"&#x\"",
":",
"codept",
"=",
"int"... | Replace one matched HTML entity with the character it represents,
if possible. | [
"Replace",
"one",
"matched",
"HTML",
"entity",
"with",
"the",
"character",
"it",
"represents",
"if",
"possible",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L296-L323 | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | convert_surrogate_pair | def convert_surrogate_pair(match):
"""
Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
"""
pair = match.group(0)
codept = 0x10000 + (ord(pair[0]) - 0xd800) * ... | python | def convert_surrogate_pair(match):
"""
Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
"""
pair = match.group(0)
codept = 0x10000 + (ord(pair[0]) - 0xd800) * ... | [
"def",
"convert_surrogate_pair",
"(",
"match",
")",
":",
"pair",
"=",
"match",
".",
"group",
"(",
"0",
")",
"codept",
"=",
"0x10000",
"+",
"(",
"ord",
"(",
"pair",
"[",
"0",
"]",
")",
"-",
"0xd800",
")",
"*",
"0x400",
"+",
"(",
"ord",
"(",
"pair"... | Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates | [
"Convert",
"a",
"surrogate",
"pair",
"to",
"the",
"single",
"codepoint",
"it",
"represents",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L457-L466 | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | restore_byte_a0 | def restore_byte_a0(byts):
"""
Some mojibake has been additionally altered by a process that said "hmm,
byte A0, that's basically a space!" and replaced it with an ASCII space.
When the A0 is part of a sequence that we intend to decode as UTF-8,
changing byte A0 to 20 would make it fail to decode.
... | python | def restore_byte_a0(byts):
"""
Some mojibake has been additionally altered by a process that said "hmm,
byte A0, that's basically a space!" and replaced it with an ASCII space.
When the A0 is part of a sequence that we intend to decode as UTF-8,
changing byte A0 to 20 would make it fail to decode.
... | [
"def",
"restore_byte_a0",
"(",
"byts",
")",
":",
"def",
"replacement",
"(",
"match",
")",
":",
"\"The function to apply when this regex matches.\"",
"return",
"match",
".",
"group",
"(",
"0",
")",
".",
"replace",
"(",
"b'\\x20'",
",",
"b'\\xa0'",
")",
"return",
... | Some mojibake has been additionally altered by a process that said "hmm,
byte A0, that's basically a space!" and replaced it with an ASCII space.
When the A0 is part of a sequence that we intend to decode as UTF-8,
changing byte A0 to 20 would make it fail to decode.
This process finds sequences that w... | [
"Some",
"mojibake",
"has",
"been",
"additionally",
"altered",
"by",
"a",
"process",
"that",
"said",
"hmm",
"byte",
"A0",
"that",
"s",
"basically",
"a",
"space!",
"and",
"replaced",
"it",
"with",
"an",
"ASCII",
"space",
".",
"When",
"the",
"A0",
"is",
"pa... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L582-L600 | train |
LuminosoInsight/python-ftfy | ftfy/fixes.py | fix_partial_utf8_punct_in_1252 | def fix_partial_utf8_punct_in_1252(text):
"""
Fix particular characters that seem to be found in the wild encoded in
UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be
consistently applied.
One form of inconsistency we need to deal with is that some character might
be fro... | python | def fix_partial_utf8_punct_in_1252(text):
"""
Fix particular characters that seem to be found in the wild encoded in
UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be
consistently applied.
One form of inconsistency we need to deal with is that some character might
be fro... | [
"def",
"fix_partial_utf8_punct_in_1252",
"(",
"text",
")",
":",
"def",
"latin1_to_w1252",
"(",
"match",
")",
":",
"\"The function to apply when this regex matches.\"",
"return",
"match",
".",
"group",
"(",
"0",
")",
".",
"encode",
"(",
"'latin-1'",
")",
".",
"deco... | Fix particular characters that seem to be found in the wild encoded in
UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be
consistently applied.
One form of inconsistency we need to deal with is that some character might
be from the Latin-1 C1 control character set, while others a... | [
"Fix",
"particular",
"characters",
"that",
"seem",
"to",
"be",
"found",
"in",
"the",
"wild",
"encoded",
"in",
"UTF",
"-",
"8",
"and",
"decoded",
"in",
"Latin",
"-",
"1",
"or",
"Windows",
"-",
"1252",
"even",
"when",
"this",
"fix",
"can",
"t",
"be",
"... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L642-L664 | train |
LuminosoInsight/python-ftfy | ftfy/formatting.py | display_ljust | def display_ljust(text, width, fillchar=' '):
"""
Return `text` left-justified in a Unicode string whose display width,
in a monospaced terminal, should be at least `width` character cells.
The rest of the string will be padded with `fillchar`, which must be
a width-1 character.
"Left" here mea... | python | def display_ljust(text, width, fillchar=' '):
"""
Return `text` left-justified in a Unicode string whose display width,
in a monospaced terminal, should be at least `width` character cells.
The rest of the string will be padded with `fillchar`, which must be
a width-1 character.
"Left" here mea... | [
"def",
"display_ljust",
"(",
"text",
",",
"width",
",",
"fillchar",
"=",
"' '",
")",
":",
"if",
"character_width",
"(",
"fillchar",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"The padding character must have display width 1\"",
")",
"text_width",
"=",
"m... | Return `text` left-justified in a Unicode string whose display width,
in a monospaced terminal, should be at least `width` character cells.
The rest of the string will be padded with `fillchar`, which must be
a width-1 character.
"Left" here means toward the beginning of the string, which may actually
... | [
"Return",
"text",
"left",
"-",
"justified",
"in",
"a",
"Unicode",
"string",
"whose",
"display",
"width",
"in",
"a",
"monospaced",
"terminal",
"should",
"be",
"at",
"least",
"width",
"character",
"cells",
".",
"The",
"rest",
"of",
"the",
"string",
"will",
"... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/formatting.py#L67-L98 | train |
LuminosoInsight/python-ftfy | ftfy/formatting.py | display_center | def display_center(text, width, fillchar=' '):
"""
Return `text` centered in a Unicode string whose display width, in a
monospaced terminal, should be at least `width` character cells. The rest
of the string will be padded with `fillchar`, which must be a width-1
character.
>>> lines = ['Table ... | python | def display_center(text, width, fillchar=' '):
"""
Return `text` centered in a Unicode string whose display width, in a
monospaced terminal, should be at least `width` character cells. The rest
of the string will be padded with `fillchar`, which must be a width-1
character.
>>> lines = ['Table ... | [
"def",
"display_center",
"(",
"text",
",",
"width",
",",
"fillchar",
"=",
"' '",
")",
":",
"if",
"character_width",
"(",
"fillchar",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"The padding character must have display width 1\"",
")",
"text_width",
"=",
"... | Return `text` centered in a Unicode string whose display width, in a
monospaced terminal, should be at least `width` character cells. The rest
of the string will be padded with `fillchar`, which must be a width-1
character.
>>> lines = ['Table flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し']
>>> for line in lines:... | [
"Return",
"text",
"centered",
"in",
"a",
"Unicode",
"string",
"whose",
"display",
"width",
"in",
"a",
"monospaced",
"terminal",
"should",
"be",
"at",
"least",
"width",
"character",
"cells",
".",
"The",
"rest",
"of",
"the",
"string",
"will",
"be",
"padded",
... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/formatting.py#L130-L154 | train |
LuminosoInsight/python-ftfy | ftfy/bad_codecs/sloppy.py | make_sloppy_codec | def make_sloppy_codec(encoding):
"""
Take a codec name, and return a 'sloppy' version of that codec that can
encode and decode the unassigned bytes in that encoding.
Single-byte encodings in the standard library are defined using some
boilerplate classes surrounding the functions that do the actual... | python | def make_sloppy_codec(encoding):
"""
Take a codec name, and return a 'sloppy' version of that codec that can
encode and decode the unassigned bytes in that encoding.
Single-byte encodings in the standard library are defined using some
boilerplate classes surrounding the functions that do the actual... | [
"def",
"make_sloppy_codec",
"(",
"encoding",
")",
":",
"all_bytes",
"=",
"bytes",
"(",
"range",
"(",
"256",
")",
")",
"sloppy_chars",
"=",
"list",
"(",
"all_bytes",
".",
"decode",
"(",
"'latin-1'",
")",
")",
"if",
"PY26",
":",
"decoded_chars",
"=",
"all_... | Take a codec name, and return a 'sloppy' version of that codec that can
encode and decode the unassigned bytes in that encoding.
Single-byte encodings in the standard library are defined using some
boilerplate classes surrounding the functions that do the actual work,
`codecs.charmap_decode` and `charm... | [
"Take",
"a",
"codec",
"name",
"and",
"return",
"a",
"sloppy",
"version",
"of",
"that",
"codec",
"that",
"can",
"encode",
"and",
"decode",
"the",
"unassigned",
"bytes",
"in",
"that",
"encoding",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/bad_codecs/sloppy.py#L79-L150 | train |
LuminosoInsight/python-ftfy | ftfy/badness.py | _make_weirdness_regex | def _make_weirdness_regex():
"""
Creates a list of regexes that match 'weird' character sequences.
The more matches there are, the weirder the text is.
"""
groups = []
# Match diacritical marks, except when they modify a non-cased letter or
# another mark.
#
# You wouldn't put a dia... | python | def _make_weirdness_regex():
"""
Creates a list of regexes that match 'weird' character sequences.
The more matches there are, the weirder the text is.
"""
groups = []
# Match diacritical marks, except when they modify a non-cased letter or
# another mark.
#
# You wouldn't put a dia... | [
"def",
"_make_weirdness_regex",
"(",
")",
":",
"groups",
"=",
"[",
"]",
"groups",
".",
"append",
"(",
"'[^CM]M'",
")",
"groups",
".",
"append",
"(",
"'[Ll][AaC]'",
")",
"groups",
".",
"append",
"(",
"'[AaC][Ll]'",
")",
"groups",
".",
"append",
"(",
"'[LA... | Creates a list of regexes that match 'weird' character sequences.
The more matches there are, the weirder the text is. | [
"Creates",
"a",
"list",
"of",
"regexes",
"that",
"match",
"weird",
"character",
"sequences",
".",
"The",
"more",
"matches",
"there",
"are",
"the",
"weirder",
"the",
"text",
"is",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/badness.py#L31-L92 | train |
LuminosoInsight/python-ftfy | ftfy/badness.py | sequence_weirdness | def sequence_weirdness(text):
"""
Determine how often a text has unexpected characters or sequences of
characters. This metric is used to disambiguate when text should be
re-decoded or left as is.
We start by normalizing text in NFC form, so that penalties for
diacritical marks don't apply to c... | python | def sequence_weirdness(text):
"""
Determine how often a text has unexpected characters or sequences of
characters. This metric is used to disambiguate when text should be
re-decoded or left as is.
We start by normalizing text in NFC form, so that penalties for
diacritical marks don't apply to c... | [
"def",
"sequence_weirdness",
"(",
"text",
")",
":",
"text2",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"text",
")",
"weirdness",
"=",
"len",
"(",
"WEIRDNESS_RE",
".",
"findall",
"(",
"chars_to_classes",
"(",
"text2",
")",
")",
")",
"adjustme... | Determine how often a text has unexpected characters or sequences of
characters. This metric is used to disambiguate when text should be
re-decoded or left as is.
We start by normalizing text in NFC form, so that penalties for
diacritical marks don't apply to characters that know what to do with
th... | [
"Determine",
"how",
"often",
"a",
"text",
"has",
"unexpected",
"characters",
"or",
"sequences",
"of",
"characters",
".",
"This",
"metric",
"is",
"used",
"to",
"disambiguate",
"when",
"text",
"should",
"be",
"re",
"-",
"decoded",
"or",
"left",
"as",
"is",
"... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/badness.py#L157-L190 | train |
LuminosoInsight/python-ftfy | ftfy/bad_codecs/__init__.py | search_function | def search_function(encoding):
"""
Register our "bad codecs" with Python's codecs API. This involves adding
a search function that takes in an encoding name, and returns a codec
for that encoding if it knows one, or None if it doesn't.
The encodings this will match are:
- Encodings of the form... | python | def search_function(encoding):
"""
Register our "bad codecs" with Python's codecs API. This involves adding
a search function that takes in an encoding name, and returns a codec
for that encoding if it knows one, or None if it doesn't.
The encodings this will match are:
- Encodings of the form... | [
"def",
"search_function",
"(",
"encoding",
")",
":",
"if",
"encoding",
"in",
"_CACHE",
":",
"return",
"_CACHE",
"[",
"encoding",
"]",
"norm_encoding",
"=",
"normalize_encoding",
"(",
"encoding",
")",
"codec",
"=",
"None",
"if",
"norm_encoding",
"in",
"UTF8_VAR... | Register our "bad codecs" with Python's codecs API. This involves adding
a search function that takes in an encoding name, and returns a codec
for that encoding if it knows one, or None if it doesn't.
The encodings this will match are:
- Encodings of the form 'sloppy-windows-NNNN' or 'sloppy-iso-8859-... | [
"Register",
"our",
"bad",
"codecs",
"with",
"Python",
"s",
"codecs",
"API",
".",
"This",
"involves",
"adding",
"a",
"search",
"function",
"that",
"takes",
"in",
"an",
"encoding",
"name",
"and",
"returns",
"a",
"codec",
"for",
"that",
"encoding",
"if",
"it"... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/bad_codecs/__init__.py#L47-L76 | train |
LuminosoInsight/python-ftfy | ftfy/bad_codecs/utf8_variants.py | IncrementalDecoder._buffer_decode | def _buffer_decode(self, input, errors, final):
"""
Decode bytes that may be arriving in a stream, following the Codecs
API.
`input` is the incoming sequence of bytes. `errors` tells us how to
handle errors, though we delegate all error-handling cases to the real
UTF-8 d... | python | def _buffer_decode(self, input, errors, final):
"""
Decode bytes that may be arriving in a stream, following the Codecs
API.
`input` is the incoming sequence of bytes. `errors` tells us how to
handle errors, though we delegate all error-handling cases to the real
UTF-8 d... | [
"def",
"_buffer_decode",
"(",
"self",
",",
"input",
",",
"errors",
",",
"final",
")",
":",
"decoded_segments",
"=",
"[",
"]",
"position",
"=",
"0",
"while",
"True",
":",
"decoded",
",",
"consumed",
"=",
"self",
".",
"_buffer_decode_step",
"(",
"input",
"... | Decode bytes that may be arriving in a stream, following the Codecs
API.
`input` is the incoming sequence of bytes. `errors` tells us how to
handle errors, though we delegate all error-handling cases to the real
UTF-8 decoder to ensure correct behavior. `final` indicates whether
... | [
"Decode",
"bytes",
"that",
"may",
"be",
"arriving",
"in",
"a",
"stream",
"following",
"the",
"Codecs",
"API",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/bad_codecs/utf8_variants.py#L88-L129 | train |
LuminosoInsight/python-ftfy | ftfy/bad_codecs/utf8_variants.py | IncrementalDecoder._buffer_decode_surrogates | def _buffer_decode_surrogates(sup, input, errors, final):
"""
When we have improperly encoded surrogates, we can still see the
bits that they were meant to represent.
The surrogates were meant to encode a 20-bit number, to which we
add 0x10000 to get a codepoint. That 20-bit num... | python | def _buffer_decode_surrogates(sup, input, errors, final):
"""
When we have improperly encoded surrogates, we can still see the
bits that they were meant to represent.
The surrogates were meant to encode a 20-bit number, to which we
add 0x10000 to get a codepoint. That 20-bit num... | [
"def",
"_buffer_decode_surrogates",
"(",
"sup",
",",
"input",
",",
"errors",
",",
"final",
")",
":",
"if",
"len",
"(",
"input",
")",
"<",
"6",
":",
"if",
"final",
":",
"return",
"sup",
"(",
"input",
",",
"errors",
",",
"final",
")",
"else",
":",
"r... | When we have improperly encoded surrogates, we can still see the
bits that they were meant to represent.
The surrogates were meant to encode a 20-bit number, to which we
add 0x10000 to get a codepoint. That 20-bit number now appears in
this form:
11101101 1010abcd 10efghij 11... | [
"When",
"we",
"have",
"improperly",
"encoded",
"surrogates",
"we",
"can",
"still",
"see",
"the",
"bits",
"that",
"they",
"were",
"meant",
"to",
"represent",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/bad_codecs/utf8_variants.py#L173-L215 | train |
LuminosoInsight/python-ftfy | ftfy/__init__.py | fix_text | def fix_text(text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
fix_line_breaks=True,
fix_surrogates=Tr... | python | def fix_text(text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
fix_line_breaks=True,
fix_surrogates=Tr... | [
"def",
"fix_text",
"(",
"text",
",",
"*",
",",
"fix_entities",
"=",
"'auto'",
",",
"remove_terminal_escapes",
"=",
"True",
",",
"fix_encoding",
"=",
"True",
",",
"fix_latin_ligatures",
"=",
"True",
",",
"fix_character_width",
"=",
"True",
",",
"uncurl_quotes",
... | r"""
Given Unicode text as input, fix inconsistencies and glitches in it,
such as mojibake.
Let's start with some examples:
>>> print(fix_text('ünicode'))
ünicode
>>> print(fix_text('Broken text… it’s flubberific!',
... normalization='NFKC'))
... | [
"r",
"Given",
"Unicode",
"text",
"as",
"input",
"fix",
"inconsistencies",
"and",
"glitches",
"in",
"it",
"such",
"as",
"mojibake",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/__init__.py#L20-L186 | train |
LuminosoInsight/python-ftfy | ftfy/__init__.py | fix_file | def fix_file(input_file,
encoding=None,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
fix_line_breaks=Tr... | python | def fix_file(input_file,
encoding=None,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
fix_line_breaks=Tr... | [
"def",
"fix_file",
"(",
"input_file",
",",
"encoding",
"=",
"None",
",",
"*",
",",
"fix_entities",
"=",
"'auto'",
",",
"remove_terminal_escapes",
"=",
"True",
",",
"fix_encoding",
"=",
"True",
",",
"fix_latin_ligatures",
"=",
"True",
",",
"fix_character_width",
... | Fix text that is found in a file.
If the file is being read as Unicode text, use that. If it's being read as
bytes, then we hope an encoding was supplied. If not, unfortunately, we
have to guess what encoding it is. We'll try a few common encodings, but we
make no promises. See the `guess_bytes` functi... | [
"Fix",
"text",
"that",
"is",
"found",
"in",
"a",
"file",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/__init__.py#L195-L241 | train |
LuminosoInsight/python-ftfy | ftfy/__init__.py | fix_text_segment | def fix_text_segment(text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
... | python | def fix_text_segment(text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
... | [
"def",
"fix_text_segment",
"(",
"text",
",",
"*",
",",
"fix_entities",
"=",
"'auto'",
",",
"remove_terminal_escapes",
"=",
"True",
",",
"fix_encoding",
"=",
"True",
",",
"fix_latin_ligatures",
"=",
"True",
",",
"fix_character_width",
"=",
"True",
",",
"uncurl_qu... | Apply fixes to text in a single chunk. This could be a line of text
within a larger run of `fix_text`, or it could be a larger amount
of text that you are certain is in a consistent encoding.
See `fix_text` for a description of the parameters. | [
"Apply",
"fixes",
"to",
"text",
"in",
"a",
"single",
"chunk",
".",
"This",
"could",
"be",
"a",
"line",
"of",
"text",
"within",
"a",
"larger",
"run",
"of",
"fix_text",
"or",
"it",
"could",
"be",
"a",
"larger",
"amount",
"of",
"text",
"that",
"you",
"a... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/__init__.py#L244-L296 | train |
LuminosoInsight/python-ftfy | ftfy/__init__.py | explain_unicode | def explain_unicode(text):
"""
A utility method that's useful for debugging mysterious Unicode.
It breaks down a string, showing you for each codepoint its number in
hexadecimal, its glyph, its category in the Unicode standard, and its name
in the Unicode standard.
>>> explain_unicode('(╯°... | python | def explain_unicode(text):
"""
A utility method that's useful for debugging mysterious Unicode.
It breaks down a string, showing you for each codepoint its number in
hexadecimal, its glyph, its category in the Unicode standard, and its name
in the Unicode standard.
>>> explain_unicode('(╯°... | [
"def",
"explain_unicode",
"(",
"text",
")",
":",
"for",
"char",
"in",
"text",
":",
"if",
"char",
".",
"isprintable",
"(",
")",
":",
"display",
"=",
"char",
"else",
":",
"display",
"=",
"char",
".",
"encode",
"(",
"'unicode-escape'",
")",
".",
"decode",... | A utility method that's useful for debugging mysterious Unicode.
It breaks down a string, showing you for each codepoint its number in
hexadecimal, its glyph, its category in the Unicode standard, and its name
in the Unicode standard.
>>> explain_unicode('(╯°□°)╯︵ ┻━┻')
U+0028 ( [Ps... | [
"A",
"utility",
"method",
"that",
"s",
"useful",
"for",
"debugging",
"mysterious",
"Unicode",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/__init__.py#L379-L411 | train |
LuminosoInsight/python-ftfy | ftfy/chardata.py | _build_regexes | def _build_regexes():
"""
ENCODING_REGEXES contain reasonably fast ways to detect if we
could represent a given string in a given encoding. The simplest one is
the 'ascii' detector, which of course just determines if all characters
are between U+0000 and U+007F.
"""
# Define a regex that mat... | python | def _build_regexes():
"""
ENCODING_REGEXES contain reasonably fast ways to detect if we
could represent a given string in a given encoding. The simplest one is
the 'ascii' detector, which of course just determines if all characters
are between U+0000 and U+007F.
"""
# Define a regex that mat... | [
"def",
"_build_regexes",
"(",
")",
":",
"encoding_regexes",
"=",
"{",
"'ascii'",
":",
"re",
".",
"compile",
"(",
"'^[\\x00-\\x7f]*$'",
")",
"}",
"for",
"encoding",
"in",
"CHARMAP_ENCODINGS",
":",
"byte_range",
"=",
"bytes",
"(",
"list",
"(",
"range",
"(",
... | ENCODING_REGEXES contain reasonably fast ways to detect if we
could represent a given string in a given encoding. The simplest one is
the 'ascii' detector, which of course just determines if all characters
are between U+0000 and U+007F. | [
"ENCODING_REGEXES",
"contain",
"reasonably",
"fast",
"ways",
"to",
"detect",
"if",
"we",
"could",
"represent",
"a",
"given",
"string",
"in",
"a",
"given",
"encoding",
".",
"The",
"simplest",
"one",
"is",
"the",
"ascii",
"detector",
"which",
"of",
"course",
"... | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/chardata.py#L25-L49 | train |
LuminosoInsight/python-ftfy | ftfy/chardata.py | _build_width_map | def _build_width_map():
"""
Build a translate mapping that replaces halfwidth and fullwidth forms
with their standard-width forms.
"""
# Though it's not listed as a fullwidth character, we'll want to convert
# U+3000 IDEOGRAPHIC SPACE to U+20 SPACE on the same principle, so start
# with that... | python | def _build_width_map():
"""
Build a translate mapping that replaces halfwidth and fullwidth forms
with their standard-width forms.
"""
# Though it's not listed as a fullwidth character, we'll want to convert
# U+3000 IDEOGRAPHIC SPACE to U+20 SPACE on the same principle, so start
# with that... | [
"def",
"_build_width_map",
"(",
")",
":",
"width_map",
"=",
"{",
"0x3000",
":",
"' '",
"}",
"for",
"i",
"in",
"range",
"(",
"0xff01",
",",
"0xfff0",
")",
":",
"char",
"=",
"chr",
"(",
"i",
")",
"alternate",
"=",
"unicodedata",
".",
"normalize",
"(",
... | Build a translate mapping that replaces halfwidth and fullwidth forms
with their standard-width forms. | [
"Build",
"a",
"translate",
"mapping",
"that",
"replaces",
"halfwidth",
"and",
"fullwidth",
"forms",
"with",
"their",
"standard",
"-",
"width",
"forms",
"."
] | 476acc6ad270bffe07f97d4f7cf2139acdc69633 | https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/chardata.py#L222-L236 | train |
pydata/numexpr | numexpr/utils.py | set_vml_accuracy_mode | def set_vml_accuracy_mode(mode):
"""
Set the accuracy mode for VML operations.
The `mode` parameter can take the values:
- 'high': high accuracy mode (HA), <1 least significant bit
- 'low': low accuracy mode (LA), typically 1-2 least significant bits
- 'fast': enhanced performance mode (EP)
... | python | def set_vml_accuracy_mode(mode):
"""
Set the accuracy mode for VML operations.
The `mode` parameter can take the values:
- 'high': high accuracy mode (HA), <1 least significant bit
- 'low': low accuracy mode (LA), typically 1-2 least significant bits
- 'fast': enhanced performance mode (EP)
... | [
"def",
"set_vml_accuracy_mode",
"(",
"mode",
")",
":",
"if",
"use_vml",
":",
"acc_dict",
"=",
"{",
"None",
":",
"0",
",",
"'low'",
":",
"1",
",",
"'high'",
":",
"2",
",",
"'fast'",
":",
"3",
"}",
"acc_reverse_dict",
"=",
"{",
"1",
":",
"'low'",
","... | Set the accuracy mode for VML operations.
The `mode` parameter can take the values:
- 'high': high accuracy mode (HA), <1 least significant bit
- 'low': low accuracy mode (LA), typically 1-2 least significant bits
- 'fast': enhanced performance mode (EP)
- None: mode settings are ignored
This ... | [
"Set",
"the",
"accuracy",
"mode",
"for",
"VML",
"operations",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/utils.py#L34-L62 | train |
pydata/numexpr | numexpr/utils.py | _init_num_threads | def _init_num_threads():
"""
Detects the environment variable 'NUMEXPR_MAX_THREADS' to set the threadpool
size, and if necessary the slightly redundant 'NUMEXPR_NUM_THREADS' or
'OMP_NUM_THREADS' env vars to set the initial number of threads used by
the virtual machine.
"""
# Any platform-... | python | def _init_num_threads():
"""
Detects the environment variable 'NUMEXPR_MAX_THREADS' to set the threadpool
size, and if necessary the slightly redundant 'NUMEXPR_NUM_THREADS' or
'OMP_NUM_THREADS' env vars to set the initial number of threads used by
the virtual machine.
"""
# Any platform-... | [
"def",
"_init_num_threads",
"(",
")",
":",
"if",
"'sparc'",
"in",
"platform",
".",
"machine",
"(",
")",
":",
"log",
".",
"warning",
"(",
"'The number of threads have been set to 1 because problems related '",
"'to threading have been reported on some sparc machine. '",
"'The ... | Detects the environment variable 'NUMEXPR_MAX_THREADS' to set the threadpool
size, and if necessary the slightly redundant 'NUMEXPR_NUM_THREADS' or
'OMP_NUM_THREADS' env vars to set the initial number of threads used by
the virtual machine. | [
"Detects",
"the",
"environment",
"variable",
"NUMEXPR_MAX_THREADS",
"to",
"set",
"the",
"threadpool",
"size",
"and",
"if",
"necessary",
"the",
"slightly",
"redundant",
"NUMEXPR_NUM_THREADS",
"or",
"OMP_NUM_THREADS",
"env",
"vars",
"to",
"set",
"the",
"initial",
"num... | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/utils.py#L100-L145 | train |
pydata/numexpr | numexpr/utils.py | detect_number_of_cores | def detect_number_of_cores():
"""
Detects the number of cores on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if i... | python | def detect_number_of_cores():
"""
Detects the number of cores on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if i... | [
"def",
"detect_number_of_cores",
"(",
")",
":",
"if",
"hasattr",
"(",
"os",
",",
"\"sysconf\"",
")",
":",
"if",
"\"SC_NPROCESSORS_ONLN\"",
"in",
"os",
".",
"sysconf_names",
":",
"ncpus",
"=",
"os",
".",
"sysconf",
"(",
"\"SC_NPROCESSORS_ONLN\"",
")",
"if",
"... | Detects the number of cores on a system. Cribbed from pp. | [
"Detects",
"the",
"number",
"of",
"cores",
"on",
"a",
"system",
".",
"Cribbed",
"from",
"pp",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/utils.py#L148-L168 | train |
pydata/numexpr | bench/multidim.py | chunkify | def chunkify(chunksize):
""" Very stupid "chunk vectorizer" which keeps memory use down.
This version requires all inputs to have the same number of elements,
although it shouldn't be that hard to implement simple broadcasting.
"""
def chunkifier(func):
def wrap(*args):
... | python | def chunkify(chunksize):
""" Very stupid "chunk vectorizer" which keeps memory use down.
This version requires all inputs to have the same number of elements,
although it shouldn't be that hard to implement simple broadcasting.
"""
def chunkifier(func):
def wrap(*args):
... | [
"def",
"chunkify",
"(",
"chunksize",
")",
":",
"def",
"chunkifier",
"(",
"func",
")",
":",
"def",
"wrap",
"(",
"*",
"args",
")",
":",
"assert",
"len",
"(",
"args",
")",
">",
"0",
"assert",
"all",
"(",
"len",
"(",
"a",
".",
"flat",
")",
"==",
"l... | Very stupid "chunk vectorizer" which keeps memory use down.
This version requires all inputs to have the same number of elements,
although it shouldn't be that hard to implement simple broadcasting. | [
"Very",
"stupid",
"chunk",
"vectorizer",
"which",
"keeps",
"memory",
"use",
"down",
".",
"This",
"version",
"requires",
"all",
"inputs",
"to",
"have",
"the",
"same",
"number",
"of",
"elements",
"although",
"it",
"shouldn",
"t",
"be",
"that",
"hard",
"to",
... | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/bench/multidim.py#L28-L57 | train |
pydata/numexpr | numexpr/necompiler.py | expressionToAST | def expressionToAST(ex):
"""Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number.
"""
return ASTNode(ex.astType, ex.astKind, ex.value,
[expressionToAST(c) fo... | python | def expressionToAST(ex):
"""Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number.
"""
return ASTNode(ex.astType, ex.astKind, ex.value,
[expressionToAST(c) fo... | [
"def",
"expressionToAST",
"(",
"ex",
")",
":",
"return",
"ASTNode",
"(",
"ex",
".",
"astType",
",",
"ex",
".",
"astKind",
",",
"ex",
".",
"value",
",",
"[",
"expressionToAST",
"(",
"c",
")",
"for",
"c",
"in",
"ex",
".",
"children",
"]",
")"
] | Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number. | [
"Take",
"an",
"expression",
"tree",
"made",
"out",
"of",
"expressions",
".",
"ExpressionNode",
"and",
"convert",
"to",
"an",
"AST",
"tree",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L158-L166 | train |
pydata/numexpr | numexpr/necompiler.py | sigPerms | def sigPerms(s):
"""Generate all possible signatures derived by upcasting the given
signature.
"""
codes = 'bilfdc'
if not s:
yield ''
elif s[0] in codes:
start = codes.index(s[0])
for x in codes[start:]:
for y in sigPerms(s[1:]):
yield x + y
... | python | def sigPerms(s):
"""Generate all possible signatures derived by upcasting the given
signature.
"""
codes = 'bilfdc'
if not s:
yield ''
elif s[0] in codes:
start = codes.index(s[0])
for x in codes[start:]:
for y in sigPerms(s[1:]):
yield x + y
... | [
"def",
"sigPerms",
"(",
"s",
")",
":",
"codes",
"=",
"'bilfdc'",
"if",
"not",
"s",
":",
"yield",
"''",
"elif",
"s",
"[",
"0",
"]",
"in",
"codes",
":",
"start",
"=",
"codes",
".",
"index",
"(",
"s",
"[",
"0",
"]",
")",
"for",
"x",
"in",
"codes... | Generate all possible signatures derived by upcasting the given
signature. | [
"Generate",
"all",
"possible",
"signatures",
"derived",
"by",
"upcasting",
"the",
"given",
"signature",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L169-L185 | train |
pydata/numexpr | numexpr/necompiler.py | typeCompileAst | def typeCompileAst(ast):
"""Assign appropiate types to each node in the AST.
Will convert opcodes and functions to appropiate upcast version,
and add "cast" ops if needed.
"""
children = list(ast.children)
if ast.astType == 'op':
retsig = ast.typecode()
basesig = ''.join(x.typec... | python | def typeCompileAst(ast):
"""Assign appropiate types to each node in the AST.
Will convert opcodes and functions to appropiate upcast version,
and add "cast" ops if needed.
"""
children = list(ast.children)
if ast.astType == 'op':
retsig = ast.typecode()
basesig = ''.join(x.typec... | [
"def",
"typeCompileAst",
"(",
"ast",
")",
":",
"children",
"=",
"list",
"(",
"ast",
".",
"children",
")",
"if",
"ast",
".",
"astType",
"==",
"'op'",
":",
"retsig",
"=",
"ast",
".",
"typecode",
"(",
")",
"basesig",
"=",
"''",
".",
"join",
"(",
"x",
... | Assign appropiate types to each node in the AST.
Will convert opcodes and functions to appropiate upcast version,
and add "cast" ops if needed. | [
"Assign",
"appropiate",
"types",
"to",
"each",
"node",
"in",
"the",
"AST",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L188-L228 | train |
pydata/numexpr | numexpr/necompiler.py | stringToExpression | def stringToExpression(s, types, context):
"""Given a string, convert it to a tree of ExpressionNode's.
"""
old_ctx = expressions._context.get_current_context()
try:
expressions._context.set_new_context(context)
# first compile to a code object to determine the names
if context.g... | python | def stringToExpression(s, types, context):
"""Given a string, convert it to a tree of ExpressionNode's.
"""
old_ctx = expressions._context.get_current_context()
try:
expressions._context.set_new_context(context)
# first compile to a code object to determine the names
if context.g... | [
"def",
"stringToExpression",
"(",
"s",
",",
"types",
",",
"context",
")",
":",
"old_ctx",
"=",
"expressions",
".",
"_context",
".",
"get_current_context",
"(",
")",
"try",
":",
"expressions",
".",
"_context",
".",
"set_new_context",
"(",
"context",
")",
"if"... | Given a string, convert it to a tree of ExpressionNode's. | [
"Given",
"a",
"string",
"convert",
"it",
"to",
"a",
"tree",
"of",
"ExpressionNode",
"s",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L273-L306 | train |
pydata/numexpr | numexpr/necompiler.py | getInputOrder | def getInputOrder(ast, input_order=None):
"""Derive the input order of the variables in an expression.
"""
variables = {}
for a in ast.allOf('variable'):
variables[a.value] = a
variable_names = set(variables.keys())
if input_order:
if variable_names != set(input_order):
... | python | def getInputOrder(ast, input_order=None):
"""Derive the input order of the variables in an expression.
"""
variables = {}
for a in ast.allOf('variable'):
variables[a.value] = a
variable_names = set(variables.keys())
if input_order:
if variable_names != set(input_order):
... | [
"def",
"getInputOrder",
"(",
"ast",
",",
"input_order",
"=",
"None",
")",
":",
"variables",
"=",
"{",
"}",
"for",
"a",
"in",
"ast",
".",
"allOf",
"(",
"'variable'",
")",
":",
"variables",
"[",
"a",
".",
"value",
"]",
"=",
"a",
"variable_names",
"=",
... | Derive the input order of the variables in an expression. | [
"Derive",
"the",
"input",
"order",
"of",
"the",
"variables",
"in",
"an",
"expression",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L314-L333 | train |
pydata/numexpr | numexpr/necompiler.py | assignLeafRegisters | def assignLeafRegisters(inodes, registerMaker):
"""Assign new registers to each of the leaf nodes.
"""
leafRegisters = {}
for node in inodes:
key = node.key()
if key in leafRegisters:
node.reg = leafRegisters[key]
else:
node.reg = leafRegisters[key] = regi... | python | def assignLeafRegisters(inodes, registerMaker):
"""Assign new registers to each of the leaf nodes.
"""
leafRegisters = {}
for node in inodes:
key = node.key()
if key in leafRegisters:
node.reg = leafRegisters[key]
else:
node.reg = leafRegisters[key] = regi... | [
"def",
"assignLeafRegisters",
"(",
"inodes",
",",
"registerMaker",
")",
":",
"leafRegisters",
"=",
"{",
"}",
"for",
"node",
"in",
"inodes",
":",
"key",
"=",
"node",
".",
"key",
"(",
")",
"if",
"key",
"in",
"leafRegisters",
":",
"node",
".",
"reg",
"=",... | Assign new registers to each of the leaf nodes. | [
"Assign",
"new",
"registers",
"to",
"each",
"of",
"the",
"leaf",
"nodes",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L368-L377 | train |
pydata/numexpr | numexpr/necompiler.py | assignBranchRegisters | def assignBranchRegisters(inodes, registerMaker):
"""Assign temporary registers to each of the branch nodes.
"""
for node in inodes:
node.reg = registerMaker(node, temporary=True) | python | def assignBranchRegisters(inodes, registerMaker):
"""Assign temporary registers to each of the branch nodes.
"""
for node in inodes:
node.reg = registerMaker(node, temporary=True) | [
"def",
"assignBranchRegisters",
"(",
"inodes",
",",
"registerMaker",
")",
":",
"for",
"node",
"in",
"inodes",
":",
"node",
".",
"reg",
"=",
"registerMaker",
"(",
"node",
",",
"temporary",
"=",
"True",
")"
] | Assign temporary registers to each of the branch nodes. | [
"Assign",
"temporary",
"registers",
"to",
"each",
"of",
"the",
"branch",
"nodes",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L380-L384 | train |
pydata/numexpr | numexpr/necompiler.py | collapseDuplicateSubtrees | def collapseDuplicateSubtrees(ast):
"""Common subexpression elimination.
"""
seen = {}
aliases = []
for a in ast.allOf('op'):
if a in seen:
target = seen[a]
a.astType = 'alias'
a.value = target
a.children = ()
aliases.append(a)
... | python | def collapseDuplicateSubtrees(ast):
"""Common subexpression elimination.
"""
seen = {}
aliases = []
for a in ast.allOf('op'):
if a in seen:
target = seen[a]
a.astType = 'alias'
a.value = target
a.children = ()
aliases.append(a)
... | [
"def",
"collapseDuplicateSubtrees",
"(",
"ast",
")",
":",
"seen",
"=",
"{",
"}",
"aliases",
"=",
"[",
"]",
"for",
"a",
"in",
"ast",
".",
"allOf",
"(",
"'op'",
")",
":",
"if",
"a",
"in",
"seen",
":",
"target",
"=",
"seen",
"[",
"a",
"]",
"a",
".... | Common subexpression elimination. | [
"Common",
"subexpression",
"elimination",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L387-L406 | train |
pydata/numexpr | numexpr/necompiler.py | optimizeTemporariesAllocation | def optimizeTemporariesAllocation(ast):
"""Attempt to minimize the number of temporaries needed, by
reusing old ones.
"""
nodes = [n for n in ast.postorderWalk() if n.reg.temporary]
users_of = dict((n.reg, set()) for n in nodes)
node_regs = dict((n, set(c.reg for c in n.children if c.reg.tempor... | python | def optimizeTemporariesAllocation(ast):
"""Attempt to minimize the number of temporaries needed, by
reusing old ones.
"""
nodes = [n for n in ast.postorderWalk() if n.reg.temporary]
users_of = dict((n.reg, set()) for n in nodes)
node_regs = dict((n, set(c.reg for c in n.children if c.reg.tempor... | [
"def",
"optimizeTemporariesAllocation",
"(",
"ast",
")",
":",
"nodes",
"=",
"[",
"n",
"for",
"n",
"in",
"ast",
".",
"postorderWalk",
"(",
")",
"if",
"n",
".",
"reg",
".",
"temporary",
"]",
"users_of",
"=",
"dict",
"(",
"(",
"n",
".",
"reg",
",",
"s... | Attempt to minimize the number of temporaries needed, by
reusing old ones. | [
"Attempt",
"to",
"minimize",
"the",
"number",
"of",
"temporaries",
"needed",
"by",
"reusing",
"old",
"ones",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L409-L439 | train |
pydata/numexpr | numexpr/necompiler.py | setOrderedRegisterNumbers | def setOrderedRegisterNumbers(order, start):
"""Given an order of nodes, assign register numbers.
"""
for i, node in enumerate(order):
node.reg.n = start + i
return start + len(order) | python | def setOrderedRegisterNumbers(order, start):
"""Given an order of nodes, assign register numbers.
"""
for i, node in enumerate(order):
node.reg.n = start + i
return start + len(order) | [
"def",
"setOrderedRegisterNumbers",
"(",
"order",
",",
"start",
")",
":",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"order",
")",
":",
"node",
".",
"reg",
".",
"n",
"=",
"start",
"+",
"i",
"return",
"start",
"+",
"len",
"(",
"order",
")"
] | Given an order of nodes, assign register numbers. | [
"Given",
"an",
"order",
"of",
"nodes",
"assign",
"register",
"numbers",
"."
] | 364bac13d84524e0e01db892301b2959d822dcff | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L442-L447 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.