_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q21600
getUsers
train
def getUsers(context, roles, allow_empty=True): """ Present a DisplayList containing users in the specified list of roles """ mtool = getToolByName(context, 'portal_membership') pairs = allow_empty and [['', '']] or [] users = mtool.searchForMembers(roles=roles) for user in users: uid = user.getId()
python
{ "resource": "" }
q21601
formatDateQuery
train
def formatDateQuery(context, date_id): """ Obtain and reformat the from and to dates into a date query construct """ from_date = context.REQUEST.get('%s_fromdate' % date_id, None) if from_date: from_date = from_date + ' 00:00' to_date = context.REQUEST.get('%s_todate' % date_id, None) if to_date: to_date = to_date + ' 23:59' date_query = {} if
python
{ "resource": "" }
q21602
formatDateParms
train
def formatDateParms(context, date_id): """ Obtain and reformat the from and to dates into a printable date parameter construct """ from_date = context.REQUEST.get('%s_fromdate' % date_id, None) to_date = context.REQUEST.get('%s_todate' % date_id, None) date_parms = {} if from_date and to_date: date_parms =
python
{ "resource": "" }
q21603
encode_header
train
def encode_header(header, charset='utf-8'): """ Will encode in quoted-printable encoding only if header contains non latin characters """ # Return empty headers unchanged if not header: return header # return plain header if it does not contain non-ascii characters if hqre.match(header): return header quoted = '' # max_encoded = 76 - len(charset) - 7 for c in header: # Space may be represented as _ instead of =20 for readability if c == ' ':
python
{ "resource": "" }
q21604
sortable_title
train
def sortable_title(portal, title): """Convert title to sortable title """ if not title: return '' def_charset = portal.plone_utils.getSiteEncoding() sortabletitle = str(title.lower().strip()) # Replace numbers with zero filled numbers sortabletitle = num_sort_regex.sub(zero_fill, sortabletitle)
python
{ "resource": "" }
q21605
changeWorkflowState
train
def changeWorkflowState(content, wf_id, state_id, **kw): """Change the workflow state of an object @param content: Content obj which state will be changed @param state_id: name of the state to put on content @param kw: change the values of same name of the state mapping @return: True if succeed. Otherwise, False """ portal_workflow = api.get_tool("portal_workflow") workflow = portal_workflow.getWorkflowById(wf_id) if not workflow: logger.error("%s: Cannot find workflow id %s" % (content, wf_id)) return False wf_state = { 'action': kw.get("action", None), 'actor': kw.get("actor", api.get_current_user().id), 'comments':
python
{ "resource": "" }
q21606
senaite_url_fetcher
train
def senaite_url_fetcher(url): """Uses plone.subrequest to fetch an internal image resource. If the URL points to an external resource, the URL is handed to weasyprint.default_url_fetcher. Please see these links for details: - https://github.com/plone/plone.subrequest - https://pypi.python.org/pypi/plone.subrequest - https://github.com/senaite/senaite.core/issues/538 :returns: A dict with the following keys: * One of ``string`` (a byte string) or ``file_obj`` (a file-like object) * Optionally: ``mime_type``, a MIME type extracted e.g. from a *Content-Type* header. If not provided, the type is guessed from the file extension in the URL. * Optionally: ``encoding``, a character encoding extracted e.g. from a *charset* parameter in a *Content-Type* header * Optionally: ``redirected_url``, the actual URL of the resource if there were e.g. HTTP redirects. * Optionally: ``filename``, the filename of the resource. Usually derived from the *filename* parameter in a *Content-Disposition* header If a ``file_obj`` key is given, it is the caller’s responsibility to call ``file_obj.close()``. """ logger.info("Fetching URL '{}' for WeasyPrint".format(url)) # get the pyhsical path from the URL request = api.get_request() host = request.get_header("HOST") path = "/".join(request.physicalPathFromURL(url)) # fetch the object by sub-request portal = api.get_portal() context = portal.restrictedTraverse(path, None) # We double check here to avoid an edge case, where we have the same path
python
{ "resource": "" }
q21607
dicts_to_dict
train
def dicts_to_dict(dictionaries, key_subfieldname): """Convert a list of dictionaries into a dictionary of dictionaries. key_subfieldname must exist in each Record's subfields and have a value, which will be used as the key for the new
python
{ "resource": "" }
q21608
drop_trailing_zeros_decimal
train
def drop_trailing_zeros_decimal(num): """ Drops the trailinz zeros from decimal value. Returns a string """
python
{ "resource": "" }
q21609
checkPermissions
train
def checkPermissions(permissions=[], obj=None): """ Checks if a user has permissions for a given object. Args: permissions: The permissions the current user must be compliant with obj: The object for which the permissions apply Returns: 1 if the user complies with all the permissions for the given object.
python
{ "resource": "" }
q21610
PrintView.get_analysis_data_by_title
train
def get_analysis_data_by_title(self, ar_data, title): """A template helper to pick an Analysis identified by the name of the current Analysis Service. ar_data is the dictionary structure which is returned by _ws_data """ analyses = ar_data.get("analyses", [])
python
{ "resource": "" }
q21611
PrintView.getWorksheet
train
def getWorksheet(self): """ Returns the current worksheet from the list. Returns None when the iterator reaches the end of
python
{ "resource": "" }
q21612
PrintView._analyses_data
train
def _analyses_data(self, ws): """ Returns a list of dicts. Each dict represents an analysis assigned to the worksheet """ ans = ws.getAnalyses() layout = ws.getLayout() pos_count = 0 prev_pos = 0 ars = {} # mapping of analysis UID -> position in layout uid_to_pos_mapping = dict( map(lambda row: (row["analysis_uid"], row["position"]), layout)) for an in ans: # Build the analysis-specific dict if an.portal_type == "DuplicateAnalysis": andict = self._analysis_data(an.getAnalysis()) andict['id'] = an.getReferenceAnalysesGroupID() andict['obj'] = an andict['type'] = "DuplicateAnalysis" andict['reftype'] = 'd' else: andict = self._analysis_data(an) # Analysis position pos = uid_to_pos_mapping.get(an.UID(), 0) # compensate for possible bad data (dbw#104) if isinstance(pos, (list, tuple)) and pos[0] == 'new': pos = prev_pos pos = int(pos) prev_pos = pos # This will allow to sort automatically all the analyses, # also if they have the same initial position. andict['tmp_position'] = (pos * 100) + pos_count andict['position'] = pos pos_count += 1 # Look for the analysis request, client and sample info and # group the analyses per Analysis Request reqid = andict['request_id'] if an.portal_type in ("ReferenceAnalysis", "DuplicateAnalysis"): reqid = an.getReferenceAnalysesGroupID() if reqid not in ars: arobj = an.aq_parent if an.portal_type == "DuplicateAnalysis": arobj = an.getAnalysis().aq_parent ar = self._ar_data(arobj) ar['client'] = self._client_data(arobj.aq_parent) ar["sample"] = dict() if IReferenceSample.providedBy(an):
python
{ "resource": "" }
q21613
PrintView._analysis_data
train
def _analysis_data(self, analysis): """ Returns a dict that represents the analysis """ decimalmark = analysis.aq_parent.aq_parent.getDecimalMark() keyword = analysis.getKeyword() andict = { 'obj': analysis, 'id': analysis.id, 'title': analysis.Title(), 'keyword': keyword, 'scientific_name': analysis.getScientificName(), 'accredited': analysis.getAccredited(), 'point_of_capture': to_utf8(POINTS_OF_CAPTURE.getValue(analysis.getPointOfCapture())), 'category': to_utf8(analysis.getCategoryTitle()), 'result': analysis.getResult(), 'unit': to_utf8(analysis.getUnit()), 'formatted_unit': format_supsub(to_utf8(analysis.getUnit())), 'capture_date': analysis.getResultCaptureDate(), 'request_id': analysis.aq_parent.getId(), 'formatted_result': '', 'uncertainty': analysis.getUncertainty(), 'formatted_uncertainty': '', 'retested': analysis.isRetest(), 'remarks': to_utf8(analysis.getRemarks()), 'outofrange': False, 'type': analysis.portal_type, 'reftype': analysis.getReferenceType() if hasattr( analysis, 'getReferenceType') else None, 'worksheet': None, 'specs': {}, 'formatted_specs': '',
python
{ "resource": "" }
q21614
PrintView._ar_data
train
def _ar_data(self, ar): """ Returns a dict that represents the analysis request """ if not ar: return {} if ar.portal_type == "AnalysisRequest": return {'obj': ar, 'id': ar.getId(), 'date_received': self.ulocalized_time( ar.getDateReceived(), long_format=0), 'date_sampled': self.ulocalized_time( ar.getDateSampled(), long_format=True),
python
{ "resource": "" }
q21615
AnalysisService._getAvailableInstrumentsDisplayList
train
def _getAvailableInstrumentsDisplayList(self): """ Returns a DisplayList with the available Instruments registered in Bika-Setup. Only active Instruments are fetched. Used to fill the Instruments MultiSelectionWidget """ bsc = getToolByName(self, 'bika_setup_catalog') items = [(i.UID, i.Title)
python
{ "resource": "" }
q21616
AnalysisService.after_deactivate_transition_event
train
def after_deactivate_transition_event(self): """Method triggered after a 'deactivate' transition for the current AnalysisService is performed. Removes this service from the Analysis Profiles or Analysis Request Templates where is assigned. This function is called automatically by bika.lims.workflow.AfterTransitionEventHandler """ # Remove the service from profiles to which is assigned profiles = self.getBackReferences('AnalysisProfileAnalysisService') for profile in profiles: profile.remove_service(self) #
python
{ "resource": "" }
q21617
AnalysisRequestAnalysesView.get_results_range
train
def get_results_range(self): """Get the results Range from the AR """ spec = self.context.getResultsRange() if spec:
python
{ "resource": "" }
q21618
AnalysisRequestAnalysesView.folderitems
train
def folderitems(self): """XXX refactor if possible to non-classic mode """
python
{ "resource": "" }
q21619
getAuthenticatedMember
train
def getAuthenticatedMember(self): ''' Returns the currently authenticated member object or the Anonymous User. Never returns None. This caches the value in the reqeust... ''' if not "_c_authenticatedUser" in self.REQUEST: u = _getAuthenticatedUser(self) if u is None:
python
{ "resource": "" }
q21620
FolderView.before_render
train
def before_render(self): """Before render hook of the listing base view """ super(FolderView, self).before_render() # disable the editable border of the Add-, Display- and Workflow menu self.request.set("disable_border", 1) # the current selected WF state self.selected_state = self.get_selected_state() self.allow_edit = self.is_edit_allowed() self.can_manage = self.is_manage_allowed() # Check if analysts can be assigned if self.is_analyst_assignment_allowed(): self.can_reassign = True self.allow_analyst_reassignment() if not self.can_manage: # The current has no prvileges to manage WS. # Remove the add button self.context_actions = {} if self.context.bika_setup.getRestrictWorksheetUsersAccess(): # Display only the worksheets assigned to the current user unless # the user belongs to a privileged role allowed = ["Manager", "LabManager", "RegulatoryInspector"]
python
{ "resource": "" }
q21621
FolderView.is_analyst_assignment_allowed
train
def is_analyst_assignment_allowed(self): """Check if the analyst can be assigned """ if not self.allow_edit: return False if not self.can_manage:
python
{ "resource": "" }
q21622
FolderView.allow_analyst_reassignment
train
def allow_analyst_reassignment(self): """Allow the Analyst reassignment """ reassing_analyst_transition = { "id": "reassign", "title": _("Reassign")} for rs in self.review_states: if rs["id"] not in ["default", "mine", "open", "all"]:
python
{ "resource": "" }
q21623
FolderView.get_selected_state
train
def get_selected_state(self): """Returns the current selected state
python
{ "resource": "" }
q21624
FolderView.getTemplateInstruments
train
def getTemplateInstruments(self): """Returns worksheet templates as JSON """ items = dict() templates = self._get_worksheet_templates_brains() for template in templates: template_obj = api.get_object(template) uid_template = api.get_uid(template_obj) instrument = template_obj.getInstrument()
python
{ "resource": "" }
q21625
ObjectInitializedEventHandler
train
def ObjectInitializedEventHandler(analysis, event): """Actions to be done when an analysis is added in an Analysis Request """ # Initialize the analysis if it was e.g. added by Manage Analysis wf.doActionFor(analysis, "initialize") # Try to transition the analysis_request to "sample_received". There are # some cases that can end up with an inconsistent state between the AR # and the analyses it contains: retraction of an analysis when the state
python
{ "resource": "" }
q21626
ObjectRemovedEventHandler
train
def ObjectRemovedEventHandler(analysis, event): """Actions to be done when an analysis is removed from an Analysis Request """ # If all the remaining analyses have been submitted (or verified), try to # promote the transition
python
{ "resource": "" }
q21627
fixPath
train
def fixPath(path): """ Ensures paths are correct for linux and windows """
python
{ "resource": "" }
q21628
getPlatformInfo
train
def getPlatformInfo(): """Identify platform.""" if "linux" in sys.platform: platform = "linux" elif "darwin" in sys.platform: platform = "darwin" # win32 elif sys.platform.startswith("win"):
python
{ "resource": "" }
q21629
main
train
def main(): """Measure capnp serialization performance of a network containing a simple python region that in-turn contains a Random instance. """ engine.Network.registerPyRegion(__name__,
python
{ "resource": "" }
q21630
checkImportBindingsExtensions
train
def checkImportBindingsExtensions(): """Check that nupic.bindings extension libraries can be imported. Throws ImportError on failure.
python
{ "resource": "" }
q21631
checkMain
train
def checkMain(): """ This script performs two checks. First it tries to import nupic.bindings to check that it is correctly installed. Then it tries to import the C extensions under nupic.bindings. Appropriate user-friendly status messages are printed depend on the outcome. """ try: checkImportBindingsInstalled() except ImportError as e: print ("Could not import nupic.bindings. It must be installed before use. " "Error message:")
python
{ "resource": "" }
q21632
PyRegion.getParameterArrayCount
train
def getParameterArrayCount(self, name, index): """Default implementation that return the length of the attribute. This default implementation goes hand in hand with :meth:`~nupic.bindings.regions.PyRegion.PyRegion.getParameterArray`. If you override one of them in your subclass, you should probably override both of them. The implementation prevents accessing parameters names that start with ``_``. It may be better to enforce this convention at the node spec level.
python
{ "resource": "" }
q21633
PyRegion.executeMethod
train
def executeMethod(self, methodName, args): """Executes a method named ``methodName`` with the specified arguments. This method is called when the user executes a command as defined in the node spec. It provides a perfectly reasonble implementation of the command mechanism. As a sub-class developer you just need to implement a method for each command in the node spec.
python
{ "resource": "" }
q21634
PyRegion.setSparseOutput
train
def setSparseOutput(outputs, name, value): """ Set region sparse output value. The region output memory is owned by the c++ caller and cannot be changed directly from python. Use this method to update the sparse output fields in the "outputs" array so it can be resized from the c++ code. :param outputs: (dict) of numpy arrays. This is the original outputs dict owned by the C++ caller, passed to region via the compute method to be updated. :param name: (string) name of an existing output to modify :param value: (list) list of UInt32 indices of all the nonzero entries representing the sparse array to be set """ # The region output memory is owned by the c++ and cannot be changed from # python. We
python
{ "resource": "" }
q21635
main
train
def main(): """Measure capnp serialization performance of Random """ r = Random(42) # Measure serialization startSerializationTime = time.time() for i in xrange(_SERIALIZATION_LOOPS): # NOTE pycapnp's builder.from_dict (used in nupic.bindings) leaks # memory if called on the same builder more than once, so we construct a # fresh builder here builderProto = RandomProto.new_message() r.write(builderProto) elapsedSerializationTime = time.time() - startSerializationTime builderBytes = builderProto.to_bytes() # Measure deserialization startDeserializationTime = time.time() deserializationCount = 0 while deserializationCount < _DESERIALIZATION_LOOPS: # NOTE: periodicaly create a new reader to avoid "Exceeded message traversal # limit" error readerProto = RandomProto.from_bytes( builderBytes, traversal_limit_in_words=_TRAVERSAL_LIMIT_IN_WORDS, nesting_limit=_NESTING_LIMIT) numReads = min(_DESERIALIZATION_LOOPS - deserializationCount,
python
{ "resource": "" }
q21636
generate_twofactor_code_for_time
train
def generate_twofactor_code_for_time(shared_secret, timestamp): """Generate Steam 2FA code for timestamp :param shared_secret: authenticator shared secret :type shared_secret: bytes :param timestamp: timestamp to use, if left out uses current time :type timestamp: int :return: steam two factor code
python
{ "resource": "" }
q21637
generate_confirmation_key
train
def generate_confirmation_key(identity_secret, tag, timestamp): """Generate confirmation key for trades. Can only be used once. :param identity_secret: authenticator identity secret :type identity_secret: bytes :param tag: tag identifies what the request, see list below :type tag: str :param timestamp: timestamp to use for
python
{ "resource": "" }
q21638
get_time_offset
train
def get_time_offset(): """Get time offset from steam server time via WebAPI :return: time offset (``None`` when Steam WebAPI fails to respond) :rtype: :class:`int`, :class:`None` """ try:
python
{ "resource": "" }
q21639
generate_device_id
train
def generate_device_id(steamid): """Generate Android device id :param steamid: Steam ID :type steamid: :class:`.SteamID`, :class:`int` :return: android device id :rtype: str
python
{ "resource": "" }
q21640
extract_secrets_from_android_rooted
train
def extract_secrets_from_android_rooted(adb_path='adb'): """Extract Steam Authenticator secrets from a rooted Android device Prerequisite for this to work: - rooted android device - `adb binary <https://developer.android.com/studio/command-line/adb.html>`_ - device in debug mode, connected and paired .. note:: If you know how to make this work, without requiring the device to be rooted, please open a issue on github. Thanks :param adb_path: path to adb binary :type adb_path: str :raises: When there is any problem :return: all secrets from the device, steamid as key :rtype: dict """ data = subprocess.check_output([ adb_path, 'shell', 'su', '-c', "'cat
python
{ "resource": "" }
q21641
SteamAuthenticator.finalize
train
def finalize(self, activation_code): """Finalize authenticator with received SMS code :param activation_code: SMS code :type activation_code: str :raises: :class:`SteamAuthenticatorError` """ resp = self._send_request('FinalizeAddAuthenticator', { 'steamid': self.backend.steam_id, 'authenticator_time': int(time()), 'authenticator_code': self.get_code(), 'activation_code': activation_code, }) if resp['status'] != EResult.TwoFactorActivationCodeMismatch and resp.get('want_more', False) and self._finalize_attempts: self.steam_time_offset += 30 self._finalize_attempts -= 1
python
{ "resource": "" }
q21642
SteamAuthenticator.create_emergency_codes
train
def create_emergency_codes(self, code=None): """Generate emergency codes :param code: SMS code :type code: str :raises: :class:`SteamAuthenticatorError` :return: list of codes :rtype: list .. note:: A confirmation code is required to generate emergency codes and this method needs to be called twice as shown below. .. code:: python sa.create_emergency_codes() # request a SMS code
python
{ "resource": "" }
q21643
SteamAuthenticator.add_phone_number
train
def add_phone_number(self, phone_number): """Add phone number to account Then confirm it via :meth:`confirm_phone_number()` :param phone_number: phone number with country code :type phone_number: :class:`str` :return: success (returns ``False`` on request fail/timeout) :rtype: :class:`bool` """ sess = self._get_web_session() try: resp = sess.post('https://steamcommunity.com/steamguard/phoneajax', data={ 'op': 'add_phone_number', 'arg': phone_number, 'checkfortos': 0,
python
{ "resource": "" }
q21644
SteamAuthenticator.confirm_phone_number
train
def confirm_phone_number(self, sms_code): """Confirm phone number with the recieved SMS code :param sms_code: sms code :type sms_code: :class:`str` :return: success (returns ``False`` on request fail/timeout) :rtype: :class:`bool` """ sess = self._get_web_session() try: resp = sess.post('https://steamcommunity.com/steamguard/phoneajax', data={ 'op': 'check_sms_code', 'arg': sms_code, 'checkfortos': 1,
python
{ "resource": "" }
q21645
SteamAuthenticator.has_phone_number
train
def has_phone_number(self): """Check whether the account has a verified phone number :return: result :rtype: :class:`bool` or :class:`None` .. note:: Retruns `None` if the web requests fails for any reason """ sess = self._get_web_session() try: resp = sess.post('https://steamcommunity.com/steamguard/phoneajax', data={ 'op': 'has_phone', 'arg': '0', 'checkfortos': 0,
python
{ "resource": "" }
q21646
WebAuth.get_rsa_key
train
def get_rsa_key(self, username): """Get rsa key for a given username :param username: username :type username: :class:`str` :return: json response :rtype: :class:`dict` :raises HTTPError: any problem with http request, timeouts, 5xx, 4xx etc """ try: resp = self.session.post('https://steamcommunity.com/login/getrsakey/', timeout=15, data={ 'username': username,
python
{ "resource": "" }
q21647
WebAuth.login
train
def login(self, password='', captcha='', email_code='', twofactor_code='', language='english'): """Attempts web login and returns on a session with cookies set :param password: password, if it wasn't provided on instance init :type password: :class:`str` :param captcha: text reponse for captcha challenge :type captcha: :class:`str` :param email_code: email code for steam guard :type email_code: :class:`str` :param twofactor_code: 2FA code for steam guard :type twofactor_code: :class:`str` :param language: select language for steam web pages (sets language cookie) :type language: :class:`str` :return: a session on success and :class:`None` otherwise :rtype: :class:`requests.Session`, :class:`None` :raises HTTPError: any problem with http request, timeouts, 5xx, 4xx etc :raises LoginIncorrect: wrong username or password :raises CaptchaRequired: when captcha is needed :raises CaptchaRequiredLoginIncorrect: when captcha is needed and login is incorrect :raises EmailCodeRequired: when email is needed :raises TwoFactorCodeRequired: when 2FA is needed """ if self.logged_on: return self.session if password: self.password = password else: if self.password: password = self.password
python
{ "resource": "" }
q21648
WebAuth.cli_login
train
def cli_login(self, password='', captcha='', email_code='', twofactor_code='', language='english'): """Generates CLI prompts to perform the entire login process :param password: password, if it wasn't provided on instance init :type password: :class:`str` :param captcha: text reponse for captcha challenge :type captcha: :class:`str` :param email_code: email code for steam guard :type email_code: :class:`str` :param twofactor_code: 2FA code for steam guard :type twofactor_code: :class:`str` :param language: select language for steam web pages (sets language cookie) :type language: :class:`str` :return: a session on success and :class:`None` otherwise :rtype: :class:`requests.Session`, :class:`None` .. code:: python In [3]: user.cli_login() Enter password for 'steamuser': Solve CAPTCHA at https://steamcommunity.com/login/rendercaptcha/?gid=1111111111111111111 CAPTCHA code: 123456 Invalid password for 'steamuser'.
python
{ "resource": "" }
q21649
SteamLeaderboard.get_entries
train
def get_entries(self, start=0, end=0, data_request=None, steam_ids=None): """Get leaderboard entries. :param start: start entry, not index (e.g. rank 1 is ``start=1``) :type start: :class:`int` :param end: end entry, not index (e.g. only one entry then ``start=1,end=1``) :type end: :class:`int` :param data_request: data being requested :type data_request: :class:`steam.enums.common.ELeaderboardDataRequest` :param steam_ids: list of steam ids when using :prop:`.ELeaderboardDataRequest.Users` :type steamids: :class:`list` :return: a list of entries, see ``CMsgClientLBSGetLBEntriesResponse`` :rtype: :class:`list` :raises: :class:`LookupError` on message timeout or error """ message = MsgProto(EMsg.ClientLBSGetLBEntries) message.body.app_id = self.app_id message.body.leaderboard_id = self.id
python
{ "resource": "" }
q21650
SteamLeaderboard.get_iter
train
def get_iter(self, times, seconds, chunk_size=2000): """Make a iterator over the entries See :class:`steam.util.throttle.ConstantRateLimit` for ``times`` and ``seconds`` parameters. :param chunk_size: number of entries per request :type chunk_size: :class:`int` :returns: generator object :rtype: :class:`generator` The iterator essentially buffers ``chuck_size`` number of entries, and ensures we are not sending messages too fast. For example, the ``__iter__`` method on this class uses ``get_iter(1, 1, 2000)`` """ def entry_generator():
python
{ "resource": "" }
q21651
SteamClient.get_sentry
train
def get_sentry(self, username): """ Returns contents of sentry file for the given username .. note:: returns ``None`` if :attr:`credential_location` is not set, or file is not found/inaccessible :param username: username :type username: :class:`str` :return: sentry file contents, or ``None`` :rtype: :class:`bytes`, :class:`None` """
python
{ "resource": "" }
q21652
SteamClient.store_sentry
train
def store_sentry(self, username, sentry_bytes): """ Store sentry bytes under a username :param username: username :type username: :class:`str` :return: Whenver the operation succeed :rtype: :class:`bool` """ filepath = self._get_sentry_path(username) if filepath: try: with open(filepath, 'wb') as f:
python
{ "resource": "" }
q21653
SteamClient.login
train
def login(self, username, password='', login_key=None, auth_code=None, two_factor_code=None, login_id=None): """Login as a specific user :param username: username :type username: :class:`str` :param password: password :type password: :class:`str` :param login_key: login key, instead of password :type login_key: :class:`str` :param auth_code: email authentication code :type auth_code: :class:`str` :param two_factor_code: 2FA authentication code :type two_factor_code: :class:`str` :param login_id: number used for identifying logon session :type login_id: :class:`int` :return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_ :rtype: :class:`.EResult` .. note:: Failure to login will result in the server dropping the connection, ``error`` event is fired ``auth_code_required`` event is fired when 2FA or Email code is needed. Here is example code of how to handle the situation. .. code:: python @steamclient.on(steamclient.EVENT_AUTH_CODE_REQUIRED) def auth_code_prompt(is_2fa, code_mismatch): if is_2fa: code = input("Enter 2FA Code: ") steamclient.login(username, password, two_factor_code=code) else: code = input("Enter Email Code: ") steamclient.login(username, password, auth_code=code) Codes are required every time a user logins if sentry is not setup. See :meth:`set_credential_location` """ self._LOG.debug("Attempting login") if not self._pre_login(): return EResult.TryAnotherCM self.username = username message = MsgProto(EMsg.ClientLogon) message.header.steamid = SteamID(type='Individual', universe='Public') message.body.protocol_version = 65579 message.body.client_package_version = 1771 message.body.client_os_type = EOSType.Windows10 message.body.client_language = "english" message.body.should_remember_password = True message.body.supports_rate_limit_response = True
python
{ "resource": "" }
q21654
SteamClient.anonymous_login
train
def anonymous_login(self): """Login as anonymous user :return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_ :rtype: :class:`.EResult` """
python
{ "resource": "" }
q21655
SteamClient.logout
train
def logout(self): """ Logout from steam. Doesn't nothing if not logged on. .. note:: The server will drop the connection immediatelly upon logout. """
python
{ "resource": "" }
q21656
SteamClient.cli_login
train
def cli_login(self, username='', password=''): """Generates CLI prompts to complete the login process :param username: optionally provide username :type username: :class:`str` :param password: optionally provide password :type password: :class:`str` :return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_ :rtype: :class:`.EResult` Example console output after calling :meth:`cli_login` .. code:: python In [5]: client.cli_login() Steam username: myusername Password: Steam is down. Keep retrying? [y/n]: y Invalid password for 'myusername'. Enter password: Enter email code: 123 Incorrect code. Enter email code: K6VKF Out[5]: <EResult.OK: 1> """ if not username: username = _cli_input("Username: ") if not password: password = getpass() auth_code = two_factor_code = None prompt_for_unavailable = True result = self.login(username, password) while result in (EResult.AccountLogonDenied, EResult.InvalidLoginAuthCode, EResult.AccountLoginDeniedNeedTwoFactor, EResult.TwoFactorCodeMismatch, EResult.TryAnotherCM, EResult.ServiceUnavailable, EResult.InvalidPassword, ): self.sleep(0.1) if result == EResult.InvalidPassword: password = getpass("Invalid password for %s. Enter password: " % repr(username)) elif result in (EResult.AccountLogonDenied, EResult.InvalidLoginAuthCode): prompt = ("Enter email code: " if result == EResult.AccountLogonDenied else "Incorrect code. Enter email code: ") auth_code, two_factor_code = _cli_input(prompt), None elif result in
python
{ "resource": "" }
q21657
CMClient.connect
train
def connect(self, retry=0, delay=0): """Initiate connection to CM. Blocks until connected unless ``retry`` is specified. :param retry: number of retries before returning. Unlimited when set to ``None`` :type retry: :class:`int` :param delay: delay in secnds before connection attempt :type delay: :class:`int` :return: successful connection :rtype: :class:`bool` """ if self.connected: self._LOG.debug("Connect called, but we are connected?") return if self._connecting: self._LOG.debug("Connect called, but we are already connecting.") return self._connecting = True if delay: self._LOG.debug("Delayed connect: %d seconds" % delay) self.emit(self.EVENT_RECONNECT, delay) self.sleep(delay) self._LOG.debug("Connect initiated.") for i, server_addr in enumerate(self.cm_servers): if retry and i > retry: return False
python
{ "resource": "" }
q21658
CMServerList.clear
train
def clear(self): """Clears the server list"""
python
{ "resource": "" }
q21659
CMServerList.bootstrap_from_webapi
train
def bootstrap_from_webapi(self, cellid=0): """ Fetches CM server list from WebAPI and replaces the current one :param cellid: cell id (0 = global) :type cellid: :class:`int` :return: booststrap success :rtype: :class:`bool` """ self._LOG.debug("Attempting bootstrap via WebAPI") from steam import webapi try: resp = webapi.get('ISteamDirectory', 'GetCMList', 1, params={'cellid': cellid}) except Exception as exp: self._LOG.error("WebAPI boostrap failed: %s" % str(exp)) return False result = EResult(resp['response']['result']) if result != EResult.OK:
python
{ "resource": "" }
q21660
CMServerList.reset_all
train
def reset_all(self): """Reset status for all servers in the list""" self._LOG.debug("Marking all CMs as Good.")
python
{ "resource": "" }
q21661
CMServerList.mark_good
train
def mark_good(self, server_addr): """Mark server address as good :param server_addr: (ip, port) tuple :type server_addr: :class:`tuple`
python
{ "resource": "" }
q21662
CMServerList.mark_bad
train
def mark_bad(self, server_addr): """Mark server address as bad, when unable to connect for example :param server_addr: (ip, port) tuple
python
{ "resource": "" }
q21663
CMServerList.merge_list
train
def merge_list(self, new_list): """Add new CM servers to the list :param new_list: a list of ``(ip, port)`` tuples :type new_list: :class:`list` """ total = len(self.list) for ip, port in new_list:
python
{ "resource": "" }
q21664
SteamFriendlist.remove
train
def remove(self, steamid): """ Remove a friend :param steamid: their steamid :type steamid: :class:`int`, :class:`.SteamID`, :class:`.SteamUser`
python
{ "resource": "" }
q21665
webapi_request
train
def webapi_request(url, method='GET', caller=None, session=None, params=None): """Low level function for calling Steam's WebAPI .. versionchanged:: 0.8.3 :param url: request url (e.g. ``https://api.steampowered.com/A/B/v001/``) :type url: :class:`str` :param method: HTTP method (GET or POST) :type method: :class:`str` :param caller: caller reference, caller.last_response is set to the last response :param params: dict of WebAPI and endpoint specific params :type params: :class:`dict` :param session: an instance requests session, or one is created per call :type session: :class:`requests.Session` :return: response based on paramers :rtype: :class:`dict`, :class:`lxml.etree.Element`, :class:`str` """ if method not in ('GET', 'POST'): raise NotImplemented("HTTP method: %s" % repr(self.method)) if params is None: params = {} onetime = {} for param in DEFAULT_PARAMS: params[param] = onetime[param] = params.get(param, DEFAULT_PARAMS[param]) for param in ('raw', 'apihost', 'https', 'http_timeout'): del params[param] if onetime['format'] not in ('json', 'vdf', 'xml'): raise ValueError("Expected format to be json,vdf or xml; got %s" % onetime['format']) for k, v in list(params.items()): # serialize some types if isinstance(v, bool): params[k] = 1 if v else 0 elif isinstance(v, dict): params[k] = _json.dumps(v) elif isinstance(v, list): del params[k] for
python
{ "resource": "" }
q21666
get
train
def get(interface, method, version=1, apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'], caller=None, session=None, params=None): """Send GET request to an API endpoint .. versionadded:: 0.8.3 :param interface: interface name :type interface: str :param method: method name :type method: str :param version: method version
python
{ "resource": "" }
q21667
post
train
def post(interface, method, version=1, apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'], caller=None, session=None, params=None): """Send POST request to an API endpoint .. versionadded:: 0.8.3 :param interface: interface name :type interface: str :param method: method name :type method: str :param version: method version
python
{ "resource": "" }
q21668
WebAPI.fetch_interfaces
train
def fetch_interfaces(self): """ Returns a dict with the response from ``GetSupportedAPIList`` :return: :class:`dict` of all interfaces and methods The returned value can passed to :meth:`load_interfaces` """ return get('ISteamWebAPIUtil', 'GetSupportedAPIList', 1, https=self.https,
python
{ "resource": "" }
q21669
WebAPI.load_interfaces
train
def load_interfaces(self, interfaces_dict): """ Populates the namespace under the instance """ if interfaces_dict.get('apilist', {}).get('interfaces', None) is None: raise ValueError("Invalid response for GetSupportedAPIList") interfaces = interfaces_dict['apilist']['interfaces'] if len(interfaces) == 0: raise ValueError("API returned not interfaces; probably using invalid key") # clear existing interface instances for interface in self.interfaces: delattr(self, interface.name)
python
{ "resource": "" }
q21670
WebAPI.call
train
def call(self, method_path, **kwargs): """ Make an API call for specific method :param method_path: format ``Interface.Method`` (e.g. ``ISteamWebAPIUtil.GetServerInfo``) :type method_path: :class:`str` :param kwargs: keyword arguments for the specific method :return: response :rtype:
python
{ "resource": "" }
q21671
SteamUnifiedMessages.get
train
def get(self, method_name): """Get request proto instance for given methed name :param method_name: name for the method (e.g. ``Player.GetGameBadgeLevels#1``) :type method_name: :class:`str` :return: proto message instance, or :class:`None` if not found """ proto
python
{ "resource": "" }
q21672
SteamUnifiedMessages.send
train
def send(self, message, params=None): """Send service method request :param message: proto message instance (use :meth:`SteamUnifiedMessages.get`) or method name (e.g. ``Player.GetGameBadgeLevels#1``) :type message: :class:`str`, proto message instance :param params: message parameters :type params: :class:`dict` :return: ``jobid`` event identifier :rtype: :class:`str` Listen for ``jobid`` on this object to catch the response. .. note:: If you listen for ``jobid`` on the client instance you will get the encapsulated message """ if isinstance(message, str):
python
{ "resource": "" }
q21673
SteamUnifiedMessages.send_and_wait
train
def send_and_wait(self, message, params=None, timeout=10, raises=False): """Send service method request and wait for response :param message: proto message instance (use :meth:`SteamUnifiedMessages.get`) or method name (e.g. ``Player.GetGameBadgeLevels#1``) :type message: :class:`str`, proto message instance :param params: message parameters :type params: :class:`dict` :param timeout: (optional) seconds to wait :type timeout: :class:`int` :param raises: (optional) On timeout if :class:`False` return :class:`None`, else raise :class:`gevent.Timeout` :type raises: :class:`bool`
python
{ "resource": "" }
q21674
StructReader.read
train
def read(self, n=1): """Return n bytes :param n: number of bytes to return :type n: :class:`int` :return: bytes
python
{ "resource": "" }
q21675
StructReader.read_cstring
train
def read_cstring(self, terminator=b'\x00'): """Reads a single null termianted string :return: string without bytes :rtype: :class:`bytes` """ null_index = self.data.find(terminator, self.offset) if null_index == -1: raise RuntimeError("Reached end of buffer")
python
{ "resource": "" }
q21676
StructReader.unpack
train
def unpack(self, format_text): """Unpack bytes using struct modules format :param format_text: struct's module format :type format_text: :class:`str` :return data: result from :func:`struct.unpack_from` :rtype: :class:`tuple` """
python
{ "resource": "" }
q21677
proto_to_dict
train
def proto_to_dict(message): """Converts protobuf message instance to dict :param message: protobuf message instance :return: parameters and their values :rtype: dict :raises: :class:`.TypeError` if ``message`` is not a proto message """ if not isinstance(message, _ProtoMessageType): raise TypeError("Expected `message` to be
python
{ "resource": "" }
q21678
chunks
train
def chunks(arr, size): """Splits a list into chunks :param arr: list to split :type arr: :class:`list` :param size: number of elements in each chunk :type size: :class:`int` :return:
python
{ "resource": "" }
q21679
GameCoordinator.send
train
def send(self, header, body): """ Send a message to GC :param header: message header :type header: :class:`steam.core.msg.GCMsgHdr` :param body: serialized body of the message :type body: :class:`bytes` """ message = MsgProto(EMsg.ClientToGC) message.header.routing_appid = self.app_id message.body.appid = self.app_id message.body.msgtype =
python
{ "resource": "" }
q21680
get_um
train
def get_um(method_name, response=False): """Get protobuf for given method name :param method_name: full method name (e.g. ``Player.GetGameBadgeLevels#1``) :type method_name: :class:`str` :param response: whether to return proto for response or request :type response: :class:`bool` :return: protobuf message """ key = (method_name, response) if key not in method_lookup: match = re.findall(r'^([a-z]+)\.([a-z]+)#(\d)?$', method_name, re.I)
python
{ "resource": "" }
q21681
make_steam64
train
def make_steam64(id=0, *args, **kwargs): """ Returns steam64 from various other representations. .. code:: python make_steam64() # invalid steamid make_steam64(12345) # accountid make_steam64('12345') make_steam64(id=12345, type='Invalid', universe='Invalid', instance=0) make_steam64(103582791429521412) # steam64 make_steam64('103582791429521412') make_steam64('STEAM_1:0:2') # steam2 make_steam64('[g:1:4]') # steam3 """ accountid = id etype = EType.Invalid universe = EUniverse.Invalid instance = None if len(args) == 0 and len(kwargs) == 0: value = str(accountid) # numeric input if value.isdigit(): value = int(value) # 32 bit account id if 0 < value < 2**32: accountid = value etype = EType.Individual universe = EUniverse.Public # 64 bit elif value < 2**64: return value # textual input e.g. [g:1:4] else: result = steam2_to_tuple(value) or steam3_to_tuple(value) if result: (accountid, etype, universe, instance, ) = result else: accountid = 0 elif len(args) > 0: length = len(args) if length == 1: etype, = args elif length == 2:
python
{ "resource": "" }
q21682
steam64_from_url
train
def steam64_from_url(url, http_timeout=30): """ Takes a Steam Community url and returns steam64 or None .. note:: Each call makes a http request to ``steamcommunity.com`` .. note:: For a reliable resolving of vanity urls use ``ISteamUser.ResolveVanityURL`` web api :param url: steam community url :type url: :class:`str` :param http_timeout: how long to wait on http request before turning ``None`` :type http_timeout: :class:`int` :return: steam64, or ``None`` if ``steamcommunity.com`` is down :rtype: :class:`int` or :class:`None` Example URLs:: https://steamcommunity.com/gid/[g:1:4] https://steamcommunity.com/gid/103582791429521412 https://steamcommunity.com/groups/Valve https://steamcommunity.com/profiles/[U:1:12]
python
{ "resource": "" }
q21683
SteamID.is_valid
train
def is_valid(self): """ Check whether this SteamID is valid :rtype: :py:class:`bool` """ if self.type == EType.Invalid or self.type >= EType.Max: return False if self.universe == EUniverse.Invalid or self.universe >= EUniverse.Max: return False if self.type == EType.Individual: if self.id == 0 or self.instance > 4: return False if self.type == EType.Clan: if
python
{ "resource": "" }
q21684
SteamGameServers.query
train
def query(self, filter_text, max_servers=10, timeout=30, **kw): r""" Query game servers https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol .. note:: When specifying ``filter_text`` use *raw strings* otherwise python won't treat backslashes as literal characters (e.g. ``query(r'\appid\730\white\1')``) :param filter_text: filter for servers :type filter_text: str :param max_servers: (optional) number of servers to return :type max_servers: int :param timeout: (optional) timeout for request in seconds :type timeout: int :param app_id: (optional) app id :type app_id: int :param geo_location_ip: (optional) ip (e.g. '1.2.3.4') :type geo_location_ip: str :returns: list of servers, see below. (``None`` is returned steam doesn't respond) :rtype: :class:`list`, :class:`None` Sample response: .. code:: python [{'auth_players': 0, 'server_ip': '1.2.3.4', 'server_port': 27015}, {'auth_players': 6, 'server_ip': '1.2.3.4', 'server_port': 27016}, ... ] """
python
{ "resource": "" }
q21685
SteamGameServers.get_ips_from_steamids
train
def get_ips_from_steamids(self, server_steam_ids, timeout=30): """Resolve IPs from SteamIDs :param server_steam_ids: a list of steamids :type server_steam_ids: list :param timeout: (optional) timeout for request in seconds :type timeout: int :return: map of ips to steamids :rtype: dict :raises: :class:`.UnifiedMessageError` Sample response: .. code:: python {SteamID(id=123456, type='AnonGameServer', universe='Public', instance=1234): '1.2.3.4:27060'} """ resp, error = self._um.send_and_wait("GameServers.GetServerIPsBySteamID#1",
python
{ "resource": "" }
q21686
SteamGameServers.get_steamids_from_ips
train
def get_steamids_from_ips(self, server_ips, timeout=30): """Resolve SteamIDs from IPs :param steam_ids: a list of ips (e.g. ``['1.2.3.4:27015',...]``) :type steam_ids: list :param timeout: (optional) timeout for request in seconds :type timeout: int :return: map of steamids to ips :rtype: dict :raises: :class:`.UnifiedMessageError` Sample response: .. code:: python {'1.2.3.4:27060': SteamID(id=123456, type='AnonGameServer', universe='Public', instance=1234)} """ resp, error = self._um.send_and_wait("GameServers.GetServerSteamIDsByIP#1",
python
{ "resource": "" }
q21687
Account.request_validation_mail
train
def request_validation_mail(self): """Request validation email :return: result :rtype: :class:`.EResult` """ message =
python
{ "resource": "" }
q21688
Account.request_password_change_mail
train
def request_password_change_mail(self, password): """Request password change mail :param password: current account password :type password: :class:`str` :return: result :rtype: :class:`.EResult` """ message = Msg(EMsg.ClientRequestChangeMail, extended=True) message.body.password = password
python
{ "resource": "" }
q21689
Account.change_password
train
def change_password(self, password, new_password, email_code): """Change account's password :param password: current account password :type password: :class:`str` :param new_password: new account password :type new_password: :class:`str` :param email_code: confirmation code from email :type email_code: :class:`str` :return: result :rtype: :class:`.EResult` .. note:: First request change mail via :meth:`request_password_change_mail()` to get the email code """
python
{ "resource": "" }
q21690
SteamUser.get_ps
train
def get_ps(self, field_name, wait_pstate=True): """Get property from PersonaState `See full list of available fields_names <https://github.com/ValvePython/steam/blob/fa8a5127e9bb23185483930da0b6ae85e93055a7/protobufs/steammessages_clientserver_friends.proto#L125-L153>`_ """ if not wait_pstate or self._pstate_ready.wait(timeout=5): if self._pstate
python
{ "resource": "" }
q21691
SteamUser.rich_presence
train
def rich_presence(self): """Contains Rich Presence key-values :rtype: dict """ kvs = self.get_ps('rich_presence') data = {} if kvs:
python
{ "resource": "" }
q21692
SteamUser.get_avatar_url
train
def get_avatar_url(self, size=2): """Get URL to avatar picture :param size: possible values are ``0``, ``1``, or ``2`` corresponding to small, medium, large :type size: :class:`int` :return: url to avatar :rtype: :class:`str` """ hashbytes = self.get_ps('avatar_hash') if hashbytes != "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000": ahash = hexlify(hashbytes).decode('ascii') else:
python
{ "resource": "" }
q21693
SteamUser.send_message
train
def send_message(self, message): """Send chat message to this steam user :param message: message to send :type message: str """ self._steam.send(MsgProto(EMsg.ClientFriendMsg), { 'steamid': self.steam_id,
python
{ "resource": "" }
q21694
ConstantRateLimit.wait
train
def wait(self): """Blocks until the rate is met""" now = _monotonic() if now < self._ref:
python
{ "resource": "" }
q21695
Apps.get_player_count
train
def get_player_count(self, app_id, timeout=5): """Get numbers of players for app id :param app_id: app id :type app_id: :class:`int` :return: number of players :rtype: :class:`int`, :class:`.EResult` """ resp = self.send_job_and_wait(MsgProto(EMsg.ClientGetNumberOfCurrentPlayersDP), {'appid': app_id},
python
{ "resource": "" }
q21696
Apps.get_product_info
train
def get_product_info(self, apps=[], packages=[], timeout=15): """Get product info for apps and packages :param apps: items in the list should be either just ``app_id``, or ``(app_id, access_token)`` :type apps: :class:`list` :param packages: items in the list should be either just ``package_id``, or ``(package_id, access_token)`` :type packages: :class:`list` :return: dict with ``apps`` and ``packages`` containing their info, see example below :rtype: :class:`dict`, :class:`None` .. code:: python {'apps': {570: {...}, ...}, 'packages': {123: {...}, ...} } """ if not apps and not packages: return message = MsgProto(EMsg.ClientPICSProductInfoRequest) for app in apps: app_info =
python
{ "resource": "" }
q21697
Apps.get_changes_since
train
def get_changes_since(self, change_number, app_changes=True, package_changes=False): """Get changes since a change number :param change_number: change number to use as stating point :type change_number: :class:`int` :param app_changes: whether to inclued app changes :type app_changes: :class:`bool` :param package_changes: whether to inclued package changes :type package_changes: :class:`bool` :return: `CMsgClientPICSChangesSinceResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver.proto#L1171-L1191>`_ :rtype: proto message instance, or :class:`None` on timeout """ return self.send_job_and_wait(MsgProto(EMsg.ClientPICSChangesSinceRequest),
python
{ "resource": "" }
q21698
Apps.get_app_ticket
train
def get_app_ticket(self, app_id): """Get app ownership ticket :param app_id: app id :type app_id: :class:`int` :return: `CMsgClientGetAppOwnershipTicketResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver.proto#L158-L162>`_ :rtype: proto message
python
{ "resource": "" }
q21699
Apps.get_depot_key
train
def get_depot_key(self, depot_id, app_id=0): """Get depot decryption key :param depot_id: depot id :type depot_id: :class:`int` :param app_id: app id :type app_id: :class:`int` :return: `CMsgClientGetDepotDecryptionKeyResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver_2.proto#L533-L537>`_
python
{ "resource": "" }