_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q51900
TupleField.unwrap
train
def unwrap(self, value, session=None): ''' Validate and then unwrap ``value`` for object creation. :param value: list returned from the database. ''' self.validate_unwrap(value) ret = [] for field, value in izip(self.types, value): ret.append(field.unwrap...
python
{ "resource": "" }
q51901
EnumField.validate_wrap
train
def validate_wrap(self, value): ''' Checks that value is valid for `EnumField.item_type` and that value is one of the values specified when the EnumField was constructed ''' self.item_type.validate_wrap(value) if value not in self.values: self._fail_validatio...
python
{ "resource": "" }
q51902
EnumField.wrap
train
def wrap(self, value): ''' Validate and wrap value using the wrapping function from ``EnumField.item_type`` ''' self.validate_wrap(value) return self.item_type.wrap(value)
python
{ "resource": "" }
q51903
EnumField.unwrap
train
def unwrap(self, value, session=None): ''' Unwrap value using the unwrap function from ``EnumField.item_type``. Since unwrap validation could not happen in is_valid_wrap, it happens in this function.''' self.validate_unwrap(value) value = self.item_type.unwrap(value, sess...
python
{ "resource": "" }
q51904
ObjectIdField.validate_wrap
train
def validate_wrap(self, value): ''' Checks that ``value`` is a pymongo ``ObjectId`` or a string representation of one''' if (not isinstance(value, ObjectId) and not isinstance(value, basestring) and not isinstance(value, bytes) ): self....
python
{ "resource": "" }
q51905
ResourceView.dispatch
train
def dispatch(self, request, **resources): """ Try to dispatch the request. :return object: result """ # Fix PUT and PATH methods in Django request request = fix_request(request) # Set self identifier self.identifier = request.META.get('REMOTE_ADDR', 'anonymous...
python
{ "resource": "" }
q51906
ResourceView.check_owners
train
def check_owners(self, request, **resources): """ Check parents of current resource. Recursive scanning of the fact that the child has FK to the parent and in resources we have right objects. We check that in request like /author/1/book/2/page/3 Page object with pk=3 has Forei...
python
{ "resource": "" }
q51907
ResourceView.handle_exception
train
def handle_exception(self, e, request=None): """ Handle code exception. :return response: Http response """ if isinstance(e, HttpError): response = SerializedHttpResponse(e.content, status=e.status) return self.emit( response, request=request, em...
python
{ "resource": "" }
q51908
ResourceView.as_url
train
def as_url(cls, api=None, name_prefix='', url_prefix=''): """ Generate url for resource. :return RegexURLPattern: Django URL """ url_prefix = url_prefix and "%s/" % url_prefix name_prefix = name_prefix and "%s-" % name_prefix url_regex = '^%s%s/?$' % ( url_...
python
{ "resource": "" }
q51909
Trigpoints.import_locations
train
def import_locations(self, marker_file): """Import trigpoint database files. ``import_locations()`` returns a dictionary with keys containing the trigpoint identifier, and values that are :class:`Trigpoint` objects. It expects trigpoint marker files in the format provided at al...
python
{ "resource": "" }
q51910
HandlerMixin.handle_request
train
def handle_request(self, request, **resources): """ Get a method for request and execute. :return object: method result """ if not request.method in self._meta.callmap.keys(): raise HttpError( 'Unknown or unsupported method \'%s\'' % request.method, ...
python
{ "resource": "" }
q51911
HandlerMixin.post
train
def post(self, request, **resources): """ Default POST method. Uses the handler's form. :return object: saved instance or raise form's error """ if not self._meta.form: return None form = self._meta.form(request.data, **resources) if form.is_valid(): ...
python
{ "resource": "" }
q51912
HandlerMixin.put
train
def put(self, request, **resources): """ Default PUT method. Uses self form. Allow bulk update. :return object: changed instance or raise form's error """ if not self._meta.form: return None if not self._meta.name in resources or not resources[self._meta.name]: ...
python
{ "resource": "" }
q51913
HandlerMixin.delete
train
def delete(self, request, **resources): """ Default DELETE method. Allow bulk delete. :return django.http.response: empty response """ resource = resources.get(self._meta.name) if not resource: raise HttpError("Bad request", status=status.HTTP_404_NOT_FOUND) ...
python
{ "resource": "" }
q51914
HandlerMixin.check_method_allowed
train
def check_method_allowed(cls, request): """ Ensure the request HTTP method is permitted for this resource. Raising a ResourceException if it is not. """ if not request.method in cls._meta.allowed_methods: raise HttpError( 'Method \'%s\' not allowed on this r...
python
{ "resource": "" }
q51915
HandlerMixin.get_resources
train
def get_resources(self, request, **resources): """ Parse resource objects from URL and request. :return dict: Resources. """ if self.parent: resources = self.parent.get_resources(request, **resources) pks = ( resources.get(self._meta.name) or ...
python
{ "resource": "" }
q51916
PaymentManager.create_contact
train
def create_contact(self, email=None, first_name=None, last_name=None, phone_number=None): """ Create a contant which is later passed to payment. """ result = {} if email: result['email'] = email if first_name is not None: result['first_name'] = fir...
python
{ "resource": "" }
q51917
PaymentManager.create_single_payment
train
def create_single_payment(self, order_number, order_description, order_items, amount, return_url, contact=None, currency=None, lang=None, additional_params=None): """ Create a single payment. Args: contact: JSON describing a payer (see PaymentManager#create_contact) orde...
python
{ "resource": "" }
q51918
Bookstore.get_books_for_schedule
train
def get_books_for_schedule(self, schedule): """ Returns a dictionary of data. SLNs are the keys, an array of Book objects are the values. """ slns = self._get_slns(schedule) books = {} for sln in slns: try: section_books = self.get_b...
python
{ "resource": "" }
q51919
EboxClient._post_login_page
train
async def _post_login_page(self, token): """Login to EBox website.""" data = {"usrname": self.username, "pwd": self.password, "_csrf_security_token": token} try: async with async_timeout.timeout(10): raw_res = await self._session.post(...
python
{ "resource": "" }
q51920
EboxClient._get_home_data
train
async def _get_home_data(self): """Get home data.""" # Import from bs4 import BeautifulSoup # Prepare return home_data = {} # Http request try: async with async_timeout.timeout(10): raw_res = await self._session.get(HOME_URL, ...
python
{ "resource": "" }
q51921
EboxClient._get_usage_data
train
async def _get_usage_data(self): """Get data usage.""" # Get Usage raw_res = await self._session.get(USAGE_URL) content = await raw_res.text() soup = BeautifulSoup(content, 'html.parser') # Find all span span_list = soup.find_all("span", {"class": "switchDisplay"}...
python
{ "resource": "" }
q51922
EboxClient.fetch_data
train
async def fetch_data(self): """Get the latest data from EBox.""" # Get http session await self._get_httpsession() # Get login page token = await self._get_login_page() # Post login page await self._post_login_page(token) # Get home data home_data =...
python
{ "resource": "" }
q51923
EboxClient.close_session
train
def close_session(self): """Close current session.""" if not self._session.closed: if self._session._connector_owner: self._session._connector.close() self._session._connector = None
python
{ "resource": "" }
q51924
Cube.make_query
train
def make_query(self, query_type, expression, **kwargs): """ Actually perform the query, try to convert datetime to isoformat on the fly """ data = dict(expression=str(expression), stop=kwargs.get('stop', datetime.utcnow())) data.update(kwargs) ...
python
{ "resource": "" }
q51925
Cube.types
train
def types(self): """ List of the known event types """ r = requests.get(self.evaluator_url + 'types') r.raise_for_status() return r.json()
python
{ "resource": "" }
q51926
sorted_chain
train
def sorted_chain(*ranges: Iterable[Tuple[int, int]]) -> List[Tuple[int, int]]: """Chain & sort ranges.""" return sorted(itertools.chain(*ranges))
python
{ "resource": "" }
q51927
authors_titles_validator
train
def authors_titles_validator(record, result): """Compute a validation score for the possible match. The score is based on a similarity score of the authors sets and the maximum Jaccard index found between 2 titles: one from the record and one from the result title sets. If the computed score is higher...
python
{ "resource": "" }
q51928
cds_identifier_validator
train
def cds_identifier_validator(record, result): """Ensure that the two records have the same CDS identifier. This is needed because the search is done only for ``external_system_identifiers.value``, which might cause false positives in case the matched record has an identifier with the same ``value`` but...
python
{ "resource": "" }
q51929
addMenuLabel
train
def addMenuLabel(menu, text): """Adds a QLabel contaning text to the given menu""" qaw = QWidgetAction(menu) lab = QLabel(text, menu) qaw.setDefaultWidget(lab) lab.setAlignment(Qt.AlignCenter) lab.setFrameShape(QFrame.StyledPanel) lab.setFrameShadow(QFrame.Sunken) menu.addAction(qaw) ...
python
{ "resource": "" }
q51930
BIC.elements
train
def elements(self): """Return the BIC's Party Prefix, Country Code, Party Suffix and Branch Code as a tuple.""" return (self.party_prefix, self.country_code, self.party_suffix, self.branch_code)
python
{ "resource": "" }
q51931
IBAN.bank_identifier
train
def bank_identifier(self): """Return the IBAN's Bank Identifier.""" end = get_iban_spec(self.country_code).bban_split_pos + 4 return self._id[4:end]
python
{ "resource": "" }
q51932
IBAN.bank_account_number
train
def bank_account_number(self): """Return the IBAN's Bank Account Number.""" start = get_iban_spec(self.country_code).bban_split_pos + 4 return self._id[start:]
python
{ "resource": "" }
q51933
IBAN.elements
train
def elements(self): """Return the IBAN's Country Code, check digits, Bank Identifier and Bank Account Number as tuple.""" return (self.country_code, self.check_digits, self.bank_identifier, self.bank_account_number)
python
{ "resource": "" }
q51934
Config.load
train
def load(self, filename): """read configdata from file. Parameters ---------- filename : string the name of the YAML formatted config file. """ self.filename = filename with open(filename) as CFG: self.data = yaml.load(CFG.read()) ...
python
{ "resource": "" }
q51935
HeartbeatClock.schedule
train
def schedule(self): """Schedule or reschedule the next heartbeat.""" if self.stopped: raise RuntimeError("Can't schedule stopped heartbeat") if self.pendingHeartbeat is None: self._createHeartbeatCall() else: self.pendingHeartbeat.reset(self.period)
python
{ "resource": "" }
q51936
HeartbeatClock.stop
train
def stop(self): """Permanently stop sending heartbeats.""" if not self.stopped: self.stopped = True if self.pendingHeartbeat is not None: self.pendingHeartbeat.cancel() self.pendingHeartbeat = None
python
{ "resource": "" }
q51937
SockJSProtocolMachine.withHeartbeater
train
def withHeartbeater(cls, heartbeater): """Connect a SockJSProtocolMachine to its heartbeater.""" instance = cls(heartbeater) heartbeater.writeHeartbeat = instance.heartbeat return instance
python
{ "resource": "" }
q51938
SockJSProtocolMachine._connectionEstablished
train
def _connectionEstablished(self, transport): '''Store a reference to our transport and write an open frame.''' self.transport = transport self.transport.writeOpen() self.heartbeater.schedule()
python
{ "resource": "" }
q51939
SockJSProtocolMachine._writeToTransport
train
def _writeToTransport(self, data): '''Frame the array-like thing and write it.''' self.transport.writeData(data) self.heartbeater.schedule()
python
{ "resource": "" }
q51940
SockJSProtocolMachine._writeCloseFrame
train
def _writeCloseFrame(self, reason=DISCONNECT.GO_AWAY): '''Write a close frame with the given reason and schedule this connection close. ''' self.transport.writeClose(reason) self.transport.loseConnection() self.transport = None
python
{ "resource": "" }
q51941
SockJSProtocolMachine._stopHeartbeatWithReason
train
def _stopHeartbeatWithReason(self, reason=DISCONNECT.GO_AWAY): '''We lost our connection - stop our heartbeat. This runs when the protocol wants a disconnection. This redundant output ensures that the heartbeater stops immediately after the connection is lost. Twisted will call ...
python
{ "resource": "" }
q51942
RequestSessionMachine._flushBuffer
train
def _flushBuffer(self, request): '''Flush any pending data from the buffer to the request''' assert request is self.requestSession.request self.requestSession.writeData(self.buffer) self.buffer = []
python
{ "resource": "" }
q51943
calculate_priority
train
def calculate_priority(ratios=None, **kwargs): "Calculates a priority score based on a number of attributes." if not ratios: ratios = PRIORITY_FEATURE_WEIGHTS scores = [DEFAULT_PRIORITY_SCORE] for key, value in kwargs.items(): if key not in PRIORITY_FEATURE_WEIGHTS: raise Key...
python
{ "resource": "" }
q51944
adrest_include
train
def adrest_include(parser, token): """ Include adrest_template for any objects. :return str: Rendered string. """ bits = token.split_contents()[1:] args, kwargs = parse_bits( parser, bits, ['content'], 'args', 'kwargs', tuple(), False, 'adrest_include') return AdrestInclusionNo...
python
{ "resource": "" }
q51945
adrest_jsonify
train
def adrest_jsonify(content, **options): """ Serialize any object to JSON . :return str: Rendered string. """ from adrest.utils.serializer import JSONSerializer worker = JSONSerializer(**options) return worker.serialize(content)
python
{ "resource": "" }
q51946
AdrestInclusionNode.render
train
def render(self, context): """ Render node. :return str: Rendered string. """ try: args, ctx = self.get_resolved_arguments(context) target = args[0] if not target: return '' ctx['content'] = target except VariableD...
python
{ "resource": "" }
q51947
UpdateExpression.inc
train
def inc(self, *args, **kwargs): ''' Atomically increment ``qfield`` by ``value`` ''' pairs = [] if len(args) == 1: pairs.append((args[0], 1)) elif len(args) == 2: pairs.append(args) elif len(kwargs) != 0: pairs.extend([(k, v) for k, v in kwargs...
python
{ "resource": "" }
q51948
UpdateExpression.remove
train
def remove(self, qfield, value): ''' Atomically remove ``value`` from ``qfield``''' if isinstance(value, QueryExpression): return self._atomic_expression_op('$pull', qfield, value) return self._atomic_list_op('$pull', qfield, value)
python
{ "resource": "" }
q51949
IntfIpMeta._asQuartusTcl
train
def _asQuartusTcl(self, buff: List[str], version: str, intfName: str, component: "Component", packager: "IpPackager", thisIf: 'Interface', intfMapOrName: Dict[str, Union[Dict, str]]): """ Add interface to Quartus tcl by specified name map :param buff:...
python
{ "resource": "" }
q51950
IntfIpMeta.asQuartusTcl
train
def asQuartusTcl(self, buff: List[str], version: str, component: "Component", packager: "IpPackager", thisIf: 'Interface'): """ Add interface to Quartus tcl :param buff: line buffer for output :param version: Quartus version :param intfName: name of top inte...
python
{ "resource": "" }
q51951
IntfIpMeta.quartus_tcl_add_interface
train
def quartus_tcl_add_interface(self, buff, thisIntf, packager): """ Create interface in Quartus TCL :return: add_interface command string """ if packager.getInterfaceDirection(thisIntf) == INTF_DIRECTION.MASTER: dir_ = "start" else: dir_ = "end" ...
python
{ "resource": "" }
q51952
IntfIpMeta.quartus_prop
train
def quartus_prop(self, buff: List[str], intfName: str, name: str, value, escapeStr=True): """ Set property on interface in Quartus TCL :param buff: line buffer for output :param intfName: name of interface to set property on :param name: property name ...
python
{ "resource": "" }
q51953
IntfIpMeta.quartus_add_interface_port
train
def quartus_add_interface_port(self, buff: List[str], intfName: str, signal, logicName: str, packager: "IpCorePackager"): """ Add subinterface to Quartus interface :param buff: line buffer for output :param intfName: name of top interface :para...
python
{ "resource": "" }
q51954
record_is_valid
train
def record_is_valid(record): "Checks if a record is valid for processing." # No random contigs if record.CHROM.startswith('GL'): return False # Skip results with a read depth < 5. If no read depth is specified then # we have no choice but to consider this record as being valid. if 'DP'...
python
{ "resource": "" }
q51955
extend_env
train
def extend_env(extra_env): """ Copies and extends the current environment with the values present in `extra_env`. """ env = os.environ.copy() env.update(extra_env) return env
python
{ "resource": "" }
q51956
get_env_str
train
def get_env_str(env): """ Gets a string representation of a dict as though it contained environment variable values. """ return ' '.join("{0}='{1}'".format(k, v) for k, v in env.items())
python
{ "resource": "" }
q51957
pipe_commands
train
def pipe_commands(cmds, extra_env=None, show_stderr=False, show_last_stdout=False): """ Executes the list of commands piping each one into the next. """ env = extend_env(extra_env) if extra_env else None env_str = (get_env_str(extra_env) + ' ') if extra_env else '' cmd_strs = [env_str + ' '.join...
python
{ "resource": "" }
q51958
pipe_commands_to_file
train
def pipe_commands_to_file(cmds, path, extra_env=None, show_stderr=False): """ Executes the list of commands piping each one into the next and writing stdout of the last process into a file at the given path. """ env = extend_env(extra_env) if extra_env else None env_str = (get_env_str(extra_env)...
python
{ "resource": "" }
q51959
for_all
train
def for_all(*generators): """ Takes a list of generators and returns a closure which takes a property, then tests the property against arbitrary instances of the generators. """ # Pass in n as an argument n = 100 def test_property(property_function): """ A closure which take...
python
{ "resource": "" }
q51960
maybe_a
train
def maybe_a(generator): """ Generates either an arbitrary value of the specified generator or None. This is a class factory, it makes a class which is a closure around the specified generator. """ class MaybeAGenerator(ArbitraryInterface): """ A closure class around the generato...
python
{ "resource": "" }
q51961
one_of
train
def one_of(*generators): """ Generates an arbitrary value of one of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators. """ class OneOfGenerators(ArbitraryInterface): """ A closure class around the generators sp...
python
{ "resource": "" }
q51962
tuple_of
train
def tuple_of(*generators): """ Generates a tuple by generating values for each of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators. """ class TupleOfGenerators(ArbitraryInterface): """ A closure class arou...
python
{ "resource": "" }
q51963
set_of
train
def set_of(*generators): """ Generates a set consisting solely of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators. """ class SetOfGenerators(ArbitraryInterface): """ A closure class around the generators spec...
python
{ "resource": "" }
q51964
list_of
train
def list_of(*generators): """ Generates a list consisting solely of the specified generators. This is a class factory, it makes a class which is a closure around the specified generators. """ class ListOfGenerators(ArbitraryInterface): """ A closure class around the generators s...
python
{ "resource": "" }
q51965
dict_of
train
def dict_of(**kwargs): """ Generates a homogeneous dict of the specified generators using kwargs. You can generate non-homogeneous dicts using `dict`. This is a class factory, it makes a class which is a closure around the specified keys and generators. """ class DictOfKeyGenerators(Arbitra...
python
{ "resource": "" }
q51966
Dashboard.__make_skeleton
train
def __make_skeleton(self, path): """This method creates the folder tree which will contain the website.""" self.path = path if os.path.exists(os.path.join(self.path, "output", self.name)): shutil.rmtree(os.path.join(self.path, "output", self.name)) self.path...
python
{ "resource": "" }
q51967
Dashboard.__copy_static
train
def __copy_static(self, template, output_path): """This method takes the files in css and js folders of the template and copy to final folders""" self.path_static = os.path.join(template, "static", "css") for file in os.listdir(self.path_static): print(file) shut...
python
{ "resource": "" }
q51968
Dashboard.__save_plots_of_the_current_page
train
def __save_plots_of_the_current_page(self, section, page, output_path): """This method saves plots in the appropriate section folder. As a consequence two plots cannot have the same name within the same section.""" for key in self.sections[section].pages[page].elements.keys(): ...
python
{ "resource": "" }
q51969
Dashboard.__create_template_vars_index
train
def __create_template_vars_index(self): """This method will create the dictionnary to be passed in the template in order to generate index.html""" template_vars = {} template_vars["index"] = True template_vars["name"] = self.name template_vars["title"] = self.title ...
python
{ "resource": "" }
q51970
Dashboard.__create_template_vars
train
def __create_template_vars(self, section, page): """This method will create the dictionnary to be passed in the template in order to generate each page""" template_vars = {} template_vars["index"] = False template_vars["name"] = self.name template_vars["...
python
{ "resource": "" }
q51971
Element.add_table
train
def add_table(self, dataframe, isStyled = False): """This method stores plain html string.""" if isStyled : table_string = dataframe.render() else : table_string = dataframe.style.render() table_string = table_string.replace("\n", "").replace("<table...
python
{ "resource": "" }
q51972
cache_invalidate_by_tags
train
def cache_invalidate_by_tags(tags, cache=None): """ Clear cache by tags. """ if isinstance(tags, basestring): tags = [tags] tag_keys = [CACHE_TAG_KEY % tag for tag in tags if tag] if not tag_keys: raise ValueError('Attr tags invalid') if cache is None: cache = default...
python
{ "resource": "" }
q51973
main
train
def main(): '''i2a creates ASCII art from images right on your terminal.''' arguments = docopt(__doc__, version=__version__) if arguments['FILE']: display_output(arguments) else: print(__doc__)
python
{ "resource": "" }
q51974
check_dups
train
def check_dups( iterable, debug_limit=1000, ): """ Checks an iterable for duplicates Note that it does not make sense to call this on a set() If calling on a collection without a .count method, set @debug_limit to -1. For custom equality comparisons, create a custom ...
python
{ "resource": "" }
q51975
_prepare_nameparser_constants
train
def _prepare_nameparser_constants(): """Prepare nameparser Constants. Remove nameparser's titles and use our own and add as suffixes the roman numerals. Configuration is the same for all names (i.e. instances). """ constants = Constants() roman_numeral_suffixes = [u'v', u'vi', u'vii', u'viii', ...
python
{ "resource": "" }
q51976
_generate_non_lastnames_variations
train
def _generate_non_lastnames_variations(non_lastnames): """Generate variations for all non-lastnames. E.g. For 'John Richard', this method generates: [ 'John', 'J', 'Richard', 'R', 'John Richard', 'John R', 'J Richard', 'J R', ] """ if not non_lastnames: return [] # Generate nam...
python
{ "resource": "" }
q51977
_generate_lastnames_variations
train
def _generate_lastnames_variations(lastnames): """Generate variations for lastnames. Note: This method follows the assumption that the first last name is the main one. E.g. For 'Caro Estevez', this method generates: ['Caro', 'Caro Estevez']. In the case the lastnames are dashed, it spli...
python
{ "resource": "" }
q51978
generate_name_variations
train
def generate_name_variations(name): """Generate name variations for a given name. Args: name (six.text_type): The name whose variations are to be generated. Returns: list: All the name variations for the given name. Notes: Uses `unidecode` for doing unicode characters translit...
python
{ "resource": "" }
q51979
ParsedName.loads
train
def loads(cls, name): """Load a parsed name from a string. Raises: TypeError: when name isn't a type of `six.string_types`. ValueError: when name is empty or None. """ if not isinstance(name, six.string_types): raise TypeError(u'arguments to {classnam...
python
{ "resource": "" }
q51980
ParsedName.pprint
train
def pprint(self, initials_only=False): """Pretty print the name. Args: initials_only (bool): ``True`` if we want the first names to be displayed with only the initial followed by a dot. ``False`` otherwise. Examples: >>> ParsedName('Lieber, Stanley Martin')....
python
{ "resource": "" }
q51981
partition_range
train
def partition_range(stop, annotations=None): """ Partition the range from 0 to `stop` based on annotations. >>> partition_range(50, annotations=[[(0, 21), (30, 35)], ... [(15, 32), (40, 46)]]) [(0, 15, {0}), (15, 21, {0, 1}), (21, 30, {...
python
{ "resource": "" }
q51982
pprint_sequence
train
def pprint_sequence(sequence, annotations=None, block_length=10, blocks_per_line=6, format=PlaintextFormat): """ Pretty-print sequence for use with a monospace font. >>> sequence = 'MIMANQPLWLDSEVEMNHYQQSHIKSKSPYFPEDKHICWIKIFKAFGT' * 4 >>> print pprint_sequence(sequence, for...
python
{ "resource": "" }
q51983
http.bind
train
def bind(cls, param=None, **kwargs): """Bind middleware's method as endpoint. """ def stick(function, **binding): if not asyncio.iscoroutine(function): function = asyncio.coroutine(function) bindings = getattr(function, STICKER, []) bindings.ap...
python
{ "resource": "" }
q51984
Reader.seek
train
def seek(self, pos): """ Move to new input file position. If position is negative or out of file, raise Exception. """ if (pos > self.file_size) or (pos < 0): raise Exception("Unable to seek - position out of file!") self.file.seek(pos)
python
{ "resource": "" }
q51985
Reader.read_string
train
def read_string(self): """ Read string from input file with UTF-8 encoding. """ length = self.read_int() return str(self.read(length).decode("UTF-8"))
python
{ "resource": "" }
q51986
GaResource.get
train
def get(self, request, path=None, **resources): """ Proxy request to GA. """ tracker = Tracker( self._meta.account_id, self._meta.domain or request.META.get('SERVER_NAME')) visitor = Visitor() visitor.extract_from_server_meta(request.META) session = Sessio...
python
{ "resource": "" }
q51987
EmitterMixin.determine_emitter
train
def determine_emitter(cls, request): """ Get emitter for request. :return emitter: Instance of adrest.utils.emitters.BaseEmitter """ default_emitter = cls._meta.emitters[0] if not request: return default_emitter if request.method == 'OPTIONS': r...
python
{ "resource": "" }
q51988
list_jobs
train
def list_jobs(tail): """Show info about the existing crawler jobs.""" query = ( db.session.query(models.CrawlerJob) .order_by(models.CrawlerJob.id.desc()) ) if tail != 0: query = query.limit(tail) results = query.yield_per(10).all() _show_table(results=results)
python
{ "resource": "" }
q51989
get_job_logs
train
def get_job_logs(id): """Get the crawl logs from the job.""" crawler_job = models.CrawlerJob.query.filter_by(id=id).one_or_none() if crawler_job is None: click.secho( ( "CrawlJob %s was not found, maybe it's not a crawl job?" % id ), ...
python
{ "resource": "" }
q51990
get_job_results
train
def get_job_results(id): """Get the crawl results from the job.""" crawler_job = models.CrawlerJob.query.filter_by(id=id).one() _show_file( file_path=crawler_job.results, header_name='Results', )
python
{ "resource": "" }
q51991
list_crawler_workflows
train
def list_crawler_workflows(tail): """Show info about the existing crawler workflows.""" query = ( models.CrawlerWorkflowObject.query .order_by(models.CrawlerWorkflowObject.object_id.desc()) ) if tail != 0: query = query.limit(tail) workflows = query.yield_per(10).all() _...
python
{ "resource": "" }
q51992
get_job_logs_from_workflow
train
def get_job_logs_from_workflow(workflow_id): """Retrieve the crawl logs from the workflow id.""" query_result = ( db.session.query( models.CrawlerJob.logs, ) .join( models.CrawlerWorkflowObject, models.CrawlerJob.job_id == models.CrawlerWorkflowObject....
python
{ "resource": "" }
q51993
schedule_crawl_cli
train
def schedule_crawl_cli(spider_name, workflow_name, dont_force_crawl, kwarg): """Schedule a new crawl. Note: Currently the oaiharvesting is done on inspire side, before this, so it's not supported here yet. """ extra_kwargs = {} for extra_kwarg in kwarg: if '=' not in extra_k...
python
{ "resource": "" }
q51994
get_memory_usage
train
def get_memory_usage(user=None): """ Returns a three-tupel with memory usage for the given user. The result contains:: (total memory, largest process' memory, largest process name) :param user: String representing the user. If `None`, the total size of all processes for all users will b...
python
{ "resource": "" }
q51995
CannonModel.train_global
train
def train_global(self, label_vector_description=None, N=None, limits=None, pivot=True, **kwargs): """ Train the model in a Cannon-like fashion using the grid points as labels and the intensities as normalised rest-frame fluxes. """ lv = self._cannon_label_vector if label...
python
{ "resource": "" }
q51996
CannonModel.train_local
train
def train_local(self, closest_point, label_vector_description=None, N=None, pivot=True, **kwargs): """ Train the model in a Cannon-like fashion using the grid points as labels and the intensities as normalsied rest-frame fluxes within some local regime. """ lv = ...
python
{ "resource": "" }
q51997
CannonModel.train_and_save
train
def train_and_save(self, model_filename, cannon_data_filename, clobber=False, **kwargs): """ Train the Cannon coefficients. """ if any(map(os.path.exists, (model_filename, cannon_data_filename))) and not clobber: raise IOError("output file already exists...
python
{ "resource": "" }
q51998
SRefField.dereference
train
def dereference(self, session, ref, allow_none=False): """ Dereference an ObjectID to this field's underlying type """ ref = DBRef(id=ref, collection=self.type.type.get_collection_name(), database=self.db) ref.type = self.type.type return session.dereference(ref, allo...
python
{ "resource": "" }
q51999
RefField.unwrap
train
def unwrap(self, value, fields=None, session=None): ''' If ``autoload`` is False, return a DBRef object. Otherwise load the object. ''' self.validate_unwrap(value) value.type = self.type return value
python
{ "resource": "" }