code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if self._stream: self._stream.close(exc_info=exc_info)
def _disconnect(self, exc_info=False)
Disconnect and cleanup.
4.466345
3.678238
1.214262
# log messages received so that no one else has to if self._logger.isEnabledFor(logging.DEBUG): self._logger.debug( "received from {}: {}" .format(self.bind_address_string, repr(str(msg)))) if msg.mtype == Message.INFORM: return s...
def handle_message(self, msg)
Handle a message from the server. Parameters ---------- msg : Message object The Message to dispatch to the handler methods.
3.810136
3.828982
0.995078
method = self._inform_handlers.get( msg.name, self.__class__.unhandled_inform) try: return method(self, msg) except Exception: e_type, e_value, trace = sys.exc_info() reason = "\n".join(traceback.format_exception( e_type, ...
def handle_inform(self, msg)
Dispatch an inform message to the appropriate method. Parameters ---------- msg : Message object The inform message to dispatch.
3.432372
3.914669
0.876797
method = self.__class__.unhandled_reply if msg.name in self._reply_handlers: method = self._reply_handlers[msg.name] try: return method(self, msg) except Exception: e_type, e_value, trace = sys.exc_info() reason = "\n".join(traceb...
def handle_reply(self, msg)
Dispatch a reply message to the appropriate method. Parameters ---------- msg : Message object The reply message to dispatch.
3.245814
3.480141
0.932668
method = self.__class__.unhandled_request if msg.name in self._request_handlers: method = self._request_handlers[msg.name] try: reply = method(self, msg) if isinstance(reply, Message): # If it is a message object, assume it is a reply...
def handle_request(self, msg)
Dispatch a request message to the appropriate method. Parameters ---------- msg : Message object The request message to dispatch.
4.9653
5.034571
0.986241
self._ioloop_manager.set_ioloop(ioloop, managed=False) self.ioloop = ioloop
def set_ioloop(self, ioloop=None)
Set the tornado.ioloop.IOLoop instance to use. This defaults to IOLoop.current(). If set_ioloop() is never called the IOLoop is managed: started in a new thread, and will be stopped if self.stop() is called. Notes ----- Must be called before start() is called
5.852895
7.718707
0.758274
if self.threadsafe: return # Already done! if self._running.isSet(): raise RuntimeError('Cannot enable thread safety after start') def _getattr(obj, name): # use 'is True' so mock objects don't return true for everything ...
def enable_thread_safety(self)
Enable thread-safety features. Must be called before start().
3.939833
3.943156
0.999157
if self._running.isSet(): raise RuntimeError("Device client already started.") # Make sure we have an ioloop self.ioloop = self._ioloop_manager.get_ioloop() if timeout: t0 = self.ioloop.time() self._ioloop_manager.start(timeout) self.ioloo...
def start(self, timeout=None)
Start the client in a new thread. Parameters ---------- timeout : float in seconds Seconds to wait for client thread to start. Do not specify a timeout if start() is being called from the same ioloop that this client will be installed on, since it will block ...
3.918715
3.600568
1.08836
ioloop = getattr(self, 'ioloop', None) if not ioloop: raise RuntimeError('Call start() before stop()') if timeout: if get_thread_ident() == self.ioloop_thread_id: raise RuntimeError('Cannot block inside ioloop') self._running.wait_with...
def stop(self, timeout=None)
Stop a running client (from another thread). Parameters ---------- timeout : float in seconds Seconds to wait for client thread to have *started*.
4.715682
4.854605
0.971383
ioloop = getattr(self, 'ioloop', None) if not ioloop: raise RuntimeError('Call start() before wait_running()') return self._running.wait_with_ioloop(ioloop, timeout)
def wait_running(self, timeout=None)
Wait until the client is running. Parameters ---------- timeout : float in seconds Seconds to wait for the client to start running. Returns ------- running : bool Whether the client is running Notes ----- Do not call this...
4.584349
4.509638
1.016567
t0 = self.ioloop.time() yield self.until_running(timeout=timeout) t1 = self.ioloop.time() if timeout: timedelta = timeout - (t1 - t0) else: timedelta = None assert get_thread_ident() == self.ioloop_thread_id yield self._connected.u...
def until_connected(self, timeout=None)
Return future that resolves when the client is connected.
4.191644
3.918966
1.069579
t0 = self.ioloop.time() yield self.until_running(timeout=timeout) t1 = self.ioloop.time() if timeout: timedelta = timeout - (t1 - t0) else: timedelta = None assert get_thread_ident() == self.ioloop_thread_id yield self._received_pr...
def until_protocol(self, timeout=None)
Return future that resolves after receipt of katcp protocol info. If the returned future resolves, the server's protocol information is available in the ProtocolFlags instance self.protocol_flags.
4.914876
4.165586
1.179876
assert get_thread_ident() == self.ioloop_thread_id self._async_queue[msg_id] = ( request, reply_cb, inform_cb, user_data, timeout_handle) if request.name in self._async_id_stack: self._async_id_stack[request.name].append(msg_id) else: self._as...
def _push_async_request(self, msg_id, request, reply_cb, inform_cb, user_data, timeout_handle)
Store reply / inform callbacks for request we've sent.
2.508891
2.511576
0.998931
assert get_thread_ident() == self.ioloop_thread_id if msg_id is None: msg_id = self._msg_id_for_name(msg_name) if msg_id in self._async_queue: callback_tuple = self._async_queue[msg_id] del self._async_queue[msg_id] self._async_id_stack[ca...
def _pop_async_request(self, msg_id, msg_name)
Pop the set of callbacks for a request. Return tuple of Nones if callbacks already popped (or don't exist).
3.250213
3.013012
1.078726
assert get_thread_ident() == self.ioloop_thread_id if msg_id is None: msg_id = self._msg_id_for_name(msg_name) if msg_id in self._async_queue: return self._async_queue[msg_id] else: return None, None, None, None, None
def _peek_async_request(self, msg_id, msg_name)
Peek at the set of callbacks for a request. Return tuple of Nones if callbacks don't exist.
3.280914
3.015845
1.087892
if msg_name in self._async_id_stack and self._async_id_stack[msg_name]: return self._async_id_stack[msg_name][0]
def _msg_id_for_name(self, msg_name)
Find the msg_id for a given request name. Return None if no message id exists.
3.355343
3.536595
0.948749
if timeout is None: timeout = self._request_timeout mid = self._get_mid_and_update_msg(msg, use_mid) if timeout is None: # deal with 'no timeout', i.e. None timeout_handle = None else: timeout_handle = self.ioloop.call_later( ...
def callback_request(self, msg, reply_cb=None, inform_cb=None, user_data=None, timeout=None, use_mid=None)
Send a request messsage. Parameters ---------- msg : Message object The request message to send. reply_cb : function The reply callback with signature reply_cb(msg) or reply_cb(msg, \*user_data) inform_cb : function The inform call...
3.801404
3.855025
0.986091
if timeout is None: timeout = self._request_timeout f = tornado_Future() informs = [] def reply_cb(msg): f.set_result((msg, informs)) def inform_cb(msg): informs.append(msg) try: self.callback_request(msg, reply...
def future_request(self, msg, timeout=None, use_mid=None)
Send a request messsage, with future replies. Parameters ---------- msg : Message object The request Message to send. timeout : float in seconds How long to wait for a reply. The default is the the timeout set when creating the AsyncClient. us...
2.738564
2.657076
1.030668
assert (get_thread_ident() != self.ioloop_thread_id), ( 'Cannot call blocking_request() in ioloop') if timeout is None: timeout = self._request_timeout f = Future() # for thread safety tf = [None] # Placeholder for tornado Future for exception traceba...
def blocking_request(self, msg, timeout=None, use_mid=None)
Send a request messsage and wait for its reply. Parameters ---------- msg : Message object The request Message to send. timeout : float in seconds How long to wait for a reply. The default is the the timeout set when creating the AsyncClient. ...
5.454749
5.660831
0.963595
# this may also result in inform_cb being None if no # inform_cb was passed to the request method. if msg.mid is not None: _request, _reply_cb, inform_cb, user_data, _timeout_handle = \ self._peek_async_request(msg.mid, None) else: request...
def handle_inform(self, msg)
Handle inform messages related to any current requests. Inform messages not related to the current request go up to the base class method. Parameters ---------- msg : Message object The inform message to dispatch.
3.777195
3.92575
0.962159
# this may also result in reply_cb being None if no # reply_cb was passed to the request method if reply_cb is None: # this happens if no reply_cb was passed in to the request return reason_msg = Message.reply(msg.name, "fail", reason, mid=msg.mid) ...
def _do_fail_callback( self, reason, msg, reply_cb, inform_cb, user_data, timeout_handle)
Do callback for a failed request.
4.162935
4.22267
0.985854
msg, reply_cb, inform_cb, user_data, timeout_handle = \ self._pop_async_request(msg_id, None) # We may have been racing with the actual reply handler if the reply # arrived close to the timeout expiry, # which means the self._pop_async_request() call gave us None's. ...
def _handle_timeout(self, msg_id, start_time)
Handle a timed-out callback request. Parameters ---------- msg_id : uuid.UUID for message The name of the reply which was expected.
6.995345
6.979931
1.002208
# this may also result in reply_cb being None if no # reply_cb was passed to the request method if msg.mid is not None: _request, reply_cb, _inform_cb, user_data, timeout_handle = \ self._pop_async_request(msg.mid, None) else: request, _re...
def handle_reply(self, msg)
Handle a reply message related to the current request. Reply messages not related to the current request go up to the base class method. Parameters ---------- msg : Message object The reply message to dispatch.
3.26226
3.358852
0.971242
# Check that the answer is JSON-serializable try: serialized = json.dumps(value) except (ValueError, TypeError): raise serializers.ValidationError("Answer value must be JSON-serializable") # Check the length of the serialized representation if le...
def validate_answer(self, value)
Check that the answer is JSON-serializable and not too long.
4.351177
3.582193
1.214668
annotations = ScoreAnnotation.objects.filter(score_id=obj.id) return [ ScoreAnnotationSerializer(instance=annotation).data for annotation in annotations ]
def get_annotations(self, obj)
Inspect ScoreAnnotations to attach all relevant annotations.
4.403314
3.284679
1.340561
# By setting the "reset" flag, we ensure that the "highest" # score in the score summary will point to this score. # By setting points earned and points possible to 0, # we ensure that this score will be hidden from the user. return cls.objects.create( studen...
def create_reset_score(cls, student_item)
Create a "reset" score (a score with a null submission). Only scores created after the most recent "reset" score should be used to determine a student's effective score. Args: student_item (StudentItem): The student item model. Returns: Score: The newly created...
5.330619
5.333438
0.999472
score = kwargs['instance'] try: score_summary = ScoreSummary.objects.get( student_item=score.student_item ) score_summary.latest = score # A score with the "reset" flag set will always replace the current highest score ...
def update_score_summary(sender, **kwargs)
Listen for new Scores and update the relevant ScoreSummary. Args: sender: not used Kwargs: instance (Score): The score model whose save triggered this receiver.
4.317906
4.534445
0.952246
parser.add_argument( '--start', '-s', default=0, type=int, help=u"The Submission.id at which to begin updating rows. 0 by default." ) parser.add_argument( '--chunk', '-c', default=1000, type=int, ...
def add_arguments(self, parser)
Add arguments to the command parser. Uses argparse syntax. See documentation at https://docs.python.org/3/library/argparse.html.
3.010754
3.021558
0.996424
# Note that by taking last_id here, we're going to miss any submissions created *during* the command execution # But that's okay! All new entries have already been created using the new style, no acion needed there last_id = Submission._objects.all().aggregate(Max('id'))['id__max'] ...
def handle(self, *args, **options)
By default, we're going to do this in chunks. This way, if there ends up being an error, we can check log messages and continue from that point after fixing the issue.
5.690969
5.376636
1.058463
student_item_dict = dict( course_id=course_id, student_id=student_id, item_id=item_id, ) context = dict(**student_item_dict) try: submissions = get_submissions(student_item_dict) context["submissions"] = submissions except SubmissionRequestError: ...
def get_submissions_for_student_item(request, course_id, student_id, item_id)
Retrieve all submissions associated with the given student item. Developer utility for accessing all the submissions associated with a student item. The student item is specified by the unique combination of course, student, and item. Args: request (dict): The request. course_id (str):...
2.721406
2.798118
0.972585
student_item_model = _get_or_create_student_item(student_item_dict) if attempt_number is None: try: submissions = Submission.objects.filter( student_item=student_item_model)[:1] except DatabaseError: error_message = u"An error occurred while filtering...
def create_submission(student_item_dict, answer, submitted_at=None, attempt_number=None)
Creates a submission for assessment. Generic means by which to submit an answer for assessment. Args: student_item_dict (dict): The student_item this submission is associated with. This is used to determine which course, student, and location this submission belongs to. ...
2.227977
2.186312
1.019057
submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) try: submission = submission_qs.get(uuid=uuid) except Submission.DoesNotExist: try: hyphenated_value = six.text_type(UUID(uuid)) query = ...
def _get_submission_model(uuid, read_replica=False)
Helper to retrieve a given Submission object from the database. Helper is needed to centralize logic that fixes EDUCATOR-1090, because uuids are stored both with and without hyphens.
6.565886
6.435908
1.020196
if not isinstance(submission_uuid, six.string_types): if isinstance(submission_uuid, UUID): submission_uuid = six.text_type(submission_uuid) else: raise SubmissionRequestError( msg="submission_uuid ({!r}) must be serializable".format(submission_uuid) ...
def get_submission(submission_uuid, read_replica=False)
Retrieves a single submission by uuid. Args: submission_uuid (str): Identifier for the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Raises: SubmissionNotFoundError...
2.949316
2.972838
0.992088
# This may raise API exceptions submission = get_submission(uuid, read_replica=read_replica) # Retrieve the student item from the cache cache_key = "submissions.student_item.{}".format(submission['student_item']) try: cached_student_item = cache.get(cache_key) except Exception: ...
def get_submission_and_student(uuid, read_replica=False)
Retrieve a submission by its unique identifier, including the associated student item. Args: uuid (str): the unique identifier of the submission. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default databas...
3.046789
3.006885
1.013271
student_item_model = _get_or_create_student_item(student_item_dict) try: submission_models = Submission.objects.filter( student_item=student_item_model) except DatabaseError: error_message = ( u"Error getting submission request for student item {}" .f...
def get_submissions(student_item_dict, limit=None)
Retrieves the submissions for the specified student item, ordered by most recent submitted date. Returns the submissions relative to the specified student item. Exception thrown if no submission is found relative to this location. Args: student_item_dict (dict): The location of the problem thi...
2.686744
3.022248
0.888989
submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) # We cannot use SELECT DISTINCT ON because it's PostgreSQL only, so unfortunately # our results will contain every entry of each student, not just the most recent. # We sort by student_i...
def get_all_submissions(course_id, item_id, item_type, read_replica=True)
For the given item, get the most recent submission for every student who has submitted. This may return a very large result set! It is implemented as a generator for efficiency. Args: course_id, item_id, item_type (string): The values of the respective student_item fields to filter the sub...
4.256506
4.005878
1.062565
submission_qs = Submission.objects if read_replica: submission_qs = _use_read_replica(submission_qs) query = submission_qs.select_related('student_item__scoresummary__latest__submission').filter( student_item__course_id=course_id, student_item__item_type=item_type, ).itera...
def get_all_course_submission_information(course_id, item_type, read_replica=True)
For the given course, get all student items of the given item type, all the submissions for those itemes, and the latest scores for each item. If a submission was given a score that is not the latest score for the relevant student item, it will still be included but without score. Args: course_id (...
3.670062
3.251877
1.128598
if number_of_top_scores < 1 or number_of_top_scores > MAX_TOP_SUBMISSIONS: error_msg = ( u"Number of top scores must be a number between 1 and {}.".format(MAX_TOP_SUBMISSIONS) ) logger.exception(error_msg) raise SubmissionRequestError(msg=error_msg) # First chec...
def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True)
Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater than 0 score for a piece of assessment. A score is only calculated for a student item if it has completed the workfl...
2.578006
2.466932
1.045025
try: student_item_model = StudentItem.objects.get(**student_item) score = ScoreSummary.objects.get(student_item=student_item_model).latest except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist): return None # By convention, scores are hidden if "points possible" is set to...
def get_score(student_item)
Get the score for a particular student item Each student item should have a unique score. This function will return the score if it is available. A score is only calculated for a student item if it has completed the workflow for a particular assessment module. Args: student_item (dict): The di...
5.496511
5.77679
0.951482
try: score_summaries = ScoreSummary.objects.filter( student_item__course_id=course_id, student_item__student_id=student_id, ).select_related('latest', 'latest__submission', 'student_item') except DatabaseError: msg = u"Could not fetch scores for course {}, st...
def get_scores(course_id, student_id)
Return a dict mapping item_ids to scores. Scores are represented by serialized Score objects in JSON-like dict format. This method would be used by an LMS to find all the scores for a given student in a given course. Scores that are "hidden" (because they have points earned set to zero) are e...
3.565391
3.114516
1.144766
# Retrieve the student item try: student_item = StudentItem.objects.get( student_id=student_id, course_id=course_id, item_id=item_id ) except StudentItem.DoesNotExist: # If there is no student item, then there is no score to reset, # so we can return immediat...
def reset_score(student_id, course_id, item_id, clear_state=False, emit_signal=True)
Reset scores for a specific student on a specific problem. Note: this does *not* delete `Score` models from the database, since these are immutable. It simply creates a new score with the "reset" flag set to True. Args: student_id (unicode): The ID of the student for whom to reset scores. ...
2.61928
2.370069
1.105149
try: submission_model = _get_submission_model(submission_uuid) except Submission.DoesNotExist: raise SubmissionNotFoundError( u"No submission matching uuid {}".format(submission_uuid) ) except DatabaseError: error_msg = u"Could not retrieve submission {}.".fo...
def set_score(submission_uuid, points_earned, points_possible, annotation_creator=None, annotation_type=None, annotation_reason=None)
Set a score for a particular submission. Sets the score for a particular submission. This score is calculated externally to the API. Args: submission_uuid (str): UUID for the submission (must exist). points_earned (int): The earned points for this submission. points_possible (int):...
3.156602
3.038007
1.039037
logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], course_id=student_item["course_id"], ite...
def _log_submission(submission, student_item)
Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None
2.424949
2.413322
1.004818
logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) )
def _log_score(score)
Log the creation of a score. Args: score (Score): The score model. Returns: None
8.059968
8.989391
0.896609
try: try: return StudentItem.objects.get(**student_item_dict) except StudentItem.DoesNotExist: student_item_serializer = StudentItemSerializer( data=student_item_dict ) if not student_item_serializer.is_valid(): log...
def _get_or_create_student_item(student_item_dict)
Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): The dict containing the student_id, item_id, co...
2.531389
2.387372
1.060324
assert path.startswith('/'), "bogus path: %r" % path # Presuming utf-8 encoding here for requests. Not sure if that is # technically correct. if not isinstance(path, bytes): spath = path.encode('utf-8') else: spath = path qpath = urlquot...
def _request(self, path, method="GET", query=None, body=None, headers=None)
Make a Manta request ... @returns (res, content)
3.868767
3.992985
0.968891
log.debug('PutDirectory %r', mdir) headers = {"Content-Type": "application/json; type=directory"} res, content = self._request(mdir, "PUT", headers=headers) if res["status"] != "204": raise errors.MantaAPIError(res, content)
def put_directory(self, mdir)
PutDirectory https://apidocs.joyent.com/manta/api.html#PutDirectory @param mdir {str} A manta path, e.g. '/trent/stor/mydir'.
4.924203
4.045686
1.217149
res, dirents = self.list_directory2(mdir, limit=limit, marker=marker) return dirents
def list_directory(self, mdir, limit=None, marker=None)
ListDirectory https://apidocs.joyent.com/manta/api.html#ListDirectory @param mdir {str} A manta path, e.g. '/trent/stor/mydir'. @param limit {int} Limits the number of records to come back (default and max is 1000). @param marker {str} Key name at which to start the next lis...
5.081648
7.492919
0.678193
log.debug('ListDirectory %r', mdir) query = {} if limit: query["limit"] = limit if marker: query["marker"] = marker res, content = self._request(mdir, "GET", query=query) if res["status"] != "200": raise errors.MantaAPIError(...
def list_directory2(self, mdir, limit=None, marker=None)
A lower-level version of `list_directory` that returns the response object (which includes the headers). ... @returns (res, dirents) {2-tuple}
2.921141
2.911197
1.003416
log.debug('HEAD ListDirectory %r', mdir) res, content = self._request(mdir, "HEAD") if res["status"] != "200": raise errors.MantaAPIError(res, content) return res
def head_directory(self, mdir)
HEAD method on ListDirectory https://apidocs.joyent.com/manta/api.html#ListDirectory This is not strictly a documented Manta API call. However it is provided to allow access to the useful 'result-set-size' header. @param mdir {str} A manta path, e.g. '/trent/stor/mydir'. @retur...
7.723147
4.973283
1.552927
log.debug('PutObject %r', mpath) headers = {"Content-Type": content_type, } if durability_level: headers["x-durability-level"] = durability_level methods = [m for m in [content, path, file] if m is not None] if len(methods) != 1: raise errors.Man...
def put_object(self, mpath, content=None, path=None, file=None, content_length=None, content_type="application/octet-stream", durability_level=None)
PutObject https://apidocs.joyent.com/manta/api.html#PutObject Examples: client.put_object('/trent/stor/foo', 'foo\nbar\nbaz') client.put_object('/trent/stor/foo', path='path/to/foo.txt') client.put_object('/trent/stor/foo', file=open('path/to/foo.txt'), ...
2.469217
2.397985
1.029705
res, content = self.get_object2(mpath, path=path, accept=accept) try: if isinstance(content, bytes): return content.decode(sys.stdout.encoding) else: return content except UnicodeDecodeError: return content
def get_object(self, mpath, path=None, accept="*/*")
GetObject https://apidocs.joyent.com/manta/api.html#GetObject @param mpath {str} Required. A manta path, e.g. '/trent/stor/myobj'. @param path {str} Optional. If given, the retrieved object will be written to the given file path instead of the content being returned. ...
3.130329
3.839295
0.81534
log.debug('GetObject %r', mpath) headers = {"Accept": accept} res, content = self._request(mpath, "GET", headers=headers) if res["status"] not in ("200", "304"): raise errors.MantaAPIError(res, content) if len(content) != int(res["content-length"]): ...
def get_object2(self, mpath, path=None, accept="*/*")
A lower-level version of `get_object` that returns the response object (which includes the headers). ... @returns (res, content) {2-tuple} `content` is None if `path` was provided
2.339472
2.444808
0.956915
log.debug('DeleteObject %r', mpath) res, content = self._request(mpath, "DELETE") if res["status"] != "204": raise errors.MantaAPIError(res, content) return res
def delete_object(self, mpath)
DeleteObject https://apidocs.joyent.com/manta/api.html#DeleteObject @param mpath {str} Required. A manta path, e.g. '/trent/stor/myobj'.
5.563125
4.764325
1.167663
log.debug('PutLink %r -> %r', link_path, object_path) headers = { "Content-Type": "application/json; type=link", #"Content-Length": "0", #XXX Needed? "Location": object_path } res, content = self._request(link_path, "PUT", headers=headers) ...
def put_snaplink(self, link_path, object_path)
PutSnapLink https://mo.joyent.com/docs/muskie/master/api.html#putsnaplink @param link_path {str} Required. A manta path, e.g. '/trent/stor/mylink'. @param object_path {str} Required. The manta path to an existing target manta object.
4.222903
3.938437
1.072228
log.debug('CreateJob') path = '/%s/jobs' % self.account body = {"phases": phases} if name: body["name"] = name if input: body["input"] = input headers = {"Content-Type": "application/json"} res, content = self._request(path, ...
def create_job(self, phases, name=None, input=None)
CreateJob https://apidocs.joyent.com/manta/api.html#CreateJob
2.866444
2.55036
1.123937
log.debug("AddJobInputs %r", job_id) path = "/%s/jobs/%s/live/in" % (self.account, job_id) body = '\r\n'.join(keys) + '\r\n' headers = { "Content-Type": "text/plain", "Content-Length": str(len(body)) } res, content = self._request(path, "P...
def add_job_inputs(self, job_id, keys)
AddJobInputs https://apidocs.joyent.com/manta/api.html#AddJobInputs
3.254141
2.791007
1.165938
log.debug("EndJobInput %r", job_id) path = "/%s/jobs/%s/live/in/end" % (self.account, job_id) headers = { # "Content-Length": "0" #XXX needed? } res, content = self._request(path, "POST", headers=headers) if res["status"] != '202': raise...
def end_job_input(self, job_id)
EndJobInput https://mo.joyent.com/docs/muskie/master/api.html#EndJobInput
4.967298
4.783677
1.038385
log.debug('ListJobs') path = "/%s/jobs" % self.account query = {} if state: query["state"] = state if limit: query["limit"] = limit if marker: query["marker"] = marker res, content = self._request(path, "GET", query=q...
def list_jobs(self, state=None, limit=None, marker=None)
ListJobs https://apidocs.joyent.com/manta/api.html#ListJobs Limitation: at this time `list_jobs` doesn't support paging through more than the default response num results. (TODO) @param state {str} Only return jobs in the given state, e.g. "running", "done", etc. @p...
2.608857
2.567228
1.016216
log.debug("GetJob %r", job_id) path = "/%s/jobs/%s/live/status" % (self.account, job_id) res, content = self._request(path, "GET") if res.status != 200: raise errors.MantaAPIError(res, content) try: return json.loads(content) except ValueE...
def get_job(self, job_id)
GetJob https://apidocs.joyent.com/manta/api.html#GetJob
3.564914
3.035174
1.174534
log.debug("GetJobOutput %r", job_id) path = "/%s/jobs/%s/live/out" % (self.account, job_id) res, content = self._request(path, "GET") if res["status"] != "200": raise errors.MantaAPIError(res, content) keys = content.splitlines(False) return keys
def get_job_output(self, job_id)
GetJobOutput https://apidocs.joyent.com/manta/api.html#GetJobOutput
4.650548
3.730038
1.246783
log.debug("GetJobErrors %r", job_id) path = "/%s/jobs/%s/live/err" % (self.account, job_id) res, content = self._request(path, "GET") if res["status"] != "200": raise errors.MantaAPIError(res, content) return self._job_errors_from_content(content)
def get_job_errors(self, job_id)
GetJobErrors https://apidocs.joyent.com/manta/api.html#GetJobErrors
4.012764
3.30174
1.215348
dirents = self.ls(mtop) mdirs, mnondirs = [], [] for dirent in sorted(dirents.values(), key=itemgetter("name")): if dirent["type"] == "directory": mdirs.append(dirent) else: mnondirs.append(dirent) if topdown: ...
def walk(self, mtop, topdown=True)
`os.walk(path)` for a directory in Manta. A somewhat limited form in that some of the optional args to `os.walk` are not supported. Also, instead of dir *names* and file *names*, the dirents for those are returned. E.g.: >>> for dirpath, dirents, objents in client.walk('/trent/stor...
2.411814
2.380152
1.013303
assert limit is None and marker is None, "not yet implemented" dirents = {} if limit or marker: entries = self.list_directory(mdir, limit=limit, marker=marker) for entry in entries: dirents[entry["name"]] = entry else: marker...
def ls(self, mdir, limit=None, marker=None)
List a directory. Dev Notes: - If `limit` and `marker` are *not* specified. This handles paging through a directory with more entries than Manta will return in one request (1000). - This returns a dict mapping name to dirent as a convenience. Note that that makes t...
3.986222
4.113153
0.96914
assert mdir.startswith('/'), "%s: invalid manta path" % mdir parts = mdir.split('/') assert len(parts) > 3, "%s: cannot create top-level dirs" % mdir if not parents: self.put_directory(mdir) else: # Find the first non-existant dir: binary search. ...
def mkdir(self, mdir, parents=False)
Make a directory. Note that this will not error out if the directory already exists (that is how the PutDirectory Manta API behaves). @param mdir {str} A manta path, e.g. '/trent/stor/mydir'. @param parents {bool} Optional. Default false. Like 'mkdir -p', this will create p...
4.326394
3.948779
1.095628
parts = mpath.split('/') if len(parts) == 0: raise errors.MantaError("cannot stat empty manta path: %r" % mpath) elif len(parts) <= 3: raise errors.MantaError("cannot stat special manta path: %r" % mpath) mparent = udir...
def stat(self, mpath)
Return available dirent info for the given Manta path.
4.069718
3.557447
1.144
try: return self.stat(mpath)["type"] except errors.MantaResourceNotFoundError: return None except errors.MantaAPIError: _, ex, _ = sys.exc_info() if ex.code in ('ResourceNotFound', 'DirectoryDoesNotExist'): return None ...
def type(self, mpath)
Return the manta type for the given manta path. @param mpath {str} The manta path for which to get the type. @returns {str|None} The manta type, e.g. "object" or "directory", or None if the path doesn't exist.
5.439245
4.166792
1.305379
try: return RawMantaClient.get_job(self, job_id) except errors.MantaAPIError as ex: if ex.res.status != 404: raise # Job was archived, try to retrieve the archived data. mpath = "/%s/jobs/%s/job.json" % (self.account, job_id) ...
def get_job(self, job_id)
GetJob https://apidocs.joyent.com/manta/api.html#GetJob with the added sugar that it will retrieve the archived job if it has been archived, per: https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival
4.057437
3.501682
1.158711
try: return RawMantaClient.get_job_input(self, job_id) except errors.MantaAPIError as ex: if ex.res.status != 404: raise # Job was archived, try to retrieve the archived data. mpath = "/%s/jobs/%s/in.txt" % (self.account, job_id) ...
def get_job_input(self, job_id)
GetJobInput https://apidocs.joyent.com/manta/api.html#GetJobInput with the added sugar that it will retrieve the archived job if it has been archived, per: https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival
5.174983
4.266703
1.212876
try: return RawMantaClient.get_job_errors(self, job_id) except errors.MantaAPIError as ex: if ex.res.status != 404: raise # Job was archived, try to retrieve the archived data. mpath = "/%s/jobs/%s/err.txt" % (self.account, job_id)...
def get_job_errors(self, job_id)
GetJobErrors https://apidocs.joyent.com/manta/api.html#GetJobErrors with the added sugar that it will retrieve the archived job if it has been archived, per: https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival
4.619711
3.915706
1.17979
def decorate(f): if not hasattr(f, "aliases"): f.aliases = [] f.aliases += aliases return f return decorate
def alias(*aliases)
Decorator to add aliases for Cmdln.do_* command handlers. Example: class MyShell(cmdln.Cmdln): @cmdln.alias("!", "sh") def do_shell(self, argv): #...implement 'shell' command
3.233848
3.599401
0.898441
#XXX Is there a possible optimization for many options to not have a # large stack depth here? def decorate(f): if not hasattr(f, "optparser"): f.optparser = SubCmdOptionParser() f.optparser.add_option(*args, **kwargs) return f return decorate
def option(*args, **kwargs)
Decorator to add an option to the optparser argument of a Cmdln subcommand. Example: class MyShell(cmdln.Cmdln): @cmdln.option("-f", "--force", help="force removal") def do_remove(self, subcmd, opts, *args): #...
7.08042
6.788545
1.042995
if not inst.__class__.name: raise ValueError("cannot generate man page content: `name` is not " "set on class %r" % inst.__class__) data = { "name": inst.name, "ucname": inst.name.upper(), "date": datetime.date.today().strftime("%b %Y"), "cmd...
def man_sections_from_cmdln(inst, summary=None, description=None, author=None)
Return man page sections appropriate for the given Cmdln instance. Join these sections for man page content. The man page sections generated are: NAME SYNOPSIS DESCRIPTION (if `description` is given) OPTIONS COMMANDS HELP TOPICS (if any) @param inst {Cmdln}...
3.809133
3.623455
1.051243
lines = [] WIDTH = 78 - indent_width SPACING = 2 NAME_WIDTH_LOWER_BOUND = 13 NAME_WIDTH_UPPER_BOUND = 30 NAME_WIDTH = max([len(s) for s, d in linedata]) if NAME_WIDTH < NAME_WIDTH_LOWER_BOUND: NAME_WIDTH = NAME_WIDTH_LOWER_BOUND elif NAME_WIDTH > NAME_WIDTH_UPPER_BOUND: ...
def _format_linedata(linedata, indent, indent_width)
Format specific linedata into a pleasant layout. "linedata" is a list of 2-tuples of the form: (<item-display-string>, <item-docstring>) "indent" is a string to use for one level of indentation "indent_width" is a number of columns by which the formatted data will be ind...
2.500284
2.437969
1.02556
r import re if doc is None: return "" assert length > 3, "length <= 3 is absurdly short for a doc summary" doclines = doc.strip().splitlines(0) if not doclines: return "" summlines = [] for i, line in enumerate(doclines): stripped = line.strip() if not st...
def _summarize_doc(doc, length=60)
r"""Parse out a short one line summary from the given doclines. "doc" is the doc string to summarize. "length" is the max length for the summary >>> _summarize_doc("this function does this") 'this function does this' >>> _summarize_doc("this function does this", 10) 'this fu...' >>...
3.305906
3.152346
1.048713
r line = line.strip() argv = [] state = "default" arg = None # the current argument being parsed i = -1 WHITESPACE = '\t\n\x0b\x0c\r ' # don't use string.whitespace (bug 81316) while 1: i += 1 if i >= len(line): break ch = line[i] if ch == "\\" and i + ...
def line2argv(line)
r"""Parse the given line into an argument vector. "line" is the line of input to parse. This may get niggly when dealing with quoting and escaping. The current state of this parsing may not be completely thorough/correct in this respect. >>> from cmdln import line2argv >>> line2argv("foo"...
2.64629
2.617883
1.010851
r escapedArgs = [] for arg in argv: if ' ' in arg and '"' not in arg: arg = '"' + arg + '"' elif ' ' in arg and "'" not in arg: arg = "'" + arg + "'" elif ' ' in arg: arg = arg.replace('"', r'\"') arg = '"' + arg + '"' escapedAr...
def argv2line(argv)
r"""Put together the given argument vector into a command line. "argv" is the argument vector to process. >>> from cmdln import argv2line >>> argv2line(['foo']) 'foo' >>> argv2line(['foo', 'bar']) 'foo bar' >>> argv2line(['foo', 'bar baz']) 'foo "bar baz"' >>> argv2line(['foo"b...
2.58137
2.916585
0.885066
# Figure out how much the marker is indented. INDENT_CHARS = tuple(' \t') start = s.index(marker) i = start while i > 0: if s[i - 1] not in INDENT_CHARS: break i -= 1 indent = s[i:start] indent_width = 0 for ch in indent: if ch == ' ': ...
def _get_indent(marker, s, tab_width=8)
_get_indent(marker, s, tab_width=8) -> (<indentation-of-'marker'>, <indentation-width>)
2.309063
2.229156
1.035847
suffix = '' start = s.index(marker) + len(marker) i = start while i < len(s): if s[i] in ' \t': suffix += s[i] elif s[i] in '\r\n': suffix += s[i] if s[i] == '\r' and i + 1 < len(s) and s[i + 1] == '\n': suffix += s[i + 1] ...
def _get_trailing_whitespace(marker, s)
Return the whitespace content trailing the given 'marker' in string 's', up to and including a newline.
1.871858
1.869483
1.00127
version = (self.version is not None and "%s %s" % (self._name_str, self.version) or None) return CmdlnOptionParser(self, version=version)
def get_optparser(self)
Hook for subclasses to set the option parser for the top-level command/shell. This option parser is used retrieved and used by `.main()' to handle top-level options. The default implements a single '-h|--help' option. Sub-classes can return None to have no options at the top-le...
6.841435
5.63682
1.213705
if argv is None: import sys argv = sys.argv else: argv = argv[:] # don't modify caller's list self.optparser = self.get_optparser() if self.optparser: # i.e. optparser=None means don't process for opts try: self....
def main(self, argv=None, loop=LOOP_NEVER)
A possible mainline handler for a script, like so: import cmdln class MyCmd(cmdln.Cmdln): name = "mycmd" ... if __name__ == "__main__": MyCmd().main() By default this will use sys.argv to issue a single command to 'My...
3.0986
2.920784
1.06088
assert isinstance(argv, (list, tuple)), \ "'argv' is not a sequence: %r" % argv retval = None try: argv = self.precmd(argv) retval = self.onecmd(argv) self.postcmd(argv) except: if not self.cmdexc(argv): ...
def cmd(self, argv)
Run one command and exit. "argv" is the arglist for the command to run. argv[0] is the command to run. If argv is an empty list then the 'emptyline' handler is run. Returns the return value from the command handler.
3.129758
3.355546
0.932712
self.cmdlooping = True self.preloop() if self.use_rawinput and self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) if sys.platform == "darwi...
def cmdloop(self, intro=None)
Repeatedly issue a prompt, accept input, parse into an argv, and dispatch (via .precmd(), .onecmd() and .postcmd()), passing them the argv. In other words, start a shell. "intro" (optional) is a introductory message to print when starting the command loop. This overrides the...
2.066205
2.01706
1.024365
import sys type, exc, traceback = sys.exc_info() if isinstance(exc, CmdlnUserError): msg = "%s %s: %s\nTry '%s help %s' for info.\n"\ % (self.name, argv[0], exc, self.name, argv[0]) self.stderr.write(self._str(msg)) self.stderr.flush...
def cmdexc(self, argv)
Called if an exception is raised in any of precmd(), onecmd(), or postcmd(). If True is returned, the exception is deemed to have been dealt with. Otherwise, the exception is re-raised. The default implementation handles CmdlnUserError's, which typically correspond to user error in call...
4.570648
3.467302
1.318215
errmsg = self._str(self.unknowncmd % (argv[0], )) if self.cmdlooping: self.stderr.write(errmsg + "\n") else: self.stderr.write("%s: %s\nTry '%s help' for info.\n" % (self._name_str, errmsg, self._name_str)) self.stderr.flush(...
def default(self, argv)
Hook called to handle a command for which there is no handler. "argv" is the command and arguments to run. The default implementation writes an error message to stderr and returns an error exit status. Returns a numeric command exit status.
4.684796
4.866671
0.962629
if known: msg = self._str(self.nohelp % (cmd, )) if self.cmdlooping: self.stderr.write(msg + '\n') else: self.stderr.write("%s: %s\n" % (self.name, msg)) else: msg = self.unknowncmd % (cmd, ) if self.cmd...
def helpdefault(self, cmd, known)
Hook called to handle help on a command for which there is no help handler. "cmd" is the command name on which help was requested. "known" is a boolean indicating if this command is known (i.e. if there is a handler for it). Returns a return code.
2.686472
2.829505
0.94945
if len(argv) > 1: # asking for help on a particular command doc = None cmdname = self._get_canonical_cmd_name(argv[1]) or argv[1] if not cmdname: return self.helpdefault(argv[1], False) else: helpfunc = getattr(self, "help...
def do_help(self, argv)
${cmd_name}: give detailed help on a specific sub-command Usage: ${name} help [COMMAND]
4.823689
5.070009
0.951416
if indent is None: indent = self.helpindent lines = help.splitlines(0) _dedentlines(lines, skip_first_line=True) lines = [(indent + line).rstrip() for line in lines] return '\n'.join(lines)
def _help_reindent(self, help, indent=None)
Hook to re-indent help strings before writing to stdout. "help" is the help content to re-indent "indent" is a string with which to indent each line of the help content after normalizing. If unspecified or None then the default is use: the 'self.helpindent' class...
3.739919
3.311198
1.129476
preprocessors = { "${name}": self._help_preprocess_name, "${option_list}": self._help_preprocess_option_list, "${command_list}": self._help_preprocess_command_list, "${help_list}": self._help_preprocess_help_list, "${cmd_name}": self._help_pre...
def _help_preprocess(self, help, cmdname)
Hook to preprocess a help string before writing to stdout. "help" is the help string to process. "cmdname" is the canonical sub-command name for which help is being given, or None if the help is not specific to a command. By default the following templat...
2.039444
1.647648
1.237792
# Determine the additional help topics, if any. help_names = {} token2cmdname = self._get_canonical_map() for attrname, attr in self._gen_names_and_attrs(): if not attrname.startswith("help_"): continue help_name = attrname[5:] if help_name no...
def _get_help_names(self)
Return a mapping of help topic name to `.help_*()` method.
5.14517
4.348584
1.183183
cacheattr = "_token2canonical" if not hasattr(self, cacheattr): # Get the list of commands and their aliases, if any. token2canonical = {} cmd2funcname = {} # use a dict to strip duplicates for attr in self.get_names(): if attr.st...
def _get_canonical_map(self)
Return a mapping of available command names and aliases to their canonical command name.
3.060229
2.84989
1.073806
self.cmdln = cmdln self.subcmd = subcmd
def set_cmdln_info(self, cmdln, subcmd)
Called by Cmdln to pass relevant info about itself needed for print_help().
2.916499
2.830394
1.030422
co_argcount = handler.__func__.__code__.co_argcount if co_argcount == 2: # handler ::= do_foo(self, argv) return handler(argv) elif co_argcount >= 3: # handler ::= do_foo(self, subcmd, opts, ...) try: optparser = handler.optparser ex...
def _dispatch_cmd(self, handler, argv)
Introspect sub-command handler signature to determine how to dispatch the command. The raw handler provided by the base 'RawCmdln' class is still supported: def do_foo(self, argv): # 'argv' is the vector of command line args, argv[0] is # the command name its...
6.726731
6.12161
1.09885
registered = None if sys.platform.startswith('win'): if os.path.splitext(exeName)[1].lower() != '.exe': exeName += '.exe' import _winreg try: key = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" +\ exeName value = _w...
def _getRegisteredExecutable(exeName)
Windows allow application paths to be registered in the registry.
2.690922
2.669794
1.007914
matches = [] if path is None: usingGivenPath = 0 path = os.environ.get("PATH", "").split(os.pathsep) if sys.platform.startswith("win"): path.insert(0, os.curdir) # implied by Windows shell else: usingGivenPath = 1 # Windows has the concept of a list of ...
def whichgen(command, path=None, verbose=0, exts=None)
Return a generator of full paths to the given command. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to use the PATH environment variable. "verbose", if true, will cause a 2-tuple to be returned for each matc...
3.278504
3.008708
1.089672
return list( whichgen(command, path, verbose, exts) )
def whichall(command, path=None, verbose=0, exts=None)
Return a list of full paths to all matches of the given command on the path. "command" is a the name of the executable to search for. "path" is an optional alternate path list to search. The default it to use the PATH environment variable. "verbose", if true, will cause a 2-tuple to be return...
8.530068
13.161571
0.648104
_globals = {} _locals = {} exec( compile( open(TOP + "/manta/version.py").read(), TOP + "/manta/version.py", 'exec'), _globals, _locals) return _locals["__version__"]
def get_version()
Get the python-manta version without having to import the manta package, which requires deps to already be installed.
3.887907
3.431093
1.133139
data = data.strip() # Let's accept either: # - just the base64 encoded data part, e.g. # 'AAAAB3NzaC1yc2EAAAABIwAA...2l24uq9Lfw==' # - the full ssh pub key file content, e.g.: # 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAA...2l24uq9Lfw== my comment' if (re.search(r'^ssh-(?:rsa|dss) ', data) o...
def fingerprint_from_ssh_pub_key(data)
Calculate the fingerprint of SSH public key data. >>> data = "ssh-rsa AAAAB3NzaC1y...4IEAA1Z4wIWCuk8F9Tzw== my key comment" >>> fingerprint_from_ssh_pub_key(data) '54:c7:4c:93:cf:ff:e3:32:68:bc:89:6e:5e:22:b5:9c' Adapted from <http://stackoverflow.com/questions/6682815/> and imgapi.js#fingerprintF...
3.3461
3.15282
1.061304
fp_plain = hashlib.md5(key).hexdigest() return ':'.join(a + b for a, b in zip(fp_plain[::2], fp_plain[1::2]))
def fingerprint_from_raw_ssh_pub_key(key)
Encode a raw SSH key (string of bytes, as from `str(paramiko.AgentKey)`) to a fingerprint in the typical '54:c7:4c:93:cf:ff:e3:32:68:bc:89:6e:5e:22:b5:9c' form.
2.66899
2.617873
1.019526
digest = hashlib.sha256(raw_key).digest() h = base64.b64encode(digest).decode('utf-8') h = h.rstrip().rstrip('=') # drop newline and possible base64 padding return 'SHA256:' + h
def sha256_fingerprint_from_raw_ssh_pub_key(raw_key)
Encode a raw SSH key (string of bytes, as from `str(paramiko.AgentKey)`) to a fingerprint in the SHA256 form: SHA256:j2WoSeOWhFy69BQ39fuafFAySp9qCZTSCEyT2vRKcL+s
3.648773
3.535101
1.032155