_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q263500
Client.disconnect
validation
def disconnect(self): """Disconnect from the server""" logger.info(u'Disconnecting')
python
{ "resource": "" }
q263501
Client.send
validation
def send(self, command, timeout=5): """Send a command to the server :param string command: command to send """ logger.info(u'Sending %s' % command) _, writable, __ =
python
{ "resource": "" }
q263502
Client._readline
validation
def _readline(self): """Read a line from the server. Data is read from the socket until a character ``\n`` is found :return: the read line :rtype: string """ line = '' while 1: readable, _, __ = select.select([self.sock], [], [], 0.5) if self._stop: break if not readable:
python
{ "resource": "" }
q263503
Client._readblock
validation
def _readblock(self): """Read a block from the server. Lines are read until a character ``.`` is found :return: the read block :rtype: string """ block = ''
python
{ "resource": "" }
q263504
Client._readxml
validation
def _readxml(self): """Read a block and return the result as XML :return: block as xml :rtype: xml.etree.ElementTree
python
{ "resource": "" }
q263505
cli
validation
def cli(id): """Analyse an OpenStreetMap changeset.""" ch = Analyse(id) ch.full_analysis() click.echo( 'Created: %s. Modified: %s. Deleted: %s' % (ch.create, ch.modify, ch.delete) ) if ch.is_suspect: click.echo('The changeset {} is suspect! Reasons: {}'.format(
python
{ "resource": "" }
q263506
get_user_details
validation
def get_user_details(user_id): """Get information about number of changesets, blocks and mapping days of a user, using both the OSM API and the Mapbox comments APIself. """ reasons = [] try: url = OSM_USERS_API.format(user_id=requests.compat.quote(user_id)) user_request = requests.get(url) if user_request.status_code == 200: user_data = user_request.content xml_data = ET.fromstring(user_data).getchildren()[0].getchildren() changesets = [i for i in xml_data if i.tag == 'changesets'][0] blocks = [i for i in xml_data if i.tag == 'blocks'][0] if int(changesets.get('count')) <= 5: reasons.append('New mapper') elif int(changesets.get('count')) <= 30: url = MAPBOX_USERS_API.format( user_id=requests.compat.quote(user_id) ) user_request = requests.get(url)
python
{ "resource": "" }
q263507
changeset_info
validation
def changeset_info(changeset): """Return a dictionary with id, user, user_id, bounds, date of creation and all the tags of the changeset. Args: changeset: the XML string of the changeset. """ keys = [tag.attrib.get('k') for tag
python
{ "resource": "" }
q263508
get_changeset
validation
def get_changeset(changeset): """Get the changeset using the OSM API and return the content as a XML ElementTree. Args: changeset: the id of the changeset. """
python
{ "resource": "" }
q263509
get_metadata
validation
def get_metadata(changeset): """Get the metadata of a changeset using the OSM API and return it as a XML ElementTree. Args: changeset: the id of the changeset.
python
{ "resource": "" }
q263510
ChangesetList.get_area
validation
def get_area(self, geojson): """Read the first feature from the geojson and return it as a Polygon
python
{ "resource": "" }
q263511
ChangesetList.filter
validation
def filter(self): """Filter the changesets that intersects with the geojson geometry.""" self.content = [ ch for ch
python
{ "resource": "" }
q263512
Analyse.set_fields
validation
def set_fields(self, changeset): """Set the fields of this class with the metadata of the analysed changeset. """ self.id = int(changeset.get('id')) self.user = changeset.get('user') self.uid = changeset.get('uid') self.editor = changeset.get('created_by', None) self.review_requested = changeset.get('review_requested', False) self.host = changeset.get('host', 'Not reported') self.bbox = changeset.get('bbox').wkt self.comment = changeset.get('comment',
python
{ "resource": "" }
q263513
Analyse.label_suspicious
validation
def label_suspicious(self, reason): """Add suspicion reason and set the suspicious flag."""
python
{ "resource": "" }
q263514
Analyse.full_analysis
validation
def full_analysis(self): """Execute the count and verify_words methods.""" self.count() self.verify_words() self.verify_user()
python
{ "resource": "" }
q263515
Analyse.verify_words
validation
def verify_words(self): """Verify the fields source, imagery_used and comment of the changeset for some suspect words. """ if self.comment: if find_words(self.comment, self.suspect_words, self.excluded_words): self.label_suspicious('suspect_word') if self.source: for word in self.illegal_sources: if word in self.source.lower(): self.label_suspicious('suspect_word')
python
{ "resource": "" }
q263516
Analyse.verify_editor
validation
def verify_editor(self): """Verify if the software used in the changeset is a powerfull_editor. """ powerful_editors = [ 'josm', 'level0', 'merkaartor', 'qgis', 'arcgis', 'upload.py', 'osmapi', 'Services_OpenStreetMap' ] if self.editor is not None: for editor in powerful_editors: if editor in self.editor.lower(): self.powerfull_editor = True break if 'iD' in self.editor: trusted_hosts = [ 'www.openstreetmap.org/id', 'www.openstreetmap.org/edit', 'improveosm.org', 'strava.github.io/iD', 'preview.ideditor.com/release', 'preview.ideditor.com/master',
python
{ "resource": "" }
q263517
Analyse.count
validation
def count(self): """Count the number of elements created, modified and deleted by the changeset and analyses if it is a possible import, mass modification or a mass deletion. """ xml = get_changeset(self.id) actions = [action.tag for action in xml.getchildren()] self.create = actions.count('create') self.modify = actions.count('modify') self.delete = actions.count('delete') self.verify_editor() try: if (self.create / len(actions) > self.percentage and self.create > self.create_threshold and (self.powerfull_editor or self.create > self.top_threshold)): self.label_suspicious('possible import')
python
{ "resource": "" }
q263518
_unwrap_stream
validation
def _unwrap_stream(uri, timeout, scanner, requests_session): """ Get a stream URI from a playlist URI, ``uri``. Unwraps nested playlists until something that's not a playlist is found or the ``timeout`` is reached. """ original_uri = uri seen_uris = set() deadline = time.time() + timeout while time.time() < deadline: if uri in seen_uris: logger.info( 'Unwrapping stream from URI (%s) failed: ' 'playlist referenced itself', uri) return None else: seen_uris.add(uri) logger.debug('Unwrapping stream from URI: %s', uri) try: scan_timeout = deadline - time.time() if scan_timeout < 0: logger.info( 'Unwrapping stream from URI (%s) failed: ' 'timed out in %sms', uri, timeout) return None scan_result = scanner.scan(uri, timeout=scan_timeout) except exceptions.ScannerError as exc: logger.debug('GStreamer failed scanning URI (%s): %s', uri, exc) scan_result = None if scan_result is not None and not ( scan_result.mime.startswith('text/') or scan_result.mime.startswith('application/')): logger.debug( 'Unwrapped potential %s stream: %s', scan_result.mime, uri)
python
{ "resource": "" }
q263519
Worker.serve
validation
def serve(self, sock, request_handler, error_handler, debug=False, request_timeout=60, ssl=None, request_max_size=None, reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100, **kwargs): """Start asynchronous HTTP Server on an individual process. :param request_handler: Sanic request handler with middleware :param error_handler: Sanic error handler with middleware :param debug: enables debug output (slows server) :param request_timeout: time in seconds :param ssl: SSLContext :param sock: Socket for the server to accept connections from :param request_max_size: size in bytes, `None` for no limit :param reuse_port: `True` for multiple workers :param loop: asyncio compatible event loop :param protocol: subclass of asyncio protocol class :return: Nothing """ if debug: loop.set_debug(debug) server = partial( protocol, loop=loop, connections=self.connections,
python
{ "resource": "" }
q263520
Pantheon.spawn
validation
def spawn(self, generations): """Grow this Pantheon by multiplying Gods.""" egg_donors = [god for god in self.gods.values() if god.chromosomes == 'XX'] sperm_donors = [god for god in self.gods.values() if god.chromosomes == 'XY'] for i in range(generations): print("\nGENERATION %d\n" % (i+1)) gen_xx = [] gen_xy = [] for egg_donor in egg_donors: sperm_donor = random.choice(sperm_donors) brood = self.breed(egg_donor, sperm_donor) for child in brood: if child.divinity > human: # divine offspring join the Pantheon self.add_god(child) if child.chromosomes == 'XX':
python
{ "resource": "" }
q263521
Pantheon.breed
validation
def breed(self, egg_donor, sperm_donor): """Get it on.""" offspring = [] try: num_children = npchoice([1,2], 1, p=[0.8, 0.2])[0] # 20% chance of twins for _ in range(num_children): child = God(egg_donor, sperm_donor)
python
{ "resource": "" }
q263522
cosine
validation
def cosine(vec1, vec2): """Compare vectors. Borrowed from A. Parish.""" if norm(vec1)
python
{ "resource": "" }
q263523
God.set_gender
validation
def set_gender(self, gender=None): """This model recognizes that sex chromosomes don't always line up with gender. Assign M, F, or NB according to the probabilities in p_gender. """ if gender and gender in genders:
python
{ "resource": "" }
q263524
God.set_inherited_traits
validation
def set_inherited_traits(self, egg_donor, sperm_donor): """Accept either strings or Gods as inputs.""" if type(egg_donor) == str:
python
{ "resource": "" }
q263525
God.reproduce_asexually
validation
def reproduce_asexually(self, egg_word, sperm_word): """Produce two gametes, an egg and a sperm, from the input strings. Combine them to produce a genome a la sexual
python
{ "resource": "" }
q263526
God.reproduce_sexually
validation
def reproduce_sexually(self, egg_donor, sperm_donor): """Produce two gametes, an egg and a sperm, from input Gods. Combine them to produce a genome a la sexual reproduction. Assign divinity according to probabilities in p_divinity. The more divine the parents, the more divine their offspring. """ egg_word = random.choice(egg_donor.genome) egg = self.generate_gamete(egg_word) sperm_word = random.choice(sperm_donor.genome) sperm = self.generate_gamete(sperm_word)
python
{ "resource": "" }
q263527
God.generate_gamete
validation
def generate_gamete(self, egg_or_sperm_word): """Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens by searching the list of tokens for words that are related to the given egg_or_sperm_word. """ p_rate_of_mutation = [0.9, 0.1] should_use_mutant_pool = (npchoice([0,1], 1, p=p_rate_of_mutation)[0] == 1)
python
{ "resource": "" }
q263528
God.print_parents
validation
def print_parents(self): """Print parents' names and epithets.""" if self.gender == female: title = 'Daughter' elif self.gender == male:
python
{ "resource": "" }
q263529
Stage.instance
validation
def instance(self, counter=None, pipeline_counter=None): """Returns all the information regarding a specific stage run See the `Go stage instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-stage-instance Args: counter (int): The stage instance to fetch. If falsey returns the latest stage instance from :meth:`history`. pipeline_counter (int): The pipeline instance for which to fetch the stage. If falsey returns the latest pipeline instance. Returns: Response: :class:`gocd.api.response.Response` object """ pipeline_counter = pipeline_counter or self.pipeline_counter pipeline_instance = None if not pipeline_counter: pipeline_instance = self.server.pipeline(self.pipeline_name).instance() self.pipeline_counter = int(pipeline_instance['counter']) if not counter: if pipeline_instance is None: pipeline_instance = ( self.server
python
{ "resource": "" }
q263530
Server.request
validation
def request(self, path, data=None, headers=None, method=None): """Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present this request will become a POST request. headers (dict, optional): Headers to set for this particular request Raises: HTTPError: when the HTTP request fails. Returns:
python
{ "resource": "" }
q263531
Server.add_logged_in_session
validation
def add_logged_in_session(self, response=None): """Make the request appear to be coming from a browser This is to interact with older parts of Go that doesn't have a proper API call to be made. What will be done: 1. If no response passed in a call to `go/api/pipelines.xml` is made to get a valid session 2. `JSESSIONID` will be populated from this request 3. A request to `go/pipelines` will be so the `authenticity_token` (CSRF) can be extracted. It will then silently be injected into `post_args` on any POST calls that doesn't start with `go/api` from this point. Args: response: a :class:`Response` object from a previously successful API call. So we won't have to query `go/api/pipelines.xml` unnecessarily. Raises: HTTPError: when the HTTP request fails. AuthenticationFailed: when failing to get the `session_id` or the `authenticity_token`. """ if not response:
python
{ "resource": "" }
q263532
flatten
validation
def flatten(d): """Return a dict as a list of lists. >>> flatten({"a": "b"}) [['a', 'b']] >>> flatten({"a": [1, 2, 3]}) [['a', [1, 2, 3]]] >>> flatten({"a": {"b": "c"}}) [['a', 'b', 'c']] >>> flatten({"a": {"b": {"c": "e"}}}) [['a', 'b', 'c', 'e']] >>> flatten({"a": {"b": "c", "d": "e"}}) [['a', 'b', 'c'], ['a', 'd',
python
{ "resource": "" }
q263533
Pipeline.instance
validation
def instance(self, counter=None): """Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. If falsey returns the latest pipeline instance from :meth:`history`. Returns: Response: :class:`gocd.api.response.Response` object """ if not counter:
python
{ "resource": "" }
q263534
Pipeline.schedule
validation
def schedule(self, variables=None, secure_variables=None, materials=None, return_new_instance=False, backoff_time=1.0): """Schedule a pipeline run Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`. Args: variables (dict, optional): Variables to set/override secure_variables (dict, optional): Secure variables to set/override materials (dict, optional): Material revisions to be used for this pipeline run. The exact format for this is a bit iffy, have a look at the official `Go pipeline scheduling documentation`__ or inspect a call from triggering manually in the UI. return_new_instance (bool): Returns a :meth:`history` compatible response for the newly scheduled instance. This is primarily so users easily can get the new instance number. **Note:** This is done in a very naive way, it just checks that the instance number is higher than before the pipeline was triggered. backoff_time (float): How long between each check for
python
{ "resource": "" }
q263535
Pipeline.console_output
validation
def console_output(self, instance=None): """Yields the output and metadata from all jobs in the pipeline Args: instance: The result of a :meth:`instance` call, if not supplied the latest of the pipeline will be used. Yields: tuple: (metadata (dict), output (str)). metadata contains: - pipeline - pipeline_counter - stage - stage_counter - job - job_result """ if instance is None: instance = self.instance() for stage in instance['stages']: for job in stage['jobs']: if job['result'] not in self.final_results: continue artifact = self.artifact( instance['counter'], stage['name'],
python
{ "resource": "" }
q263536
TemplateConfig.edit
validation
def edit(self, config, etag): """Update template config for specified template name. .. __: https://api.go.cd/current/#edit-template-config Returns: Response: :class:`gocd.api.response.Response` object """ data = self._json_encode(config) headers = self._default_headers() if etag is not
python
{ "resource": "" }
q263537
TemplateConfig.create
validation
def create(self, config): """Create template config for specified template name. .. __: https://api.go.cd/current/#create-template-config Returns: Response: :class:`gocd.api.response.Response` object """ assert config["name"] == self.name, "Given config is not for this template"
python
{ "resource": "" }
q263538
TemplateConfig.delete
validation
def delete(self): """Delete template config for specified template name. .. __: https://api.go.cd/current/#delete-a-template Returns: Response: :class:`gocd.api.response.Response` object """ headers = self._default_headers() return self._request(self.name,
python
{ "resource": "" }
q263539
PipelineGroups.pipelines
validation
def pipelines(self): """Returns a set of all pipelines from the last response Returns: set: Response success: all the pipelines available in the response Response failure: an empty set
python
{ "resource": "" }
q263540
Artifact.get_directory
validation
def get_directory(self, path_to_directory, timeout=30, backoff=0.4, max_wait=4): """Gets an artifact directory by its path. See the `Go artifact directory documentation`__ for example responses. .. __: http://api.go.cd/current/#get-artifact-directory .. note:: Getting a directory relies on Go creating a zip file of the directory in question. Because of this Go will zip the file in the background and return a 202 Accepted response. It's then up to the client to check again later and get the final file. To work with normal assumptions this :meth:`get_directory` will retry itself up to ``timeout`` seconds to get a 200 response to return. At that point it will then return the response as is, no matter whether it's still 202 or 200. The retry is done with an exponential backoff with a max value between retries. See the ``backoff`` and ``max_wait`` variables. If you want to handle the retry logic yourself then use :meth:`get` and add '.zip' as a suffix on the directory. Args: path_to_directory (str): The path to the directory to get. It can be nested eg ``target/dist.zip`` timeout (int): How many seconds we will wait in total for a
python
{ "resource": "" }
q263541
config_loader
validation
def config_loader(app, **kwargs_config): """Configuration loader. Adds support for loading templates from the Flask application's instance folder (``<instance_folder>/templates``). """ # This is the only place customize the Flask application right after # it has been created, but before all extensions etc are loaded. local_templates_path = os.path.join(app.instance_path, 'templates') if os.path.exists(local_templates_path): # Let's customize the template loader to look into packages #
python
{ "resource": "" }
q263542
app_class
validation
def app_class(): """Create Flask application class. Invenio-Files-REST needs to patch the Werkzeug form parsing in order to support streaming large file uploads. This is done by subclassing the Flask application class. """ try: pkg_resources.get_distribution('invenio-files-rest') from invenio_files_rest.app import Flask as FlaskBase except pkg_resources.DistributionNotFound: from flask import Flask as FlaskBase
python
{ "resource": "" }
q263543
InvenioApp.init_app
validation
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ # Init the configuration self.init_config(app) # Enable Rate limiter self.limiter = Limiter(app, key_func=get_ipaddr) # Enable secure HTTP headers if app.config['APP_ENABLE_SECURE_HEADERS']: self.talisman = Talisman( app, **app.config.get('APP_DEFAULT_SECURE_HEADERS', {}) ) # Enable PING view if app.config['APP_HEALTH_BLUEPRINT_ENABLED']: blueprint = Blueprint('invenio_app_ping', __name__) @blueprint.route('/ping') def ping(): """Load balancer ping view.""" return 'OK' ping.talisman_view_options = {'force_https': False} app.register_blueprint(blueprint) requestid_header = app.config.get('APP_REQUESTID_HEADER') if requestid_header: @app.before_request def set_request_id(): """Extracts a request id from an HTTP header."""
python
{ "resource": "" }
q263544
InvenioApp.init_config
validation
def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ config_apps = ['APP_', 'RATELIMIT_'] flask_talisman_debug_mode = ["'unsafe-inline'"] for k in dir(config): if any([k.startswith(prefix) for prefix in config_apps]): app.config.setdefault(k, getattr(config, k)) if app.config['DEBUG']: app.config.setdefault('APP_DEFAULT_SECURE_HEADERS', {}) headers = app.config['APP_DEFAULT_SECURE_HEADERS'] # ensure `content_security_policy` is not set to {} if headers.get('content_security_policy') != {}: headers.setdefault('content_security_policy', {})
python
{ "resource": "" }
q263545
camel2word
validation
def camel2word(string): """Covert name from CamelCase to "Normal case". >>> camel2word('CamelCase') 'Camel case' >>> camel2word('CaseWithSpec') 'Case with spec' """
python
{ "resource": "" }
q263546
SpecPlugin.format_seconds
validation
def format_seconds(self, n_seconds): """Format a time in seconds.""" func = self.ok if n_seconds >= 60: n_minutes, n_seconds = divmod(n_seconds, 60)
python
{ "resource": "" }
q263547
ppdict
validation
def ppdict(dict_to_print, br='\n', html=False, key_align='l', sort_keys=True, key_preffix='', key_suffix='', value_prefix='', value_suffix='', left_margin=3, indent=2): """Indent representation of a dict""" if dict_to_print: if sort_keys: dic = dict_to_print.copy() keys = list(dic.keys()) keys.sort() dict_to_print = OrderedDict() for k in keys: dict_to_print[k] = dic[k] tmp = ['{'] ks = [type(x) == str and "'%s'" % x or x for x in dict_to_print.keys()]
python
{ "resource": "" }
q263548
_assert_contains
validation
def _assert_contains(haystack, needle, invert, escape=False): """ Test for existence of ``needle`` regex within ``haystack``. Say ``escape`` to escape the ``needle`` if you aren't really using the regex feature & have special characters in it. """ myneedle = re.escape(needle) if escape else needle matched = re.search(myneedle, haystack, re.M) if (invert and
python
{ "resource": "" }
q263549
flag_inner_classes
validation
def flag_inner_classes(obj): """ Mutates any attributes on ``obj`` which are classes, with link to ``obj``. Adds a convenience accessor which instantiates ``obj`` and then calls its ``setup`` method. Recurses on those objects as well. """ for tup in class_members(obj):
python
{ "resource": "" }
q263550
pvpc_calc_tcu_cp_feu_d
validation
def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True): """Procesa TCU, CP, FEU diario. :param df: :param verbose: :param convert_kwh: :return: """ if 'TCU' + TARIFAS[0] not in df.columns: # Pasa de €/MWh a €/kWh: if convert_kwh: cols_mwh = [c + t for c in COLS_PVPC for t in TARIFAS if c != 'COF'] df[cols_mwh] = df[cols_mwh].applymap(lambda x: x / 1000.) # Obtiene columnas TCU, CP, precio día gb_t = df.groupby(lambda x: TARIFAS[np.argmax([t in x for t in TARIFAS])], axis=1) for k, g in gb_t: if verbose: print('TARIFA {}'.format(k)) print(g.head()) # Cálculo de TCU df['TCU{}'.format(k)] = g[k] - g['TEU{}'.format(k)] # Cálculo de CP # cols_cp = [c + k for c in ['FOS', 'FOM', 'INT', 'PCAP', 'PMH', 'SAH']] cols_cp = [c + k for c in COLS_PVPC if c not in ['', 'COF', 'TEU']] df['CP{}'.format(k)] = g[cols_cp].sum(axis=1) # Cálculo de PERD --> No es posible así, ya que los
python
{ "resource": "" }
q263551
SplunkLogger._compress
validation
def _compress(self, input_str): """ Compress the log message in order to send less bytes to the wire. """ compressed_bits = cStringIO.StringIO()
python
{ "resource": "" }
q263552
SpecSelector.registerGoodClass
validation
def registerGoodClass(self, class_): """ Internal bookkeeping to handle nested classes """ # Class itself added to "good" list
python
{ "resource": "" }
q263553
SpecSelector.isValidClass
validation
def isValidClass(self, class_): """ Needs to be its own method so it can be called from both wantClass and registerGoodClass. """ module = inspect.getmodule(class_) valid = ( module in self._valid_modules
python
{ "resource": "" }
q263554
PVPC.get_resample_data
validation
def get_resample_data(self): """Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.""" if self.data is not None: if self._pvpc_mean_daily is None: self._pvpc_mean_daily = self.data['data'].resample('D').mean() if self._pvpc_mean_monthly is
python
{ "resource": "" }
q263555
sanitize_path
validation
def sanitize_path(path): """Performs sanitation of the path after validating :param path: path to sanitize :return: path :raises: - InvalidPath if the path doesn't start with a slash """ if path == '/': # Nothing to do, just return return path
python
{ "resource": "" }
q263556
_validate_schema
validation
def _validate_schema(obj): """Ensures the passed schema instance is compatible :param obj: object to validate :return: obj :raises:
python
{ "resource": "" }
q263557
route
validation
def route(bp, *args, **kwargs): """Journey route decorator Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow. :param bp: :class:`flask.Blueprint` object :param args: args to pass along to `Blueprint.route` :param kwargs: - :strict_slashes: Enable / disable strict slashes (default False) - :validate: Enable / disable body/query validation (default True) - :_query: Unmarshal Query string into this schema - :_body: Unmarshal JSON body into this schema - :marshal_with: Serialize the output with this schema :raises: - ValidationError if the query parameters or JSON body fails validation """ kwargs['strict_slashes'] = kwargs.pop('strict_slashes', False) body = _validate_schema(kwargs.pop('_body', None)) query = _validate_schema(kwargs.pop('_query', None)) output = _validate_schema(kwargs.pop('marshal_with', None)) validate = kwargs.pop('validate', True) def decorator(f): @bp.route(*args, **kwargs) @wraps(f) def wrapper(*inner_args, **inner_kwargs): """If a schema (_body and/or _query) was supplied to the route decorator, the deserialized :class`marshmallow.Schema` object is injected into the decorated function's kwargs.""" try: if query is not None:
python
{ "resource": "" }
q263558
BlueprintBundle.attach_bp
validation
def attach_bp(self, bp, description=''): """Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint` """
python
{ "resource": "" }
q263559
DottedRule.move_dot
validation
def move_dot(self): """Returns the DottedRule that results from moving the dot."""
python
{ "resource": "" }
q263560
Grammar.first
validation
def first(self, symbols): """Computes the intermediate FIRST set using symbols.""" ret = set() if EPSILON in symbols: return set([EPSILON]) for symbol in symbols: ret |= self._first[symbol] - set([EPSILON])
python
{ "resource": "" }
q263561
Grammar._compute_first
validation
def _compute_first(self): """Computes the FIRST set for every symbol in the grammar. Tenatively based on _compute_first in PLY. """ for terminal in self.terminals: self._first[terminal].add(terminal) self._first[END_OF_INPUT].add(END_OF_INPUT) while True: changed = False for nonterminal, productions in self.nonterminals.items(): for production in productions:
python
{ "resource": "" }
q263562
Grammar._compute_follow
validation
def _compute_follow(self): """Computes the FOLLOW set for every non-terminal in the grammar. Tenatively based on _compute_follow in PLY. """ self._follow[self.start_symbol].add(END_OF_INPUT) while True: changed = False for nonterminal, productions in self.nonterminals.items(): for production in productions: for i, symbol in enumerate(production.rhs): if symbol not in self.nonterminals: continue first = self.first(production.rhs[i + 1:]) new_follow = first - set([EPSILON]) if EPSILON
python
{ "resource": "" }
q263563
Grammar.initial_closure
validation
def initial_closure(self): """Computes the initial closure using the START_foo production."""
python
{ "resource": "" }
q263564
Grammar.goto
validation
def goto(self, rules, symbol): """Computes the next closure for rules based on the symbol we got. Args: rules - an iterable of DottedRules symbol - a string denoting the symbol we've just seen Returns: frozenset of DottedRules """
python
{ "resource": "" }
q263565
Grammar.closure
validation
def closure(self, rules): """Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules """ closure = set() todo = set(rules) while todo: rule = todo.pop() closure.add(rule) # If the dot is at the end, there's no need to process it. if rule.at_end:
python
{ "resource": "" }
q263566
Journey.init_app
validation
def init_app(self, app): """Initializes Journey extension :param app: App passed from constructor or directly to init_app :raises: - NoBundlesAttached if no bundles has been attached attached """ if len(self._attached_bundles) == 0: raise NoBundlesAttached("At least one bundle must be attached before initializing Journey") for bundle in self._attached_bundles:
python
{ "resource": "" }
q263567
Journey.routes_simple
validation
def routes_simple(self): """Returns simple info about registered blueprints :return: Tuple containing endpoint, path and allowed methods for each route """ routes = [] for bundle in self._registered_bundles: bundle_path = bundle['path'] for blueprint in bundle['blueprints']: bp_path = blueprint['path'] for child in blueprint['routes']:
python
{ "resource": "" }
q263568
Journey._bundle_exists
validation
def _bundle_exists(self, path): """Checks if a bundle exists at the provided path :param path: Bundle path
python
{ "resource": "" }
q263569
Journey.attach_bundle
validation
def attach_bundle(self, bundle): """Attaches a bundle object :param bundle: :class:`flask_journey.BlueprintBundle` object :raises: - IncompatibleBundle if the bundle is not of type `BlueprintBundle` - ConflictingPath if a bundle already exists at bundle.path - MissingBlueprints if the bundle doesn't contain any blueprints """ if not isinstance(bundle, BlueprintBundle): raise IncompatibleBundle('BlueprintBundle object passed to attach_bundle must be of type {0}' .format(BlueprintBundle)) elif len(bundle.blueprints) == 0:
python
{ "resource": "" }
q263570
Journey._register_blueprint
validation
def _register_blueprint(self, app, bp, bundle_path, child_path, description): """Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path :return: Dict with info about the blueprint """ base_path
python
{ "resource": "" }
q263571
Journey.get_blueprint_routes
validation
def get_blueprint_routes(app, base_path): """Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path :param app: App instance to obtain rules from :param base_path: Base path to return detailed route info for :return: List of route detail
python
{ "resource": "" }
q263572
ParserBase.compute_precedence
validation
def compute_precedence(terminals, productions, precedence_levels): """Computes the precedence of terminal and production. The precedence of a terminal is it's level in the PRECEDENCE tuple. For a production, the precedence is the right-most terminal (if it exists). The default precedence is DEFAULT_PREC - (LEFT, 0). Returns: precedence - dict[terminal | production] = (assoc, level) """ precedence = collections.OrderedDict() for terminal in terminals: precedence[terminal] = DEFAULT_PREC
python
{ "resource": "" }
q263573
ParserBase.make_tables
validation
def make_tables(grammar, precedence): """Generates the ACTION and GOTO tables for the grammar. Returns: action - dict[state][lookahead] = (action, ...) goto - dict[state][just_reduced] = new_state """ ACTION = {} GOTO = {} labels = {} def get_label(closure): if closure not in labels: labels[closure] = len(labels) return labels[closure] def resolve_shift_reduce(lookahead, s_action, r_action): s_assoc, s_level = precedence[lookahead] r_assoc, r_level = precedence[r_action[1]] if s_level < r_level: return r_action elif s_level == r_level and r_assoc == LEFT: return r_action else: return s_action initial, closures, goto = grammar.closures() for closure in closures: label = get_label(closure) for rule in closure: new_action, lookahead = None, rule.lookahead if not rule.at_end: symbol = rule.rhs[rule.pos] is_terminal = symbol in grammar.terminals has_goto = symbol in goto[closure] if is_terminal and has_goto: next_state = get_label(goto[closure][symbol]) new_action, lookahead = ('shift', next_state), symbol elif rule.production == grammar.start and rule.at_end: new_action = ('accept',) elif rule.at_end: new_action = ('reduce', rule.production) if new_action is None: continue prev_action = ACTION.get((label, lookahead)) if prev_action is
python
{ "resource": "" }
q263574
parse_definite_clause
validation
def parse_definite_clause(s): "Return the antecedents and the consequent of a definite clause." assert is_definite_clause(s) if is_symbol(s.op): return [], s
python
{ "resource": "" }
q263575
tt_check_all
validation
def tt_check_all(kb, alpha, symbols, model): "Auxiliary routine to implement tt_entails." if not symbols: if pl_true(kb, model): result = pl_true(alpha, model) assert result in (True, False) return result else:
python
{ "resource": "" }
q263576
prop_symbols
validation
def prop_symbols(x): "Return a list of all propositional symbols in x." if not isinstance(x, Expr): return []
python
{ "resource": "" }
q263577
pl_true
validation
def pl_true(exp, model={}): """Return True if the propositional logic expression is true in the model, and False if it is false. If the model does not specify the value for every proposition, this may return None to indicate 'not obvious'; this may happen even when the expression is tautological.""" op, args = exp.op, exp.args if exp == TRUE: return True elif exp == FALSE: return False elif is_prop_symbol(op): return model.get(exp) elif op == '~': p = pl_true(args[0], model) if p is None: return None else: return not p elif op == '|': result = False for arg in args: p = pl_true(arg, model) if p is True: return True if p is None: result = None return result elif op == '&': result = True for arg in args:
python
{ "resource": "" }
q263578
dpll
validation
def dpll(clauses, symbols, model): "See if the clauses are true in a partial model." unknown_clauses = [] ## clauses with an unknown truth value for c in clauses: val = pl_true(c, model) if val == False: return False if val != True: unknown_clauses.append(c) if not unknown_clauses: return model P, value = find_pure_symbol(symbols, unknown_clauses) if P: return
python
{ "resource": "" }
q263579
is_variable
validation
def is_variable(x): "A variable is an Expr with no args and a lowercase symbol as the op."
python
{ "resource": "" }
q263580
PropKB.retract
validation
def retract(self, sentence): "Remove the sentence's clauses from the KB." for c in conjuncts(to_cnf(sentence)):
python
{ "resource": "" }
q263581
SettingDict.refresh
validation
def refresh(self): """ Updates the cache with setting values from the database. """ # `values_list('name', 'value')` doesn't work because `value` is not a # setting (base class) field, it's a setting value (subclass) field. So # we have to get real instances.
python
{ "resource": "" }
q263582
alphabeta_search
validation
def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None): """Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function.""" player = game.to_move(state) def max_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = -infinity for a in game.actions(state): v = max(v, min_value(game.result(state, a), alpha, beta, depth+1)) if v >= beta: return v alpha = max(alpha, v) return v def min_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = infinity for a in game.actions(state): v = min(v, max_value(game.result(state, a), alpha, beta, depth+1)) if v <= alpha:
python
{ "resource": "" }
q263583
TicTacToe.utility
validation
def utility(self, state, player): "Return the value to player; 1
python
{ "resource": "" }
q263584
TicTacToe.compute_utility
validation
def compute_utility(self, board, move, player): "If X wins with this move, return 1; if O return -1; else return 0." if (self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1,
python
{ "resource": "" }
q263585
TicTacToe.k_in_row
validation
def k_in_row(self, board, move, player, (delta_x, delta_y)): "Return true if there is a line through move on board for player." x, y = move n = 0 # n is number of moves in row while
python
{ "resource": "" }
q263586
update
validation
def update(x, **entries): """Update a dict, or an object with slots, according to `entries` dict. >>> update({'a': 1}, a=10, b=20)
python
{ "resource": "" }
q263587
weighted_sample_with_replacement
validation
def weighted_sample_with_replacement(seq, weights, n): """Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding
python
{ "resource": "" }
q263588
weighted_sampler
validation
def weighted_sampler(seq, weights): "Return a random-sample function that picks from seq weighted by weights." totals = [] for w in weights:
python
{ "resource": "" }
q263589
printf
validation
def printf(format, *args): """Format args with the first argument as format string, and write. Return the
python
{ "resource": "" }
q263590
name
validation
def name(object): "Try to find some reasonable name for the object." return (getattr(object, 'name', 0) or getattr(object, '__name__', 0)
python
{ "resource": "" }
q263591
AIMAFile
validation
def AIMAFile(components, mode='r'): "Open a file based at the AIMA root directory." import utils
python
{ "resource": "" }
q263592
NaiveBayesLearner
validation
def NaiveBayesLearner(dataset): """Just count how many times each value of each input attribute occurs, conditional on the target value. Count the different target values too.""" targetvals = dataset.values[dataset.target] target_dist = CountingProbDist(targetvals) attr_dists = dict(((gv, attr), CountingProbDist(dataset.values[attr])) for gv in targetvals for attr in dataset.inputs) for example in dataset.examples: targetval = example[dataset.target] target_dist.add(targetval) for attr in dataset.inputs: attr_dists[targetval, attr].add(example[attr]) def predict(example): """Predict the target value for example.
python
{ "resource": "" }
q263593
information_content
validation
def information_content(values): "Number of bits to represent the probability distribution
python
{ "resource": "" }
q263594
NeuralNetLearner
validation
def NeuralNetLearner(dataset, sizes): """Layered feed-forward network.""" activations =
python
{ "resource": "" }
q263595
EnsembleLearner
validation
def EnsembleLearner(learners): """Given a list of learning algorithms, have them vote.""" def train(dataset): predictors = [learner(dataset) for learner in learners] def predict(example):
python
{ "resource": "" }
q263596
WeightedMajority
validation
def WeightedMajority(predictors, weights): "Return a predictor that takes a weighted vote." def predict(example):
python
{ "resource": "" }
q263597
replicated_dataset
validation
def replicated_dataset(dataset, weights, n=None): "Copy dataset, replicating each example in proportion to its weight." n = n or len(dataset.examples) result = copy.copy(dataset)
python
{ "resource": "" }
q263598
leave1out
validation
def leave1out(learner, dataset): "Leave one out cross-validation
python
{ "resource": "" }
q263599
SyntheticRestaurant
validation
def SyntheticRestaurant(n=20): "Generate a DataSet with n examples." def gen(): example = map(random.choice, restaurant.values)
python
{ "resource": "" }