code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''get node sn and key''' thread = termui.waiting_echo("Getting message from Server...") thread.daemon = True thread.start() try: params = {"name":"node000", "board":board, "access_token":token} r = requests.post("%s%s" %(mserver_url, nodes_create_endpoint), params=params, timeout=10...
def get_new(mserver_url, token, board)
get node sn and key
3.400733
3.125177
1.088173
# note: isfile() also accepts symlinks return os.path.isfile(filename) and filename.lower().endswith(ImageExts)
def is_image(filename)
Determine if given filename is an image.
9.736624
7.957059
1.223646
if not os.path.isdir(directory): print("ERROR: Directory", directory, "not found.") return base = os.path.basename(directory.rstrip(os.path.sep)) zipname = '%s.cbz' % base zipname = os.path.join(directory, zipname) d = os.path.join(directory, 'inorder') if os.path.isdir(d): ...
def create_cbz(directory)
Creates or updates a CBZ from files in the given comic directory.
2.763433
2.725249
1.014011
if isinstance(node, type): mro = node.mro() else: mro = type(node).mro() for cls in mro: meth = getattr(self, 'visit_' + cls.__name__, None) if meth is not None: return meth(node) raise NotImplementedError('No visi...
def visit(self, node)
Visit a node. Calls ``visit_CLASSNAME`` on itself passing ``node``, where ``CLASSNAME`` is the node's class. If the visitor does not implement an appropriate visitation method, will go up the `MRO <https://www.python.org/download/releases/2.3/mro/>`_ until a match is found. ...
2.906394
2.58962
1.122324
if not hasattr(instance, '_translation_cache'): return for l_id, translation in instance._translation_cache.iteritems(): # set the translation ID just in case the translation was # created while instance was not stored in the DB yet # note: we're using _get_pk_val here even...
def translation_save_translated_fields(instance, **kwargs)
Save all the translations of instance in post_save signal handler.
8.042551
7.826455
1.027611
if hasattr(instance, '_translation_cache'): # do not refill the cache return instance._translation_cache = {} # unsafed instances cannot have translations if not instance.pk: return for language_code in get_language_code_list(): # see if translation for langua...
def fill_translation_cache(instance)
Fill the translation cache using information received in the instance objects as extra fields. You can not do this in post_init because the extra fields are assigned by QuerySet.iterator after model initialization.
4.253319
4.156638
1.02326
def get_translation_field(cls, language_code=None, fallback=False): try: return cls.get_translation(language_code, fallback=fallback, field=field_name) except TranslationDoesNotExist: return No...
def getter_generator(field_name, short_description)
Generate get_'field name' method for field field_name.
2.832282
3.002772
0.943222
def set_translation_field(cls, value, language_code=None): setattr(cls.get_translation(language_code, True), field_name, value) set_translation_field.short_description = "set " + field_name return set_translation_field
def setter_generator(field_name)
Generate set_'field name' method for field field_name.
3.939885
3.912739
1.006938
# fill the cache if necessary cls.fill_translation_cache() if language_code is None: language_code = getattr(cls, '_default_language', None) if language_code is None: language_code = get_default_language() force = False if GLL.is_active: language_code = GLL.languag...
def get_translation(cls, language_code, create_if_necessary=False, fallback=False, field=None)
Get a translation instance for the given `language_id_or_code`. If the translation does not exist: 1. if `create_if_necessary` is True, this function will create one 2. otherwise, if `fallback` is True, this function will search the list of languages looking for the first existing translation 3...
2.973242
3.075784
0.966661
# delay the creation of the *Translation until the master model is # fully created signals.class_prepared.connect(cls.finish_multilingual_class, sender=main_cls, weak=False) # connect the post_save signal on master class to a handler # that saves transl...
def contribute_to_class(cls, main_cls, name)
Handle the inner 'Translation' class.
7.675111
7.425941
1.033554
translated_fields = {} for fname, field in cls.__dict__.items(): if isinstance(field, models.fields.Field): translated_fields[fname] = (field, None) # add get_'fname' and set_'fname' methods to main_cls getter = getter_generator(fnam...
def create_translation_attrs(cls, main_cls)
Creates get_'field name'(language_code) and set_'field name'(language_id) methods for all the translation fields. Adds the 'field name' properties too. Returns the translated_fields hash used in field lookups, see multilingual.query. It maps field names to (field, language_id) ...
2.601006
2.430975
1.069943
unique_fields = [] for fname, field in cls.__dict__.items(): if isinstance(field, models.fields.Field): if getattr(field,'unique',False): try: field.unique = False except AttributeError: ...
def get_unique_fields(cls)
Return a list of fields with "unique" attribute, which needs to be augmented by the language.
5.745802
5.722151
1.004133
main_cls = kwargs['sender'] translation_model_name = main_cls.__name__ + "Translation" # create the model with all the translatable fields unique = [('language_code', 'master')] for f in cls.get_unique_fields(): unique.append(('language_code',f)) c...
def finish_multilingual_class(cls, *args, **kwargs)
Create a model with translations of a multilingual class.
3.282811
3.290836
0.997561
archive = cls.url + 'archive.html' data = getPageContent(archive, cls.session) search = compile(tagre("a", "href", r"(\d\d\d\d-\d\d.html)")) archivepages = search.findall(data) return cls.url + archivepages[-1]
def starter(cls)
Pick last one in a list of archive pages.
6.321659
4.910568
1.287358
start = '' tsmatch = compile(r'/(\d+)-').search(imageUrl) if tsmatch: start = datetime.utcfromtimestamp(int(tsmatch.group(1))).strftime("%Y-%m-%d") else: # There were only chapter 1, page 4 and 5 not matching when writing # this... ...
def namer(cls, imageUrl, pageUrl)
Image file name is UNIX time stamp & something for most of the comics...
7.189607
6.389272
1.125262
index = int(compile(r'id=(\d+)').search(pageUrl).group(1)) ext = imageUrl.rsplit('.', 1)[1] return "SnowFlakes-%d.%s" % (index, ext)
def namer(cls, imageUrl, pageUrl)
Use strip index number for image name.
5.150706
4.652218
1.107151
parts, year, month, stripname = pageUrl.rsplit('/', 3) stripname = stripname.rsplit('.', 1)[0] parts, imagename = imageUrl.rsplit('/', 1) return '%s-%s-%s-%s' % (year, month, stripname, imagename)
def namer(cls, imageUrl, pageUrl)
Use page URL to construct meaningful image name.
3.610152
3.613289
0.999132
if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") for arg in args: # The default_alias property may raise a TypeError, so we use # a try/except construct rather than hasattr in order to remain ...
def aggregate(self, *args, **kwargs)
Returns a dictionary containing the calculations (aggregation) over the current queryset If args is present the expression is passed as a kwarg using the Aggregate object's default alias.
5.618827
5.312871
1.057588
# Copy the body of this method from Django except the final # return statement. We will ignore code coverage for this. if using is None and connection is None: # pragma: no cover raise ValueError("Need either using or connection") if using: connection = ...
def get_compiler(self, using=None, connection=None)
Overrides the Query method get_compiler in order to return an instance of the above custom compiler.
4.497603
4.331439
1.038362
CTEQuery._remove_cte_where(self.query) return super(self.__class__, self).as_sql(*args, **kwargs)
def as_sql(self, *args, **kwargs)
Overrides the :class:`SQLUpdateCompiler` method in order to remove any CTE-related WHERE clauses, which are not necessary for UPDATE queries, yet may have been added if this query was cloned from a CTEQuery. :return: :rtype:
6.665208
5.399642
1.23438
def _as_sql(): return super(CTEAggregateQueryCompiler, self).as_sql(*args, **kwargs) return CTECompiler.generate_sql(self.connection, self.query, _as_sql)
def as_sql(self, *args, **kwargs)
Overrides the :class:`SQLAggregateCompiler` method in order to prepend the necessary CTE syntax, as well as perform pre- and post- processing, including adding the extra CTE table and WHERE clauses. :param qn: :type qn: :return: :rtype:
6.179528
5.984346
1.032615
global message_stack message_stack.append((exchange, routing_key, message, properties))
def _add_to_publish_stack(self, exchange, routing_key, message, properties)
Temporarily add the message to the stack to publish to RabbitMQ :param str exchange: The exchange to publish to :param str routing_key: The routing key to publish with :param str message: The message body :param pika.BasicProperties: The message properties
4.249284
4.768602
0.891096
global pending_rabbitmq_connection, rabbitmq_connection if not rabbitmq_connection: LOGGER.info('Creating a new RabbitMQ connection') pending_rabbitmq_connection = self._new_rabbitmq_connection()
def _connect_to_rabbitmq(self)
Connect to RabbitMQ and assign a local attribute
5.384288
4.950221
1.087686
return pika.BasicProperties(content_type, content_encoding, headers, delivery_mode, priority, correlation_id, reply_to, expiration, message_id, timestamp, message_type, user_id, app_id)
def _new_message_properties(self, content_type=None, content_encoding=None, headers=None, delivery_mode=None, priority=None, correlation_id=None, reply_to=None, expiration=None, message_id=None, ...
Create a BasicProperties object, with the properties specified :param str content_type: MIME content type :param str content_encoding: MIME content encoding :param dict headers: Message header field table :param int delivery_mode: Non-persistent (1) or persistent (2) :param int ...
1.692149
1.665784
1.015827
global message_stack if not self._rabbitmq_is_closed and message_stack: LOGGER.info('Publishing %i deferred message(s)', len(message_stack)) while message_stack: self._publish_message(*message_stack.pop())
def _publish_deferred_messages(self)
Called when pika is connected and has a channel open to publish any requests buffered.
4.952281
4.419251
1.120615
if self._rabbitmq_is_closed or not self._rabbitmq_channel: LOGGER.warning('Temporarily buffering message to publish') self._add_to_publish_stack(exchange, routing_key, message, properties) return self._rabbitmq_channel.b...
def _publish_message(self, exchange, routing_key, message, properties)
Publish the message to RabbitMQ :param str exchange: The exchange to publish to :param str routing_key: The routing key to publish with :param str message: The message body :param pika.BasicProperties: The message properties
4.599971
4.886541
0.941355
config = self.application.settings.get('rabbitmq') if not config: raise exceptions.ConfigurationException('rabbitmq') return config
def _rabbitmq_config(self)
Return the RabbitMQ configuration dictionary. :rtype: dict
7.472391
8.256103
0.905075
kwargs = dict(self._rabbitmq_config) kwargs['credentials'] = pika.PlainCredentials(kwargs['username'], kwargs['password']) for key in ['username', 'password']: del kwargs[key] return pika.ConnectionParameters(**...
def _rabbitmq_parameters(self)
Return a pika ConnectionParameters object using the configuration from the configuration service. The configuration dictionary should match the parameters for pika.connection.ConnectionParameters and include an extra username and password variable. :rtype: pika.ConnectionParameters
3.365571
3.320828
1.013473
setattr(self.application.attributes, self.CHANNEL, channel)
def _set_rabbitmq_channel(self, channel)
Assign the channel object to the tinman global object. :param pika.channel.Channel channel: The pika channel
19.806107
29.908653
0.66222
global rabbitmq_connection LOGGER.warning('RabbitMQ has disconnected (%s): %s', reply_code, reply_text) rabbitmq_connection = None self._set_rabbitmq_channel(None) self._connect_to_rabbitmq()
def on_rabbitmq_close(self, reply_code, reply_text)
Called when RabbitMQ has been connected to. :param int reply_code: The code for the disconnect :param str reply_text: The disconnect reason
4.720155
4.963799
0.950916
global pending_rabbitmq_connection, rabbitmq_connection LOGGER.info('RabbitMQ has connected') rabbitmq_connection = connection rabbitmq_connection.add_on_close_callback(self.on_rabbitmq_close) rabbitmq_connection.channel(self.on_rabbitmq_channel_open) pending_rab...
def on_rabbitmq_conn_open(self, connection)
Called when RabbitMQ has been connected to. :param pika.connection.Connection connection: The pika connection
3.150073
3.270042
0.963313
LOGGER.info('Channel %i is opened for communication with RabbitMQ', channel.channel_number) self._set_rabbitmq_channel(channel) self._publish_deferred_messages()
def on_rabbitmq_channel_open(self, channel)
Called when the RabbitMQ accepts the channel open request. :param pika.channel.Channel channel: The channel opened with RabbitMQ
6.114438
7.73017
0.790984
super(RabbitMQRequestHandler, self).prepare() if self._rabbitmq_is_closed: self._connect_to_rabbitmq()
def prepare(self)
Prepare the handler, ensuring RabbitMQ is connected or start a new connection attempt.
11.248034
5.493178
2.047637
url = 'http://www.hagardunor.net/comics.php' data = cls.getPage(url) pattern = compile(tagre("a", "href", cls.prevUrl)) for starturl in cls.fetchUrls(url, data, pattern): pass return starturl
def starter(cls)
Return last gallery link.
11.957298
10.379585
1.152002
packet = _parse_irc_packet(next(self.lines)) #Get next line from generator for event_handler in list(self.on_packet_received): event_handler(self, packet) if packet.command == "PRIVMSG": if packet.arguments[0].startswith("#"): for event_handler ...
def run_once(self)
This function runs one iteration of the IRC client. This is called in a loop by the run_loop function. It can be called separately, but most of the time there is no need to do this.
2.12973
2.072331
1.027698
self.socket.connect((server, port)) self.lines = self._read_lines() for event_handler in list(self.on_connect): event_handler(self)
def connect(self, server, port=6667)
Connects to a given IRC server. After the connection is established, it calls the on_connect event handler.
5.25997
4.062342
1.294812
self.nick = nick self.send_line("NICK {}".format(nick))
def set_nick(self, nick)
Sets or changes your link. This should be called before joining channels, but can be called at any time afterwards. If the requested nickname is not available, the library will keep adding an underscore until a suitable nick is found.
4.214527
4.893137
0.861314
self.classes = list(set(y)) n_points = len(y) if len(X) != n_points: raise Exception('Number of training points should be the same as training labels.') if not self._state_machine: self._state_machine = DefaultStateMachine(self.classes) # Initia...
def fit(self, X, y, verbosity=0)
Fit the model according to the given training data. Parameters ---------- X : List of ndarrays, one for each training example. Each training example's shape is (string1_len, string2_len, n_features), where string1_len and string2_len are the length of the two training st...
3.790324
3.790214
1.000029
parameters = np.ascontiguousarray(self.parameters.T) predictions = [_Model(self._state_machine, x).predict(parameters, self.viterbi) for x in X] predictions = np.array([[probability for _, probability ...
def predict_proba(self, X)
Probability estimates. The returned estimates for all classes are ordered by the label of classes. Parameters ---------- X : List of ndarrays, one for each training example. Each training example's shape is (string1_len, string2_len, n_features, where st...
7.362372
8.944569
0.823111
return [self.classes[prediction.argmax()] for prediction in self.predict_proba(X)]
def predict(self, X)
Predict the class for X. The predicted class for each sample in X is returned. Parameters ---------- X : List of ndarrays, one for each training example. Each training example's shape is (string1_len, string2_len, n_features), where string1_len and s...
4.667882
10.564025
0.441866
return np.zeros((state_machine.n_states + state_machine.n_transitions, n_features))
def _initialize_parameters(state_machine, n_features)
Helper to create initial parameter vector with the correct shape.
4.965665
4.310514
1.151989
return {'l2_regularization': self.l2_regularization, 'optimizer': self._optimizer, 'optimizer_kwargs': self._optimizer_kwargs}
def get_params(self, deep=True)
Get parameters for this estimator. Parameters ---------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Pa...
3.851516
6.464694
0.595777
self.l2_regularization = l2_regularization self._optimizer = optimizer self._optimizer_kwargs = optimizer_kwargs return self
def set_params(self, l2_regularization=0.0, optimizer=None, optimizer_kwargs=None)
Set the parameters of this estimator. Returns ------- self
2.400281
3.143872
0.763479
# If the features are sparse, we can use an optimization. # I'm not using scipy.sparse here because we want to avoid a scipy dependency and also scipy.sparse doesn't seem # to handle arrays of shape higher than 2. if isinstance(self.sparse_x, str) and self.sparse_x == 'uninitial...
def forward_backward(self, parameters)
Run the forward backward algorithm with the given parameters.
3.346923
3.349759
0.999153
x_dot_parameters = np.einsum('ijk,kl->ijl', self.x, parameters) if not viterbi: alpha = forward_predict(self._lattice, x_dot_parameters, self.state_machine.n_states) else: alpha = forward_max_predict(self._lattice, x_dot_param...
def predict(self, parameters, viterbi)
Run forward algorithm to find the predicted distribution over classes.
3.561968
3.424409
1.04017
return forward(self._lattice, x_dot_parameters, self.state_machine.n_states)
def _forward(self, x_dot_parameters)
Helper to calculate the forward weights.
10.486323
8.738653
1.199993
I, J, _ = self.x.shape return backward(self._lattice, x_dot_parameters, I, J, self.state_machine.n_states)
def _backward(self, x_dot_parameters)
Helper to calculate the backward weights.
10.128999
8.690493
1.165526
I, J, K = x.shape new_array_height = (x != 0).sum(axis=2).max() index_array = -np.ones((I, J, new_array_height), dtype='int64') value_array = -np.ones((I, J, new_array_height), dtype='float64') populate_sparse_features(x, index_array, value_array, I, J, K) return...
def _construct_sparse_features(self, x)
Helper to construct a sparse representation of the features.
3.283049
3.089251
1.062733
if status == SUCCESS: return 'SUCCESS' elif status == FAILED: return 'FAILED' elif status == ERR: return 'ERR' elif status == EX: return 'EX' elif status == NOT_RUN: return 'NOT_RUN' elif status == INVALID: return 'INVALID' elif status == ...
def get_status( status)
get_status Return the string label for an integer status code which should be one of the ones above. :param status: integer status code
2.759809
2.917262
0.946027
try: renderer = pytablewriter.HtmlTableWriter data = self._build_export(renderer) return data except Exception as e: self.err(e, "Can not convert data to html")
def to_html_(self) -> str
Convert the main dataframe to html :return: html data :rtype: str :example: ``ds.to_html_()``
9.898521
9.386043
1.0546
try: renderer = pytablewriter.JsonTableWriter data = self._build_export(renderer) return data except Exception as e: self.err(e, "Can not convert data to json")
def to_json_(self) -> str
Convert the main dataframe to json :return: json data :rtype: str :example: ``ds.to_json_()``
10.16753
10.753851
0.945478
try: renderer = pytablewriter.JavaScriptTableWriter data = self._build_export(renderer, table_name) return data except Exception as e: self.err(e, "Can not convert data to javascript code")
def to_javascript_(self, table_name: str="data") -> str
Convert the main dataframe to javascript code :param table_name: javascript variable name, defaults to "data" :param table_name: str, optional :return: a javascript constant with the data :rtype: str :example: ``ds.to_javastript_("myconst")``
8.997919
10.15104
0.886404
try: renderer = pytablewriter.MarkdownTableWriter data = self._build_export(renderer) return data except Exception as e: self.err(e, "Can not convert data to markdown")
def to_markdown_(self) -> str
Convert the main dataframe to markdown :return: markdown data :rtype: str :example: ``ds.to_markdown_()``
9.879169
9.417393
1.049034
try: renderer = pytablewriter.RstGridTableWriter data = self._build_export(renderer) return data except Exception as e: self.err(e, "Can not convert data to restructured text")
def to_rst_(self) -> str
Convert the main dataframe to restructured text :return: rst data :rtype: str :example: ``ds.to_rst_()``
10.240457
9.257877
1.106134
try: renderer = pytablewriter.PythonCodeTableWriter data = self._build_export(renderer, table_name) return data except Exception as e: self.err(e, "Can not convert data to python list")
def to_python_(self, table_name: str="data") -> list
Convert the main dataframe to python a python list :param table_name: python variable name, defaults to "data" :param table_name: str, optional :return: a python list of lists with the data :rtype: str :example: ``ds.to_python_("myvar")``
10.227528
11.058604
0.924848
try: renderer = pytablewriter.NumpyTableWriter data = self._build_export(renderer, table_name) return data except Exception as e: self.err(e, "Can not convert data to numpy array")
def to_numpy_(self, table_name: str="data") -> numpy.array
Convert the main dataframe to a numpy array :param table_name: name of the python variable, defaults to "data" :param table_name: str, optional :return: a numpy array :rtype: np.array :example: ``ds.to_numpy_("myvar")``
8.823698
10.528691
0.838062
try: dic = self.df.to_dict(orient="records") return dic except Exception as e: self.err(e, "Can not convert data to records")
def to_records_(self) -> dict
Returns a list of dictionary records from the main dataframe :return: a python dictionnary with the data :rtype: str :example: ``ds.to_records_()``
5.356964
5.14794
1.040604
try: self.start("Saving data to "+filepath + " ...") if self.datapath is not None: if filepath.startswith("/") is False and \ filepath.startswith(".") is False: filepath = self.datapath + "/" + filepath self...
def to_csv(self, filepath: str, index: bool=False, **kwargs)
Write the main dataframe to a csv file :param filepath: path of the file to save :type filepath: str :param index: [description], defaults to False :param index: bool, optional :param \*args: arguments to pass to ``pd.to_csv`` :example: ``ds.to_csv_("myfile.csv", header...
4.142049
4.26669
0.970787
try: self.start("Saving data to Excell file: "+filepath + " ...") writer = pytablewriter.ExcelXlsxTableWriter() writer.from_dataframe(self.df) writer.open(filepath) writer.make_worksheet(title) writer.write_table() writ...
def to_excel(self, filepath: str, title: str)
Write the main dataframe to an Excell file :param filepath: path of the Excel file to write :type filepath: str :param title: Title of the stylesheet :type title: str :example: ``ds.to_excel_("./myfile.xlsx", "My data")``
5.404273
5.297007
1.02025
try: self.start("Saving data to Hdf5...") dd.io.save(filepath, self.df) self.end("Finished saving Hdf5 data") except Exception as e: self.err(e, "Can not convert data to Hdf5")
def to_hdf5(self, filepath: str)
Write the main dataframe to Hdf5 file :param filepath: path where to save the file :type filepath: str :example: ``ds.to_hdf5_("./myfile.hdf5")``
5.750396
5.513174
1.043028
# validate tree tree = tree.get_public_object() assert tree.application_urls == 'CMSArticlesApp' # validate template assert template in [tpl[0] for tpl in settings.CMS_ARTICLES_TEMPLATES] get_template(template) # validate language: assert language in get_language_list(tree.node.s...
def create_article(tree, template, title, language, slug=None, description=None, page_title=None, menu_title=None, meta_description=None, created_by=None, image=None, publication_date=None, publication_end_date=None, published=False, login_required=False, creatio...
Create a CMS Article and it's title for the given language
2.404796
2.384793
1.008388
# validate article assert isinstance(article, Article) # validate language: assert language in get_language_list(article.tree.node.site_id) # validate creation date if creation_date: assert isinstance(creation_date, datetime.date) # set default slug: if not slug: ...
def create_title(article, language, title, slug=None, description=None, page_title=None, menu_title=None, meta_description=None, creation_date=None, image=None)
Create an article title.
2.408443
2.410447
0.999169
placeholder = obj.placeholders.get(slot=slot) add_plugin(placeholder, TextPlugin, language, body=content)
def add_content(obj, language, slot, content)
Adds a TextPlugin with given content to given slot
4.486689
3.292627
1.362647
article = article.reload() # get username if changed_by: username = changed_by.get_username() else: username = 'script' with current_user(username): article.publish(language) return article.reload()
def publish_article(article, language, changed_by=None)
Publish an article. This sets `article.published` to `True` and calls article.publish() which does the actual publishing.
5.800815
5.374091
1.079404
name = module.__name__[:-6] if module.__name__.endswith('Module') else module.__name__ return name.lower()
def _get_module_name(module)
Return the module name. >>> from openprovider.modules import CustomerModule >>> _get_module_name(CustomerModule) 'customer' >>> _get_module_name(OpenProvider) 'openprovider'
4.459219
5.645267
0.789904
apirequest = lxml.etree.tostring( E.openXML( E.credentials( E.username(self.username), OE('password', self.password), OE('hash', self.password_hash), ), tree ), ...
def request(self, tree, **kwargs)
Construct a new request with the given tree as its contents, then ship it to the OpenProvider API.
3.762864
3.705041
1.015607
if os.path.exists(fname): with open(fname) as hive_file: return cls(**json.load(hive_file)).from_version(version, require_https=require_https) else: raise MissingHive(fname)
def from_file(cls, fname, version=None, require_https=True)
Create a Hive object based on JSON located in a local file.
3.980036
2.88492
1.3796
if "https://" in url: require_https = True if "http://" in url and require_https: try: hive = cls.from_url(url, version=version, require_https=False) except HiveLoadedOverHTTP as err: hive = err.hive raise HiveLoade...
def from_url(cls, url, version=None, require_https=False)
Create a Hive object based on JSON located at a remote URL.
4.768129
4.061457
1.173995
url = 'https://' + domain + '/api/hive.json' try: return cls.from_url(url, version=version, require_https=require_https) except MissingHive: url = 'http://' + domain + '/api/hive.json' return cls.from_url(url, version=version, require_https=require_ht...
def from_domain(cls, domain, version=None, require_https=True)
Try to find a hive for the given domain; raise an error if we have to failover to HTTP and haven't explicitly suppressed it in the call.
2.431735
1.903516
1.277497
if version is None or self.version() == version: return self else: return Hive.from_url(self.get_version_url(version), require_https=require_https)
def from_version(self, version, require_https=False)
Create a Hive object based on the information in the object and the version passed into the method.
3.956911
2.85159
1.387616
for each_version in self.other_versions(): if version == each_version['version'] and 'location' in each_version: return each_version.get('location') raise VersionNotInHive(version)
def get_version_url(self, version)
Retrieve the URL for the designated version of the hive.
6.246194
4.642349
1.345481
try: self.dsmap = self._marker( lat, long, text, self.dsmap, color, icon, True, style) return self.dsmap except Exception as e: self.err(e, self.tmarker, "Can not get text marker")
def tmarker(self, lat, long, text, color=None, icon=None, style=None)
Returns the map with a text marker to the default map
6.318309
5.703501
1.107795
try: xmap = self._marker( lat, long, text, pmap, color, icon, True, style) return xmap except Exception as e: self.err(e, self.tmarker_, "Can not get text marker")
def tmarker_(self, lat, long, text, pmap, color=None, icon=None, style=None)
Returns the map with a text marker to the default map
6.039736
5.634448
1.07193
try: xmap = self._marker(lat, long, text, pmap, color, icon) return xmap except Exception as e: self.err(e, self.marker_, "Can not get marker")
def marker_(self, lat, long, text, pmap, color=None, icon=None)
Returns the map with a marker to the default map
4.714797
4.621823
1.020116
try: self.dsmap = self._marker(lat, long, text, self.dsmap, color, icon) return self.dsmap except Exception as e: self.err(e, self.marker, "Can not get marker")
def marker(self, lat, long, text, color=None, icon=None)
Set the main map with a marker to the default map
5.371134
5.408614
0.99307
kwargs = {} if icon is not None: kwargs["icon"] = icon if color is not None: kwargs["color"] = color if style is None: style = "font-size:18pt;font-weight:bold;" + \ "color:black;border-radius:0.5" try: xico...
def _marker(self, lat, long, text, xmap, color=None, icon=None, text_mark=False, style=None)
Adds a marker to the default map
2.761011
2.731518
1.010797
try: return self._map(lat, long, zoom, tiles) except Exception as e: self.err(e, self.map_, "Can not get map")
def map_(self, lat, long, zoom=13, tiles="map")
Returns a map
5.145942
5.145296
1.000126
try: self.dsmap = self._map(lat, long, zoom, tiles) except Exception as e: self.err(e, self.map, "Can not get map")
def map(self, lat, long, zoom=13, tiles="map")
Sets a map
6.508188
6.574693
0.989885
if tiles == "map": tiles = "OpenStreetMap" elif tiles == "terrain": tiles = "Stamen Terrain" elif tiles == "basic": tiles = "Stamen Toner" try: xmap = folium.Map( location=[lat, long], tiles=tiles, ...
def _map(self, lat, long, zoom, tiles)
Returns a map
3.278323
3.239175
1.012086
return E(element, transform(value)) if value is not None else None
def OE(element, value, transform=lambda x: x)
Create an Optional Element. Returns an Element as ElementMaker would, unless value is None. Optionally the value can be transformed through a function. >>> OE('elem', None) None >>> lxml.etree.tostring(OE('elem', 'value')) <elem>value</elem> >>> lxml.etree.tostring(OE('elem', True, int))...
6.225919
11.721498
0.531154
def func(self, *args, **kwargs): return self._call_command(command_name, *args, **kwargs) return func
def _make_command_method(cls, command_name)
Return a function which call _call_command for the given name. Used to bind redis commands to our own calls
2.756052
2.262815
1.217975
obj = getattr(self, '_instance', self) # _instance if a field, self if an instance # The object may not be already connected, so if we want to update a # field, connect it before. # If the object as no PK yet, let the object create itself if name in self.available_modi...
def _call_command(self, name, *args, **kwargs)
Check if the command to be executed is a modifier, to connect the object. Then call _traverse_command.
11.275288
9.0411
1.247115
if not name in self.available_commands: raise AttributeError("%s is not an available command for %s" % (name, self.__class__.__name__)) attr = getattr(self.connection, "%s" % name) key = self.key log.debug(u"Requesting %s with key %s ...
def _traverse_command(self, name, *args, **kwargs)
Add the key to the args and call the Redis command.
3.454115
3.086083
1.119255
setter = getattr(self, self.proxy_setter) if isinstance(value, (list, tuple, set)): result = setter(*value) elif isinstance(value, dict): result = setter(**value) else: result = setter(value) return result
def proxy_set(self, value)
A helper to easily call the proxy_setter of the field
2.689388
2.364971
1.137176
return self.make_key( self._instance._name, self._instance.pk.get(), self.name, )
def key(self)
A property to return the key used in redis for the current field.
10.267691
6.756013
1.519786
return self._instance.post_command( sender=self, name=name, result=result, args=args, kwargs=kwargs )
def post_command(self, sender, name, result, args, kwargs)
Call after we got the result of a redis command. By default, let the instance manage the post_modify signal
3.878029
3.729105
1.039936
try: key = self.key except DoesNotExist: return False else: return self.connection.exists(key)
def exists(self)
Call the exists command to check if the redis key exists for the current field
8.160029
6.636877
1.229498
if not self.indexable: return [] if not self.index_classes: self.index_classes = self.get_default_indexes()[::1] if not self.index_classes: raise ImplementationError('%s field is indexable but has no indexes attached' % ...
def _indexes(self)
Instantiate the indexes only when asked Returns ------- list An empty list if the field is not indexable, else a list of all indexes tied to the field. If no indexes where passed when creating the field, the default indexes from the field/model/da...
4.514603
3.392066
1.33093
klass = index if isclass(index) else index.__class__ for one_index in self._indexes: if isinstance(one_index, klass): return True return False
def has_index(self, index)
Tells if the field have an index matching the current one Parameters ----------- index: type or BaseIndex It could be an index instance, or an index class Returns ------- bool Will be ``True`` if the current field has an index that is an instance...
4.655184
5.767354
0.807161
self._instance = instance self.lockable = self.lockable and instance.lockable
def _attach_to_instance(self, instance)
Attach the current field to an instance of a model. Can be overriden to do something when an instance is set
9.156471
10.670731
0.858092
try: if not bool(self._model): return False except AttributeError: return False else: try: return not bool(self._instance) except AttributeError: return True
def attached_to_model(self)
Tells if the current field is the one attached to the model, not instance
4.207534
3.49579
1.2036
meth = super(RedisField, self)._call_command if self.indexable and name in self.available_modifiers: with FieldLock(self): try: result = meth(name, *args, **kwargs) except: self._rollback_indexes() ...
def _call_command(self, name, *args, **kwargs)
Add lock management and call parent.
4.830895
4.505377
1.072251
assert self.indexable, "Field not indexable" assert self.attached_to_model, \ '`rebuild_indexes` can only be called on a field attached to the model' for index in self._indexes: if index_class and not isinstance(index, index_class): continue ...
def clear_indexes(self, chunk_size=1000, aggressive=False, index_class=None)
Clear all indexes tied to this field Parameters ---------- chunk_size: int Default to 1000, it's the number of instances to load at once if not in aggressive mode. aggressive: bool Default to ``False``. When ``False``, the actual collection of instances will ...
4.153534
5.452312
0.761793
assert self.indexable, "Field not indexable" assert self.attached_to_model, \ '`rebuild_indexes` can only be called on a field attached to the model' for index in self._indexes: if index_class and not isinstance(index, index_class): continue ...
def rebuild_indexes(self, chunk_size=1000, aggressive_clear=False, index_class=None)
Rebuild all indexes tied to this field Parameters ---------- chunk_size: int Default to 1000, it's the number of instances to load at once. aggressive_clear: bool Will be passed to the `aggressive` argument of the `clear_indexes` method. If `False`, a...
3.537079
4.26335
0.829648
if self.indexable: self.deindex() result = self._traverse_command(command, *args, **kwargs) if self.indexable: self.index() return result
def _reset(self, command, *args, **kwargs)
Shortcut for commands that reset values of the field. All will be deindexed and reindexed.
4.647995
3.091727
1.503365
if self.indexable: self.deindex() return self._traverse_command(command, *args, **kwargs)
def _del(self, command, *args, **kwargs)
Shortcut for commands that remove all values of the field. All will be deindexed.
8.768629
4.970298
1.764206
if self.indexable: current = self.proxy_get() if normalize(current) != normalize(value): if current is not None: self.deindex(current) if value is not None: self.index(value) return self._traverse_co...
def _call_set(self, command, value, *args, **kwargs)
Helper for commands that only set a value to the field.
4.723977
4.429892
1.066387
result = self._traverse_command(command, value) if self.indexable and value is not None and result: self.index(value) return result
def _call_setnx(self, command, value)
Index only if value has been set.
7.880365
6.666377
1.182106
if self.indexable: self.index(args) return self._traverse_command(command, *args, **kwargs)
def _add(self, command, *args, **kwargs)
Shortcut for commands that only add values to the field. Added values will be indexed.
8.166802
5.47682
1.491158
if self.indexable: self.deindex(args) return self._traverse_command(command, *args, **kwargs)
def _rem(self, command, *args, **kwargs)
Shortcut for commands that only remove values from the field. Removed values will be deindexed.
9.569915
5.506188
1.738029