code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
assert isinstance(date_str, str)
self.value = datetime.strptime(date_str, ISO_DATE_FORMAT)
return self.value | def from_iso_date_string(self, date_str: str) -> datetime | Parse ISO date string (YYYY-MM-DD) | 4.345118 | 3.544299 | 1.225946 |
weekday = self.value.isoweekday() - 1
return calendar.day_name[weekday] | def get_day_name(self) -> str | Returns the day name | 6.093337 | 4.823176 | 1.263345 |
assert isinstance(self.value, datetime)
return datetime.isoformat(self.value) | def to_iso_string(self) -> str | Returns full ISO string for the given date | 6.451558 | 5.355272 | 1.204712 |
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59)
return self.value | def end_of_day(self) -> datetime | End of day | 2.488649 | 2.255961 | 1.103144 |
# Increase month by 1,
result = self.value + relativedelta(months=1)
# take the 1st day of the (next) month,
result = result.replace(day=1)
# subtract one day
result = result - relativedelta(days=1)
self.value = result
return self.value | def end_of_month(self) -> datetime | Provides end of the month for the given date | 4.404643 | 4.117374 | 1.06977 |
end_of_month = Datum()
# get_end_of_month(value)
end_of_month.end_of_month()
return self.value == end_of_month.value | def is_end_of_month(self) -> bool | Checks if the date is at the end of the month | 5.676325 | 4.800048 | 1.182556 |
self.value = self.value.replace(day=day)
return self.value | def set_day(self, day: int) -> datetime | Sets the day value | 5.071026 | 3.474177 | 1.459634 |
assert isinstance(value, datetime)
self.value = value | def set_value(self, value: datetime) | Sets the current value | 10.09073 | 8.017517 | 1.258585 |
self.value = datetime(self.value.year, self.value.month, self.value.day)
return self.value | def start_of_day(self) -> datetime | Returns start of day | 3.465552 | 2.838416 | 1.220946 |
self.value = self.value - relativedelta(days=days)
return self.value | def subtract_days(self, days: int) -> datetime | Subtracts dates from the given value | 5.042776 | 3.567045 | 1.413713 |
self.value = self.value - timedelta(weeks=weeks)
return self.value | def subtract_weeks(self, weeks: int) -> datetime | Subtracts number of weeks from the current value | 4.261898 | 2.873687 | 1.483076 |
self.value = self.value - relativedelta(months=months)
return self.value | def subtract_months(self, months: int) -> datetime | Subtracts a number of months from the current value | 4.625264 | 3.002321 | 1.540563 |
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}" | def to_short_time_string(self) -> str | Return the iso time string only | 3.695938 | 3.324766 | 1.111639 |
hour = self.time.hour
minute = self.time.minute
second = self.time.second
return f"{hour:02}:{minute:02}:{second:02}" | def to_long_time_string(self) -> str | Return the iso time string only | 2.530724 | 2.288852 | 1.105674 |
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}" | def to_iso_time_string(self) -> str | Return the iso time string only | 5.582317 | 4.492262 | 1.242652 |
date_display = self.to_iso_date_string()
time_display = self.to_long_time_string()
return f"{date_display} {time_display}" | def to_datetime_string(self) -> str | Returns a human-readable string representation with iso date and time
Example: 2018-12-06 12:32:56 | 4.362482 | 3.357556 | 1.299303 |
date_display = self.to_iso_date_string()
time_display = self.to_short_time_string()
return f"{date_display} {time_display}" | def to_long_datetime_string(self) -> str | Returns the long date/time string
Example: 2018-12-06 12:34 | 3.862364 | 3.472528 | 1.112263 |
self.value = datetime.combine(datetime.today().date(), time.min)
return self.value | def today(self) -> datetime | Returns today (date only) as datetime | 6.588646 | 4.755856 | 1.385375 |
self.value = datetime.today() - timedelta(days=1)
return self.value | def yesterday(self) -> datetime | Set the value to yesterday | 5.713386 | 3.229612 | 1.769063 |
if low is None or high is None:
return None
x = ''.join([parse_part(low), parse_part(high)])
return '-'.join([x[:8], x[8:12], x[12:16], x[16:20], x[20:32]]) | def get_uuid_string(low=None, high=None, **x) | This method parses a UUID protobuf message type from its component
'high' and 'low' longs into a standard formatted UUID string
Args:
x (dict): containing keys, 'low' and 'high' corresponding to the UUID
protobuf message type
Returns:
str: UUID formatted string | 2.746888 | 3.283992 | 0.836448 |
res = requests.get('https://zenodo.org/record/'+self.data['conceptrecid'])
soup = BeautifulSoup(res.text, 'html.parser')
version_rows = soup.select('.well.metadata > table.table tr')
if len(version_rows) == 0: # when only 1 version
return [{
'recid':... | def get_versions_from_webpage(self) | Get version details from Zenodo webpage (it is not available in the REST api) | 3.775236 | 3.447232 | 1.09515 |
search = search.replace('/', ' ') # zenodo can't handle '/' in search query
params = {'q': search}
return self._get_records(params) | def search(self, search) | search Zenodo record for string `search`
:param search: string to search
:return: Record[] results | 9.078297 | 8.204699 | 1.106475 |
pks = qdict.getlist(k)
return [e for e in pks if e] | def qdict_get_list(qdict, k) | get list from QueryDict and remove blank date from list. | 5.13863 | 3.822637 | 1.344263 |
next_url = request.POST.get('next')\
or request.GET.get('next')\
or request.META.get('HTTP_REFERER')\
or default_next
return next_url | def request_get_next(request, default_next) | get next url form request
order: POST.next GET.next HTTP_REFERER, default_next | 2.294974 | 2.064615 | 1.111575 |
if 'X-Progress-ID' in request.GET:
progress_id = request.GET['X-Progress-ID']
elif 'X-Progress-ID' in request.META:
progress_id = request.META['X-Progress-ID']
if 'logfilename' in request.GET:
logfilename = request.GET['logfilename']
elif 'logfilename' in request.META:
... | def upload_progress(request) | AJAX view adapted from django-progressbarupload
Return the upload progress and total length values | 2.102065 | 2.132474 | 0.98574 |
raise NotImplementedError | def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout) | Set foreground- and background colors and intensity. | 1,909.993896 | 625.235291 | 3.05484 |
do_append = self.__check_new(entity)
if do_append:
self.__entities.append(entity) | def add(self, entity) | Adds the given entity to this cache.
:param entity: Entity to add.
:type entity: Object implementing :class:`everest.interfaces.IEntity`.
:raises ValueError: If the ID of the entity to add is ``None``
(unless the `allow_none_id` constructor argument was set). | 6.216183 | 7.913877 | 0.785479 |
self.__id_map.pop(entity.id, None)
self.__slug_map.pop(entity.slug, None)
self.__entities.remove(entity) | def remove(self, entity) | Removes the given entity from this cache.
:param entity: Entity to remove.
:type entity: Object implementing :class:`everest.interfaces.IEntity`.
:raises KeyError: If the given entity is not in this cache.
:raises ValueError: If the ID of the given entity is `None`. | 3.710611 | 4.177777 | 0.888178 |
ents = iter(self.__entities)
if not filter_expression is None:
ents = filter_expression(ents)
if not order_expression is None:
# Ordering always involves a copy and conversion to a list, so
# we have to wrap in an iterator.
ents = iter(ord... | def retrieve(self, filter_expression=None,
order_expression=None, slice_key=None) | Retrieve entities from this cache, possibly after filtering, ordering
and slicing. | 3.553186 | 3.4083 | 1.04251 |
####################################################################################################################
# Extract keywords serially.
####################################################################################################################
for user_twitter_id, twitter_lists_l... | def extract_user_keywords_generator(twitter_lists_gen, lemmatizing="wordnet") | Based on the user-related lists I have downloaded, annotate the users.
Inputs: - twitter_lists_gen: A python generator that yields a user Twitter id and a generator of Twitter lists.
- lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet".
Yields: - user_twitter_... | 2.809761 | 1.983582 | 1.416509 |
user_label_matrix, annotated_nodes, label_to_lemma, node_to_lemma_tokeywordbag = form_user_term_matrix(user_twitter_list_keywords_gen,
id_to_node,
... | def form_user_label_matrix(user_twitter_list_keywords_gen, id_to_node, max_number_of_labels) | Forms the user-label matrix to be used in multi-label classification.
Input: - user_twitter_list_keywords_gen:
- id_to_node: A Twitter id to node map as a python dictionary.
Outputs: - user_label_matrix: A user-to-label matrix in scipy sparse matrix format.
- annotated_nodes: A nu... | 2.815405 | 2.718374 | 1.035695 |
# Reduce relevant lemma-to-original keyword bags.
lemma_to_keywordbag = defaultdict(lambda: defaultdict(int))
for node in annotated_nodes:
for lemma, keywordbag in node_to_lemma_tokeywordbag[node].items():
for keyword, multiplicity in keywordbag.items():
lemma_to_key... | def form_lemma_tokeyword_map(annotated_nodes, node_to_lemma_tokeywordbag) | Forms the aggregated dictionary that maps lemmas/stems to the most popular topic keyword.
Inputs: - annotated_nodes: A numpy array of anonymized nodes that are annotated.
- node_to_lemma_tokeywordbag: A map from nodes to maps from lemmas to bags of keywords.
Output: - lemma_to_keyword: A dictionar... | 2.229551 | 2.297184 | 0.970559 |
####################################################################################################################
# Log into my application.
####################################################################################################################
twitter = login(twitter_app_key,
... | def fetch_twitter_lists_for_user_ids_generator(twitter_app_key,
twitter_app_secret,
user_id_list) | Collects at most 500 Twitter lists for each user from an input list of Twitter user ids.
Inputs: - twitter_app_key: What is says on the tin.
- twitter_app_secret: Ditto.
- user_id_list: A python list of Twitter user ids.
Yields: - user_twitter_id: A Twitter user id.
- twitt... | 2.840566 | 2.631475 | 1.079458 |
# Sort the centrality vector according to decreasing centrality.
centrality_vector = np.asarray(centrality_vector)
ind = np.argsort(np.squeeze(centrality_vector))
if centrality_vector.size > 1:
reversed_ind = ind[::-1]
else:
reversed_ind = list()
reversed_ind = reversed_... | def decide_which_users_to_annotate(centrality_vector,
number_to_annotate,
already_annotated,
node_to_id) | Sorts a centrality vector and returns the Twitter user ids that are to be annotated.
Inputs: - centrality_vector: A numpy array vector, that contains the centrality values for all users.
- number_to_annotate: The number of users to annotate.
- already_annotated: A python set of user twitter... | 2.663401 | 2.563591 | 1.038934 |
####################################################################################################################
# Log into my application
####################################################################################################################
twitter = login(twitter_app_key, twitte... | def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id) | A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this. | 3.363445 | 3.285161 | 1.02383 |
reg = get_current_registry()
if IInterface in provided_by(resource):
member_class = reg.getUtility(resource, name='member-class')
else:
member_class = reg.getAdapter(resource, IMemberResource,
name='member-class')
return member_class | def get_member_class(resource) | Returns the registered member class for the given resource.
:param resource: registered resource
:type resource: class implementing or instance providing or subclass of
a registered resource interface. | 4.712029 | 4.148254 | 1.135906 |
reg = get_current_registry()
if IInterface in provided_by(resource):
coll_class = reg.getUtility(resource, name='collection-class')
else:
coll_class = reg.getAdapter(resource, ICollectionResource,
name='collection-class')
return coll_class | def get_collection_class(resource) | Returns the registered collection resource class for the given marker
interface or member resource class or instance.
:param rc: registered resource
:type rc: class implementing or instance providing or subclass of
a registered resource interface. | 5.121049 | 5.180108 | 0.988599 |
reg = get_current_registry()
rc = reg.getAdapter(entity, IMemberResource)
if not parent is None:
rc.__parent__ = parent # interface method pylint: disable=E1121
return rc | def as_member(entity, parent=None) | Adapts an object to a location aware member resource.
:param entity: a domain object for which a resource adapter has been
registered
:type entity: an object implementing
:class:`everest.entities.interfaces.IEntity`
:param parent: optional parent collection resource to make the new member
... | 9.530625 | 7.712987 | 1.235659 |
path = model_path(resource)
parsed = list(urlparse.urlparse(path))
parsed[1] = ""
return urlparse.urlunparse(parsed) | def get_resource_url(resource) | Returns the URL for the given resource. | 4.279337 | 3.989633 | 1.072614 |
if isinstance(obj, type):
obj = object.__new__(obj)
return IResource in provided_by(obj) | def provides_resource(obj) | Checks if the given type or instance provides the
:class:`everest.resources.interfaces.IResource` interface. | 9.515319 | 6.444895 | 1.476412 |
if isinstance(obj, type):
obj = object.__new__(obj)
return IMemberResource in provided_by(obj) | def provides_member_resource(obj) | Checks if the given type or instance provides the
:class:`everest.resources.interfaces.IMemberResource` interface. | 9.217422 | 5.677337 | 1.623547 |
if isinstance(obj, type):
obj = object.__new__(obj)
return ICollectionResource in provided_by(obj) | def provides_collection_resource(obj) | Checks if the given type or instance provides the
:class:`everest.resources.interfaces.ICollectionResource` interface. | 9.7117 | 7.30716 | 1.329066 |
reg = get_current_registry()
return [util.component
for util in reg.registeredUtilities()
if util.name == 'collection-class'] | def get_registered_collection_resources() | Returns a list of all registered collection resource classes. | 12.317055 | 10.407607 | 1.183467 |
if request is None:
request = get_current_request()
# cnv = request.registry.getAdapter(request, IResourceUrlConverter)
reg = get_current_registry()
cnv = reg.getAdapter(request, IResourceUrlConverter)
return cnv.resource_to_url(resource, quote=quote) | def resource_to_url(resource, request=None, quote=False) | Converts the given resource to a URL.
:param request: Request object (required for the host name part of the
URL). If this is not given, the current request is used.
:param bool quote: If set, the URL returned will be quoted. | 3.271911 | 4.221852 | 0.774994 |
if request is None:
request = get_current_request()
# cnv = request.registry.getAdapter(request, IResourceUrlConverter)
reg = get_current_registry()
cnv = reg.getAdapter(request, IResourceUrlConverter)
return cnv.url_to_resource(url) | def url_to_resource(url, request=None) | Converts the given URL to a resource.
:param request: Request object (required for the host name part of the
URL). If this is not given, the current request is used. | 3.408187 | 4.070641 | 0.837261 |
return (fp / float(tn + fp) + fn / float(fn + tp)) / 2 | def ber(tp, tn, fp, fn) | Balanced Error Rate [0, 1]
:param int tp: number of true positives
:param int tn: number of true negatives
:param int fp: number of false positives
:param int fn: number of false negatives
:rtype: float | 4.304718 | 6.283406 | 0.685093 |
if tp + fp == 0 or tp + fn == 0 or tn + fp == 0 or tn + fn == 0:
den = 1.0
else:
den = math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
return (tp * tn - fp * fn) / den | def mcc(tp, tn, fp, fn) | Matthew's Correlation Coefficient [-1, 1]
0 = you're just guessing
:param int tp: number of true positives
:param int tn: number of true negatives
:param int fp: number of false positives
:param int fn: number of false negatives
:rtype: float | 1.737191 | 1.83136 | 0.94858 |
assert len(exp) == len(obs)
return numpy.mean((numpy.array(exp) - numpy.array(obs)) ** 2) | def mse(exp, obs) | Mean Squared Error
:param exp: expected values
:type exp: list of float
:param obs: observed values
:type obs: list of float | 2.696159 | 2.791726 | 0.965768 |
assert len(x) == len(y)
l = len(x)
p_x = Counter(x)
p_y = Counter(y)
p_xy = Counter(zip(x, y))
return sum(p_xy[(x, y)] * math.log((p_xy[(x, y)] * l) / float(p_x[x] * p_y[y]), 2) / l
for x, y in p_xy) | def mui(x, y) | MUtial Information | 2.444719 | 2.421835 | 1.009449 |
assert len(clss) == len(vals)
global X, Y, A, T, M, B
order = numpy.argsort(vals)
if reverse:
order = order[::-1]
clss = numpy.array(clss)[order]
vals = numpy.array(vals)[order]
length = len(clss) + 1
data = numpy.empty((length, 6), dtype=numpy.float32)
data[0,... | def roc(clss, vals, reverse=False) | Reciever Operator Characteristic
:param clss: known classes. 1 if positive case, -1 if the negative case
:type class: list of boolean
:param vals: classification probabilites etc...
:type vals: list of real numbers
:param bool reverse: whether the values should be sorted in reverse order | 2.092315 | 2.163254 | 0.967207 |
assert len(exp) == len(obs)
# Expected in the first dimension (0;rows), observed in the second (1;cols)
lbls = sorted(set(exp))
res = numpy.zeros(shape=(len(lbls), len(lbls)))
for i in range(len(exp)):
res[lbls.index(exp[i]), lbls.index(obs[i])] += 1
return res, lbls | def confusion_matrix(exp, obs) | Create a confusion matrix
In each axis of the resulting confusion matrix the negative case is
0-index and the positive case 1-index. The labels get sorted, in a
True/False scenario true positives will occur at (1,1). The first dimension
(rows) of the resulting matrix is the expected class and the s... | 3.2644 | 2.852548 | 1.14438 |
if mat.shape[0] != mat.shape[1] or mat.shape < (2, 2):
raise TypeError('{} is not a confusion matrix'.format(mat))
elif mat.shape == (2, 2):
return fn(mat[TP], mat[TN], mat[FP], mat[FN])
res = numpy.empty(mat.shape[0])
for i in range(len(res)):
res[i] = fn(mat[i, i], ... | def confusion_performance(mat, fn) | Apply a performance function to a confusion matrix
:param mat: confusion matrix
:type mat: square matrix
:param function fn: performance function | 2.585096 | 2.647214 | 0.976535 |
reg = get_current_registry()
if IInterface in provided_by(resource):
ent_cls = reg.getUtility(resource, name='entity-class')
else:
ent_cls = reg.getAdapter(resource, IEntity, name='entity-class')
return ent_cls | def get_entity_class(resource) | Returns the entity class registered for the given registered resource.
:param resource: registered resource
:type collection: class implementing or instance providing a registered
resource interface.
:return: entity class
(class implementing `everest.entities.interfaces.IEntity`) | 4.673594 | 4.546151 | 1.028033 |
if prebump not in REL_TYPES:
raise ValueError(f'{type_} not in {REL_TYPES}')
prebump = REL_TYPES.index(prebump)
version = _read_version()
version = _bump_release(version, type_)
_write_version(version)
# Needs to happen before Towncrier deletes fragment files.
tag_content = _r... | def release(ctx, type_, repo, prebump=PREBUMP) | Make a new release. | 4.025134 | 3.956595 | 1.017323 |
bunch = AutoBunch()
board_id = '{mcu}_{f_cpu}_{programmer}'.format(f_cpu=f_cpu,
mcu=mcu,
programmer=programmer,
)
bunch.name = '{mcu}@{f} Prog:{programmer}'.format(f=st... | def install_board_with_programmer(mcu,
programmer,
f_cpu=16000000,
core='arduino',
replace_existing=False,
) | install board with programmer. | 4.555414 | 4.498507 | 1.01265 |
if self.repo.head.is_detached:
if os.getenv('GIT_BRANCH'):
branch = os.getenv('GIT_BRANCH')
elif os.getenv('BRANCH_NAME'):
branch = os.getenv('BRANCH_NAME')
elif os.getenv('TRAVIS_BRANCH'):
branch = os.getenv('TRAVIS_BR... | def get_branch(self) | :return: | 2.025932 | 1.945841 | 1.04116 |
tag = next((tag for tag in self.repo.tags if tag.commit == self.repo.commit()), None)
if tag:
return tag
return self.repo.rev_parse(str(self.repo.commit())) | def get_version(self) | :return: | 4.147455 | 3.758408 | 1.103514 |
if not exclude_paths:
exclude_paths = []
first_commit = self.repo.commit(first_sha)
second_commit = self.repo.commit(second_sha)
diffs = first_commit.diff(second_commit)
changed_files = []
for diff in diffs:
excluded = False
... | def get_changed_files(self, first_sha, second_sha, exclude_paths=None) | :param first_sha:
:param second_sha:
:param exclude_paths:
:return: | 1.718312 | 1.685978 | 1.019178 |
output = "\n\n# Git information \n" \
"-------------------------------------------\n" \
" Branch :\t{0}\n" \
" Version:\t{1}\n" \
" Summary:\t{2}\n" \
"-------------------------------------------\n\n".format(
... | def print_all(self) | :return: | 4.499389 | 4.31736 | 1.042162 |
time = datetime.datetime.now().strftime('%I:%M %p')
self.log = '{0}\n{1} | {2}'.format(self.log, time, msg)
if printMsg:
print msg
if self.addLogsToArcpyMessages:
from arcpy import AddMessage
AddMessage(msg) | def logMsg(self, msg, printMsg=True) | logs a message and prints it to the screen | 5.04823 | 4.984226 | 1.012841 |
from arcpy import GetMessages
msgs = GetMessages()
try:
self.logMsg(msgs, printMsg)
except:
self.logMsg('error getting arcpy message', printMsg) | def logGPMsg(self, printMsg=True) | logs the arcpy messages and prints them to the screen | 5.861221 | 4.37874 | 1.338563 |
if not os.path.exists(self.logFolder):
os.mkdir(self.logFolder)
with open(self.logFile, mode='a') as f:
f.write('\n\n' + self.log) | def writeLogToFile(self) | writes the log to a | 2.814859 | 2.987924 | 0.942079 |
# got from http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Error_handling_with_Python
import traceback
self.logMsg('ERROR!!!')
errMsg = traceback.format_exc()
self.logMsg(errMsg)
return errMsg | def logError(self) | gets traceback info and logs it | 5.406683 | 4.705137 | 1.149102 |
song = self._connection.request(
'autoplayGetSong',
{'weightModifierRange': [-9, 9],
'seedArtists': dict([(artist, 'p') for artist in self._artists]),
'tagID': self._radio,
'recentArtists': self._recent_artists,
'songQueueID': ... | def song(self) | :class:`Song` object of next song to play | 8.057946 | 7.729314 | 1.042518 |
return {'artists': self._artists,
'radio': self._radio,
'recent_artists': self._recent_artists,
'songs_already_seen': self._songs_already_seen} | def export(self) | Returns a dictionary with all song information.
Use the :meth:`from_export` method to recreate the
:class:`Song` object. | 6.281556 | 5.575586 | 1.126618 |
with warnings.catch_warnings():
warnings.simplefilter('ignore')
giphy = giphypop.Giphy()
results = giphy.search_list(phrase=phrase, limit=100)
if not results:
raise ValueError('There were no results for that phrase')
return random.choice(results).media_url | def get_random_giphy(phrase) | Return the URL of a random GIF related to the phrase, if possible | 3.784388 | 3.665169 | 1.032527 |
phrase = ' '.join(sys.argv[1:]) or 'random'
try:
giphy = get_random_giphy(phrase)
except ValueError:
sys.stderr.write('Unable to find any GIFs for {!r}\n'.format(phrase))
sys.exit(1)
display(fetch_image(giphy)) | def handle_command_line() | Display an image for the phrase in sys.argv, if possible | 4.55078 | 3.598913 | 1.264487 |
for folder in [
self.pending_folder,
self.usb_incoming_folder,
self.outgoing_folder,
self.incoming_folder,
self.archive_folder,
self.tmp_folder,
self.log_folder,
]:
if not os.path.exists(folder):
... | def make_required_folders(self) | Makes all folders declared in the config if they
do not exist. | 3.209262 | 3.202344 | 1.00216 |
try:
self.offset = offset
self.fd = open(filename, 'rb')
# 1024 - temporary, need to find out actual volume header size
self.fd.seek(self.offset + VOLUME_HEADER_OFFSET)
data = self.fd.read(1024)
self.vol_header = VolumeHeader(data)... | def load(self, filename, offset) | Loads HFS+ volume information | 3.99276 | 3.746424 | 1.065752 |
interfaces = self.xml.find('devices').iter('interface')
iobjs = []
for interface in interfaces:
_type = interface.attrib['type']
mac = interface.find('mac').attrib['address']
source = interface.find('source').attrib[_type]
model = interfac... | def get_interfaces(self) | Return a list of sham.network.interfaces.NetworkInterface
describing all the interfaces this VM has | 3.40784 | 3.188474 | 1.0688 |
disks = [disk for disk in self.xml.iter('disk')]
disk_objs = []
for disk in disks:
source = disk.find('source')
if source is None:
continue
path = source.attrib['file']
diskobj = self.domain.connect().storageVolLookupByPath... | def get_disks(self) | Return a list of all the Disks attached to this VM
The disks are returned in a sham.storage.volumes.Volume
object | 3.924898 | 3.847561 | 1.0201 |
disks = self.get_disks()
self.domain.undefine()
for disk in disks:
disk.wipe()
disk.delete() | def delete(self) | Delete this VM, and remove all its disks | 7.066713 | 5.645731 | 1.251691 |
disks = self.get_disks()
self.domain.destroy()
if delete:
for disk in disks:
disk.wipe()
disk.delete() | def shutdown(self, delete=False) | Shutdown this VM
:param delete: Should we delete after shutting the VM down?
:type delete: bool | 5.416371 | 5.803257 | 0.933333 |
return {'domain_type': self.domain_type,
'max_memory': self.max_memory,
'current_memory': self.current_memory,
'num_cpus': self.num_cpus,
'running': self.is_running(),
'name': self.name,
} | def to_dict(self) | Return the values contained in this object as a dict | 3.403787 | 3.164239 | 1.075705 |
parsed = urllib.parse.urlsplit(url)
if parsed.scheme in ('git', 'svn'):
return parsed.scheme
elif parsed.path.endswith('.git'):
return 'git'
elif parsed.hostname == 'github.com':
return 'git'
# If it's an http url, we can try requesting it and guessing from the
# c... | def guess_url_vcs(url) | Given a url, try to guess what kind of VCS it's for. Return None if we
can't make a good guess. | 4.102711 | 4.025131 | 1.019274 |
try:
contents = os.listdir(folder)
vcs_folders = ['.git', '.hg', '.svn']
found = next((x for x in vcs_folders if x in contents), None)
# Chop off the dot if we got a string back
return found[1:] if found else None
except OSError:
return None | def guess_folder_vcs(folder) | Given a path for a folder on the local filesystem, see what kind of vcs
repo it is, if any. | 3.767019 | 3.774869 | 0.99792 |
# It's easy to accidentally have whitespace on the beginning or end of the
# url.
url = url.strip()
url, _sep, _fragment = url.partition('#')
# Remove trailing slash from url if present
if url.endswith('/'):
url = url[:-1]
# Also strip .git from url if it ends in that.
retu... | def basename(url) | Return the name of the folder that you'd get if you cloned 'url' into the
current working directory. | 5.378537 | 5.452781 | 0.986384 |
cmd = {
'hg': 'hg paths default',
'git': 'git config --local --get remote.origin.url',
}[self.vcs_type]
with chdir(self.folder):
r = self.run(cmd)
return r.output.replace('\n', '') | def get_url(self) | Assuming that the repo has been cloned locally, get its default
upstream URL. | 5.418556 | 4.334481 | 1.250105 |
bits = token.contents.split(' ')
if len(bits) < 2:
raise template.TemplateSyntaxError("'%s' takes at least one argument"
" (path to a view)" % bits[0])
viewname = bits[1]
args = []
kwargs = {}
asvar = None
if len(bits) > 2:
bits = iter(... | def fburl(parser, token) | Returns an absolute URL matching given view with its parameters.
This is a way to define links that aren't tied to a particular URL
configuration::
{% url path.to.some_view arg1,arg2,name1=value1 %}
The first argument is a path to a view. It can be an absolute python path
or just ``app_name.v... | 2.185352 | 2.230314 | 0.97984 |
def wrapper(self, dir, *args, **kw):
dirstack = ChdirStack()
dirstack.push(dir)
try:
return method(self, dir, *args, **kw)
finally:
dirstack.pop()
return functools.wraps(method)(wrapper) | def chdir(method) | Decorator executing method in directory 'dir'. | 2.91531 | 2.593092 | 1.12426 |
self.stack.append(os.getcwd())
os.chdir(dir or os.getcwd()) | def push(self, dir) | Push cwd on stack and change to 'dir'. | 5.515295 | 3.570196 | 1.544816 |
if len(self.stack):
os.chdir(self.stack.pop()) | def pop(self) | Pop dir off stack and change to it. | 8.200648 | 3.506873 | 2.33845 |
value = self._accessor.get_by_id(source_id)
if not value is None:
reg = get_current_registry()
prx_fac = reg.getUtility(IDataTraversalProxyFactory)
prx = prx_fac.make_proxy(value,
self._accessor,
... | def get_matching(self, source_id) | Returns a matching target object for the given source ID. | 6.22099 | 5.847309 | 1.063906 |
for attr in self._attribute_iterator():
if attr.kind != RESOURCE_ATTRIBUTE_KINDS.COLLECTION:
try:
attr_val = self._get_proxied_attribute_value(attr)
except AttributeError:
continue
else:
... | def update_attribute_value_items(self) | Returns an iterator of items for an attribute value map to use for
an UPDATE operation.
The iterator ignores collection attributes as these are processed
implicitly by the traversal algorithm.
:returns: iterator yielding tuples with objects implementing
:class:`everest.resour... | 4.835376 | 3.580585 | 1.350443 |
attr_val = self._get_relation_attribute_value(attribute)
if attr_val is None:
prx = None
else:
if not self._accessor is None:
# FIXME: This implies that the accessor is an aggregate.
acc = self._accessor.get_root_aggregate(attribut... | def get_attribute_proxy(self, attribute) | Returns a traversal proxy (cardinality ONE) or an iterable sequence
data traversal proxy (cardinality MANY) for the specified relation
attribute value of the proxied data.
:raises ValueError: If :param:`attribute` is a terminal attribute. | 5.934105 | 5.708103 | 1.039593 |
if self._accessor is None:
if self.__converted_entity is None:
self.__converted_entity = self._convert_to_entity()
else:
# If we have an accessor, we can get the proxied entity by ID.
# FIXME: This is a hack that is only used for REMOVE operat... | def get_entity(self) | Returns the entity converted from the proxied data. | 6.977406 | 5.714161 | 1.221073 |
reg = get_current_registry()
prx_fac = reg.getUtility(IDataTraversalProxyFactory)
if relation_operation == RELATION_OPERATIONS.ADD \
or relation_operation == RELATION_OPERATIONS.UPDATE:
if relation_operation == RELATION_OPERATIONS.ADD \
and not targ... | def make_traverser(cls, source_data, target_data, relation_operation,
accessor=None, manage_back_references=True) | Factory method to create a tree traverser depending on the input
source and target data combination.
:param source_data: Source data.
:param target_target: Target data.
:param str relation_operation: Relation operation. On of the constants
defined in :class:`everest.constants.... | 2.382523 | 2.336656 | 1.019629 |
if __debug__:
self.__log_run(visitor)
visitor.prepare()
if self.__root_is_sequence:
if not self._tgt_prx is None:
tgts = iter(self._tgt_prx)
else:
tgts = None
if not self._src_prx is None:
sr... | def run(self, visitor) | :param visitor: visitor to call with every node in the domain tree.
:type visitor: subclass of
:class:`everest.entities.traversal.DomainVisitor` | 3.433008 | 3.416263 | 1.004902 |
if __debug__:
self.__log_traverse_one(self.__trv_path, attribute, source, target)
prx = source or target
rel_op = RELATION_OPERATIONS.check(source, target)
if prx.do_traverse() \
and (rel_op == prx.relation_operation or attribute is None):
for ... | def traverse_one(self, attribute, source, target, visitor) | :param source: source data proxy
:type source: instance of `DataTraversalProxy` or None
:param target: target data proxy
:type target: instance of `DataTraversalProxy` or None | 2.994585 | 3.005723 | 0.996294 |
target_map = {}
if not target_sequence is None:
for target in target_sequence:
target_map[target.get_id()] = target
src_tgt_pairs = []
if not source_sequence is None:
for source in source_sequence:
source_id = source.get_id... | def traverse_many(self, attribute, source_sequence, target_sequence,
visitor) | Traverses the given source and target sequences and makes appropriate
calls to :method:`traverse_one`.
Algorithm:
1) Build a map target item ID -> target data item from the target
sequence;
2) For each source data item in the source sequence check if it
has a not-N... | 3.62921 | 3.495732 | 1.038183 |
'''Get info about object id
|coro|
Parameters
----------
obj_id : str, list
if not provided, server info is retured(as a dict).
Otherwise, an object with that id is returned
(or objects if `obj_id` is a list).
'''
if obj_id:
try:
return await self.process(ob... | async def info(self, obj_id=None) | Get info about object id
|coro|
Parameters
----------
obj_id : str, list
if not provided, server info is retured(as a dict).
Otherwise, an object with that id is returned
(or objects if `obj_id` is a list). | 8.554091 | 3.466894 | 2.467364 |
'''Sends a search request to emby, returns results
|coro|
Parameters
----------
query : str
the search string to send to emby
sort_map : dict
is a dict of strings to ints. Strings should be item types, and
the ints are the priority of those types(for sorting).
lower val... | async def search(self, query,
sort_map = {'BoxSet':0,'Series':1,'Movie':2,'Audio':3,'Person':4},
strict_sort = False) | Sends a search request to emby, returns results
|coro|
Parameters
----------
query : str
the search string to send to emby
sort_map : dict
is a dict of strings to ints. Strings should be item types, and
the ints are the priority of those types(for sorting).
lower valued(0) ... | 5.874639 | 2.463334 | 2.384832 |
'''returns list of items marked as `next up`
|coro|
Parameters
----------
userId : str
if provided, then the list returned is
the one that that use will see.
Returns
-------
list
the itmes that will appear as next up
(for user if id was given)
'''
json ... | async def nextUp(self, userId=None) | returns list of items marked as `next up`
|coro|
Parameters
----------
userId : str
if provided, then the list returned is
the one that that use will see.
Returns
-------
list
the itmes that will appear as next up
(for user if id was given) | 16.099138 | 3.634899 | 4.429047 |
'''
reload all cached information
|coro|
Notes
-----
This is a slow process, and will remove the cache before updating.
Thus it is recomended to use the `*_force` properties, which will
only update the cache after data is retrived.
'''
keys = self.extras.keys()
self.extras ... | async def update(self) | reload all cached information
|coro|
Notes
-----
This is a slow process, and will remove the cache before updating.
Thus it is recomended to use the `*_force` properties, which will
only update the cache after data is retrived. | 9.992457 | 2.230274 | 4.480373 |
'''create a new playlist
|coro|
Parameters
----------
name : str
name of new playlist
songs : array_like
list of song ids to add to playlist
'''
data = {'Name': name}
ids = [i.id for i in (await self.process(songs))]
if ids:
data['Ids'] = ','.join(ids)
#... | async def create_playlist(self, name, *songs) | create a new playlist
|coro|
Parameters
----------
name : str
name of new playlist
songs : array_like
list of song ids to add to playlist | 7.151178 | 5.326313 | 1.342613 |
for ep in iter_entry_points(group=group):
plugin = ep.load()
plugin(self.__config) | def load_all(self, group) | Loads all plugins advertising entry points with the given group name.
The specified plugin needs to be a callable that accepts the everest
configurator as single argument. | 8.171629 | 4.843154 | 1.687254 |
sel = psidialogs.multi_choice(libraries(),
'select libraries to remove from %s!' % libraries_dir(),
title='remove boards')
print('%s selected' % sel)
if sel:
if psidialogs.ask_yes_no('Do you really want to remove selected lib... | def gui() | remove libraries by GUI. | 8.001028 | 6.978138 | 1.146585 |
record = Record.get_record(identifier)
click.echo(json.dumps(
Document(record, pointer).copy(destination)
)) | def copy_document(destination, identifier, pointer) | Copy file to a new destination. | 8.529964 | 9.404325 | 0.907026 |
record = Record.get_record(identifier)
Document(record, pointer).setcontents(source) | def setcontents(source, identifier, pointer) | Patch existing bibliographic record. | 12.23691 | 11.189477 | 1.093609 |
try:
return ast.parse(src, mode='eval')
except SyntaxError:
raise ValueError("Not a valid expression.") from None | def src2ast(src: str) -> Expression | Return ast.Expression created from source code given in `src`. | 4.445636 | 3.725429 | 1.193322 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.