code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
parser.description = __doc__ parser.formatter_class = argparse.RawDescriptionHelpFormatter parser.add_argument("--debug", action="store_true", help="Debug level logging") parser.add_argument( "--force", action="store_true", help="Import even i...
def add_arguments(self, parser)
Args: parser:
2.54441
2.541565
1.001119
d1_gmn.app.management.commands.util.util.log_setup(opt["debug"]) logging.info( "Running management command: {}".format( __name__ ) # util.get_command_name()) ) d1_gmn.app.management.commands.util.util.exit_if_other_instance_is_running( ...
def handle(self, *args, **opt)
Args: *args: **opt:
4.350592
4.051147
1.073916
event_log_model = d1_gmn.app.event_log.create_log_entry( d1_gmn.app.model_util.get_sci_model( d1_common.xml.get_req_val(log_record_pyxb.identifier) ), log_record_pyxb.event, log_record_pyxb.ipAddress, log_record_pyxb.userAgent,...
def _create_log_entry(self, log_record_pyxb)
Args: log_record_pyxb:
3.140975
3.153842
0.99592
if d1_gmn.app.sciobj_store.is_existing_sciobj_file(pid): self._events.log_and_count( "Skipped download of existing sciobj bytes", 'pid="{}"'.format(pid) ) else: with d1_gmn.app.sciobj_store.open_sciobj_file_by_pid( pid, write=T...
def _download_source_sciobj_bytes_to_store(self, client, pid)
Args: client: pid:
3.744301
3.778746
0.990885
if not os.path.isdir(dir_path): raise django.core.management.base.CommandError( 'Invalid dir path. path="{}"'.format(dir_path) )
def _assert_path_is_dir(self, dir_path)
Args: dir_path:
4.138869
3.698192
1.11916
try: with open(subject_info_xml_path) as f: return d1_common.xml.deserialize(f.read()) except ValueError as e: raise d1_common.types.exceptions.InvalidToken( 0, 'Could not deserialize SubjectInfo. subject_info="{}", error="{}"'.format( sub...
def deserialize_subject_info(subject_info_xml_path)
Deserialize a SubjectInfo XML file to a PyXB object.
3.164443
3.110767
1.017255
kwargs.setdefault("allow_redirects", False) return self._request("HEAD", rest_path_list, **kwargs)
def HEAD(self, rest_path_list, **kwargs)
Send a HEAD request. See requests.sessions.request for optional parameters. :returns: Response object
3.225423
4.537253
0.710876
fields = kwargs.pop("fields", None) if fields is not None: return self._send_mmp_stream("POST", rest_path_list, fields, **kwargs) else: return self._request("POST", rest_path_list, **kwargs)
def POST(self, rest_path_list, **kwargs)
Send a POST request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. To post regular data, pass a string, iterator or generator as the ``data`` argument. To post a multipart stream, pass a dictionary of multipart elements as the ``fields`` argume...
3.428359
3.799667
0.902279
fields = kwargs.pop("fields", None) if fields is not None: return self._send_mmp_stream("PUT", rest_path_list, fields, **kwargs) else: return self._request("PUT", rest_path_list, **kwargs)
def PUT(self, rest_path_list, **kwargs)
Send a PUT request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. See post() for parameters. :returns: Response object
3.40626
4.084216
0.834006
if kwargs.get("query"): url = "{}?{}".format(url, d1_common.url.urlencode(kwargs["query"])) curl_list = ["curl"] if method.lower() == "head": curl_list.append("--head") else: curl_list.append("-X {}".format(method)) for k, v in sorted(...
def get_curl_command_line(self, method, url, **kwargs)
Get request as cURL command line for debugging.
2.375597
2.345455
1.012851
if response.reason is None: response.reason = "<unknown>" return d1_client.util.normalize_request_response_dump( requests_toolbelt.utils.dump.dump_response(response) )
def dump_request_and_response(self, response)
Return a string containing a nicely formatted representation of the request and response objects for logging and debugging. - Note: Does not work if the request or response body is a MultipartEncoder object.
8.918325
8.084718
1.103109
if timeout is not None: try: timeout_float = float(timeout) except ValueError: raise ValueError( 'timeout_sec must be a valid number or None. timeout="{}"'.format( timeout ) ...
def _timeout_to_float(self, timeout)
Convert timeout to float. Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in Requests.
3.620595
3.354293
1.079391
parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", help="Python module path") args = parser.parse_args() r = d1_dev.util.redbaron_module_path_to_tree(args.path) print(r.help(True))
def main()
Print the RedBaron syntax tree for a Python module.
4.126175
3.120976
1.322078
# noinspection PyProtectedMember return os.path.abspath( os.path.join( os.path.dirname(sys._getframe(1).f_code.co_filename), base_path, rel_path ) )
def abs_path_from_base(base_path, rel_path)
Join a base and a relative path and return an absolute path to the resulting location. Args: base_path: str Relative or absolute path to prepend to ``rel_path``. rel_path: str Path relative to the location of the module file from which this function is called. Returns: ...
2.475129
3.020786
0.819366
# noinspection PyProtectedMember return os.path.abspath( os.path.join(os.path.dirname(sys._getframe(1).f_code.co_filename), rel_path) )
def abs_path(rel_path)
Convert a path that is relative to the module from which this function is called, to an absolute path. Args: rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified by ``rel_path``.
2.462656
3.071803
0.801697
return xml.etree.ElementTree.tostring(self._root_el, encoding)
def get_xml(self, encoding='unicode')
Returns: str : Current state of the wrapper as XML
5.481458
8.771945
0.624885
return d1_common.xml.reformat_to_pretty_xml( xml.etree.ElementTree.tostring(self._root_el, encoding) )
def get_pretty_xml(self, encoding='unicode')
Returns: str : Current state of the wrapper as a pretty printed XML string.
6.031879
7.067358
0.853484
return xml.etree.ElementTree.tostring( self.get_element_by_name(el_name, el_idx), encoding )
def get_xml_below_element(self, el_name, el_idx=0, encoding='unicode')
Args: el_name : str Name of element that is the base of the branch to retrieve. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: str : XML fragment rooted at ``el``.
3.363412
4.406677
0.763254
try: return self._root_el.findall('.' + xpath_str, namespaces) except (ValueError, xml.etree.ElementTree.ParseError) as e: raise SimpleXMLWrapperException( 'XPath select raised exception. xpath_str="{}" error="{}"'.format( xpath_str, s...
def get_element_by_xpath(self, xpath_str, namespaces=None)
Args: xpath_str : str XPath matching the elements for which to search. Returns: list : List of elements matching ``xpath_str``. If there are no matching elements, an empty list is returned.
4.871245
5.317349
0.916104
el_list = self.get_element_list_by_name(el_name) try: return el_list[el_idx] except IndexError: raise SimpleXMLWrapperException( 'Element not found. element_name="{}" requested_idx={} ' 'available_elements={}'.format(el_name, el_id...
def get_element_by_name(self, el_name, el_idx=0)
Args: el_name : str Name of element to get. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: element : The selected element.
3.316939
4.136596
0.801852
el_list = self.get_element_list_by_attr_key(attr_key) try: return el_list[el_idx] except IndexError: raise SimpleXMLWrapperException( 'Element with tag not found. tag_name="{}" requested_idx={} ' 'available_elements={}'.format(attr...
def get_element_by_attr_key(self, attr_key, el_idx=0)
Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: Element containing an attribute key named ``attr_key``.
3.97936
4.872206
0.816747
self.get_element_by_name(el_name, el_idx).text = el_text
def set_element_text(self, el_name, el_text, el_idx=0)
Args: el_name : str Name of element to update. el_text : str Text to set for element. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name.
3.245258
3.489755
0.929939
self.get_element_by_attr_key(attr_key, el_idx).text = el_text
def set_element_text_by_attr_key(self, attr_key, el_text, el_idx=0)
Args: attr_key : str Name of attribute for which to search el_text : str Text to set for element. el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name.
2.767463
3.146836
0.879443
return self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key]
def get_attr_value(self, attr_key, el_idx=0)
Return the value of the selected attribute in the selected element. Args: attr_key : str Name of attribute for which to search el_idx : int Index of element to use in the event that there are multiple sibling elements with the same name. Returns...
3.4089
5.170189
0.659338
self.get_element_by_attr_key(attr_key, el_idx).attrib[attr_key] = attr_val
def set_attr_text(self, attr_key, attr_val, el_idx=0)
Set the value of the selected attribute of the selected element. Args: attr_key : str Name of attribute for which to search attr_val : str Text to set for the attribute. el_idx : int Index of element to use in the event that there are multiple...
3.721623
4.65631
0.799265
return iso8601.parse_date(self.get_element_by_name(el_name, el_idx).text, tz)
def get_element_dt(self, el_name, tz=None, el_idx=0)
Return the text of the selected element as a ``datetime.datetime`` object. The element text must be a ISO8601 formatted datetime Args: el_name : str Name of element to use. tz : datetime.tzinfo Timezone in which to return the datetime. - Withou...
3.581698
5.422584
0.660515
dt = d1_common.date_time.cast_naive_datetime_to_tz(dt, tz) self.get_element_by_name(el_name, el_idx).text = dt.isoformat()
def set_element_dt(self, el_name, dt, tz=None, el_idx=0)
Set the text of the selected element to an ISO8601 formatted datetime. Args: el_name : str Name of element to update. dt : datetime.datetime Date and time to set tz : datetime.tzinfo Timezone to set - Without a timezone, other con...
3.898124
3.819237
1.020655
el = self.get_element_by_name(root_el.tag, el_idx) el[:] = list(root_el) el.attrib = root_el.attrib
def replace_by_etree(self, root_el, el_idx=0)
Replace element. Select element that has the same name as ``root_el``, then replace the selected element with ``root_el`` ``root_el`` can be a single element or the root of an element tree. Args: root_el : element New element that will replace the existing elemen...
3.552789
4.162422
0.853539
root_el = self.parse_xml(xml_str) self.replace_by_etree(root_el, el_idx)
def replace_by_xml(self, xml_str, el_idx=0)
Replace element. Select element that has the same name as ``xml_str``, then replace the selected element with ``xml_str`` - ``xml_str`` must have a single element in the root. - The root element in ``xml_str`` can have an arbitrary number of children. Args: xml_str :...
3.636464
5.930156
0.613216
def as_sql(self, compiler, connection): # pylint: disable=arguments-differ sql, params = super().as_sql(compiler, connection) params.append(self.path) return sql, params
Compile SQL for this function.
null
null
null
if field is None: field = '_'.join(['json'] + json_path_components(path)) kwargs = {field: JsonGetPath('json', path)} return self.defer('json').annotate(**kwargs)
def with_json_path(self, path, field=None)
Annotate Storage objects with a specific JSON path. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string :param field: Optional output field name
11.32517
14.805676
0.764921
return self.with_json_path(path, field='result').values_list('result', flat=True)
def get_json_path(self, path)
Return only a specific JSON path of Storage objects. :param path: Path to get inside the stored object, which can be either a list of path components or a comma-separated string
12.106858
18.301394
0.661527
if self._json is None: self._json = Storage.objects.get(**self._kwargs).json
def _get_storage(self)
Load `json` field from `Storage` object.
10.215064
4.505546
2.26722
Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name try: # pylint: disable=invalid-name ProcessMigrationHistory = from_state.apps.get_model('flow',...
def database_forwards(self, app_label, schema_editor, from_state, to_state)
Perform forward migration.
2.638304
2.617795
1.007834
return ( self.__class__.__name__, [], { 'process': self.process, 'field': self._raw_field, 'schema': self.schema, 'default': self.default, } )
def deconstruct(self)
Deconstruct operation.
4.40609
4.472683
0.985111
container = dict_dot(schema, '.'.join(self.field[:-1]), default=list) # Ignore processes, which already contain the target field with the # target schema. for field in container: if field['name'] == self.field[-1]: if field == self.schema: ...
def migrate_process_schema(self, process, schema, from_state)
Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise
5.557221
5.684173
0.977666
if not self.default: return self.default.prepare(data, from_state) for instance in data: value = self.default.get_default_for(instance, from_state) if not value and not self.schema.get('required', True): continue # Set de...
def migrate_data(self, data, from_state)
Migrate data objects. :param data: Queryset containing all data objects that need to be migrated :param from_state: Database model state
5.036735
5.626935
0.895112
return ( self.__class__.__name__, [], { 'process': self.process, 'field': self._raw_field, 'new_field': self.new_field, } )
def deconstruct(self)
Deconstruct operation.
4.591891
4.586364
1.001205
container = dict_dot(schema, '.'.join(self.field[:-1]), default=list) # Ignore processes, which already contain the target field. migrate = False for field in container: if field['name'] == self.field[-1]: field['name'] = self.new_field ...
def migrate_process_schema(self, process, schema, from_state)
Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise
4.774576
5.095328
0.93705
for instance in data: if instance.status == 'ER': continue container = getattr(instance, self.schema_type, {}) schema = container.pop(self.field[-1]) container[self.new_field] = schema setattr(instance, self.schema_type, cont...
def migrate_data(self, data, from_state)
Migrate data objects. :param data: Queryset containing all data objects that need to be migrated :param from_state: Database model state
6.320391
7.43539
0.850042
from resolwe.flow.models.data import DataQuerySet # pylint: disable=protected-access Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name DataQuerySet._delete_chunked(Data.objects.filter(process__persistence='TMP')) DataQuerySet._delete_chunk...
def database_forwards(self, app_label, schema_editor, from_state, to_state)
Perform forward migration.
4.954466
4.829632
1.025848
from resolwe.flow.models.data import DataQuerySet # pylint: disable=protected-access Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name DataQuerySet._delete_chunked(Data.objects.filter(process__slug=self.process)) Process = from_state.apps...
def database_forwards(self, app_label, schema_editor, from_state, to_state)
Perform forward migration.
2.927614
2.891457
1.012505
if process.type == self.new_type: return False process.type = self.new_type return True
def migrate_process_schema(self, process, schema, from_state)
Migrate process schema. :param process: Process instance :param schema: Process schema to migrate :param from_state: Database model state :return: True if the process was migrated, False otherwise
6.072644
8.639903
0.70286
Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name # Validate process types to ensure consistency. errors = validate_process_types(Process.objects.all()) if errors: raise ValueError("Process type consistency check failed after mig...
def database_forwards(self, app_label, schema_editor, from_state, to_state)
Perform forward migration.
5.562333
5.377361
1.034398
if request.path.endswith('/'): return django.http.HttpResponseRedirect(request.path[:-1]) return django.http.HttpResponse( generate_status_xml(), d1_common.const.CONTENT_TYPE_XML )
def home(request)
Home page. Root of web server should redirect to here.
6.400981
5.601126
1.142802
return django.http.HttpResponseNotFound( d1_common.types.exceptions.NotFound( 0, 'Invalid API endpoint', # Include the regexes the URL was tested against # traceInformation=str(exception), nodeId=django.conf.settings.NODE_IDENTIFIER, )...
def error_404(request, exception)
Handle 404s outside of the valid API URL endpoints Note: Cannot raise NotFound() here, as this method is not covered by the GMN middleware handler that catches DataONE exceptions raised by normal views.
11.03881
9.688606
1.13936
obj_store_path = django.conf.settings.OBJECT_STORE_PATH if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW( ctypes.c_wchar_p(obj_store_path), None, None, ctypes.pointer(free_bytes) ) return free_bytes....
def get_obj_store_free_space_bytes()
Return total free space available on the disk on which the object storage resides (in bytes)
1.734077
1.700863
1.019528
try: v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) except ValueError: v = 0 Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda * C['phiBox'] + Lambda * C['phiD'])) return {'v': v,...
def m2Lambda_to_vMh2(m2, Lambda, C)
Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential.
5.237434
5.166652
1.0137
if C['phi'] == 0 and C['phiBox'] == 0 and C['phiD'] == 0: return _vMh2_to_m2Lambda_SM(v, Mh2) else: def f0(x): # we want the root of this function m2, Lambda = x d = m2Lambda_to_vMh2(m2=m2.real, Lambda=Lambda.real, C=C) r...
def vMh2_to_m2Lambda(v, Mh2, C)
Function to numerically determine the parameters of the Higgs potential given the physical Higgs VEV and mass.
3.58757
3.588132
0.999843
r if C['phiWB'] == 0: # this is the trivial case gpbar = ebar * gbar / sqrt(gbar**2 - ebar**2) else: # if epsilon != 0, need to iterate def f0(x): # we want the root of this function gpb = x gb = gbar eps = C['phiWB'] * (v**2) ebar_calc = (g...
def get_gpbar(ebar, gbar, v, C)
r"""Function to numerically determine the hypercharge gauge coupling in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients.
6.032843
5.762529
1.046909
# start with a zero dict and update it with the input values MW = p['m_W'] # MZ = p['m_Z'] GF = p['GF'] Mh = p['m_h'] vb = sqrt(1 / sqrt(2) / GF) v = vb # TODO _d = vMh2_to_m2Lambda(v=v, Mh2=Mh**2, C=C) m2 = _d['m2'].real Lambda = _d['Lambda'].real gsbar = sqrt(4 * pi *...
def smeftpar(scale, C, basis)
Get the running parameters in SMEFT.
4.262923
4.117831
1.035235
m2 = C['m2'].real Lambda = C['Lambda'].real v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) GF = 1 / (sqrt(2) * v**2) # TODO Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda * C['phiBox'] + Lambd...
def smpar(C)
Get the running effective SM parameters.
3.721134
3.668721
1.014286
a = np.array(b, copy=True, dtype=complex) for i in range(3): a[0, 0, 1, i] = 1/2 * b[0, 0, 1, i] a[0, 0, 2, i] = 1/2 * b[0, 0, 2, i] a[0, 1, 1, i] = 1/2 * b[0, 1, 1, i] a[0, 1, 2, i] = 2/3 * b[0, 1, 2, i] - 1/6 * b[0, 2, 1, i] - 1/6 * b[1, 0, 2, i] + 1/6 * b[1, 2, 0, i] ...
def scale_8(b)
Translations necessary for class-8 coefficients to go from a basis with only non-redundant WCxf operators to a basis where the Wilson coefficients are symmetrized like the operators.
1.368256
1.36731
1.000692
C_symm = {} for i, v in C.items(): if i in C_symm_keys[0]: C_symm[i] = v.real elif i in C_symm_keys[1] + C_symm_keys[3]: C_symm[i] = v # nothing to do elif i in C_symm_keys[2]: C_symm[i] = symmetrize_2(C[i]) elif i in C_symm_keys[4]: ...
def symmetrize(C)
Symmetrize the Wilson coefficient arrays. Note that this function does not take into account the symmetry factors that occur when transitioning from a basis with only non-redundant operators (like in WCxf) to a basis where the Wilson coefficients are symmetrized like the operators. See `symmetrize_nonr...
1.446207
1.526697
0.947278
d = {} for k, v in C.items(): if np.shape(v) == () or np.shape(v) == (1,): d[k] = v else: ind = np.indices(v.shape).reshape(v.ndim, v.size).T for i in ind: name = k + '_' + ''.join([str(int(j) + 1) for j in i]) d[name] = v[...
def arrays2wcxf(C)
Convert a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values to a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values. This is needed for the output in WCxf format.
2.371762
2.21205
1.072201
C = {} for k, v in d.items(): name = k.split('_')[0] s = C_keys_shape[name] if s == 1: C[k] = v else: ind = k.split('_')[-1] if name not in C: C[name] = np.zeros(s, dtype=complex) C[name][tuple([int(i) - 1 for i...
def wcxf2arrays(d)
Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. This is needed for the parsing of input in WCxf format.
3.06542
2.84067
1.079119
C_out = C.copy() for k in (set(WC_keys) - set(C.keys())): C_out[k] = np.zeros(C_keys_shape[k]) return C_out
def add_missing(C)
Add arrays with zeros for missing Wilson coefficient keys
4.323444
3.373033
1.281767
d = OrderedDict() i=0 for k in C_keys: s = C_keys_shape[k] if s == 1: j = i+1 d[k] = C[i] else: j = i \ + reduce(operator.mul, s, 1) d[k] = C[i:j].reshape(s) i = j return d
def C_array2dict(C)
Convert a 1D array containing C values to a dictionary.
3.443367
3.46749
0.993043
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys])
def C_dict2array(C)
Convert an OrderedDict containing C values to a 1D array.
4.874111
4.525845
1.076951
C_symm = {} for i, v in C.items(): if i in C_symm_keys[0]: C_symm[i] = v.real elif i in C_symm_keys[1] + C_symm_keys[3]: C_symm[i] = v # nothing to do elif i in C_symm_keys[2]: C_symm[i] = symmetrize_2(C[i]) elif i in C_symm_keys[4]: ...
def symmetrize_nonred(C)
Symmetrize the Wilson coefficient arrays. This function takes into account the symmetry factors that occur when transitioning from a basis with only non-redundant operators (like in WCxf) to a basis where the Wilson coefficients are symmetrized like the operators.
1.558742
1.611057
0.967528
C_out = {k: _scale_dict[k] * v for k, v in C.items()} for k in C_symm_keys[8]: C_out['qqql'] = unscale_8(C_out['qqql']) return C_out
def unscale_dict(C)
Undo the scaling applied in `scale_dict`.
7.339424
7.17944
1.022284
C = wcxf2arrays(d) C = symmetrize_nonred(C) C = add_missing(C) return C
def wcxf2arrays_symmetrized(d)
Convert a dictionary with a Wilson coefficient name followed by underscore and numeric indices as keys and numbers as values to a dictionary with Wilson coefficient names as keys and numbers or numpy arrays as values. In contrast to `wcxf2arrays`, here the numpy arrays fulfill the same symmetry re...
5.633313
7.464257
0.754705
if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False): immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False) async_to_sync(manager.communicate)(data_id=data_id, save_settings=False, run_sync=immediate)
def commit_signal(data_id)
Nudge manager at the end of every Data object save event.
7.75853
7.293478
1.063763
if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created: # Run manager at the end of the potential transaction. Otherwise # tasks are send to workers before transaction ends and therefore # workers cannot access objects created inside transaction. ...
def manager_post_save_handler(sender, instance, created, **kwargs)
Run newly created (spawned) processes.
12.03667
12.137094
0.991726
# 1 means that the last Data object is going to be deleted. Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete()
def delete_entity(sender, instance, **kwargs)
Delete Entity when last Data object is deleted.
8.369617
5.040384
1.660512
def process_signal(relation_id): try: relation = Relation.objects.get(pk=relation_id) except Relation.DoesNotExist: return if relation.entities.count() == 0: relation.delete() # Wait for partitions to be recreated. transaction.on_co...
def delete_relation(sender, instance, **kwargs)
Delete the Relation object when the last Entity is removed.
4.450541
4.041709
1.101153
parser = argparse.ArgumentParser(description="Run the specified executor.") parser.add_argument('module', help="The module from which to instantiate the concrete executor.") args = parser.parse_args() module_name = '{}.run'.format(args.module) class_name = 'FlowExecutor' module = import_m...
async def run_executor()
Start the actual execution; instantiate the executor and run.
4.750179
4.366934
1.087761
if not (_is_validation_enabled() and _is_installed_scimeta_format_id(sysmeta_pyxb)): return if _is_above_size_limit(sysmeta_pyxb): if _is_action_accept(): return else: raise d1_common.types.exceptions.InvalidRequest( 0, 'Scien...
def assert_valid(sysmeta_pyxb, pid)
Validate file at {sciobj_path} against schema selected via formatId and raise InvalidRequest if invalid. Validation is only performed when: - SciMeta validation is enabled - and Object size is below size limit for validation - and formatId designates object as a Science Metadata object which is re...
4.34221
3.694574
1.175294
# Initialize the type extension composer. from . composer import composer composer.discover_extensions() is_migrating = sys.argv[1:2] == ['migrate'] if is_migrating: # Do not register signals and ES indices when: # * migrating - model instances u...
def ready(self)
Perform application initialization.
14.112011
13.226227
1.066972
user = getattr(self.context.get('request'), 'user') queryset = self.get_queryset() permission = get_full_perm('view', queryset.model) try: return get_objects_for_user( user, permission, queryset.filter(**{self.slug_fiel...
def to_internal_value(self, data)
Convert to internal value.
3.115098
3.019759
1.031572
result_ = TypeSerializer().serialize(json.loads(json.dumps(dct, default=json_serial), use_decimal=True)) if as_dict: return next(six.iteritems(result_))[1] else: return json.dumps(next(six.iteritems(result_))[1], **kwargs)
def dumps(dct, as_dict=False, **kwargs)
Dump the dict to json in DynamoDB Format You can use any other simplejson or json options :param dct - the dict to dump :param as_dict - returns the result as python dict (useful for DynamoDB boto3 library) or as json sting :returns: DynamoDB json format.
5.295092
5.501897
0.962412
try: # First - Try to parse the dct as DynamoDB parsed if 'BOOL' in dct: return dct['BOOL'] if 'S' in dct: val = dct['S'] try: return datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f') except: return str(val) ...
def object_hook(dct)
DynamoDB object hook to return python values
2.273553
2.259899
1.006042
if as_dict or (not isinstance(s, six.string_types)): s = json.dumps(s) kwargs['object_hook'] = object_hook return json.loads(s, *args, **kwargs)
def loads(s, as_dict=False, *args, **kwargs)
Loads dynamodb json format to a python dict. :param s - the json string or dict (with the as_dict variable set to True) to convert :returns python dict object
2.809005
4.295273
0.653976
"Returns the size (in meters) of a tile" assert zoom in range(0, len(self.RESOLUTIONS)) return self.tileSizePx * self.RESOLUTIONS[int(zoom)]
def tileSize(self, zoom)
Returns the size (in meters) of a tile
6.211646
5.906493
1.051664
"Returns the bounds of a tile in LV03 (EPSG:21781)" assert zoom in range(0, len(self.RESOLUTIONS)) # 0,0 at top left: y axis down and x axis right tileSize = self.tileSize(zoom) minX = self.MINX + tileCol * tileSize maxX = self.MINX + (tileCol + 1) * tileSize if ...
def tileBounds(self, zoom, tileCol, tileRow)
Returns the bounds of a tile in LV03 (EPSG:21781)
2.782191
2.491438
1.116701
"Returns a tile address based on a zoom level and \ a point in the tile" [x, y] = point assert x <= self.MAXX and x >= self.MINX assert y <= self.MAXY and y >= self.MINY assert zoom in range(0, len(self.RESOLUTIONS)) tileS = self.tileSize(zoom) offsetX = ...
def tileAddress(self, zoom, point)
Returns a tile address based on a zoom level and \ a point in the tile
2.972256
2.704184
1.099132
"Determine if an extent intersects this instance extent" return \ self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \ self.extent[1] <= extent[3] and self.extent[3] >= extent[1]
def intersectsExtent(self, extent)
Determine if an extent intersects this instance extent
2.872746
2.628567
1.092894
"Yields the tileBounds, zoom, tileCol and tileRow" assert minZoom in range(0, len(self.RESOLUTIONS)) assert maxZoom in range(0, len(self.RESOLUTIONS)) assert minZoom <= maxZoom for zoom in xrange(minZoom, maxZoom + 1): [minRow, minCol, maxRow, maxCol] = self.getExten...
def iterGrid(self, minZoom, maxZoom)
Yields the tileBounds, zoom, tileCol and tileRow
2.738389
2.341457
1.169523
"Returns the number of tiles over x at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxCol - minCol + 1
def numberOfXTilesAtZoom(self, zoom)
Returns the number of tiles over x at a given zoom level
5.84866
4.692213
1.246461
"Retruns the number of tiles over y at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxRow - minRow + 1
def numberOfYTilesAtZoom(self, zoom)
Retruns the number of tiles over y at a given zoom level
6.351389
4.559016
1.393149
"Returns the total number of tile at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return (maxCol - minCol + 1) * (maxRow - minRow + 1)
def numberOfTilesAtZoom(self, zoom)
Returns the total number of tile at a given zoom level
3.861057
3.503556
1.102039
"Return the total number of tiles for this instance extent" nbTiles = 0 minZoom = minZoom or 0 if maxZoom: maxZoom = maxZoom + 1 else: maxZoom = len(self.RESOLUTIONS) for zoom in xrange(minZoom, maxZoom): nbTiles += self.numberOfTilesAt...
def totalNumberOfTiles(self, minZoom=None, maxZoom=None)
Return the total number of tiles for this instance extent
3.53018
2.874311
1.228183
"Return the zoom level for a given resolution" assert resolution in self.RESOLUTIONS return self.RESOLUTIONS.index(resolution)
def getZoom(self, resolution)
Return the zoom level for a given resolution
5.496517
4.954944
1.1093
"Return lower and higher zoom level given a resolution" assert unit in ('meters', 'degrees') if unit == 'meters' and self.unit == 'degrees': resolution = resolution / self.metersPerUnit elif unit == 'degrees' and self.unit == 'meters': resolution = resolution * EP...
def _getZoomLevelRange(self, resolution, unit='meters')
Return lower and higher zoom level given a resolution
2.857764
2.522428
1.132942
lo, hi = self._getZoomLevelRange(resolution, unit) if lo == 0: return lo if hi == len(self.RESOLUTIONS): return hi - 1 before = self.RESOLUTIONS[lo - 1] if abs(self.RESOLUTIONS[lo] - resolution) < abs(before - resolution): return lo ...
def getClosestZoom(self, resolution, unit='meters')
Return the closest zoom level for a given resolution Parameters: resolution -- max. resolution unit -- unit for output (default='meters')
3.053744
2.985982
1.022693
if resolution in self.RESOLUTIONS: return self.getZoom(resolution) lo, hi = self._getZoomLevelRange(resolution, unit) if lo == 0 or lo == hi: return lo if hi == len(self.RESOLUTIONS): return hi - 1 return lo + 1
def getCeilingZoom(self, resolution, unit='meters')
Return the maximized zoom level for a given resolution Parameters: resolution -- max. resolution unit -- unit for output (default='meters')
3.784984
3.752186
1.008741
if self.unit == 'degrees': resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT else: resolution = self.getResolution(zoom) return resolution / STANDARD_PIXEL_SIZE
def getScale(self, zoom)
Returns the scale at a given zoom level
4.574338
4.662992
0.980988
if extent: bbox = extent else: bbox = self.extent minX = bbox[0] maxX = bbox[2] if self.originCorner == 'bottom-left': minY = bbox[3] maxY = bbox[1] elif self.originCorner == 'top-left': minY = bbox[1] ...
def getExtentAddress(self, zoom, extent=None, contained=False)
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based on the instance's extent or a user defined extent. Generic method that works with regular and irregular pyramids. Parameters: zoom -- the zoom for which we want the bounding addresses extent (optional) ...
1.989291
1.933271
1.028977
assert zoomParent <= zoom if zoomParent == zoom: return [[zoom, col, row]] extent = self.tileBounds(zoom, col, row) minRow, minCol, maxRow, maxCol = self.getExtentAddress( zoomParent, extent=extent, contained=True) addresses = [] for c in ...
def getParentTiles(self, zoom, col, row, zoomParent)
Return the parent tile(s) for an irregular (not following quadindex) and regular tiling scheme Parameters: zoom -- the zoom level a the child tile row -- the row of the child tile col -- the col of the child tile zoomParent -- the target zoom of the parent...
3.074209
3.108081
0.989102
if graph.metadata.debug or graph.metadata.testing: return False try: if not graph.config.logging.loggly.token: return False if not graph.config.logging.loggly.environment: return False except AttributeError: return False return True
def enable_loggly(graph)
Enable loggly if it is configured and not debug/testing.
3.744105
3.019763
1.239867
formatters = {} handlers = {} loggers = {} # create the console handler formatters["ExtraFormatter"] = make_extra_console_formatter(graph) handlers["console"] = make_stream_handler(graph, formatter="ExtraFormatter") # maybe create the loggly handler if enable_loggly(graph): ...
def make_dict_config(graph)
Build a dictionary configuration from conventions and configuration.
3.305644
3.287421
1.005543
return { "()": graph.config.logging.json_formatter.formatter, "fmt": graph.config.logging.json_required_keys, }
def make_json_formatter(graph)
Create the default json formatter.
12.547046
10.088418
1.243708
return { "class": graph.config.logging.stream_handler.class_, "formatter": formatter, "level": graph.config.logging.level, "stream": graph.config.logging.stream_handler.stream, }
def make_stream_handler(graph, formatter)
Create the stream handler. Used for console/debug output.
2.718979
2.584786
1.051916
base_url = graph.config.logging.loggly.base_url loggly_url = "{}/inputs/{}/tag/{}".format( base_url, graph.config.logging.loggly.token, ",".join([ graph.metadata.name, graph.config.logging.loggly.environment, ]), ) return { "class": gr...
def make_loggly_handler(graph, formatter)
Create the loggly handler. Used for searchable aggregation.
2.969054
3.05747
0.971082
# inject the default components; these can, but probably shouldn't, be overridden levels = {} for level in ["DEBUG", "INFO", "WARN", "ERROR"]: levels.update({ component: { "level": level, } for component in graph.config.logging.levels.default[level.lower(...
def make_library_levels(graph)
Create third party library logging level configurations. Tunes down overly verbose logs in commonly used libraries.
3.972525
3.927903
1.01136
site = request.site cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=site.domain) redirects = cache.get(cache_key) if redirects is None: redirects = {redirect.old_path: redirect.new_path for redirect in Redirect.objects.filter(site...
def process_request(self, request)
Redirects the current request if there is a matching Redirect model with the current request URL as the old_path field.
2.135545
2.044517
1.044523
if parent is None: parent = func.__self__ def wrapped(*args, **kwargs): parent.logger = ContextLogger( getattr(parent, 'logger', getLogger(parent.__class__.__name__)), context_func(*args, **kwargs) or dict(), ) try: result = func(*args, *...
def context_logger(context_func, func, parent=None)
The results of context_func will be executed and applied to a ContextLogger instance for the execution of func. The resulting ContextLogger instance will be available on parent.logger for the duration of func. :param context_func: callable which provides dictionary-like context information :param func:...
3.002138
3.005018
0.999042
# Imported here to avoid circular import from django.conf import settings if request: try: return self._get_site_by_request(request) # pylint: disable=protected-access except Site.DoesNotExist: pass if getattr(settings, 'SITE_ID', ''): return self._...
def patched_get_current(self, request=None)
Monkey patched version of Django's SiteManager.get_current() function. Returns the current Site based on a given request or the SITE_ID in the project's settings. If a request is given attempts to match a site with domain matching request.get_host(). If a request is not given or a site cannot be found ...
3.222869
2.931881
1.09925
now = datetime.datetime.utcnow() site = models.SITE_CACHE.get(site_id) cache_timeout = SITE_CACHE_TIMEOUTS.get(site_id, now) if not site or cache_timeout <= now: site = self.get(pk=site_id) models.SITE_CACHE[site_id] = site SITE_CACHE_TIMEOUTS[site_id] = now + get_site_cache...
def patched_get_site_by_id(self, site_id)
Monkey patched version of Django's SiteManager._get_site_by_id() function. Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site. This allows for the use of an in-memory cache for Site models, avoiding one or more DB hits on every request made to the Django application, but also allo...
2.726845
2.585578
1.054636
host = request.get_host() now = datetime.datetime.utcnow() site = models.SITE_CACHE.get(host) cache_timeout = SITE_CACHE_TIMEOUTS.get(host, now) if not site or cache_timeout <= now: site = self.get(domain__iexact=host) models.SITE_CACHE[host] = site SITE_CACHE_TIMEOUTS[h...
def patched_get_site_by_request(self, request)
Monkey patched version of Django's SiteManager._get_site_by_request() function. Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site. This allows for the use of an in-memory cache for Site models, avoiding one or more DB hits on every request made to the Django application, but also...
3.19236
2.979713
1.071365