_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q48200
OsidSession._init_catalog
train
def _init_catalog(self, proxy=None, runtime=None): """Initialize this session as an OsidCatalog based session.""" self._init_proxy_and_runtime(proxy, runtime) osid_name = self._session_namespace.split('.')[0] try: config = self._runtime.get_configuration() paramet...
python
{ "resource": "" }
q48201
OsidSession._init_object
train
def _init_object(self, catalog_id, proxy, runtime, db_name, cat_name, cat_class): """Initialize this session an OsidObject based session.""" self._catalog_identifier = None self._init_proxy_and_runtime(proxy, runtime) uses_cataloging = False if catalog_id is not None and catalog...
python
{ "resource": "" }
q48202
OsidSession._get_phantom_root_catalog
train
def _get_phantom_root_catalog(self, cat_name, cat_class): """Get's the catalog id corresponding to the root of all implementation catalogs.""" catalog_map = make_catalog_map(cat_name, identifier=PHANTOM_ROOT_IDENTIFIER) return cat_class(osid_object_map=catalog_map, runtime=self._runtime, proxy=s...
python
{ "resource": "" }
q48203
OsidSession._create_orchestrated_cat
train
def _create_orchestrated_cat(self, foreign_catalog_id, db_name, cat_name): """Creates a catalog in the current service orchestrated with a foreign service Id.""" if (foreign_catalog_id.identifier_namespace == db_name + '.' + cat_name and foreign_catalog_id.authority == self._authority): ...
python
{ "resource": "" }
q48204
OsidSession._get_id
train
def _get_id(self, id_, pkg_name): """ Returns the primary id given an alias. If the id provided is not in the alias table, it will simply be returned as is. Only looks within the Id Alias namespace for the session package """ collection = JSONClientValidated('i...
python
{ "resource": "" }
q48205
OsidSession._alias_id
train
def _alias_id(self, primary_id, equivalent_id): """Adds the given equivalent_id as an alias for primary_id if possible""" pkg_name = primary_id.get_identifier_namespace().split('.')[0] obj_name = primary_id.get_identifier_namespace().split('.')[1] collection = JSONClientValidated(pkg_nam...
python
{ "resource": "" }
q48206
OsidSession._get_catalog_idstrs
train
def _get_catalog_idstrs(self): """Returns the proper list of catalog idstrs based on catalog view""" if self._catalog_view == ISOLATED: return [str(self._catalog_id)] else: return self._get_descendent_cat_idstrs(self._catalog_id)
python
{ "resource": "" }
q48207
OsidSession._get_descendent_cat_idstrs
train
def _get_descendent_cat_idstrs(self, cat_id, hierarchy_session=None): """Recursively returns a list of all descendent catalog ids, inclusive""" def get_descendent_ids(h_session): idstr_list = [str(cat_id)] if h_session is None: pkg_name = cat_id.get_identifier_nam...
python
{ "resource": "" }
q48208
OsidSession._effective_view_filter
train
def _effective_view_filter(self): """Returns the mongodb relationship filter for effective views""" if self._effective_view == EFFECTIVE: now = datetime.datetime.utcnow() return {'startDate': {'$$lte': now}, 'endDate': {'$$gte': now}} return {}
python
{ "resource": "" }
q48209
OsidSession._view_filter
train
def _view_filter(self): """ Returns the mongodb catalog filter for isolated or federated views. This also searches across all underlying catalogs in federated catalog views. Real authz for controlling access to underlying catalogs will need to be managed in an adapter above the ...
python
{ "resource": "" }
q48210
Package.walk
train
def walk(self): """ A generator that walking through all sub packages and sub modules. 1. current package object (包对象) 2. current package's parent (当前包对象的母包) 3. list of sub packages (所有子包) 4. list of sub modules (所有模块) """ yield ( self, ...
python
{ "resource": "" }
q48211
Package._tree_view_builder
train
def _tree_view_builder(self, indent=0, is_root=True): """ Build a text to represent the package structure. """ def pad_text(indent): return " " * indent + "|-- " lines = list() if is_root: lines.append(SP_DIR) lines.append( ...
python
{ "resource": "" }
q48212
AssetContent.get_url
train
def get_url(self): """Gets the URL associated with this content for web-based retrieval. return: (string) - the url for this data raise: IllegalState - ``has_url()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # construct the URL from r...
python
{ "resource": "" }
q48213
run
train
def run(m, w, trace=False, steps=1000, show_stack=3): """Runs an automaton, automatically selecting a search method.""" # Check to see whether run_pda can handle it. is_pda = True stack = None if not m.oneway: is_pda = False for s in range(m.num_stores): if s == m.input: ...
python
{ "resource": "" }
q48214
run_bfs
train
def run_bfs(m, w, trace=False, steps=1000): """Runs an automaton using breadth-first search.""" from .machines import Store, Configuration, Transition agenda = collections.deque() chart = {} # Initial configuration config = list(m.start_config) w = Store(w) config[m.input] = w conf...
python
{ "resource": "" }
q48215
ApiClient.get
train
def get(self, mac): """Get data from API as instance of ResponseModel. Keyword arguments: mac -- MAC address or OUI for searching """ data = { self._FORMAT_F: 'json', self._SEARCH_F: mac } response = self.__decode_str(self.__call...
python
{ "resource": "" }
q48216
ApiClient.get_raw_data
train
def get_raw_data(self, mac, response_format='json'): """Get data from API as string. Keyword arguments: mac -- MAC address or OUI for searching response_format -- supported types you can see on the https://macaddress.io """ data = { self._FORMAT_...
python
{ "resource": "" }
q48217
ApiClient.get_vendor
train
def get_vendor(self, mac): """Get vendor company name. Keyword arguments: mac -- MAC address or OUI for searching """ data = { self._SEARCH_F: mac, self._FORMAT_F: self._VERBOSE_T } response = self.__decode_str(self.__call_api(se...
python
{ "resource": "" }
q48218
ShellCommands.md5_checker
train
def md5_checker(self, md5sum, local_file=None, file_object=None): """Return True if the local file and the provided `md5sum` are equal. If the processed file and the provided md5sum do not match an exception is raised indicating the failure. :param md5sum: ``str`` :param local_...
python
{ "resource": "" }
q48219
generate_signature
train
def generate_signature(secret, verb, url, nonce, data): """Generate a request signature compatible with BitMEX.""" # Parse the url so we can remove the base and extract just the path. parsedURL = urllib.parse.urlparse(url) path = parsedURL.path if parsedURL.query: path = path + '?' + parsedU...
python
{ "resource": "" }
q48220
BitMEXWebsocket.get_ticker
train
def get_ticker(self): '''Return a ticker object. Generated from quote and trade.''' lastQuote = self.data['quote'][-1] lastTrade = self.data['trade'][-1] ticker = { "last": lastTrade['price'], "buy": lastQuote['bidPrice'], "sell": lastQuote['askPrice']...
python
{ "resource": "" }
q48221
BitMEXWebsocket.__connect
train
def __connect(self, wsURL, symbol): '''Connect to the websocket in a thread.''' self.logger.debug("Starting thread") self.ws = websocket.WebSocketApp(wsURL, on_message=self.__on_message, on_close=self.__on_close, ...
python
{ "resource": "" }
q48222
BitMEXWebsocket.__get_auth
train
def __get_auth(self): '''Return auth headers. Will use API Keys if present in settings.''' if self.api_key == None and self.login == None: self.logger.error("No authentication provided! Unable to connect.") sys.exit(1) if self.api_key == None: self.logger.inf...
python
{ "resource": "" }
q48223
BitMEXWebsocket.__push_symbol
train
def __push_symbol(self, symbol): '''Ask the websocket for a symbol push. Gets instrument, orderBook, quote, and trade''' self.__send_command("getSymbol", symbol) while not {'instrument', 'trade', 'orderBook25'} <= set(self.data): sleep(0.1)
python
{ "resource": "" }
q48224
BitMEXWebsocket.__send_command
train
def __send_command(self, command, args=[]): '''Send a raw command.''' self.ws.send(json.dumps({"op": command, "args": args}))
python
{ "resource": "" }
q48225
BitMEXWebsocket.__on_message
train
def __on_message(self, ws, message): '''Handler for parsing WS messages.''' message = json.loads(message) self.logger.debug(json.dumps(message)) table = message['table'] if 'table' in message else None action = message['action'] if 'action' in message else None try: ...
python
{ "resource": "" }
q48226
SteemConnectOAuth2.get_user_details
train
def get_user_details(self, response): """Return user details from GitHub account""" account = response['account'] metadata = json.loads(account.get('json_metadata') or '{}') account['json_metadata'] = metadata return { 'id': account['id'], 'username': ac...
python
{ "resource": "" }
q48227
SoapAuthenticator.authenticate_admin
train
def authenticate_admin(self, transport, account_name, password): """ Authenticates administrator using username and password. """ Authenticator.authenticate_admin(self, transport, account_name, password) auth_token = AuthToken() auth_token.account_name = account_name ...
python
{ "resource": "" }
q48228
SoapAuthenticator.authenticate
train
def authenticate(self, transport, account_name, password=None): """ Authenticates account using soap method. """ Authenticator.authenticate(self, transport, account_name, password) if password == None: return self.pre_auth(transport, account_name) else: ...
python
{ "resource": "" }
q48229
SoapAuthenticator.auth
train
def auth(self, transport, account_name, password): """ Authenticates using username and password. """ auth_token = AuthToken() auth_token.account_name = account_name attrs = {sconstant.A_BY: sconstant.V_NAME} account = SOAPpy.Types.stringType(data=account_name, a...
python
{ "resource": "" }
q48230
SoapAuthenticator.pre_auth
train
def pre_auth(self, transport, account_name): """ Authenticates using username and domain key. """ auth_token = AuthToken() auth_token.account_name = account_name domain = util.get_domain(account_name) if domain == None: raise AuthException('Invalid au...
python
{ "resource": "" }
q48231
ShowSpecsDirective.nodes_for_spec
train
def nodes_for_spec(self, spec): """ Determine nodes for an input_algorithms spec Taking into account nested specs """ tokens = [] if isinstance(spec, sb.create_spec): container = nodes.container(classes=["option_spec_option shortline blue-back"]) ...
python
{ "resource": "" }
q48232
LoggingManager.get_log_entry_admin_session_for_log
train
def get_log_entry_admin_session_for_log(self, log_id): """Gets the ``OsidSession`` associated with the log entry administrative service for the given log. arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` return: (osid.logging.LogEntryAdminSession) - a ``LogEntryAdminSessio...
python
{ "resource": "" }
q48233
LoggingProxyManager.get_logging_session
train
def get_logging_session(self, proxy): """Gets the ``OsidSession`` associated with the logging service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LoggingSession) - a ``LoggingSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - un...
python
{ "resource": "" }
q48234
LoggingProxyManager.get_logging_session_for_log
train
def get_logging_session_for_log(self, log_id, proxy): """Gets the ``OsidSession`` associated with the logging service for the given log. arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LoggingSession) - a ``LoggingSe...
python
{ "resource": "" }
q48235
LoggingProxyManager.get_log_entry_lookup_session
train
def get_log_entry_lookup_session(self, proxy): """Gets the ``OsidSession`` associated with the logging reading service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryLookupSession) - a ``LogEntryLookupSession`` raise: NullArgument - ``proxy`` i...
python
{ "resource": "" }
q48236
LoggingProxyManager.get_log_entry_lookup_session_for_log
train
def get_log_entry_lookup_session_for_log(self, log_id, proxy): """Gets the ``OsidSession`` associated with the log reading service for the given log. arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryLookupSess...
python
{ "resource": "" }
q48237
LoggingProxyManager.get_log_entry_query_session
train
def get_log_entry_query_session(self, proxy): """Gets the ``OsidSession`` associated with the logging entry query service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryQuerySession) - a ``LogEntryQuerySession`` raise: NullArgument - ``proxy`` ...
python
{ "resource": "" }
q48238
LoggingProxyManager.get_log_entry_query_session_for_log
train
def get_log_entry_query_session_for_log(self, log_id, proxy): """Gets the ``OsidSession`` associated with the log entry query service for the given log. arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryQuerySe...
python
{ "resource": "" }
q48239
LoggingProxyManager.get_log_entry_admin_session
train
def get_log_entry_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the logging entry administrative service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryAdminSession) - a ``LogEntryAdminSession`` raise: NullArgument - `...
python
{ "resource": "" }
q48240
LoggingProxyManager.get_log_entry_log_session
train
def get_log_entry_log_session(self, proxy): """Gets the session for retrieving log entry to log mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryLogSession) - a ``LogEntryLogSession`` raise: NullArgument - ``proxy`` is ``null`` r...
python
{ "resource": "" }
q48241
LoggingProxyManager.get_log_entry_log_assignment_session
train
def get_log_entry_log_assignment_session(self, proxy): """Gets the session for assigning log entry to log mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogEntryLogAssignmentSession) - a ``LogEntryLogAssignmentSession`` raise: NullArgument - `...
python
{ "resource": "" }
q48242
LoggingProxyManager.get_log_lookup_session
train
def get_log_lookup_session(self, proxy): """Gets the ``OsidSession`` associated with the log lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogLookupSession) - a ``LogLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationF...
python
{ "resource": "" }
q48243
LoggingProxyManager.get_log_admin_session
train
def get_log_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the log administrative service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogAdminSession) - a ``LogAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: Opera...
python
{ "resource": "" }
q48244
LoggingProxyManager.get_log_hierarchy_session
train
def get_log_hierarchy_session(self, proxy): """Gets the ``OsidSession`` associated with the log hierarchy service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogHierarchySession) - a ``LogHierarchySession`` for logs raise: NullArgument - ``proxy`` i...
python
{ "resource": "" }
q48245
LoggingProxyManager.get_log_hierarchy_design_session
train
def get_log_hierarchy_design_session(self, proxy): """Gets the ``OsidSession`` associated with the log hierarchy design service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogHierarchyDesignSession) - a ``HierarchyDesignSession`` for logs raise: Nul...
python
{ "resource": "" }
q48246
ArgumentParserator._add_opt_argument
train
def _add_opt_argument(self, opt_args, arg_parser): """Add an argument to an instantiated parser. :param opt_args: ``dict`` :param arg_parser: ``object`` """ option_args = opt_args.copy() groups = option_args.pop('groups', None) if groups: self._add_g...
python
{ "resource": "" }
q48247
ArgumentParserator._setup_parser
train
def _setup_parser(self): """Setup a configuration parser. Contains built in ``--system-config`` || ``-SC`` variable which is used to allow a user to set arguments in a configuration file which would then be processed from the "default" section of the provided file, assuming the ...
python
{ "resource": "" }
q48248
OpenIOC_Import.reference_handler
train
def reference_handler(self,iobject, fact, attr_info, add_fact_kargs): """ Handler for facts that contain a reference to a fact. See below in the comment regarding the fact_handler_list for a description of the signature of handler functions. As shown below in the handler list, t...
python
{ "resource": "" }
q48249
process_args
train
def process_args(mod_id, args, type_args): """ Takes as input a list of arguments defined on a module and the information about the required arguments defined on the corresponding module type. Validates that the number of supplied arguments is valid and fills any missing arguments with their default...
python
{ "resource": "" }
q48250
process_params
train
def process_params(mod_id, params, type_params): """ Takes as input a dictionary of parameters defined on a module and the information about the required parameters defined on the corresponding module type. Validatates that are required parameters were supplied and fills any missing parameters with ...
python
{ "resource": "" }
q48251
make_dir_name_from_url
train
def make_dir_name_from_url(url): """This function attempts to emulate something like Git's "humanish" directory naming for clone. It's probably not a perfect facimile, but it's close.""" url_path = urlparse(url).path head, tail = os.path.split(url_path) # If tail happens to be empty as in case `...
python
{ "resource": "" }
q48252
safe_cpp_var
train
def safe_cpp_var(s): """ Given a string representing a variable, return a new string that is safe for C++ codegen. If string is already safe, will leave it alone. """ s = str(s) # Remove non-word, non-space characters s = re.sub(r"[^\w\s]", '', s) # Replace spaces with _ s = re.sub(r...
python
{ "resource": "" }
q48253
booleanise
train
def booleanise(b): """Normalise a 'stringified' Boolean to a proper Python Boolean. ElasticSearch has a habit of returning "true" and "false" in its JSON responses when it should be returning `true` and `false`. If `b` looks like a stringified Boolean true, return True. If `b` looks like a str...
python
{ "resource": "" }
q48254
fmt_bytes
train
def fmt_bytes(bytes, precision=2): """Reduce a large number of `bytes` down to a humanised SI equivalent and return the result as a string with trailing unit abbreviation. """ UNITS = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'] if bytes == 0: return '0 bytes' log = math.floor(math.l...
python
{ "resource": "" }
q48255
Connection.get_index_translog_disable_flush
train
def get_index_translog_disable_flush(self): """Return a dictionary showing the position of the 'translog.disable_flush' knob for each index in the cluster. The dictionary will look like this: { "index1": True, # Autoflushing DISABLED "index2": ...
python
{ "resource": "" }
q48256
Connection.allocator_disabled
train
def allocator_disabled(self): """Return a simplified one-word answer to the question, 'Has the automatic shard allocator been disabled for this cluster?' The answer will be one of "disabled" (yes), "enabled" (no), or "unknown". """ state = "unknown" setting_ge...
python
{ "resource": "" }
q48257
Connection.flushing_disabled
train
def flushing_disabled(self): """Return a simplified one-word answer to the question, 'Has automatic transaction log flushing been disabled on all indexes in the cluster?' The answer will be one of "disabled" (yes, on all), "enabled" (no, on all), "some" (yes, only on some), o...
python
{ "resource": "" }
q48258
TabularPrinter.nontruncating_zip
train
def nontruncating_zip(*seqs): """Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is as long as the longest argument sequence. Shorter argument sequences will be represented in the output as None paddi...
python
{ "resource": "" }
q48259
pearson
train
def pearson(x, y): """ Pearson's correlation implementation without scipy or numpy. :param list x: Dataset x :param list y: Dataset y :return: Population pearson correlation coefficient :rtype: float """ mx = Decimal(mean(x)) my = Decimal(mean(y)) xm = [Decimal(i) - mx for i in...
python
{ "resource": "" }
q48260
clean_up_datetime
train
def clean_up_datetime(obj_map): """convert datetime objects to dictionaries for storage""" clean_map = {} for key, value in obj_map.items(): if isinstance(value, datetime.datetime): clean_map[key] = { 'year': value.year, 'month': value.month, ...
python
{ "resource": "" }
q48261
convert_dict_to_datetime
train
def convert_dict_to_datetime(obj_map): """converts dictionary representations of datetime back to datetime obj""" converted_map = {} for key, value in obj_map.items(): if isinstance(value, dict) and 'tzinfo' in value.keys(): converted_map[key] = datetime.datetime(**value) elif is...
python
{ "resource": "" }
q48262
convert_ids_to_object_ids
train
def convert_ids_to_object_ids(obj_map): """converts string representations of _id back to ObjectId obj""" converted_map = {} for key, value in obj_map.items(): if key == '_id': # hacky, but using alias sends back the whole ID string, like # assessment.Item%3A5758326b4a40452...
python
{ "resource": "" }
q48263
fix_reserved_word
train
def fix_reserved_word(word, is_module=False): """ Replaces words that may be problematic In particular the term 'type' is used in the osid spec, primarily as an argument parameter where a type is provided to a method. 'type' is a reserved word in python, so we give ours a trailing underscore. If w...
python
{ "resource": "" }
q48264
remove_null_proxy_kwarg
train
def remove_null_proxy_kwarg(func): """decorator, to remove a 'proxy' keyword argument. For wrapping certain Manager methods""" def wrapper(*args, **kwargs): if 'proxy' in kwargs: # if kwargs['proxy'] is None: del kwargs['proxy'] # else: # raise InvalidA...
python
{ "resource": "" }
q48265
arguments_not_none
train
def arguments_not_none(func): """decorator, to check if any arguments are None; raise exception if so""" def wrapper(*args, **kwargs): for arg in args: if arg is None: raise NullArgument() for arg, val in kwargs.items(): if val is None: rai...
python
{ "resource": "" }
q48266
handle_simple_sequencing
train
def handle_simple_sequencing(func): """decorator, deal with simple sequencing cases""" from .assessment import assessment_utilities def wrapper(*args, **kwargs): # re-order these things because have to delete the part after # removing it from the parent sequence map if 'create_asses...
python
{ "resource": "" }
q48267
get_registry
train
def get_registry(entry, runtime): """Returns a record registry given an entry and runtime""" try: records_location_param_id = Id('parameter:recordsRegistry@mongo') registry = runtime.get_configuration().get_value_by_parameter( records_location_param_id).get_string_value() ret...
python
{ "resource": "" }
q48268
is_authenticated_with_proxy
train
def is_authenticated_with_proxy(proxy): """Given a Proxy, checks whether a user is authenticated""" if proxy is None: return False elif proxy.has_authentication(): return proxy.get_authentication().is_valid() else: return False
python
{ "resource": "" }
q48269
get_effective_agent_id_with_proxy
train
def get_effective_agent_id_with_proxy(proxy): """Given a Proxy, returns the Id of the effective Agent""" if is_authenticated_with_proxy(proxy): if proxy.has_effective_agent(): return proxy.get_effective_agent_id() else: return proxy.get_authentication().get_agent_id() ...
python
{ "resource": "" }
q48270
get_locale_with_proxy
train
def get_locale_with_proxy(proxy): """Given a Proxy, returns the Locale This assumes that instantiating a dlkit.mongo.locale.objects.Locale without constructor arguments wlll return the default Locale. """ from .locale.objects import Locale if proxy is not None: locale = proxy.get_l...
python
{ "resource": "" }
q48271
convert_catalog_id_to_object_id_string
train
def convert_catalog_id_to_object_id_string(catalog_id): """When doing hierarchies, need to convert a catalogId into an ObjectId, so convert to a string, then into a hex format. i.e. Bank Assessment hierarchy should become BANKASSESSME '42414e4b4153534553534d45' """ if not isinst...
python
{ "resource": "" }
q48272
all_as_list
train
def all_as_list(): ''' returns a list of all defined containers ''' as_dict = all_as_dict() containers = as_dict['Running'] + as_dict['Frozen'] + as_dict['Stopped'] containers_list = [] for i in containers: i = i.replace(' (auto)', '') containers_list.append(i) ...
python
{ "resource": "" }
q48273
start
train
def start(name, config_file=None): ''' starts a container in daemon mode ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) if name in running(): raise ContainerAlreadyRunning('The container %s is already started!' % name) cmd =...
python
{ "resource": "" }
q48274
stop
train
def stop(name): ''' stops a container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-stop', '-n', name] subprocess.check_call(cmd)
python
{ "resource": "" }
q48275
monitor
train
def monitor(name, callback): ''' monitors actions on the specified container, callback is a function to be called on ''' global _monitor if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) if _monitor: if _monitor.is_monitored...
python
{ "resource": "" }
q48276
freeze
train
def freeze(name): ''' freezes the container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-freeze', '-n', name] subprocess.check_call(cmd)
python
{ "resource": "" }
q48277
unfreeze
train
def unfreeze(name): ''' unfreezes the container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-unfreeze', '-n', name] subprocess.check_call(cmd)
python
{ "resource": "" }
q48278
info
train
def info(name): ''' returns info dict about the specified container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-info', '-n', name] out = subprocess.check_output(cmd).splitlines() info = {} for line in out: ...
python
{ "resource": "" }
q48279
checkconfig
train
def checkconfig(): ''' returns the output of lxc-checkconfig ''' cmd = ['lxc-checkconfig'] return subprocess.check_output(cmd).replace('[1;32m', '').replace('[1;33m', '').replace('[0;39m', '').replace('[1;32m', '').replace(' ', '').split('\n')
python
{ "resource": "" }
q48280
get_grade_mdata
train
def get_grade_mdata(): """Return default mdata map for Grade""" return { 'output_score': { 'element_label': { 'text': 'output score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'forma...
python
{ "resource": "" }
q48281
get_grade_system_mdata
train
def get_grade_system_mdata(): """Return default mdata map for GradeSystem""" return { 'numeric_score_increment': { 'element_label': { 'text': 'numeric score increment', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_S...
python
{ "resource": "" }
q48282
get_gradebook_column_mdata
train
def get_gradebook_column_mdata(): """Return default mdata map for GradebookColumn""" return { 'grade_system': { 'element_label': { 'text': 'grade system', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), ...
python
{ "resource": "" }
q48283
get_gradebook_column_summary_mdata
train
def get_gradebook_column_summary_mdata(): """Return default mdata map for GradebookColumnSummary""" return { 'gradebook_column': { 'element_label': { 'text': 'gradebook column', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(...
python
{ "resource": "" }
q48284
Roll._calc_odds
train
def _calc_odds(self): '''Calculates the absolute probability of all posible rolls.''' def recur(val, h, dice, combinations): for pip in dice[0]: tot = val + pip if len(dice) > 1: combinations = recur(tot, h, dice[1:], combinations) ...
python
{ "resource": "" }
q48285
ResourceLookupSession.get_resource
train
def get_resource(self, resource_id): """Gets the ``Resource`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``Resource`` may have a different ``Id`` than requested, such as the case where a duplicate ``Id``...
python
{ "resource": "" }
q48286
ResourceLookupSession.get_resources_by_ids
train
def get_resources_by_ids(self, resource_ids): """Gets a ``ResourceList`` corresponding to the given ``IdList``. In plenary mode, the returned list contains all of the resources specified in the ``Id`` list, in the order of the list, including duplicates, or an error results if an ``Id``...
python
{ "resource": "" }
q48287
ResourceLookupSession.get_resources_by_genus_type
train
def get_resources_by_genus_type(self, resource_genus_type): """Gets a ``ResourceList`` corresponding to the given resource genus ``Type`` which does not include resources of types derived from the specified ``Type``. In plenary mode, the returned list contains all known resources or an error re...
python
{ "resource": "" }
q48288
ResourceLookupSession.get_resources
train
def get_resources(self): """Gets all ``Resources``. In plenary mode, the returned list contains all known resources or an error results. Otherwise, the returned list may contain only those resources that are accessible through this session. return: (osid.resource.ResourceList) ...
python
{ "resource": "" }
q48289
ResourceQuerySession.get_resources_by_query
train
def get_resources_by_query(self, resource_query): """Gets a list of ``Resources`` matching the given resource query. arg: resource_query (osid.resource.ResourceQuery): the resource query return: (osid.resource.ResourceList) - the returned ``ResourceList`` ...
python
{ "resource": "" }
q48290
ResourceAdminSession.get_resource_form_for_create
train
def get_resource_form_for_create(self, resource_record_types): """Gets the resource form for creating new resources. A new form should be requested for each create transaction. arg: resource_record_types (osid.type.Type[]): array of resource record types return: (osi...
python
{ "resource": "" }
q48291
ResourceAdminSession.delete_resource
train
def delete_resource(self, resource_id): """Deletes a ``Resource``. arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`` to remove raise: NotFound - ``resource_id`` not found raise: NullArgument - ``resource_id`` is ``null`` raise: OperationFailed -...
python
{ "resource": "" }
q48292
ResourceAdminSession.alias_resource
train
def alias_resource(self, resource_id, alias_id): """Adds an ``Id`` to a ``Resource`` for the purpose of creating compatibility. The primary ``Id`` of the ``Resource`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to a...
python
{ "resource": "" }
q48293
ResourceNotificationSession.register_for_deleted_resource
train
def register_for_deleted_resource(self, resource_id): """Registers for notification of a deleted resource. ``ResourceReceiver.deletedResources()`` is invoked when the specified resource is deleted or removed from this bin. arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`...
python
{ "resource": "" }
q48294
ResourceBinSession.get_resource_ids_by_bin
train
def get_resource_ids_by_bin(self, bin_id): """Gets the list of ``Resource`` ``Ids`` associated with a ``Bin``. arg: bin_id (osid.id.Id): ``Id`` of a ``Bin`` return: (osid.id.IdList) - list of related resource ``Ids`` raise: NotFound - ``bin_id`` is not found raise: NullArg...
python
{ "resource": "" }
q48295
ResourceBinSession.get_resources_by_bin
train
def get_resources_by_bin(self, bin_id): """Gets the list of ``Resources`` associated with a ``Bin``. arg: bin_id (osid.id.Id): ``Id`` of a ``Bin`` return: (osid.resource.ResourceList) - list of related resources raise: NotFound - ``bin_id`` is not found raise: NullArgument ...
python
{ "resource": "" }
q48296
ResourceBinSession.get_resource_ids_by_bins
train
def get_resource_ids_by_bins(self, bin_ids): """Gets the list of ``Resource Ids`` corresponding to a list of ``Bin`` objects. arg: bin_ids (osid.id.IdList): list of bin ``Ids`` return: (osid.id.IdList) - list of resource ``Ids`` raise: NullArgument - ``bin_ids`` is ``null`` ...
python
{ "resource": "" }
q48297
ResourceBinSession.get_resources_by_bins
train
def get_resources_by_bins(self, bin_ids): """Gets the list of ``Resources`` corresponding to a list of ``Bins``. arg: bin_ids (osid.id.IdList): list of bin ``Ids`` return: (osid.resource.ResourceList) - list of resources raise: NullArgument - ``bin_ids`` is ``null`` raise: ...
python
{ "resource": "" }
q48298
ResourceBinSession.get_bin_ids_by_resource
train
def get_bin_ids_by_resource(self, resource_id): """Gets the list of ``Bin`` ``Ids`` mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.id.IdList) - list of bin ``Ids`` raise: NotFound - ``resource_id`` is not found raise: NullAr...
python
{ "resource": "" }
q48299
ResourceBinSession.get_bins_by_resource
train
def get_bins_by_resource(self, resource_id): """Gets the list of ``Bin`` objects mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.resource.BinList) - list of bins raise: NotFound - ``resource_id`` is not found raise: NullArgume...
python
{ "resource": "" }