code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return self._get_page(self.object_list[bottom:top], number, self)
def page(self, number)
Returns a Page object for the given 1-based page number.
3.446065
3.195071
1.078557
try: return self.object_list.count() except (AttributeError, TypeError): # AttributeError if object_list has no count() method. # TypeError if object_list.count() requires arguments # (i.e. is of type list). return len(self.object_lis...
def count(self)
Returns the total number of objects, across all pages.
3.906891
3.298314
1.184512
if self.count == 0 and not self.allow_empty_first_page: return 0 hits = max(1, self.count - self.orphans) return int(ceil(hits / float(self.per_page)))
def num_pages(self)
Returns the total number of pages.
4.65416
3.861977
1.205124
if hasattr(self.object_list, 'ordered') and not self.object_list.ordered: warnings.warn( 'Pagination may yield inconsistent results with an unordered ' 'object_list: {!r}'.format(self.object_list), UnorderedObjectListWarning )
def _check_object_list_is_ordered(self)
Warn if self.object_list is unordered (typically a QuerySet).
4.81337
3.435937
1.40089
# max_messages_to_send = 200 max_messages_to_send = 1000000 end_time = None num_logs_per_batch = 0.0 num_logs = 0.0 running_time = 0.0 start_time = datetime.datetime.utcnow() checkpoint = datetime.datetime.utcnow() last_checkpoint = datetime.datetime.utcnow() try: ...
def run_main()
run_main
3.059174
3.056225
1.000965
try: return [klass(mod) for mod in self.tree.reply.data.results.array[0].item] except AttributeError: return []
def as_models(self, klass)
Turns an array-style response into a list of models.
10.419184
8.436805
1.234968
parser = self._new_argument_parser() self._add_base_arguments(parser) self._add_required_arguments(parser) return parser
def _create_argument_parser(self)
Create and return the argument parser with all of the arguments and configuration ready to go. :rtype: argparse.ArgumentParser
3.604958
4.140607
0.870635
sig = inspect.signature(fun) injectables: Dict[str, Any] = {} for name, param in sig.parameters.items(): type_ = param.annotation if name == 'self': continue else: injectables[name] = type_ @wraps(fun) def _inner(*args, **kwargs): contai...
def inject(fun: Callable) -> Callable
A decorator for injection dependencies into functions/methods, based on their type annotations. .. code-block:: python class SomeClass: @inject def __init__(self, my_dep: DepType) -> None: self.my_dep = my_dep .. important:: On the opposite to :cla...
2.422569
2.772574
0.873761
first_arg = qualifier def egg_dec(obj: Union[FunctionType, type]) -> T: if isinstance(obj, FunctionType): spec = inspect.signature(obj) return_annotation = spec.return_annotation if return_annotation is Signature.empty: raise ConfigurationError('...
def egg(qualifier: Union[str, Type] = '', profile: str = None)
A function that returns a decorator (or acts like a decorator) that marks class or function as a source of `base`. If a class is decorated, it should inherit after from `base` type. If a function is decorated, it declared return type should inherit after some `base` type, or it should be the `base` ty...
3.732252
3.900024
0.956982
def dec(egg_: T) -> T: egg_.__haps_custom_scope = scope_type return egg_ return dec
def scope(scope_type: str) -> Callable
A function that returns decorator that set scopes to some class/function .. code-block:: python @egg() @scopes(SINGLETON_SCOPE) class DepImpl: pass :param scope_type: Which scope should be used :return:
20.502136
21.715645
0.944118
profiles = Configuration().get_var(PROFILES, tuple) assert isinstance(profiles, (list, tuple)) profiles = tuple(profiles) + (None,) seen = set() registered = set() filtered_config: List[Egg] = [] for profile in profiles: for egg_ in (e for...
def configure(config: List[Egg], subclass: 'Container' = None) -> None
Configure haps manually, an alternative to :func:`~haps.Container.autodiscover` :param config: List of configured Eggs :param subclass: Optional Container subclass that should be used
4.375758
4.355793
1.004584
def find_base(bases: set, implementation: Type): found = {b for b in bases if issubclass(implementation, b)} if not found: raise ConfigurationError( "No base defined for %r" % implementation) elif len(found) > 1: r...
def autodiscover(cls, module_paths: List[str], subclass: 'Container' = None) -> None
Load all modules automatically and find bases and eggs. :param module_paths: List of paths that should be discovered :param subclass: Optional Container subclass that should be used
2.886175
2.745055
1.051409
egg_ = self._find_egg(base_, qualifier) if egg_ is None: raise UnknownDependency('Unknown dependency %s' % base_) scope_id = getattr(egg_.egg, '__haps_custom_scope', INSTANCE_SCOPE) try: _scope = self.scopes[scope_id] except KeyError: ...
def get_object(self, base_: Type, qualifier: str = None) -> Any
Get instance directly from the container. If the qualifier is not None, proper method to create/retrieve instance is used. :param base_: `base` of this object :param qualifier: optional qualifier :return: object instance
5.903572
6.15709
0.958825
with self._lock: if name in self.scopes: raise AlreadyConfigured(f'Scope {name} already registered') self.scopes[name] = scope_class()
def register_scope(self, name: str, scope_class: Type[Scope]) -> None
Register new scopes which should be subclass of `Scope` :param name: Name of new scopes :param scope_class: Class of new scopes
4.137994
4.665183
0.886995
context = {} context['article'] = article context['lang'] = current_language context['current_article'] = article context['has_change_permissions'] = article.has_change_permission(request) response = TemplateResponse(request, article.template, context) response.add_post_render_callback...
def render_article(request, article, current_language, slug)
Renders an article
4.348909
4.344691
1.000971
if method not in self.methods: raise TypeError('{} not in valid method(s): {}.'.format(method, self.methods)) return Action(self, method, **kwargs)
def new_action(self, method='GET', **kwargs)
Create a new Action linked to this endpoint with the given args.
4.120625
3.779106
1.09037
if iskeyword(name): name = '_' + name self._actions[name] = parent.new_action(**action) setattr(self, name, self._actions[name].execute)
def add_action(self, name, parent, action)
Add a single Action to the APIObject.
5.505053
4.501145
1.223034
out = '' out += '|\n' if self._id_variable: subs = '[{}]'.format(self._id_variable) else: subs = '' out += '|---{}{}\n'.format(name, subs) if self._description: out += '| | {}\n'.format(self._description) for name, ...
def printed_out(self, name)
Create a string describing the APIObject and its children
3.564427
3.570317
0.99835
_verbose = kwargs.pop('_verbose', False) return_full_object = kwargs.pop('return_full_object', False) variables = self.variables().fill(*args, **kwargs) return Request(self, variables).send( traversal=self.traversal, _verbose=_verbose, return_...
def execute(self, *args, **kwargs)
Fill all variables from *args and **kwargs, build the request, and send it. If we set the _verbose kwarg to true, then we'll get a Response object back instead of loaded data.
4.744348
3.626498
1.308245
opt = self.variables().optional_namestring() req = self.variables().required_namestring() out = '' out += '| |\n' out += '| |---{}({}{})\n'.format(name, req, opt) if self.description: out += '| | {}\n'.format(self.description) retu...
def printed_out(self, name)
Create a string representation of the action
5.6309
5.538504
1.016683
version = kwargs.pop('version', None) require = kwargs.pop('require_https', True) return cls(Hive.from_file(fname, version, require), *args, **kwargs)
def from_hive_file(cls, fname, *args, **kwargs)
Open a local JSON hive file and initialize from the hive contained in that file, paying attention to the version keyword argument.
4.967368
3.968735
1.251625
version = kwargs.pop('version', None) require = kwargs.pop('require_https', False) return cls(Hive.from_url(url, version, require), *args, **kwargs)
def from_remote_hive(cls, url, *args, **kwargs)
Download a JSON hive file from a URL, and initialize from it, paying attention to the version keyword argument.
4.498909
3.83972
1.171676
version = kwargs.pop('version', None) require = kwargs.pop('require_https', False) return cls(Hive.from_domain(domain, version, require), *args, **kwargs)
def from_domain(cls, domain, *args, **kwargs)
Try to download the hive file from the domain using the defined beekeeper spec of domain/api/hive.json.
5.460726
4.294187
1.271656
self._endpoints[name] = Endpoint(self, **kwargs)
def add_endpoint(self, name, **kwargs)
Add an endpoint with the given name to the API.
4.818851
4.038725
1.193162
if iskeyword(name): name = '_' + name setattr(self, name, APIObject(self, **obj)) self._objects[name] = getattr(self, name)
def add_object(self, name, obj)
Initialize an APIObject with the given name and make it available using dot notation from the top-level namespace.
5.131983
3.95386
1.297968
if key in self.altair_encode: del self.altair_encode[key] else: self.warning("Key " + key + " not found in Altair encoding dict")
def raenc(self, key)
Remove an entry from the altair encoding dict
6.052957
2.781304
2.176302
try: c = self._altair_chart_num_("line", xfield, yfield, opts, style, encode) except Exception as e: self.err(e, "Can not draw a line num chart") return return c
def _altair_line_num_(self, xfield, yfield, opts, style, encode)
Get a line + text number chart
5.245109
4.685085
1.119533
style = {**style2} text_color = "grey" if "text_color" in style: text_color = style["text_color"] del style["text_color"] if "text_color" in self.chart_style: del self.chart_style["text_color"] if chart_type == "line": ...
def _altair_chart_num_(self, chart_type, xfield, yfield, opts, style2, encode)
Get a chart + text number chart
2.228829
2.232147
0.998514
try: rawy = yfield if ":" in yfield: rawy = yfield.split(":")[0] mean = self.df[rawy].mean() l = [] i = 0 while i < len(self.df[rawy]): l.append(mean) i += 1 self.df["Mean...
def _altair_hline_(self, xfield, yfield, opts, style, encode)
Get a mean line chart
3.969676
3.701725
1.072385
encode = self.altair_encode chart = None if chart_type == "bar": chart = Chart(self.df).mark_bar(**style).encode(x=xfield, \ y=yfield, **encode).properties(**opts) elif chart_type == "circle": chart = Chart(self...
def _get_altair_chart(self, xfield, yfield, chart_type, label, opts={}, style={}, **kwargs)
Get an Altair chart object
1.384105
1.388141
0.997092
try: json_data = chart_obj.to_json(indent=0) except Exception as e: self.err(e) html = '<div id="' + slug + '"></div>\n' html += '<script type="text/javascript">' html += 'var spec = ' + json_data.replace("\n", "") + ";" html += h...
def _get_altair_html_(self, chart_obj, slug)
Get html for an Altair chart
3.406384
3.386429
1.005893
normalized = "".join(map(lambda c: " " if c.isspace() else c, s)) string = False quote = False v = [] for col, char in enumerate(normalized.rstrip(), 1): if char == '\\': quote = True if char == '"' and not quote: ...
def split(self, s)
Splits a string into a list of (start_column, substring) tuples.
3.284944
3.009539
1.091511
start = 1 if s[0] in ["-","+"] else 0 all_digits = lambda x: all(map(lambda c: c.isdigit(), x)) ishex = lambda c: c.isdigit() or ord(c.lower()) in range(ord("a"), ord("f")) all_hex = lambda x: all(map(ishex, x)) if all_digits(s[start:]): try: ...
def parse_number(self, s)
Parses integers in bases 10 and 16 and floats.
2.169971
2.130399
1.018575
a = s[0] if len(s)>0 else "" b = s[1] if len(s)>1 else "" if a.isdigit() or (a in ["+","-"] and b.isdigit()): return self.parse_number(s) elif a == '"': return self.parse_string(s) elif a == ':': return self.parse_colon(s) elif a == ';': return self....
def tokentype(self, s)
Parses string and returns a (Tokenizer.TYPE, value) tuple.
2.493765
2.463638
1.012228
def readlines(s): while True: line = s.readline() if line != "": yield line.rstrip() else: break for self.lineno, line in enumerate(readlines(self.stream), 1): for self.column, part ...
def tokenize(self)
Breaks a stream up into tokens. Yields tuples of the form (line_number, column, Tokenizer.TOKEN).
4.463385
4.182907
1.067053
module = app_class.__module__ if (module == '__main__' and extra_module_paths is None and 'module_paths' not in kwargs): raise ConfigurationError( 'You cannot run application from __main__ module without ' 'providing mo...
def run(app_class: Type[Application], extra_module_paths: List[str] = None, **kwargs: Any) -> None
Runner for haps application. :param app_class: :class:`~haps.application.Application` type :param extra_module_paths: Extra modules list to autodiscover :param kwargs: Extra arguments are passed to\ :func:`~haps.Container.autodiscover`
2.885521
2.656481
1.08622
if type(d) != dict: raise TypeError('Expecting a <dict>, got a {0}'.format(type(d))) obj = cls() obj._full_data = d # import attributes obj._import_attributes(d) # import <a> child tags as dict items, see __getitem__() obj._a_tags = obj._pa...
def from_dict(cls, d)
Given a dict in python-zimbra format or XML, generate a Python object.
7.959504
7.31427
1.088216
try: return self._a_tags[property_name] except KeyError: if default != Ellipsis: return default else: raise
def property(self, property_name, default=Ellipsis)
Returns a property value :param: default will return that value if the property is not found, else, will raise a KeyError.
4.045963
3.85569
1.049349
try: res = self._a_tags[property_name] except KeyError: return [] if type(res) == list: return res else: return [res]
def property_as_list(self, property_name)
property() but encapsulates it in a list, if it's a single-element property.
3.921
3.99914
0.980461
props = {} if 'a' in dic: childs = dic['a'] # If there is only one "a", it's not presentend as # a list, that's why we put it in a list if not isinstance(childs, (list, tuple)): childs = [childs] else: childs =...
def _parse_a_tags(cls, dic)
Iterates over all <a> tags and builds a dict with those. If a tag with same "n" attributes appears several times, the dict value is a list with the tags values, else it's a string. :param: dic the dict describing the tag :returns: a dict
3.700424
3.974044
0.931148
prop_tags = [] for k, v in attrs_dict.items(): node = {cls.ATTRNAME_PROPERTY: k, '_content': utils.auto_type(v)} prop_tags.append(node) return prop_tags
def _unparse_a_tags(cls, attrs_dict)
Iterates over the dictionary :param: attrs_dict a dict of attributes :returns: a SimpleXMLElement list containing <a> tags
6.377995
7.31233
0.872225
o = {} for prop in ('name', 'id'): if hasattr(self, prop): o[prop] = getattr(self, prop) try: if len(self.a) > 0: o['a'] = [] for node in self._unparse_a_tags(self._a_tags): o['a'].append(node)...
def to_creator(self)
Returns the dict suitable for CreateIdentity or ModifyIdentity
4.365019
4.171063
1.0465
for i in self.SELECTORS: if hasattr(self, i): val = getattr(self, i) selector = i break return {selector: val}
def to_selector(self)
For some reason, the selector for <identity> is <identity id="1234" /> rather than <identity by="id"></identity>
5.941374
4.969985
1.195451
o = super(DistributionList, cls).from_dict(d) o.members = [] if 'dlm' in d: o.members = [utils.get_content(member) for member in utils.as_list(d["dlm"])] return o
def from_dict(cls, d)
Override default, adding the capture of members.
5.347757
4.81194
1.111351
o = super(Signature, cls).from_dict(d) if 'content' in d: # Sometimes, several contents, (one txt, other html), take last try: o._content = d['content']['_content'] o._contenttype = d['content']['type'] except TypeError: ...
def from_dict(cls, d)
Override default, adding the capture of content and contenttype.
5.716948
4.90584
1.165335
signature = {} if for_modify: try: # we should have an ID signature['id'] = self.id except AttributeError: raise AttributeError('a modify request should specify an ID') # Case where we change or set a name ...
def to_creator(self, for_modify=False)
Returns a dict object suitable for a 'CreateSignature'. A signature object for creation is like : <signature name="unittest"> <content type="text/plain">My signature content</content> </signature> which is : { 'name' : 'unittest', ...
5.216252
4.458797
1.169879
task = { 'm': { 'su': subject, 'inv': { 'comp': { 'name': subject, 'fr': {'_content': desc}, 'desc': {'_content': desc}, 'percentComplete': '0...
def to_creator(self, subject, desc)
Return a python-zimbra dict for CreateTaskRequest Example : <CreateTaskRequest> <m su="Task subject"> <inv> <comp name="Task subject"> <fr>Task comment</fr> <desc>Task comment</desc> </co...
7.43996
2.472125
3.009541
use_user = os.getenv( "SPLUNK_ADMIN_USER", user) use_password = os.getenv( "SPLUNK_ADMIN_PASSWORD", password) if not use_user: use_user = "admin" if not use_password: use_password = "changeme" full_url = ( '{}/servicesNS/admin/splunk_http...
def get_token( user=None, password=None, url='https://localhost:8089', verify=False, ssl_options=None, version="7.0.3", debug=False)
get_token This will get a user token and throw for any errors :param user: username - defaults to env var: SPLUNK_ADMIN_USER :param password: password - defaults to env var: SPLUNK_ADMIN_PASSWORD :param url: splunk auth url :param verify: verify cert :para...
3.024229
3.030084
0.998068
node_id = self._get_node_id_for_packet(packet) client_protocol = self._client_protocols.get(node_id) if node_id and client_protocol: if client_protocol.is_connected(): packet['to'] = node_id client_protocol.send(packet) return...
def _request_sender(self, packet: dict)
Sends a request to a server from a ServiceClient auto dispatch method called from self.send()
3.99212
3.63362
1.098662
authors = [] authorfile = os.path.join('doc', 'authors.txt') with codecs.open(authorfile, 'r', 'utf-8') as f: for line in f: line = line.strip() if line and not line.startswith(u'#'): authors.append(line) return u", ".join(authors)
def get_authors()
Read list of authors from a text file, filtering comments.
2.290627
2.22196
1.030904
ds2 = self._duplicate_(quiet=True) if ds2 is None: self.err("Can not clone instance") else: if quiet is False: self.ok("Instance cloned") return ds2
def clone_(self, quiet=False)
Clone the DataSwim instance
7.163641
6.273599
1.141871
try: self.backup_df = self.df.copy() except Exception as e: self.err(e, "Can not backup data") return self.ok("Dataframe backed up")
def backup(self)
Backup the main dataframe
5.847675
4.780992
1.223109
if self.backup_df is None: self.warning("No dataframe is backed up: nothing restore") return self.df = self.backup_df self.ok("Dataframe is restored")
def restore(self)
Restore the main dataframe
8.220304
6.584959
1.248346
try: df = pd.read_json(path, **kwargs) self.df = df except Exception as e: self.err(e, "Can not load json")
def load_json(self, path, **kwargs)
Load data in the main dataframe from json :param filepath: url of the csv file to load, can be absolute if it starts with ``/`` or relative if it starts with ``./`` :type filepath: str :param kwargs: keyword argu...
4.068019
4.684711
0.868361
try: self.start("Loading Hdf5 data...") self.df = dd.io.load(filepath) self.end("Finished loading Hdf5 data") except Exception as e: self.err(e, "Can not load Hdf5 file")
def load_h5(self, filepath)
Load a Hdf5 file to the main dataframe :param filepath: url of the csv file to load, can be absolute if it starts with ``/`` or relative if it starts with ``./`` :type filepath: str :example: ``ds.load_h5("./myfi...
4.495175
4.42814
1.015138
try: df = pd.read_excel(filepath, **kwargs) if len(df.index) == 0: self.warning("Empty Excel file. Can not set the dataframe.") return self.df = df except Exception as e: self.err(e, "Can not load Excel file")
def load_excel(self, filepath, **kwargs)
Set the main dataframe with the content of an Excel file :param filepath: url of the csv file to load, can be absolute if it starts with ``/`` or relative if it starts with ``./`` :type filepath: str :param kwargs: keyword arguments to pass to ...
3.479329
3.689697
0.942985
self.start("Loading csv...") try: if self.datapath is not None and url.startswith("/") is False: url = self.datapath + "/" + url df = pd.read_csv(url, **kwargs) self.df = df except FileNotFoundError: msg = "File " + url + "...
def load_csv(self, url, **kwargs)
Loads csv data in the main dataframe :param url: url of the csv file to load: can be absolute if it starts with ``/`` or relative if it starts with ``./`` :type url: str :param kwargs: keyword arguments to pass to Pandas ...
3.226109
3.231092
0.998458
def dateparse(dates): return [pd.datetime.strptime(d, dformat) for d in dates] return dateparse
def dateparser(self, dformat='%d/%m/%Y')
Returns a date parser for pandas
6.02553
5.35393
1.125441
self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME) scope = self._BASE_SCOPE if extended_permissions: scope += extended_permissions args = {'client_id': self.settings[self._CLIENT_ID_SETTING], 'redirect_uri': self.oauth2_redirect_uri(callb...
def authenticate_redirect(self, callback_uri=None, cancel_uri=None, extended_permissions=None, callback=None)
Perform the authentication redirect to GitHub
3.500003
3.457224
1.012374
self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME) self.require_setting(self._CLIENT_SECRET_SETTING, self._API_NAME) if self.state: if (not self.get_argument('state', None) or self.state != self.get_argument('state')): LOGGER.error...
def get_authenticated_user(self, callback)
Fetches the authenticated user :param method callback: The callback method to invoke
2.65144
2.749289
0.964409
content = escape.json_decode(response.body) if 'error' in content: LOGGER.error('Error fetching access token: %s', content['error']) future.set_exception(auth.AuthError('Github auth error: %s' % str(content['error']))) ...
def _on_access_token(self, future, response)
Invoked as a callback when GitHub has returned a response to the access token request. :param method future: The callback method to pass along :param tornado.httpclient.HTTPResponse response: The HTTP response
3.739464
4.04036
0.925527
response['access_token'] = access_token future.set_result(response)
def _on_github_user(self, future, access_token, response)
Invoked as a callback when self.github_request returns the response to the request for user data. :param method future: The callback method to pass along :param str access_token: The access token for the user's use :param dict response: The HTTP response already decoded
3.918376
6.671599
0.587322
url = self._API_URL + path all_args = {} if access_token: all_args["access_token"] = access_token all_args.update(kwargs) if all_args: url += "?" + auth.urllib_parse.urlencode(all_args) callback = self.async_callback(self._on_github_re...
def github_request(self, path, callback, access_token=None, post_args=None, **kwargs)
Make a request to the GitHub API, passing in the path, a callback, the access token, optional post arguments and keyword arguments to be added as values in the request body or URI
2.764912
2.902998
0.952433
try: content = escape.json_decode(response.body) except ValueError as error: future.set_exception(Exception('Github error: %s' % response.body)) return if 'error' in content: future.set_exception...
def _on_github_request(self, future, response)
Invoked as a response to the GitHub API request. Will decode the response and set the result for the future to return the callback or raise an exception
2.850773
2.923441
0.975143
LOGGER.info(response.body) content = escape.json_decode(response.body) if 'error' in content: LOGGER.error('Error fetching access token: %s', content['error']) future.set_exception(auth.AuthError('StackExchange auth error: %s' % ...
def _on_access_token(self, future, response)
Invoked as a callback when StackExchange has returned a response to the access token request. :param method future: The callback method to pass along :param tornado.httpclient.HTTPResponse response: The HTTP response
4.010273
3.849267
1.041828
response['access_token'] = access_token future.set_result(response)
def _on_stackexchange_user(self, future, access_token, response)
Invoked as a callback when self.stackexchange_request returns the response to the request for user data. :param method future: The callback method to pass along :param str access_token: The access token for the user's use :param dict response: The HTTP response already decoded
4.077828
6.980954
0.584136
url = self._API_URL + path all_args = {} if access_token: all_args["access_token"] = access_token all_args.update(kwargs) if all_args: url += "?" + auth.urllib_parse.urlencode(all_args) callback = self.async_callback(self._on_stackexch...
def stackexchange_request(self, path, callback, access_token=None, post_args=None, **kwargs)
Make a request to the StackExchange API, passing in the path, a callback, the access token, optional post arguments and keyword arguments to be added as values in the request body or URI
2.40537
2.536442
0.948325
content = escape.json_decode(response.body) if 'error' in content: future.set_exception(Exception('StackExchange error: %s' % str(content['error']))) return future.set_result(content)
def _on_stackexchange_request(self, future, response)
Invoked as a response to the StackExchange API request. Will decode the response and set the result for the future to return the callback or raise an exception
3.490541
3.457702
1.009497
results = {} for key, val in params.items(): lookup_len = len(self.query_string_lookup) + 1 if key[0:lookup_len] == '{}['.format(self.query_string_lookup) and key[-1] == ']': results[key[lookup_len:-1]] = val if val.lower() != 'null' else None ...
def parse_query_string(self, params)
Override this method if you need to support query string filter keys other than those in the format of ``key[field_name]=val``. Maps query string values == 'null' to ``None``. :param params: The query string parameters from ``request.params``. :return: Dictionary.
3.429697
3.235821
1.059915
if not request.params: return query querystring_params = self.parse_query_string(request.params) query, filter_list = self.build_filter_list(querystring_params, query, view) return self.apply_filter(query, filter_list)
def filter_query(self, request, query, view)
You may want to override this method if you want to add custom filtering to an ViewSet while still utilizing the feature of the ``AttributeFilter`` implementation. :param request: The pyramid ``Request`` instance. :param query: The SQLAlchemy ``Query`` instance. :param view: An instance...
3.817467
3.889194
0.981557
if not url.endswith('/') and settings.APPEND_SLASH: return HttpResponseRedirect("%s/" % request.path) if not url.startswith('/'): url = "/" + url f = get_object_or_404(MultilingualFlatPage, url__exact=url, sites__id__exact=settings.SITE_ID) # If registration is required for accessin...
def multilingual_flatpage(request, url)
Multilingual flat page view. Models: `multilingual.flatpages.models` Templates: Uses the template defined by the ``template_name`` field, or `flatpages/default.html` if template_name is not defined. Context: flatpage `flatpages.flatpages` object
3.294213
3.352341
0.982661
return [self._extract_features(sequence1, sequence2) for sequence1, sequence2 in raw_X]
def transform(self, raw_X, y=None)
Transform sequence pairs to feature arrays that can be used as input to `Hacrf` models. Parameters ---------- raw_X : List of (sequence1_n, sequence2_n) pairs, one for each training example n. y : (ignored) Returns ------- X : List of numpy ndarrays, each with ...
6.70759
5.063707
1.32464
array1 = np.array(tuple(sequence1), ndmin=2).T array2 = np.array(tuple(sequence2), ndmin=2) K = (len(self._binary_features) + sum(num_feats for _, num_feats in self._sparse_features)) feature_array = np.zeros((array1.size, array2.size, K), dtype='float64') ...
def _extract_features(self, sequence1, sequence2)
Helper to extract features for one data point.
2.694505
2.707943
0.995038
label = colors.green("OK") self._msg(label, *msg)
def ok(self, *msg)
Prints a message with an ok prefix
12.708611
12.581356
1.010115
label = colors.blue("INFO") self._msg(label, *msg)
def info(self, *msg)
Prints a message with an info prefix
12.98111
11.53461
1.125405
label = colors.yellow("STATUS") self._msg(label, *msg)
def status(self, *msg)
Prints a status message
17.638489
16.478556
1.07039
label = colors.yellow("WARNING") self._msg(label, *msg)
def warning(self, *msg)
Prints a warning
12.848793
15.476293
0.830224
label = colors.yellow("DEBUG") self._msg(label, *msg)
def debug(self, *msg)
Prints a warning
12.309983
14.440587
0.852457
label = colors.purple("Progress") self._msg(label, *msg)
def progress(self, *msg)
Prints a progress message
19.796141
19.255157
1.028095
self.start_time = datetime.datetime.now() label = colors.purple("START") self._msg(label, *msg)
def start(self, *msg)
Prints an start message
8.004729
7.483587
1.069638
if self.start_time is None: self.err("No start time set: please use start() " "before using this function") endtime = datetime.datetime.now() rd = dateutil.relativedelta.relativedelta(endtime, self.start_time) endmsg = self._endmsg(rd) la...
def end(self, *msg)
Prints an end message with elapsed time
5.438342
5.070138
1.072622
lbl = "[" + label + "] " txt = lbl + " " + " ".join(list(msg)) if self.notebook is True: html = HTML(txt) display(lbl + html) else: print(lbl + txt)
def html(self, label, *msg)
Prints html in notebook
5.852369
5.081296
1.151747
txt = self._unpack_msg(*msg) return "[" + label + "] " + txt
def msg_(self, label, *msg)
Returns a message with a label
10.655775
10.511598
1.013716
if self.quiet is False: txt = self._unpack_msg(*msg) print("[" + label + "] " + txt)
def _msg(self, label, *msg)
Prints a message with a label
6.790294
6.837302
0.993125
l = [] for m in msg: l.append(str(m)) return " ".join(l)
def _unpack_msg(self, *msg)
Convert all message elements to string
3.881345
3.048528
1.273187
msg = "" s = "" if rd.hours > 0: if rd.hours > 1: s = "s" msg += colors.bold(str(rd.hours)) + " hour" + s + " " s = "" if rd.minutes > 0: if rd.minutes > 1: s = "s" msg += colors.bold(str(rd....
def _endmsg(self, rd)
Returns an end message with elapsed time
2.328971
2.212044
1.052859
return build_colorized_logger( name=name, config=config, log_level=log_level, log_config_path=log_config_path, handler_name=handler_name, handlers_dict=handlers_dict, enable_splunk=enable_splunk, splunk_user=splunk_user, splunk_password=s...
def simple_logger( name='', config='shared-logging.json', log_level=logging.INFO, log_config_path=None, handler_name='simple', handlers_dict=None, enable_splunk=False, splunk_user=None, splunk_password=None, splunk_address=None, spl...
simple_logger Build a colorized logger for just the message - Used by command line tools. :param name: name that shows in the logger :param config: name of the config file :param log_level: level to log :param log_config_path: path to log config file :param handler_name: handler name in th...
1.274429
1.238648
1.028887
self.org_fields = {} self.fields_to_add = {} for k in new_fields: self.org_fields[k] = new_fields[k] self.fields_to_add[k] = new_fields[k]
def set_fields( self, new_fields)
set_fields Change the fields that will be added in on a log :param new_fields: new fields to patch in
2.333218
2.521409
0.925363
self.fields_to_add = {} for k in self.org_fields: self.fields_to_add[k] = self.org_fields[k] self.fields_to_add.update(update_fields)
def updated_current_fields( self, update_fields)
updated_current_fields :param update_fields: dict with values for updating fields_to_add
2.81939
2.855014
0.987522
super( SplunkFormatter, self).add_fields( log_record, record, message_dict) if not log_record.get('timestamp'): now = datetime.datetime.utcnow().strftime( '%Y-%m-%dT%H:%M:%S.%fZ') log...
def add_fields( self, log_record, record, message_dict)
add_fields :param log_record: log record :param record: log message :param message_dict: message dict
2.152937
2.477491
0.868999
now = datetime.datetime.now() utc_now = datetime.datetime.utcnow() asctime = None if self.datefmt: asctime = now.strftime( self.datefmt) else: asctime = now.strftime( datefmt) message = { 'time...
def format( self, record, datefmt='%Y:%m:%d %H:%M:%S.%f')
format :param record: message object to format
2.634185
2.669533
0.986759
return constant_fold(code, silent=silent, ignore_errors=ignore_errors)
def optimized(code, silent=True, ignore_errors=True)
Performs optimizations on already parsed code.
4.824764
5.306701
0.909183
super(MultilingualSQLCompiler, self).pre_sql_setup() if not self.query.include_translation_data: return opts = self.query.model._meta qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name if hasattr(opts, 'translation_model'): ...
def pre_sql_setup(self)
Adds the JOINS and SELECTS for fetching multilingual data.
2.896821
2.654009
1.091489
result = super(MultilingualSQLCompiler, self).get_from_clause() if not self.query.include_translation_data: return result from_ = result[0] for join in self.query.extra_join.values(): from_.append(join) return (from_, result[1])
def get_from_clause(self)
Add the JOINS for related multilingual fields filtering.
4.93532
4.00977
1.230824
kwargs = {self.fk.get_attname(): self.instance.pk} new_obj = self.model(**kwargs) self._prepare_multilingual_object(new_obj, form) return forms.save_instance(form, new_obj, exclude=[self._pk_field.name], commit=commit)
def save_new(self, form, commit=True)
NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object
4.908768
4.968138
0.98805
self._prepare_multilingual_object(instance, form) return forms.save_instance(form, instance, exclude=[self._pk_field.name], commit=commit)
def save_existing(self, form, instance, commit=True)
NOTE: save_new method is completely overridden here, there's no other way to pretend double save otherwise. Just assign translated data to object
8.433442
7.911962
1.06591
qs = super(MultilingualInlineAdmin, self).queryset(request) # Don't now what the hell I was thinking here, but this code breaks stuff: # # checkfield = self.get_fill_check_field() # if checkfield is not None: # kwargs = {str('%s_%s__isnull' % (checkfield, GLL...
def queryset(self, request)
Filter objects which don't have a value in this language
4.080341
3.920812
1.040688
if not request: return queryset if GLL.is_active: return queryset.filter(language=GLL.language_code) return queryset
def placeholder_plugin_filter(self, request, queryset)
This is only used on models which use placeholders from the django-cms
7.159785
7.133476
1.003688
''' Displays a list of your devices. \b DOES: Displays a list of your devices, as well as their APIs \b USE: wio list ''' user_token = wio.config.get("token", None) api_prefix = wio.config.get("mserver", None) if not api_prefix or not user_token: click.e...
def cli(wio)
Displays a list of your devices. \b DOES: Displays a list of your devices, as well as their APIs \b USE: wio list
2.188946
2.039304
1.073379
try: df = pd.DataFrame() for dsx in dss: df = pd.concat([df, dsx.df], **kwargs) self.df = df except Exception as e: self.err(e, "Can not concatenate data")
def concat(self, *dss, **kwargs)
Concatenate dataswim instances from and set it to the main dataframe :param dss: dataswim instances to concatenate :type dss: Ds :param kwargs: keyword arguments for ``pd.concat``
3.997165
4.000411
0.999189