_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
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 in '12'] examples.append([x, y, int(x) != int(y)]) return DataSet(name="continuous xor", examples=examples)
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.""" print_table([[a.__name__.replace('Learner','')] + [cross_validation(a, d, k, trials) for d in datasets] for a in algorithms], header=[''] + [d.name[0:7] for d in datasets], numfmt='%.2f')
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 assert set(self.inputs).issubset(set(self.attrs)) map(self.check_example, self.examples)
python
{ "resource": "" }
q263603
DataSet.add_example
validation
def add_example(self, example): "Add an example to the list of examples, checking it first." self.check_example(example) self.examples.append(example)
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]: raise ValueError('Bad value %s for attribute %s in %s' % (example[a], self.attrnames[a], example))
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) + attr elif isinstance(attr, str): return self.attrnames.index(attr) else: return attr
python
{ "resource": "" }
q263606
DataSet.sanitize
validation
def sanitize(self, example): "Return a copy of example, with non-input attributes replaced by None." return [attr_i if i in self.inputs else None for i, attr_i in enumerate(example)]
python
{ "resource": "" }
q263607
CountingProbDist.add
validation
def add(self, o): "Add an observation o to the distribution." self.smooth_for(o) self.dictionary[o] += 1 self.n_obs += 1 self.sampler = None
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: self.dictionary[o] = self.default self.n_obs += self.default self.sampler = None
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(), self.dictionary.values()) return self.sampler()
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 y: not csp.constraints(Xi, x, Xj, y), csp.curr_domains[Xj]): csp.prune(Xi, x, removals) revised = True return revised
python
{ "resource": "" }
q263611
mrv
validation
def mrv(assignment, csp): "Minimum-remaining-values heuristic." return argmin_random_tie( [v for v in csp.vars if v not in assignment], lambda var: num_legal_values(csp, var, assignment))
python
{ "resource": "" }
q263612
lcv
validation
def lcv(var, assignment, csp): "Least-constraining-values heuristic." return sorted(csp.choices(var), key=lambda val: csp.nconflicts(var, val, assignment))
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 csp.constraints(var, value, B, b): csp.prune(B, b, removals) if not csp.curr_domains[B]: return False return True
python
{ "resource": "" }
q263614
mac
validation
def mac(csp, var, value, assignment, removals): "Maintain arc consistency." return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)
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): conflicted = csp.conflicted_vars(current) if not conflicted: return current var = random.choice(conflicted) val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) return None
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. If there is a tie, choose at random.""" return argmin_random_tie(csp.domains[var], lambda val: csp.nconflicts(var, val, current))
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 and not self.constraints(var, val, var2, assignment[var2])) return count_if(conflict, self.neighbors[var])
python
{ "resource": "" }
q263618
CSP.suppose
validation
def suppose(self, var, value): "Start accumulating inferences from assuming var=value." self.support_pruning() removals = [(var, a) for a in self.curr_domains[var] if a != value] self.curr_domains[var] = [value] return removals
python
{ "resource": "" }
q263619
CSP.prune
validation
def prune(self, var, value, removals): "Rule out var=value." self.curr_domains[var].remove(value) if removals is not None: removals.append((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 dict((v, self.curr_domains[v][0]) for v in self.vars if 1 == len(self.curr_domains[v]))
python
{ "resource": "" }
q263621
CSP.restore
validation
def restore(self, removals): "Undo a supposition and all inferences from it." for B, b in removals: self.curr_domains[B].append(b)
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 if self.nconflicts(var, current[var], current) > 0]
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) c = self.rows[val] + self.downs[var+val] + self.ups[var-val+n-1] if assignment.get(var, None) == val: c -= 3 return c
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 self.record_conflict(assignment, var, oldval, -1) self.record_conflict(assignment, var, val, +1) CSP.assign(self, var, val, assignment)
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) self.rows[val] += delta self.downs[var + val] += delta self.ups[var - val + n - 1] += delta
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]: best[i] = P[w] * best[i - len(w)] words[i] = w ## Now recover the sequence of best words sequence = []; i = len(words)-1 while i > 0: sequence[0:0] = [words[i]] i = i - len(words[i]) ## Return sequence of best words and overall probability return sequence, best[-1]
python
{ "resource": "" }
q263627
encode
validation
def encode(plaintext, code): "Encodes text, using a code which is a permutation of the alphabet." from string import maketrans trans = maketrans(alphabet + alphabet.upper(), code + code.upper()) return plaintext.translate(trans)
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: nminus1gram = ('',) * (n-1) # Cannot continue, so restart. wn = self.cond_prob[nminus1gram].sample() output.append(wn) nminus1gram = nminus1gram[1:] + (wn,) return ' '.join(output)
python
{ "resource": "" }
q263629
IRSystem.index_collection
validation
def index_collection(self, filenames): "Index a whole collection of files." for filename in filenames: self.index_document(open(filename).read(), filename)
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() docwords = words(text) docid = len(self.documents) self.documents.append(Document(title, url, len(docwords))) for word in docwords: if word not in self.stopwords: self.index[word][docid] += 1
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 + self.index[word][docid]) / math.log(1 + self.documents[docid].nwords))
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] print ("%5.2f|%25s | %s" % (100 * score, doc.url, doc.title[:45].expandtabs()))
python
{ "resource": "" }
q263633
IRSystem.present_results
validation
def present_results(self, query_text, n=10): "Get results for the query and present them." self.present(self.query(query_text, n))
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 for bi in bigrams(plaintext): s = s * self.P2[bi] return s
python
{ "resource": "" }
q263635
PermutationDecoder.decode
validation
def decode(self, ciphertext): "Search for a decoding of the ciphertext." self.ciphertext = ciphertext problem = PermutationDecoderProblem(decoder=self) return search.best_first_tree_search( problem, lambda node: self.score(node.state))
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, code) logP = (sum([log(self.Pwords[word]) for word in words(text)]) + sum([log(self.P1[c]) for c in text]) + sum([log(self.P2[b]) for b in bigrams(text)])) return exp(logP)
python
{ "resource": "" }
q263637
GetSettings.get_value
validation
def get_value(self, context, default): """ Returns a ``SettingDict`` object. """ if default is None: settings = self.setting_model.objects.as_dict() else: settings = self.setting_model.objects.as_dict(default=default) return settings
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 U." return sum([p * U[s1] for (p, s1) in mdp.T(s, a)])
python
{ "resource": "" }
q263639
GridMDP.go
validation
def go(self, state, direction): "Return the state that results from going in this direction." state1 = vector_add(state, direction) return if_(state1 in self.states, state1, state)
python
{ "resource": "" }
q263640
SettingQuerySet.as_dict
validation
def as_dict(self, default=None): """ Returns a ``SettingDict`` object for this queryset. """ settings = SettingDict(queryset=self, default=default) return settings
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 be `None`.') model = Setting.get_model_for_value(value) # Call `create()` method on the super class to avoid recursion. obj = super(SettingQuerySet, model.objects.all()) \ .create(name=name, value=value) return obj
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 between single and multi-line text. """ if not hasattr(cls, 'value_type'): raise NotImplementedError( 'You must define a `value_type` attribute or override the ' '`is_compatible()` method on `SettingValueModel` subclasses.') return isinstance(value, cls.value_type)
python
{ "resource": "" }
q263643
exp_schedule
validation
def exp_schedule(k=20, lam=0.005, limit=100): "One possible schedule function for simulated annealing" return lambda t: if_(t < limit, k * math.exp(-lam * t), 0)
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.""" s = problem.initial_state states = [problem.result(s, a) for a in problem.actions(s)] random.shuffle(states) return genetic_algorithm(states[:n], problem.value, ngen, pmut)
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 range(n*n)] random.shuffle(cubes) return map(random.choice, cubes)
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 board[i] == 'Q': print 'Qu', else: print str(board[i]) + ' ', print
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) if not on_right: neighbors[i].append(i - n + 1) if not on_bottom: neighbors[i].append(i + n) if not on_left: neighbors[i].append(i + n - 1) if not on_right: neighbors[i].append(i + n + 1) if not on_left: neighbors[i].append(i - 1) if not on_right: neighbors[i].append(i + 1) cache[n2] = neighbors return neighbors
python
{ "resource": "" }
q263648
exact_sqrt
validation
def exact_sqrt(n2): "If n2 is a perfect square, return its square root, else raise error." n = int(math.sqrt(n2)) assert n * n == n2 return n
python
{ "resource": "" }
q263649
Node.expand
validation
def expand(self, problem): "List the nodes reachable in one step from this node." return [self.child_node(problem, action) for action in problem.actions(self.state)]
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, problem.path_cost(self.path_cost, self.state, action, next))
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: path_back.append(node) node = node.parent return list(reversed(path_back))
python
{ "resource": "" }
q263652
GAState.mate
validation
def mate(self, other): "Return a new individual crossing self and other." c = random.randrange(len(self.genes)) return self.__class__(self.genes[:c] + other.genes[c:])
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(): for (b, distance) in self.dict[a].items(): self.connect1(b, a, distance)
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.""" self.connect1(A, B, distance) if not self.directed: self.connect1(B, A, distance)
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." self.dict.setdefault(A,{})[B] = distance
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: return int(distance(locs[node.state], locs[self.goal])) else: return infinity
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) return [row for row in range(self.N) if not self.conflicted(state, row, col)]
python
{ "resource": "" }
q263658
NQueensProblem.result
validation
def result(self, state, row): "Place the next queen at the given row." col = state.index(None) new = state[:] new[col] = row return new
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 self.neighbors = boggle_neighbors(len(board)) self.found = {} for i in range(len(board)): lo, hi = self.wordlist.bounds[board[i]] self.find(lo, hi, i, [], '') return self
python
{ "resource": "" }
q263660
BoggleFinder.score
validation
def score(self): "The total score for the words found, according to the rules." return sum([self.scores[len(w)] for w in self.words()])
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.""" old_program = agent.program def new_program(percept): action = old_program(percept) print '%s perceives %s and does %s' % (agent, percept, action) return action agent.program = new_program return agent
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': return 'NoOp' elif status == 'Dirty': return 'Suck' elif location == loc_A: return 'Right' elif location == loc_B: return 'Left' return Agent(program)
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 override this method.""" if not self.is_done(): actions = [agent.program(self.percept(agent)) for agent in self.agents] for (agent, action) in zip(self.agents, actions): self.execute_action(agent, action) self.exogenous_change()
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): if self.is_done(): return self.step()
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 if thing.location == location and isinstance(thing, tclass)]
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 in self.things, "Don't add the same thing twice" thing.location = location or self.default_location(thing) self.things.append(thing) if isinstance(thing, Agent): thing.performance = 0 self.agents.append(thing)
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) print " from list: %s" % [(thing, thing.location) for thing in self.things] if thing in self.agents: self.agents.remove(thing)
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 return [thing for thing in self.things if distance2(location, thing.location) <= radius2]
python
{ "resource": "" }
q263669
XYEnvironment.percept
validation
def percept(self, agent): "By default, agent perceives things within a default radius." return [self.thing_percept(thing, agent) for thing in self.things_near(agent.location)]
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: thing.location = destination for o in self.observers: o.thing_moved(thing)
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)) for y in range(self.height): self.add_thing(Wall(), (0, y)) self.add_thing(Wall(), (self.width-1, y))
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)] self.add_edge([0, 0, 'S_', [], [S]]) for i in range(len(words)): self.scanner(i, words[i]) return self.chart
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: print '%10s: added %s' % (caller(2), edge) if not expects: self.extender(edge) else: self.predictor(edge)
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]: if Bb and self.grammar.isa(word, Bb[0]): self.add_edge([i, j+1, A, alpha + [(Bb[0], word)], Bb[1:]])
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: for rhs in self.grammar.rewrites_for(B): self.add_edge([j, j, B, [], rhs])
python
{ "resource": "" }
q263676
Chart.extender
validation
def extender(self, edge): "See what edges can be extended by this edge." (j, k, B, _, _) = edge for (i, j, A, alpha, B1b) in self.chart[j]: if B1b and B == B1b[0]: self.add_edge([i, k, A, alpha + [edge], B1b[1:]])
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. """ settings = Setting.objects.all().as_dict(default='') context = { 'SETTINGS': settings, } return context
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 these factors for bn's variables.""" node = bn.variable_node(var) vars = [X for X in [var] + node.parents if X not in e] cpt = dict((event_values(e1, vars), node.p(e1[var], e1)) for e1 in all_events(vars, bn, e)) return Factor(vars, cpt)
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: (var_factors if var in f.vars else result).append(f) result.append(pointwise_product(var_factors, bn).sum_out(var, bn)) return result
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 else: X, rest = vars[0], vars[1:] for e1 in all_events(rest, bn, e): for x in bn.variable_values(X): yield extend(e1, X, x)
python
{ "resource": "" }
q263681
consistent_with
validation
def consistent_with(event, evidence): "Is event consistent with the given evidence?" return every(lambda (k, v): evidence.get(k, v) == v, event.items())
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: Xi = node.variable if Xi in e: w *= node.p(e[Xi], event) else: event[Xi] = node.sample(event) return event, w
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.""" return ', '.join([('%s: ' + numfmt) % (v, p) for (v, p) in sorted(self.prob.items())])
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, node.parents) self.nodes.append(node) self.vars.append(node.variable) for parent in node.parents: self.variable_node(parent).children.append(node)
python
{ "resource": "" }
q263685
Factor.pointwise_product
validation
def pointwise_product(self, other, bn): "Multiply two factors, combining their variables." vars = list(set(self.vars) | set(other.vars)) cpt = dict((event_values(e, vars), self.p(e) * other.p(e)) for e in all_events(vars, bn, {})) return Factor(vars, cpt)
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)) for val in bn.variable_values(var))) for e in all_events(vars, bn, {})) return Factor(vars, cpt)
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], dict((k, v) for ((k,), v) in self.cpt.items()))
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: child.nodeValue = child.nodeValue.strip() elif child.nodeType == Node.ELEMENT_NODE: strip_minidom_whitespace(child)
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 return -1 else: hue = (-hue + 1 + 2.0/3.0) % 1 # invert and translate by 2/3 return int(floor(hue * 256))
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: r = r / 255.0 g = g / 255.0 b = b / 255.0 return color_from_hls(*rgb_to_hls(r,g,b))
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: unhexed = binascii.unhexlify(value) # Fallback for 2.7 compatibility return color_from_rgb(*struct.unpack('BBB',unhexed))
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 range(0, reps): commands.append(Command(0x00, wait=True)) return tuple(commands)
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 """ jsonText = view(request) jsonText = json.loads(jsonText.content.decode('utf-8')) return jsonText
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 """ cmd = [TermCursor.save, TermCursor.move(*xy), ''.join(args), TermCursor.restore] write(''.join(cmd))
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) new[3] &= ~termios.ECHO # lflags try: termios.tcsetattr(fd, termios.TCSADRAIN, new) passwd = raw_input(prompt) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old) return passwd
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: termios.tcsetattr(_fd, termios.TCSADRAIN, _old_settings) return ch
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 times # (it's constant anyway) if not record.exc_text: record.exc_text = self.formatException(record.exc_info) if record.exc_text: if s[-1:] != '\n': s += '\n' try: s = s + record.exc_text except UnicodeError: s = s + record.exc_text.decode(sys.getfilesystemencoding(), 'replace') return s
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: return None try: ownerName = pwd.getpwuid(ownerUid).pw_name except: ownerName = None return { 'uid' : ownerUid, 'name' : ownerName }
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: isMatch = True else: if searchPortion in cwd: isMatch = True else: if searchPortion.endswith('/') and searchPortion[:-1] in cwd: isMatch = True if not isMatch: return None cmdline = getProcessCommandLineStr(pid) owner = getProcessOwnerStr(pid) return { 'searchPortion' : searchPortion, 'pid' : pid, 'owner' : owner, 'cmdline' : cmdline, 'cwd' : cwd, } except OSError: return None except IOError: return None except FileNotFoundError: return None except PermissionError: return None
python
{ "resource": "" }