code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self.downloaded is False:
raise serror("Track not downloaded, can't convert file..")
filetype = magic.from_file(self.filepath, mime=True)
if filetype == "audio/mpeg":
print("File is already in mp3 format. Skipping convert.")
return False
r... | def convert(self) | Convert file in mp3 format. | 3.726896 | 3.472759 | 1.07318 |
if self.get("artwork-url") == "None":
self.metadata["artwork-path"] = None
return None
artwork_dir = localdir + "/artworks"
if not os.path.isdir(artwork_dir):
if os.path.isfile(artwork_dir):
os.unlink(artwork_dir)
os.mkdir... | def download_artwork(self, localdir, max_retry) | Download track's artwork and return file path.
Artwork's path is saved in track's metadata as 'artwork-path' key. | 2.67239 | 2.407162 | 1.110183 |
read = blocknum * blocksize
if totalsize > 0:
percent = read * 1e2 / totalsize
s = "\r%d%% %*d / %d" % (
percent, len(str(totalsize)), read, totalsize)
sys.stdout.write(s)
if read >= totalsize:
sys.stdout.write("\n... | def _progress_hook(self, blocknum, blocksize, totalsize) | Progress hook for urlretrieve. | 1.698387 | 1.70809 | 0.994319 |
if not isinstance(track, strack):
raise TypeError('strack object required')
timestamp = calendar.timegm(parse(track.get("created-at")).timetuple())
self.mapper[TIT1] = TIT1(text=track.get("description"))
self.mapper[TIT2] = TIT2(text=track.get("title"))
sel... | def load_id3(self, track) | Load id3 tags from strack metadata | 2.657716 | 2.486001 | 1.069073 |
if not os.path.exists(filename):
raise ValueError("File doesn't exists.")
self.mapper.write(filename) | def write_id3(self, filename) | Write id3 tags | 6.585255 | 6.378457 | 1.032421 |
import pyglet
widest = max(img.width for img in images)
height = sum(img.height for img in images)
atlas = pyglet.image.atlas.TextureAtlas(
width=_nearest_pow2(widest), height=_nearest_pow2(height))
textures = [atlas.add(image) for image in images]
return atlas, textures | def _atlas_from_images(images) | Create a pyglet texture atlas from a sequence of images.
Return a tuple of (atlas, textures) | 3.112307 | 2.535904 | 1.227297 |
from pyglet import gl
assert feather >= 0, 'Expected feather value >= 0'
coords = range(size)
texel = (gl.GLfloat * size**2)()
r = size / 2.0
c = feather + 1.0
for y in coords:
col = y * size
for x in coords:
d = math.sqrt((x - r)**2 + (y - r)**2)
if d < r and (1.0 - 1.0 / (d / r - 1.0)) < 100:
... | def create_point_texture(size, feather=0) | Create and load a circular grayscale image centered in a square texture
with a width and height of size. The radius of the circle is size / 2.
Since size is used as the texture width and height, it should typically
be a power of two.
Feather determines the softness of the edge of the circle. The default,
zero, cr... | 2.286356 | 2.384154 | 0.95898 |
import pyglet
atlas, textures = _atlas_from_images(images)
texturizer = cls(
atlas.texture.id, [tex.tex_coords for tex in textures],
weights, filter or pyglet.gl.GL_LINEAR, wrap or pyglet.gl.GL_CLAMP,
aspect_adjust_width, aspect_adjust_height)
texturizer.atlas = atlas
texturizer.textures = texture... | def from_images(cls, images, weights=None, filter=None, wrap=None,
aspect_adjust_width=False, aspect_adjust_height=False) | Create a SpriteTexturizer from a sequence of Pyglet images.
Note all the images must be able to fit into a single OpenGL texture, so
their combined size should typically be less than 1024x1024 | 3.092479 | 2.990538 | 1.034088 |
if querystring is None or len(querystring) == 0:
return {}
qs_dict = parse.parse_qs(querystring, keep_blank_values=True)
for key in qs_dict:
if len(qs_dict[key]) != 1:
continue
qs_dict[key] = qs_dict[key][0]
if qs_dict[key] == '':
qs_dict[key] = ... | def parse_querystring(querystring) | Return parsed querystring in dict | 1.990785 | 2.009685 | 0.990596 |
data_dict = self.to_dict()
if pretty:
return json.dumps(
data_dict, sort_keys=True, indent=2)
return json.dumps(data_dict, sort_keys=True) | def to_json(self, pretty=True) | to_json will call to_dict then dumps into json format | 2.308135 | 2.071615 | 1.114172 |
return dict(
(k, self.__dict__[k]) for k in self.__dict__ if k.find("_") != 0) | def to_dict(self) | to_dict will clean all protected and private properties | 4.189811 | 3.834545 | 1.092649 |
_resource = trim_resource(self.resource)
self.method = self.method.lower()
resource_match = route.resource_regex.search(_resource)
if resource_match is None:
return None
# build params and querystring
params = resource_match.groupdict()
query... | def match(self, route) | Match input route and return new Message instance
with parsed content | 4.261008 | 4.134645 | 1.030562 |
msg = copy.deepcopy(self)
msg.data = data
setattr(msg, 'code', code)
for _ in ["query", "param", "tunnel"]:
if not hasattr(msg, _):
continue
delattr(msg, _)
if hasattr(msg, 'sign') and isinstance(msg.sign, list):
msg.... | def to_response(self, sign, code=200, data=None) | transform message to response message
Notice: this method will return a deepcopy | 4.165666 | 3.927616 | 1.060609 |
msg = copy.deepcopy(self)
for _ in ["id", "sign", "tunnel", "query", "param"]:
if not hasattr(msg, _):
continue
delattr(msg, _)
msg._type = Message.get_message_type(msg.__dict__)
return msg | def to_event(self) | get rid of id, sign, tunnel and update message type
Notice: this method will return a deepcopy | 7.745381 | 4.411245 | 1.755826 |
for msg_type in MessageType.FIELDS:
if Message.is_type(msg_type, message):
return msg_type
return MessageType.UNKNOWN | def get_message_type(message) | Return message's type | 5.808815 | 5.059368 | 1.148131 |
for prop in MessageType.FIELDS[msg_type]["must"]:
if msg.get(prop, False) is False:
return False
for prop in MessageType.FIELDS[msg_type]["prohibit"]:
if msg.get(prop, False) is not False:
return False
return True | def is_type(msg_type, msg) | Return message's type is or not | 3.873629 | 3.872279 | 1.000349 |
if name is None:
fname = f.__name__ # Register the function using its own name.
else:
fname = name
self.method_data[fname] = {'method': f}
if types is not None:
self.method_data[fname]['types'] = types
if required is not None:
... | def add(self, f, name=None, types=None, required=None) | Adds a new method to the jsonrpc service.
Arguments:
f -- the remote function
name -- name of the method in the jsonrpc service
types -- list or dictionary of the types of accepted arguments
required -- list of required keyword arguments
If name argument is not given, f... | 3.162612 | 3.165473 | 0.999096 |
if exception is None:
exception = ServiceUnavailableError
self.serve_exception = exception
if self.pending:
d = self.out_of_service_deferred = defer.Deferred()
return d
return defer.succeed(None) | def stopServing(self, exception=None) | Returns a deferred that will fire immediately if there are
no pending requests, otherwise when the last request is removed
from self.pending. | 5.592385 | 4.125123 | 1.355689 |
result = yield self.call_py(jsondata)
if result is None:
defer.returnValue(None)
else:
defer.returnValue(json.dumps(result)) | def call(self, jsondata) | Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format | 3.731997 | 4.133591 | 0.902846 |
try:
try:
rdata = json.loads(jsondata)
except ValueError:
raise ParseError
except ParseError, e:
defer.returnValue(self._get_err(e))
return
# set some default values for error handling
request = sel... | def call_py(self, jsondata) | Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes. | 2.479826 | 2.485937 | 0.997542 |
# Do not respond to notifications when the request is valid.
if not id \
and not isinstance(e, ParseError) \
and not isinstance(e, InvalidRequestError):
return None
respond = {'id': id}
if isinstance(jsonrpc, int):
# v1.0... | def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC) | Returns jsonrpc error message. | 5.49717 | 5.344031 | 1.028656 |
argcount = f.func_code.co_argcount
# account for "self" getting passed to class instance methods
if isinstance(f, types.MethodType):
argcount -= 1
if f.func_defaults is None:
return argcount
return argcount - len(f.func_defaults) | def _man_args(self, f) | Returns number of mandatory arguments required by given function. | 4.162203 | 3.544212 | 1.174366 |
if f.func_defaults is None:
return f.func_code.co_argcount
return f.func_code.co_argcount + len(f.func_defaults) | def _max_args(self, f) | Returns maximum number of arguments accepted by given function. | 2.498402 | 2.275454 | 1.097979 |
if 'id' in rdata:
if isinstance(rdata['id'], basestring) or \
isinstance(rdata['id'], int) or \
isinstance(rdata['id'], long) or \
isinstance(rdata['id'], float) or \
rdata['id'] is None:
return ... | def _get_id(self, rdata) | Returns jsonrpc request's id value or None if there is none.
InvalidRequestError will be raised if the id value has invalid type. | 2.92013 | 2.245603 | 1.300377 |
if 'method' in rdata:
if not isinstance(rdata['method'], basestring):
raise InvalidRequestError
else:
raise InvalidRequestError
if rdata['method'] not in self.method_data.keys():
raise MethodNotFoundError
return rdata['method... | def _get_method(self, rdata) | Returns jsonrpc request's method value.
InvalidRequestError will be raised if it's missing or is wrong type.
MethodNotFoundError will be raised if a method with given method name
does not exist. | 3.227864 | 2.556739 | 1.262493 |
if 'params' in rdata:
if isinstance(rdata['params'], dict) \
or isinstance(rdata['params'], list) \
or rdata['params'] is None:
return rdata['params']
else:
# wrong type
raise InvalidRequestE... | def _get_params(self, rdata) | Returns a list of jsonrpc request's method parameters. | 3.110214 | 2.701398 | 1.151335 |
if not isinstance(rdata, dict):
raise InvalidRequestError
request['jsonrpc'] = self._get_jsonrpc(rdata)
request['id'] = self._get_id(rdata)
request['method'] = self._get_method(rdata)
request['params'] = self._get_params(rdata) | def _fill_request(self, request, rdata) | Fills request with data from the jsonrpc call. | 2.463113 | 2.043518 | 1.205329 |
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method):
raise Inval... | def _call_method(self, request) | Calls given method with given params and returns it value. | 3.641026 | 3.643671 | 0.999274 |
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
if self.serve_exception:
raise self.serve_exception()
d = self._call_method(request)
self.pending.add(d)
if self.timeout:
... | def _handle_request(self, request) | Handles given request and returns its response. | 4.401473 | 4.326475 | 1.017335 |
if isinstance(params, list):
if not isinstance(self.method_data[method]['types'], list):
raise InvalidParamsError(
'expected keyword params, not positional')
for param, type, posnum in zip(params,
se... | def _validate_params_types(self, method, params) | Validates request's parameter types. | 2.291792 | 2.261439 | 1.013422 |
self.clientFactory.connect().addErrback(
log.err, 'error starting the JSON-RPC client service %r' % (self,))
service.Service.startService(self) | def startService(self) | Start the service and connect the JSONRPCClientFactory. | 9.12503 | 5.772673 | 1.580729 |
if not self.running:
return defer.fail(ServiceStopped())
return self.clientFactory.callRemote(*a, **kw) | def callRemote(self, *a, **kw) | Make a callRemote request of the JSONRPCClientFactory. | 5.600638 | 4.137891 | 1.353501 |
error = {'code': self.code,
'message': str(self.message)}
if self.data is not None:
error['data'] = self.data
return error | def dumps(self) | Return the Exception data in a format for JSON-RPC. | 4.288803 | 2.702138 | 1.587189 |
response = self.post(self.server_url + parent.ref + '/' + obj_type, attributes)
return self._get_href(response.json()) | def add(self, parent, obj_type, **attributes) | IXN API add command
@param parent: object parent - object will be created under this parent.
@param object_type: object type.
@param attributes: additional attributes.
@return: STC object reference. | 7.337272 | 7.019196 | 1.045315 |
sorted_segments = sorted(self.segments,
key=lambda x: (
x.genome_id * (10 ** 23) +
x.chr_id * (10 ** 21) +
(x.left + (int(x.left == 0) * x.right - 1)) * (10 ** 11) +
x.right * (10 ** 1) +
int(x.direction == "F")
)
)
s... | def stringize(
self,
rnf_profile=RnfProfile(),
) | Create RNF representation of this read.
Args:
read_tuple_id_width (int): Maximal expected string length of read tuple ID.
genome_id_width (int): Maximal expected string length of genome ID.
chr_id_width (int): Maximal expected string length of chromosome ID.
coor_width (int): Maximal expected string leng... | 3.910434 | 3.569935 | 1.09538 |
# todo: assert -- starting with (, ending with )
# (prefix,read_tuple_id,segments_t,suffix)=(text).split("__")
# segments=segments_t.split("),(")
m = read_tuple_destr_pattern.match(string)
if not m:
smbl.messages.error(
"'{}' is not a valid r... | def destringize(self, string) | Get RNF values for this read from its textual representation and save them
into this object.
Args:
string(str): Textual representation of a read.
Raises:
ValueError | 5.479629 | 5.450897 | 1.005271 |
'''Construct a .desktop file and return it as a string.
Create a standards-compliant .desktop file, returning it as a string.
Args:
name (str) : The program's name.
exec\_ (str) : The command.
terminal (bool): Determine if program should be run in a terminal emulator or not. Defaults to ``False``.
... | def construct(name, exec_, terminal=False, additional_opts={}) | Construct a .desktop file and return it as a string.
Create a standards-compliant .desktop file, returning it as a string.
Args:
name (str) : The program's name.
exec\_ (str) : The command.
terminal (bool): Determine if program should be run in a terminal emulator or not. Defaults to ``False``.
addi... | 2.627989 | 1.564639 | 1.679613 |
'''Execute a .desktop file.
Executes a given .desktop file path properly.
Args:
desktop_file (str) : The path to the .desktop file.
files (list): Any files to be launched by the .desktop. Defaults to empty list.
return_cmd (bool): Return the command (as ``str``) instead of executing. Defaults to ``False`... | def execute(desktop_file, files=None, return_cmd=False, background=False) | Execute a .desktop file.
Executes a given .desktop file path properly.
Args:
desktop_file (str) : The path to the .desktop file.
files (list): Any files to be launched by the .desktop. Defaults to empty list.
return_cmd (bool): Return the command (as ``str``) instead of executing. Defaults to ``False``.
... | 3.689939 | 2.423559 | 1.522529 |
'''Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the filename of a .desktop file or the nam... | def locate(desktop_filename_or_name) | Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the filename of a .desktop file or the name of... | 2.564594 | 1.861467 | 1.377727 |
'''Parse a .desktop file.
Parse a .desktop file or a string with its contents into an easy-to-use dict, with standard values present even if not defined in file.
Args:
desktop_file_or_string (str): Either the path to a .desktop file or a string with a .desktop file as its contents.
Returns:
dict: A dictionary... | def parse(desktop_file_or_string) | Parse a .desktop file.
Parse a .desktop file or a string with its contents into an easy-to-use dict, with standard values present even if not defined in file.
Args:
desktop_file_or_string (str): Either the path to a .desktop file or a string with a .desktop file as its contents.
Returns:
dict: A dictionary of ... | 2.249545 | 1.482547 | 1.517351 |
with _AcquireFutures(fs):
finished = set(f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
pending = set(fs) - finished
waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
timer = Timeout(timeout)
timer.start()
try:
for future in finished:
... | def as_completed(fs, timeout=None) | An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
... | 3.672418 | 3.866105 | 0.949901 |
loop = evergreen.current.loop
timeout = kwargs.get('timeout')
if timeout is not None:
end_time = timeout + loop.time()
fs = [self.submit(fn, *args) for args in zip(*iterables)]
# Yield must be hidden in closure so that the futures are submitted
# b... | def map(self, fn, *iterables, **kwargs) | Returns a iterator equivalent to map(fn, iter).
Args:
fn: A callable that will take take as many arguments as there are
passed iterables.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
... | 4.392922 | 4.437032 | 0.990059 |
self.set_wsgi_app(wsgi_app)
ssl_config = self.get_config("ssl")
ssl_context = {}
if self.get_config("server") == "gevent":
if ssl_config.get("enabled"):
ssl_context["certfile"] = ssl_config.get("cert")
ssl_context["keyfile"] = ssl_... | def set_server(self, wsgi_app, fnc_serve=None) | figures out how the wsgi application is to be served
according to config | 2.676036 | 2.662462 | 1.005098 |
# get currently entered slug
value = self.value_from_object(instance)
slug = None
# auto populate (if the form didn't do that already).
# If you want unique_with logic, use django-autoslug instead.
# This model field only allows parameters which can be passed to... | def pre_save(self, instance, add) | Auto-generate the slug if needed. | 7.350838 | 6.831194 | 1.076069 |
def FirstSlotSlicer(primary_query, secondary_query, limit=30): # noqa
reading_list = SearchSlicer(limit=limit)
reading_list.register_queryset(primary_query)
reading_list.register_queryset(secondary_query, validator=lambda x: bool(x == 0))
return reading_list | Inject the first object from a queryset into the first position of a reading list.
:param primary_queryset: djes.LazySearch object. Default queryset for reading list.
:param secondary_queryset: djes.LazySearch object. first result leads the reading_list.
:return list: mixed reading list. | null | null | null | |
if default or self.default_queryset is None:
self.default_queryset = queryset
return
if validator:
self.querysets[validator] = queryset
else:
raise ValueError(
) | def register_queryset(self, queryset, validator=None, default=False) | Add a given queryset to the iterator with custom logic for iteration.
:param queryset: List of objects included in the reading list.
:param validator: Custom logic to determine a queryset's position in a reading_list.
Validators must accept an index as an argument and return a truthy value.... | 4.409086 | 6.435787 | 0.685089 |
now = timezone.now()
return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo) | def get_month_start_date(self) | Returns the first day of the current month | 3.150289 | 3.033692 | 1.038434 |
'''
Given a iterable like list or tuple the function yields each of its
items with _yield
'''
if l is not None:
if type(l) in [list, tuple]:
for f in l:
for x in self._yield(f): yield x
else:
for x in sel... | def _yield_all(self, l) | Given a iterable like list or tuple the function yields each of its
items with _yield | 5.318059 | 2.547935 | 2.087203 |
response = self.session.post(
url=self._get_url(administration_id, resource_path),
json=data,
)
return self._process_response(response) | def post(self, resource_path: str, data: dict, administration_id: int = None) | Performs a POST request to the endpoint identified by the resource path. POST requests are usually used to add
new data.
Example:
>>> from moneybird import MoneyBird, TokenAuthentication
>>> moneybird = MoneyBird(TokenAuthentication('access_token'))
>>> data = {'url'... | 3.173439 | 3.565748 | 0.889978 |
response = self.session.delete(
url=self._get_url(administration_id, resource_path),
)
return self._process_response(response) | def delete(self, resource_path: str, administration_id: int = None) | Performs a DELETE request to the endpoint identified by the resource path. DELETE requests are usually used to
(permanently) delete existing data. USE THIS METHOD WITH CAUTION.
From a client perspective, DELETE requests behave similarly to GET requests.
:param resource_path: The resource path.... | 3.654018 | 3.474814 | 1.051572 |
logger.debug("API session renewed")
self.session = self.authentication.get_session()
self.session.headers.update({
'User-Agent': 'MoneyBird for Python %s' % VERSION,
'Accept': 'application/json',
}) | def renew_session(self) | Clears all session data and starts a new session using the same settings as before.
This method can be used to clear session data, e.g., cookies. Future requests will use a new session initiated
with the same settings and authentication method. | 4.834061 | 5.187697 | 0.931832 |
url = urljoin(cls.base_url, '%s/' % cls.version)
if administration_id is not None:
url = urljoin(url, '%s/' % administration_id)
url = urljoin(url, '%s.json' % resource_path)
return url | def _get_url(cls, administration_id: int, resource_path: str) | Builds the URL to the API endpoint specified by the given parameters.
:param administration_id: The ID of the administration (may be None).
:param resource_path: The path to the resource.
:return: The absolute URL to the endpoint. | 2.852338 | 2.63718 | 1.081586 |
responses = {
200: None,
201: None,
204: None,
400: MoneyBird.Unauthorized,
401: MoneyBird.Unauthorized,
403: MoneyBird.Throttled,
404: MoneyBird.NotFound,
406: MoneyBird.NotFound,
422: MoneyBird... | def _process_response(response: requests.Response, expected: list = []) -> dict | Processes an API response. Raises an exception when appropriate.
The exception that will be raised is MoneyBird.APIError. This exception is subclassed so implementing programs
can easily react appropriately to different exceptions.
The following subclasses of MoneyBird.APIError are likely to b... | 2.387788 | 2.01678 | 1.183961 |
# construct url
url = getattr(settings, "VIDEOHUB_API_SEARCH_URL", cls.DEFAULT_VIDEOHUB_API_SEARCH_URL)
# construct auth headers
headers = {
"Content-Type": "application/json",
"Authorization": settings.VIDEOHUB_API_TOKEN,
}
# construct pa... | def search_videohub(cls, query, filters=None, status=None, sort=None, size=None, page=None) | searches the videohub given a query and applies given filters and other bits
:see: https://github.com/theonion/videohub/blob/master/docs/search/post.md
:see: https://github.com/theonion/videohub/blob/master/docs/search/get.md
:param query: query terms to search by
:type query: str
... | 1.873547 | 1.966491 | 0.952736 |
url = getattr(settings, "VIDEOHUB_VIDEO_URL", self.DEFAULT_VIDEOHUB_VIDEO_URL)
# slugify needs ascii
ascii_title = ""
if isinstance(self.title, str):
ascii_title = self.title
elif six.PY2 and isinstance(self.title, six.text_type):
# Legacy unicod... | def get_hub_url(self) | gets a canonical path to the detail page of the video on the hub
:return: the path to the consumer ui detail page of the video
:rtype: str | 4.482204 | 4.784117 | 0.936893 |
url = getattr(settings, "VIDEOHUB_EMBED_URL", self.DEFAULT_VIDEOHUB_EMBED_URL)
url = url.format(self.id)
if targeting is not None:
for k, v in sorted(targeting.items()):
url += '&{0}={1}'.format(k, v)
if recirc is not None:
url += '&recirc... | def get_embed_url(self, targeting=None, recirc=None) | gets a canonical path to an embedded iframe of the video from the hub
:return: the path to create an embedded iframe of the video
:rtype: str | 2.301948 | 2.471835 | 0.931271 |
url = getattr(settings, 'VIDEOHUB_API_URL', None)
# Support alternate setting (used by most client projects)
if not url:
url = getattr(settings, 'VIDEOHUB_API_BASE_URL', None)
if url:
url = url.rstrip('/') + '/videos/{}'
if not url:
... | def get_api_url(self) | gets a canonical path to the api detail url of the video on the hub
:return: the path to the api detail of the video
:rtype: str | 4.285234 | 4.417882 | 0.969975 |
if node is None or node._prev == -1:
return
if node._next is None:
self._last = node._prev # last node
else:
node._next._prev = node._prev
if node._prev is None:
self._first = node._next # first node
else:
nod... | def remove(self, node) | Remove a node from the list.
The *node* argument must be a node that was previously inserted in the
list | 2.337254 | 2.52613 | 0.925231 |
def get_all_outcome_links_for_context_accounts(self, account_id, outcome_group_style=None, outcome_style=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# OPTIONAL - outcome_style
... | Get all outcome links for context. | null | null | null | |
def get_all_outcome_links_for_context_courses(self, course_id, outcome_group_style=None, outcome_style=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# OPTIONAL - outcome_style
... | Get all outcome links for context. | null | null | null | |
def create_link_outcome_global_outcome_id(self, id, outcome_id, calculation_int=None, calculation_method=None, description=None, display_name=None, mastery_points=None, ratings_description=None, ratings_points=None, title=None, vendor_guid=None):
path = {}
data = {}
params = {}
... | Create/link an outcome.
Link an outcome into the outcome group. The outcome to link can either be
specified by a PUT to the link URL for a specific outcome (the outcome_id
in the PUT URLs) or by supplying the information for a new outcome (title,
description, ratings, mastery_point... | null | null | null | |
def list_subgroups_global(self, id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
path["id"] = id
self.logger.debug("GET /api/v1/global/outcome_groups/{id}/subgroups with query params: {params} and form data: {data}".format(params=p... | List subgroups.
List the immediate OutcomeGroup children of the outcome group. Paginated. | null | null | null | |
def list_subgroups_accounts(self, id, account_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# REQUIRED - PATH - id
path["id"] = id
self.logger.debug("GET /api... | List subgroups.
List the immediate OutcomeGroup children of the outcome group. Paginated. | null | null | null | |
def create_subgroup_global(self, id, title, description=None, vendor_guid=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
path["id"] = id
# REQUIRED - title
data["title"] = title
# OPTIONAL - descri... | Create a subgroup.
Creates a new empty subgroup under the outcome group with the given title
and description. | null | null | null | |
def update_single_grading_period(self, id, course_id, grading_periods_end_date, grading_periods_start_date, grading_periods_weight=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED -... | Update a single grading period.
Update an existing grading period. | null | null | null | |
def delete_grading_period_accounts(self, id, account_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
path["account_id"] = account_id
# REQUIRED - PATH - id
path["id"] = id
self.logger.debug("D... | Delete a grading period.
<b>204 No Content</b> response code is returned if the deletion was
successful. | null | null | null | |
def list_appointment_groups(self, context_codes=None, include=None, include_past_appointments=None, scope=None):
path = {}
data = {}
params = {}
# OPTIONAL - scope
"
if scope is not None:
self._validate_enum(scope, ["reservable", "manageable... | List appointment groups.
Retrieve the list of appointment groups that can be reserved or managed by
the current user. | null | null | null | |
def create_appointment_group(self, appointment_group_title, appointment_group_context_codes, appointment_group_description=None, appointment_group_location_address=None, appointment_group_location_name=None, appointment_group_max_appointments_per_participant=None, appointment_group_min_appointments_per_participant=None... | Create an appointment group.
Create and return a new appointment group. If new_appointments are
specified, the response will return a new_appointments array (same format
as appointments array, see "List appointment groups" action) | null | null | null | |
def list_user_participants(self, id, registration_status=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
path["id"] = id
# OPTIONAL - registration_status
"
if registration_status is not None:
self.... | List user participants.
List users that are (or may be) participating in this appointment group.
Refer to the Users API for the response fields. Returns no results for
appointment groups with the "Group" participant_type. | null | null | null | |
def get_next_appointment(self, appointment_group_ids=None):
path = {}
data = {}
params = {}
# OPTIONAL - appointment_group_ids
if appointment_group_ids is not None:
params["appointment_group_ids"] = appointment_group_ids
self.log... | Get next appointment.
Return the next appointment available to sign up for. The appointment
is returned in a one-element array. If no future appointments are
available, an empty array is returned. | null | null | null | |
fs = self.clampings.to_funset("exp")
fs = fs.union(self.setup.to_funset())
for i, row in self.readouts.iterrows():
for var, val in row.iteritems():
if not np.isnan(val):
fs.add(gringo.Fun('obs', [i, var, discrete(val)]))
return f... | def to_funset(self, discrete) | Converts the dataset to a set of `gringo.Fun`_ instances
Parameters
----------
discrete : callable
A discretization function
Returns
-------
set
Representation of the dataset as a set of `gringo.Fun`_ instances
.. _gringo.Fun: http://po... | 8.610484 | 7.720489 | 1.115277 |
# Set current timestamp
timestamp = datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H-%M-%S')
# Clean sub_dir
if sub_dir and '.' in sub_dir:
sub_dir = sub_dir.rsplit('.', 1)[0]
# Create a directory to save fail SQL scripts
# TODO: Replace with function that recursively creates ... | def set_dump_directory(base=None, sub_dir=None) | Create directory for dumping SQL commands. | 2.659619 | 2.570059 | 1.034847 |
print('\t' + str(len(commands)), 'failed commands')
# Create dump_dir directory
if directory and os.path.isfile(directory):
dump_dir = set_dump_directory(os.path.dirname(directory), sub_dir)
return_dir = dump_dir
elif directory:
dump_dir = set_dump_directory(directory, sub_... | def dump_commands(commands, directory=None, sub_dir=None) | Dump SQL commands to .sql files.
:param commands: List of SQL commands
:param directory: Directory to dump commands to
:param sub_dir: Sub directory
:return: Directory failed commands were dumped to | 3.384745 | 3.317597 | 1.02024 |
command = _command.strip()
with open(txt_file, 'w') as txt:
txt.writelines(command) | def write_text(_command, txt_file) | Dump SQL command to a text file. | 3.53055 | 3.170389 | 1.113602 |
# Get SQL commands file paths
failed_scripts = sorted([os.path.join(directory, fn) for fn in os.listdir(directory) if fn.endswith('.sql')])
# Read each failed SQL file and append contents to a list
print('\tReading SQL scripts from files')
commands = []
for sql_file in failed_scripts:
... | def get_commands_from_dir(directory, zip_backup=True, remove_dir=True) | Traverse a directory and read contained SQL files. | 4.447816 | 4.197542 | 1.059624 |
blueprint = dict()
blueprint['type'] = "%s.%s" % (self.__module__, self.__class__.__name__)
# Fields
fields = dict()
# inspects the attributes of a parameter set and tries to validate the input
for attribute_name, type_instance in self.getmembers():
... | def blueprint(self) | blueprint support, returns a partial dictionary | 2.90895 | 2.841629 | 1.023691 |
validated_parameter_set = self.__class__()
# Inspects the attributes of a parameter set and tries to validate the input
for attribute_name, type_instance in self.getmembers():
#: Must be one of the following types
if not isinstance(type_instance, String) and \... | def validate(self, request) | validate method for %ParameterSet
Since the introduction of ResponseFieldListParser, the parameter _response_field_list
will be ignored, this is a prestans reserved parameter, and cannot be used by apps.
:param request: The request object to be validated
:type request: webob.request.Re... | 3.403276 | 3.226249 | 1.054871 |
# Need to get attribute from dictionary for instance tests to work
for base in subclass.__mro__: # pragma: no branch
if meth in base.__dict__:
submethobj = base.__dict__[meth]
break
# If we found our abstract method, we didn't find anything
... | def _check_methods(cls, subclass): # pylint: disable=too-many-branches
for meth, methobj in cls.__abstractmethods__.items() | Args:
cls(:py:class:`Plugin`): Parent class
subclass(:py:class:`Plugin`): Subclass to evaluate
Returns:
Result: Named tuple
Validate abstract methods are defined in subclass
For error codes see _inspect_class | 2.149397 | 2.204153 | 0.975158 |
if callable(subclass._skipload_):
result = subclass._skipload_()
if isinstance(result, tuple):
skip, msg = result
else:
skip, msg = result, None
if skip:
return Result(False, msg, 156)
elif subclass._skipload_:
return Result(F... | def _inspect_class(cls, subclass) | Args:
cls(:py:class:`Plugin`): Parent class
subclass(:py:class:`Plugin`): Subclass to evaluate
Returns:
Result: Named tuple
Inspect subclass for inclusion
Values for errorcode:
* 0: No error
Error codes between 0 and 100 are not intended for import
* 50 ... | 5.449771 | 3.70325 | 1.471618 |
def version(cls): # noqa: N805 # pylint: disable=no-self-argument
return cls._version_ or getattr(sys.modules.get(cls.__module__, None),
'__version__', None) | :py:class:Returns `str` -- Returns :attr:`_version_` if set,
otherwise falls back to module `__version__` or None | null | null | null | |
try:
_add_url_rule([page.url for page in Page.query.all()])
except Exception: # pragma: no cover
current_app.logger.warn('Pages were not loaded.')
raise | def preload_pages() | Register all pages before the first application request. | 7.786746 | 6.413182 | 1.214178 |
try:
page = Page.get_by_url(request.path)
except NoResultFound:
abort(404)
return render_template(
[page.template_name, current_app.config['PAGES_DEFAULT_TEMPLATE']],
page=page) | def render_page(path) | Internal interface to the page view.
:param path: Page path.
:returns: The rendered template. | 3.838166 | 4.040091 | 0.95002 |
assert isinstance(exception, NotFound)
page = Page.query.filter(db.or_(Page.url == request.path,
Page.url == request.path + "/")).first()
if page:
_add_url_rule(page.url)
return render_template(
[
page.template_name,
... | def handle_not_found(exception, **extra) | Custom blueprint exception handler. | 4.520713 | 4.249856 | 1.063733 |
old = current_app._got_first_request
# This is bit of cheating to overcome @flask.app.setupmethod decorator.
current_app._got_first_request = False
if isinstance(url_or_urls, six.string_types):
url_or_urls = [url_or_urls]
map(lambda url: current_app.add_url_rule(url, 'invenio_pages.view... | def _add_url_rule(url_or_urls) | Register URL rule to application URL map. | 4.522384 | 4.710729 | 0.960018 |
def list_members_of_collaboration(self, id, include=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
path["id"] = id
# OPTIONAL - include
if include is not None:
self._validate_enum(include, ["coll... | List members of a collaboration.
List the collaborators of a given collaboration | null | null | null | |
def list_discussion_topics_courses(self, course_id, exclude_context_module_locked_topics=None, include=None, only_announcements=None, order_by=None, scope=None, search_term=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["cours... | List discussion topics.
Returns the paginated list of discussion topics for this course or group. | null | null | null | |
def create_new_discussion_topic_courses(self, course_id, allow_rating=None, assignment=None, attachment=None, delayed_post_at=None, discussion_type=None, group_category_id=None, is_announcement=None, lock_at=None, message=None, only_graders_can_rate=None, pinned=None, podcast_enabled=None, podcast_has_student_posts=Non... | Create a new discussion topic.
Create an new discussion topic for the course or group. | null | null | null | |
def delete_topic_groups(self, group_id, topic_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
path["group_id"] = group_id
# REQUIRED - PATH - topic_id
path["topic_id"] = topic_id
self.logger.deb... | Delete a topic.
Deletes the discussion topic. This will also delete the assignment, if it's
an assignment discussion. | null | null | null | |
def reorder_pinned_topics_courses(self, order, course_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - order
data["order"] = order
self.logger.debug("P... | Reorder pinned topics.
Puts the pinned discussion topics in the specified order.
All pinned topics should be included. | null | null | null | |
def reorder_pinned_topics_groups(self, order, group_id):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
path["group_id"] = group_id
# REQUIRED - order
data["order"] = order
self.logger.debug("POST /... | Reorder pinned topics.
Puts the pinned discussion topics in the specified order.
All pinned topics should be included. | null | null | null | |
def post_entry_courses(self, topic_id, course_id, attachment=None, message=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - topic_id
path["topic_id"] = t... | Post an entry.
Create a new entry in a discussion topic. Returns a json representation of
the created entry (see documentation for 'entries' method) on success. | null | null | null | |
def post_reply_groups(self, group_id, topic_id, entry_id, attachment=None, message=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
path["group_id"] = group_id
# REQUIRED - PATH - topic_id
path["topic_id"... | Post a reply.
Add a reply to an entry in a discussion topic. Returns a json
representation of the created reply (see documentation for 'replies'
method) on success.
May require (depending on the topic) that the user has posted in the topic.
If it is required, and... | null | null | null | |
def rate_entry_courses(self, topic_id, entry_id, course_id, rating=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
path["course_id"] = course_id
# REQUIRED - PATH - topic_id
path["topic_id"] = topic_id
... | Rate entry.
Rate a discussion entry.
On success, the response will be 204 No Content with an empty body. | null | null | null | |
setup_logging(settings)
settings = setup_languages(settings)
channels = setup_channel_map(settings)
app = CriticApp(**dict(settings, channels=channels))
if settings['sentry_dsn']:
app.sentry_client = Client(settings['sentry_dsn'])
logger.debug('Errors are reported to %s' % setti... | def cli(**settings) | Notify about new reviews in AppStore and Google Play in slack.
Launch command using supervisor or using screen/tmux/etc.
Reviews are fetched for multiple apps and languages in --beat=300 interval. | 3.219282 | 3.12337 | 1.030708 |
if self._seqs is None:
os.symlink(self._fa0_fn, self._fa_fn)
else:
in_seqs = pyfaidx.Fasta(self._fa0_fn)
with open(self._fa_fn, "w+") as g:
for seq_desc in self._seqs:
x = in_seqs[seq_desc]
name, seq =... | def create_fa(self) | Create a FASTA file with extracted sequences. | 3.112465 | 2.979947 | 1.04447 |
fai_index = rnftools.utils.FaIdx(fai_fo)
# last_read_tuple_name=[]
read_tuple_id_width = len(format(number_of_read_tuples, 'x'))
fq_creator = rnftools.rnfformat.FqCreator(
fastq_fo=fastq_rnf_fo,
read_tuple_id_width=read_tuple_id_width,
genome... | def recode_sam_reads(
sam_fn,
fastq_rnf_fo,
fai_fo,
genome_id,
number_of_read_tuples=10**9,
simulator_name=None,
allow_unmapped=False,
) | Transform a SAM file to RNF-compatible FASTQ.
Args:
sam_fn (str): SAM/BAM file - file name.
fastq_rnf_fo (str): Output FASTQ file - file object.
fai_fo (str): FAI index of the reference genome - file object.
genome_id (int): Genome ID for RNF.
number_of_read_tuples (int): Expected number of read tuple... | 3.362147 | 3.345948 | 1.004841 |
for handle, cfg in list(config["apps"].items()):
if not cfg.get("enabled", True):
continue
app = get_application(handle)
instances[app.handle] = app(cfg) | def instantiate(config) | instantiate all registered vodka applications
Args:
config (dict or MungeConfig): configuration object | 6.466904 | 6.480951 | 0.997832 |
return re.compile("^" + trim_resource(re.sub(r":(\w+)", r"(?P<\1>[\w-]+?)",
resource)) + r"(\?(?P<querystring>.*))?$") | def compile_resource(resource) | Return compiled regex for resource matching | 7.33781 | 6.207253 | 1.182135 |
def _handler(callback, schema=None):
# reentrant default is False [POST, DELETE, PUT]
reentrant = False
if method == "get":
reentrant = True
self.handlers.append({
"method": method,
"callback":... | def create_handler_func(self, method) | create_handler_func | 5.759857 | 5.622638 | 1.024405 |
handlers = []
for handler in self.handlers:
if handler["method"] != message.method:
continue
handlers.append(handler)
return handlers | def dispatch(self, message) | dispatch | 4.965608 | 4.989014 | 0.995308 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.