_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q263600 | ContinuousXor | validation | def ContinuousXor(n):
"2 inputs are chosen uniformly from (0.0 .. 2.0]; output is xor of ints."
examples = []
for i in range(n):
x, y = [random.uniform(0.0, 2.0) for i | python | {
"resource": ""
} |
q263601 | compare | validation | def compare(algorithms=[PluralityLearner, NaiveBayesLearner,
NearestNeighborLearner, DecisionTreeLearner],
datasets=[iris, orings, zoo, restaurant, SyntheticRestaurant(20),
Majority(7, 100), Parity(7, 100), Xor(100)],
k=10, trials=1):
"""Compare various learners on various datasets using cross-validation.
Print results as a table.""" | python | {
"resource": ""
} |
q263602 | DataSet.check_me | validation | def check_me(self):
"Check that my fields make sense."
assert len(self.attrnames) == len(self.attrs)
assert self.target in self.attrs
assert self.target not in self.inputs | python | {
"resource": ""
} |
q263603 | DataSet.add_example | validation | def add_example(self, example):
"Add an example to the list of examples, checking it first."
| python | {
"resource": ""
} |
q263604 | DataSet.check_example | validation | def check_example(self, example):
"Raise ValueError if example has any invalid values."
if self.values:
for a in self.attrs:
if example[a] not in self.values[a]:
| python | {
"resource": ""
} |
q263605 | DataSet.attrnum | validation | def attrnum(self, attr):
"Returns the number used for attr, which can be a name, or -n .. n-1."
if attr < 0:
return len(self.attrs) + | python | {
"resource": ""
} |
q263606 | DataSet.sanitize | validation | def sanitize(self, example):
"Return a copy of example, with non-input attributes replaced | python | {
"resource": ""
} |
q263607 | CountingProbDist.add | validation | def add(self, o):
"Add an observation o to the distribution."
| python | {
"resource": ""
} |
q263608 | CountingProbDist.smooth_for | validation | def smooth_for(self, o):
"""Include o among the possible observations, whether or not
it's been observed yet."""
if o not in self.dictionary:
| python | {
"resource": ""
} |
q263609 | CountingProbDist.sample | validation | def sample(self):
"Return a random sample from the distribution."
if self.sampler is None:
self.sampler = weighted_sampler(self.dictionary.keys(),
| python | {
"resource": ""
} |
q263610 | revise | validation | def revise(csp, Xi, Xj, removals):
"Return true if we remove a value."
revised = False
for x in csp.curr_domains[Xi][:]:
# If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x
if every(lambda | python | {
"resource": ""
} |
q263611 | mrv | validation | def mrv(assignment, csp):
"Minimum-remaining-values heuristic."
return argmin_random_tie(
| python | {
"resource": ""
} |
q263612 | lcv | validation | def lcv(var, assignment, csp):
"Least-constraining-values heuristic."
return sorted(csp.choices(var),
| python | {
"resource": ""
} |
q263613 | forward_checking | validation | def forward_checking(csp, var, value, assignment, removals):
"Prune neighbor values inconsistent with var=value."
for B in csp.neighbors[var]:
if B not in assignment:
for b in csp.curr_domains[B][:]:
if not | python | {
"resource": ""
} |
q263614 | mac | validation | def mac(csp, var, value, assignment, removals):
"Maintain arc consistency."
return AC3(csp, [(X, | python | {
"resource": ""
} |
q263615 | min_conflicts | validation | def min_conflicts(csp, max_steps=100000):
"""Solve a CSP by stochastic hillclimbing on the number of conflicts."""
# Generate a complete assignment for all vars (probably with conflicts)
csp.current = current = {}
for var in csp.vars:
val = min_conflicts_value(csp, var, current)
csp.assign(var, val, current)
# Now repeatedly choose a random conflicted variable and change it
for i in range(max_steps): | python | {
"resource": ""
} |
q263616 | min_conflicts_value | validation | def min_conflicts_value(csp, var, current):
"""Return the value that will give var the least number of conflicts.
| python | {
"resource": ""
} |
q263617 | CSP.nconflicts | validation | def nconflicts(self, var, val, assignment):
"Return the number of conflicts var=val has with other variables."
# Subclasses may implement this more efficiently
def conflict(var2):
return (var2 in assignment
| python | {
"resource": ""
} |
q263618 | CSP.suppose | validation | def suppose(self, var, value):
"Start accumulating inferences from assuming var=value."
self.support_pruning()
| python | {
"resource": ""
} |
q263619 | CSP.prune | validation | def prune(self, var, value, removals):
"Rule out var=value."
| python | {
"resource": ""
} |
q263620 | CSP.infer_assignment | validation | def infer_assignment(self):
"Return the partial assignment implied by the current inferences."
self.support_pruning()
return | python | {
"resource": ""
} |
q263621 | CSP.restore | validation | def restore(self, removals):
"Undo a supposition and all inferences | python | {
"resource": ""
} |
q263622 | CSP.conflicted_vars | validation | def conflicted_vars(self, current):
"Return a list of variables in current assignment that are in conflict"
return [var for var in self.vars | python | {
"resource": ""
} |
q263623 | NQueensCSP.nconflicts | validation | def nconflicts(self, var, val, assignment):
"""The number of conflicts, as recorded with each assignment.
Count conflicts in row and in up, down diagonals. If there
is a queen there, it can't conflict with itself, so subtract 3."""
n = len(self.vars)
| python | {
"resource": ""
} |
q263624 | NQueensCSP.assign | validation | def assign(self, var, val, assignment):
"Assign var, and keep track of conflicts."
oldval = assignment.get(var, None)
if val != oldval:
if oldval is not None: # Remove old val if there was one
| python | {
"resource": ""
} |
q263625 | NQueensCSP.record_conflict | validation | def record_conflict(self, assignment, var, val, delta):
"Record conflicts caused by addition or deletion of a Queen."
n = len(self.vars)
| python | {
"resource": ""
} |
q263626 | viterbi_segment | validation | def viterbi_segment(text, P):
"""Find the best segmentation of the string of characters, given the
UnigramTextModel P."""
# best[i] = best probability for text[0:i]
# words[i] = best word ending at position i
n = len(text)
words = [''] + list(text)
best = [1.0] + [0.0] * n
## Fill in the vectors best, words via dynamic programming
for i in range(n+1):
for j in range(0, i):
w = text[j:i]
if P[w] * best[i - len(w)] >= best[i]:
| python | {
"resource": ""
} |
q263627 | encode | validation | def encode(plaintext, code):
"Encodes text, using a code which is a permutation of the alphabet."
| python | {
"resource": ""
} |
q263628 | NgramTextModel.samples | validation | def samples(self, nwords):
"""Build up a random sample of text nwords words long, using
the conditional probability given the n-1 preceding words."""
n = self.n
nminus1gram = ('',) * (n-1)
output = []
for i in range(nwords):
if nminus1gram not in self.cond_prob:
| python | {
"resource": ""
} |
q263629 | IRSystem.index_collection | validation | def index_collection(self, filenames):
"Index a whole collection of files."
for filename in filenames:
| python | {
"resource": ""
} |
q263630 | IRSystem.index_document | validation | def index_document(self, text, url):
"Index the text of a document."
## For now, use first line for title
title = text[:text.index('\n')].strip()
| python | {
"resource": ""
} |
q263631 | IRSystem.score | validation | def score(self, word, docid):
"Compute a score for this word on this docid."
## There are many options; here we take a very simple approach
return (math.log(1 | python | {
"resource": ""
} |
q263632 | IRSystem.present | validation | def present(self, results):
"Present the results as a list."
for (score, d) in results:
doc = self.documents[d]
| python | {
"resource": ""
} |
q263633 | IRSystem.present_results | validation | def present_results(self, query_text, n=10):
"Get results for the query and present them."
| python | {
"resource": ""
} |
q263634 | ShiftDecoder.score | validation | def score(self, plaintext):
"Return a score for text based on how common letters pairs are."
s = 1.0
| python | {
"resource": ""
} |
q263635 | PermutationDecoder.decode | validation | def decode(self, ciphertext):
"Search for a decoding of the ciphertext."
self.ciphertext = ciphertext
problem = PermutationDecoderProblem(decoder=self)
| python | {
"resource": ""
} |
q263636 | PermutationDecoder.score | validation | def score(self, code):
"""Score is product of word scores, unigram scores, and bigram scores.
This can get very small, so we use logs and exp."""
text = permutation_decode(self.ciphertext, | python | {
"resource": ""
} |
q263637 | GetSettings.get_value | validation | def get_value(self, context, default):
"""
Returns a ``SettingDict`` object.
"""
if default is None: | python | {
"resource": ""
} |
q263638 | expected_utility | validation | def expected_utility(a, s, U, mdp):
"The expected utility of doing a in state s, according to the MDP and | python | {
"resource": ""
} |
q263639 | GridMDP.go | validation | def go(self, state, direction):
"Return the state that results from going in this direction."
| python | {
"resource": ""
} |
q263640 | SettingQuerySet.as_dict | validation | def as_dict(self, default=None):
"""
Returns a ``SettingDict`` object for this queryset.
"""
| python | {
"resource": ""
} |
q263641 | SettingQuerySet.create | validation | def create(self, name, value):
"""
Creates and returns an object of the appropriate type for ``value``.
"""
if value is None:
raise ValueError('Setting value cannot | python | {
"resource": ""
} |
q263642 | SettingValueModel.is_compatible | validation | def is_compatible(cls, value):
"""
Returns ``True`` if this model should be used to store ``value``.
Checks if ``value`` is an instance of ``value_type``. Override this
method if you need more advanced behaviour. For example, to distinguish
| python | {
"resource": ""
} |
q263643 | exp_schedule | validation | def exp_schedule(k=20, lam=0.005, limit=100):
"One possible schedule function for simulated annealing"
return | python | {
"resource": ""
} |
q263644 | genetic_search | validation | def genetic_search(problem, fitness_fn, ngen=1000, pmut=0.1, n=20):
"""Call genetic_algorithm on the appropriate parts of a problem.
This requires the problem to have states that can mate and mutate,
plus a value method that scores states."""
| python | {
"resource": ""
} |
q263645 | random_boggle | validation | def random_boggle(n=4):
"""Return a random Boggle board of size n x n.
We represent a board as a linear list of letters."""
cubes = [cubes16[i % 16] for i in | python | {
"resource": ""
} |
q263646 | print_boggle | validation | def print_boggle(board):
"Print the board in a 2-d array."
n2 = len(board); n = exact_sqrt(n2)
for i in range(n2):
if i % n == 0 and i > 0: print
if | python | {
"resource": ""
} |
q263647 | boggle_neighbors | validation | def boggle_neighbors(n2, cache={}):
"""Return a list of lists, where the i-th element is the list of indexes
for the neighbors of square i."""
if cache.get(n2):
return cache.get(n2)
n = exact_sqrt(n2)
neighbors = [None] * n2
for i in range(n2):
neighbors[i] = []
on_top = i < n
on_bottom = i >= n2 - n
on_left = i % n == 0
on_right = (i+1) % n == 0
if not on_top:
neighbors[i].append(i - n)
if not on_left: neighbors[i].append(i - n - 1)
| python | {
"resource": ""
} |
q263648 | exact_sqrt | validation | def exact_sqrt(n2):
"If n2 is a perfect square, return its square root, else raise error."
| python | {
"resource": ""
} |
q263649 | Node.expand | validation | def expand(self, problem):
"List the nodes reachable in one step from this node."
| python | {
"resource": ""
} |
q263650 | Node.child_node | validation | def child_node(self, problem, action):
"Fig. 3.10"
next = problem.result(self.state, action)
return Node(next, self, action,
| python | {
"resource": ""
} |
q263651 | Node.path | validation | def path(self):
"Return a list of nodes forming the path from the root to this node."
node, path_back = self, []
while node:
| python | {
"resource": ""
} |
q263652 | GAState.mate | validation | def mate(self, other):
"Return a new individual crossing self and other."
| python | {
"resource": ""
} |
q263653 | Graph.make_undirected | validation | def make_undirected(self):
"Make a digraph into an undirected graph by adding symmetric edges."
for a in self.dict.keys():
| python | {
"resource": ""
} |
q263654 | Graph.connect | validation | def connect(self, A, B, distance=1):
"""Add a link from A and B of given distance, and also add the inverse
link if the graph is undirected."""
| python | {
"resource": ""
} |
q263655 | Graph.connect1 | validation | def connect1(self, A, B, distance):
"Add a link from A to B of given distance, in one direction only."
| python | {
"resource": ""
} |
q263656 | GraphProblem.h | validation | def h(self, node):
"h function is straight-line distance from a node's state to goal."
locs = getattr(self.graph, 'locations', None)
if locs:
| python | {
"resource": ""
} |
q263657 | NQueensProblem.actions | validation | def actions(self, state):
"In the leftmost empty column, try all non-conflicting rows."
if state[-1] is not None:
return [] # All columns filled; no successors
else:
col = state.index(None)
| python | {
"resource": ""
} |
q263658 | NQueensProblem.result | validation | def result(self, state, row):
"Place the next queen at the given row."
col = state.index(None)
| python | {
"resource": ""
} |
q263659 | BoggleFinder.set_board | validation | def set_board(self, board=None):
"Set the board, and find all the words in it."
if board is None:
board = random_boggle()
self.board = board | python | {
"resource": ""
} |
q263660 | BoggleFinder.score | validation | def score(self):
"The total score for the words found, according to the rules."
| python | {
"resource": ""
} |
q263661 | TraceAgent | validation | def TraceAgent(agent):
"""Wrap the agent's program to print its input and output. This will let
you see what the agent is doing in the environment."""
| python | {
"resource": ""
} |
q263662 | ModelBasedVacuumAgent | validation | def ModelBasedVacuumAgent():
"An agent that keeps track of what locations are clean or dirty."
model = {loc_A: None, loc_B: None}
def program((location, status)):
"Same as ReflexVacuumAgent, except if everything is clean, do NoOp."
model[location] = status ## Update the model here
if model[loc_A] == model[loc_B] == 'Clean': | python | {
"resource": ""
} |
q263663 | Environment.step | validation | def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
| python | {
"resource": ""
} |
q263664 | Environment.run | validation | def run(self, steps=1000):
"Run the Environment for given number of time steps."
for step in range(steps):
| python | {
"resource": ""
} |
q263665 | Environment.list_things_at | validation | def list_things_at(self, location, tclass=Thing):
"Return all things exactly at a given location."
return [thing for thing in self.things
| python | {
"resource": ""
} |
q263666 | Environment.add_thing | validation | def add_thing(self, thing, location=None):
"""Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this."""
if not isinstance(thing, Thing):
thing = Agent(thing)
assert thing not | python | {
"resource": ""
} |
q263667 | Environment.delete_thing | validation | def delete_thing(self, thing):
"""Remove a thing from the environment."""
try:
self.things.remove(thing)
except ValueError, e:
print e
print " in Environment delete_thing"
print " Thing to be removed: %s at %s" % (thing, thing.location)
| python | {
"resource": ""
} |
q263668 | XYEnvironment.things_near | validation | def things_near(self, location, radius=None):
"Return all things within radius of location."
if radius is None: radius = self.perceptible_distance
radius2 = radius * radius
| python | {
"resource": ""
} |
q263669 | XYEnvironment.percept | validation | def percept(self, agent):
"By default, agent perceives things within a default radius."
| python | {
"resource": ""
} |
q263670 | XYEnvironment.move_to | validation | def move_to(self, thing, destination):
"Move a thing to a new location."
thing.bump = self.some_things_at(destination, Obstacle)
if not thing.bump:
| python | {
"resource": ""
} |
q263671 | XYEnvironment.add_walls | validation | def add_walls(self):
"Put walls around the entire perimeter of the grid."
for x in range(self.width):
self.add_thing(Wall(), (x, 0))
self.add_thing(Wall(), (x, self.height-1))
| python | {
"resource": ""
} |
q263672 | Chart.parse | validation | def parse(self, words, S='S'):
"""Parse a list of words; according to the grammar.
Leave results in the chart."""
self.chart = [[] for i in range(len(words)+1)]
| python | {
"resource": ""
} |
q263673 | Chart.add_edge | validation | def add_edge(self, edge):
"Add edge to chart, and see if it extends or predicts another edge."
start, end, lhs, found, expects = edge
if edge not in self.chart[end]:
self.chart[end].append(edge)
if self.trace:
| python | {
"resource": ""
} |
q263674 | Chart.scanner | validation | def scanner(self, j, word):
"For each edge expecting a word of this category here, extend the edge."
for (i, j, A, alpha, Bb) in self.chart[j]:
| python | {
"resource": ""
} |
q263675 | Chart.predictor | validation | def predictor(self, (i, j, A, alpha, Bb)):
"Add to chart any rules for B that could help extend this edge."
B = Bb[0]
if B in self.grammar.rules:
| python | {
"resource": ""
} |
q263676 | Chart.extender | validation | def extender(self, edge):
"See what edges can be extended by this edge."
(j, k, B, _, _) = edge
| python | {
"resource": ""
} |
q263677 | settings | validation | def settings(request):
"""
Adds a ``SettingDict`` object for the ``Setting`` model to the context as
``SETTINGS``. Automatically creates non-existent settings with an empty
string as the default value.
| python | {
"resource": ""
} |
q263678 | make_factor | validation | def make_factor(var, e, bn):
"""Return the factor for var in bn's joint distribution given e.
That is, bn's full joint distribution, projected to accord with e,
is the pointwise product of | python | {
"resource": ""
} |
q263679 | sum_out | validation | def sum_out(var, factors, bn):
"Eliminate var from all factors by summing over its values."
result, var_factors = [], []
for f in factors:
| python | {
"resource": ""
} |
q263680 | all_events | validation | def all_events(vars, bn, e):
"Yield every way of extending e with values for all vars."
if not vars:
yield e
| python | {
"resource": ""
} |
q263681 | consistent_with | validation | def consistent_with(event, evidence):
"Is event consistent with the given evidence?"
return every(lambda (k, | python | {
"resource": ""
} |
q263682 | weighted_sample | validation | def weighted_sample(bn, e):
"""Sample an event from bn that's consistent with the evidence e;
return the event and its weight, the likelihood that the event
accords to the evidence."""
w = 1
event = dict(e) # boldface x in Fig. 14.15
for node in bn.nodes:
| python | {
"resource": ""
} |
q263683 | ProbDist.show_approx | validation | def show_approx(self, numfmt='%.3g'):
"""Show the probabilities rounded and sorted by key, for the
sake of portable doctests."""
| python | {
"resource": ""
} |
q263684 | BayesNet.add | validation | def add(self, node_spec):
"""Add a node to the net. Its parents must already be in the
net, and its variable must not."""
node = BayesNode(*node_spec)
assert node.variable not in self.vars
assert every(lambda parent: parent in self.vars, | python | {
"resource": ""
} |
q263685 | Factor.pointwise_product | validation | def pointwise_product(self, other, bn):
"Multiply two factors, combining their variables."
vars = list(set(self.vars) | | python | {
"resource": ""
} |
q263686 | Factor.sum_out | validation | def sum_out(self, var, bn):
"Make a factor eliminating var by summing over its values."
vars = [X for X in self.vars if X != var]
cpt = dict((event_values(e, vars),
sum(self.p(extend(e, var, val))
| python | {
"resource": ""
} |
q263687 | Factor.normalize | validation | def normalize(self):
"Return my probabilities; must be down to one variable."
assert len(self.vars) == 1
return ProbDist(self.vars[0],
| python | {
"resource": ""
} |
q263688 | strip_minidom_whitespace | validation | def strip_minidom_whitespace(node):
"""Strips all whitespace from a minidom XML node and its children
This operation is made in-place."""
for child in node.childNodes:
if child.nodeType == Node.TEXT_NODE:
if child.nodeValue:
| python | {
"resource": ""
} |
q263689 | color_from_hls | validation | def color_from_hls(hue, light, sat):
""" Takes a hls color and converts to proper hue
Bulbs use a BGR order instead of RGB """
if light > 0.95: #too bright, let's just switch to white
return 256
elif light < 0.05: #too dark, let's shut it off
| python | {
"resource": ""
} |
q263690 | color_from_rgb | validation | def color_from_rgb(red, green, blue):
""" Takes your standard rgb color
and converts it to a proper hue value """
r = min(red, 255)
g = min(green, 255)
b = min(blue, 255)
if r > 1 or g > 1 or b > 1:
| python | {
"resource": ""
} |
q263691 | color_from_hex | validation | def color_from_hex(value):
""" Takes an HTML hex code
and converts it to a proper hue value """
if "#" in value:
value = value[1:]
try:
unhexed = bytes.fromhex(value)
except:
| python | {
"resource": ""
} |
q263692 | LightBulb.wait | validation | def wait(self, sec=0.1):
""" Wait for x seconds
each wait command is 100ms """
sec = max(sec, 0)
reps = int(floor(sec / 0.1))
commands = []
for i in | python | {
"resource": ""
} |
q263693 | getJsonFromApi | validation | def getJsonFromApi(view, request):
"""Return json from querying Web Api
Args:
view: django view function.
request: http request object got from django.
Returns: json format dictionary
| python | {
"resource": ""
} |
q263694 | put | validation | def put(xy, *args):
"""
put text on on screen
a tuple as first argument tells absolute position for the text
does not change TermCursor position
args = list of optional position, formatting tokens and strings
| python | {
"resource": ""
} |
q263695 | getpassword | validation | def getpassword(prompt="Password: "):
"""
get user input without echo
"""
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
| python | {
"resource": ""
} |
q263696 | getch | validation | def getch():
"""
get character. waiting for key
"""
try:
termios.tcsetattr(_fd, termios.TCSANOW, _new_settings)
ch = sys.stdin.read(1)
finally: | python | {
"resource": ""
} |
q263697 | FormatterX.format | validation | def format(self, record):
"""tweaked from source of base"""
try:
record.message = record.getMessage()
except TypeError:
# if error during msg = msg % self.args
if record.args:
if isinstance(record.args, collections.Mapping):
record.message = record.msg.format(**record.args)
else:
record.message = record.msg.format(record.args)
self._fmt = self.getfmt(record.levelname)
if self.usesTime():
record.asctime = self.formatTime(record, self.datefmt)
s = self._fmt.format(**record.__dict__)
if record.exc_info:
# Cache the traceback text to avoid converting it multiple | python | {
"resource": ""
} |
q263698 | getProcessOwner | validation | def getProcessOwner(pid):
'''
getProcessOwner - Get the process owner of a pid
@param pid <int> - process id
@return - None if process not found or can't be determined. Otherwise, a dict:
{
uid - Owner UID
name - Owner name, or None if one cannot be determined
}
'''
try:
ownerUid = os.stat('/proc/' + str(pid)).st_uid
except:
| python | {
"resource": ""
} |
q263699 | scanProcessForCwd | validation | def scanProcessForCwd(pid, searchPortion, isExactMatch=False):
'''
scanProcessForCwd - Searches a given pid's cwd for a given pattern
@param pid <int> - A running process ID on this system
@param searchPortion <str> - Any portion of directory to search
@param isExactMatch <bool> Default False - If match should be exact, otherwise a partial match is performed.
@return <dict> - If result is found, the following dict is returned. If no match found on the given pid, or pid is not found running, None is returned.
{
'searchPortion' : The passed search pattern
'pid' : The passed pid (as an integer)
'owner' : String of process owner, or uid if no mapping can be found, or "unknown" if neither could be determined.
'cmdline' : Commandline string
'cwd' : The exact cwd of matched process
}
'''
try:
try:
pid = int(pid)
except ValueError as e:
sys.stderr.write('Expected an integer, got %s for pid.\n' %(str(type(pid)),))
raise e
cwd = getProcessCwd(pid)
if not cwd:
return None
isMatch = False
if isExactMatch is True:
if searchPortion == cwd:
isMatch = True
else:
if searchPortion.endswith('/') and searchPortion[:-1] == cwd:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.