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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
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: csf = dict(clicks=0) session_state['bootstrap_demo_state'] = csf else: csf['clicks'] = n_clicks return "Button has been clicked %s times since the page was rendered" %n_clicks
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: csf = dict(clicks=0) session_state['bootstrap_demo_state'] = csf else: csf['clicks'] = n_clicks return "Button has been clicked %s times since the page was rendered" %n_clicks
[ "def", "session_demo_alert_callback", "(", "n_clicks", ",", "session_state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "session_state", "is", "None", ":", "raise", "NotImplementedError", "(", "\"Cannot handle a missing session state\"", ")", "csf", "=", ...
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
226,700
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", ")", ":", "name", "=", "slugify", "(", "name", ")", "global", "usable_apps", "# pylint: disable=global-statement", "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
226,701
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_pathname = "%s:%s" % (app_name, main_view_label) ndid = specific_identifier kwargs = {'ident': ndid} if cache_id: kwargs['cache_id'] = cache_id app_pathname = app_pathname + "--args" full_url = reverse(app_pathname, kwargs=kwargs) if full_url[-1] != '/': full_url = full_url + '/' return ndid, full_url
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_pathname = "%s:%s" % (app_name, main_view_label) ndid = specific_identifier kwargs = {'ident': ndid} if cache_id: kwargs['cache_id'] = cache_id app_pathname = app_pathname + "--args" full_url = reverse(app_pathname, kwargs=kwargs) if full_url[-1] != '/': full_url = full_url + '/' return ndid, full_url
[ "def", "get_base_pathname", "(", "self", ",", "specific_identifier", ",", "cache_id", ")", ":", "if", "not", "specific_identifier", ":", "app_pathname", "=", "\"%s:app-%s\"", "%", "(", "app_name", ",", "main_view_label", ")", "ndid", "=", "self", ".", "_uid", ...
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
226,702
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, base_pathname)
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, base_pathname)
[ "def", "do_form_dash_instance", "(", "self", ",", "replacements", "=", "None", ",", "specific_identifier", "=", "None", ",", "cache_id", "=", "None", ")", ":", "ndid", ",", "base_pathname", "=", "self", ".", "get_base_pathname", "(", "specific_identifier", ",", ...
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
226,703
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, replacements=replacements, ndid=ndid, serve_locally=self._serve_locally) rd.layout = self.layout rd.config['suppress_callback_exceptions'] = self._suppress_callback_exceptions for cb, func in self._callback_sets: rd.callback(**cb)(func) for s in self.css.items: rd.css.append_css(s) for s in self.scripts.items: rd.scripts.append_script(s) return rd
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, replacements=replacements, ndid=ndid, serve_locally=self._serve_locally) rd.layout = self.layout rd.config['suppress_callback_exceptions'] = self._suppress_callback_exceptions for cb, func in self._callback_sets: rd.callback(**cb)(func) for s in self.css.items: rd.css.append_css(s) for s in self.scripts.items: rd.scripts.append_script(s) return rd
[ "def", "form_dash_instance", "(", "self", ",", "replacements", "=", "None", ",", "ndid", "=", "None", ",", "base_pathname", "=", "None", ")", ":", "if", "ndid", "is", "None", ":", "ndid", "=", "self", ".", "_uid", "rd", "=", "WrappedDash", "(", "base_p...
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
226,704
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 state or dict(), 'events':events and events or dict()} def wrap_func(func, callback_set=callback_set, callback_sets=self._callback_sets): # pylint: disable=dangerous-default-value, missing-docstring callback_sets.append((callback_set, func)) return func return wrap_func
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 state or dict(), 'events':events and events or dict()} def wrap_func(func, callback_set=callback_set, callback_sets=self._callback_sets): # pylint: disable=dangerous-default-value, missing-docstring callback_sets.append((callback_set, func)) return func return wrap_func
[ "def", "callback", "(", "self", ",", "output", ",", "inputs", "=", "None", ",", "state", "=", "None", ",", "events", "=", "None", ")", ":", "callback_set", "=", "{", "'output'", ":", "output", ",", "'inputs'", ":", "inputs", "and", "inputs", "or", "d...
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
226,705
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. ''' self._expanded_callbacks = True return self.callback(output, inputs, state, events)
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. ''' self._expanded_callbacks = True return self.callback(output, inputs, state, events)
[ "def", "expanded_callback", "(", "self", ",", "output", ",", "inputs", "=", "[", "]", ",", "state", "=", "[", "]", ",", "events", "=", "[", "]", ")", ":", "# pylint: disable=dangerous-default-value", "self", ".", "_expanded_callbacks", "=", "True", "return",...
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
226,706
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 baseDataInBytes = base_response.data baseData = json.loads(baseDataInBytes.decode('utf-8')) # Also add in any initial arguments if initial_arguments: if isinstance(initial_arguments, str): initial_arguments = json.loads(initial_arguments) # Walk tree. If at any point we have an element whose id # matches, then replace any named values at this level reworked_data = self.walk_tree_and_replace(baseData, initial_arguments) response_data = json.dumps(reworked_data, cls=PlotlyJSONEncoder) return response_data, base_response.mimetype
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 baseDataInBytes = base_response.data baseData = json.loads(baseDataInBytes.decode('utf-8')) # Also add in any initial arguments if initial_arguments: if isinstance(initial_arguments, str): initial_arguments = json.loads(initial_arguments) # Walk tree. If at any point we have an element whose id # matches, then replace any named values at this level reworked_data = self.walk_tree_and_replace(baseData, initial_arguments) response_data = json.dumps(reworked_data, cls=PlotlyJSONEncoder) return response_data, base_response.mimetype
[ "def", "augment_initial_layout", "(", "self", ",", "base_response", ",", "initial_arguments", "=", "None", ")", ":", "if", "self", ".", "use_dash_layout", "(", ")", "and", "not", "initial_arguments", "and", "False", ":", "return", "base_response", ".", "data", ...
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
226,707
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) if ident is not None: idVals = target.get(ident, {}) for key, value in data.items(): if key not in ['props', 'options', 'children', 'id']: idVals[key] = value if idVals: target[ident] = idVals if isinstance(data, list): for element in data: self.walk_tree_and_extract(element, target)
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) if ident is not None: idVals = target.get(ident, {}) for key, value in data.items(): if key not in ['props', 'options', 'children', 'id']: idVals[key] = value if idVals: target[ident] = idVals if isinstance(data, list): for element in data: self.walk_tree_and_extract(element, target)
[ "def", "walk_tree_and_extract", "(", "self", ",", "data", ",", "target", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "for", "key", "in", "[", "'children'", ",", "'props'", ",", "]", ":", "self", ".", "walk_tree_and_extract", "(", ...
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
226,708
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 = {} # look for id entry thisID = data.get('id', None) if thisID is not None: replacements = overrides.get(thisID, None) if overrides else None if not replacements: replacements = self._replacements.get(thisID, {}) # walk all keys and replace if needed for k, v in data.items(): r = replacements.get(k, None) if r is None: r = self.walk_tree_and_replace(v, overrides) response[k] = r return response if isinstance(data, list): # process each entry in turn and return return [self.walk_tree_and_replace(x, overrides) for x in data] return data
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 = {} # look for id entry thisID = data.get('id', None) if thisID is not None: replacements = overrides.get(thisID, None) if overrides else None if not replacements: replacements = self._replacements.get(thisID, {}) # walk all keys and replace if needed for k, v in data.items(): r = replacements.get(k, None) if r is None: r = self.walk_tree_and_replace(v, overrides) response[k] = r return response if isinstance(data, list): # process each entry in turn and return return [self.walk_tree_and_replace(x, overrides) for x in data] return data
[ "def", "walk_tree_and_replace", "(", "self", ",", "data", ",", "overrides", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "response", "=", "{", "}", "replacements", "=", "{", "}", "# look for id entry", "thisID", "=", "data", ".", "ge...
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
226,709
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", ")", ":", "if", "name", "is", "not", "None", ":", "ep", "=", "\"%s_%s\"", "%", "(", "self", ".", "_base_pathname", ",", "name", ")", "else", ":", "ep", "=", "self", ".", "_base...
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
226,710
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", ")", ":", "if", "self", ".", "_adjust_id", ":", "self", ".", "_fix_component_id", "(", "value", ")", "return", "Dash", ".", "layout", ".", "fset", "(", "self", ",", "value", ")" ]
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
226,711
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_id(c) except: #pylint: disable=bare-except pass
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_id(c) except: #pylint: disable=bare-except pass
[ "def", "_fix_component_id", "(", "self", ",", "component", ")", ":", "theID", "=", "getattr", "(", "component", ",", "\"id\"", ",", "None", ")", "if", "theID", "is", "not", "None", ":", "setattr", "(", "component", ",", "\"id\"", ",", "self", ".", "_fi...
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
226,712
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", ")", ":", "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
226,713
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 be removed once the library has been extended raise NotImplementedError("django-plotly-dash cannot handle multiple callback outputs at present") else: fixed_outputs = self._fix_callback_item(output) return super(WrappedDash, self).callback(fixed_outputs, [self._fix_callback_item(x) for x in inputs], [self._fix_callback_item(x) for x in state])
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 be removed once the library has been extended raise NotImplementedError("django-plotly-dash cannot handle multiple callback outputs at present") else: fixed_outputs = self._fix_callback_item(output) return super(WrappedDash, self).callback(fixed_outputs, [self._fix_callback_item(x) for x in inputs], [self._fix_callback_item(x) for x in state])
[ "def", "callback", "(", "self", ",", "output", ",", "inputs", "=", "[", "]", ",", "state", "=", "[", "]", ",", "events", "=", "[", "]", ")", ":", "# pylint: disable=dangerous-default-value", "if", "isinstance", "(", "output", ",", "(", "list", ",", "tu...
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
226,714
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", ")", ":", "import", "flask", "body", "=", "flask", ".", "request", ".", "get_json", "(", ")", "return", "self", ".", "dispatch_with_args", "(", "body", ",", "argMap", "=", "dict", "(", ")", ")" ]
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
226,715
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_property = output['property'] target_id = "%s.%s" %(output_id, output_property) except: target_id = output output_id, output_property = output.split(".") args = [] da = argMap.get('dash_app', None) for component_registration in self.callback_map[target_id]['inputs']: for c in inputs: if c['property'] == component_registration['property'] and c['id'] == component_registration['id']: v = c.get('value', None) args.append(v) if da: da.update_current_state(c['id'], c['property'], v) for component_registration in self.callback_map[target_id]['state']: for c in state: if c['property'] == component_registration['property'] and c['id'] == component_registration['id']: v = c.get('value', None) args.append(v) if da: da.update_current_state(c['id'], c['property'], v) # Special: intercept case of insufficient arguments # This happens when a propery has been updated with a pipe component # TODO see if this can be attacked from the client end if len(args) < len(self.callback_map[target_id]['inputs']): return 'EDGECASEEXIT' res = self.callback_map[target_id]['callback'](*args, **argMap) if da and da.have_current_state_entry(output_id, output_property): response = json.loads(res.data.decode('utf-8')) value = response.get('response', {}).get('props', {}).get(output_property, None) da.update_current_state(output_id, output_property, value) return res
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_property = output['property'] target_id = "%s.%s" %(output_id, output_property) except: target_id = output output_id, output_property = output.split(".") args = [] da = argMap.get('dash_app', None) for component_registration in self.callback_map[target_id]['inputs']: for c in inputs: if c['property'] == component_registration['property'] and c['id'] == component_registration['id']: v = c.get('value', None) args.append(v) if da: da.update_current_state(c['id'], c['property'], v) for component_registration in self.callback_map[target_id]['state']: for c in state: if c['property'] == component_registration['property'] and c['id'] == component_registration['id']: v = c.get('value', None) args.append(v) if da: da.update_current_state(c['id'], c['property'], v) # Special: intercept case of insufficient arguments # This happens when a propery has been updated with a pipe component # TODO see if this can be attacked from the client end if len(args) < len(self.callback_map[target_id]['inputs']): return 'EDGECASEEXIT' res = self.callback_map[target_id]['callback'](*args, **argMap) if da and da.have_current_state_entry(output_id, output_property): response = json.loads(res.data.decode('utf-8')) value = response.get('response', {}).get('props', {}).get(output_property, None) da.update_current_state(output_id, output_property, value) return res
[ "def", "dispatch_with_args", "(", "self", ",", "body", ",", "argMap", ")", ":", "inputs", "=", "body", ".", "get", "(", "'inputs'", ",", "[", "]", ")", "state", "=", "body", ".", "get", "(", "'state'", ",", "[", "]", ")", "output", "=", "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
226,716
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 "django-plotly-dash" post_part = "-%s" % postfix if postfix else "" template_type = template_type if template_type else "iframe" slugified_id = self.slugified_id() return "%(prefix)s %(prefix)s-%(template_type)s %(prefix)s-app-%(slugified_id)s%(post_part)s" % {'slugified_id':slugified_id, 'post_part':post_part, 'template_type':template_type, 'prefix':prefix, }
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 "django-plotly-dash" post_part = "-%s" % postfix if postfix else "" template_type = template_type if template_type else "iframe" slugified_id = self.slugified_id() return "%(prefix)s %(prefix)s-%(template_type)s %(prefix)s-app-%(slugified_id)s%(post_part)s" % {'slugified_id':slugified_id, 'post_part':post_part, 'template_type':template_type, 'prefix':prefix, }
[ "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
226,717
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_embedded(eh) try: resp = view_func() finally: app.exit_embedded() return locals()
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_embedded(eh) try: resp = view_func() finally: app.exit_embedded() return locals()
[ "def", "plotly_direct", "(", "context", ",", "name", "=", "None", ",", "slug", "=", "None", ",", "da", "=", "None", ")", ":", "da", ",", "app", "=", "_locate_daapp", "(", "name", ",", "slug", ",", "da", ")", "view_func", "=", "app", ".", "locate_en...
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
226,718
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", ")", ":", "da", ",", "app", "=", "_locate_daapp", "(", "name", ",", "slug", ",", "da", ")", "slugified_id", "=", ...
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
226,719
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, template_type=template_type)
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, template_type=template_type)
[ "def", "plotly_class", "(", "name", "=", "None", ",", "slug", "=", "None", ",", "da", "=", "None", ",", "prefix", "=", "None", ",", "postfix", "=", "None", ",", "template_type", "=", "None", ")", ":", "da", ",", "app", "=", "_locate_daapp", "(", "n...
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
226,720
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 in enumerate(wyckoff_file): if line.strip() == 'end of data': break rowdata.append(line.strip().split(':')) # 2:P -1 ::::::: <-- store line number if first element is number if rowdata[-1][0].isdigit(): points.append(i) points.append(i) wyckoff = [] for i in range(len(points) - 1): # 0 to 529 symbol = rowdata[points[i]][1] # e.g. "C 1 2 1" if i + 1 in hP_nums: symbol = symbol.replace('R', 'H', 1) wyckoff.append({'symbol': symbol.strip()}) # When the number of positions is larger than 4, # the positions are written in the next line. # So those positions are connected. for i in range(len(points) - 1): count = 0 wyckoff[i]['wyckoff'] = [] for j in range(points[i] + 1, points[i + 1]): # Hook if the third element is a number (multiplicity), e.g., # # 232:P 2/b 2/m 2/b::::::: <- ignored # ::8:r:1:(x,y,z):(-x,y,-z):(x,-y+1/2,-z):(-x,-y+1/2,z) # :::::(-x,-y,-z):(x,-y,z):(-x,y+1/2,z):(x,y+1/2,-z) <- ignored # ::4:q:..m:(x,0,z):(-x,0,-z):(x,1/2,-z):(-x,1/2,z) # ::4:p:..2:(0,y,1/2):(0,-y+1/2,1/2):(0,-y,1/2):(0,y+1/2,1/2) # ::4:o:..2:(1/2,y,0):(1/2,-y+1/2,0):(1/2,-y,0):(1/2,y+1/2,0) # ... if rowdata[j][2].isdigit(): pos = [] w = {'letter': rowdata[j][3].strip(), 'multiplicity': int(rowdata[j][2]), 'site_symmetry': rowdata[j][4].strip(), 'positions': pos} wyckoff[i]['wyckoff'].append(w) for k in range(4): if rowdata[j][k + 5]: # check if '(x,y,z)' or '' count += 1 pos.append(rowdata[j][k + 5]) else: for k in range(4): if rowdata[j][k + 5]: count += 1 pos.append(rowdata[j][k + 5]) # assertion for w in wyckoff[i]['wyckoff']: n_pos = len(w['positions']) n_pos *= len(lattice_symbols[wyckoff[i]['symbol'][0]]) assert n_pos == w['multiplicity'] return wyckoff
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 in enumerate(wyckoff_file): if line.strip() == 'end of data': break rowdata.append(line.strip().split(':')) # 2:P -1 ::::::: <-- store line number if first element is number if rowdata[-1][0].isdigit(): points.append(i) points.append(i) wyckoff = [] for i in range(len(points) - 1): # 0 to 529 symbol = rowdata[points[i]][1] # e.g. "C 1 2 1" if i + 1 in hP_nums: symbol = symbol.replace('R', 'H', 1) wyckoff.append({'symbol': symbol.strip()}) # When the number of positions is larger than 4, # the positions are written in the next line. # So those positions are connected. for i in range(len(points) - 1): count = 0 wyckoff[i]['wyckoff'] = [] for j in range(points[i] + 1, points[i + 1]): # Hook if the third element is a number (multiplicity), e.g., # # 232:P 2/b 2/m 2/b::::::: <- ignored # ::8:r:1:(x,y,z):(-x,y,-z):(x,-y+1/2,-z):(-x,-y+1/2,z) # :::::(-x,-y,-z):(x,-y,z):(-x,y+1/2,z):(x,y+1/2,-z) <- ignored # ::4:q:..m:(x,0,z):(-x,0,-z):(x,1/2,-z):(-x,1/2,z) # ::4:p:..2:(0,y,1/2):(0,-y+1/2,1/2):(0,-y,1/2):(0,y+1/2,1/2) # ::4:o:..2:(1/2,y,0):(1/2,-y+1/2,0):(1/2,-y,0):(1/2,y+1/2,0) # ... if rowdata[j][2].isdigit(): pos = [] w = {'letter': rowdata[j][3].strip(), 'multiplicity': int(rowdata[j][2]), 'site_symmetry': rowdata[j][4].strip(), 'positions': pos} wyckoff[i]['wyckoff'].append(w) for k in range(4): if rowdata[j][k + 5]: # check if '(x,y,z)' or '' count += 1 pos.append(rowdata[j][k + 5]) else: for k in range(4): if rowdata[j][k + 5]: count += 1 pos.append(rowdata[j][k + 5]) # assertion for w in wyckoff[i]['wyckoff']: n_pos = len(w['positions']) n_pos *= len(lattice_symbols[wyckoff[i]['symbol'][0]]) assert n_pos == w['multiplicity'] return wyckoff
[ "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
226,721
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['wyckoff']] damp_array_site_symmetries(ssyms)
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['wyckoff']] damp_array_site_symmetries(ssyms)
[ "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
226,722
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, ClassDef): for attr in mcls.get_children(): if isinstance(attr, Assign): if attr.targets[0].name == "app": appname = attr.value.value mname = "{}.{}".format(appname, cls.name) MODELS[mname] = cls for relname, relval in FUTURE_RELATIONS.get(mname, []): cls.locals[relname] = relval for attr in cls.get_children(): if isinstance(attr, Assign): try: attrname = attr.value.func.attrname except AttributeError: pass else: if attrname in ["ForeignKeyField", "ManyToManyField"]: tomodel = attr.value.args[0].value relname = "" if attr.value.keywords: for keyword in attr.value.keywords: if keyword.arg == "related_name": relname = keyword.value.value if not relname: relname = cls.name.lower() + "s" # Injected model attributes need to also have the relation manager if attrname == "ManyToManyField": relval = [ attr.value.func, MANAGER.ast_from_module_name("tortoise.fields").lookup( "ManyToManyRelationManager" )[1][0], ] else: relval = [ attr.value.func, MANAGER.ast_from_module_name("tortoise.fields").lookup( "RelationQueryContainer" )[1][0], ] if tomodel in MODELS: MODELS[tomodel].locals[relname] = relval else: FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval)) cls.locals["_meta"] = [ MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class() ] if "id" not in cls.locals: cls.locals["id"] = [nodes.ClassDef("id", None)]
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, ClassDef): for attr in mcls.get_children(): if isinstance(attr, Assign): if attr.targets[0].name == "app": appname = attr.value.value mname = "{}.{}".format(appname, cls.name) MODELS[mname] = cls for relname, relval in FUTURE_RELATIONS.get(mname, []): cls.locals[relname] = relval for attr in cls.get_children(): if isinstance(attr, Assign): try: attrname = attr.value.func.attrname except AttributeError: pass else: if attrname in ["ForeignKeyField", "ManyToManyField"]: tomodel = attr.value.args[0].value relname = "" if attr.value.keywords: for keyword in attr.value.keywords: if keyword.arg == "related_name": relname = keyword.value.value if not relname: relname = cls.name.lower() + "s" # Injected model attributes need to also have the relation manager if attrname == "ManyToManyField": relval = [ attr.value.func, MANAGER.ast_from_module_name("tortoise.fields").lookup( "ManyToManyRelationManager" )[1][0], ] else: relval = [ attr.value.func, MANAGER.ast_from_module_name("tortoise.fields").lookup( "RelationQueryContainer" )[1][0], ] if tomodel in MODELS: MODELS[tomodel].locals[relname] = relval else: FUTURE_RELATIONS.setdefault(tomodel, []).append((relname, relval)) cls.locals["_meta"] = [ MANAGER.ast_from_module_name("tortoise.models").lookup("MetaInfo")[1][0].instantiate_class() ] if "id" not in cls.locals: cls.locals["id"] = [nodes.ClassDef("id", None)]
[ "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
226,723
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("str") elif cls.name == "BooleanField": base_nodes = scoped_nodes.builtin_lookup("bool") elif cls.name == "FloatField": base_nodes = scoped_nodes.builtin_lookup("float") elif cls.name == "DecimalField": base_nodes = MANAGER.ast_from_module_name("decimal").lookup("Decimal") elif cls.name == "DatetimeField": base_nodes = MANAGER.ast_from_module_name("datetime").lookup("datetime") elif cls.name == "DateField": base_nodes = MANAGER.ast_from_module_name("datetime").lookup("date") elif cls.name == "ForeignKeyField": base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup("BackwardFKRelation") elif cls.name == "ManyToManyField": base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup( "ManyToManyRelationManager" ) else: return iter([cls]) return iter([cls] + base_nodes[1])
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("str") elif cls.name == "BooleanField": base_nodes = scoped_nodes.builtin_lookup("bool") elif cls.name == "FloatField": base_nodes = scoped_nodes.builtin_lookup("float") elif cls.name == "DecimalField": base_nodes = MANAGER.ast_from_module_name("decimal").lookup("Decimal") elif cls.name == "DatetimeField": base_nodes = MANAGER.ast_from_module_name("datetime").lookup("datetime") elif cls.name == "DateField": base_nodes = MANAGER.ast_from_module_name("datetime").lookup("date") elif cls.name == "ForeignKeyField": base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup("BackwardFKRelation") elif cls.name == "ManyToManyField": base_nodes = MANAGER.ast_from_module_name("tortoise.fields").lookup( "ManyToManyRelationManager" ) else: return iter([cls]) return iter([cls] + base_nodes[1])
[ "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
226,724
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
226,725
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( "You should first call .save() on {model}".format(model=self.instance) ) db = using_db if using_db else self.model._meta.db through_table = Table(self.field.through) select_query = ( db.query_class.from_(through_table) .where(getattr(through_table, self.field.backward_key) == self.instance.id) .select(self.field.backward_key, self.field.forward_key) ) query = db.query_class.into(through_table).columns( getattr(through_table, self.field.forward_key), getattr(through_table, self.field.backward_key), ) if len(instances) == 1: criterion = getattr(through_table, self.field.forward_key) == instances[0].id else: criterion = getattr(through_table, self.field.forward_key).isin( [i.id for i in instances] ) select_query = select_query.where(criterion) already_existing_relations_raw = await db.execute_query(str(select_query)) already_existing_relations = { (r[self.field.backward_key], r[self.field.forward_key]) for r in already_existing_relations_raw } insert_is_required = False for instance_to_add in instances: if instance_to_add.id is None: raise OperationalError( "You should first call .save() on {model}".format(model=instance_to_add) ) if (self.instance.id, instance_to_add.id) in already_existing_relations: continue query = query.insert(instance_to_add.id, self.instance.id) insert_is_required = True if insert_is_required: await db.execute_query(str(query))
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( "You should first call .save() on {model}".format(model=self.instance) ) db = using_db if using_db else self.model._meta.db through_table = Table(self.field.through) select_query = ( db.query_class.from_(through_table) .where(getattr(through_table, self.field.backward_key) == self.instance.id) .select(self.field.backward_key, self.field.forward_key) ) query = db.query_class.into(through_table).columns( getattr(through_table, self.field.forward_key), getattr(through_table, self.field.backward_key), ) if len(instances) == 1: criterion = getattr(through_table, self.field.forward_key) == instances[0].id else: criterion = getattr(through_table, self.field.forward_key).isin( [i.id for i in instances] ) select_query = select_query.where(criterion) already_existing_relations_raw = await db.execute_query(str(select_query)) already_existing_relations = { (r[self.field.backward_key], r[self.field.forward_key]) for r in already_existing_relations_raw } insert_is_required = False for instance_to_add in instances: if instance_to_add.id is None: raise OperationalError( "You should first call .save() on {model}".format(model=instance_to_add) ) if (self.instance.id, instance_to_add.id) in already_existing_relations: continue query = query.insert(instance_to_add.id, self.instance.id) insert_is_required = True if insert_is_required: await db.execute_query(str(query))
[ "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
226,726
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, self.field.backward_key) == self.instance.id) .delete() ) await db.execute_query(str(query))
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, self.field.backward_key) == self.instance.id) .delete() ) await db.execute_query(str(query))
[ "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
226,727
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_table = Table(self.field.through) if len(instances) == 1: condition = (getattr(through_table, self.field.forward_key) == instances[0].id) & ( getattr(through_table, self.field.backward_key) == self.instance.id ) else: condition = (getattr(through_table, self.field.backward_key) == self.instance.id) & ( getattr(through_table, self.field.forward_key).isin([i.id for i in instances]) ) query = db.query_class.from_(through_table).where(condition).delete() await db.execute_query(str(query))
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_table = Table(self.field.through) if len(instances) == 1: condition = (getattr(through_table, self.field.forward_key) == instances[0].id) & ( getattr(through_table, self.field.backward_key) == self.instance.id ) else: condition = (getattr(through_table, self.field.backward_key) == self.instance.id) & ( getattr(through_table, self.field.forward_key).isin([i.id for i in instances]) ) query = db.query_class.from_(through_table).where(condition).delete() await db.execute_query(str(query))
[ "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
226,728
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 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)``. Parameters ---------- app: Quart app. config: Dict containing config: Example ------- .. code-block:: python3 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:@qwerty123localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. generate_schemas: True to generate schema immediately. Only useful for dev environments or SQLite ``:memory:`` databases """ @app.before_serving async def init_orm(): await Tortoise.init(config=config, config_file=config_file, db_url=db_url, modules=modules) print("Tortoise-ORM started, {}, {}".format(Tortoise._connections, Tortoise.apps)) if generate_schemas: print("Tortoise-ORM generating schema") await Tortoise.generate_schemas() @app.after_serving async def close_orm(): await Tortoise.close_connections() print("Tortoise-ORM shutdown") @app.cli.command() # type: ignore def generate_schemas(): # pylint: disable=E0102 """Populate DB with Tortoise-ORM schemas.""" async def inner(): await Tortoise.init( config=config, config_file=config_file, db_url=db_url, modules=modules ) await Tortoise.generate_schemas() await Tortoise.close_connections() logging.basicConfig(level=logging.DEBUG) loop = asyncio.get_event_loop() loop.run_until_complete(inner())
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 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)``. Parameters ---------- app: Quart app. config: Dict containing config: Example ------- .. code-block:: python3 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:@qwerty123localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. generate_schemas: True to generate schema immediately. Only useful for dev environments or SQLite ``:memory:`` databases """ @app.before_serving async def init_orm(): await Tortoise.init(config=config, config_file=config_file, db_url=db_url, modules=modules) print("Tortoise-ORM started, {}, {}".format(Tortoise._connections, Tortoise.apps)) if generate_schemas: print("Tortoise-ORM generating schema") await Tortoise.generate_schemas() @app.after_serving async def close_orm(): await Tortoise.close_connections() print("Tortoise-ORM shutdown") @app.cli.command() # type: ignore def generate_schemas(): # pylint: disable=E0102 """Populate DB with Tortoise-ORM schemas.""" async def inner(): await Tortoise.init( config=config, config_file=config_file, db_url=db_url, modules=modules ) await Tortoise.generate_schemas() await Tortoise.close_connections() logging.basicConfig(level=logging.DEBUG) loop = asyncio.get_event_loop() loop.run_until_complete(inner())
[ "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)``. Parameters ---------- app: Quart app. config: Dict containing config: Example ------- .. code-block:: python3 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:@qwerty123localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. generate_schemas: True to generate schema immediately. Only useful for dev environments or SQLite ``:memory:`` databases
[ "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
226,729
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', models={'models': ['app.models']} ) ... run_async(do_stuff()) """ loop = asyncio.get_event_loop() try: loop.run_until_complete(coro) finally: loop.run_until_complete(Tortoise.close_connections())
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', models={'models': ['app.models']} ) ... run_async(do_stuff()) """ loop = asyncio.get_event_loop() try: loop.run_until_complete(coro) finally: loop.run_until_complete(Tortoise.close_connections())
[ "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']} ) ... run_async(do_stuff())
[ "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
226,730
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 configure using only one of ``config``, ``config_file`` and ``(db_url, modules)``. Parameters ---------- config: Dict containing config: Example ------- .. code-block:: python3 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:@qwerty123localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. _create_db: If ``True`` tries to create database for specified connections, could be used for testing purposes. Raises ------ ConfigurationError For any configuration error """ if cls._inited: await cls.close_connections() await cls._reset_apps() if int(bool(config) + bool(config_file) + bool(db_url)) != 1: raise ConfigurationError( 'You should init either from "config", "config_file" or "db_url"' ) if config_file: config = cls._get_config_from_config_file(config_file) if db_url: if not modules: raise ConfigurationError('You must specify "db_url" and "modules" together') config = generate_config(db_url, modules) try: connections_config = config["connections"] # type: ignore except KeyError: raise ConfigurationError('Config must define "connections" section') try: apps_config = config["apps"] # type: ignore except KeyError: raise ConfigurationError('Config must define "apps" section') logger.info( "Tortoise-ORM startup\n connections: %s\n apps: %s", str(connections_config), str(apps_config), ) await cls._init_connections(connections_config, _create_db) cls._init_apps(apps_config) cls._inited = True
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 configure using only one of ``config``, ``config_file`` and ``(db_url, modules)``. Parameters ---------- config: Dict containing config: Example ------- .. code-block:: python3 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:@qwerty123localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. _create_db: If ``True`` tries to create database for specified connections, could be used for testing purposes. Raises ------ ConfigurationError For any configuration error """ if cls._inited: await cls.close_connections() await cls._reset_apps() if int(bool(config) + bool(config_file) + bool(db_url)) != 1: raise ConfigurationError( 'You should init either from "config", "config_file" or "db_url"' ) if config_file: config = cls._get_config_from_config_file(config_file) if db_url: if not modules: raise ConfigurationError('You must specify "db_url" and "modules" together') config = generate_config(db_url, modules) try: connections_config = config["connections"] # type: ignore except KeyError: raise ConfigurationError('Config must define "connections" section') try: apps_config = config["apps"] # type: ignore except KeyError: raise ConfigurationError('Config must define "apps" section') logger.info( "Tortoise-ORM startup\n connections: %s\n apps: %s", str(connections_config), str(apps_config), ) await cls._init_connections(connections_config, _create_db) cls._init_apps(apps_config) cls._inited = True
[ "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 { 'connections': { # Dict format for connection 'default': { 'engine': 'tortoise.backends.asyncpg', 'credentials': { 'host': 'localhost', 'port': '5432', 'user': 'tortoise', 'password': 'qwerty123', 'database': 'test', } }, # Using a DB_URL string 'default': 'postgres://postgres:@qwerty123localhost:5432/events' }, 'apps': { 'models': { 'models': ['__main__'], # If no default_connection specified, defaults to 'default' 'default_connection': 'default', } } } config_file: Path to .json or .yml (if PyYAML installed) file containing config with same format as above. db_url: Use a DB_URL string. See :ref:`db_url` modules: Dictionary of ``key``: [``list_of_modules``] that defined "apps" and modules that should be discovered for models. _create_db: If ``True`` tries to create database for specified connections, could be used for testing purposes. Raises ------ ConfigurationError For any configuration error
[ "Sets", "up", "Tortoise", "-", "ORM", "." ]
7d16457731905e19d4d06ccd5b4ea16d4a9447b2
https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/__init__.py#L231-L332
train
226,731
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 connection to run with, optional if you have only one db connection """ connection = _get_connection(connection_name) return connection._in_transaction()
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 connection to run with, optional if you have only one db connection """ connection = _get_connection(connection_name) return connection._in_transaction()
[ "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
226,732
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 one db connection """ def wrapper(func): @wraps(func) async def wrapped(*args, **kwargs): connection = _get_connection(connection_name) async with connection._in_transaction(): return await func(*args, **kwargs) return wrapped return wrapper
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 one db connection """ def wrapper(func): @wraps(func) async def wrapped(*args, **kwargs): connection = _get_connection(connection_name) async with connection._in_transaction(): return await func(*args, **kwargs) return wrapped return wrapper
[ "def", "atomic", "(", "connection_name", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Callable", ":", "def", "wrapper", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "async", "def", "wrapped", "(", "*", "args", ",", "*", "*",...
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
226,733
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 transaction with above methods. :param connection_name: name of connection to run with, optional if you have only one db connection """ connection = _get_connection(connection_name) transaction = connection._in_transaction() await transaction.start() return transaction
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 transaction with above methods. :param connection_name: name of connection to run with, optional if you have only one db connection """ connection = _get_connection(connection_name) transaction = connection._in_transaction() await transaction.start() return transaction
[ "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 you have only one db connection
[ "Function", "to", "manually", "control", "your", "transaction", "." ]
7d16457731905e19d4d06ccd5b4ea16d4a9447b2
https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/transactions.py#L62-L76
train
226,734
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
226,735
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
226,736
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 instance") queryset._annotations[key] = aggregation from tortoise.models import get_filters_for_field queryset._custom_filters.update(get_filters_for_field(key, None, key)) return queryset
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 instance") queryset._annotations[key] = aggregation from tortoise.models import get_filters_for_field queryset._custom_filters.update(get_filters_for_field(key, None, key)) return queryset
[ "def", "annotate", "(", "self", ",", "*", "*", "kwargs", ")", "->", "\"QuerySet\"", ":", "queryset", "=", "self", ".", "_clone", "(", ")", "for", "key", ",", "aggregation", "in", "kwargs", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", ...
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
226,737
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 ValuesListQuery( db=self._db, model=self.model, q_objects=self._q_objects, flat=flat, fields_for_select_list=fields_, distinct=self._distinct, limit=self._limit, offset=self._offset, orderings=self._orderings, annotations=self._annotations, custom_filters=self._custom_filters, )
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 ValuesListQuery( db=self._db, model=self.model, q_objects=self._q_objects, flat=flat, fields_for_select_list=fields_, distinct=self._distinct, limit=self._limit, offset=self._offset, orderings=self._orderings, annotations=self._annotations, custom_filters=self._custom_filters, )
[ "def", "values_list", "(", "self", ",", "*", "fields_", ":", "str", ",", "flat", ":", "bool", "=", "False", ")", "->", "\"ValuesListQuery\"", ":", "# pylint: disable=W0621", "return", "ValuesListQuery", "(", "db", "=", "self", ".", "_db", ",", "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
226,738
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 {}".format(field)) fields_for_select[field] = field for return_as, field in kwargs.items(): if return_as in fields_for_select: raise FieldError("Duplicate key {}".format(return_as)) fields_for_select[return_as] = field return ValuesQuery( db=self._db, model=self.model, q_objects=self._q_objects, fields_for_select=fields_for_select, distinct=self._distinct, limit=self._limit, offset=self._offset, orderings=self._orderings, annotations=self._annotations, custom_filters=self._custom_filters, )
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 {}".format(field)) fields_for_select[field] = field for return_as, field in kwargs.items(): if return_as in fields_for_select: raise FieldError("Duplicate key {}".format(return_as)) fields_for_select[return_as] = field return ValuesQuery( db=self._db, model=self.model, q_objects=self._q_objects, fields_for_select=fields_for_select, distinct=self._distinct, limit=self._limit, offset=self._offset, orderings=self._orderings, annotations=self._annotations, custom_filters=self._custom_filters, )
[ "def", "values", "(", "self", ",", "*", "args", ":", "str", ",", "*", "*", "kwargs", ":", "str", ")", "->", "\"ValuesQuery\"", ":", "fields_for_select", "=", "{", "}", "# type: Dict[str, str]", "for", "field", "in", "args", ":", "if", "field", "in", "f...
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
226,739
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
226,740
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._annotations, custom_filters=self._custom_filters, )
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._annotations, custom_filters=self._custom_filters, )
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", "->", "\"UpdateQuery\"", ":", "return", "UpdateQuery", "(", "db", "=", "self", ".", "_db", ",", "model", "=", "self", ".", "model", ",", "update_kwargs", "=", "kwargs", ",", "q_objects", "=", ...
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
226,741
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._custom_filters, )
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._custom_filters, )
[ "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
226,742
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
226,743
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", ".", "_...
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
226,744
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: ``EXPLAIN QUERY PLAN ...`` - MySQL: ``EXPLAIN FORMAT=JSON ...`` .. note:: This is only meant to be used in an interactive environment for debugging and query optimization. **The output format may (and will) vary greatly depending on the database backend.** """ if self._db is None: self._db = self.model._meta.db return await self._db.executor_class(model=self.model, db=self._db).execute_explain( self._make_query() )
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: ``EXPLAIN QUERY PLAN ...`` - MySQL: ``EXPLAIN FORMAT=JSON ...`` .. note:: This is only meant to be used in an interactive environment for debugging and query optimization. **The output format may (and will) vary greatly depending on the database backend.** """ if self._db is None: self._db = self.model._meta.db return await self._db.executor_class(model=self.model, db=self._db).execute_explain( self._make_query() )
[ "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: ``EXPLAIN FORMAT=JSON ...`` .. note:: This is only meant to be used in an interactive environment for debugging and query optimization. **The output format may (and will) vary greatly depending on the database backend.**
[ "Fetch", "and", "return", "information", "about", "the", "query", "execution", "plan", "." ]
7d16457731905e19d4d06ccd5b4ea16d4a9447b2
https://github.com/tortoise/tortoise-orm/blob/7d16457731905e19d4d06ccd5b4ea16d4a9447b2/tortoise/queryset.py#L393-L413
train
226,745
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
226,746
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 tuple.".format(cls.__name__) ) elif any( not isinstance(unique_fields, (tuple, list)) for unique_fields in cls._meta.unique_together ): raise ConfigurationError( "All '{}.unique_together' elements must be lists or tuples.".format(cls.__name__) ) else: for fields_tuple in cls._meta.unique_together: for field_name in fields_tuple: field = cls._meta.fields_map.get(field_name) if not field: raise ConfigurationError( "'{}.unique_together' has no '{}' " "field.".format(cls.__name__, field_name) ) if isinstance(field, ManyToManyField): raise ConfigurationError( "'{}.unique_together' '{}' field refers " "to ManyToMany field.".format(cls.__name__, field_name) )
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 tuple.".format(cls.__name__) ) elif any( not isinstance(unique_fields, (tuple, list)) for unique_fields in cls._meta.unique_together ): raise ConfigurationError( "All '{}.unique_together' elements must be lists or tuples.".format(cls.__name__) ) else: for fields_tuple in cls._meta.unique_together: for field_name in fields_tuple: field = cls._meta.fields_map.get(field_name) if not field: raise ConfigurationError( "'{}.unique_together' has no '{}' " "field.".format(cls.__name__, field_name) ) if isinstance(field, ManyToManyField): raise ConfigurationError( "'{}.unique_together' '{}' field refers " "to ManyToMany field.".format(cls.__name__, field_name) )
[ "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
226,747
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 = EpubWriter(name, book, options) epub.process() try: epub.write() except IOError: pass
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 = EpubWriter(name, book, options) epub.process() try: epub.write() except IOError: pass
[ "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
226,748
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 EpubBook. """ reader = EpubReader(name, options) book = reader.load() reader.process() return book
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 EpubBook. """ reader = EpubReader(name, options) book = reader.load() reader.process() return book
[ "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
226,749
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 - ITEM_VECTOR = 5 - ITEM_FONT = 6 - ITEM_VIDEO = 7 - ITEM_AUDIO = 8 - ITEM_DOCUMENT = 9 - ITEM_COVER = 10 We map type according to the extensions which are defined in ebooklib.EXTENSIONS. :Returns: Returns type of the item as number. """ _, ext = zip_path.splitext(self.get_name()) ext = ext.lower() for uid, ext_list in six.iteritems(ebooklib.EXTENSIONS): if ext in ext_list: return uid return ebooklib.ITEM_UNKNOWN
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 - ITEM_VECTOR = 5 - ITEM_FONT = 6 - ITEM_VIDEO = 7 - ITEM_AUDIO = 8 - ITEM_DOCUMENT = 9 - ITEM_COVER = 10 We map type according to the extensions which are defined in ebooklib.EXTENSIONS. :Returns: Returns type of the item as number. """ _, ext = zip_path.splitext(self.get_name()) ext = ext.lower() for uid, ext_list in six.iteritems(ebooklib.EXTENSIONS): if ext in ext_list: return uid return ebooklib.ITEM_UNKNOWN
[ "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 - ITEM_FONT = 6 - ITEM_VIDEO = 7 - ITEM_AUDIO = 8 - ITEM_DOCUMENT = 9 - ITEM_COVER = 10 We map type according to the extensions which are defined in ebooklib.EXTENSIONS. :Returns: Returns type of the item as number.
[ "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
226,750
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': if 'scripted' not in self.properties: self.properties.append('scripted')
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': if 'scripted' not in self.properties: self.properties.append('scripted')
[ "def", "add_link", "(", "self", ",", "*", "*", "kwgs", ")", ":", "self", ".", "links", ".", "append", "(", "kwgs", ")", "if", "kwgs", ".", "get", "(", "'type'", ")", "==", "'text/javascript'", ":", "if", "'scripted'", "not", "in", "self", ".", "pro...
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
226,751
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
226,752
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=item.get_name(), rel='stylesheet', type='text/css') if item.get_type() == ebooklib.ITEM_SCRIPT: self.add_link(src=item.get_name(), type='text/javascript')
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=item.get_name(), rel='stylesheet', type='text/css') if item.get_type() == ebooklib.ITEM_SCRIPT: self.add_link(src=item.get_name(), type='text/javascript')
[ "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
226,753
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' self._id_html = 0 self._id_image = 0 self._id_static = 0 self.title = '' self.language = 'en' self.direction = None self.templates = { 'ncx': NCX_XML, 'nav': NAV_XML, 'chapter': CHAPTER_XML, 'cover': COVER_XML } self.add_metadata('OPF', 'generator', '', { 'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION]) }) # default to using a randomly-unique identifier if one is not specified manually self.set_identifier(str(uuid.uuid4())) # custom prefixes and namespaces to be set to the content.opf doc self.prefixes = [] self.namespaces = {}
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' self._id_html = 0 self._id_image = 0 self._id_static = 0 self.title = '' self.language = 'en' self.direction = None self.templates = { 'ncx': NCX_XML, 'nav': NAV_XML, 'chapter': CHAPTER_XML, 'cover': COVER_XML } self.add_metadata('OPF', 'generator', '', { 'name': 'generator', 'content': 'Ebook-lib %s' % '.'.join([str(s) for s in VERSION]) }) # default to using a randomly-unique identifier if one is not specified manually self.set_identifier(str(uuid.uuid4())) # custom prefixes and namespaces to be set to the content.opf doc self.prefixes = [] self.namespaces = {}
[ "def", "reset", "(", "self", ")", ":", "self", ".", "metadata", "=", "{", "}", "self", ".", "items", "=", "[", "]", "self", ".", "spine", "=", "[", "]", "self", ".", "guide", "=", "[", "]", "self", ".", "pages", "=", "[", "]", "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
226,754
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
226,755
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
226,756
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 (optional). Default value is True. """ # as it is now, it can only be called once c0 = EpubCover(file_name=file_name) c0.content = content self.add_item(c0) if create_page: c1 = EpubCoverHtml(image_name=file_name) self.add_item(c1) self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
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 (optional). Default value is True. """ # as it is now, it can only be called once c0 = EpubCover(file_name=file_name) c0.content = content self.add_item(c0) if create_page: c1 = EpubCoverHtml(image_name=file_name) self.add_item(c1) self.add_metadata(None, 'meta', '', OrderedDict([('name', 'cover'), ('content', 'cover-img')]))
[ "def", "set_cover", "(", "self", ",", "file_name", ",", "content", ",", "create_page", "=", "True", ")", ":", "# as it is now, it can only be called once", "c0", "=", "EpubCover", "(", "file_name", "=", "file_name", ")", "c0", ".", "content", "=", "content", "...
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
226,757
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, 'property': 'file-as', 'scheme': 'marc:relators'}) if role: self.add_metadata(None, 'meta', role, {'refines': '#' + uid, 'property': 'role', 'scheme': 'marc:relators'})
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, 'property': 'file-as', 'scheme': 'marc:relators'}) if role: self.add_metadata(None, 'meta', role, {'refines': '#' + uid, 'property': 'role', 'scheme': 'marc:relators'})
[ "def", "add_author", "(", "self", ",", "author", ",", "file_as", "=", "None", ",", "role", "=", "None", ",", "uid", "=", "'creator'", ")", ":", "self", ".", "add_metadata", "(", "'DC'", ",", "'creator'", ",", "author", ",", "{", "'id'", ":", "uid", ...
Add author for this document
[ "Add", "author", "for", "this", "document" ]
305f2dd7f02923ffabf9586a5d16266113d00c4a
https://github.com/aerkalov/ebooklib/blob/305f2dd7f02923ffabf9586a5d16266113d00c4a/ebooklib/epub.py#L660-L672
train
226,758
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().lower()) if has_guessed: if media_type is not None: item.media_type = media_type else: item.media_type = has_guessed else: item.media_type = 'application/octet-stream' if not item.get_id(): # make chapter_, image_ and static_ configurable if isinstance(item, EpubHtml): item.id = 'chapter_%d' % self._id_html self._id_html += 1 # If there's a page list, append it to the book's page list self.pages += item.pages elif isinstance(item, EpubImage): item.id = 'image_%d' % self._id_image self._id_image += 1 else: item.id = 'static_%d' % self._id_image self._id_image += 1 item.book = self self.items.append(item) return item
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().lower()) if has_guessed: if media_type is not None: item.media_type = media_type else: item.media_type = has_guessed else: item.media_type = 'application/octet-stream' if not item.get_id(): # make chapter_, image_ and static_ configurable if isinstance(item, EpubHtml): item.id = 'chapter_%d' % self._id_html self._id_html += 1 # If there's a page list, append it to the book's page list self.pages += item.pages elif isinstance(item, EpubImage): item.id = 'image_%d' % self._id_image self._id_image += 1 else: item.id = 'static_%d' % self._id_image self._id_image += 1 item.book = self self.items.append(item) return item
[ "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
226,759
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(): if item.id == uid: return item return None
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(): if item.id == uid: return item return None
[ "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
226,760
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. """ for item in self.get_items(): if item.get_name() == href: return item return None
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. """ for item in self.get_items(): if item.get_name() == href: return item return None
[ "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
226,761
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 item in self.items if item.get_type() == item_type)
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 item in self.items if item.get_type() == item_type)
[ "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
226,762
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_type == media_type)
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_type == media_type)
[ "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
226,763
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 is to be fixed. Defaults ' 'to -, meaning standard input.') parser.add_argument('-o', '--output', type=str, default='-', help='The file to output to. Defaults to -, meaning ' 'standard output.') parser.add_argument('-g', '--guess', action='store_true', help="Ask ftfy to guess the encoding of your input. " "This is risky. Overrides -e.") parser.add_argument('-e', '--encoding', type=str, default='utf-8', help='The encoding of the input. Defaults to UTF-8.') parser.add_argument('-n', '--normalization', type=str, default='NFC', help='The normalization of Unicode to apply. ' 'Defaults to NFC. Can be "none".') parser.add_argument('--preserve-entities', action='store_true', help="Leave HTML entities as they are. The default " "is to decode them, as long as no HTML tags " "have appeared in the file.") args = parser.parse_args() encoding = args.encoding if args.guess: encoding = None if args.filename == '-': # Get a standard input stream made of bytes, so we can decode it as # whatever encoding is necessary. file = sys.stdin.buffer else: file = open(args.filename, 'rb') if args.output == '-': outfile = sys.stdout else: if os.path.realpath(args.output) == os.path.realpath(args.filename): sys.stderr.write(SAME_FILE_ERROR_TEXT) sys.exit(1) outfile = open(args.output, 'w', encoding='utf-8') normalization = args.normalization if normalization.lower() == 'none': normalization = None if args.preserve_entities: fix_entities = False else: fix_entities = 'auto' try: for line in fix_file(file, encoding=encoding, fix_entities=fix_entities, normalization=normalization): try: outfile.write(line) except UnicodeEncodeError: if sys.platform == 'win32': sys.stderr.write(ENCODE_ERROR_TEXT_WINDOWS) else: sys.stderr.write(ENCODE_ERROR_TEXT_UNIX) sys.exit(1) except UnicodeDecodeError as err: sys.stderr.write(DECODE_ERROR_TEXT % (encoding, err)) sys.exit(1)
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 is to be fixed. Defaults ' 'to -, meaning standard input.') parser.add_argument('-o', '--output', type=str, default='-', help='The file to output to. Defaults to -, meaning ' 'standard output.') parser.add_argument('-g', '--guess', action='store_true', help="Ask ftfy to guess the encoding of your input. " "This is risky. Overrides -e.") parser.add_argument('-e', '--encoding', type=str, default='utf-8', help='The encoding of the input. Defaults to UTF-8.') parser.add_argument('-n', '--normalization', type=str, default='NFC', help='The normalization of Unicode to apply. ' 'Defaults to NFC. Can be "none".') parser.add_argument('--preserve-entities', action='store_true', help="Leave HTML entities as they are. The default " "is to decode them, as long as no HTML tags " "have appeared in the file.") args = parser.parse_args() encoding = args.encoding if args.guess: encoding = None if args.filename == '-': # Get a standard input stream made of bytes, so we can decode it as # whatever encoding is necessary. file = sys.stdin.buffer else: file = open(args.filename, 'rb') if args.output == '-': outfile = sys.stdout else: if os.path.realpath(args.output) == os.path.realpath(args.filename): sys.stderr.write(SAME_FILE_ERROR_TEXT) sys.exit(1) outfile = open(args.output, 'w', encoding='utf-8') normalization = args.normalization if normalization.lower() == 'none': normalization = None if args.preserve_entities: fix_entities = False else: fix_entities = 'auto' try: for line in fix_file(file, encoding=encoding, fix_entities=fix_entities, normalization=normalization): try: outfile.write(line) except UnicodeEncodeError: if sys.platform == 'win32': sys.stderr.write(ENCODE_ERROR_TEXT_WINDOWS) else: sys.stderr.write(ENCODE_ERROR_TEXT_UNIX) sys.exit(1) except UnicodeDecodeError as err: sys.stderr.write(DECODE_ERROR_TEXT % (encoding, err)) sys.exit(1)
[ "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
226,764
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. """ best_version = text best_cost = text_cost(text) best_plan = [] plan_so_far = [] while True: prevtext = text text, plan = fix_one_step_and_explain(text) plan_so_far.extend(plan) cost = text_cost(text) for _, _, step_cost in plan_so_far: cost += step_cost if cost < best_cost: best_cost = cost best_version = text best_plan = list(plan_so_far) if text == prevtext: return best_version, best_plan
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. """ best_version = text best_cost = text_cost(text) best_plan = [] plan_so_far = [] while True: prevtext = text text, plan = fix_one_step_and_explain(text) plan_so_far.extend(plan) cost = text_cost(text) for _, _, step_cost in plan_so_far: cost += step_cost if cost < best_cost: best_cost = cost best_version = text best_plan = list(plan_so_far) if text == prevtext: return best_version, best_plan
[ "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
226,765
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: return text, [] # The first plan is to return ASCII text unchanged. if possible_encoding(text, 'ascii'): return text, [] # As we go through the next step, remember the possible encodings # that we encounter but don't successfully fix yet. We may need them # later. possible_1byte_encodings = [] # Suppose the text was supposed to be UTF-8, but it was decoded using # a single-byte encoding instead. When these cases can be fixed, they # are usually the correct thing to do, so try them next. for encoding in CHARMAP_ENCODINGS: if possible_encoding(text, encoding): encoded_bytes = text.encode(encoding) encode_step = ('encode', encoding, ENCODING_COSTS.get(encoding, 0)) transcode_steps = [] # Now, find out if it's UTF-8 (or close enough). Otherwise, # remember the encoding for later. try: decoding = 'utf-8' # Check encoded_bytes for sequences that would be UTF-8, # except they have b' ' where b'\xa0' would belong. if ALTERED_UTF8_RE.search(encoded_bytes): encoded_bytes = restore_byte_a0(encoded_bytes) cost = encoded_bytes.count(0xa0) * 2 transcode_steps.append(('transcode', 'restore_byte_a0', cost)) # Check for the byte 0x1a, which indicates where one of our # 'sloppy' codecs found a replacement character. if encoding.startswith('sloppy') and 0x1a in encoded_bytes: encoded_bytes = replace_lossy_sequences(encoded_bytes) transcode_steps.append(('transcode', 'replace_lossy_sequences', 0)) if 0xed in encoded_bytes or 0xc0 in encoded_bytes: decoding = 'utf-8-variants' decode_step = ('decode', decoding, 0) steps = [encode_step] + transcode_steps + [decode_step] fixed = encoded_bytes.decode(decoding) return fixed, steps except UnicodeDecodeError: possible_1byte_encodings.append(encoding) # Look for a-hat-euro sequences that remain, and fix them in isolation. if PARTIAL_UTF8_PUNCT_RE.search(text): steps = [('transcode', 'fix_partial_utf8_punct_in_1252', 1)] fixed = fix_partial_utf8_punct_in_1252(text) return fixed, steps # The next most likely case is that this is Latin-1 that was intended to # be read as Windows-1252, because those two encodings in particular are # easily confused. if 'latin-1' in possible_1byte_encodings: if 'windows-1252' in possible_1byte_encodings: # This text is in the intersection of Latin-1 and # Windows-1252, so it's probably legit. return text, [] else: # Otherwise, it means we have characters that are in Latin-1 but # not in Windows-1252. Those are C1 control characters. Nobody # wants those. Assume they were meant to be Windows-1252. Don't # use the sloppy codec, because bad Windows-1252 characters are # a bad sign. encoded = text.encode('latin-1') try: fixed = encoded.decode('windows-1252') steps = [] if fixed != text: steps = [('encode', 'latin-1', 0), ('decode', 'windows-1252', 1)] return fixed, steps except UnicodeDecodeError: # This text contained characters that don't even make sense # if you assume they were supposed to be Windows-1252. In # that case, let's not assume anything. pass # The cases that remain are mixups between two different single-byte # encodings, and not the common case of Latin-1 vs. Windows-1252. # # These cases may be unsolvable without adding false positives, though # I have vague ideas about how to optionally address them in the future. # Return the text unchanged; the plan is empty. return text, []
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: return text, [] # The first plan is to return ASCII text unchanged. if possible_encoding(text, 'ascii'): return text, [] # As we go through the next step, remember the possible encodings # that we encounter but don't successfully fix yet. We may need them # later. possible_1byte_encodings = [] # Suppose the text was supposed to be UTF-8, but it was decoded using # a single-byte encoding instead. When these cases can be fixed, they # are usually the correct thing to do, so try them next. for encoding in CHARMAP_ENCODINGS: if possible_encoding(text, encoding): encoded_bytes = text.encode(encoding) encode_step = ('encode', encoding, ENCODING_COSTS.get(encoding, 0)) transcode_steps = [] # Now, find out if it's UTF-8 (or close enough). Otherwise, # remember the encoding for later. try: decoding = 'utf-8' # Check encoded_bytes for sequences that would be UTF-8, # except they have b' ' where b'\xa0' would belong. if ALTERED_UTF8_RE.search(encoded_bytes): encoded_bytes = restore_byte_a0(encoded_bytes) cost = encoded_bytes.count(0xa0) * 2 transcode_steps.append(('transcode', 'restore_byte_a0', cost)) # Check for the byte 0x1a, which indicates where one of our # 'sloppy' codecs found a replacement character. if encoding.startswith('sloppy') and 0x1a in encoded_bytes: encoded_bytes = replace_lossy_sequences(encoded_bytes) transcode_steps.append(('transcode', 'replace_lossy_sequences', 0)) if 0xed in encoded_bytes or 0xc0 in encoded_bytes: decoding = 'utf-8-variants' decode_step = ('decode', decoding, 0) steps = [encode_step] + transcode_steps + [decode_step] fixed = encoded_bytes.decode(decoding) return fixed, steps except UnicodeDecodeError: possible_1byte_encodings.append(encoding) # Look for a-hat-euro sequences that remain, and fix them in isolation. if PARTIAL_UTF8_PUNCT_RE.search(text): steps = [('transcode', 'fix_partial_utf8_punct_in_1252', 1)] fixed = fix_partial_utf8_punct_in_1252(text) return fixed, steps # The next most likely case is that this is Latin-1 that was intended to # be read as Windows-1252, because those two encodings in particular are # easily confused. if 'latin-1' in possible_1byte_encodings: if 'windows-1252' in possible_1byte_encodings: # This text is in the intersection of Latin-1 and # Windows-1252, so it's probably legit. return text, [] else: # Otherwise, it means we have characters that are in Latin-1 but # not in Windows-1252. Those are C1 control characters. Nobody # wants those. Assume they were meant to be Windows-1252. Don't # use the sloppy codec, because bad Windows-1252 characters are # a bad sign. encoded = text.encode('latin-1') try: fixed = encoded.decode('windows-1252') steps = [] if fixed != text: steps = [('encode', 'latin-1', 0), ('decode', 'windows-1252', 1)] return fixed, steps except UnicodeDecodeError: # This text contained characters that don't even make sense # if you assume they were supposed to be Windows-1252. In # that case, let's not assume anything. pass # The cases that remain are mixups between two different single-byte # encodings, and not the common case of Latin-1 vs. Windows-1252. # # These cases may be unsolvable without adding false positives, though # I have vague ideas about how to optionally address them in the future. # Return the text unchanged; the plan is empty. return text, []
[ "def", "fix_one_step_and_explain", "(", "text", ")", ":", "if", "isinstance", "(", "text", ",", "bytes", ")", ":", "raise", "UnicodeError", "(", "BYTES_ERROR_TEXT", ")", "if", "len", "(", "text", ")", "==", "0", ":", "return", "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.
[ "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
226,766
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. - `encoding` is the name of the encoding to use, such as 'utf-8' or 'latin-1', or the function name in the case of 'transcode'. - The `cost` does not affect how the plan itself works. It's used by other users of plans, namely `fix_encoding_and_explain`, which has to decide *which* plan to use. """ obj = text for operation, encoding, _ in plan: if operation == 'encode': obj = obj.encode(encoding) elif operation == 'decode': obj = obj.decode(encoding) elif operation == 'transcode': if encoding in TRANSCODERS: obj = TRANSCODERS[encoding](obj) else: raise ValueError("Unknown transcode operation: %s" % encoding) else: raise ValueError("Unknown plan step: %s" % operation) return obj
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. - `encoding` is the name of the encoding to use, such as 'utf-8' or 'latin-1', or the function name in the case of 'transcode'. - The `cost` does not affect how the plan itself works. It's used by other users of plans, namely `fix_encoding_and_explain`, which has to decide *which* plan to use. """ obj = text for operation, encoding, _ in plan: if operation == 'encode': obj = obj.encode(encoding) elif operation == 'decode': obj = obj.decode(encoding) elif operation == 'transcode': if encoding in TRANSCODERS: obj = TRANSCODERS[encoding](obj) else: raise ValueError("Unknown transcode operation: %s" % encoding) else: raise ValueError("Unknown plan step: %s" % operation) return obj
[ "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 encoding to use, such as 'utf-8' or 'latin-1', or the function name in the case of 'transcode'. - The `cost` does not affect how the plan itself works. It's used by other users of plans, namely `fix_encoding_and_explain`, which has to decide *which* plan to use.
[ "Apply", "a", "plan", "for", "fixing", "the", "encoding", "of", "text", "." ]
476acc6ad270bffe07f97d4f7cf2139acdc69633
https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/fixes.py#L262-L290
train
226,767
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: codept = int(text[2:-1]) if 0x80 <= codept < 0xa0: # Decode this range of characters as Windows-1252, as Web # browsers do in practice. return bytes([codept]).decode('sloppy-windows-1252') else: return chr(codept) except ValueError: return text else: # This is a named entity; if it's a known HTML5 entity, replace # it with the appropriate character. try: return entities.html5[text[1:]] except KeyError: return text
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: codept = int(text[2:-1]) if 0x80 <= codept < 0xa0: # Decode this range of characters as Windows-1252, as Web # browsers do in practice. return bytes([codept]).decode('sloppy-windows-1252') else: return chr(codept) except ValueError: return text else: # This is a named entity; if it's a known HTML5 entity, replace # it with the appropriate character. try: return entities.html5[text[1:]] except KeyError: return text
[ "def", "_unescape_fixup", "(", "match", ")", ":", "text", "=", "match", ".", "group", "(", "0", ")", "if", "text", "[", ":", "2", "]", "==", "\"&#\"", ":", "# character reference", "try", ":", "if", "text", "[", ":", "3", "]", "==", "\"&#x\"", ":",...
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
226,768
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) * 0x400 + (ord(pair[1]) - 0xdc00) return chr(codept)
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) * 0x400 + (ord(pair[1]) - 0xdc00) return chr(codept)
[ "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
226,769
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. This process finds sequences that would convincingly decode as UTF-8 if byte 20 were changed to A0, and puts back the A0. For the purpose of deciding whether this is a good idea, this step gets a cost of twice the number of bytes that are changed. This is used as a step within `fix_encoding`. """ def replacement(match): "The function to apply when this regex matches." return match.group(0).replace(b'\x20', b'\xa0') return ALTERED_UTF8_RE.sub(replacement, byts)
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. This process finds sequences that would convincingly decode as UTF-8 if byte 20 were changed to A0, and puts back the A0. For the purpose of deciding whether this is a good idea, this step gets a cost of twice the number of bytes that are changed. This is used as a step within `fix_encoding`. """ def replacement(match): "The function to apply when this regex matches." return match.group(0).replace(b'\x20', b'\xa0') return ALTERED_UTF8_RE.sub(replacement, byts)
[ "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 would convincingly decode as UTF-8 if byte 20 were changed to A0, and puts back the A0. For the purpose of deciding whether this is a good idea, this step gets a cost of twice the number of bytes that are changed. This is used as a step within `fix_encoding`.
[ "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
226,770
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 from the Latin-1 C1 control character set, while others are from the set of characters that take their place in Windows-1252. So we first replace those characters, then apply a fix that only works on Windows-1252 characters. This is used as a transcoder within `fix_encoding`. """ def latin1_to_w1252(match): "The function to apply when this regex matches." return match.group(0).encode('latin-1').decode('sloppy-windows-1252') def w1252_to_utf8(match): "The function to apply when this regex matches." return match.group(0).encode('sloppy-windows-1252').decode('utf-8') text = C1_CONTROL_RE.sub(latin1_to_w1252, text) return PARTIAL_UTF8_PUNCT_RE.sub(w1252_to_utf8, text)
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 from the Latin-1 C1 control character set, while others are from the set of characters that take their place in Windows-1252. So we first replace those characters, then apply a fix that only works on Windows-1252 characters. This is used as a transcoder within `fix_encoding`. """ def latin1_to_w1252(match): "The function to apply when this regex matches." return match.group(0).encode('latin-1').decode('sloppy-windows-1252') def w1252_to_utf8(match): "The function to apply when this regex matches." return match.group(0).encode('sloppy-windows-1252').decode('utf-8') text = C1_CONTROL_RE.sub(latin1_to_w1252, text) return PARTIAL_UTF8_PUNCT_RE.sub(w1252_to_utf8, text)
[ "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 are from the set of characters that take their place in Windows-1252. So we first replace those characters, then apply a fix that only works on Windows-1252 characters. This is used as a transcoder within `fix_encoding`.
[ "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
226,771
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 means toward the beginning of the string, which may actually appear on the right in an RTL context. This is similar to the use of the word "left" in "left parenthesis". >>> lines = ['Table flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し'] >>> for line in lines: ... print(display_ljust(line, 20, '▒')) Table flip▒▒▒▒▒▒▒▒▒▒ (╯°□°)╯︵ ┻━┻▒▒▒▒▒▒▒ ちゃぶ台返し▒▒▒▒▒▒▒▒ This example, and the similar ones that follow, should come out justified correctly when viewed in a monospaced terminal. It will probably not look correct if you're viewing this code or documentation in a Web browser. """ if character_width(fillchar) != 1: raise ValueError("The padding character must have display width 1") text_width = monospaced_width(text) if text_width == -1: # There's a control character here, so just don't add padding return text padding = max(0, width - text_width) return text + fillchar * padding
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 means toward the beginning of the string, which may actually appear on the right in an RTL context. This is similar to the use of the word "left" in "left parenthesis". >>> lines = ['Table flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し'] >>> for line in lines: ... print(display_ljust(line, 20, '▒')) Table flip▒▒▒▒▒▒▒▒▒▒ (╯°□°)╯︵ ┻━┻▒▒▒▒▒▒▒ ちゃぶ台返し▒▒▒▒▒▒▒▒ This example, and the similar ones that follow, should come out justified correctly when viewed in a monospaced terminal. It will probably not look correct if you're viewing this code or documentation in a Web browser. """ if character_width(fillchar) != 1: raise ValueError("The padding character must have display width 1") text_width = monospaced_width(text) if text_width == -1: # There's a control character here, so just don't add padding return text padding = max(0, width - text_width) return text + fillchar * padding
[ "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 appear on the right in an RTL context. This is similar to the use of the word "left" in "left parenthesis". >>> lines = ['Table flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し'] >>> for line in lines: ... print(display_ljust(line, 20, '▒')) Table flip▒▒▒▒▒▒▒▒▒▒ (╯°□°)╯︵ ┻━┻▒▒▒▒▒▒▒ ちゃぶ台返し▒▒▒▒▒▒▒▒ This example, and the similar ones that follow, should come out justified correctly when viewed in a monospaced terminal. It will probably not look correct if you're viewing this code or documentation in a Web browser.
[ "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
226,772
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 flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し'] >>> for line in lines: ... print(display_center(line, 20, '▒')) ▒▒▒▒▒Table flip▒▒▒▒▒ ▒▒▒(╯°□°)╯︵ ┻━┻▒▒▒▒ ▒▒▒▒ちゃぶ台返し▒▒▒▒ """ if character_width(fillchar) != 1: raise ValueError("The padding character must have display width 1") text_width = monospaced_width(text) if text_width == -1: return text padding = max(0, width - text_width) left_padding = padding // 2 right_padding = padding - left_padding return fillchar * left_padding + text + fillchar * right_padding
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 flip', '(╯°□°)╯︵ ┻━┻', 'ちゃぶ台返し'] >>> for line in lines: ... print(display_center(line, 20, '▒')) ▒▒▒▒▒Table flip▒▒▒▒▒ ▒▒▒(╯°□°)╯︵ ┻━┻▒▒▒▒ ▒▒▒▒ちゃぶ台返し▒▒▒▒ """ if character_width(fillchar) != 1: raise ValueError("The padding character must have display width 1") text_width = monospaced_width(text) if text_width == -1: return text padding = max(0, width - text_width) left_padding = padding // 2 right_padding = padding - left_padding return fillchar * left_padding + text + fillchar * right_padding
[ "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: ... print(display_center(line, 20, '▒')) ▒▒▒▒▒Table flip▒▒▒▒▒ ▒▒▒(╯°□°)╯︵ ┻━┻▒▒▒▒ ▒▒▒▒ちゃぶ台返し▒▒▒▒
[ "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
226,773
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 work, `codecs.charmap_decode` and `charmap_encode`. This function, given an encoding name, *defines* those boilerplate classes. """ # Make a bytestring of all 256 possible bytes. all_bytes = bytes(range(256)) # Get a list of what they would decode to in Latin-1. sloppy_chars = list(all_bytes.decode('latin-1')) # Get a list of what they decode to in the given encoding. Use the # replacement character for unassigned bytes. if PY26: decoded_chars = all_bytes.decode(encoding, 'replace') else: decoded_chars = all_bytes.decode(encoding, errors='replace') # Update the sloppy_chars list. Each byte that was successfully decoded # gets its decoded value in the list. The unassigned bytes are left as # they are, which gives their decoding in Latin-1. for i, char in enumerate(decoded_chars): if char != REPLACEMENT_CHAR: sloppy_chars[i] = char # For ftfy's own purposes, we're going to allow byte 1A, the "Substitute" # control code, to encode the Unicode replacement character U+FFFD. sloppy_chars[0x1a] = REPLACEMENT_CHAR # Create the data structures that tell the charmap methods how to encode # and decode in this sloppy encoding. decoding_table = ''.join(sloppy_chars) encoding_table = codecs.charmap_build(decoding_table) # Now produce all the class boilerplate. Look at the Python source for # `encodings.cp1252` for comparison; this is almost exactly the same, # except I made it follow pep8. class Codec(codecs.Codec): def encode(self, input, errors='strict'): return codecs.charmap_encode(input, errors, encoding_table) def decode(self, input, errors='strict'): return codecs.charmap_decode(input, errors, decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input, self.errors, encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input, self.errors, decoding_table)[0] class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass return codecs.CodecInfo( name='sloppy-' + encoding, encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
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 work, `codecs.charmap_decode` and `charmap_encode`. This function, given an encoding name, *defines* those boilerplate classes. """ # Make a bytestring of all 256 possible bytes. all_bytes = bytes(range(256)) # Get a list of what they would decode to in Latin-1. sloppy_chars = list(all_bytes.decode('latin-1')) # Get a list of what they decode to in the given encoding. Use the # replacement character for unassigned bytes. if PY26: decoded_chars = all_bytes.decode(encoding, 'replace') else: decoded_chars = all_bytes.decode(encoding, errors='replace') # Update the sloppy_chars list. Each byte that was successfully decoded # gets its decoded value in the list. The unassigned bytes are left as # they are, which gives their decoding in Latin-1. for i, char in enumerate(decoded_chars): if char != REPLACEMENT_CHAR: sloppy_chars[i] = char # For ftfy's own purposes, we're going to allow byte 1A, the "Substitute" # control code, to encode the Unicode replacement character U+FFFD. sloppy_chars[0x1a] = REPLACEMENT_CHAR # Create the data structures that tell the charmap methods how to encode # and decode in this sloppy encoding. decoding_table = ''.join(sloppy_chars) encoding_table = codecs.charmap_build(decoding_table) # Now produce all the class boilerplate. Look at the Python source for # `encodings.cp1252` for comparison; this is almost exactly the same, # except I made it follow pep8. class Codec(codecs.Codec): def encode(self, input, errors='strict'): return codecs.charmap_encode(input, errors, encoding_table) def decode(self, input, errors='strict'): return codecs.charmap_decode(input, errors, decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input, self.errors, encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input, self.errors, decoding_table)[0] class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass return codecs.CodecInfo( name='sloppy-' + encoding, encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
[ "def", "make_sloppy_codec", "(", "encoding", ")", ":", "# Make a bytestring of all 256 possible bytes.", "all_bytes", "=", "bytes", "(", "range", "(", "256", ")", ")", "# Get a list of what they would decode to in Latin-1.", "sloppy_chars", "=", "list", "(", "all_bytes", ...
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 `charmap_encode`. This function, given an encoding name, *defines* those boilerplate classes.
[ "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
226,774
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 diacritical mark on a digit or a space, for example. # You might put it on a Latin letter, but in that case there will almost # always be a pre-composed version, and we normalize to pre-composed # versions first. The cases that can't be pre-composed tend to be in # large scripts without case, which are in class C. groups.append('[^CM]M') # Match non-Latin characters adjacent to Latin characters. # # This is a simplification from ftfy version 2, which compared all # adjacent scripts. However, the ambiguities we need to resolve come from # encodings designed to represent Latin characters. groups.append('[Ll][AaC]') groups.append('[AaC][Ll]') # Match IPA letters next to capital letters. # # IPA uses lowercase letters only. Some accented capital letters next to # punctuation can accidentally decode as IPA letters, and an IPA letter # appearing next to a capital letter is a good sign that this happened. groups.append('[LA]i') groups.append('i[LA]') # Match non-combining diacritics. We've already set aside the common ones # like ^ (the CIRCUMFLEX ACCENT, repurposed as a caret, exponent sign, # or happy eye) and assigned them to category 'o'. The remaining ones, # like the diaeresis (¨), are pretty weird to see on their own instead # of combined with a letter. groups.append('2') # Match C1 control characters, which are almost always the result of # decoding Latin-1 that was meant to be Windows-1252. groups.append('X') # Match private use and unassigned characters. groups.append('P') groups.append('_') # Match adjacent characters from any different pair of these categories: # - Modifier marks (M) # - Letter modifiers (m) # - Miscellaneous numbers (N) # - Symbols (1 or 3, because 2 is already weird on its own) exclusive_categories = 'MmN13' for cat1 in exclusive_categories: others_range = ''.join(c for c in exclusive_categories if c != cat1) groups.append('{cat1}[{others_range}]'.format( cat1=cat1, others_range=others_range )) regex = '|'.join(groups) return re.compile(regex)
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 diacritical mark on a digit or a space, for example. # You might put it on a Latin letter, but in that case there will almost # always be a pre-composed version, and we normalize to pre-composed # versions first. The cases that can't be pre-composed tend to be in # large scripts without case, which are in class C. groups.append('[^CM]M') # Match non-Latin characters adjacent to Latin characters. # # This is a simplification from ftfy version 2, which compared all # adjacent scripts. However, the ambiguities we need to resolve come from # encodings designed to represent Latin characters. groups.append('[Ll][AaC]') groups.append('[AaC][Ll]') # Match IPA letters next to capital letters. # # IPA uses lowercase letters only. Some accented capital letters next to # punctuation can accidentally decode as IPA letters, and an IPA letter # appearing next to a capital letter is a good sign that this happened. groups.append('[LA]i') groups.append('i[LA]') # Match non-combining diacritics. We've already set aside the common ones # like ^ (the CIRCUMFLEX ACCENT, repurposed as a caret, exponent sign, # or happy eye) and assigned them to category 'o'. The remaining ones, # like the diaeresis (¨), are pretty weird to see on their own instead # of combined with a letter. groups.append('2') # Match C1 control characters, which are almost always the result of # decoding Latin-1 that was meant to be Windows-1252. groups.append('X') # Match private use and unassigned characters. groups.append('P') groups.append('_') # Match adjacent characters from any different pair of these categories: # - Modifier marks (M) # - Letter modifiers (m) # - Miscellaneous numbers (N) # - Symbols (1 or 3, because 2 is already weird on its own) exclusive_categories = 'MmN13' for cat1 in exclusive_categories: others_range = ''.join(c for c in exclusive_categories if c != cat1) groups.append('{cat1}[{others_range}]'.format( cat1=cat1, others_range=others_range )) regex = '|'.join(groups) return re.compile(regex)
[ "def", "_make_weirdness_regex", "(", ")", ":", "groups", "=", "[", "]", "# Match diacritical marks, except when they modify a non-cased letter or", "# another mark.", "#", "# You wouldn't put a diacritical mark on a digit or a space, for example.", "# You might put it on a Latin letter, bu...
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
226,775
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 characters that know what to do with them. The following things are deemed weird: - Lowercase letters followed by non-ASCII uppercase letters - Non-Latin characters next to Latin characters - Un-combined diacritical marks, unless they're stacking on non-alphabetic characters (in languages that do that kind of thing a lot) or other marks - C1 control characters - Adjacent symbols from any different pair of these categories: - Modifier marks - Letter modifiers - Non-digit numbers - Symbols (including math and currency) The return value is the number of instances of weirdness. """ text2 = unicodedata.normalize('NFC', text) weirdness = len(WEIRDNESS_RE.findall(chars_to_classes(text2))) adjustment = ( len(MOJIBAKE_SYMBOL_RE.findall(text2)) * 2 - len(COMMON_SYMBOL_RE.findall(text2)) ) return weirdness * 2 + adjustment
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 characters that know what to do with them. The following things are deemed weird: - Lowercase letters followed by non-ASCII uppercase letters - Non-Latin characters next to Latin characters - Un-combined diacritical marks, unless they're stacking on non-alphabetic characters (in languages that do that kind of thing a lot) or other marks - C1 control characters - Adjacent symbols from any different pair of these categories: - Modifier marks - Letter modifiers - Non-digit numbers - Symbols (including math and currency) The return value is the number of instances of weirdness. """ text2 = unicodedata.normalize('NFC', text) weirdness = len(WEIRDNESS_RE.findall(chars_to_classes(text2))) adjustment = ( len(MOJIBAKE_SYMBOL_RE.findall(text2)) * 2 - len(COMMON_SYMBOL_RE.findall(text2)) ) return weirdness * 2 + adjustment
[ "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 them. The following things are deemed weird: - Lowercase letters followed by non-ASCII uppercase letters - Non-Latin characters next to Latin characters - Un-combined diacritical marks, unless they're stacking on non-alphabetic characters (in languages that do that kind of thing a lot) or other marks - C1 control characters - Adjacent symbols from any different pair of these categories: - Modifier marks - Letter modifiers - Non-digit numbers - Symbols (including math and currency) The return value is the number of instances of weirdness.
[ "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
226,776
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 'sloppy-windows-NNNN' or 'sloppy-iso-8859-N', where the non-sloppy version is an encoding that leaves some bytes unmapped to characters. - The 'utf-8-variants' encoding, which has the several aliases seen above. """ if encoding in _CACHE: return _CACHE[encoding] norm_encoding = normalize_encoding(encoding) codec = None if norm_encoding in UTF8_VAR_NAMES: from ftfy.bad_codecs.utf8_variants import CODEC_INFO codec = CODEC_INFO elif norm_encoding.startswith('sloppy_'): from ftfy.bad_codecs.sloppy import CODECS codec = CODECS.get(norm_encoding) if codec is not None: _CACHE[encoding] = codec return codec
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 'sloppy-windows-NNNN' or 'sloppy-iso-8859-N', where the non-sloppy version is an encoding that leaves some bytes unmapped to characters. - The 'utf-8-variants' encoding, which has the several aliases seen above. """ if encoding in _CACHE: return _CACHE[encoding] norm_encoding = normalize_encoding(encoding) codec = None if norm_encoding in UTF8_VAR_NAMES: from ftfy.bad_codecs.utf8_variants import CODEC_INFO codec = CODEC_INFO elif norm_encoding.startswith('sloppy_'): from ftfy.bad_codecs.sloppy import CODECS codec = CODECS.get(norm_encoding) if codec is not None: _CACHE[encoding] = codec return codec
[ "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-N', where the non-sloppy version is an encoding that leaves some bytes unmapped to characters. - The 'utf-8-variants' encoding, which has the several aliases seen above.
[ "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
226,777
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 decoder to ensure correct behavior. `final` indicates whether this is the end of the sequence, in which case we should raise an error given incomplete input. Returns as much decoded text as possible, and the number of bytes consumed. """ # decoded_segments are the pieces of text we have decoded so far, # and position is our current position in the byte string. (Bytes # before this position have been consumed, and bytes after it have # yet to be decoded.) decoded_segments = [] position = 0 while True: # Use _buffer_decode_step to decode a segment of text. decoded, consumed = self._buffer_decode_step( input[position:], errors, final ) if consumed == 0: # Either there's nothing left to decode, or we need to wait # for more input. Either way, we're done for now. break # Append the decoded text to the list, and update our position. decoded_segments.append(decoded) position += consumed if final: # _buffer_decode_step must consume all the bytes when `final` is # true. assert position == len(input) return ''.join(decoded_segments), position
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 decoder to ensure correct behavior. `final` indicates whether this is the end of the sequence, in which case we should raise an error given incomplete input. Returns as much decoded text as possible, and the number of bytes consumed. """ # decoded_segments are the pieces of text we have decoded so far, # and position is our current position in the byte string. (Bytes # before this position have been consumed, and bytes after it have # yet to be decoded.) decoded_segments = [] position = 0 while True: # Use _buffer_decode_step to decode a segment of text. decoded, consumed = self._buffer_decode_step( input[position:], errors, final ) if consumed == 0: # Either there's nothing left to decode, or we need to wait # for more input. Either way, we're done for now. break # Append the decoded text to the list, and update our position. decoded_segments.append(decoded) position += consumed if final: # _buffer_decode_step must consume all the bytes when `final` is # true. assert position == len(input) return ''.join(decoded_segments), position
[ "def", "_buffer_decode", "(", "self", ",", "input", ",", "errors", ",", "final", ")", ":", "# decoded_segments are the pieces of text we have decoded so far,", "# and position is our current position in the byte string. (Bytes", "# before this position have been consumed, and bytes after...
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 this is the end of the sequence, in which case we should raise an error given incomplete input. Returns as much decoded text as possible, and the number of bytes consumed.
[ "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
226,778
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 number now appears in this form: 11101101 1010abcd 10efghij 11101101 1011klmn 10opqrst The CESU8_RE above matches byte sequences of this form. Then we need to extract the bits and assemble a codepoint number from them. """ if len(input) < 6: if final: # We found 0xed near the end of the stream, and there aren't # six bytes to decode. Delegate to the superclass method to # handle it as normal UTF-8. It might be a Hangul character # or an error. return sup(input, errors, final) else: # We found a surrogate, the stream isn't over yet, and we don't # know enough of the following bytes to decode anything, so # consume zero bytes and wait. return '', 0 else: if CESU8_RE.match(input): # Given this is a CESU-8 sequence, do some math to pull out # the intended 20-bit value, and consume six bytes. codepoint = ( ((input[1] & 0x0f) << 16) + ((input[2] & 0x3f) << 10) + ((input[4] & 0x0f) << 6) + (input[5] & 0x3f) + 0x10000 ) return chr(codepoint), 6 else: # This looked like a CESU-8 sequence, but it wasn't one. # 0xed indicates the start of a three-byte sequence, so give # three bytes to the superclass to decode as usual. return sup(input[:3], errors, False)
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 number now appears in this form: 11101101 1010abcd 10efghij 11101101 1011klmn 10opqrst The CESU8_RE above matches byte sequences of this form. Then we need to extract the bits and assemble a codepoint number from them. """ if len(input) < 6: if final: # We found 0xed near the end of the stream, and there aren't # six bytes to decode. Delegate to the superclass method to # handle it as normal UTF-8. It might be a Hangul character # or an error. return sup(input, errors, final) else: # We found a surrogate, the stream isn't over yet, and we don't # know enough of the following bytes to decode anything, so # consume zero bytes and wait. return '', 0 else: if CESU8_RE.match(input): # Given this is a CESU-8 sequence, do some math to pull out # the intended 20-bit value, and consume six bytes. codepoint = ( ((input[1] & 0x0f) << 16) + ((input[2] & 0x3f) << 10) + ((input[4] & 0x0f) << 6) + (input[5] & 0x3f) + 0x10000 ) return chr(codepoint), 6 else: # This looked like a CESU-8 sequence, but it wasn't one. # 0xed indicates the start of a three-byte sequence, so give # three bytes to the superclass to decode as usual. return sup(input[:3], errors, False)
[ "def", "_buffer_decode_surrogates", "(", "sup", ",", "input", ",", "errors", ",", "final", ")", ":", "if", "len", "(", "input", ")", "<", "6", ":", "if", "final", ":", "# We found 0xed near the end of the stream, and there aren't", "# six bytes to decode. Delegate to ...
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 11101101 1011klmn 10opqrst The CESU8_RE above matches byte sequences of this form. Then we need to extract the bits and assemble a codepoint number from them.
[ "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
226,779
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=True, remove_control_chars=True, remove_bom=True, normalization='NFC', max_decode_length=10**6): 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&hellip; it&#x2019;s flubberific!', ... normalization='NFKC')) Broken text... it's flubberific! >>> print(fix_text('HTML entities &lt;3')) HTML entities <3 >>> print(fix_text('<em>HTML entities &lt;3</em>')) <em>HTML entities &lt;3</em> >>> print(fix_text("&macr;\\_(ã\x83\x84)_/&macr;")) ¯\_(ツ)_/¯ >>> # This example string starts with a byte-order mark, even if >>> # you can't see it on the Web. >>> print(fix_text('\ufeffParty like\nit&rsquo;s 1999!')) Party like it's 1999! >>> print(fix_text('LOUD NOISES')) LOUD NOISES >>> len(fix_text('fi' * 100000)) 200000 >>> len(fix_text('')) 0 Based on the options you provide, ftfy applies these steps in order: - If `remove_terminal_escapes` is True, remove sequences of bytes that are instructions for Unix terminals, such as the codes that make text appear in different colors. - If `fix_encoding` is True, look for common mistakes that come from encoding or decoding Unicode text incorrectly, and fix them if they are reasonably fixable. See `fixes.fix_encoding` for details. - If `fix_entities` is True, replace HTML entities with their equivalent characters. If it's "auto" (the default), then consider replacing HTML entities, but don't do so in text where you have seen a pair of actual angle brackets (that's probably actually HTML and you shouldn't mess with the entities). - If `uncurl_quotes` is True, replace various curly quotation marks with plain-ASCII straight quotes. - If `fix_latin_ligatures` is True, then ligatures made of Latin letters, such as `fi`, will be separated into individual letters. These ligatures are usually not meaningful outside of font rendering, and often represent copy-and-paste errors. - If `fix_character_width` is True, half-width and full-width characters will be replaced by their standard-width form. - If `fix_line_breaks` is true, convert all line breaks to Unix style (CRLF and CR line breaks become LF line breaks). - If `fix_surrogates` is true, ensure that there are no UTF-16 surrogates in the resulting string, by converting them to the correct characters when they're appropriately paired, or replacing them with \ufffd otherwise. - If `remove_control_chars` is true, remove control characters that are not suitable for use in text. This includes most of the ASCII control characters, plus some Unicode controls such as the byte order mark (U+FEFF). Useful control characters, such as Tab, Line Feed, and bidirectional marks, are left as they are. - If `remove_bom` is True, remove the Byte-Order Mark at the start of the string if it exists. (This is largely redundant, because it's a special case of `remove_control_characters`. This option will become deprecated in a later version.) - If `normalization` is not None, apply the specified form of Unicode normalization, which can be one of 'NFC', 'NFKC', 'NFD', and 'NFKD'. - The default normalization, NFC, combines characters and diacritics that are written using separate code points, such as converting "e" plus an acute accent modifier into "é", or converting "ka" (か) plus a dakuten into the single character "ga" (が). Unicode can be converted to NFC form without any change in its meaning. - If you ask for NFKC normalization, it will apply additional normalizations that can change the meanings of characters. For example, ellipsis characters will be replaced with three periods, all ligatures will be replaced with the individual characters that make them up, and characters that differ in font style will be converted to the same character. - If anything was changed, repeat all the steps, so that the function is idempotent. "&amp;amp;" will become "&", for example, not "&amp;". `fix_text` will work one line at a time, with the possibility that some lines are in different encodings, allowing it to fix text that has been concatenated together from different sources. When it encounters lines longer than `max_decode_length` (1 million codepoints by default), it will not run the `fix_encoding` step, to avoid unbounded slowdowns. If you're certain that any decoding errors in the text would have affected the entire text in the same way, and you don't mind operations that scale with the length of the text, you can use `fix_text_segment` directly to fix the whole string in one batch. """ if isinstance(text, bytes): raise UnicodeError(fixes.BYTES_ERROR_TEXT) out = [] pos = 0 while pos < len(text): textbreak = text.find('\n', pos) + 1 fix_encoding_this_time = fix_encoding if textbreak == 0: textbreak = len(text) if (textbreak - pos) > max_decode_length: fix_encoding_this_time = False substring = text[pos:textbreak] if fix_entities == 'auto' and '<' in substring and '>' in substring: # we see angle brackets together; this could be HTML fix_entities = False out.append( fix_text_segment( substring, fix_entities=fix_entities, remove_terminal_escapes=remove_terminal_escapes, fix_encoding=fix_encoding_this_time, uncurl_quotes=uncurl_quotes, fix_latin_ligatures=fix_latin_ligatures, fix_character_width=fix_character_width, fix_line_breaks=fix_line_breaks, fix_surrogates=fix_surrogates, remove_control_chars=remove_control_chars, remove_bom=remove_bom, normalization=normalization ) ) pos = textbreak return ''.join(out)
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=True, remove_control_chars=True, remove_bom=True, normalization='NFC', max_decode_length=10**6): 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&hellip; it&#x2019;s flubberific!', ... normalization='NFKC')) Broken text... it's flubberific! >>> print(fix_text('HTML entities &lt;3')) HTML entities <3 >>> print(fix_text('<em>HTML entities &lt;3</em>')) <em>HTML entities &lt;3</em> >>> print(fix_text("&macr;\\_(ã\x83\x84)_/&macr;")) ¯\_(ツ)_/¯ >>> # This example string starts with a byte-order mark, even if >>> # you can't see it on the Web. >>> print(fix_text('\ufeffParty like\nit&rsquo;s 1999!')) Party like it's 1999! >>> print(fix_text('LOUD NOISES')) LOUD NOISES >>> len(fix_text('fi' * 100000)) 200000 >>> len(fix_text('')) 0 Based on the options you provide, ftfy applies these steps in order: - If `remove_terminal_escapes` is True, remove sequences of bytes that are instructions for Unix terminals, such as the codes that make text appear in different colors. - If `fix_encoding` is True, look for common mistakes that come from encoding or decoding Unicode text incorrectly, and fix them if they are reasonably fixable. See `fixes.fix_encoding` for details. - If `fix_entities` is True, replace HTML entities with their equivalent characters. If it's "auto" (the default), then consider replacing HTML entities, but don't do so in text where you have seen a pair of actual angle brackets (that's probably actually HTML and you shouldn't mess with the entities). - If `uncurl_quotes` is True, replace various curly quotation marks with plain-ASCII straight quotes. - If `fix_latin_ligatures` is True, then ligatures made of Latin letters, such as `fi`, will be separated into individual letters. These ligatures are usually not meaningful outside of font rendering, and often represent copy-and-paste errors. - If `fix_character_width` is True, half-width and full-width characters will be replaced by their standard-width form. - If `fix_line_breaks` is true, convert all line breaks to Unix style (CRLF and CR line breaks become LF line breaks). - If `fix_surrogates` is true, ensure that there are no UTF-16 surrogates in the resulting string, by converting them to the correct characters when they're appropriately paired, or replacing them with \ufffd otherwise. - If `remove_control_chars` is true, remove control characters that are not suitable for use in text. This includes most of the ASCII control characters, plus some Unicode controls such as the byte order mark (U+FEFF). Useful control characters, such as Tab, Line Feed, and bidirectional marks, are left as they are. - If `remove_bom` is True, remove the Byte-Order Mark at the start of the string if it exists. (This is largely redundant, because it's a special case of `remove_control_characters`. This option will become deprecated in a later version.) - If `normalization` is not None, apply the specified form of Unicode normalization, which can be one of 'NFC', 'NFKC', 'NFD', and 'NFKD'. - The default normalization, NFC, combines characters and diacritics that are written using separate code points, such as converting "e" plus an acute accent modifier into "é", or converting "ka" (か) plus a dakuten into the single character "ga" (が). Unicode can be converted to NFC form without any change in its meaning. - If you ask for NFKC normalization, it will apply additional normalizations that can change the meanings of characters. For example, ellipsis characters will be replaced with three periods, all ligatures will be replaced with the individual characters that make them up, and characters that differ in font style will be converted to the same character. - If anything was changed, repeat all the steps, so that the function is idempotent. "&amp;amp;" will become "&", for example, not "&amp;". `fix_text` will work one line at a time, with the possibility that some lines are in different encodings, allowing it to fix text that has been concatenated together from different sources. When it encounters lines longer than `max_decode_length` (1 million codepoints by default), it will not run the `fix_encoding` step, to avoid unbounded slowdowns. If you're certain that any decoding errors in the text would have affected the entire text in the same way, and you don't mind operations that scale with the length of the text, you can use `fix_text_segment` directly to fix the whole string in one batch. """ if isinstance(text, bytes): raise UnicodeError(fixes.BYTES_ERROR_TEXT) out = [] pos = 0 while pos < len(text): textbreak = text.find('\n', pos) + 1 fix_encoding_this_time = fix_encoding if textbreak == 0: textbreak = len(text) if (textbreak - pos) > max_decode_length: fix_encoding_this_time = False substring = text[pos:textbreak] if fix_entities == 'auto' and '<' in substring and '>' in substring: # we see angle brackets together; this could be HTML fix_entities = False out.append( fix_text_segment( substring, fix_entities=fix_entities, remove_terminal_escapes=remove_terminal_escapes, fix_encoding=fix_encoding_this_time, uncurl_quotes=uncurl_quotes, fix_latin_ligatures=fix_latin_ligatures, fix_character_width=fix_character_width, fix_line_breaks=fix_line_breaks, fix_surrogates=fix_surrogates, remove_control_chars=remove_control_chars, remove_bom=remove_bom, normalization=normalization ) ) pos = textbreak return ''.join(out)
[ "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&hellip; it&#x2019;s flubberific!', ... normalization='NFKC')) Broken text... it's flubberific! >>> print(fix_text('HTML entities &lt;3')) HTML entities <3 >>> print(fix_text('<em>HTML entities &lt;3</em>')) <em>HTML entities &lt;3</em> >>> print(fix_text("&macr;\\_(ã\x83\x84)_/&macr;")) ¯\_(ツ)_/¯ >>> # This example string starts with a byte-order mark, even if >>> # you can't see it on the Web. >>> print(fix_text('\ufeffParty like\nit&rsquo;s 1999!')) Party like it's 1999! >>> print(fix_text('LOUD NOISES')) LOUD NOISES >>> len(fix_text('fi' * 100000)) 200000 >>> len(fix_text('')) 0 Based on the options you provide, ftfy applies these steps in order: - If `remove_terminal_escapes` is True, remove sequences of bytes that are instructions for Unix terminals, such as the codes that make text appear in different colors. - If `fix_encoding` is True, look for common mistakes that come from encoding or decoding Unicode text incorrectly, and fix them if they are reasonably fixable. See `fixes.fix_encoding` for details. - If `fix_entities` is True, replace HTML entities with their equivalent characters. If it's "auto" (the default), then consider replacing HTML entities, but don't do so in text where you have seen a pair of actual angle brackets (that's probably actually HTML and you shouldn't mess with the entities). - If `uncurl_quotes` is True, replace various curly quotation marks with plain-ASCII straight quotes. - If `fix_latin_ligatures` is True, then ligatures made of Latin letters, such as `fi`, will be separated into individual letters. These ligatures are usually not meaningful outside of font rendering, and often represent copy-and-paste errors. - If `fix_character_width` is True, half-width and full-width characters will be replaced by their standard-width form. - If `fix_line_breaks` is true, convert all line breaks to Unix style (CRLF and CR line breaks become LF line breaks). - If `fix_surrogates` is true, ensure that there are no UTF-16 surrogates in the resulting string, by converting them to the correct characters when they're appropriately paired, or replacing them with \ufffd otherwise. - If `remove_control_chars` is true, remove control characters that are not suitable for use in text. This includes most of the ASCII control characters, plus some Unicode controls such as the byte order mark (U+FEFF). Useful control characters, such as Tab, Line Feed, and bidirectional marks, are left as they are. - If `remove_bom` is True, remove the Byte-Order Mark at the start of the string if it exists. (This is largely redundant, because it's a special case of `remove_control_characters`. This option will become deprecated in a later version.) - If `normalization` is not None, apply the specified form of Unicode normalization, which can be one of 'NFC', 'NFKC', 'NFD', and 'NFKD'. - The default normalization, NFC, combines characters and diacritics that are written using separate code points, such as converting "e" plus an acute accent modifier into "é", or converting "ka" (か) plus a dakuten into the single character "ga" (が). Unicode can be converted to NFC form without any change in its meaning. - If you ask for NFKC normalization, it will apply additional normalizations that can change the meanings of characters. For example, ellipsis characters will be replaced with three periods, all ligatures will be replaced with the individual characters that make them up, and characters that differ in font style will be converted to the same character. - If anything was changed, repeat all the steps, so that the function is idempotent. "&amp;amp;" will become "&", for example, not "&amp;". `fix_text` will work one line at a time, with the possibility that some lines are in different encodings, allowing it to fix text that has been concatenated together from different sources. When it encounters lines longer than `max_decode_length` (1 million codepoints by default), it will not run the `fix_encoding` step, to avoid unbounded slowdowns. If you're certain that any decoding errors in the text would have affected the entire text in the same way, and you don't mind operations that scale with the length of the text, you can use `fix_text_segment` directly to fix the whole string in one batch.
[ "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
226,780
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=True, fix_surrogates=True, remove_control_chars=True, remove_bom=True, normalization='NFC'): """ 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` function for how this is done. The output is a stream of fixed lines of text. """ entities = fix_entities for line in input_file: if isinstance(line, bytes): if encoding is None: line, encoding = guess_bytes(line) else: line = line.decode(encoding) if fix_entities == 'auto' and '<' in line and '>' in line: entities = False yield fix_text_segment( line, fix_entities=entities, remove_terminal_escapes=remove_terminal_escapes, fix_encoding=fix_encoding, fix_latin_ligatures=fix_latin_ligatures, fix_character_width=fix_character_width, uncurl_quotes=uncurl_quotes, fix_line_breaks=fix_line_breaks, fix_surrogates=fix_surrogates, remove_control_chars=remove_control_chars, remove_bom=remove_bom, normalization=normalization )
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=True, fix_surrogates=True, remove_control_chars=True, remove_bom=True, normalization='NFC'): """ 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` function for how this is done. The output is a stream of fixed lines of text. """ entities = fix_entities for line in input_file: if isinstance(line, bytes): if encoding is None: line, encoding = guess_bytes(line) else: line = line.decode(encoding) if fix_entities == 'auto' and '<' in line and '>' in line: entities = False yield fix_text_segment( line, fix_entities=entities, remove_terminal_escapes=remove_terminal_escapes, fix_encoding=fix_encoding, fix_latin_ligatures=fix_latin_ligatures, fix_character_width=fix_character_width, uncurl_quotes=uncurl_quotes, fix_line_breaks=fix_line_breaks, fix_surrogates=fix_surrogates, remove_control_chars=remove_control_chars, remove_bom=remove_bom, normalization=normalization )
[ "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` function for how this is done. The output is a stream of fixed lines of text.
[ "Fix", "text", "that", "is", "found", "in", "a", "file", "." ]
476acc6ad270bffe07f97d4f7cf2139acdc69633
https://github.com/LuminosoInsight/python-ftfy/blob/476acc6ad270bffe07f97d4f7cf2139acdc69633/ftfy/__init__.py#L195-L241
train
226,781
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, fix_line_breaks=True, fix_surrogates=True, remove_control_chars=True, remove_bom=True, normalization='NFC'): """ 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. """ if isinstance(text, bytes): raise UnicodeError(fixes.BYTES_ERROR_TEXT) if fix_entities == 'auto' and '<' in text and '>' in text: fix_entities = False while True: origtext = text if remove_terminal_escapes: text = fixes.remove_terminal_escapes(text) if fix_encoding: text = fixes.fix_encoding(text) if fix_entities: text = fixes.unescape_html(text) if fix_latin_ligatures: text = fixes.fix_latin_ligatures(text) if fix_character_width: text = fixes.fix_character_width(text) if uncurl_quotes: text = fixes.uncurl_quotes(text) if fix_line_breaks: text = fixes.fix_line_breaks(text) if fix_surrogates: text = fixes.fix_surrogates(text) if remove_control_chars: text = fixes.remove_control_chars(text) if remove_bom and not remove_control_chars: # Skip this step if we've already done `remove_control_chars`, # because it would be redundant. text = fixes.remove_bom(text) if normalization is not None: text = unicodedata.normalize(normalization, text) if text == origtext: return text
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, fix_line_breaks=True, fix_surrogates=True, remove_control_chars=True, remove_bom=True, normalization='NFC'): """ 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. """ if isinstance(text, bytes): raise UnicodeError(fixes.BYTES_ERROR_TEXT) if fix_entities == 'auto' and '<' in text and '>' in text: fix_entities = False while True: origtext = text if remove_terminal_escapes: text = fixes.remove_terminal_escapes(text) if fix_encoding: text = fixes.fix_encoding(text) if fix_entities: text = fixes.unescape_html(text) if fix_latin_ligatures: text = fixes.fix_latin_ligatures(text) if fix_character_width: text = fixes.fix_character_width(text) if uncurl_quotes: text = fixes.uncurl_quotes(text) if fix_line_breaks: text = fixes.fix_line_breaks(text) if fix_surrogates: text = fixes.fix_surrogates(text) if remove_control_chars: text = fixes.remove_control_chars(text) if remove_bom and not remove_control_chars: # Skip this step if we've already done `remove_control_chars`, # because it would be redundant. text = fixes.remove_bom(text) if normalization is not None: text = unicodedata.normalize(normalization, text) if text == origtext: return text
[ "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
226,782
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('(╯°□°)╯︵ ┻━┻') U+0028 ( [Ps] LEFT PARENTHESIS U+256F ╯ [So] BOX DRAWINGS LIGHT ARC UP AND LEFT U+00B0 ° [So] DEGREE SIGN U+25A1 □ [So] WHITE SQUARE U+00B0 ° [So] DEGREE SIGN U+0029 ) [Pe] RIGHT PARENTHESIS U+256F ╯ [So] BOX DRAWINGS LIGHT ARC UP AND LEFT U+FE35 ︵ [Ps] PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS U+0020 [Zs] SPACE U+253B ┻ [So] BOX DRAWINGS HEAVY UP AND HORIZONTAL U+2501 ━ [So] BOX DRAWINGS HEAVY HORIZONTAL U+253B ┻ [So] BOX DRAWINGS HEAVY UP AND HORIZONTAL """ for char in text: if char.isprintable(): display = char else: display = char.encode('unicode-escape').decode('ascii') print('U+{code:04X} {display} [{category}] {name}'.format( display=display_ljust(display, 7), code=ord(char), category=unicodedata.category(char), name=unicodedata.name(char, '<unknown>') ))
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('(╯°□°)╯︵ ┻━┻') U+0028 ( [Ps] LEFT PARENTHESIS U+256F ╯ [So] BOX DRAWINGS LIGHT ARC UP AND LEFT U+00B0 ° [So] DEGREE SIGN U+25A1 □ [So] WHITE SQUARE U+00B0 ° [So] DEGREE SIGN U+0029 ) [Pe] RIGHT PARENTHESIS U+256F ╯ [So] BOX DRAWINGS LIGHT ARC UP AND LEFT U+FE35 ︵ [Ps] PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS U+0020 [Zs] SPACE U+253B ┻ [So] BOX DRAWINGS HEAVY UP AND HORIZONTAL U+2501 ━ [So] BOX DRAWINGS HEAVY HORIZONTAL U+253B ┻ [So] BOX DRAWINGS HEAVY UP AND HORIZONTAL """ for char in text: if char.isprintable(): display = char else: display = char.encode('unicode-escape').decode('ascii') print('U+{code:04X} {display} [{category}] {name}'.format( display=display_ljust(display, 7), code=ord(char), category=unicodedata.category(char), name=unicodedata.name(char, '<unknown>') ))
[ "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] LEFT PARENTHESIS U+256F ╯ [So] BOX DRAWINGS LIGHT ARC UP AND LEFT U+00B0 ° [So] DEGREE SIGN U+25A1 □ [So] WHITE SQUARE U+00B0 ° [So] DEGREE SIGN U+0029 ) [Pe] RIGHT PARENTHESIS U+256F ╯ [So] BOX DRAWINGS LIGHT ARC UP AND LEFT U+FE35 ︵ [Ps] PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS U+0020 [Zs] SPACE U+253B ┻ [So] BOX DRAWINGS HEAVY UP AND HORIZONTAL U+2501 ━ [So] BOX DRAWINGS HEAVY HORIZONTAL U+253B ┻ [So] BOX DRAWINGS HEAVY UP AND HORIZONTAL
[ "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
226,783
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 matches ASCII text. encoding_regexes = {'ascii': re.compile('^[\x00-\x7f]*$')} for encoding in CHARMAP_ENCODINGS: # Make a sequence of characters that bytes \x80 to \xFF decode to # in each encoding, as well as byte \x1A, which is used to represent # the replacement character � in the sloppy-* encodings. byte_range = bytes(list(range(0x80, 0x100)) + [0x1a]) charlist = byte_range.decode(encoding) # The rest of the ASCII bytes -- bytes \x00 to \x19 and \x1B # to \x7F -- will decode as those ASCII characters in any encoding we # support, so we can just include them as ranges. This also lets us # not worry about escaping regex special characters, because all of # them are in the \x1B to \x7F range. regex = '^[\x00-\x19\x1b-\x7f{0}]*$'.format(charlist) encoding_regexes[encoding] = re.compile(regex) return encoding_regexes
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 matches ASCII text. encoding_regexes = {'ascii': re.compile('^[\x00-\x7f]*$')} for encoding in CHARMAP_ENCODINGS: # Make a sequence of characters that bytes \x80 to \xFF decode to # in each encoding, as well as byte \x1A, which is used to represent # the replacement character � in the sloppy-* encodings. byte_range = bytes(list(range(0x80, 0x100)) + [0x1a]) charlist = byte_range.decode(encoding) # The rest of the ASCII bytes -- bytes \x00 to \x19 and \x1B # to \x7F -- will decode as those ASCII characters in any encoding we # support, so we can just include them as ranges. This also lets us # not worry about escaping regex special characters, because all of # them are in the \x1B to \x7F range. regex = '^[\x00-\x19\x1b-\x7f{0}]*$'.format(charlist) encoding_regexes[encoding] = re.compile(regex) return encoding_regexes
[ "def", "_build_regexes", "(", ")", ":", "# Define a regex that matches ASCII text.", "encoding_regexes", "=", "{", "'ascii'", ":", "re", ".", "compile", "(", "'^[\\x00-\\x7f]*$'", ")", "}", "for", "encoding", "in", "CHARMAP_ENCODINGS", ":", "# Make a sequence of charact...
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
226,784
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 in the dictionary. width_map = {0x3000: ' '} for i in range(0xff01, 0xfff0): char = chr(i) alternate = unicodedata.normalize('NFKC', char) if alternate != char: width_map[i] = alternate return width_map
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 in the dictionary. width_map = {0x3000: ' '} for i in range(0xff01, 0xfff0): char = chr(i) alternate = unicodedata.normalize('NFKC', char) if alternate != char: width_map[i] = alternate return width_map
[ "def", "_build_width_map", "(", ")", ":", "# 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 in the dictionary.", "width_map", "=", "{", "0x3000", ":", "' '", "}", "for", ...
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
226,785
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) - None: mode settings are ignored This call is equivalent to the `vmlSetMode()` in the VML library. See: http://www.intel.com/software/products/mkl/docs/webhelp/vml/vml_DataTypesAccuracyModes.html for more info on the accuracy modes. Returns old accuracy settings. """ if use_vml: acc_dict = {None: 0, 'low': 1, 'high': 2, 'fast': 3} acc_reverse_dict = {1: 'low', 2: 'high', 3: 'fast'} if mode not in acc_dict.keys(): raise ValueError( "mode argument must be one of: None, 'high', 'low', 'fast'") retval = _set_vml_accuracy_mode(acc_dict.get(mode, 0)) return acc_reverse_dict.get(retval) else: return None
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) - None: mode settings are ignored This call is equivalent to the `vmlSetMode()` in the VML library. See: http://www.intel.com/software/products/mkl/docs/webhelp/vml/vml_DataTypesAccuracyModes.html for more info on the accuracy modes. Returns old accuracy settings. """ if use_vml: acc_dict = {None: 0, 'low': 1, 'high': 2, 'fast': 3} acc_reverse_dict = {1: 'low', 2: 'high', 3: 'fast'} if mode not in acc_dict.keys(): raise ValueError( "mode argument must be one of: None, 'high', 'low', 'fast'") retval = _set_vml_accuracy_mode(acc_dict.get(mode, 0)) return acc_reverse_dict.get(retval) else: return None
[ "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 call is equivalent to the `vmlSetMode()` in the VML library. See: http://www.intel.com/software/products/mkl/docs/webhelp/vml/vml_DataTypesAccuracyModes.html for more info on the accuracy modes. Returns old accuracy settings.
[ "Set", "the", "accuracy", "mode", "for", "VML", "operations", "." ]
364bac13d84524e0e01db892301b2959d822dcff
https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/utils.py#L34-L62
train
226,786
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-specific short-circuits 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 number of threads can be changed using the "set_num_threads" ' 'function.') set_num_threads(1) return 1 env_configured = False n_cores = detect_number_of_cores() if 'NUMEXPR_MAX_THREADS' in os.environ: # The user has configured NumExpr in the expected way, so suppress logs. env_configured = True n_cores = MAX_THREADS else: # The use has not set 'NUMEXPR_MAX_THREADS', so likely they have not # configured NumExpr as desired, so we emit info logs. if n_cores > MAX_THREADS: log.info('Note: detected %d virtual cores but NumExpr set to maximum of %d, check "NUMEXPR_MAX_THREADS" environment variable.'%(n_cores, MAX_THREADS)) if n_cores > 8: # The historical 'safety' limit. log.info('Note: NumExpr detected %d cores but "NUMEXPR_MAX_THREADS" not set, so enforcing safe limit of 8.'%n_cores) n_cores = 8 # Now we check for 'NUMEXPR_NUM_THREADS' or 'OMP_NUM_THREADS' to set the # actual number of threads used. if 'NUMEXPR_NUM_THREADS' in os.environ: requested_threads = int(os.environ['NUMEXPR_NUM_THREADS']) elif 'OMP_NUM_THREADS' in os.environ: requested_threads = int(os.environ['OMP_NUM_THREADS']) else: requested_threads = n_cores if not env_configured: log.info('NumExpr defaulting to %d threads.'%n_cores) # The C-extension function performs its own checks against `MAX_THREADS` set_num_threads(requested_threads) return requested_threads
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-specific short-circuits 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 number of threads can be changed using the "set_num_threads" ' 'function.') set_num_threads(1) return 1 env_configured = False n_cores = detect_number_of_cores() if 'NUMEXPR_MAX_THREADS' in os.environ: # The user has configured NumExpr in the expected way, so suppress logs. env_configured = True n_cores = MAX_THREADS else: # The use has not set 'NUMEXPR_MAX_THREADS', so likely they have not # configured NumExpr as desired, so we emit info logs. if n_cores > MAX_THREADS: log.info('Note: detected %d virtual cores but NumExpr set to maximum of %d, check "NUMEXPR_MAX_THREADS" environment variable.'%(n_cores, MAX_THREADS)) if n_cores > 8: # The historical 'safety' limit. log.info('Note: NumExpr detected %d cores but "NUMEXPR_MAX_THREADS" not set, so enforcing safe limit of 8.'%n_cores) n_cores = 8 # Now we check for 'NUMEXPR_NUM_THREADS' or 'OMP_NUM_THREADS' to set the # actual number of threads used. if 'NUMEXPR_NUM_THREADS' in os.environ: requested_threads = int(os.environ['NUMEXPR_NUM_THREADS']) elif 'OMP_NUM_THREADS' in os.environ: requested_threads = int(os.environ['OMP_NUM_THREADS']) else: requested_threads = n_cores if not env_configured: log.info('NumExpr defaulting to %d threads.'%n_cores) # The C-extension function performs its own checks against `MAX_THREADS` set_num_threads(requested_threads) return requested_threads
[ "def", "_init_num_threads", "(", ")", ":", "# Any platform-specific short-circuits", "if", "'sparc'", "in", "platform", ".", "machine", "(", ")", ":", "log", ".", "warning", "(", "'The number of threads have been set to 1 because problems related '", "'to threading have been ...
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
226,787
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 isinstance(ncpus, int) and ncpus > 0: return ncpus else: # OSX: return int(subprocess.check_output(["sysctl", "-n", "hw.ncpu"])) # Windows: try: ncpus = int(os.environ.get("NUMBER_OF_PROCESSORS", "")) if ncpus > 0: return ncpus except ValueError: pass return 1
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 isinstance(ncpus, int) and ncpus > 0: return ncpus else: # OSX: return int(subprocess.check_output(["sysctl", "-n", "hw.ncpu"])) # Windows: try: ncpus = int(os.environ.get("NUMBER_OF_PROCESSORS", "")) if ncpus > 0: return ncpus except ValueError: pass return 1
[ "def", "detect_number_of_cores", "(", ")", ":", "# Linux, Unix and MacOS:", "if", "hasattr", "(", "os", ",", "\"sysconf\"", ")", ":", "if", "\"SC_NPROCESSORS_ONLN\"", "in", "os", ".", "sysconf_names", ":", "# Linux & Unix:", "ncpus", "=", "os", ".", "sysconf", "...
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
226,788
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): assert len(args) > 0 assert all(len(a.flat) == len(args[0].flat) for a in args) nelements = len(args[0].flat) nchunks, remain = divmod(nelements, chunksize) out = np.ndarray(args[0].shape) for start in range(0, nelements, chunksize): #print(start) stop = start+chunksize if start+chunksize > nelements: stop = nelements-start iargs = tuple(a.flat[start:stop] for a in args) out.flat[start:stop] = func(*iargs) return out return wrap return chunkifier
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): assert len(args) > 0 assert all(len(a.flat) == len(args[0].flat) for a in args) nelements = len(args[0].flat) nchunks, remain = divmod(nelements, chunksize) out = np.ndarray(args[0].shape) for start in range(0, nelements, chunksize): #print(start) stop = start+chunksize if start+chunksize > nelements: stop = nelements-start iargs = tuple(a.flat[start:stop] for a in args) out.flat[start:stop] = func(*iargs) return out return wrap return chunkifier
[ "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
226,789
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) for c in ex.children])
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) for c in ex.children])
[ "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
226,790
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 elif s[0] == 's': # numbers shall not be cast to strings for y in sigPerms(s[1:]): yield 's' + y else: yield s
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 elif s[0] == 's': # numbers shall not be cast to strings for y in sigPerms(s[1:]): yield 's' + y else: yield s
[ "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
226,791
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.typecode() for x in list(ast.children)) # Find some operation that will work on an acceptable casting of args. for sig in sigPerms(basesig): value = (ast.value + '_' + retsig + sig).encode('ascii') if value in interpreter.opcodes: break else: for sig in sigPerms(basesig): funcname = (ast.value + '_' + retsig + sig).encode('ascii') if funcname in interpreter.funccodes: value = ('func_%sn' % (retsig + sig)).encode('ascii') children += [ASTNode('raw', 'none', interpreter.funccodes[funcname])] break else: raise NotImplementedError( "couldn't find matching opcode for '%s'" % (ast.value + '_' + retsig + basesig)) # First just cast constants, then cast variables if necessary: for i, (have, want) in enumerate(zip(basesig, sig)): if have != want: kind = typecode_to_kind[want] if children[i].astType == 'constant': children[i] = ASTNode('constant', kind, children[i].value) else: opname = "cast" children[i] = ASTNode('op', kind, opname, [children[i]]) else: value = ast.value children = ast.children return ASTNode(ast.astType, ast.astKind, value, [typeCompileAst(c) for c in children])
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.typecode() for x in list(ast.children)) # Find some operation that will work on an acceptable casting of args. for sig in sigPerms(basesig): value = (ast.value + '_' + retsig + sig).encode('ascii') if value in interpreter.opcodes: break else: for sig in sigPerms(basesig): funcname = (ast.value + '_' + retsig + sig).encode('ascii') if funcname in interpreter.funccodes: value = ('func_%sn' % (retsig + sig)).encode('ascii') children += [ASTNode('raw', 'none', interpreter.funccodes[funcname])] break else: raise NotImplementedError( "couldn't find matching opcode for '%s'" % (ast.value + '_' + retsig + basesig)) # First just cast constants, then cast variables if necessary: for i, (have, want) in enumerate(zip(basesig, sig)): if have != want: kind = typecode_to_kind[want] if children[i].astType == 'constant': children[i] = ASTNode('constant', kind, children[i].value) else: opname = "cast" children[i] = ASTNode('op', kind, opname, [children[i]]) else: value = ast.value children = ast.children return ASTNode(ast.astType, ast.astKind, value, [typeCompileAst(c) for c in children])
[ "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
226,792
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.get('truediv', False): flags = __future__.division.compiler_flag else: flags = 0 c = compile(s, '<expr>', 'eval', flags) # make VariableNode's for the names names = {} for name in c.co_names: if name == "None": names[name] = None elif name == "True": names[name] = True elif name == "False": names[name] = False else: t = types.get(name, default_type) names[name] = expressions.VariableNode(name, type_to_kind[t]) names.update(expressions.functions) # now build the expression ex = eval(c, names) if expressions.isConstant(ex): ex = expressions.ConstantNode(ex, expressions.getKind(ex)) elif not isinstance(ex, expressions.ExpressionNode): raise TypeError("unsupported expression type: %s" % type(ex)) finally: expressions._context.set_new_context(old_ctx) return ex
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.get('truediv', False): flags = __future__.division.compiler_flag else: flags = 0 c = compile(s, '<expr>', 'eval', flags) # make VariableNode's for the names names = {} for name in c.co_names: if name == "None": names[name] = None elif name == "True": names[name] = True elif name == "False": names[name] = False else: t = types.get(name, default_type) names[name] = expressions.VariableNode(name, type_to_kind[t]) names.update(expressions.functions) # now build the expression ex = eval(c, names) if expressions.isConstant(ex): ex = expressions.ConstantNode(ex, expressions.getKind(ex)) elif not isinstance(ex, expressions.ExpressionNode): raise TypeError("unsupported expression type: %s" % type(ex)) finally: expressions._context.set_new_context(old_ctx) return ex
[ "def", "stringToExpression", "(", "s", ",", "types", ",", "context", ")", ":", "old_ctx", "=", "expressions", ".", "_context", ".", "get_current_context", "(", ")", "try", ":", "expressions", ".", "_context", ".", "set_new_context", "(", "context", ")", "# f...
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
226,793
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): raise ValueError( "input names (%s) don't match those found in expression (%s)" % (input_order, variable_names)) ordered_names = input_order else: ordered_names = list(variable_names) ordered_names.sort() ordered_variables = [variables[v] for v in ordered_names] return ordered_variables
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): raise ValueError( "input names (%s) don't match those found in expression (%s)" % (input_order, variable_names)) ordered_names = input_order else: ordered_names = list(variable_names) ordered_names.sort() ordered_variables = [variables[v] for v in ordered_names] return ordered_variables
[ "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
226,794
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] = registerMaker(node)
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] = registerMaker(node)
[ "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
226,795
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
226,796
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) else: seen[a] = a # Set values and registers so optimizeTemporariesAllocation # doesn't get confused for a in aliases: while a.value.astType == 'alias': a.value = a.value.value return aliases
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) else: seen[a] = a # Set values and registers so optimizeTemporariesAllocation # doesn't get confused for a in aliases: while a.value.astType == 'alias': a.value = a.value.value return aliases
[ "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
226,797
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.temporary)) for n in nodes) if nodes and nodes[-1] is not ast: nodes_to_check = nodes + [ast] else: nodes_to_check = nodes for n in nodes_to_check: for c in n.children: if c.reg.temporary: users_of[c.reg].add(n) unused = dict([(tc, set()) for tc in scalar_constant_kinds]) for n in nodes: for c in n.children: reg = c.reg if reg.temporary: users = users_of[reg] users.discard(n) if not users: unused[reg.node.astKind].add(reg) if unused[n.astKind]: reg = unused[n.astKind].pop() users_of[reg] = users_of[n.reg] n.reg = reg
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.temporary)) for n in nodes) if nodes and nodes[-1] is not ast: nodes_to_check = nodes + [ast] else: nodes_to_check = nodes for n in nodes_to_check: for c in n.children: if c.reg.temporary: users_of[c.reg].add(n) unused = dict([(tc, set()) for tc in scalar_constant_kinds]) for n in nodes: for c in n.children: reg = c.reg if reg.temporary: users = users_of[reg] users.discard(n) if not users: unused[reg.node.astKind].add(reg) if unused[n.astKind]: reg = unused[n.astKind].pop() users_of[reg] = users_of[n.reg] n.reg = reg
[ "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
226,798
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
226,799