code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
Simply calls out to easy_install --upgrade
'''
parser.add_argument('packages', nargs='*', default=local_packages(),
help='Packages to upgrade (defaults to all installed packages)')
parser.add_argument('-n', '--dry-run', action='store_true',
help='Print upgrade actions without run... | def cli(parser) | Simply calls out to easy_install --upgrade | 4.095095 | 3.122367 | 1.311535 |
if self.upload_allowed():
form = self.get_upload_form()
result = {}
if form.is_valid():
storage = self.get_storage()
result['is_valid'] = True
info = form.stash(storage, self.request.path)
result.update(... | def post(self, *args, **kwargs) | Save file and return saved info or report errors. | 2.901733 | 2.7418 | 1.058332 |
return self.form_class(self.request.POST, self.request.FILES) | def get_upload_form(self) | Construct form for accepting file upload. | 3.93898 | 2.725744 | 1.445102 |
req = urllib.request.Request(location)
with urllib.request.urlopen(req) as response:
the_page = response.read().decode()
return the_page | def from_url(location) | HTTP request for page at location returned as string
malformed url returns ValueError
nonexistant IP returns URLError
wrong subnet IP return URLError
reachable IP, no HTTP server returns URLError
reachable IP, HTTP, wrong page returns HTTPError | 2.634427 | 2.802064 | 0.940174 |
class _URLBase(str):
@property
def hostname(self):
return urlsplit(self).hostname
#
# may want to suppress ParseError in the event that it was caused
# by a none bridge device although this seems unlikely
try:
xml_str = from_url(location)
excep... | def parse_description_xml(location) | Extract serial number, base ip, and img url from description.xml
missing data from XML returns AttributeError
malformed XML returns ParseError
Refer to included example for URLBase and serialNumber elements | 4.884008 | 4.534857 | 1.076993 |
from ipaddress import ip_address
try:
ip_address(baseip)
except ValueError:
#
# logger.warning("Format of internalipaddress changed: %s", baseip)
if 'http' not in baseip[0:4].lower():
baseip = urlunsplit(['http', baseip, '', '', ''])
spl = urlsplit(b... | def _build_from(baseip) | Build URL for description.xml from ip | 4.619961 | 4.162504 | 1.109899 |
try:
json_str = from_url('https://www.meethue.com/api/nupnp')
except urllib.request.HTTPError as error:
logger.error("Problem at portal: %s", error)
raise
except urllib.request.URLError as error:
logger.warning("Problem reaching portal: %s", error)
return []
... | def parse_portal_json() | Extract id, ip from https://www.meethue.com/api/nupnp
Note: the ip is only the base and needs xml file appended, and
the id is not exactly the same as the serial number in the xml | 3.382506 | 3.035306 | 1.114387 |
ssdp_list = ssdp_discover("ssdp:all", timeout=5)
#import pickle
#with open("ssdp.pickle", "wb") as f:
#pickle.dump(ssdp_list,f)
bridges_from_ssdp = [u for u in ssdp_list if 'IpBridge' in u.server]
logger.info('SSDP returned %d items with %d Hue bridges(s).',
len(ssdp_li... | def via_upnp() | Use SSDP as described by the Philips guide | 4.378686 | 4.250545 | 1.030147 |
bridges_from_portal = parse_portal_json()
logger.info('Portal returned %d Hue bridges(s).',
len(bridges_from_portal))
# Confirm Portal gave an accessible bridge device by reading from the returned
# location. Should look like: http://192.168.0.1/description.xml
found_bridges =... | def via_nupnp() | Use method 2 as described by the Philips guide | 6.310696 | 6.246546 | 1.01027 |
import socket
import ipaddress
import httpfind
bridges_from_scan = []
hosts = socket.gethostbyname_ex(socket.gethostname())[2]
for host in hosts:
bridges_from_scan += httpfind.survey(
# TODO: how do we determine subnet configuration?
ipaddress.ip_interface(ho... | def via_scan() | IP scan - now implemented | 5.941772 | 6.006743 | 0.989184 |
found_bridges = {}
# Validate caller's provided list
try:
prior_bridges_list = prior_bridges.items()
except AttributeError:
# if caller didnt provide dict then assume single SN or None
# in either case, the discovery must be executed
run_discovery = True
else:
... | def find_bridges(prior_bridges=None) | Confirm or locate IP addresses of Philips Hue bridges.
`prior_bridges` -- optional list of bridge serial numbers
* omitted - all discovered bridges returned as dictionary
* single string - returns IP as string or None
* dictionary - validate provided ip's before attempting discovery
* collection or... | 5.095532 | 4.840117 | 1.052771 |
package_a = self.processor._u2p(a['msg']['update']['title'])[0]
package_b = self.processor._u2p(b['msg']['update']['title'])[0]
if package_a != package_b:
return False
return True | def matches(self, a, b, **config) | The message must match by package | 5.227784 | 4.433794 | 1.179077 |
'''
Currently a cop-out -- just calls easy_install
'''
parser.add_argument('-n', '--dry-run', action='store_true', help='Print uninstall actions without running')
parser.add_argument('packages', nargs='+', help='Packages to install')
opts = parser.parse_args()
for package in opts.packages:
... | def cli(parser) | Currently a cop-out -- just calls easy_install | 4.807019 | 2.941041 | 1.634462 |
val = m_dict
keys = keys.split(delimiter)
for key in keys:
try:
val = val[key]
except KeyError:
return default
except TypeError:
return default
return val | def mget(m_dict, keys, default=None, delimiter=':') | :param m_dict: A dictionary to search inside of
:type m_dict: dict
:param keys: A list of keys
:type keys: str
:param default: A default value to return if none found
:param delimiter: The delimiter used in the keys list
:type delimiter: str
:return: The value according to the keys list | 2.085219 | 3.098752 | 0.672922 |
val = m_dict
keys = keys.split(delimiter)
for i, key in enumerate(keys):
try:
if i == len(keys) - 1:
val[key] = value
return
else:
val = val[key]
except KeyError:
if i == len(keys) - 1:
v... | def mset(m_dict, keys, value, delimiter=':') | :param m_dict: A dictionary to set the value inside of
:type m_dict: dict
:param keys: A list of keys
:type keys: str
:param value: The value to set inside of the dictionary
:param delimiter: The delimiter used in the keys list
:type delimiter: str | 1.793399 | 2.011605 | 0.891526 |
if not grain:
return InstantTime.day
if grain.lower() == 'week':
return InstantTime.week
return InstantTime.day | def parse_grain(grain) | Parse a string to a granularity, e.g. "Day" to InstantTime.day.
:param grain: a string representing a granularity. | 7.509722 | 4.059483 | 1.849921 |
package = pypi.Package(self.package_name)
self.licence = package.licence()
if self.is_parseable:
self.latest_version = package.latest_version()
self.next_version = package.next_version(self.current_version)
self.diff_status = pypi.version_diff(self.cu... | def update_from_pypi(self) | Call get_latest_version and then save the object. | 3.622229 | 3.531724 | 1.025626 |
if not self._s or not hasattr(self._s, "close"):
return
try:
self._s.close()
except BaseException:
pass | def close(self) | close conn | 4.159119 | 3.604678 | 1.153812 |
if hasattr(data, 'seek'):
data.seek(0)
chunk_size = CHUNK_SIZE
if zlib_compress:
chunk_size = BLOCK_SIZE
compressor = compressobj(compress_level)
while 1:
binarydata = data.read(chunk_size)
if binarydata == '':
... | def sendfile(self, data, zlib_compress=None, compress_level=6) | Send data from a file object | 2.521851 | 2.508628 | 1.005271 |
class GhostedDistArrayAny(BaseClass):
def __init__(self, shape, dtype):
# call the parent Ctor
BaseClass.__init__(self, shape, dtype)
def setNumberOfGhosts(self, numGhosts):
# expose each window to other PE domains
... | def ghostedDistArrayFactory(BaseClass) | Returns a ghosted distributed array class that derives from BaseClass
@param BaseClass base class, e.g. DistArray or MaskedDistArray
@return ghosted dist array class | 4.461843 | 4.537493 | 0.983328 |
a = numpy.array(arry, dtype)
res = GhostedDistArray(a.shape, a.dtype)
res.setNumberOfGhosts(numGhosts)
res[:] = a
return res | def gdaArray(arry, dtype, numGhosts=1) | ghosted distributed array constructor
@param arry numpy-like array
@param numGhosts the number of ghosts (>= 0) | 4.947282 | 5.082589 | 0.973378 |
res = GhostedDistArray(shape, dtype)
res.setNumberOfGhosts(numGhosts)
res[:] = 0
return res | def gdaZeros(shape, dtype, numGhosts=1) | ghosted distributed array zero constructor
@param shape the shape of the array
@param dtype the numpy data type
@param numGhosts the number of ghosts (>= 0) | 6.391194 | 5.117797 | 1.248818 |
res = GhostedDistArray(shape, dtype)
res.setNumberOfGhosts(numGhosts)
res[:] = 1
return res | def gdaOnes(shape, dtype, numGhosts=1) | ghosted distributed array one constructor
@param shape the shape of the array
@param dtype the numpy data type
@param numGhosts the number of ghosts (>= 0) | 6.295249 | 5.099219 | 1.234551 |
a = numpy.array(arry, dtype)
res = GhostedMaskedDistArray(a.shape, a.dtype)
res.mask = mask
res.setNumberOfGhosts(numGhosts)
res[:] = a
return res | def gmdaArray(arry, dtype, mask=None, numGhosts=1) | ghosted distributed array constructor
@param arry numpy-like array
@param numGhosts the number of ghosts (>= 0) | 4.90689 | 5.6768 | 0.864376 |
res = GhostedMaskedDistArray(shape, dtype)
res.mas = mask
res.setNumberOfGhosts(numGhosts)
res[:] = 0
return res | def gmdaZeros(shape, dtype, mask=None, numGhosts=1) | ghosted distributed array zero constructor
@param shape the shape of the array
@param dtype the numpy data type
@param numGhosts the number of ghosts (>= 0) | 7.393402 | 6.60742 | 1.118954 |
res = GhostedMaskedDistArray(shape, dtype)
res.mask = mask
res.setNumberOfGhosts(numGhosts)
res[:] = 1
return res | def gmdaOnes(shape, dtype, mask=None, numGhosts=1) | ghosted distributed array one constructor
@param shape the shape of the array
@param dtype the numpy data type
@param numGhosts the number of ghosts (>= 0) | 5.629447 | 5.550841 | 1.014161 |
if isinstance(storage, LazyObject):
# Unwrap lazy storage class
storage._setup()
cls = storage._wrapped.__class__
else:
cls = storage.__class__
return signing.dumps({
'name': name,
'storage': '%s.%s' % (cls.__module__, cls.__name__)
}, salt=url) | def serialize_upload(name, storage, url) | Serialize uploaded file by name and storage. Namespaced by the upload url. | 3.950765 | 4.04408 | 0.976925 |
result = {'name': None, 'storage': None}
try:
result = signing.loads(value, salt=url)
except signing.BadSignature:
# TODO: Log invalid signature
pass
else:
try:
result['storage'] = get_storage_class(result['storage'])
except (ImproperlyConfigured,... | def deserialize_upload(value, url) | Restore file and name and storage from serialized value and the upload url. | 3.639227 | 3.236156 | 1.124552 |
upload = None
result = deserialize_upload(value, url)
filename = result['name']
storage_class = result['storage']
if storage_class and filename:
storage = storage_class()
if storage.exists(filename):
upload = storage.open(filename)
upload.name = os.path.b... | def open_stored_file(value, url) | Deserialize value for a given upload url and return open file.
Returns None if deserialization fails. | 3.886325 | 3.702398 | 1.049678 |
if isinstance(action, types.StringTypes):
action = action.lower()
if action not in ['learn', 'forget', 'report', 'revoke']:
raise SpamCError('The action option is invalid')
return action | def _check_action(action) | check for invalid actions | 9.203675 | 8.185699 | 1.12436 |
resp = conn.socket().makefile('rb', -1)
resp_dict = dict(
code=0,
message='',
isspam=False,
score=0.0,
basescore=0.0,
report=[],
symbols=[],
headers={},
)
if cmd == 'TELL':
resp_dict['didset'] = False
resp_dict['didrem... | def get_response(cmd, conn) | Return a response | 2.805327 | 2.801777 | 1.001267 |
if self.host is None:
connector = SpamCUnixConnector
conn = connector(self.socket_file, self.backend_mod)
else:
connector = SpamCTcpConnector
conn = connector(
self.host,
self.port,
self.backend_mod,... | def get_connection(self) | Creates a new connection | 4.964543 | 4.741038 | 1.047143 |
cmd_header = "%s %s" % (cmd, PROTOCOL_VERSION)
len_header = "Content-length: %s" % msg_length
headers = [cmd_header, len_header]
if self.user:
user_header = "User: %s" % self.user
headers.append(user_header)
if self.gzip:
headers.appen... | def get_headers(self, cmd, msg_length, extra_headers) | Returns the headers string based on command to execute | 2.261611 | 2.25424 | 1.00327 |
tries = 0
while 1:
conn = None
try:
conn = self.get_connection()
if hasattr(msg, 'read') and hasattr(msg, 'fileno'):
msg_length = str(os.fstat(msg.fileno()).st_size)
elif hasattr(msg, 'read'):
... | def perform(self, cmd, msg='', extra_headers=None) | Perform the call | 2.566665 | 2.574829 | 0.996829 |
action = _check_action(action)
mode = learnas.upper()
headers = {
'Message-class': '',
'Set': 'local',
}
if action == 'learn':
if mode == 'SPAM':
headers['Message-class'] = 'spam'
elif mode in ['HAM', 'NOT... | def tell(self, msg, action, learnas='') | Tell what type of we are to process and what should be done
with that message. This includes setting or removing a local
or a remote database (learning, reporting, forgetting, revoking). | 3.96967 | 3.6363 | 1.091679 |
if not isinstance(learnas, types.StringTypes):
raise SpamCError('The learnas option is invalid')
if learnas.lower() == 'forget':
resp = self.tell(msg, 'forget')
else:
resp = self.tell(msg, 'learn', learnas)
return resp | def learn(self, msg, learnas) | Learn message as spam/ham or forget | 5.11456 | 4.197757 | 1.218403 |
''' generates a new, random secret key at the given location on the
filesystem and returns its path
'''
fs = path.abspath(path.expanduser(filepath))
with open(fs, 'wb') as outfile:
outfile.write(Fernet.generate_key())
chmod(fs, 0o400)
return fs | def generate_key(filepath) | generates a new, random secret key at the given location on the
filesystem and returns its path | 5.078948 | 3.126523 | 1.624472 |
if key is None:
if keyfile is None:
key = environ.get('CRYPTOYAML_SECRET')
if key is None:
raise MissingKeyException(
'''You must either provide a key value,'''
''' a path to a key or its value via the environment variable ... | def get_key(key=None, keyfile=None) | returns a key given either its value, a path to it on the filesystem
or as last resort it checks the environment variable CRYPTOYAML_SECRET | 4.016831 | 3.052648 | 1.315851 |
if path.exists(self.filepath):
with open(self.filepath, 'rb') as infile:
self.data = yaml.load(
self.fernet.decrypt(infile.read()))
else:
self.data = dict() | def read(self) | Reads and decrypts data from the filesystem | 4.0453 | 3.600857 | 1.123427 |
with open(self.filepath, 'wb') as outfile:
outfile.write(
self.fernet.encrypt(
yaml.dump(self.data, encoding='utf-8'))) | def write(self) | Encrypts and writes the current state back onto the filesystem | 5.078658 | 4.523239 | 1.122792 |
return_value = None
for instance in instances + [None]:
if not self.can_execute(instance):
continue
result = self.is_active(instance, condition)
if result is False:
return False
elif result is True:
... | def has_active_condition(self, condition, instances) | Given a list of instances, and the condition active for
this switch, returns a boolean representing if the
conditional is met, including a non-instance default. | 3.472565 | 3.476985 | 0.998729 |
self._version_data["source"] = "Local"
try:
from homeassistant.const import __version__ as localversion
self._version = localversion
_LOGGER.debug("Version: %s", self.version)
_LOGGER.debug("Version data: %s", self.version_data)
except I... | async def get_local_version(self) | Get the local installed version. | 3.640295 | 3.363689 | 1.082233 |
self._version_data["beta"] = self.beta
self._version_data["source"] = "PyPi"
info_version = None
last_release = None
try:
async with async_timeout.timeout(5, loop=self.loop):
response = await self.session.get(URL["pypi"])
data = ... | async def get_pypi_version(self) | Get version published to PyPi. | 2.413835 | 2.366017 | 1.02021 |
if self.image not in IMAGES:
_LOGGER.warning("%s is not a valid image using default", self.image)
self.image = "default"
board = BOARDS.get(self.image, BOARDS["default"])
self._version_data["source"] = "Hassio"
self._version_data["beta"] = self.beta
... | async def get_hassio_version(self) | Get version published for hassio. | 2.483642 | 2.437996 | 1.018723 |
if self.image not in IMAGES:
_LOGGER.warning("%s is not a valid image using default", self.image)
self.image = "default"
self._version_data["beta"] = self.beta
self._version_data["source"] = "Docker"
self._version_data["image"] = IMAGES[self.image]["dock... | async def get_docker_version(self) | Get version published for docker. | 2.639834 | 2.591474 | 1.018661 |
if playbook.startswith(fs_prefix):
return True, playbook[len(fs_prefix):]
else:
return False, playbook.split('/')[-1] | def relative_playbook(playbook) | Returns a tuple (controlled, playbook).
- controlled is a boolean indicating whether or not we think that the
playbook being run was checked in to our ansible git repo.
- playbook is the relative file path of the playbook. | 3.823631 | 4.383647 | 0.872249 |
submitter_a = a['msg']['override']['submitter']['name']
submitter_b = b['msg']['override']['submitter']['name']
if submitter_a != submitter_b:
return False
return True | def matches(self, a, b, **config) | The message must match by username | 4.27659 | 3.704409 | 1.15446 |
if not self._stream_process_started: # pragma: no cover
if sys.platform.startswith("win"): # if we're on windows we can't expect multiprocessing to work
self._stream_process_started = True
self._stream()
self._stream_process_started = True
... | def start_stream_subscriber(self) | Starts the stream consumer's main loop.
Called when the stream consumer has been set up with the correct callbacks. | 4.936286 | 4.864153 | 1.01483 |
if not self._stream_process_started:
raise StreamSubscriberNotStarted()
def real_decorator(func):
if not self._on_delete:
raise DeleteRequired()
if hasattr(self.factory, 'datasift') and 'send_message' in self.factory.datasift: # pragma: no c... | def subscribe(self, stream) | Subscribe to a stream.
:param stream: stream to subscribe to
:type stream: str
:raises: :class:`~datasift.exceptions.StreamSubscriberNotStarted`, :class:`~datasift.exceptions.DeleteRequired`, :class:`~datasift.exceptions.StreamNotConnected`
Used as a decorator, eg.::
... | 5.839667 | 4.200112 | 1.39036 |
self._on_open = func
if self.opened: # pragma: no cover
self._on_open(self)
return func | def on_open(self, func) | Function to set the callback for the opening of a stream.
Can be called manually::
def open_callback(data):
setup_stream()
client.on_open(open_callback)
or as a decorator::
@client.on_open
def open_callback()... | 4.267418 | 5.014763 | 0.850971 |
from twisted.internet import ssl
options = ssl.optionsForClientTLS(hostname=WEBSOCKET_HOST)
connectWS(self.factory, options)
else:
connectWS(self.factory)
reactor.run() | def _stream(self): # pragma: no cover
self.factory.protocol = LiveStream
self.factory.datasift = {
'on_open': self._on_open,
'on_close': self._on_close,
'on_message': self._on_message,
'send_message': None
}
if self.config.ssl | Runs in a sub-process to perform stream consumption | 5.299321 | 4.859474 | 1.090513 |
return self.request.post('compile', data=dict(csdl=csdl)) | def compile(self, csdl) | Compile the given CSDL.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/compile
Raises a DataSiftApiException for any error given by the REST API, including CSDL compilation.
:param csdl: CSDL to compile
:type csdl: str
:returns: ... | 9.569805 | 7.074335 | 1.35275 |
try:
self.validate(csdl)
except DataSiftApiException as e:
if e.response.status_code == 400:
return False
else:
raise e
return True | def is_valid(self, csdl) | Checks if the given CSDL is valid.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/validate
:param csdl: CSDL to validate
:type csdl: str
:returns: Boolean indicating the validity of the CSDL
:rtype: bool
:raises: :clas... | 3.575895 | 2.557941 | 1.397958 |
return self.request.get('usage', params=dict(period=period)) | def usage(self, period='hour') | Check the number of objects processed and delivered for a given time period
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/usage
:param period: (optional) time period to measure usage for, can be one of "day", "hour" or "current" (5 minutes), default is hour
... | 11.215143 | 8.430071 | 1.330374 |
if hash:
return self.request.get('dpu', params=dict(hash=hash))
if historics_id:
return self.request.get('dpu', params=dict(historics_id=historics_id)) | def dpu(self, hash=None, historics_id=None) | Calculate the DPU cost of consuming a stream.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/dpu
:param hash: target CSDL filter hash
:type hash: str
:returns: dict with extra response data
:rtype: :class:`~datasift.request.DictRe... | 2.125539 | 2.425215 | 0.876433 |
params = {'id': subscription_id}
if size:
params['size'] = size
if cursor:
params['cursor'] = cursor
raw = self.request('get', 'pull', params=params)
def pull_parser(headers, data):
pull_type = headers.get("X-DataSift-Format")
... | def pull(self, subscription_id, size=None, cursor=None) | Pulls a series of interactions from the queue for the given subscription ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pull
:param subscription_id: The ID of the subscription to pull interactions for
:type subscription_id: str
:param siz... | 3.854506 | 3.720495 | 1.03602 |
def _get_player_profile(self, player_handle):
url = self.pubg_url + player_handle
response = requests.request("GET", url, headers=self.headers)
data = json.loads(response.text)
return data | Returns pubg player profile from PUBG api, no filtering
:param player_handle: player PUBG profile name
:type player_handle: str
:return: return json from PUBG API
:rtype: dict | null | null | null | |
def player(self, player_handle):
try:
url = self.pubg_url + player_handle
response = requests.request("GET", url, headers=self.headers)
return json.loads(response.text)
except BaseException as error:
print('Unhandled exception: ' + str(erro... | Returns the full set of data on a player, no filtering | null | null | null | |
def player_s(self, sid) :
try:
url = self.pubg_url_steam.format(str(sid))
response = requests.request("GET", url, headers=self.headers)
return json.loads(response.text)
except BaseException as error:
print('Unhandled exception: ' + st... | Returns the full set of data on a player, no filtering | null | null | null | |
def player_mode_stats(self, player_handle, game_mode=constants.GAME_MODE_WILDCARD, game_region=constants.GAME_REGION_WILDCARD):
if game_mode not in constants.GAME_MODES:
raise APIException("game_mode must be one of: solo, duo, squad, all")
if game_region not in constants.GAME_RE... | Returns the stats for a particular mode of play,
accepts solo, duo and squad. Will return both regional
and global stats. Default gamemode is solo
by Zac: Add parameter game_region to extract player stats by region directly | null | null | null | |
def _filter_gameplay_stats(self, data, game_mode, game_region):
return_data = []
for stat in data['Stats']:
if self._is_target_game_mode(stat, game_mode) and self._is_target_region(stat, game_region):
return_data.append(stat)
return return_data | Returns gameplay stats that are filtered by game_mode and game_region.
:param data: Json of gameplay stats.
:type data: dict
:param game_mode: Target game mode.
:type game_mode: str
:param game_region: Target game region.
:type game_region:... | null | null | null | |
def _is_target_game_mode(self, stat, game_mode):
if game_mode == constants.GAME_MODE_WILDCARD:
return True
return stat['Match'] == game_mode | Returns if the stat matches target game mode.
:param stat: Json of gameplay stat.
:type stat: dict
:param game_mode: Target game mode.
:type game_mode: str
:return: return does the stat matches target game mode.
:rtype: bool | null | null | null | |
def _is_target_region(self, stat, game_region):
if game_region == constants.GAME_REGION_WILDCARD:
return True
return stat['Region'] == game_region | Returns if the stat matches target game region.
:param stat: Json of gameplay stat.
:type stat: dict
:param game_region: Target game region.
:type game_region: str
:return: return does the stat matches target game region.
:rtype: bool | null | null | null | |
def player_skill(self, player_handle, game_mode='solo'):
if game_mode not in constants.GAME_MODES:
raise APIException("game_mode must be one of: solo, duo, squad, all")
try:
data = self._get_player_profile(player_handle)
player_stats = {}
r... | Returns the current skill rating of the player for a specified gamemode,
default gamemode is solo | null | null | null | |
sz = MPI.COMM_WORLD.Get_size()
rk = MPI.COMM_WORLD.Get_rank()
iBegs = MPI.COMM_WORLD.gather(iBeg, root=0)
iEnds = MPI.COMM_WORLD.gather(iEnd, root=0)
jBegs = MPI.COMM_WORLD.gather(jBeg, root=0)
jEnds = MPI.COMM_WORLD.gather(jEnd, root=0)
arrays = MPI.COMM_WORLD.gather(numpy.array(data),... | def plot(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data, title='') | Plot distributed array
@param nxG number of global cells in x
@param nyG number of global cells in y
@param iBeg global starting index in x
@param iEnd global ending index in x
@param jBeg global starting index in y
@param jEnd global ending index in y
@param data local array
@param titl... | 2.018867 | 1.999248 | 1.009813 |
nxGHalf = nxG/2.
nyGHalf = nyG/2.
nxGQuart = nxGHalf/2.
nyGQuart = nyGHalf/2.
for i in range(data.shape[0]):
iG = iBeg + i
di = iG - nxG
for j in range(data.shape[1]):
jG = jBeg + j
dj = jG - 0.8*nyG
data[i, j] = numpy.floor(1.9*numpy.... | def setValues(nxG, nyG, iBeg, iEnd, jBeg, jEnd, data) | Set setValues
@param nxG number of global cells in x
@param nyG number of global cells in y
@param iBeg global starting index in x
@param iEnd global ending index in x
@param jBeg global starting index in y
@param jEnd global ending index in y
@param data local array | 2.820203 | 3.383623 | 0.833486 |
for d in self.dirs:
self.stdout.write("\033[0;34m" + ('%s\n' % d) + "\033[0m")
for f in self.files:
self.stdout.write('%s\n' % f) | def do_ls(self, nothing = '') | list files in current remote directory | 3.246134 | 3.151387 | 1.030065 |
path = path[0]
if path == "..":
self.current_path = "/".join(self.current_path[:-1].split("/")[0:-1]) + '/'
elif path == '/':
self.current_path = "/"
else:
if path[-1] == '/':
self.current_path += path
else:
... | def do_cd(self, path = '/') | change current working directory | 3.091664 | 3.098474 | 0.997802 |
path = path[0]
tmp_file_path = self.TMP_PATH + 'tmp'
if not os.path.exists(self.TMP_PATH):
os.makedirs(self.TMP_PATH)
f = self.n.downloadFile(self.current_path + path, tmp_file_path)
f = open(tmp_file_path, 'r')
self.stdout.write(f.read())
... | def do_cat(self, path) | display the contents of a file | 3.298804 | 3.275851 | 1.007007 |
path = path[0]
self.n.makeDirectory(self.current_path + path)
self.dirs = self.dir_complete() | def do_mkdir(self, path) | create a new directory | 13.526813 | 13.811393 | 0.979395 |
path = path[0]
self.n.delete(self.current_path + path)
self.dirs = self.dir_complete()
self.files = self.file_complete() | def do_rm(self, path) | delete a file or directory | 10.282 | 9.623501 | 1.068426 |
self.n.doMove(self.current_path + from_path,
self.current_path + to_path) | def do_mv(self, from_path, to_path, nothing = '') | move/rename a file or directory | 6.741108 | 5.828058 | 1.156665 |
s, metadata = self.n.getRegisterUserInfo()
pprint.PrettyPrinter(indent=2).pprint(metadata) | def do_account_info(self) | display account information | 21.724442 | 17.808262 | 1.219908 |
to_file = open(os.path.expanduser(to_path), "wb")
self.n.downloadFile(self.current_path + "/" + from_path, to_path) | def do_get(self, from_path, to_path) | Copy file from Ndrive to local file and print out out the metadata.
Examples:
Ndrive> get file.txt ~/ndrive-file.txt | 5.703535 | 5.893247 | 0.967809 |
from_file = open(os.path.expanduser(from_path), "rb")
self.n.put(self.current_path + "/" + from_path, to_path) | def do_put(self, from_path, to_path) | Copy local file to Ndrive
Examples:
Ndrive> put ~/test.txt ndrive-copy-test.txt | 4.815041 | 5.132432 | 0.93816 |
results = self.n.doSearch(string, full_path = self.current_path)
if results:
for r in results:
self.stdout.write("%s\n" % r['path']) | def do_search(self, string) | Search Ndrive for filenames containing the given string. | 6.491734 | 6.021329 | 1.078123 |
if not is_valid_type(source):
raise TypeError('source must be unicode')
from_list = make_char_list(string1)
if option == 's':
from_list = to_unichr(from_list)
return squeeze(from_list, source)
elif 'c' in option:
from_list = to_unichr(from_list)
from_list = ... | def tr(string1, string2, source, option='') | Replace or remove specific characters.
If not given option, then replace all characters in string1 with
the character in the same position in string2.
Following options are available:
c Replace all complemented characters in string1 with
the character in the same position in string2.... | 2.244809 | 2.102859 | 1.067504 |
'''
"Upload" a file to a service
This copies a file from the local filesystem into the ``DataService``'s
filesystem. If ``remove==True``, the file is moved rather than copied.
If ``filepath`` and ``service_path`` paths are the same, ``upload``
deletes the file if ``remo... | def upload(self, filepath, service_path, remove=False) | "Upload" a file to a service
This copies a file from the local filesystem into the ``DataService``'s
filesystem. If ``remove==True``, the file is moved rather than copied.
If ``filepath`` and ``service_path`` paths are the same, ``upload``
deletes the file if ``remove==True`` and retur... | 3.175745 | 1.870379 | 1.697916 |
'''
Returns a storage path for the archive and version
If the archive is versioned, the version number is used as the file
path and the archive path is the directory. If not, the archive path is
used as the file path.
Parameters
----------
version : str ... | def get_version_path(self, version=None) | Returns a storage path for the archive and version
If the archive is versioned, the version number is used as the file
path and the archive path is the directory. If not, the archive path is
used as the file path.
Parameters
----------
version : str or object
... | 3.604162 | 1.309604 | 2.7521 |
'''
Enter a new version to a DataArchive
Parameters
----------
filepath : str
The path to the file on your local file system
cache : bool
Turn on caching for this archive if not already on before update
remove : bool
removes... | def update(
self,
filepath,
cache=False,
remove=False,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None) | Enter a new version to a DataArchive
Parameters
----------
filepath : str
The path to the file on your local file system
cache : bool
Turn on caching for this archive if not already on before update
remove : bool
removes a file from your lo... | 3.744174 | 1.935491 | 1.934483 |
'''
Get default dependencies for archive
Get default dependencies from requirements file or (if no requirements
file) from previous version
'''
# Get default dependencies from requirements file
default_dependencies = {
k: v for k,
v in se... | def _get_default_dependencies(self) | Get default dependencies for archive
Get default dependencies from requirements file or (if no requirements
file) from previous version | 5.505514 | 3.582529 | 1.536767 |
'''
Opens a file for read/write
Parameters
----------
mode : str
Specifies the mode in which the file is opened (default 'r')
version : str
Version number of the file to open (default latest)
bumpversion : str
Version compone... | def open(
self,
mode='r',
version=None,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None,
*args,
**kwargs) | Opens a file for read/write
Parameters
----------
mode : str
Specifies the mode in which the file is opened (default 'r')
version : str
Version number of the file to open (default latest)
bumpversion : str
Version component to update on writ... | 3.987992 | 2.371002 | 1.681986 |
'''
Returns a local path for read/write
Parameters
----------
version : str
Version number of the file to retrieve (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion valu... | def get_local_path(
self,
version=None,
bumpversion=None,
prerelease=None,
dependencies=None,
metadata=None,
message=None) | Returns a local path for read/write
Parameters
----------
version : str
Version number of the file to retrieve (default latest)
bumpversion : str
Version component to update on write if archive is versioned. Valid
bumpversion values are 'major', 'min... | 4.140344 | 2.515204 | 1.646126 |
'''
Downloads a file from authority to local path
1. First checks in cache to check if file is there and if it is, is it
up to date
2. If it is not up to date, it will download the file to cache
'''
version = _process_version(self, version)
dirname, ... | def download(self, filepath, version=None) | Downloads a file from authority to local path
1. First checks in cache to check if file is there and if it is, is it
up to date
2. If it is not up to date, it will download the file to cache | 5.659094 | 4.051701 | 1.396721 |
'''
Delete the archive
.. warning::
Deleting an archive will erase all data and metadata permanently.
For help setting user permissions, see
:ref:`Administrative Tools <admin>`
'''
versions = self.get_versions()
self.api.manager.dele... | def delete(self) | Delete the archive
.. warning::
Deleting an archive will erase all data and metadata permanently.
For help setting user permissions, see
:ref:`Administrative Tools <admin>` | 2.99614 | 2.022636 | 1.481305 |
'''
Check whether the path exists and is a file
'''
version = _process_version(self, version)
path = self.get_version_path(version)
self.authority.fs.isfile(path, *args, **kwargs) | def isfile(self, version=None, *args, **kwargs) | Check whether the path exists and is a file | 6.111167 | 4.670944 | 1.308337 |
'''
Set the cache property to start/stop file caching for this archive
'''
version = _process_version(self, version)
if self.api.cache and self.api.cache.fs.isfile(
self.get_version_path(version)):
return True
return False | def is_cached(self, version=None) | Set the cache property to start/stop file caching for this archive | 10.56431 | 5.02469 | 2.10248 |
'''
Parameters
----------
version: str
string representing version number whose dependencies you are
looking up
'''
version = _process_version(self, version)
history = self.get_history()
for v in reversed(history):
if ... | def get_dependencies(self, version=None) | Parameters
----------
version: str
string representing version number whose dependencies you are
looking up | 6.564285 | 3.812266 | 1.721885 |
'''
Set tags for a given archive
'''
normed_tags = self.api.manager._normalize_tags(tags)
self.api.manager.add_tags(self.archive_name, normed_tags) | def add_tags(self, *tags) | Set tags for a given archive | 7.240599 | 5.167676 | 1.401133 |
if isinstance(file_like_obj, AsyncIOBaseWrapper):
return file_like_obj
if isinstance(file_like_obj, sync_io.FileIO):
return AsyncFileIOWrapper(file_like_obj)
if isinstance(file_like_obj, sync_io.BufferedRandom):
return AsyncBufferedRandomWrapper(file_like_obj)
if isins... | def wrap_file(file_like_obj) | Wrap a file like object in an async stream wrapper.
Files generated with `open()` may be one of several types. This
convenience function retruns the stream wrapped in the most appropriate
wrapper for the type. If the stream is already wrapped it is returned
unaltered. | 1.890267 | 1.762181 | 1.072686 |
raw = sync_io.StringIO(*args, **kwargs)
return AsyncStringIOWrapper(raw) | def StringIO(*args, **kwargs) | StringIO constructor shim for the async wrapper. | 9.176884 | 7.53589 | 1.217757 |
raw = sync_io.BytesIO(*args, **kwargs)
return AsyncBytesIOWrapper(raw) | def BytesIO(*args, **kwargs) | BytesIO constructor shim for the async wrapper. | 9.161456 | 7.050001 | 1.299497 |
return self._stream.seek(pos, whence) | async def seek(self, pos, whence=sync_io.SEEK_SET) | Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other
values are SEEK_CUR or 1 (move relative to current position, positive
or negative), and SEEK_END or 2 (move relative ... | 6.62888 | 12.685571 | 0.522553 |
if limit:
query = query.limit(limit)
if as_df:
results = read_sql(query.statement, self.engine)
else:
results = query.all()
return results | def _limit_and_df(self, query, limit, as_df=False) | adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame
:param bool as_df: if is set to True results return as pandas.DataFrame
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param int limit: maximum number of results
:return: query res... | 2.641517 | 3.46547 | 0.762239 |
if gene_name or gene_symbol:
query = query.join(models.Gene)
if gene_symbol:
query = query.filter(models.Gene.gene_symbol.like(gene_symbol))
if gene_name:
query = query.filter(models.Gene.gene_name.like(gene_name))
if ge... | def _join_gene(query, gene_name, gene_symbol, gene_id) | helper function to add a query join to Gene model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str gene_name: gene name
:param str gene_symbol: gene symbol
:param int gene_id: NCBI Gene identifier
:return: `sqlalchemy.orm.query.Query` object | 1.644503 | 1.813608 | 0.906758 |
if cas_rn or chemical_id or chemical_name or chemical_definition:
query = query.join(models.Chemical)
if cas_rn:
query = query.filter(models.Chemical.cas_rn.like(cas_rn))
if chemical_id:
query = query.filter(models.Chemical.chemical_... | def _join_chemical(query, cas_rn, chemical_id, chemical_name, chemical_definition) | helper function to add a query join to Chemical model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param cas_rn:
:param chemical_id:
:param chemical_name:
:param chemical_definition:
:return: `sqlalchemy.orm.query.Query` object | 1.49495 | 1.573221 | 0.950248 |
if disease_definition or disease_id or disease_name:
query = query.join(models.Disease)
if disease_definition:
query = query.filter(models.Disease.definition.like(disease_definition))
if disease_id:
query = query.filter(models.Diseas... | def _join_disease(query, disease_definition, disease_id, disease_name) | helper function to add a query join to Disease model
:param sqlalchemy.orm.query.Query query: SQL Alchemy query
:param disease_definition:
:param str disease_id: see :attr:`models.Disease.disease_id`
:param disease_name:
:rtype: sqlalchemy.orm.query.Query | 1.558353 | 1.576169 | 0.988697 |
if pathway_id or pathway_name:
if pathway_id:
query = query.filter(models.Pathway.pathway_id.like(pathway_id))
if pathway_name:
query = query.filter(models.Pathway.pathway_name.like(pathway_name))
return query | def _join_pathway(query, pathway_id, pathway_name) | helper function to add a query join to Pathway model
:param `sqlalchemy.orm.query.Query` query: SQL Alchemy query
:param str pathway_id: pathway identifier
:param str pathway_name: pathway name
:return: `sqlalchemy.orm.query.Query` object | 1.824798 | 2.06517 | 0.883607 |
q = self.session.query(models.Disease)
if disease_name:
q = q.filter(models.Disease.disease_name.like(disease_name))
if disease_id:
q = q.filter(models.Disease.disease_id == disease_id)
if definition:
q = q.filter(models.Disease.definition.... | def get_disease(self, disease_name=None, disease_id=None, definition=None, parent_ids=None, tree_numbers=None,
parent_tree_numbers=None, slim_mapping=None, synonym=None, alt_disease_id=None, limit=None,
as_df=False) | Get diseases
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param int limit: maximum number of results
:param str disease_name: disease name
:param str disease_id: disease identifier
:param str definition: definition of disease
:param str parent_... | 1.385962 | 1.39539 | 0.993244 |
q = self.session.query(models.Gene)
if gene_symbol:
q = q.filter(models.Gene.gene_symbol.like(gene_symbol))
if gene_name:
q = q.filter(models.Gene.gene_name.like(gene_name))
if gene_id:
q = q.filter(models.Gene.gene_id.like(gene_id))
... | def get_gene(self, gene_name=None, gene_symbol=None, gene_id=None, synonym=None, uniprot_id=None,
pharmgkb_id=None, biogrid_id=None, alt_gene_id=None, limit=None, as_df=False) | Get genes
:param bool as_df: if set to True result returns as `pandas.DataFrame`
:param alt_gene_id:
:param str gene_name: gene name
:param str gene_symbol: HGNC gene symbol
:param int gene_id: NCBI Entrez Gene identifier
:param str synonym: Synonym
:param str u... | 1.374279 | 1.389392 | 0.989123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.