_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| 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()
fullname = user.getProperty('fullname')
if not fullname:
fullname = uid
pairs.append((uid, fullname))
pairs.sort(lambda x, y: cmp(x[1], y[1]))
return DisplayList(pairs)
|
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 from_date and to_date:
date_query = {'query': [from_date, to_date],
'range': 'min:max'}
elif from_date or to_date:
date_query = {'query': from_date or to_date,
'range': from_date and 'min' or 'max'}
return date_query
|
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 = 'from %s to %s' % (from_date, to_date)
elif from_date:
date_parms = 'from %s' % (from_date)
elif to_date:
date_parms = 'to %s' % (to_date)
return 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 == ' ':
quoted += '_'
# These characters can be included verbatim
elif hqre.match(c):
quoted += c
# Otherwise, replace with hex value like =E2
else:
quoted += "=%02X" % ord(c)
return '=?%s?q?%s?=' % (charset, quoted)
|
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)
# Truncate to prevent bloat
for charset in [def_charset, 'latin-1', 'utf-8']:
try:
sortabletitle = safe_unicode(sortabletitle, charset)[:30]
sortabletitle = sortabletitle.encode(def_charset or 'utf-8')
break
except UnicodeError:
pass
except TypeError:
# If we get a TypeError if we already have a unicode string
sortabletitle = sortabletitle[:30]
break
return 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': "Setting state to %s" % state_id,
'review_state': state_id,
'time': DateTime()
}
# Change status and update permissions
portal_workflow.setStatusOf(wf_id, content, wf_state)
workflow.updateRoleMappingsFor(content)
# Map changes to catalog
indexes = ["allowedRolesAndUsers", "review_state", "is_active"]
content.reindexObject(idxs=indexes)
return True
|
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
# as well in our local site, e.g. we have `/senaite/img/systems/senaite.png`,
# but the user requested http://www.ridingbytes.com/img/systems/senaite.png:
#
# "/".join(request.physicalPathFromURL("http://www.ridingbytes.com/img/systems/senaite.png"))
# '/senaite/img/systems/senaite.png'
if context is None or host not in url:
logger.info("URL is external, passing over to the default URL fetcher...")
return default_url_fetcher(url)
logger.info("URL is local, fetching data by path '{}' via subrequest".format(path))
# get the data via an authenticated subrequest
response = subrequest(path)
# Prepare the return data as required by WeasyPrint
string = response.getBody()
filename = url.split("/")[-1]
mime_type = mimetypes.guess_type(url)[0]
redirected_url = url
return {
"string": string,
"filename": filename,
"mime_type": mime_type,
"redirected_url": redirected_url,
}
|
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 dictionary. If a key is duplicated,
the earlier value will be overwritten.
"""
result = {}
for d in dictionaries:
result[d[key_subfieldname]] = d
return result
|
python
|
{
"resource": ""
}
|
q21608
|
drop_trailing_zeros_decimal
|
train
|
def drop_trailing_zeros_decimal(num):
""" Drops the trailinz zeros from decimal value.
Returns a string
"""
out = str(num)
return out.rstrip('0').rstrip('.') if '.' in out else out
|
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.
Otherwise, it returns empty.
"""
if not obj:
return False
sm = getSecurityManager()
for perm in permissions:
if not sm.checkPermission(perm, obj):
return ''
return True
|
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", [])
for analysis in analyses:
if analysis.get("title") == title:
return analysis
return None
|
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 the array.
"""
ws = None
if self._current_ws_index < len(self._worksheets):
ws = self._ws_data(self._worksheets[self._current_ws_index])
return ws
|
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):
ar['sample'] = self._sample_data(an.getSample())
else:
ar['sample'] = self._sample_data(an.getRequest())
ar['analyses'] = []
ar['tmp_position'] = andict['tmp_position']
ar['position'] = andict['position']
if an.portal_type in ("ReferenceAnalysis", "DuplicateAnalysis"):
ar['id'] = an.getReferenceAnalysesGroupID()
ar['url'] = an.absolute_url()
else:
ar = ars[reqid]
if (andict['tmp_position'] < ar['tmp_position']):
ar['tmp_position'] = andict['tmp_position']
ar['position'] = andict['position']
# Sort analyses by position
ans = ar['analyses']
ans.append(andict)
ans.sort(lambda x, y: cmp(x.get('tmp_position'), y.get('tmp_position')))
ar['analyses'] = ans
ars[reqid] = ar
ars = [a for a in ars.itervalues()]
# Sort analysis requests by position
ars.sort(lambda x, y: cmp(x.get('tmp_position'), y.get('tmp_position')))
return ars
|
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': '',
'review_state': api.get_workflow_status_of(analysis),
}
andict['refsample'] = analysis.getSample().id \
if IReferenceAnalysis.providedBy(analysis) \
else analysis.getRequestID()
specs = analysis.getResultsRange()
andict['specs'] = specs
scinot = self.context.bika_setup.getScientificNotationReport()
andict['formatted_result'] = analysis.getFormattedResult(specs=specs, sciformat=int(scinot), decimalmark=decimalmark)
fs = ''
if specs.get('min', None) and specs.get('max', None):
fs = '%s - %s' % (specs['min'], specs['max'])
elif specs.get('min', None):
fs = '> %s' % specs['min']
elif specs.get('max', None):
fs = '< %s' % specs['max']
andict['formatted_specs'] = formatDecimalMark(fs, decimalmark)
andict['formatted_uncertainty'] = format_uncertainty(analysis, analysis.getResult(), decimalmark=decimalmark, sciformat=int(scinot))
# Out of range?
andict['outofrange'] = is_out_of_range(analysis)[0]
return andict
|
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),
'url': ar.absolute_url(), }
elif ar.portal_type == "ReferenceSample":
return {'obj': ar,
'id': ar.id,
'date_received': self.ulocalized_time(
ar.getDateReceived(), long_format=0),
'date_sampled': self.ulocalized_time(
ar.getDateSampled(), long_format=True),
'url': ar.absolute_url(), }
else:
return {'obj': ar,
'id': ar.id,
'date_received': "",
'date_sampled': "",
'url': ar.absolute_url(), }
|
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)
for i in bsc(portal_type='Instrument',
is_active=True)]
items.sort(lambda x, y: cmp(x[1], y[1]))
return DisplayList(list(items))
|
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)
# Remove the service from templates to which is assigned
bsc = api.get_tool('bika_setup_catalog')
templates = bsc(portal_type='ARTemplate')
for template in templates:
template = api.get_object(template)
template.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:
return dicts_to_dict(spec, "keyword")
return ResultsRangeDict()
|
python
|
{
"resource": ""
}
|
q21618
|
AnalysisRequestAnalysesView.folderitems
|
train
|
def folderitems(self):
"""XXX refactor if possible to non-classic mode
"""
items = super(AnalysisRequestAnalysesView, self).folderitems()
self.categories.sort()
return items
|
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:
u = nobody
if str(u) not in ('Anonymous User',):
self.REQUEST['_c_authenticatedUser'] = u
else:
u = self.REQUEST['_c_authenticatedUser']
return self.wrapUser(u)
|
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"]
diff = filter(lambda role: role in allowed, self.member.getRoles())
self.filter_by_user = len(diff) == 0
if self.filter_by_user:
# Remove 'Mine' button and hide 'Analyst' column
del self.review_states[1] # Mine
self.columns["Analyst"]["toggle"] = False
self.contentFilter["getAnalyst"] = self.member.id
for rvw in self.review_states:
rvw["contentFilter"]["getAnalyst"] = self.member.id
|
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:
return False
if self.filter_by_user:
return False
return True
|
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"]:
continue
rs["custom_transitions"].append(reassing_analyst_transition)
self.show_select_column = True
self.show_workflow_action_buttons = True
|
python
|
{
"resource": ""
}
|
q21623
|
FolderView.get_selected_state
|
train
|
def get_selected_state(self):
"""Returns the current selected state
"""
form_key = "{}_review_state".format(self.form_id)
return self.request.get(form_key, "default")
|
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()
uid_instrument = ""
if instrument:
uid_instrument = api.get_uid(instrument)
items[uid_template] = uid_instrument
return json.dumps(items)
|
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
# of the AR was "to_be_verified", addition of a new analysis when the
# state was "to_be_verified", etc.
request = analysis.getRequest()
wf.doActionFor(request, "rollback_to_receive")
# Reindex the indexes for UIDReference fields on creation!
analysis.reindexObject(idxs="getServiceUID")
return
|
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 to the Analysis Request
# Note there is no need to check if the Analysis Request allows a given
# transition, cause this is already managed by doActionFor
analysis_request = analysis.getRequest()
wf.doActionFor(analysis_request, "submit")
wf.doActionFor(analysis_request, "verify")
return
|
python
|
{
"resource": ""
}
|
q21627
|
fixPath
|
train
|
def fixPath(path):
"""
Ensures paths are correct for linux and windows
"""
path = os.path.abspath(os.path.expanduser(path))
if path.startswith("\\"):
return "C:" + path
return path
|
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"):
platform = "windows"
else:
raise Exception("Platform '%s' is unsupported!" % sys.platform)
return platform
|
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__,
SerializationTestPyRegion.__name__)
try:
_runTest()
finally:
engine.Network.unregisterPyRegion(SerializationTestPyRegion.__name__)
|
python
|
{
"resource": ""
}
|
q21630
|
checkImportBindingsExtensions
|
train
|
def checkImportBindingsExtensions():
"""Check that nupic.bindings extension libraries can be imported.
Throws ImportError on failure.
"""
import nupic.bindings.math
import nupic.bindings.algorithms
import nupic.bindings.engine_internal
|
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:")
print e.message
return
try:
checkImportBindingsExtensions()
except ImportError as e:
print ("Could not import C extensions for nupic.bindings. Make sure that "
"the package was properly installed. Error message:")
print e.message
return
print "Successfully imported nupic.bindings."
|
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.
:param name: (string) name of requested parameter
:param index: (int) index of node inside the region (if relevant)
:raises: Exception if parameter starts with ``_``.
"""
if name.startswith('_'):
raise Exception('Parameter name must not start with an underscore')
return len(self.parameters[name])
|
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. Note that due to
the command mechanism only unnamed argument are supported.
:param methodName: (string) the name of the method that correspond to a
command in the spec.
:param args: (list) of arguments that will be passed to the method
"""
if not hasattr(self, methodName):
raise Exception('Missing command method: ' + methodName)
m = getattr(self, methodName)
if not hasattr(m, '__call__'):
raise Exception('Command: ' + methodName + ' must be callable')
return m(*args)
|
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 use a special attribule named "__{name}_len__" to pass
# the sparse array length back to c++
lenAttr = "__{}_len__".format(name)
if lenAttr not in outputs:
raise Exception("Output {} is not a valid sparse output".format(name))
if outputs[name].size < value.size:
raise Exception(
"Output {} must be less than {}. Given value size is {}".format(
name, outputs[name].size, value.size))
outputs[lenAttr][0] = value.size
outputs[name][:value.size] = value
|
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,
_MAX_DESERIALIZATION_LOOPS_PER_READER)
for _ in xrange(numReads):
r.read(readerProto)
deserializationCount += numReads
elapsedDeserializationTime = time.time() - startDeserializationTime
# Print report
print _SERIALIZATION_LOOPS, "Serialization loops in", \
elapsedSerializationTime, "seconds."
print "\t", elapsedSerializationTime/_SERIALIZATION_LOOPS, "seconds per loop."
print deserializationCount, "Deserialization loops in", \
elapsedDeserializationTime, "seconds."
print "\t", elapsedDeserializationTime/deserializationCount, "seconds per loop."
|
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
:rtype: str
"""
hmac = hmac_sha1(bytes(shared_secret),
struct.pack('>Q', int(timestamp)//30)) # this will NOT stop working in 2038
start = ord(hmac[19:20]) & 0xF
codeint = struct.unpack('>I', hmac[start:start+4])[0] & 0x7fffffff
charset = '23456789BCDFGHJKMNPQRTVWXY'
code = ''
for _ in range(5):
codeint, i = divmod(codeint, len(charset))
code += charset[i]
return 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 generating key
:type timestamp: int
:return: confirmation key
:rtype: bytes
Tag choices:
* ``conf`` to load the confirmations page
* ``details`` to load details about a trade
* ``allow`` to confirm a trade
* ``cancel`` to cancel a trade
"""
data = struct.pack('>Q', int(timestamp)) + tag.encode('ascii') # this will NOT stop working in 2038
return hmac_sha1(bytes(identity_secret), data)
|
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:
resp = webapi.post('ITwoFactorService', 'QueryTime', 1, params={'http_timeout': 10})
except:
return None
ts = int(time())
return int(resp.get('response', {}).get('server_time', ts)) - ts
|
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
"""
h = hexlify(sha1_hash(str(steamid).encode('ascii'))).decode('ascii')
return "android:%s-%s-%s-%s-%s" % (h[:8], h[8:12], h[12:16], h[16:20], h[20:32])
|
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 /data/data/com.valvesoftware.android.steam.community/files/Steamguard*'"
])
# When adb daemon is not running, `adb` will print a couple of lines before our data.
# The data doesn't have new lines and its always on the last line.
data = data.decode('utf-8').split('\n')[-1]
if data[0] != "{":
raise RuntimeError("Got invalid data: %s" % repr(data))
return {int(x['steamid']): x
for x in map(json.loads, data.replace("}{", '}|||||{').split('|||||'))}
|
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
self.finalize(activation_code)
return
elif not resp['success']:
self._finalize_attempts = 5
raise SteamAuthenticatorError("Failed to finalize authenticator. Error: %s" % repr(EResult(resp['status'])))
self.steam_time_offset = int(resp['server_time']) - time()
|
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
sa.create_emergency_codes(code='12345') # creates emergency codes
"""
if code:
return self._send_request('createemergencycodes', {'code': code}).get('codes', [])
else:
self._send_request('createemergencycodes', {})
return None
|
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,
'skipvoip': 0,
'sessionid': sess.cookies.get('sessionid', domain='steamcommunity.com'),
},
timeout=15).json()
except:
return False
return (resp or {}).get('success', False)
|
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,
'skipvoip': 1,
'sessionid': sess.cookies.get('sessionid', domain='steamcommunity.com'),
},
timeout=15).json()
except:
return False
return (resp or {}).get('success', False)
|
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,
'skipvoip': 1,
'sessionid': sess.cookies.get('sessionid', domain='steamcommunity.com'),
},
timeout=15).json()
except:
raise
if resp['success'] == True:
return resp['has_phone']
|
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,
'donotchache': int(time() * 1000),
},
).json()
except requests.exceptions.RequestException as e:
raise HTTPError(str(e))
return resp
|
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
else:
raise LoginIncorrect("password is not specified")
if not captcha and self.captcha_code:
captcha = self.captcha_code
self._load_key()
resp = self._send_login(password=password, captcha=captcha, email_code=email_code, twofactor_code=twofactor_code)
if resp['success'] and resp['login_complete']:
self.logged_on = True
self.password = self.captcha_code = ''
self.captcha_gid = -1
for cookie in list(self.session.cookies):
for domain in ['store.steampowered.com', 'help.steampowered.com', 'steamcommunity.com']:
self.session.cookies.set(cookie.name, cookie.value, domain=domain, secure=cookie.secure)
self.session_id = generate_session_id()
for domain in ['store.steampowered.com', 'help.steampowered.com', 'steamcommunity.com']:
self.session.cookies.set('Steam_Language', language, domain=domain)
self.session.cookies.set('birthtime', '-3333', domain=domain)
self.session.cookies.set('sessionid', self.session_id, domain=domain)
self._finalize_login(resp)
return self.session
else:
if resp.get('captcha_needed', False):
self.captcha_gid = resp['captcha_gid']
self.captcha_code = ''
if resp.get('clear_password_field', False):
self.password = ''
raise CaptchaRequiredLoginIncorrect(resp['message'])
else:
raise CaptchaRequired(resp['message'])
elif resp.get('emailauth_needed', False):
self.steam_id = SteamID(resp['emailsteamid'])
raise EmailCodeRequired(resp['message'])
elif resp.get('requires_twofactor', False):
raise TwoFactorCodeRequired(resp['message'])
else:
self.password = ''
raise LoginIncorrect(resp['message'])
return None
|
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'. Enter password:
Solve CAPTCHA at https://steamcommunity.com/login/rendercaptcha/?gid=2222222222222222222
CAPTCHA code: abcdef
Enter 2FA code: AB123
Out[3]: <requests.sessions.Session at 0x6fffe56bef0>
"""
# loop until successful login
while True:
try:
return self.login(password, captcha, email_code, twofactor_code, language)
except (LoginIncorrect, CaptchaRequired) as exp:
email_code = twofactor_code = ''
if isinstance(exp, LoginIncorrect):
prompt = ("Enter password for %s: " if not password else
"Invalid password for %s. Enter password: ")
password = getpass(prompt % repr(self.username))
if isinstance(exp, CaptchaRequired):
prompt = "Solve CAPTCHA at %s\nCAPTCHA code: " % self.captcha_url
captcha = _cli_input(prompt)
else:
captcha = ''
except EmailCodeRequired:
prompt = ("Enter email code: " if not email_code else
"Incorrect code. Enter email code: ")
email_code, twofactor_code = _cli_input(prompt), ''
except TwoFactorCodeRequired:
prompt = ("Enter 2FA code: " if not twofactor_code else
"Incorrect code. Enter 2FA code: ")
email_code, twofactor_code = '', _cli_input(prompt)
|
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
message.body.range_start = start
message.body.range_end = end
message.body.leaderboard_data_request = self.data_request if data_request is None else data_request
if steam_ids:
message.body.steamids.extend(steam_ids)
resp = self._steam.send_job_and_wait(message, timeout=15)
if not resp:
raise LookupError("Didn't receive response within 15seconds :(")
if resp.eresult != EResult.OK:
raise LookupError(EResult(resp.eresult))
if resp.HasField('leaderboard_entry_count'):
self.entry_count = resp.leaderboard_entry_count
return resp.entries
|
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():
with ConstantRateLimit(times, seconds, sleep_func=self._steam.sleep) as r:
for entries in chunks(self, chunk_size):
if not entries:
return
for entry in entries:
yield entry
r.wait()
return 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`
"""
filepath = self._get_sentry_path(username)
if filepath and os.path.isfile(filepath):
try:
with open(filepath, 'rb') as f:
return f.read()
except IOError as e:
self._LOG.error("get_sentry: %s" % str(e))
return 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:
f.write(sentry_bytes)
return True
except IOError as e:
self._LOG.error("store_sentry: %s" % str(e))
return False
|
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
if login_id is None:
message.body.obfustucated_private_ip = ip_to_int(self.connection.local_address) ^ 0xF00DBAAD
else:
message.body.obfustucated_private_ip = login_id
message.body.account_name = username
if login_key:
message.body.login_key = login_key
else:
message.body.password = password
sentry = self.get_sentry(username)
if sentry is None:
message.body.eresult_sentryfile = EResult.FileNotFound
else:
message.body.eresult_sentryfile = EResult.OK
message.body.sha_sentryfile = sha1_hash(sentry)
if auth_code:
message.body.auth_code = auth_code
if two_factor_code:
message.body.two_factor_code = two_factor_code
self.send(message)
resp = self.wait_msg(EMsg.ClientLogOnResponse, timeout=30)
if resp and resp.body.eresult == EResult.OK:
self.sleep(0.5)
return EResult(resp.body.eresult) if resp else EResult.Fail
|
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`
"""
self._LOG.debug("Attempting Anonymous login")
self._pre_login()
self.username = None
self.login_key = None
message = MsgProto(EMsg.ClientLogon)
message.header.steamid = SteamID(type='AnonUser', universe='Public')
message.body.protocol_version = 65579
self.send(message)
resp = self.wait_msg(EMsg.ClientLogOnResponse, timeout=30)
return EResult(resp.body.eresult) if resp else EResult.Fail
|
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.
"""
if self.logged_on:
self.logged_on = False
self.send(MsgProto(EMsg.ClientLogOff))
try:
self.wait_event(self.EVENT_DISCONNECTED, timeout=5, raises=True)
except:
self.disconnect()
self.idle()
|
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 (EResult.AccountLoginDeniedNeedTwoFactor, EResult.TwoFactorCodeMismatch):
prompt = ("Enter 2FA code: " if result == EResult.AccountLoginDeniedNeedTwoFactor else
"Incorrect code. Enter 2FA code: ")
auth_code, two_factor_code = None, _cli_input(prompt)
elif result in (EResult.TryAnotherCM, EResult.ServiceUnavailable):
if prompt_for_unavailable and result == EResult.ServiceUnavailable:
while True:
answer = _cli_input("Steam is down. Keep retrying? [y/n]: ").lower()
if answer in 'yn': break
prompt_for_unavailable = False
if answer == 'n': break
self.reconnect(maxdelay=15) # implements reconnect throttling
result = self.login(username, password, None, auth_code, two_factor_code)
return result
|
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
start = time()
if self.connection.connect(server_addr):
break
diff = time() - start
self._LOG.debug("Failed to connect. Retrying...")
if diff < 5:
self.sleep(5 - diff)
self.current_server_addr = server_addr
self.connected = True
self.emit(self.EVENT_CONNECTED)
self._recv_loop = gevent.spawn(self._recv_messages)
self._connecting = False
return True
|
python
|
{
"resource": ""
}
|
q21658
|
CMServerList.clear
|
train
|
def clear(self):
"""Clears the server list"""
if len(self.list):
self._LOG.debug("List cleared.")
self.list.clear()
|
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:
self._LOG.error("GetCMList failed with %s" % repr(result))
return False
serverlist = resp['response']['serverlist']
self._LOG.debug("Recieved %d servers from WebAPI" % len(serverlist))
def str_to_tuple(serveraddr):
ip, port = serveraddr.split(':')
return str(ip), int(port)
self.clear()
self.merge_list(map(str_to_tuple, serverlist))
return True
|
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.")
for key in self.list:
self.mark_good(key)
|
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`
"""
self.list[server_addr].update({'quality': CMServerList.Good, 'timestamp': time()})
|
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
:type server_addr: :class:`tuple`
"""
self._LOG.debug("Marking %s as Bad." % repr(server_addr))
self.list[server_addr].update({'quality': CMServerList.Bad, 'timestamp': time()})
|
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:
if (ip, port) not in self.list:
self.mark_good((ip, port))
if len(self.list) > total:
self._LOG.debug("Added %d new CM addresses." % (len(self.list) - total))
|
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`
"""
if isinstance(steamid, SteamUser):
steamid = steamid.steam_id
self._steam.send(MsgProto(EMsg.ClientRemoveFriend), {'friendid': steamid})
|
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 i, lvalue in enumerate(v):
params["%s[%d]" % (k, i)] = lvalue
kwargs = {'params': params} if method == "GET" else {'data': params} # params to data for POST
if session is None: session = _make_session()
f = getattr(session, method.lower())
resp = f(url, stream=False, timeout=onetime['http_timeout'], **kwargs)
# we keep a reference of the last response instance on the caller
if caller is not None: caller.last_response = resp
# 4XX and 5XX will cause this to raise
resp.raise_for_status()
if onetime['raw']:
return resp.text
elif onetime['format'] == 'json':
return resp.json()
elif onetime['format'] == 'xml':
from lxml import etree as _etree
return _etree.fromstring(resp.content)
elif onetime['format'] == 'vdf':
import vdf as _vdf
return _vdf.loads(resp.text)
|
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
:type version: int
:param apihost: API hostname
:type apihost: str
:param https: whether to use HTTPS
:type https: bool
:param params: parameters for endpoint
:type params: dict
:return: endpoint response
:rtype: :class:`dict`, :class:`lxml.etree.Element`, :class:`str`
"""
url = u"%s://%s/%s/%s/v%s/" % (
'https' if https else 'http', apihost, interface, method, version)
return webapi_request(url, 'GET', caller=caller, session=session, params=params)
|
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
:type version: int
:param apihost: API hostname
:type apihost: str
:param https: whether to use HTTPS
:type https: bool
:param params: parameters for endpoint
:type params: dict
:return: endpoint response
:rtype: :class:`dict`, :class:`lxml.etree.Element`, :class:`str`
"""
url = "%s://%s/%s/%s/v%s/" % (
'https' if https else 'http', apihost, interface, method, version)
return webapi_request(url, 'POST', caller=caller, session=session, params=params)
|
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,
apihost=self.apihost,
caller=None,
session=self.session,
params={'format': 'json',
'key': self.key,
},
)
|
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)
self.interfaces = []
# create interface instances from response
for interface in interfaces:
obj = WebAPIInterface(interface, parent=self)
self.interfaces.append(obj)
setattr(self, obj.name, obj)
|
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: :class:`dict`, :class:`lxml.etree.Element` or :class:`str`
"""
interface, method = method_path.split('.', 1)
return getattr(getattr(self, interface), method)(**kwargs)
|
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 = get_um(method_name)
if proto is None:
return None
message = proto()
self._data[message] = method_name
return message
|
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):
message = self.get(message)
if message not in self._data:
raise ValueError("Supplied message is invalid. Use 'get' method.")
if params:
proto_fill_from_dict(message, params)
capsule = MsgProto(EMsg.ClientServiceMethod)
capsule.body.method_name = self._data[message]
capsule.body.serialized_method = message.SerializeToString()
return self._steam.send_job(capsule)
|
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`
:return: response proto message instance
:rtype: (proto message, :class:`.UnifiedMessageError`)
:raises: :class:`gevent.Timeout`
"""
job_id = self.send(message, params)
resp = self.wait_event(job_id, timeout, raises=raises)
return (None, None) if resp is None else resp
|
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
:rtype: :class:`bytes`
"""
self.offset += n
return self.data[self.offset - n:self.offset]
|
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")
result = self.data[self.offset:null_index] # bytes without the terminator
self.offset = null_index + len(terminator) # advance offset past terminator
return result
|
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`
"""
data = _unpack_from(format_text, self.data, self.offset)
self.offset += _calcsize(format_text)
return data
|
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 a instance of protobuf message")
data = {}
for desc, field in message.ListFields():
if desc.type == desc.TYPE_MESSAGE:
if desc.label == desc.LABEL_REPEATED:
data[desc.name] = list(map(proto_to_dict, field))
else:
data[desc.name] = proto_to_dict(field)
else:
data[desc.name] = list(field) if desc.label == desc.LABEL_REPEATED else field
return data
|
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: generator object
:rtype: :class:`generator`
"""
for i in _range(0, len(arr), size):
yield arr[i:i+size]
|
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 = (set_proto_bit(header.msg)
if header.proto
else header.msg
)
message.body.payload = header.serialize() + body
self.steam.send(message)
|
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)
if not match:
return None
interface, method, version = match[0]
if interface not in service_lookup:
return None
package = import_module(service_lookup[interface])
service = getattr(package, interface, None)
if service is None:
return None
for method_desc in service.GetDescriptor().methods:
name = "%s.%s#%d" % (interface, method_desc.name, 1)
method_lookup[(name, False)] = getattr(package, method_desc.input_type.full_name, None)
method_lookup[(name, True)] = getattr(package, method_desc.output_type.full_name, None)
return method_lookup[key]
|
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:
etype, universe = args
elif length == 3:
etype, universe, instance = args
else:
raise TypeError("Takes at most 4 arguments (%d given)" % length)
if len(kwargs) > 0:
etype = kwargs.get('type', etype)
universe = kwargs.get('universe', universe)
instance = kwargs.get('instance', instance)
etype = (EType(etype)
if isinstance(etype, (int, EType))
else EType[etype]
)
universe = (EUniverse(universe)
if isinstance(universe, (int, EUniverse))
else EUniverse[universe]
)
if instance is None:
instance = 1 if etype in (EType.Individual, EType.GameServer) else 0
assert instance <= 0xffffF, "instance larger than 20bits"
return (universe << 56) | (etype << 52) | (instance << 32) | accountid
|
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]
https://steamcommunity.com/profiles/76561197960265740
https://steamcommunity.com/id/johnc
"""
match = re.match(r'^(?P<clean_url>https?://steamcommunity.com/'
r'(?P<type>profiles|id|gid|groups)/(?P<value>.*?))(?:/(?:.*)?)?$', url)
if not match:
return None
web = make_requests_session()
try:
# user profiles
if match.group('type') in ('id', 'profiles'):
text = web.get(match.group('clean_url'), timeout=http_timeout).text
data_match = re.search("g_rgProfileData = (?P<json>{.*?});[ \t\r]*\n", text)
if data_match:
data = json.loads(data_match.group('json'))
return int(data['steamid'])
# group profiles
else:
text = web.get(match.group('clean_url'), timeout=http_timeout).text
data_match = re.search("'steam://friends/joinchat/(?P<steamid>\d+)'", text)
if data_match:
return int(data_match.group('steamid'))
except requests.exceptions.RequestException:
return None
|
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 self.id == 0 or self.instance != 0:
return False
if self.type == EType.GameServer:
if self.id == 0:
return False
if self.type == EType.AnonGameServer:
if self.id == 0 and self.instance == 0:
return False
return True
|
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},
...
]
"""
if 'geo_location_ip' in kw:
kw['geo_location_ip'] = ip_to_int(kw['geo_location_ip'])
kw['filter_text'] = filter_text
kw['max_servers'] = max_servers
resp = self._s.send_job_and_wait(MsgProto(EMsg.ClientGMSServerQuery),
kw,
timeout=timeout,
)
if resp is None:
return None
resp = proto_to_dict(resp)
for server in resp['servers']:
server['server_ip'] = ip_from_int(server['server_ip'])
return resp['servers']
|
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",
{"server_steamids": server_steam_ids},
timeout=timeout,
)
if error:
raise error
if resp is None:
return None
return {SteamID(server.steamid): server.addr for server in resp.servers}
|
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",
{"server_ips": server_ips},
timeout=timeout,
)
if error:
raise error
if resp is None:
return None
return {server.addr: SteamID(server.steamid) for server in resp.servers}
|
python
|
{
"resource": ""
}
|
q21687
|
Account.request_validation_mail
|
train
|
def request_validation_mail(self):
"""Request validation email
:return: result
:rtype: :class:`.EResult`
"""
message = Msg(EMsg.ClientRequestValidationMail, extended=True)
resp = self.send_job_and_wait(message, timeout=10)
if resp is None:
return EResult.Timeout
else:
return EResult(resp.eresult)
|
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
resp = self.send_job_and_wait(message, timeout=10)
if resp is None:
return EResult.Timeout
else:
return EResult(resp.eresult)
|
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
"""
message = Msg(EMsg.ClientPasswordChange3, extended=True)
message.body.password = password
message.body.new_password = new_password
message.body.code = email_code
resp = self.send_job_and_wait(message, timeout=10)
if resp is None:
return EResult.Timeout
else:
return EResult(resp.eresult)
|
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 is None and wait_pstate:
self._steam.request_persona_state([self.steam_id])
self._pstate_ready.wait(timeout=5)
return getattr(self._pstate, field_name)
return None
|
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:
for kv in kvs:
data[kv.key] = kv.value
return data
|
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:
ahash = 'fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb'
sizes = {
0: '',
1: '_medium',
2: '_full',
}
url = "http://cdn.akamai.steamstatic.com/steamcommunity/public/images/avatars/%s/%s%s.jpg"
return url % (ahash[:2], ahash, sizes[size])
|
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,
'chat_entry_type': EChatEntryType.ChatMsg,
'message': message.encode('utf8'),
})
|
python
|
{
"resource": ""
}
|
q21694
|
ConstantRateLimit.wait
|
train
|
def wait(self):
"""Blocks until the rate is met"""
now = _monotonic()
if now < self._ref:
delay = max(0, self._ref - now)
self.sleep_func(delay)
self._update_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},
timeout=timeout
)
if resp is None:
return EResult.Timeout
elif resp.eresult == EResult.OK:
return resp.player_count
else:
return EResult(resp.eresult)
|
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 = message.body.apps.add()
app_info.only_public = False
if isinstance(app, tuple):
app_info.appid, app_info.access_token = app
else:
app_info.appid = app
for package in packages:
package_info = message.body.packages.add()
if isinstance(package, tuple):
package_info.appid, package_info.access_token = package
else:
package_info.packageid = package
message.body.meta_data_only = False
job_id = self.send_job(message)
data = dict(apps={}, packages={})
while True:
chunk = self.wait_event(job_id, timeout=timeout)
if chunk is None: return
chunk = chunk[0].body
for app in chunk.apps:
data['apps'][app.appid] = vdf.loads(app.buffer[:-1].decode('utf-8', 'replace'))['appinfo']
for pkg in chunk.packages:
data['packages'][pkg.packageid] = vdf.binary_loads(pkg.buffer[4:])[str(pkg.packageid)]
if not chunk.response_pending:
break
return data
|
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),
{
'since_change_number': change_number,
'send_app_info_changes': app_changes,
'send_package_info_changes': package_changes,
},
timeout=15
)
|
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
"""
return self.send_job_and_wait(MsgProto(EMsg.ClientGetAppOwnershipTicket),
{'app_id': app_id},
timeout=15
)
|
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>`_
:rtype: proto message
"""
return self.send_job_and_wait(MsgProto(EMsg.ClientGetDepotDecryptionKey),
{
'depot_id': depot_id,
'app_id': app_id,
},
timeout=15
)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.