_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q263500 | Client.disconnect | validation | def disconnect(self):
"""Disconnect from the server"""
logger.info(u'Disconnecting')
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.state = DISCONNECTED | 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, __ = select.select([], [self.sock], [], timeout)
if not writable:
raise SendTimeoutError()
... | 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._st... | 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 = ''
while not self._stop:
line = self._readline()
if line == '.':
break
... | 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
"""
block = re.sub(r'<(/?)s>', r'<\1s>', self._readblock())
try:
xml = XML(block)
except ParseError:
xml = None
... | 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(
id... | 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.ge... | 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 in changeset.getchildren()]
keys += ['id', 'user', 'uid', '... | 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.
"""
url = 'https://www.openstreetmap.org/api/0.6/changeset/{}/download'.format(
changeset
)
return ET.fromstring(re... | 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.
"""
url = 'https://www.openstreetmap.org/api/0.6/changeset/{}'.format(changeset)
return ET.fromstring(requests.get(url).content... | 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
object.
"""
geojson = json.load(open(geojson, 'r'))
self.area = Polygon(geojson['features'][0]['geometry']['coordinates'][0]) | python | {
"resource": ""
} |
q263511 | ChangesetList.filter | validation | def filter(self):
"""Filter the changesets that intersects with the geojson geometry."""
self.content = [
ch
for ch in self.xml.getchildren()
if get_bounds(ch).intersects(self.area)
] | 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)
... | python | {
"resource": ""
} |
q263513 | Analyse.label_suspicious | validation | def label_suspicious(self, reason):
"""Add suspicion reason and set the suspicious flag."""
self.suspicion_reasons.append(reason)
self.is_suspect = True | 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()
if self.review_requested == 'yes':
self.label_suspicious('Review requested') | 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 ... | 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:
... | 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()]
s... | 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() + timeou... | 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.
:para... | 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("\nGENERAT... | 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)
offspring.append(child)... | python | {
"resource": ""
} |
q263522 | cosine | validation | def cosine(vec1, vec2):
"""Compare vectors. Borrowed from A. Parish."""
if norm(vec1) > 0 and norm(vec2) > 0:
return dot(vec1, vec2) / (norm(vec1) * norm(vec2))
else:
return 0.0 | 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:
self.gender = gender
else:
if not self.ch... | 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:
self.reproduce_asexually(egg_donor, sperm_donor)
else:
self.reproduce_sexually(egg_donor, sperm_donor) | 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 reproduction.
"""
egg = self.generate_gamete(egg_word)
sperm = self.generate_gamete(sperm_word)
self.geno... | 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 offsp... | 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 = ... | 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:
title = 'Son'
else:
title = 'Child'
p1 = self.parents[0]
p2 = self.parents[1]
template = ... | 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 fet... | 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 thi... | 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
... | 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", "... | 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.
... | 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/overri... | 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)... | 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._defa... | 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 th... | 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
"""
if not self.response:
return set()
elif self._pipelin... | 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 dire... | 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 ext... | 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')
... | 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 secur... | 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 i... | python | {
"resource": ""
} |
q263545 | camel2word | validation | def camel2word(string):
"""Covert name from CamelCase to "Normal case".
>>> camel2word('CamelCase')
'Camel case'
>>> camel2word('CaseWithSpec')
'Case with spec'
"""
def wordize(match):
return ' ' + match.group(1).lower()
return string[0] + re.sub(r'([A-Z])', wordize, string[1:]... | 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)
return "%s minutes %s seconds" % (
func("%d" % n_minutes),
func("%.3f" % n_... | 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()
key... | 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 nee... | 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):
tup[1]._pare... | 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 i... | 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()
f = gzip.GzipFile(fileobj=compressed_bits, mode='wb')
f.write(input_str)
f.close()
return com... | python | {
"resource": ""
} |
q263552 | SpecSelector.registerGoodClass | validation | def registerGoodClass(self, class_):
"""
Internal bookkeeping to handle nested classes
"""
# Class itself added to "good" list
self._valid_classes.append(class_)
# Recurse into any inner classes
for name, cls in class_members(class_):
if self.isValidCl... | 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
or (
hasattr(module, '__fil... | 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
if path[:1] != '/':
... | 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:
- IncompatibleSchema if the passed schema is of an incompatible type
"""
if obj is not None and not isinstance(obj, Schema):
raise IncompatibleSch... | 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_sla... | 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."""
return self.__class__(self.production, self.pos + 1, self.lookahead) | 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])
if EPSILON not in self._first[symbol]:
... | 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:
... | 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 se... | python | {
"resource": ""
} |
q263563 | Grammar.initial_closure | validation | def initial_closure(self):
"""Computes the initial closure using the START_foo production."""
first_rule = DottedRule(self.start, 0, END_OF_INPUT)
return self.closure([first_rule]) | 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
"""
return self.closure(
... | 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()... | 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 NoBundlesAttac... | 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... | 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
:return: bool
"""
for attached_bundle in self._attached_bundles:
if path == attached_bundle.path:
return True
return False | 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
... | 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
... | 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 dicts... | 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 precedenc... | 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 = {}
d... | 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
else:
antecedent, consequent = s.args
return conjuncts(antecedent), consequent | 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:
return True
else:
P, rest... | 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 []
elif is_prop_symbol(x.op):
return [x]
else:
return list(set(symbol for arg in x.args
for symbol in prop_symbols(arg))) | 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."""
... | 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)
... | 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."
return isinstance(x, Expr) and not x.args and is_var_symbol(x.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)):
if c in self.clauses:
self.clauses.remove(c) | 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.
args... | 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,... | python | {
"resource": ""
} |
q263583 | TicTacToe.utility | validation | def utility(self, state, player):
"Return the value to player; 1 for win, -1 for loss, 0 otherwise."
return if_(player == 'X', state.utility, -state.utility) | 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, -1)) or
self.k_i... | 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 board.get((x, y)) == player:
n += 1
x, y = x + delta_x, y + delta_y
x, y =... | 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)
{'a': 10, 'b': 20}
>>> update(Struct(a=1), a=10, b=20)
Struct(a=10, b=20)
"""
if isinstance(x, dict):
x.update(entries)
else:
x.__dict__.upd... | 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
weight."""
sample = weighted_sampler(seq, weights)
return [sample() for s in range(n)] | 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:
totals.append(w + totals[-1] if totals else w)
return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))] | python | {
"resource": ""
} |
q263589 | printf | validation | def printf(format, *args):
"""Format args with the first argument as format string, and write.
Return the last arg, or format itself if there are no args."""
sys.stdout.write(str(format) % args)
return if_(args, lambda: args[-1], lambda: format) | 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)
or getattr(getattr(object, '__class__', 0), '__name__', 0)
or str(object)) | python | {
"resource": ""
} |
q263591 | AIMAFile | validation | def AIMAFile(components, mode='r'):
"Open a file based at the AIMA root directory."
import utils
dir = os.path.dirname(utils.__file__)
return open(apply(os.path.join, [dir] + components), mode) | 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)... | python | {
"resource": ""
} |
q263593 | information_content | validation | def information_content(values):
"Number of bits to represent the probability distribution in values."
probabilities = normalize(removeall(0, values))
return sum(-p * log2(p) for p in probabilities) | python | {
"resource": ""
} |
q263594 | NeuralNetLearner | validation | def NeuralNetLearner(dataset, sizes):
"""Layered feed-forward network."""
activations = map(lambda n: [0.0 for i in range(n)], sizes)
weights = []
def predict(example):
unimplemented()
return predict | 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):
return mode(predictor(example) for predictor in predictors)
return predict
return tr... | python | {
"resource": ""
} |
q263596 | WeightedMajority | validation | def WeightedMajority(predictors, weights):
"Return a predictor that takes a weighted vote."
def predict(example):
return weighted_mode((predictor(example) for predictor in predictors),
weights)
return predict | 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)
result.examples = weighted_replicate(dataset.examples, weights, n)
return result | python | {
"resource": ""
} |
q263598 | leave1out | validation | def leave1out(learner, dataset):
"Leave one out cross-validation over the dataset."
return cross_validation(learner, dataset, k=len(dataset.examples)) | python | {
"resource": ""
} |
q263599 | SyntheticRestaurant | validation | def SyntheticRestaurant(n=20):
"Generate a DataSet with n examples."
def gen():
example = map(random.choice, restaurant.values)
example[restaurant.target] = Fig[18,2](example)
return example
return RestaurantDataSet([gen() for i in range(n)]) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.