code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
self._storage_broker.create_structure()
self._storage_broker.put_admin_metadata(self._admin_metadata) | def create(self) | Create the required directory structure and admin metadata. | 10.569487 | 5.529527 | 1.911463 |
self._storage_broker.add_item_metadata(handle, key, value) | def add_item_metadata(self, handle, key, value) | Add metadata to a specific item in the :class:`dtoolcore.ProtoDataSet`.
:param handle: handle representing the relative path of the item in the
:class:`dtoolcore.ProtoDataSet`
:param key: metadata key
:param value: metadata value | 5.836897 | 6.463956 | 0.902991 |
overlays = defaultdict(dict)
for handle in self._storage_broker.iter_item_handles():
identifier = dtoolcore.utils.generate_identifier(handle)
item_metadata = self._storage_broker.get_item_metadata(handle)
for k, v in item_metadata.items():
ove... | def _generate_overlays(self) | Return dictionary of overlays generated from added item metadata. | 4.002301 | 3.275648 | 1.221835 |
# Call the storage broker pre_freeze hook.
self._storage_broker.pre_freeze_hook()
if progressbar:
progressbar.label = "Freezing dataset"
# Generate and persist the manifest.
manifest = self.generate_manifest(progressbar=progressbar)
self._storage_br... | def freeze(self, progressbar=None) | Convert :class:`dtoolcore.ProtoDataSet` to :class:`dtoolcore.DataSet`. | 3.969636 | 3.462272 | 1.146541 |
route_name = route_name_prefix + '_read_many'
self.add_handler(route_name, base_url, handler,
action='read_many', request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_handler(route_name, base_url + '/{id}', handler,
action='read_one',... | def add_papyrus_handler(self, route_name_prefix, base_url, handler) | Add a Papyrus handler, i.e. a handler defining the MapFish
HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_handler(
'spots', '/spots', 'mypackage.handlers.SpotHandler')
Arguments:
``route_name_prefix`` The prefix used for the ro... | 1.360711 | 1.425532 | 0.954529 |
route_name = route_name_prefix + '_read_many'
self.add_route(route_name, base_url, request_method='GET')
route_name = route_name_prefix + '_read_one'
self.add_route(route_name, base_url + '/{id}', request_method='GET')
route_name = route_name_prefix + '_count'
self.add_route(route_name, bas... | def add_papyrus_routes(self, route_name_prefix, base_url) | A helper method that adds routes to view callables that, together,
implement the MapFish HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_routes('spots', '/spots')
config.scan()
Arguments:
``route_name_prefix' The prefix used for the... | 1.365686 | 1.462818 | 0.9336 |
@wraps(f)
def wrapped_f(t, **kw):
# load kwargs with default values
# do this here instead of in the def because we want to parse
# all of kwargs later to copy values to pass into f
def_vals = {'v': 0.0, 'h': 1.0, 'x': 0.0, 'w': 1.0, 's': 1.1, 'e': 1.0}
for v in def_... | def peak_model(f) | Given a function that models a peak, add scale and location arguments to
For all functions, v is vertical offset, h is height
x is horizontal offset (1st moment), w is width (2nd moment),
s is skewness (3rd moment), e is excess (4th moment) | 5.167555 | 4.88873 | 1.057034 |
arr = np.array(arr)
# find nearest value in array
idx = (abs(arr-value)).argmin()
return arr[idx] | def _findNearest(arr, value) | Finds the value in arr that value is closest to | 3.156471 | 3.148601 | 1.0025 |
magnitude_conversion_filepath = resource_stream(__name__, 'data/magnitude_conversion.dat')
raw_table = np.loadtxt(magnitude_conversion_filepath, '|S5')
magDict = {}
for row in raw_table:
if sys.hexversion >= 0x03000000:
starClass = row[1].decode("utf-8") # otherwise we get byt... | def _createMagConversionDict() | loads magnitude_conversion.dat which is table A% 1995ApJS..101..117K | 4.188551 | 3.857149 | 1.085919 |
try:
if not startClass: # reached system with no hits
raise AttributeError
except AttributeError: # i.e calling binary on an object without one
raise HierarchyError('This object ({0}) has no {1} as a parent object'.format(self.name, parentClass))
... | def _getParentClass(self, startClass, parentClass) | gets the parent class by calling successive parent classes with .parent until parentclass is matched. | 7.931892 | 7.262347 | 1.092194 |
paramTemp = self.getParam('temperature')
if not paramTemp is np.nan:
return paramTemp
elif ed_params.estimateMissingValues:
self.flags.addFlag('Calculated Temperature')
return self.calcTemperature()
else:
return np.nan | def T(self) | Looks for the temperature in the catalogue, if absent it calculates it using calcTemperature()
:return: planet temperature | 12.558218 | 12.210135 | 1.028508 |
# TODO this will only work from a star or below. good thing?
d = self.parent.d
if ed_params.estimateMissingValues:
if d is np.nan:
d = self.estimateDistance()
if d is not np.nan:
self.flags.addFlag('Estimated Distance')
... | def d(self) | Note this should work from child parents as .d propergates, calculates using the star estimation method
estimateDistance and estimateAbsoluteMagnitude | 14.976748 | 10.259224 | 1.459832 |
allowed_mags = "UBVJIHKLMN"
catalogue_mags = 'BVIJHK'
if mag_letter not in allowed_mags or not len(mag_letter) == 1:
raise ValueError("Magnitude letter must be a single letter in {0}".format(allowed_mags))
mag_str = 'mag'+mag_letter
mag_val = self.getParam(... | def _get_or_convert_magnitude(self, mag_letter) | Takes input of the magnitude letter and ouputs the magnitude fetched from the catalogue or a converted value
:return: | 5.144624 | 5.038503 | 1.021062 |
try:
isTransiting = self.params['istransiting']
except KeyError:
return False
if isTransiting == '1':
return True
else:
return False | def isTransiting(self) | Checks the the istransiting tag to see if the planet transits. Note that this only works as of catalogue
version ee12343381ae4106fd2db908e25ffc537a2ee98c (11th March 2014) where the istransiting tag was implemented | 4.533141 | 3.053018 | 1.484806 |
try:
if circular:
return eq.transitDurationCircular(self.P, self.star.R, self.R, self.a, self.i)
else:
return eq.TransitDuration(self.P, self.a, self.R, self.star.R, self.i, self.e, self.periastron).Td
except (ValueError,
... | def calcTransitDuration(self, circular=False) | Estimation of the primary transit time assuming a circular orbit (see :py:func:`equations.transitDuration`) | 8.654014 | 8.004487 | 1.081145 |
try:
return eq.MeanPlanetTemp(self.albedo, self.star.T, self.star.R, self.a).T_p
except (ValueError, HierarchyError): # ie missing value (.a) returning nan
return np.nan | def calcTemperature(self) | Calculates the temperature using which uses equations.MeanPlanetTemp, albedo assumption and potentially
equations.starTemperature.
issues
- you cant get the albedo assumption without temp but you need it to calculate the temp. | 24.992432 | 13.957568 | 1.790601 |
try:
return eq.KeplersThirdLaw(None, self.star.M, self.P).a
except HierarchyError:
return np.nan | def calcSMA(self) | Calculates the semi-major axis from Keplers Third Law | 29.485743 | 14.071822 | 2.095375 |
return eq.MeanPlanetTemp(self.albedo(), self.star.T, self.star.R, epsilon, self.T).a | def calcSMAfromT(self, epsilon=0.7) | Calculates the semi-major axis based on planet temperature | 30.069921 | 18.911964 | 1.589995 |
return eq.KeplersThirdLaw(self.a, self.star.M).P | def calcPeriod(self) | calculates period using a and stellar mass | 71.332985 | 28.01494 | 2.546248 |
if key in self.rejectTags:
return False # TODO Replace with exception
# Temporary code to handle the seperation tag than can occur several times with different units.
# TODO code a full multi unit solution (github issue #1)
if key == 'separation':
if a... | def addParam(self, key, value, attrib=None) | Checks the key dosnt already exist, adds alternate names to a seperate list
Future
- format input and add units
- logging | 5.140244 | 4.994284 | 1.029225 |
try:
classnumber = str(int(np.around(self.classNumber)))
except TypeError:
classnumber = str(self.classNumber)
return self.classLetter + classnumber | def roundedSpecClass(self) | Spectral class with rounded class number ie A8.5V is A9 | 5.408435 | 4.093778 | 1.321136 |
try:
classString = str(classString)
except UnicodeEncodeError:
# This is for the benefit of 1RXS1609 which currently has the spectral type K7\pm 1V
# TODO add unicode support and handling for this case / ammend the target
return False
# ... | def _parseSpecType(self, classString) | This class attempts to parse the spectral type. It should probably use more advanced matching use regex | 7.801988 | 7.669207 | 1.017314 |
allowed_mags = "UBVJIHKLMN"
if from_mag:
if to_mag == 'V': # If V mag is requested (1/3) - from mag specified
return self._convert_to_from('V', from_mag)
if from_mag == 'V':
magV = self.magV
else:
magV = self.... | def convert(self, to_mag, from_mag=None) | Converts magnitudes using UBVRIJHKLMNQ photometry in Taurus-Auriga (Kenyon+ 1995)
ReadMe+ftp1995ApJS..101..117K Colors for main-sequence stars
If from_mag isn't specified the program will cycle through provided magnitudes and choose one. Note that all
magnitudes are first converted to V, and... | 3.889986 | 3.778758 | 1.029435 |
lumtype = self.spectral_type.lumType
# rounds decimal types, TODO perhaps we should interpolate?
specClass = self.spectral_type.roundedSpecClass
if not specClass: # TODO investigate implications of this
raise ValueError('Can not convert when no spectral class is g... | def _convert_to_from(self, to_mag, from_mag, fromVMag=None) | Converts from or to V mag using the conversion tables
:param to_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param from_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param fromVMag: MagV if from_mag is 'V'
:return: estimated magnitude for to_mag from from_mag | 6.707222 | 6.54758 | 1.024382 |
f.seek(off)
return f.read(2 * struct.unpack('>B', f.read(1))[0]).decode('utf-16') | def _get_str(self, f, off) | Convenience function to quickly pull out strings. | 3.576503 | 3.171534 | 1.127689 |
# possible values for constants (from NIST)
cst = OrderedDict()
cst['Craig'] = {'S13': 0.0112372, 'S18': 0.002079,
'K': 0.008333, 'A': 0.5}
cst['IAEA'] = {'S13': 0.0112372, 'S18': 0.00206716068,
'K': 0.0091993, 'A': 0.5}
cst['Werner'] = {'S13': 0.0112372, ... | def delta13c_constants() | Constants for calculating delta13C values from ratios.
From website of Verkouteren & Lee 2001 Anal. Chem. | 2.36291 | 2.405493 | 0.982297 |
# the constants for the calculations
# originally r13, r17, r18 = 1123.72e-5, 759.9e-6, 415.8e-5
k = delta13c_constants()[ks]
# TODO: not clear why need to multiply by 2?
r13, r18 = k['S13'], 2 * k['S18']
r17 = 2 * (k['K'] * k['S18'] ** k['A'])
a = (r18 + r13 * r17) * (1. + r13 + r17)
... | def delta13c_craig(r45sam, r46sam, d13cstd, r45std, r46std,
ks='Craig', d18ostd=23.5) | Algorithm from Craig 1957.
From the original Craig paper, we can set up a pair of equations
and solve for d13C and d18O simultaneously:
d45 * r45 = r13 * d13
+ 0.5 * r17 * d18
d46 = r13 * ((r17**2 + r17 - r18) / a) * d13
+ 1 - 0.5 * r17 * ((r13**2 + r13 - r18) / a... | 3.384285 | 2.92501 | 1.157016 |
k = delta13c_constants()[ks]
# function for calculating 17R from 18R
def c17(r):
return k['K'] * r ** k['A']
rcpdb, rosmow = k['S13'], k['S18']
# known delta values for the ref peak
r13std = (d13cstd / 1000. + 1) * rcpdb
r18std = (d18ostd / 1000. + 1) * rosmow
# determine... | def delta13c_santrock(r45sam, r46sam, d13cstd, r45std, r46std,
ks='Santrock', d18ostd=23.5) | Given the measured isotope signals of a sample and a
standard and the delta-13C of that standard, calculate
the delta-13C of the sample.
Algorithm from Santrock, Studley & Hayes 1985 Anal. Chem. | 3.698485 | 3.791696 | 0.975417 |
'''
Copy file/dir resource to destination.
Parameters
----------
package_or_requirement : str
resource_name : str
destination : ~pathlib.Path
Path to copy to, it must not exist.
'''
args = package_or_requirement, resource_name
if resource_isdir(*args):
destinatio... | def resource_copy(package_or_requirement, resource_name, destination) | Copy file/dir resource to destination.
Parameters
----------
package_or_requirement : str
resource_name : str
destination : ~pathlib.Path
Path to copy to, it must not exist. | 2.979147 | 2.125175 | 1.401836 |
children = zk.get_children(path)
yield path
for child in children:
if path == '/':
subpath = "/%s" % child
else:
subpath = "%s/%s" % (path, child)
for child in walk(zk, subpath):
yield child | def walk(zk, path='/') | Yields all paths under `path`. | 2.153407 | 2.156384 | 0.998619 |
raise ValueError('`count` must be at least 1')
pprint(dict(take(count, dict_.items()))) | def pretty_print_head(dict_, count=10): #TODO only format and rename to pretty_head
'''
Pretty print some items of a dict.
For an unordered dict, ``count`` arbitrary items will be printed.
Parameters
----------
dict_ : ~typing.Dict
Dict to print from.
count : int
Number of ... | Pretty print some items of a dict.
For an unordered dict, ``count`` arbitrary items will be printed.
Parameters
----------
dict_ : ~typing.Dict
Dict to print from.
count : int
Number of items to print.
Raises
------
ValueError
When ``count < 1``. | 6.868842 | 10.069623 | 0.682135 |
from pytil.multi_dict import MultiDict
inverted_dict = dict(MultiDict(inverted_dict))
Examples
--------
>>> invert({1: 2, 3: 4})
{2: {1}, 4: {3}}
>>> invert({1: 2, 3: 2, 4: 5})
{2: {1,3}, 5: {4}}
'''
result = defaultdict(lambda: set())
for k, val in dict_.items():
... | def invert(dict_): #TODO return a MultiDict right away
'''
Invert dict by swapping each value with its key.
Parameters
----------
dict_ : ~typing.Dict[~typing.Hashable, ~typing.Hashable]
Dict to invert.
Returns
-------
~typing.Dict[~typing.Hashable, ~typing.Set[~typing.Hashable... | Invert dict by swapping each value with its key.
Parameters
----------
dict_ : ~typing.Dict[~typing.Hashable, ~typing.Hashable]
Dict to invert.
Returns
-------
~typing.Dict[~typing.Hashable, ~typing.Set[~typing.Hashable]]
Dict with keys and values swapped.
See also
---... | 1.912241 | 1.517467 | 1.260153 |
return self._call('delete', url=self.endpoint, json=json) | def delete(self, json=None) | Send a DELETE request and return the JSON decoded result.
Args:
json (dict, optional): Object to encode and send in request.
Returns:
mixed: JSON decoded response data. | 8.109583 | 12.120426 | 0.669084 |
return self._call('get', url=self.endpoint, params=params) | def get(self, params=None) | Send a POST request and return the JSON decoded result.
Args:
params (dict, optional): Mapping of parameters to send in request.
Returns:
mixed: JSON decoded response data. | 7.62261 | 12.137589 | 0.628017 |
return self._call('post', url=self.endpoint, json=json) | def post(self, json=None) | Send a POST request and return the JSON decoded result.
Args:
json (dict, optional): Object to encode and send in request.
Returns:
mixed: JSON decoded response data. | 7.292695 | 12.458294 | 0.585369 |
return self._call('put', url=self.endpoint, json=json) | def put(self, json=None) | Send a PUT request and return the JSON decoded result.
Args:
json (dict, optional): Object to encode and send in request.
Returns:
mixed: JSON decoded response data. | 7.874759 | 12.374778 | 0.636356 |
assert self.session
if not kwargs.get('verify'):
kwargs['verify'] = self.SSL_VERIFY
response = self.session.request(method, *args, **kwargs)
response_json = response.text and response.json() or {}
if response.status_code < 200 or response.status_code >= 3... | def _call(self, method, *args, **kwargs) | Call the remote service and return the response data. | 2.629084 | 2.574002 | 1.0214 |
if (len(data) > length):
return data[0:length]
else:
return data + b"\0" * (length - len(data)) | def pad(data, length) | This function returns a padded version of the input data to the
given length. this function will shorten the given data to the length
specified if necessary. post-condition: len(data) = length
:param data: the data byte array to pad
:param length: the length to pad the array to | 2.610169 | 3.183373 | 0.819938 |
aes = AES.new(self.key, AES.MODE_CFB, "\0" * AES.block_size)
while True:
nonce = 0
data = KeyedPRF.pad(SHA256.new(str(x + nonce).encode()).digest(),
(number.size(self.range) + 7) // 8)
num = self.mask & number.bytes_to_long(aes... | def eval(self, x) | This method returns the evaluation of the function with input x
:param x: this is the input as a Long | 5.680425 | 6.414032 | 0.885625 |
while bins[n] != n:
n = bins[n]
return n | def _locate_bin(bins, n) | Find the bin where list n has ended up: Follow bin references until
we find a bin that has not moved. | 3.90955 | 3.780638 | 1.034098 |
'''
Of a list of sets, merge those that overlap, in place.
The result isn't necessarily a subsequence of the original ``sets``.
Parameters
----------
sets : ~typing.Sequence[~typing.Set[~typing.Any]]
Sets of which to merge those that overlap. Empty sets are ignored.
Notes
----... | def merge_by_overlap(sets) | Of a list of sets, merge those that overlap, in place.
The result isn't necessarily a subsequence of the original ``sets``.
Parameters
----------
sets : ~typing.Sequence[~typing.Set[~typing.Any]]
Sets of which to merge those that overlap. Empty sets are ignored.
Notes
-----
Implem... | 5.378397 | 2.478721 | 2.169828 |
def _proxy(*args, **kwargs):
return method(self.session, *args, **kwargs)
return _proxy | def auth_proxy(self, method) | Authentication proxy for API requests.
This is required because the API objects are naive of ``HelpScout``,
so they would otherwise be unauthenticated.
Args:
method (callable): A method call that should be authenticated. It
should accept a ``requests.Session`` as its f... | 5.061094 | 6.611771 | 0.765467 |
if hasattr(mailbox_or_id, 'id'):
mailbox_or_id = mailbox_or_id.id
return cls(
'/mailboxes/%d/users.json' % mailbox_or_id,
session=session,
) | def find_in_mailbox(cls, session, mailbox_or_id) | Get the users that are associated to a Mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox_or_id (MailboxRef or int): Mailbox of the ID of the
mailbox to get the folders for.
Returns:
RequestPaginator(output_type=helpsc... | 2.873429 | 3.288158 | 0.873872 |
BUF_SIZE = 65536
with open(filename, 'rb') as f:
buf = f.read(BUF_SIZE)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(BUF_SIZE)
return hasher | def _hash_the_file(hasher, filename) | Helper function for creating hash functions.
See implementation of :func:`dtoolcore.filehasher.shasum`
for more usage details. | 1.555884 | 1.808165 | 0.860477 |
use_metis = panel['data_source']['source_type'] == 'querybuilder'
if use_metis:
query = panel['data_source']['query']
else:
query = "u'''%s'''" % panel['data_source']['code']
precompute = panel['data_source']['precompute']
timeframe = panel['data_source']['timeframe']
bucket_width = precompute['b... | def enable_precompute(panel) | Schedule a precompute task for `panel` | 3.598749 | 3.52227 | 1.021713 |
task_id = panel['data_source']['precompute']['task_id']
result = scheduler_client.cancel(task_id)
if result['status'] != 'success':
raise RuntimeError(result.get('reason')) | def disable_precompute(panel) | Cancel precomputation for `panel` | 6.579109 | 5.987234 | 1.098856 |
if bucket_width:
bucket_width_seconds = bucket_width
bucket_width = epoch_time_to_kronos_time(bucket_width)
# TODO(derek): Potential optimization by setting the end_time equal to the
# untrusted_time if end_time > untrusted_time and the results are not being
# output to the user (only ... | def _get_timeframe_bounds(self, timeframe, bucket_width) | Get a `bucket_width` aligned `start_time` and `end_time` from a
`timeframe` dict | 2.870089 | 2.857201 | 1.004511 |
# XXX(derek): DEPRECATION WARNING
# Use of the implicit Kronos client in pycode queries is deprecated
client = KronosClient(self._app.config['KRONOS_URL'],
namespace=self._app.config['KRONOS_NAMESPACE'],
blocking=False,
sleep... | def _run_query(self, start_time, end_time, unique_id=None) | Executes a Python query string and returns events
Acts as a wrapper around exec that injects necessary local variables into
the scope of the user-provided query blob.
:param start_time: Python datetime to be injected into query
:param end_time: Python datetime to be injected into query
:param uniq... | 5.891155 | 5.915898 | 0.995818 |
if use_cache:
if not self._bucket_width:
raise ValueError('QueryCompute must be initialized with a bucket_width'
' to use caching features.')
return list(self._query_cache.retrieve_interval(self._start_time,
self... | def compute(self, use_cache=True) | Call a user defined query and return events with optional help from
the cache.
:param use_cache: Specifies whether the cache should be used when possible | 4.425761 | 4.639733 | 0.953883 |
if not self._bucket_width or self._untrusted_time is None:
raise ValueError('QueryCompute must be initialized with a bucket_width '
'and an untrusted_time in order to write to the cache.')
now = datetime.datetime.now()
untrusted_time = now - datetime.timedelta(seconds=self... | def cache(self) | Call a user defined query and cache the results | 6.10922 | 5.707144 | 1.070451 |
return super(Customers, cls).list(
session,
data=cls.__object__.get_non_empty_vals({
'firstName': first_name,
'lastName': last_name,
'email': email,
'modifiedSince': modified_since,
})
) | def list(cls, session, first_name=None, last_name=None, email=None,
modified_since=None) | List the customers.
Customers can be filtered on any combination of first name, last name,
email, and modifiedSince.
Args:
session (requests.sessions.Session): Authenticated session.
first_name (str, optional): First name of customer.
last_name (str, optiona... | 5.074697 | 5.607783 | 0.904938 |
return super(Customers, cls).search(session, queries, SearchCustomer) | def search(cls, session, queries) | Search for a customer given a domain.
Args:
session (requests.sessions.Session): Authenticated session.
queries (helpscout.models.Domain or iter): The queries for the
domain. If a ``Domain`` object is provided, it will simply be
returned. Otherwise, a ``D... | 12.783913 | 15.72014 | 0.813219 |
token = hmac.new(key)
token.update(json.dumps(payload))
return token.hexdigest() | def create_token(key, payload) | Auth token generator
payload should be a json encodable data structure | 4.16752 | 3.220613 | 1.294014 |
global _APP
if _APP:
return _APP
_APP = Flask(__name__)
db.init_app(_APP)
migrate = Migrate(_APP, db, directory='scheduler/migrations')
_APP.config.from_pyfile('../jia/conf/default_settings.py')
if settings_file:
if not settings_file.startswith('/'):
settings_file = os.path.join(os.pardi... | def get_app(settings_file=None) | Get scheduler app singleton
The app configuration is performed when the function is run for the first
time.
Because the scheduler is a threaded enviroment, it is important that this
function be thread-safe. The scheduler instance is not created until the
`commands/runscheduler.py` script is executed, and ... | 2.47449 | 2.458085 | 1.006674 |
return super(Conversations, cls).create(
session,
record,
imported=imported,
auto_reply=auto_reply,
) | def create(cls, session, record, imported=False, auto_reply=False) | Create a conversation.
Please note that conversation cannot be created with more than 100
threads, if attempted the API will respond with HTTP 412.
Args:
session (requests.sessions.Session): Authenticated session.
record (helpscout.models.Conversation): The conversation... | 2.817751 | 3.987467 | 0.706652 |
return super(Conversations, cls).create(
session,
attachment,
endpoint_override='/attachments.json',
out_type=Attachment,
) | def create_attachment(cls, session, attachment) | Create an attachment.
An attachment must be sent to the API before it can be used in a
thread. Use this method to create the attachment, then use the
resulting hash when creating a thread.
Note that HelpScout only supports attachments of 10MB or lower.
Args:
sessio... | 11.46448 | 11.72627 | 0.977675 |
return super(Conversations, cls).create(
session,
thread,
endpoint_override='/conversations/%s.json' % conversation.id,
imported=imported,
) | def create_thread(cls, session, conversation, thread, imported=False) | Create a conversation thread.
Please note that threads cannot be added to conversations with 100
threads (or more), if attempted the API will respond with HTTP 412.
Args:
conversation (helpscout.models.Conversation): The conversation
that the thread is being added to.
... | 5.113461 | 6.488019 | 0.788139 |
return super(Conversations, cls).delete(
session,
attachment,
endpoint_override='/attachments/%s.json' % attachment.id,
out_type=Attachment,
) | def delete_attachment(cls, session, attachment) | Delete an attachment.
Args:
session (requests.sessions.Session): Authenticated session.
attachment (helpscout.models.Attachment): The attachment to
be deleted.
Returns:
NoneType: Nothing. | 7.415973 | 8.972134 | 0.826556 |
return cls(
'/mailboxes/%d/customers/%s/conversations.json' % (
mailbox.id, customer.id,
),
session=session,
) | def find_customer(cls, session, mailbox, customer) | Return conversations for a specific customer in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to search.
customer (helpscout.models.Customer): Customer to search for.
Returns:
Req... | 5.820238 | 4.970489 | 1.170959 |
return cls(
'/mailboxes/%d/users/%s/conversations.json' % (
mailbox.id, user.id,
),
session=session,
) | def find_user(cls, session, mailbox, user) | Return conversations for a specific user in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to search.
user (helpscout.models.User): User to search for.
Returns:
RequestPaginator(ou... | 5.480218 | 4.770097 | 1.148869 |
return cls(
'/attachments/%d/data.json' % attachment_id,
singleton=True,
session=session,
out_type=AttachmentData,
) | def get_attachment_data(cls, session, attachment_id) | Return a specific attachment's data.
Args:
session (requests.sessions.Session): Authenticated session.
attachment_id (int): The ID of the attachment from which to get
data.
Returns:
helpscout.models.AttachmentData: An attachment data singleton, if
... | 7.09607 | 8.054989 | 0.880953 |
endpoint = '/mailboxes/%d/conversations.json' % mailbox.id
return super(Conversations, cls).list(session, endpoint) | def list(cls, session, mailbox) | Return conversations in a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to list.
Returns:
RequestPaginator(output_type=helpscout.models.Conversation):
Conversations iterator. | 4.890541 | 5.113818 | 0.956338 |
return cls(
'/mailboxes/%d/folders/%s/conversations.json' % (
mailbox.id, folder.id,
),
session=session,
) | def list_folder(cls, session, mailbox, folder) | Return conversations in a specific folder of a mailbox.
Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox that folder is in.
folder (helpscout.models.Folder): Folder to list.
Returns:
RequestPag... | 5.072248 | 5.024306 | 1.009542 |
return super(Conversations, cls).search(
session, queries, SearchConversation,
) | def search(cls, session, queries) | Search for a conversation given a domain.
Args:
session (requests.sessions.Session): Authenticated session.
queries (helpscout.models.Domain or iter): The queries for the
domain. If a ``Domain`` object is provided, it will simply be
returned. Otherwise, a... | 12.965201 | 13.875201 | 0.934415 |
data = thread.to_api()
data['reload'] = True
return cls(
'/conversations/%s/threads/%d.json' % (
conversation.id, thread.id,
),
data=data,
request_type=RequestPaginator.PUT,
singleton=True,
session=s... | def update_thread(cls, session, conversation, thread) | Update a thread.
Args:
session (requests.sessions.Session): Authenticated session.
conversation (helpscout.models.Conversation): The conversation
that the thread belongs to.
thread (helpscout.models.Thread): The thread to be updated.
Returns:
... | 5.50436 | 6.397297 | 0.86042 |
'''
Temporarily change log level of logger.
Parameters
----------
logger : str or ~logging.Logger
Logger name or logger whose log level to change.
level : int
Log level to set.
Examples
--------
>>> with set_level('sqlalchemy.engine', logging.INFO):
... pass... | def set_level(logger, level) | Temporarily change log level of logger.
Parameters
----------
logger : str or ~logging.Logger
Logger name or logger whose log level to change.
level : int
Log level to set.
Examples
--------
>>> with set_level('sqlalchemy.engine', logging.INFO):
... pass # sqlalche... | 3.265779 | 1.487947 | 2.194822 |
'''
Configure root logger to log INFO to stderr and DEBUG to log file.
The log file is appended to. Stderr uses a terse format, while the log file
uses a verbose unambiguous format.
Root level is set to INFO.
Parameters
----------
log_file : ~pathlib.Path
File to log to.
... | def configure(log_file) | Configure root logger to log INFO to stderr and DEBUG to log file.
The log file is appended to. Stderr uses a terse format, while the log file
uses a verbose unambiguous format.
Root level is set to INFO.
Parameters
----------
log_file : ~pathlib.Path
File to log to.
Returns
... | 3.177662 | 1.957758 | 1.623113 |
def get_pandasframe(self):
if self.dataset:
self._load_dimensions()
return self._get_pandasframe_one_dataset()
return self._get_pandasframe_across_datasets() | The method loads data from dataset | null | null | null | |
def add_value(self, value, index_point):
if index_point not in self.index:
self.values.append(value)
self.index.append(index_point) | The function is addeing new value to provied index. If index does not exist | null | null | null | |
def get_pandas_series(self):
return pandas.Series(self.values, self.index, name=self.name) | The function creates pandas series based on index and values | null | null | null | |
'''
Remove file or directory (recursively), if it exists.
On NFS file systems, if a directory contains :file:`.nfs*` temporary files
(sometimes created when deleting a file), it waits for them to go away.
Parameters
----------
path : ~pathlib.Path
Path to remove.
force : bool
... | def remove(path, force=False) | Remove file or directory (recursively), if it exists.
On NFS file systems, if a directory contains :file:`.nfs*` temporary files
(sometimes created when deleting a file), it waits for them to go away.
Parameters
----------
path : ~pathlib.Path
Path to remove.
force : bool
If Tr... | 4.29487 | 2.822808 | 1.521488 |
'''
Change file mode bits.
When recursively chmodding a directory, executable bits in ``mode`` are
ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777,
recursive=True)`` would apply ``mode=0o666`` to regular files.
Symlinks are ignored.
Parameters
----------
pat... | def chmod(path, mode, operator='=', recursive=False) | Change file mode bits.
When recursively chmodding a directory, executable bits in ``mode`` are
ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777,
recursive=True)`` would apply ``mode=0o666`` to regular files.
Symlinks are ignored.
Parameters
----------
path : ~pathlib... | 3.349854 | 2.050957 | 1.633313 |
raise
Raise exception on failure.
ignore
Fail silently.
'''
if dir:
dir = str(dir) # @ReservedAssignment
temp_dir = tempfile.TemporaryDirectory(suffix, prefix, dir)
try:
yield Path(temp_dir.name)
finally:
try:
temp_dir.cle... | def TemporaryDirectory(suffix=None, prefix=None, dir=None, on_error='ignore'): # @ReservedAssignment
'''
An extension to `tempfile.TemporaryDirectory`.
Unlike with `python:tempfile`, a :py:class:`~pathlib.Path` is yielded on
``__enter__``, not a `str`.
Parameters
----------
suffix : str
... | An extension to `tempfile.TemporaryDirectory`.
Unlike with `python:tempfile`, a :py:class:`~pathlib.Path` is yielded on
``__enter__``, not a `str`.
Parameters
----------
suffix : str
See `tempfile.TemporaryDirectory`.
prefix : str
See `tempfile.TemporaryDirectory`.
dir : ~p... | 3.791937 | 2.783512 | 1.362285 |
for directory, directories, files in os.walk(str(path), topdown=True):
# Note:
# - directory: path to current directory in walk relative to current working direcotry
# - directories/files: dir/file names
# Note: file names can contain nearly any character (even n... | def hash(path, hash_function=hashlib.sha512): # @ReservedAssignment
'''
Hash file or directory.
Parameters
----------
path : ~pathlib.Path
File or directory to hash.
hash_function : ~typing.Callable[[], hash object]
Function which creates a hashlib hash object when called. Defa... | Hash file or directory.
Parameters
----------
path : ~pathlib.Path
File or directory to hash.
hash_function : ~typing.Callable[[], hash object]
Function which creates a hashlib hash object when called. Defaults to
``hashlib.sha512``.
Returns
-------
hash object
... | 3.610053 | 4.099636 | 0.880579 |
rc = DKReturnCode()
if orderrun_id == 'good':
rc.set(rc.DK_SUCCESS, None, None)
else:
rc.set(rc.DK_FAIL, 'ServingDeleteV2: unable to delete OrderRun')
return rc | def delete_orderrun(self, orderrun_id) | :param self: self
:param orderrun_id: string ; 'good' return a good value ; 'bad' return a bad value
:rtype: DKReturnCode | 10.988232 | 6.245761 | 1.75931 |
a_ids = set(a.identifiers)
b_ids = set(b.identifiers)
difference = []
for i in a_ids.difference(b_ids):
difference.append((i, True, False))
for i in b_ids.difference(a_ids):
difference.append((i, False, True))
return difference | def diff_identifiers(a, b) | Return list of tuples where identifiers in datasets differ.
Tuple structure:
(identifier, present in a, present in b)
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: list of tuples where identifiers in datasets differ | 2.308641 | 1.894532 | 1.218581 |
difference = []
for i in a.identifiers:
a_size = a.item_properties(i)["size_in_bytes"]
b_size = b.item_properties(i)["size_in_bytes"]
if a_size != b_size:
difference.append((i, a_size, b_size))
if progressbar:
progressbar.update(1)
return differ... | def diff_sizes(a, b, progressbar=None) | Return list of tuples where sizes differ.
Tuple structure:
(identifier, size in a, size in b)
Assumes list of identifiers in a and b are identical.
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: list of tuples for all items with different size... | 2.545985 | 2.386057 | 1.067026 |
difference = []
for i in a.identifiers:
fpath = a.item_content_abspath(i)
calc_hash = reference._storage_broker.hasher(fpath)
ref_hash = reference.item_properties(i)["hash"]
if calc_hash != ref_hash:
info = (i, calc_hash, ref_hash)
difference.append(... | def diff_content(a, reference, progressbar=None) | Return list of tuples where content differ.
Tuple structure:
(identifier, hash in a, hash in reference)
Assumes list of identifiers in a and b are identical.
Storage broker of reference used to generate hash for files in a.
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`... | 4.453905 | 3.567276 | 1.248545 |
max_items = configuration['max_items']
for _id, event in events:
while len(self.db[namespace][stream]) >= max_items:
self.db[namespace][stream].pop(0)
bisect.insort(self.db[namespace][stream], Event(_id, event)) | def _insert(self, namespace, stream, events, configuration) | `stream` is the name of a stream and `events` is a list of
(TimeUUID, event) to insert. Make room for the events to insert if
necessary by deleting the oldest events. Then insert each event in time
sorted order. | 3.678545 | 3.354034 | 1.096752 |
start_id_event = Event(start_id)
end_id_event = Event(uuid_from_kronos_time(end_time,
_type=UUIDType.HIGHEST))
stream_events = self.db[namespace][stream]
# Find the interval our events belong to.
lo = bisect.bisect_left(stream_events, start_id_eve... | def _delete(self, namespace, stream, start_id, end_time, configuration) | Delete events with id > `start_id` and end_time <= `end_time`. | 3.821068 | 3.853232 | 0.991653 |
start_id_event = Event(start_id)
end_id_event = Event(uuid_from_kronos_time(end_time,
_type=UUIDType.HIGHEST))
stream_events = self.db[namespace][stream]
# Find the interval our events belong to.
lo = bisect.bisect_left(stream_events, start_id_eve... | def _retrieve(self, namespace, stream, start_id, end_time, order, limit,
configuration) | Yield events from stream starting after the event with id `start_id` until
and including events with timestamp `end_time`. | 3.617772 | 3.461245 | 1.045223 |
parser = argparse.ArgumentParser(prog="sphinx-serve",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
conflict_handler="resolve",
description=__doc__
)
... | def cli() | Parse options from the command line | 2.227315 | 2.184859 | 1.019432 |
path = os.path.abspath(os.path.expanduser(path))
contents = os.listdir(path)
filtered_contents = [directory for directory in contents
if os.path.isdir(os.path.join(path, directory))]
if build in filtered_contents:
return os.path.join(path, build)
else:
... | def find_build_dir(path, build="_build") | try to guess the build folder's location | 2.38255 | 2.319954 | 1.026982 |
flipped_uuid = uuid.split('-')
flipped_uuid[0], flipped_uuid[2] = flipped_uuid[2], flipped_uuid[0]
flipped_uuid = '-'.join(flipped_uuid)
return flipped_uuid | def flip_uuid_parts(uuid) | Flips high and low segments of the timestamp portion of a UUID string.
This enables correct lexicographic sorting. Because it is a simple flip,
this function works in both directions. | 1.892603 | 1.819931 | 1.039931 |
starPar = StarParameters()
starPar.addParam('age', '7.6')
starPar.addParam('magB', '9.8')
starPar.addParam('magH', '7.4')
starPar.addParam('magI', '7.6')
starPar.addParam('magJ', '7.5')
starPar.addParam('magK', '7.3')
starPar.addParam('magV', '9.0')
starPar.addParam('mass', '0.... | def genExampleStar(binaryLetter='', heirarchy=True) | generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a
system and link everything up | 3.072558 | 2.957232 | 1.038998 |
planetPar = PlanetParameters()
planetPar.addParam('discoverymethod', 'transit')
planetPar.addParam('discoveryyear', '2001')
planetPar.addParam('eccentricity', '0.09')
planetPar.addParam('inclination', '89.2')
planetPar.addParam('lastupdate', '12/12/08')
planetPar.addParam('mass', '3.9'... | def genExamplePlanet(binaryLetter='') | Creates a fake planet with some defaults
:param `binaryLetter`: host star is part of a binary with letter binaryletter
:return: | 4.129653 | 4.087011 | 1.010433 |
click.secho('Print Configuration', fg='green')
print str(backend.dki.get_config()) | def config_list(backend) | Print the current configuration | 18.436016 | 15.597283 | 1.182002 |
kitchen = DKCloudCommandRunner.which_kitchen_name()
if kitchen is None:
raise click.ClickException('You are not in a Kitchen')
recipe_dir = DKRecipeDisk.find_recipe_root_dir()
if recipe_dir is None:
raise click.ClickException('You must be in a Recipe folder')
recipe_name = DKRec... | def recipe_status(backend) | Compare local recipe to remote recipe for the current recipe. | 5.026174 | 4.842105 | 1.038014 |
recipe_dir = DKRecipeDisk.find_recipe_root_dir()
if recipe_dir is None:
raise click.ClickException('You must be in a Recipe folder.')
recipe_name = DKRecipeDisk.find_recipe_name()
click.secho("%s - Checking for conflicts on Recipe '%s'" % (
get_datetime(),recipe_name))
recipe_na... | def recipe_conflicts(backend) | See if there are any unresolved conflicts for this recipe. | 6.092057 | 5.657176 | 1.076872 |
click.echo(click.style('%s - Getting the list of kitchens' % get_datetime(), fg='green'))
check_and_print(DKCloudCommandRunner.list_kitchen(backend.dki)) | def kitchen_list(backend) | List all Kitchens | 14.664052 | 14.227357 | 1.030694 |
found_kitchen = DKKitchenDisk.find_kitchen_name()
if found_kitchen is not None and len(found_kitchen) > 0:
raise click.ClickException("You cannot get a kitchen into an existing kitchen directory structure.")
if len(recipe) > 0:
click.secho("%s - Getting kitchen '%s' and the recipes %s"... | def kitchen_get(backend, kitchen_name, recipe) | Get an existing Kitchen | 4.84482 | 4.864297 | 0.995996 |
click.secho('%s - Creating kitchen %s from parent kitchen %s' % (get_datetime(), kitchen, parent), fg='green')
master = 'master'
if kitchen.lower() != master.lower():
check_and_print(DKCloudCommandRunner.create_kitchen(backend.dki, parent, kitchen))
else:
raise click.ClickException(... | def kitchen_create(backend, parent, kitchen) | Create a new kitchen | 6.453754 | 6.487043 | 0.994868 |
click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green')
master = 'master'
if kitchen.lower() != master.lower():
check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki, kitchen))
else:
raise click.ClickException('Cannot delete the kitchen called %s' %... | def kitchen_delete(backend, kitchen) | Provide the name of the kitchen to delete | 6.753402 | 6.507737 | 1.03775 |
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get, unset, listall)) | def kitchen_config(backend, kitchen, add, get, unset, listall) | Get and Set Kitchen variable overrides | 7.283679 | 7.716561 | 0.943902 |
click.secho('%s - Merging Kitchen %s into Kitchen %s' % (get_datetime(), source_kitchen, target_kitchen), fg='green')
check_and_print(DKCloudCommandRunner.merge_kitchens_improved(backend.dki, source_kitchen, target_kitchen)) | def kitchen_merge(backend, source_kitchen, target_kitchen) | Merge two Kitchens | 7.040575 | 7.050602 | 0.998578 |
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
click.secho("%s - Getting the list of Recipes for Kitchen '%s'" % (get_datetime(), use_kitchen), fg='green')
check_and_print(DKCloudCommandRunner.list_recipe(backend.dki... | def recipe_list(backend, kitchen) | List the Recipes in a Kitchen | 7.558878 | 6.903309 | 1.094964 |
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
click.secho("%s - Creating Recipe %s for Kitchen '%s'" % (get_datetime(), name, use_kitchen), fg='green')
check_and_print(DKCloudCommandRunner.recipe_create(backend.dki,... | def recipe_create(backend, kitchen, name) | Create a new Recipe | 6.89224 | 6.845517 | 1.006825 |
recipe_root_dir = DKRecipeDisk.find_recipe_root_dir()
if recipe_root_dir is None:
if recipe is None:
raise click.ClickException("\nPlease change to a recipe folder or provide a recipe name arguement")
# raise click.ClickException('You must be in a Recipe folder')
kitche... | def recipe_get(backend, recipe) | Get the latest files for this recipe. | 4.171254 | 4.124355 | 1.011371 |
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
if recipe is None:
recipe = DKRecipeDisk.find_recipe_name()
if recipe is None:
raise click.ClickException('You must be in a recipe folder, or pr... | def recipe_compile(backend, kitchen, recipe, variation) | Apply variables to a Recipe | 7.536438 | 7.5095 | 1.003587 |
err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
if use_kitchen is None:
raise click.ClickException(err_str)
if recipe is None:
recipe = DKRecipeDisk.find_recipe_name()
if recipe is None:
raise click.ClickException('You must be in a recipe folder, or pro... | def file_add(backend, kitchen, recipe, message, filepath) | Add a newly created file to a Recipe | 5.517313 | 5.445606 | 1.013168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.