code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
text = re_invalid_var.sub('', text)
text = re_invalid_start.sub('', text)
return text | def clean_var(text) | Turn text into a valid python classname or variable | 4.385285 | 4.230889 | 1.036493 |
if self.prev_error:
return self.prev_error.tasktrace + self.tasktrace
else:
return self.tasktrace | def full_tasktrace(self) | List of all failed tasks caused by this and all previous errors.
Returns:
List[Task] | 4.975113 | 3.702353 | 1.343771 |
v = self - other if other else self
return sum(map(abs, v.vector)) | def dist_cubic(self, other=None) | Manhattan distance | 9.11679 | 6.876455 | 1.325798 |
v = self - other if other else self
return sum(map(lambda a: a * a, v)) | def dist_sq(self, other=None) | For fast length comparison | 5.84369 | 4.644758 | 1.258126 |
if not self:
return YawPitch(0, 0)
ground_distance = math.sqrt(self.x ** 2 + self.z ** 2)
if ground_distance:
alpha1 = -math.asin(self.x / ground_distance) / math.pi * 180
alpha2 = math.acos(self.z / ground_distance) / math.pi * 180
if alp... | def yaw_pitch(self) | Calculate the yaw and pitch of this vector | 2.120426 | 2.055894 | 1.031389 |
x = -math.cos(self.rpitch) * math.sin(self.ryaw)
y = -math.sin(self.rpitch)
z = math.cos(self.rpitch) * math.cos(self.ryaw)
return Vector3(x, y, z) | def unit_vector(self) | Generate a unit vector (norm = 1) | 2.550565 | 2.360663 | 1.080444 |
totals = defaultdict(int)
for id, meta, amount in self.ingredients:
totals[(id, meta)] += amount
return totals | def total_ingredient_amounts(self) | Returns:
dict: In the form { (item_id, metadata) -> amount } | 6.314324 | 3.832733 | 1.647473 |
positions = defaultdict(list)
for y, row in enumerate(self.in_shape):
for x, (item_id, metadata, amount) in enumerate(row):
positions[(item_id, metadata)].append((x, y, amount))
return positions | def ingredient_positions(self) | Returns:
dict: In the form { (item_id, metadata) -> [(x, y, amount), ...] } | 4.238503 | 2.740738 | 1.546482 |
if isinstance(wanted, types.FunctionType):
return wanted # just forward the slot check function
if isinstance(wanted, int):
item, meta = wanted, None
elif isinstance(wanted, Slot):
item, meta = wanted.item_id, wanted.damage # TODO compare NBT
elif isinstance(wanted, (Item... | def make_slot_check(wanted) | Creates and returns a function that takes a slot
and checks if it matches the wanted item.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata) | 3.735441 | 3.360234 | 1.111661 |
cls_name = '%sWindow' % camel_case(str(window_dict['name']))
bases = (Window,)
attrs = {
'__module__': sys.modules[__name__],
'name': str(window_dict['name']),
'inv_type': str(window_dict['id']),
'inv_data': window_dict,
}
# creates function-local index and size... | def _make_window(window_dict) | Creates a new class for that window and registers it at this module. | 2.423386 | 2.318846 | 1.045083 |
data = {'id': self.item_id}
if self.item_id != constants.INV_ITEMID_EMPTY:
data['damage'] = self.damage
data['amount'] = self.amount
if self.nbt is not None:
data['enchants'] = self.nbt
return data | def get_dict(self) | Formats the slot for network packing. | 5.194527 | 4.635502 | 1.120596 |
self.dirty = set()
self.apply(inv_plugin)
for changed_slot in self.dirty:
emit_set_slot(changed_slot) | def on_success(self, inv_plugin, emit_set_slot) | Called when the click was successful
and should be applied to the inventory.
Args:
inv_plugin (InventoryPlugin): inventory plugin instance
emit_set_slot (func): function to signal a slot change,
should be InventoryPlugin().emit_set_slot | 4.717546 | 5.287556 | 0.892198 |
endpoint = '/authenticate'
payload = {
'agent': {
'name': 'Minecraft',
'version': self.ygg_version,
},
'username': self.username,
'password': self.password,
'clientToken': self.client_token,
}
... | def authenticate(self) | Generate an access token using an username and password. Any existing
client token is invalidated if not provided.
Returns:
dict: Response or error dict | 2.940128 | 3.08031 | 0.954491 |
endpoint = '/refresh'
payload = {
'accessToken': self.access_token,
'clientToken': self.client_token,
}
rep = self._ygg_req(endpoint, payload)
if not rep or 'error' in rep:
return False
self.access_token = rep['accessToken']
... | def refresh(self) | Generate an access token with a client/access token pair. Used
access token is invalidated.
Returns:
dict: Response or error dict | 3.497614 | 3.499012 | 0.999601 |
endpoint = '/invalidate'
payload = {
'accessToken': self.access_token,
'clientToken': self.client_token,
}
self._ygg_req(endpoint, payload)
self.client_token = ''
self.access_token = ''
self.available_profiles = []
self.se... | def invalidate(self) | Invalidate access tokens with a client/access token pair
Returns:
dict: Empty or error dict | 4.864129 | 4.634622 | 1.04952 |
endpoint = '/validate'
payload = dict(accessToken=self.access_token)
rep = self._ygg_req(endpoint, payload)
return not bool(rep) | def validate(self) | Check if an access token is valid
Returns:
dict: Empty or error dict | 13.441109 | 10.897404 | 1.233423 |
if slots is None:
slots = self.window.slots
wanted = make_slot_check(wanted)
return sum(slot.amount for slot in slots if wanted(slot)) | def total_stored(self, wanted, slots=None) | Calculates the total number of items of that type
in the current window or given slot range.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata) | 5.090065 | 4.451165 | 1.143535 |
for slot in self.find_slots(wanted, slots):
return slot
return None | def find_slot(self, wanted, slots=None) | Searches the given slots or, if not given,
active hotbar slot, hotbar, inventory, open window in this order.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata)
Returns:
Optional[Slot]: The first slot containing the item
or N... | 4.637441 | 8.117602 | 0.571282 |
if slots is None:
slots = self.inv_slots_preferred + self.window.window_slots
wanted = make_slot_check(wanted)
for slot in slots:
if wanted(slot):
yield slot | def find_slots(self, wanted, slots=None) | Yields all slots containing the item.
Searches the given slots or, if not given,
active hotbar slot, hotbar, inventory, open window in this order.
Args:
wanted: function(Slot) or Slot or itemID or (itemID, metadata) | 7.169052 | 5.515676 | 1.299759 |
if isinstance(slot, int):
slot = self.window.slots[slot]
button = constants.INV_BUTTON_RIGHT \
if right else constants.INV_BUTTON_LEFT
return self.send_click(windows.SingleClick(slot, button)) | def click_slot(self, slot, right=False) | Left-click or right-click the slot.
Args:
slot (Slot): The clicked slot. Can be ``Slot`` instance or integer.
Set to ``inventory.cursor_slot``
for clicking outside the window. | 6.762833 | 6.534295 | 1.034975 |
if slot is None:
if self.cursor_slot.is_empty:
slot = self.active_slot
else:
slot = self.cursor_slot
elif isinstance(slot, int): # also allow slot nr
slot = self.window.slots[slot]
if slot == self.cursor_slot:
... | def drop_slot(self, slot=None, drop_stack=False) | Drop one or all items of the slot.
Does not wait for confirmation from the server. If you want that,
use a ``Task`` and ``yield inventory.async.drop_slot()`` instead.
If ``slot`` is None, drops the ``cursor_slot`` or, if that's empty,
the currently held item (``active_slot``).
... | 5.659475 | 5.09441 | 1.110919 |
slots = [self.active_slot]
slots.extend(slot for slot in self.window.hotbar_slots
if slot != self.active_slot)
slots.extend(self.window.inventory_slots)
return slots | def inv_slots_preferred(self) | List of all available inventory slots in the preferred search order.
Does not include the additional slots from the open window.
1. active slot
2. remainder of the hotbar
3. remainder of the persistent inventory | 4.851153 | 3.468371 | 1.398684 |
if None not in (y, z): # x y z supplied
pos_or_x = pos_or_x, y, z
coord_tuple = tuple(int(floor(c)) for c in pos_or_x)
return self.block_entities.get(coord_tuple, None) | def get_block_entity_data(self, pos_or_x, y=None, z=None) | Access block entity data.
Returns:
BlockEntityData subclass instance or
None if no block entity data is stored for that location. | 3.691477 | 4.273253 | 0.863856 |
if None not in (y, z): # x y z supplied
pos_or_x = pos_or_x, y, z
coord_tuple = tuple(int(floor(c)) for c in pos_or_x)
old_data = self.block_entities.get(coord_tuple, None)
self.block_entities[coord_tuple] = data
return old_data | def set_block_entity_data(self, pos_or_x, y=None, z=None, data=None) | Update block entity data.
Returns:
Old data if block entity data was already stored for that location,
None otherwise. | 3.118452 | 3.252362 | 0.958827 |
inv = self.inventory
if inv.cursor_slot.is_empty: # nothing to drop
raise StopIteration(None)
storage = inv.inv_slots_preferred
if inv.window.is_storage:
storage += inv.window.window_slots
first_empty_slot = inv.find_slot(constants.INV_ITEMID_EM... | def store_or_drop(self) | Stores the cursor item or drops it if the inventory is full.
Tip: look directly up or down before calling this, so you can
pick up the dropped item when the inventory frees up again.
Returns:
Slot: The slot used to store it, or None if dropped. | 6.111846 | 5.807425 | 1.052419 |
values = []
cur, shift = 0, 0
for c in segment:
val = B64[ord(c)]
# Each character is 6 bits:
# 5 of value and the high bit is the continuation.
val, cont = val & 0b11111, val >> 5
cur += val << shift
shift += 5
... | def parse_vlq(self, segment) | Parse a string of VLQ-encoded data.
Returns:
a list of integers. | 4.386234 | 4.267449 | 1.027835 |
"Given a JavaScript file, find the sourceMappingURL line"
source = source.splitlines()
# Source maps are only going to exist at either the top or bottom of the document.
# Technically, there isn't anything indicating *where* it should exist, so we
# are generous and assume it's somewhere either in t... | def discover(source) | Given a JavaScript file, find the sourceMappingURL line | 6.519636 | 5.525838 | 1.179846 |
try:
import virtualenv
except ImportError, e:
raise RuntimeError("virtualenv is needed for bootstrap")
bdir = options.bootstrap_dir
if not os.path.exists(bdir):
os.makedirs(bdir)
bscript = "boostrap.py"
options.virtualenv.script_name = os.path.join(options.bootstra... | def bootstrap(options) | create virtualenv in ./bootstrap | 3.979759 | 3.801338 | 1.046936 |
d = ['build', 'dist', 'scikits.audiolab.egg-info', HTML_DESTDIR,
PDF_DESTDIR]
for i in d:
paver.path.path(i).rmtree()
(paver.path.path('docs') / options.sphinx.builddir).rmtree() | def clean() | Remove build, dist, egg-info garbage. | 9.762867 | 8.73066 | 1.118228 |
new_attendees = self._build_resource_dictionary(attendees, required=required)
for email in new_attendees:
self._attendees[email] = new_attendees[email]
self._dirty_attributes.add(u'attendees') | def add_attendees(self, attendees, required=True) | Adds new attendees to the event.
*attendees* can be a list of email addresses or :class:`ExchangeEventAttendee` objects. | 4.486374 | 4.801862 | 0.934299 |
attendees_to_delete = self._build_resource_dictionary(attendees)
for email in attendees_to_delete.keys():
if email in self._attendees:
del self._attendees[email]
self._dirty_attributes.add(u'attendees') | def remove_attendees(self, attendees) | Removes attendees from the event.
*attendees* can be a list of email addresses or :class:`ExchangeEventAttendee` objects. | 4.570961 | 4.435622 | 1.030512 |
new_resources = self._build_resource_dictionary(resources)
for key in new_resources:
self._resources[key] = new_resources[key]
self._dirty_attributes.add(u'resources') | def add_resources(self, resources) | Adds new resources to the event.
*resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects. | 4.615556 | 4.710595 | 0.979825 |
resources_to_delete = self._build_resource_dictionary(resources)
for email in resources_to_delete.keys():
if email in self._resources:
del self._resources[email]
self._dirty_attributes.add(u'resources') | def remove_resources(self, resources) | Removes resources from the event.
*resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects. | 5.456332 | 4.332291 | 1.259456 |
if not self.start:
raise ValueError("Event has no start date")
if not self.end:
raise ValueError("Event has no end date")
if self.end < self.start:
raise ValueError("Start date is after end date")
if self.reminder_minutes_before_start and not isinstance(self.reminder_minutes_be... | def validate(self) | Validates that all required fields are present | 2.12269 | 2.055422 | 1.032727 |
if not classname:
classname = '%s_info' % name
if not section:
section = name
if not frameworks:
framesworks = []
class _ret(system_info):
def __init__(self):
system_info.__init__(self)
def library_extensions(self):
return system_inf... | def info_factory(name, libnames, headers, frameworks=None,
section=None, classname=None) | Create a system_info class.
Parameters
----------
name : str
name of the library
libnames : seq
list of libraries to look for
headers : seq
list of headers to look for
classname : str
name of the returned class
section : st... | 3.371677 | 3.415327 | 0.98722 |
def basic_writer(data, filename, fs = def_fs, enc = format.encoding):
if np.ndim(data) <= 1:
nc = 1
elif np.ndim(data) == 2:
nc = data.shape[1]
else:
RuntimeError("Only rank 0, 1, and 2 arrays supported as audio data")
ufor... | def _writer_factory(name, format, def_fs, descr) | Create a writer function with fileformat described by format, default
sampling rate def_fs, and docstring descr. | 4.826859 | 4.646895 | 1.038728 |
def basic_reader(filename, last = None, first = 0):
hdl = Sndfile(filename, 'r')
try:
if not hdl.format.file_format == filetype:
raise ValueError, "%s is not a %s file (is %s)" \
% (filename, filetype, hdl.format.file_format)
... | def _reader_factory(name, filetype, descr) | Factory for reader functions ala matlab. | 4.700866 | 4.6515 | 1.010613 |
result = {}
log.info(etree.tostring(element, pretty_print=True))
for key in property_map:
item = property_map[key]
log.info(u'Pulling xpath {xpath} into key {key}'.format(key=key, xpath=item[u'xpath']))
nodes = element.xpath(item[u'xpath'], namespaces=namespace_map)
if nodes... | def _xpath_to_dict(self, element, property_map, namespace_map) | property_map = {
u'name' : { u'xpath' : u't:Mailbox/t:Name'},
u'email' : { u'xpath' : u't:Mailbox/t:EmailAddress'},
u'response' : { u'xpath' : u't:ResponseType'},
u'last_response': { u'xpath' : u't:LastResponseTime', u'cast': u'datetime'},
}
This runs the given xpath ... | 1.980936 | 1.831416 | 1.081642 |
items = response.xpath(u'//m:FindItemResponseMessage/m:RootFolder/t:Items/t:CalendarItem', namespaces=soap_request.NAMESPACES)
if not items:
items = response.xpath(u'//m:GetItemResponseMessage/m:Items/t:CalendarItem', namespaces=soap_request.NAMESPACES)
if items:
self.count = len(items)
... | def _parse_response_for_all_events(self, response) | This function will retrieve *most* of the event data, excluding Organizer & Attendee details | 4.998855 | 4.713272 | 1.060591 |
log.debug(u"Loading all details")
if self.count > 0:
# Now, empty out the events to prevent duplicates!
del(self.events[:])
# Send the SOAP request with the list of exchange ID values.
log.debug(u"Requesting all event details for events: {event_list}".format(event_list=str(self.eve... | def load_all_details(self) | This function will execute all the event lookups for known events.
This is intended for use when you want to have a completely populated event entry, including
Organizer & Attendee details. | 6.68943 | 6.29573 | 1.062534 |
if not self.id:
raise TypeError(u"You can't send invites for an event that hasn't been created yet.")
# Under the hood, this is just an .update() but with no attributes changed.
# We're going to enforce that by checking if there are any changed attributes and bail if there are
if self._dirt... | def resend_invitations(self) | Resends invites for an event. ::
event = service.calendar().get_event(id='KEY HERE')
event.resend_invitations()
Anybody who has not declined this meeting will get a new invite. | 10.566788 | 9.310305 | 1.134956 |
if not self.id:
raise TypeError(u"You can't update an event that hasn't been created yet.")
if 'send_only_to_changed_attendees' in kwargs:
warnings.warn(
"The argument send_only_to_changed_attendees is deprecated. Use calendar_item_update_operation_type instead.",
DeprecationW... | def update(self, calendar_item_update_operation_type=u'SendToAllAndSaveCopy', **kwargs) | Updates an event in Exchange. ::
event = service.calendar().get_event(id='KEY HERE')
event.location = u'New location'
event.update()
If no changes to the event have been made, this method does nothing.
Notification of the change event is sent to all users. If you wish to just notify ... | 3.135324 | 2.967979 | 1.056383 |
if not self.id:
raise TypeError(u"You can't delete an event that hasn't been created yet.")
self.refresh_change_key()
self.service.send(soap_request.delete_event(self))
# TODO rsanders high - check return status to make sure it was actually sent
return None | def cancel(self) | Cancels an event in Exchange. ::
event = service.calendar().get_event(id='KEY HERE')
event.cancel()
This will send notifications to anyone who has not declined the meeting. | 16.192181 | 15.405506 | 1.051065 |
if not folder_id:
raise TypeError(u"You can't move an event to a non-existant folder")
if not isinstance(folder_id, BASESTRING_TYPES):
raise TypeError(u"folder_id must be a string")
if not self.id:
raise TypeError(u"You can't move an event that hasn't been created yet.")
self.r... | def move_to(self, folder_id) | :param str folder_id: The Calendar ID to where you want to move the event to.
Moves an event to a different folder (calendar). ::
event = service.calendar().get_event(id='KEY HERE')
event.move_to(folder_id='NEW CALENDAR KEY HERE') | 3.814547 | 3.829006 | 0.996224 |
if self.type != 'Occurrence':
raise InvalidEventType("get_master method can only be called on a 'Occurrence' event type")
body = soap_request.get_master(exchange_id=self._id, format=u"AllProperties")
response_xml = self.service.send(body)
return Exchange2010CalendarEvent(service=self.servi... | def get_master(self) | get_master()
:raises InvalidEventType: When this method is called on an event that is not a Occurrence type.
This will return the master event to the occurrence.
**Examples**::
event = service.calendar().get_event(id='<event_id>')
print event.type # If it prints out 'Occurrence' th... | 11.002414 | 6.939424 | 1.585494 |
if not all([isinstance(i, int) for i in instance_index]):
raise TypeError("instance_index must be an interable of type int")
if self.type != 'RecurringMaster':
raise InvalidEventType("get_occurrance method can only be called on a 'RecurringMaster' event type")
body = soap_request.get_occ... | def get_occurrence(self, instance_index) | get_occurrence(instance_index)
:param iterable instance_index: This should be tuple or list of integers which correspond to occurrences.
:raises TypeError: When instance_index is not an iterable of ints.
:raises InvalidEventType: When this method is called on an event that is not a RecurringMaster typ... | 4.875445 | 3.780967 | 1.28947 |
if not self.conflicting_event_ids:
return []
body = soap_request.get_item(exchange_id=self.conflicting_event_ids, format="AllProperties")
response_xml = self.service.send(body)
items = response_xml.xpath(u'//m:GetItemResponseMessage/m:Items', namespaces=soap_request.NAMESPACES)
events ... | def conflicting_events(self) | conflicting_events()
This will return a list of conflicting events.
**Example**::
event = service.calendar().get_event(id='<event_id>')
for conflict in event.conflicting_events():
print conflict.subject | 5.004498 | 4.673616 | 1.070798 |
body = soap_request.find_folder(parent_id=parent_id, format=u'AllProperties')
response_xml = self.service.send(body)
return self._parse_response_for_find_folder(response_xml) | def find_folder(self, parent_id) | find_folder(parent_id)
:param str parent_id: The parent folder to list.
This method will return a list of sub-folders to a given parent folder.
**Examples**::
# Iterate through folders within the default 'calendar' folder.
folders = service.folder().find_folder(parent_id='calendar'... | 7.298182 | 6.054755 | 1.205364 |
self.validate()
body = soap_request.new_folder(self)
response_xml = self.service.send(body)
self._id, self._change_key = self._parse_id_and_change_key_from_response(response_xml)
return self | def create(self) | Creates a folder in Exchange. ::
calendar = service.folder().new_folder(
display_name=u"New Folder Name",
folder_type="CalendarFolder",
parent_id='calendar',
)
calendar.create() | 11.769601 | 5.590468 | 2.105298 |
if not self.id:
raise TypeError(u"You can't delete a folder that hasn't been created yet.")
body = soap_request.delete_folder(self)
response_xml = self.service.send(body) # noqa
# TODO: verify deletion
self._id = None
self._change_key = None
return None | def delete(self) | Deletes a folder from the Exchange store. ::
folder = service.folder().get_folder(id)
print("Deleting folder: %s" % folder.display_name)
folder.delete() | 9.276351 | 6.98119 | 1.328764 |
if not folder_id:
raise TypeError(u"You can't move to a non-existant folder")
if not isinstance(folder_id, BASESTRING_TYPES):
raise TypeError(u"folder_id must be a string")
if not self.id:
raise TypeError(u"You can't move a folder that hasn't been created yet.")
response_xml =... | def move_to(self, folder_id) | :param str folder_id: The Folder ID of what will be the new parent folder, of this folder.
Move folder to a different location, specified by folder_id::
folder = service.folder().get_folder(id)
folder.move_to(folder_id="ID of new location's folder") | 4.377944 | 4.09445 | 1.069239 |
try:
st = self._sndfile.seek(offset, whence, mode)
except IOError, e:
raise PyaudioIOError(str(e))
return st | def seek(self, offset, whence=0, mode='rw') | similar to python seek function, taking only in account audio data.
:Parameters:
offset : int
the number of frames (eg two samples for stereo files) to move
relatively to position set by whence.
whence : int
only 0 (beginning), 1 (current)... | 5.49814 | 4.10502 | 1.33937 |
return self._sndfile.read_frames(nframes, dtype) | def read_frames(self, nframes, dtype=np.float64) | Read nframes frames of the file.
:Parameters:
nframes : int
number of frames to read.
dtype : numpy dtype
dtype of the returned array containing read data (see note).
Notes
-----
- read_frames updates the read pointer.
- ... | 7.830823 | 11.33743 | 0.690705 |
if nframes == -1:
if input.ndim == 1:
nframes = input.size
elif input.ndim == 2:
nframes = input.shape[0]
else:
raise ValueError("Input has to be rank 1 (mono) or rank 2 "\
"(multi-chann... | def write_frames(self, input, nframes = -1) | write data to file.
:Parameters:
input : ndarray
array containing data to write.
nframes : int
number of frames to write.
Notes
-----
- One column is one channel (one row per channel after 0.9)
- updates the write pointer... | 3.575496 | 4.113892 | 0.869127 |
for attendee in resources:
element.append(
T.Attendee(
T.Mailbox(
T.EmailAddress(attendee.email)
)
)
)
return element | def resource_node(element, resources) | Helper function to generate a person/conference room node from an email address
<t:OptionalAttendees>
<t:Attendee>
<t:Mailbox>
<t:EmailAddress>{{ attendee_email }}</t:EmailAddress>
</t:Mailbox>
</t:Attendee>
</t:OptionalAttendees> | 6.937738 | 3.755739 | 1.847236 |
root = T.DeleteItemField(
T.FieldURI(FieldURI=field_uri)
)
return root | def delete_field(field_uri) | Helper function to request deletion of a field. This is necessary when you want to overwrite values instead of
appending.
<t:DeleteItemField>
<t:FieldURI FieldURI="calendar:Resources"/>
</t:DeleteItemField> | 13.839457 | 8.245356 | 1.678455 |
elements = list()
if type(exchange_id) == list:
for item in exchange_id:
elements.append(T.ItemId(Id=item))
else:
elements = [T.ItemId(Id=exchange_id)]
root = M.GetItem(
M.ItemShape(
T.BaseShape(format)
),
M.ItemIds(
*elements
)
)
return root | def get_item(exchange_id, format=u"Default") | Requests a calendar item from the store.
exchange_id is the id for this event in the Exchange store.
format controls how much data you get back from Exchange. Full docs are here, but acceptible values
are IdOnly, Default, and AllProperties.
http://msdn.microsoft.com/en-us/library/aa564509(v=exchg.140... | 4.615969 | 3.068517 | 1.504299 |
root = M.GetItem(
M.ItemShape(
T.BaseShape(format)
),
M.ItemIds(
T.RecurringMasterItemId(OccurrenceId=exchange_id)
)
)
return root | def get_master(exchange_id, format=u"Default") | Requests a calendar item from the store.
exchange_id is the id for this event in the Exchange store.
format controls how much data you get back from Exchange. Full docs are here, but acceptible values
are IdOnly, Default, and AllProperties.
http://msdn.microsoft.com/en-us/library/aa564509(v=exchg.140... | 19.769644 | 4.519461 | 4.374336 |
root = M.GetItem(
M.ItemShape(
T.BaseShape(format)
),
M.ItemIds()
)
items_node = root.xpath("//m:ItemIds", namespaces=NAMESPACES)[0]
for index in instance_index:
items_node.append(T.OccurrenceItemId(RecurringMasterId=exchange_id, InstanceIndex=str(index)))
return root | def get_occurrence(exchange_id, instance_index, format=u"Default") | Requests one or more calendar items from the store matching the master & index.
exchange_id is the id for the master event in the Exchange store.
format controls how much data you get back from Exchange. Full docs are here, but acceptible values
are IdOnly, Default, and AllProperties.
GetItem Doc:
... | 9.108724 | 3.761612 | 2.421495 |
root = T.SetItemField(
T.FieldURI(FieldURI=field_uri),
T.CalendarItem(node_to_insert)
)
return root | def update_property_node(node_to_insert, field_uri) | Helper function - generates a SetItemField which tells Exchange you want to overwrite the contents of a field. | 20.22798 | 10.505377 | 1.925488 |
if files == {}:
files = None
self._multipart = files is not None
header = self.get_oauth_header(method, url, callback_url, get, post)
if get:
full_url = url + "?" + urllib.urlencode(get)
else:
full_url = url
if method.upper() == "POST":
response = requests.post(full_url, data = post, files = ... | def do_request(self, method, url, callback_url = None, get = None, post = None, files = None, stream = False, is_json = True) | # DEBUG
info = "=" * 50 + "\n"
info += "Method: %s\n" % method
info += "URL: %s\n" % full_url
info += "Headers: %s\n" % str(header)
info += "GET data: %s\n" % str(get)
info += "POST data: %s\n" % str(post)
info += "Files: %s\n" % str(files)
info += "Streaming: %s\n" % str(stream)
info ... | 2.161548 | 2.216114 | 0.975378 |
example = getattr(method, example_type + "_example")
schema = getattr(method, example_type + "_schema")
if example is None:
return None
try:
validate(example, schema)
except ValidationError as e:
raise ValidationError(
"{}_example for {}.{} could not be val... | def _validate_example(rh, method, example_type) | Validates example against schema
:returns: Formatted example if example exists and validates, otherwise None
:raises ValidationError: If example does not validate against the schema | 2.606874 | 2.756443 | 0.945738 |
for k, v in vars(rh).items():
if all([
k in HTTP_METHODS,
is_method(v),
hasattr(v, "input_schema")
]):
yield (k, v) | def _get_rh_methods(rh) | Yield all HTTP methods in ``rh`` that are decorated
with schema.validate | 4.982255 | 4.346277 | 1.146327 |
if isinstance(route, tuple):
assert len(route) >= 2
pattern, handler_class = route[:2]
elif isinstance(route, tornado.web.URLSpec):
pattern, handler_class = route.regex.pattern, route.handler_class
else:
raise TypeError("Unknown route type '{}'"
.... | def _get_tuple_from_route(route) | Return (pattern, handler_class, methods) tuple from ``route``
:type route: tuple|tornado.web.URLSpec
:rtype: tuple
:raises TypeError: If ``route`` is not a tuple or URLSpec | 2.753659 | 2.586101 | 1.064792 |
literals = list("\\`*_{}[]()<>#+-.!:|")
escape = lambda c: '\\' + c if c in literals else c
return "".join(map(escape, string)) | def _escape_markdown_literals(string) | Escape any markdown literals in ``string`` by prepending with \\
:type string: str
:rtype: str | 5.214312 | 5.87006 | 0.888289 |
indent_length = lambda s: len(s) - len(s.lstrip(" "))
not_empty = lambda s: s != ""
lines = doc.split("\n")
indent = min(map(indent_length, filter(not_empty, lines)))
return "\n".join(s[indent:] for s in lines) | def _cleandoc(doc) | Remove uniform indents from ``doc`` lines that are not empty
:returns: Cleaned ``doc`` | 3.095839 | 3.496879 | 0.885315 |
lines = string.split("\n")
first, lines = lines[0], lines[1:]
lines = ["{indent}{s}".format(indent=" " * indent, s=s)
for s in lines]
lines = [first] + lines
return "\n".join(lines) | def _add_indent(string, indent) | Add indent of ``indent`` spaces to ``string.split("\n")[1:]``
Useful for formatting in strings to already indented blocks | 2.645912 | 2.742753 | 0.964692 |
routes = map(_get_tuple_from_route, routes)
documentation = []
for url, rh, methods in sorted(routes, key=lambda a: a[0]):
if issubclass(rh, APIHandler):
documentation.append(_get_route_doc(url, rh, methods))
documentation = (
"**This documentation is automatically gene... | def get_api_docs(routes) | Generates GitHub Markdown formatted API documentation using
provided schemas in RequestHandler methods and their docstrings.
:type routes: [(url, RequestHandler), ...]
:param routes: List of routes (this is ideally all possible routes of the
app)
:rtype: str
:returns: generated GFM-formatt... | 7.594437 | 7.725544 | 0.983029 |
result = {'status': 'error', 'message': message}
if data:
result['data'] = data
if code:
result['code'] = code
self.write(result)
self.finish() | def error(self, message, data=None, code=None) | An error occurred in processing the request, i.e. an exception was
thrown.
:type data: A JSON-serializable object
:param data: A generic container for any other information about the
error, i.e. the conditions that caused the error,
stack traces, etc.
:type mes... | 2.064718 | 3.306484 | 0.624445 |
default = {}
for k, schema in object_schema.get('properties', {}).items():
if schema.get('type') == 'object':
if 'default' in schema:
default[k] = schema['default']
try:
object_defaults = get_object_defaults(schema)
except NoObje... | def get_object_defaults(object_schema) | Extracts default values dict (nested) from an type object schema.
:param object_schema: Schema type object
:type object_schema: dict
:returns: Nested dict with defaults values | 2.153095 | 2.376385 | 0.906038 |
if input_schema.get('type') == 'object':
try:
defaults = get_object_defaults(input_schema)
except NoObjectDefaults:
pass
else:
return deep_update(defaults, input_)
return input_ | def input_schema_clean(input_, input_schema) | Updates schema default values with input data.
:param input_: Input data
:type input_: dict
:param input_schema: Input schema
:type input_schema: dict
:returns: Nested dict with data (defaul values updated with input data)
:rtype: dict | 3.793099 | 3.816771 | 0.993798 |
@container
def _validate(rh_method):
@wraps(rh_method)
@tornado.gen.coroutine
def _wrapper(self, *args, **kwargs):
# In case the specified input_schema is ``None``, we
# don't json.loads the input, but just set it to ``None``
# instea... | def validate(input_schema=None, output_schema=None,
input_example=None, output_example=None,
validator_cls=None,
format_checker=None, on_empty_404=False,
use_defaults=False) | Parameterized decorator for schema validation
:type validator_cls: IValidator class
:type format_checker: jsonschema.FormatChecker or None
:type on_empty_404: bool
:param on_empty_404: If this is set, and the result from the
decorated method is a falsy value, a 404 will be raised.
:type use... | 4.348125 | 4.379893 | 0.992747 |
return codecs.open(os.path.join(__DIR__, filename), 'r').read() | def read(filename) | Read and return `filename` in root dir of project and return string | 6.803388 | 5.970386 | 1.139522 |
for key, value in overrides.items():
if isinstance(value, collections.Mapping) and value:
returned = deep_update(source.get(key, {}), value)
source[key] = returned
else:
source[key] = overrides[key]
return source | def deep_update(source, overrides) | Update a nested dictionary or similar mapping.
Modify ``source`` in place.
:type source: collections.Mapping
:type overrides: collections.Mapping
:rtype: collections.Mapping | 1.532721 | 1.669466 | 0.918091 |
# Credits: http://stackoverflow.com/a/1167248/1798683
@wraps(dec)
def meta_decorator(f):
decorator = dec(f)
decorator.orig_func = f
return decorator
return meta_decorator | def container(dec) | Meta-decorator (for decorating decorators)
Keeps around original decorated function as a property ``orig_func``
:param dec: Decorator to decorate
:type dec: function
:returns: Decorated decorator | 4.989504 | 4.181917 | 1.193114 |
if isinstance(cls, list):
return any(is_handler_subclass(c) for c in cls)
elif isinstance(cls, type):
return any(c.__name__ in classnames for c in inspect.getmro(cls))
else:
raise TypeError(
"Unexpected type `{}` for class `{}`".format(
type(cls),
... | def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")) | Determines if ``cls`` is indeed a subclass of ``classnames`` | 2.708493 | 2.463141 | 1.09961 |
def get_exc_message(exception):
return exception.log_message if \
hasattr(exception, "log_message") else str(exception)
self.clear()
self.set_status(status_code)
# Any APIError exceptions raised will result in a JSend fail written
# back wit... | def write_error(self, status_code, **kwargs) | Override of RequestHandler.write_error
Calls ``error()`` or ``fail()`` from JSendMixin depending on which
exception was raised with provided reason and status code.
:type status_code: int
:param status_code: HTTP status code | 6.085432 | 5.766356 | 1.055334 |
for importer, modname, ispkg in pkgutil.walk_packages(
path=package.__path__,
prefix=package.__name__ + '.',
onerror=lambda x: None):
yield modname | def gen_submodule_names(package) | Walk package and yield names of all submodules
:type package: package
:param package: The package to get submodule names of
:returns: Iterator that yields names of all submodules of ``package``
:rtype: Iterator that yields ``str`` | 2.499647 | 3.12606 | 0.799616 |
# Asynchronously yield a result from a method
res = yield gen.Task(self.hello, name)
# When using the `schema.validate` decorator asynchronously,
# we can return the output desired by raising
# `tornado.gen.Return(value)` which returns a
# Future that the ... | def get(self, name) | Shouts hello to the world (asynchronously)! | 7.001159 | 6.528944 | 1.072326 |
# gen.coroutine in tornado 3.x.x and 5.x.x have a different signature than 4.x.x
if TORNADO_MAJOR != 4:
wrapper = gen.coroutine(func)
else:
wrapper = gen.coroutine(func, replace_callback)
wrapper.__argspec_args = inspect.getargspec(func).args
return wrapper | def coroutine(func, replace_callback=True) | Tornado-JSON compatible wrapper for ``tornado.gen.coroutine``
Annotates original argspec.args of ``func`` as attribute ``__argspec_args`` | 5.964981 | 4.139868 | 1.440863 |
arg_parse = setup_argparse()
args = arg_parse.parse_args()
if not args.quiet:
print('GNS3 Topology Converter')
if args.debug:
logging_level = logging.DEBUG
else:
logging_level = logging.WARNING
logging.basicConfig(level=logging_level,
forma... | def main() | Entry point for gns3-converter | 3.754692 | 3.574459 | 1.050422 |
parser = argparse.ArgumentParser(
description='Convert old ini-style GNS3 topologies (<=0.8.7) to '
'the newer version 1+ JSON format')
parser.add_argument('--version',
action='version',
version='%(prog)s ' + __version__)
parse... | def setup_argparse() | Setup the argparse argument parser
:return: instance of argparse
:rtype: ArgumentParser | 3.646633 | 3.757569 | 0.970477 |
# Create a new instance of the the Converter
gns3_conv = Converter(topology_def['file'], debug)
# Read the old topology
old_top = gns3_conv.read_topology()
new_top = JSONTopology()
# Process the sections
(topology) = gns3_conv.process_topology(old_top)
# Generate the nodes
new... | def do_conversion(topology_def, topology_name, output_dir=None, debug=False,
quiet=False) | Convert the topology
:param dict topology_def: Dict containing topology file and snapshot bool.
For example:
``{'file': filename, 'snapshot': False}``
:param str topology_name: The name of the topology
:param str output_dir: The directory in which... | 3.842108 | 3.812356 | 1.007804 |
snapshots = []
snap_dir = os.path.join(topology_dirname(topology), 'snapshots')
if os.path.exists(snap_dir):
snaps = os.listdir(snap_dir)
for directory in snaps:
snap_top = os.path.join(snap_dir, directory, 'topology.net')
if os.path.exists(snap_top):
... | def get_snapshots(topology) | Return the paths of any snapshot topologies
:param str topology: topology file
:return: list of dicts containing snapshot topologies
:rtype: list | 2.777547 | 2.746957 | 1.011136 |
if topology_name is not None:
logging.debug('topology name supplied')
topo_name = topology_name
else:
logging.debug('topology name not supplied')
topo_name = os.path.basename(topology_dirname(topology_file))
return topo_name | def name(topology_file, topology_name=None) | Calculate the name to save the converted topology as using either either
a specified name or the directory name of the current project
:param str topology_file: Topology filename
:param topology_name: Optional topology name (Default: None)
:type topology_name: str or None
:return: new topology name... | 3.364281 | 3.722679 | 0.903726 |
topo_name = os.path.basename(topology_dirname(topo_name))
snap_re = re.compile('^topology_(.+)(_snapshot_)(\d{6}_\d{6})$')
result = snap_re.search(topo_name)
if result is not None:
snap_name = result.group(1) + '_' + result.group(3)
else:
raise ConvertError('Unable to get snaps... | def snapshot_name(topo_name) | Get the snapshot name
:param str topo_name: topology file location. The name is taken from the
directory containing the topology file using the
following format: topology_NAME_snapshot_DATE_TIME
:return: snapshot name
:raises ConvertError: when unable to ... | 3.645614 | 3.144515 | 1.159357 |
try:
old_topology_dir = topology_dirname(converter.topology)
if output_dir:
output_dir = os.path.abspath(output_dir)
else:
output_dir = os.getcwd()
topology_name = json_topology.name
topology_files_dir = os.path.join(output_dir, topology_name + ... | def save(output_dir, converter, json_topology, snapshot, quiet) | Save the converted topology
:param str output_dir: Output Directory
:param Converter converter: Converter instance
:param JSONTopology json_topology: JSON topology layout
:param bool snapshot: Is this a snapshot?
:param bool quiet: No console printing | 2.879328 | 2.854491 | 1.008701 |
config_err = False
if len(configs) > 0:
config_dir = os.path.join(target, 'dynamips', 'configs')
os.makedirs(config_dir)
for config in configs:
old_config_file = os.path.join(source, config['old'])
new_config_file = os.path.join(config_dir,
... | def copy_configs(configs, source, target) | Copy dynamips configs to converted topology
:param configs: Configs to copy
:param str source: Source topology directory
:param str target: Target topology files directory
:return: True when a config cannot be found, otherwise false
:rtype: bool | 2.327109 | 2.17366 | 1.070595 |
# Prepare a list of files to copy
vpcs_files = glob.glob(os.path.join(source, 'configs', '*.vpc'))
vpcs_hist = os.path.join(source, 'configs', 'vpcs.hist')
vpcs_config_path = os.path.join(target, 'vpcs', 'multi-host')
if os.path.isfile(vpcs_hist):
vpcs_files.append(vpcs_hist)
# Crea... | def copy_vpcs_configs(source, target) | Copy any VPCS configs to the converted topology
:param str source: Source topology directory
:param str target: Target topology files directory | 2.477651 | 2.4794 | 0.999295 |
files = glob.glob(os.path.join(source, '*.png'))
for file in files:
shutil.copy(file, target) | def copy_topology_image(source, target) | Copy any images of the topology to the converted topology
:param str source: Source topology directory
:param str target: Target Directory | 2.569798 | 3.287418 | 0.781707 |
image_err = False
if len(images) > 0:
images_dir = os.path.join(target, 'images')
os.makedirs(images_dir)
for image in images:
if os.path.isabs(image):
old_image_file = image
else:
old_image_file = os.path.join(source, image)
... | def copy_images(images, source, target) | Copy images to converted topology
:param images: Images to copy
:param source: Old Topology Directory
:param target: Target topology files directory
:return: True when an image cannot be found, otherwise false
:rtype: bool | 1.907786 | 1.91677 | 0.995313 |
if max_vbox_id is not None:
for i in range(1, max_vbox_id + 1):
vbox_dir = os.path.join(output_dir, topology_name + '-files',
'vbox', 'vm-%s' % i)
os.makedirs(vbox_dir) | def make_vbox_dirs(max_vbox_id, output_dir, topology_name) | Create VirtualBox working directories if required
:param int max_vbox_id: Number of directories to create
:param str output_dir: Output directory
:param str topology_name: Topology name | 2.440476 | 2.911259 | 0.838289 |
if max_qemu_id is not None:
for i in range(1, max_qemu_id + 1):
qemu_dir = os.path.join(output_dir, topology_name + '-files',
'qemu', 'vm-%s' % i)
os.makedirs(qemu_dir) | def make_qemu_dirs(max_qemu_id, output_dir, topology_name) | Create Qemu VM working directories if required
:param int max_qemu_id: Number of directories to create
:param str output_dir: Output directory
:param str topology_name: Topology name | 2.454873 | 2.810961 | 0.873322 |
new_wic = 'wic' + old_wic[-1]
self.node['properties'][new_wic] = wic | def add_wic(self, old_wic, wic) | Convert the old style WIC slot to a new style WIC slot and add the WIC
to the node properties
:param str old_wic: Old WIC slot
:param str wic: WIC name | 6.803573 | 5.962379 | 1.141084 |
wic_slot_number = int(wic_slot[3])
wic_adapter = self.node['properties'][wic_slot]
num_ports = ADAPTER_MATRIX[wic_adapter]['ports']
port_type = ADAPTER_MATRIX[wic_adapter]['type']
ports = []
# Dynamips WICs port number start on a multiple of 16.
base = ... | def add_wic_ports(self, wic_slot) | Add the ports for a specific WIC to the node['ports'] dictionary
:param str wic_slot: WIC Slot (wic0) | 3.788428 | 3.848475 | 0.984397 |
slot_nb = int(slot[4])
# slot_adapter = None
# if slot in self.node['properties']:
# slot_adapter = self.node['properties'][slot]
# elif self.device_info['model'] == 'c7200':
# if self.device_info['npe'] == 'npe-g2':
# slot_adapter = 'C720... | def add_slot_ports(self, slot) | Add the ports to be added for a adapter card
:param str slot: Slot name | 3.467384 | 3.4731 | 0.998354 |
# Router Image
if 'image' in self.hypervisor:
self.node['properties']['image'] = \
os.path.basename(self.hypervisor['image'])
# IDLE-PC
if 'idlepc' in self.hypervisor:
self.node['properties']['idlepc'] = self.hypervisor['idlepc']
#... | def add_info_from_hv(self) | Add the information we need from the old hypervisor section | 2.854037 | 2.743044 | 1.040463 |
if item in ('aux', 'console'):
self.node['properties'][item] = device[item]
elif item.startswith('slot'):
# if self.device_info['model'] == 'c7200':
# if item != 'slot0':
# self.node['properties'][item] = device[item]
# els... | def add_device_items(self, item, device) | Add the various items from the device to the node
:param str item: item key
:param dict device: dictionary containing items | 3.757489 | 3.724352 | 1.008898 |
# VirtualBox Image
if 'vmname' not in self.node['properties']:
self.node['properties']['vmname'] = \
self.hypervisor['VBoxDevice']['image']
# Number of adapters
if 'adapters' not in self.node['properties']:
self.node['properties']['adapter... | def add_to_virtualbox(self) | Add additional parameters that were in the VBoxDevice section or not
present | 3.955831 | 3.618109 | 1.093342 |
device = self.device_info['ext_conf']
node_prop = self.node['properties']
hv_device = self.hypervisor[device]
# QEMU HDD Images
if 'hda_disk_image' not in node_prop:
if 'image' in hv_device:
node_prop['hda_disk_image'] = hv_device['image']
... | def add_to_qemu(self) | Add additional parameters to a QemuVM Device that were present in its
global conf section | 2.143044 | 2.10517 | 1.017991 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.