def find_functions(lines: List[Line], framework_map) -> Iterable[Function]: for func_global_line, next_func_global_line in pairwise( function_global_search(lines)): # some blocks weren't properly split, use the map to find missing functions fr = func_global_line.index + 2 # if no next global, to = None => end of file to = next_func_global_line and next_func_global_line.index func_lines = lines[fr:to] func_idx = [] for idx, line in enumerate(func_lines): if isinstance(line.body, Instruction): addr = int(line.content[0].text.strip().split()[0], 16) if f'{addr:x}' in framework_map: func_idx.append(idx) for start_idx, end_idx in pairwise(func_idx): sub_func_lines = func_lines[start_idx:( len(func_lines) if end_idx == None else end_idx)] addr = int(sub_func_lines[0].content[0].text.strip().split()[0], 16) yield Function( name=func_global_line.body.symbol if start_idx == 0 else f'func_{addr:X}', addr=addr, lines=sub_func_lines, )
def rule_14(data): """Les octaves et quintes par mouvement direct ne sont autorisées que si la voix supérieure procède par mouvement conjoint. La quinte directe est tolérable si la voix inférieure procède par mouvement conjoint, à condition que l’une des voix soit le ténor ou le contralto et que la voix inférieure aboutisse à un des bons degrés (I – IV – V) de la gamme. La quinte directe est tolérable si l’une des notes de la quinte appartient à l’accord précédent, même par mouvement disjoint, à condition qu’elle ait une bonne sonorité. À l’intérieur d’un même accord, on tolère des quintes et des octaves directes, y compris par mouvement direct et disjoint. """ chords = chord.RealizedChord.chordify(data) extreme_titles = data[0].title, data[-1].title for s1,s2 in itertools.combinations(data,2): for (n1,n2), (na, nb) in util.pairwise(tools.iter_melodies(s1,s2)): # is it a fifth or an octave? if not na.pitch.isQualifiedInterval((8,'perfect'),(5,'perfect'),(5,'diminished'),(5,'augmented')).With(nb.pitch): continue # is it in the same chord? for c in chords: if (n1,n2,na,nb) in c: continue # is it a direct 5th or octave? if motion.MotionType.motion(n1,n2,na,nb) != motion.MotionType.direct: continue # does the upper voice proceed by conjunct movement? if n1.pitch.semitoneWith(na.pitch) in (1,2): continue # if it is an octave, there's no more tolerance: it's an error if na.pitch.isInterval(8,True).With(nb.pitch): warn(f"Direct octaves with no conjunct movement is forbidden.",n1,n2,na,nb,s1.title, s2.title) continue # is it a direct 5th with lower voice going to I, IV or V # by conjunct movement in non extreme parts? if extreme_titles != (s1.title, s2.title): # get scale of the second interval: there may be a modulation between the 2 intervals. pos = max(na.pos,nb.pos) current_scale = s2.scaleAt(pos) if n2.pitch.semitoneWith(nb.pitch) in (1,2) and current_scale.is1_4_5(nb.pitch) : warn(f"Tolerance: direct fith with lower voice going to I, IV, V by conjunct movement between non extreme parts is tolerated. Do not hesitate to find a better disposition",n1,n2,na,nb,s1.title,s2.title) continue # is it a direct 5th with a note of the 5th in the previous chord? broken=False for c1, c2 in util.pairwise(chords): if (na, nb) in c2 and (na in c1 or nb in c1): warn(f"Tolerance: direct fifth is tolerated if one of the notes of the 5th can be heard in the previous chord AND if the sound is good. Please check that.",n1,n2, na,nb, s1.title,s2.title) broken=True break if broken: continue # error warn(f"""Direct 5th are forbidden, except: - when the higher voice moves by conjunct motion - when, except in extreme parts, the lower voice moves by conjunct motion to I, IV, V - when the note of the 5th can be heard in the previous chord - in a change of position inside a chord. """, n1,n2, na,nb,s1.title,s2.title)
def forbid_false_relation_tritone(s1,s2,allow_in_minor=False): """ Warn if tritone false relation is found """ msg = f"False relation of tritone is forbidden. In {s1.title} and {s2.title}" def __fun(n1, n2): n1p, n2p = [util.to_pitch(x) for x in (n1,n2)] def __is_VI_VII_minor(): if allow_in_minor is not True: return False if s1.scale.mode == scale.Mode.m_rising: _scale = s1.scale.mode elif s1.scale.mode == scale.Mode.m_full: _scale = s1.scale.minor_scales[scale.Mode.m_rising] elif s1.scale.mode == scale.Mode.M: _scale = s1.scale.mode.relative(scale.Mode.m_rising) else: return False try: return _scale.isDegree(n1p,6) or _scale.isDegree(n1p,7) or _scale.isDegree(n2p,6) or _scale.isDegree(n2p,7) except ValueError: return False if n1p.isTritoneWith(n2p) and not __is_VI_VII_minor(): error.warn(msg,n1,n2) for (na, n1), (nb, n2) in util.pairwise(tools.iter_melodies(s1,s2,all=True)): nap, nbp, n1p, n2p = [util.to_pitch(x) for x in (na, nb, n1, n2)] __fun(na,n2) __fun(n1,nb)
def temporal_sort(self): """Get nodes sorted in temporal order Remark ------ This relies on a combination of temporal ordering of anchored times and topological ordering for drifting times. To be 100% sure that one drifting time happens before another time, check the ordering graph (method .ordering_graph()). """ g = nx.DiGraph() # add times for t in self.nodes_iter(): g.add_node(t) # add existing edges for t1, t2 in self.edges_iter(): g.add_edge(t1, t2) # connect pairs of consecutive anchored times anchored = sorted(self.anchored()) for t1, t2 in pairwise(anchored): g.add_edge(t1, t2) return nx.topological_sort(g)
def getPlayers(html): soup = BeautifulSoup(html, "html.parser") # <div class="order-title"><div>Miami Heat - Oklahoma City Thunder</div> pl = soup.findAll("span", "ev-outcome") playersJson = [] for a in pl: if not a.has_attr("onclick"): continue onclick = a["onclick"] onclick = re.sub("^[^{]*{[^{]*", "", onclick) onclick = re.sub("[^}]*}$", "", onclick) #print(onclick) resp = json.loads(onclick) if "Player total" in resp["alt_name"]: playersJson.append(resp) # print(resp["option"]) # print(resp["coef"]) # print() players = [] for a, b in util.pairwise(playersJson): player = util.Player() player.player_name = cleanName(a["option"]) player.player_total = cleanPoints(a["option"]) player.under = a["coef"] player.over = a["coef"] player.start_time = "NONE" player.bookie_name = BOOKIE_NAME player.bookie_url = BOOKIE_URL players.append(player) return players
def func(voice): for (n1,c1,*notes1), (n2,c2,*notes2) in util.pairwise(tools.iter_notes_and_chords(voice,chords,*data)): if not (c1.abstract.isSeventh(n1) and c1.abstract.degree == 5): continue # the 7th goes to the inferior degree if n1.pitch.isQualifiedInterval((2,"minor"),(2,"major")).With(n2.pitch) and n1.pitch > n2.pitch: continue # the 7th goes to the fifth in the same chord if c1 is c2 and c2.abstract.isFifth(n2): continue # the 7th stays onplace in the following chord if n1.pitch == n2.pitch: continue # the 7th goes higher to avoid doubling the leadingtone or the bass of a first inversion chord expected = [] sc2 = c2.abstract.scale for semitone in (n1.pitch.value.semitone -1,n1.pitch.value.semitone -2): try: expected.append(sc2.findNoteBySemitone(semitone)) except ValueError: continue # is it to avoid doubling the leading tone? if max((sc2.isLeading(p) for p in expected)) and max((sc2.isLeading(p.pitch) for p in notes2)): continue # is it to avoid doubling the bass of a 1st inversion chord? if c2.abstract.isInversion(notes2,1) and max((c2.abstract.isThird(p) for p in expected)): continue # error warn(f"The 7th in a dominant chord must go to the inferior degree, or to the fifth of the chord, or stay onplace in the following chord",n1,n2,voice.title)
def make_live_active_chain(g: 'G', source_chain: NRef, focal_point: NRefs, **kwargs) -> NRef: if not source_chain: raise UnexpectedFizzle('no source passive_chain') if not focal_point: raise UnexpectedFizzle('no focal_point') initial_source_node = g.initial_member_of(source_chain) if not initial_source_node: raise UnexpectedFizzle('no initial_source_node') live_active_chain = g.add_node('LiveActiveChain', source_chain=source_chain, focal_point=focal_point, **kwargs) prev_active_node: MaybeNRef = None for (prev_source_node, next_source_node) in pairwise(g.walk(initial_source_node, 'next')): next_active_node_class = look_up_active_node_class( g, prev_source_node, next_source_node) new_active_node = g.add_node( next_active_node_class, focal_point=focal_point, need_basis_like=prev_source_node, prev=prev_active_node, # TODO already_built should ignore this member_of=live_active_chain, # TODO " " " support_from=live_active_chain) g.set_mutual_activation(live_active_chain, new_active_node) prev_active_node = new_active_node return live_active_chain
def getPlayers(html): soup = BeautifulSoup(html, "html.parser") # <div class="order-title"><div>Miami Heat - Oklahoma City Thunder</div> pl = soup.findAll("span", "ev-outcome") playersJson = [] for a in pl: if not a.has_attr("onclick"): continue onclick = a["onclick"] onclick = re.sub("^[^{]*{[^{]*", "", onclick) onclick = re.sub("[^}]*}$", "", onclick) # print(onclick) resp = json.loads(onclick) if "Player total" in resp["alt_name"]: playersJson.append(resp) # print(resp["option"]) # print(resp["coef"]) # print() players = [] for a, b in util.pairwise(playersJson): player = util.Player() player.player_name = cleanName(a["option"]) player.player_total = cleanPoints(a["option"]) player.under = a["coef"] player.over = a["coef"] player.start_time = "NONE" player.bookie_name = BOOKIE_NAME player.bookie_url = BOOKIE_URL players.append(player) return players
def forbidden_intervals(s: stave.Stave, *intervals): """Same as allowed_intervals, but for forbidden ones""" for n1, n2 in util.pairwise(s): if n1.pitch.isQualifiedInterval(*intervals).With(n2.pitch): error.warn(f"Following intervals are forbidden: {intervals}.", n1, n2, s.title)
def rule_4(cp,cf): """Le temps fort doit être en consonance. Il sera toléré, dans les cas difficiles, de placer la dissonance au temps fort, à la condition qu'elle se produise dans la forme de broderie ou de note de passage et que les deux parties procèdent par mouvement contraire et par degrés conjoints""" # in this function, we do not look at the first note if the first note is at the downbeat, for it is already checked by function rule_3 for (n1, na), (n2, nb) in util.pairwise(tools.iter_melodies(cp,cf,alone=False)): # is it downbeat? if cp.isUpBeat(n2): continue n1p, nap, n2p, nbp = [util.to_pitch(x) for x in (n1,na, n2, nb)] #is it a consonance? if n2p.isConsonantWith(nbp): continue #is it a cambiata or a passing tone? is_pt_or_c = cp.isCambiata(n2,False) or cp.isPassingTone(n2,False) #is it a conjunct movement? is_conjunct = cp.isConjunct(n2) #is it a contray motion? first = [n1p,nap] second = [n2p,nbp] first.sort(key=lambda x : x,reverse=True) second.sort(key=lambda x : x,reverse=True) is_contrary = motion.MotionType.motion(*first,*second) == motion.MotionType.contrary warn(f"""The downbeat is dissonant. It must be: - a cambiata or passing tone: {is_pt_or_c} - come from a conjunct motion: {is_conjunct} - come from a contrary motion: {is_contrary} """,cp.title,n2)
def split_segments(bool_array, merge_thresh, discard_thresh=None): diff = np.diff(bool_array.astype(np.int)) ones = np.where(diff == 1)[0] mones = np.where(diff == -1)[0] if len(ones) == 0: ones = np.array([0]) if len(mones) == 0: mones = np.array([len(diff) - 1]) if ones[0] > mones[0]: ones = np.append(0, ones) if ones[-1] > mones[-1]: mones = np.append(mones, len(diff) - 1) assert len(ones) == len(mones) segments = np.array([ones, mones]).T if discard_thresh is not None: s = (segments[:, 1] - segments[:, 0]) > discard_thresh segments = segments[s] if len(segments) == 0: return [] merged = [segments[0]] for a, b in pairwise(segments): if b[0] - a[1] < merge_thresh: merged[-1][1] = b[1] else: merged.append(b.tolist()) return merged
def rule_6(data): """Les voix ne doivent pas toutes effectuer le même mouvement, sauf si on enchaîne deux accords de sixtes.""" for group1, group2 in util.pairwise(tools.iter_melodies(*data)): try: assert len(group1) == len(group2) and "Error : pauses not handled" except: from IPython import embed;embed() is_same_mov = True for i in range(len(group1)): for j in range(i+1,len(group1)): notes1 = sorted(util.to_pitch([group1[i],group1[j]]),key=lambda x : x.value.semitone) notes2 = sorted(util.to_pitch([group2[i],group2[j]]),key=lambda x : x.value.semitone) if motion.MotionType.motion(*notes1,*notes2) is not motion.MotionType.direct: is_same_mov = False break if is_same_mov is False: break if is_same_mov: # are there 2 consecutive sixth? pos1 = max(group1,key=lambda x:x.pos).pos scale1 = data[0].scaleAt(pos1) c1 = chord.AbstractChord.findBestChord(group1,scale1) pos2 = max(group2,key=lambda x:x.pos).pos scale2 = data[0].scaleAt(pos2) c2 = chord.AbstractChord.findBestChord(group2,scale2) if not (c1.isInversion(group1,1) and c2.isInversion(group2,1)): warn(f"All the voices shouldn't be in the same direction.",group1,group2)
def forbid_consecutive_interval(s1, s2, interval): """Warn if two intervals of the same type are consecutive Interval must be qualified""" for (na,n1), (nb, n2) in util.pairwise(tools.iter_melodies(s1,s2,all=True)): nap, nbp, n1p, n2p = [util.to_pitch(x) for x in (na, nb, n1, n2)] if nap.isQualifiedInterval(interval).With(n1p) and nbp.isQualifiedInterval(interval).With(n2p): error.warn(f"Two {interval} in a row are forbidden",na,nb,n1,n2,f"in {s1.title} and {s2.title}")
def viterbi_probabilities(sentence_labels, tag_map, lambda_=0.001): """Return initial state and transition probabilities estimated from given list of lists of labels.""" num_labels = len([k for k in tag_map if k is not None]) init_count = np.zeros(num_labels) + lambda_ trans_count = np.zeros((num_labels, num_labels)) + lambda_ for labels in sentence_labels: init_count[tag_map[labels[0]]] += 1 for prev, curr in pairwise(labels): try: trans_count[tag_map[prev], tag_map[curr]] += 1 except Exception as e: error(f'ERROR: {e} {tag_map}') init_prob = init_count / np.sum(init_count) trans_prob = [] for l_count in trans_count: total = np.sum(l_count) if total: l_prob = l_count / total else: # TODO warn? l_prob = np.ones(num_labels) / num_labels trans_prob.append(l_prob) trans_prob = np.array(trans_prob) return init_prob, trans_prob
def rule_23(data): """ La quarte doit être sauvée : soit la note supérieure reste en place ou descend d’un degré ; soit la basse reste en place. """ for group1, group2 in util.pairwise(tools.iter_melodies(*data)): c = chord.AbstractChord.findBestChordFromStave(group1,data[0]) if not c.isInversion(group1,2): continue last_pos = min(group1,key=lambda x : x.last_pos).last_pos is_correct = False for n,n2 in zip(group1,group2): if c.isFifth(n) and n.last_pos > last_pos: is_correct = True break elif c.isRoot(n): if (n.last_pos > last_pos): is_correct = True break elif n.pitch > n2.pitch and n.pitch.isConjunctWith(n2.pitch): is_correct = True break if is_correct: continue else: warn(f"In a 2nd inversion chord, the root must go to lower degree by conjunct motion, or must continue by syncopation, or the 5th must continue by syncopation",group1)
def parse(html): soup = BeautifulSoup(html, "html.parser") #find teams pll = soup.findAll("span", "team-name") #for p in pll: for a, b in util.pairwise(pll): line = "" aux_list = [] print(a.contents[0]) aux_list.append(cleanBothEnds(a.contents[0])) print(b.contents[0]) aux_list.append(cleanBothEnds(b.contents[0])) print("+++++++++++++++") #find date try: date = soup.find_all("span", {"class": "date ui-countdown"}) except: date = [] if date != []: date = date[0].contents[0] else: date = "En Juego" aux_list.append(cleanDate(date)) #print (soup.find_all("span", {"class":"date ui-countdown"})) print("---------------") #find bets try: runner_list = soup.find_all( "ul", {"class": "runner-list-selections"})[-1] #print(runner_list) except: runner_list = "except" money_line_first = runner_list.find_all("li", {"class": "selection sel-0"}) money_line_first_bet = money_line_first[0].find_all( "span", {"class": "ui-runner-price"}) money_line_second = runner_list.find_all("li", {"class": "selection sel-1"}) money_line_second_bet = money_line_second[0].find_all( "span", {"class": "ui-runner-price"}) print(money_line_first_bet[0].contents[0] + "++++++++++" + money_line_second_bet[0].contents[0]) """for a,b in util.pairwise(money_line_first): print("->") print (a) #print (b) #if bet != : # aux_list.append(bet.content[0])""" aux_list.append(cleanBothEnds(money_line_first_bet[0].contents[0])) aux_list.append(cleanBothEnds(money_line_second_bet[0].contents[0])) print(aux_list) print("*************************************") return aux_list
def rule_13(cp,cf): """Éviter la broderie ou la note de passage qui produit l'intervalle de seconde mineure avec le chant donné""" for (n1, na), (n2, nb) in util.pairwise(tools.iter_melodies(cp,cf,alone=False)): if not (cp.isCambiata(n2) or cp.isPassingTone(n2)): continue n1p, nap, n2p, nbp = [util.to_pitch(x) for x in (n1,na, n2, nb)] if n2p.semitoneWith(nbp) == 1: warn(f"Avoid minor seconds",cp.title,n2)
def __init__(self, words): self.words = words self.document = None for word in self.words: word.sentence = self for w1, w2 in pairwise(self.words): w1.next_word = w2 w2.prev_word = w1
def rule_26(soprano,bass): """ La quinte directe entre parties extrêmes par modulation et mouvement chromatique est prohibée. """ # TODO on ne vérifie pas s'il y a une quinte... for (h1,l1), (h2,l2) in util.pairwise(tools.iter_melodies(soprano,bass)): mot = motion.MotionType.motion(h1,l1,h2,l2) if mot == motion.MotionType.direct and (h1.pitch.isChromaticInflectionWith(h2.pitch) or l1.pitch.isChromaticInflectionWith(l2.pitch)): warn(f"A direct fifth by modulation and chromatic motion is forbidden between extreme parts",h1,h2,l1,l2,soprano.title,bass.title)
def create_bpf_repr(peaks_x, audio_chunk): bpf = np.zeros_like(audio_chunk) # bpf starts at the beginning of the chunk and ends at the end p = np.append(np.append(0, peaks_x), len(audio_chunk) - 1) for aa, bb in pairwise(p): a, b = aa - p[0], bb - p[0] ab = np.linspace(audio_chunk[a], audio_chunk[b - 1], b - a) bpf[a:b] = ab return bpf
def rule_5(cp, cf): """Le temps faible peut être en consonance ou en dissonance, pourvu que la dissonance se produise par degrés conjoints""" for (n1, na), (n2, nb) in util.pairwise(tools.iter_melodies(cp,cf,alone=False)): if not cp.isUpBeat(n2): continue n1p, nap, n2p, nbp = [util.to_pitch(x) for x in (n1,na, n2, nb)] if not n2p.isConsonantWith(nbp): if not cp.isConjunct(n2): warn(f"If the upbeat is dissonant, it must come from a conjunct motion.",cp.title,n2)
def forbid_direct_interval(s1, s2, *intervals): """Warns if interval occured by direct motion intervals must be qualified or not """ for (na,n1), (nb, n2) in util.pairwise(tools.iter_melodies(s1,s2,all=True)): nap, nbp, n1p, n2p = [util.to_pitch(x) for x in (na, nb, n1, n2)] answer = nbp.isQualifiedInterval(*intervals).With(n2p) if not isinstance(intervals[0],int) else nbp.isInterval(*intervals,True).With(n2p) if answer and (motion.MotionType.motion(na,n1,nb,n2) == motion.MotionType.direct): error.warn(f"It is forbidden to go to direct {intervals}",na,nb,n1,n2,f"in {s1.title} and {s2.title}")
def make_all(gens, subgens, coeffs): angles = PlaneAngles(gens) for (x, y), a in zip(util.pairwise(gens), coeffs): angles[x, y] = a mirrors = angles.normals cosets = solve(*schlafli(gens, subgens, coeffs)) elements = solve(*schlafli(subgens, '', coeffs[:len(subgens) - 1])) return mirrors, cosets.words, elements.words
def rule_7(cp, cf): """Lorsqu'une broderie forme dissonance attractive de quarte augmentée ou de quinte diminuée, et qu'elle retourne sur la note consonante qui l'a précédée, elle est à éviter. Cette règle est applicable aussi à la dissonance de quarte et, avec plus de tolérance, à celles de seconde et de septième""" for (n1, na), (n2, nb) in util.pairwise(tools.iter_melodies(cp,cf,alone=False)): if not cp.isCambiata(n2): continue n1p, nap, n2p, nbp = [util.to_pitch(x) for x in (n1,na, n2, nb)] if n2p.isQualifiedInterval((5,"diminished"),(4,"augmented"),(4,"perfect")).With(nbp) and n1p.isConsonantWith(nap): warn(f"It is forbidden to have a cambiata having an interval of 5th diminished, 4th perfect or augmented that return to a consonant pitch", cp.title,n2) elif n2p.isInterval(2,7,True).With(nbp) and n1p.isConsonantWith(nap): warn(f"If the cambiata forms a seventh or a second with the other voice, it can return to the consonant note by tolerance only",cp.title,n2)
def _build_playlist(graph, words): playlist = [] if len(graph) > 0: try: path = shortest_path(graph, 0, len(words)) except: raise SystemExit for start, stop in pairwise(path): track = graph.edge[start][stop]['track'] playlist.append((track['name'], track['artists'][0]['name'], track['href'])) return playlist
def allowed_intervals(s: stave.Stave, *intervals): """Checks that only allowed intervals are used in s. Warn if not true. Intervals are entered as a sequence of pairs: (interval,qualification) = (3,"minor") See pitch.py for exact syntax. """ for n1, n2 in util.pairwise(s): if not n1.pitch.isQualifiedInterval(*intervals).With(n2.pitch): error.warn( f"Interval forbidden: {n1.pitch.qualifiedIntervalWith(n2.pitch)}", n1, n2, s.title)
def rule_5(data): """La sensible doit monter sur la tonique ou rester sur place avant de monter sur la tonique. Si la sensible est dans l'une des répétitions d'une marche d'harmonie, cette règle n'est pas nécessaire.""" st = tools.SequenceTracker(data) for voice in data: for n1, n2 in util.pairwise(voice): sc1 = voice.scaleAt(n1.pos) sc2 = voice.scaleAt(n2.pos) if sc1 == sc2 and sc1.isLeading(n1.pitch) and (not sc2.isTonic(n2.pitch)) and (not sc2.isLeading(n2.pitch)) and not st.isInRestatement(n1): warn(f"The leading tone should go to the tonic, except in a restatement of a sequence.",n1,n2,voice.title)
def calculate_motion_types(s1, s2): """Finds the number of motion type: direct, contrary and oblique""" movs = { motion.MotionType.direct : 0, motion.MotionType.contrary : 0, motion.MotionType.oblique : 0, motion.MotionType.no:0} for (na,n1), (nb, n2) in util.pairwise(tools.iter_melodies(s1,s2,alone=False)): nap, nbp, n1p, n2p = [util.to_pitch(x) for x in (na, nb, n1, n2)] movs[motion.MotionType.motion(nap,n1p,nbp,n2p)] += 1 return movs
def getPlayers(html): soup = BeautifulSoup(html, "html.parser") pll = soup.findAll("span", "name ellipsis") pl = soup.findAll("span", "formatted_price") players = [] for A, B in util.pairwise(zip(pll, pl)): name, surname = getNameAndSurname(A[0].find(text=True)) points = getPoints(A[0].find(text=True)) under = A[1].find(text=True) over = B[1].find(text=True) player = util.getPlayer(name, surname, points, under, over, BOOKIE_NAME, BOOKIE_URL) players.append(player) return players
def __init__(self, *args, **kwargs): kilometers = kwargs.pop('kilometers', 0) if len(args) == 1: # if we only get one argument we assume # it's a known distance instead of # calculating it first kilometers += args[0] elif len(args) > 1: for a, b in util.pairwise(args): kilometers += self.measure(a, b) kilometers += units.kilometers(**kwargs) self.__kilometers = kilometers
def getPlayers(html): soup = BeautifulSoup(html, "html.parser") pl = soup.find("li", {"data-clue" : "Over/Under points (player)"}) players = [] names = pl.findAll("span", "bets_oc ttt") odds = pl.findAll("button", "betbut a") for a, b in util.pairwise(zip(names, odds)): name, surname = cleanName(a[0].find(text=True)) points = cleanPoints(a[0].find(text=True)) over = a[1].find(text=True) under = b[1].find(text=True) player = util.getPlayer(name, surname, points, under, over, BOOKIE_NAME, BOOKIE_URL) players.append(player) return players
def getPlayers(html): soup = BeautifulSoup(html, "html.parser") players = [] pl = soup.findAll("td", "price width30") for a, b in util.pairwise(pl): respA = json.loads(a["data-sel"]) name, surname = cleanName(respA["mn"]) points = cleanPoints(respA["sn"]) under = "%.2f" % float(respA["epr"]) respB = json.loads(b["data-sel"]) over = "%.2f" % float(respB["epr"]) player = util.getPlayer(name, surname, points, under, over, BOOKIE_NAME, BOOKIE_URL) players.append(player) return players
def rule_20(data): """La fausse relation de triton est proscrite.""" st = tools.SequenceTracker(data) for notes1, notes2 in util.pairwise(tools.iter_melodies(*data,alone=False)): clef = lambda n : n.pitch h1 = max(notes1,key=clef) l1 = min(notes1,key=clef) h2 = max(notes2,key=clef) l2 = min(notes2,key=clef) if h1 == h2 or l1 == l2: continue if ((h1.pitch.isTritoneWith(l2.pitch) or l1.pitch.isTritoneWith(h2.pitch)) and (not st.isInRestatement(h1) and not st.isInRestatement(h2))): warn(f"False relation of tritone is forbidden between extreme parts, except inside the restatement in a sequence.",notes1,notes2)
def interpolate_iter(cls, defn, nlevels): npairs = len(defn) - 1 nlevel_pair = nlevels // npairs nlevel_leftover = nlevels - (nlevel_pair * npairs) # pair together the definition for idx, (c1, c2) in enumerate(pairwise(defn)): # start at the start colour, end at the colour before the next colour level # ... except at the last idx, where we must end at the end colour ninc = n = nlevel_pair if idx == npairs - 1: n += nlevel_leftover ninc = n - 1 colour_inc = (c2 - c1) / float(ninc) for l in xrange(n): yield c1 + (colour_inc * l)
def getTemplates(dictY, dictV, phraseDict, spanMax=1, spanMin=0): positions = {} for y in dictY: for p in phraseDict[y]: positions[p] = 'y' for v in dictV: for p in phraseDict[v]: positions[p] = 'v' templates = [] for (p1, yv1), (p2, yv2) in pairwise(sorted(positions.iteritems())): if yv1 == yv2: continue if p1[:-1] != p2[:-1]: continue diff = p2[-1] - p1[-1] - 1 if spanMin <= diff <= spanMax: templates.append((p1,p2,yv1+yv2)) return templates
def calc_new_trans_p(ancestors_by_chr, states): # Count number of transitions from one state to another # (set minimum transition counts to 1 so we don't have any 0 probabilities) trans_counts = {s_outer: {s_inner: 1 for s_inner in states} for s_outer in states} for ancestors in ancestors_by_chr.values(): for anc_prev_grp, anc_curr_grp in pairwise(ancestors): for anc_prev in anc_prev_grp.split('_'): for anc_curr in anc_curr_grp.split('_'): trans_counts[anc_prev][anc_curr] += 1 # New transition rate of s1->s2 is count(s1->s2)/count(s1->*) new_trans_p = {} for s_outer in states: new_trans_p[s_outer] = {} for s_inner in states: tot_trans = float(sum(trans_counts[s_outer].values())) new_trans_p[s_outer][s_inner] = log(trans_counts[s_outer][s_inner] / tot_trans) return new_trans_p
def validate(self): errors = CompositeRecord.validate(self) start_day = 1 last_day_of_month = calendar.monthrange(self.year, self.month)[1] end_day = last_day_of_month today = date.today() if (self.year == today.year) and (self.month == today.month): end_day = today.day if (today.day == 1) else (today.day - 1) for r in self.records: if (r.day.year != self.year) or (r.day.month != self.month): errors.append('Record belongs to another month: {}'.format(r.identifier())) for i in xrange(start_day, end_day + 1): if not self.get_day_record(i): errors.append('Missing day: {}.'.format(i)) sorted_records = sorted(self.records, key=lambda r: r.checkin or datetime.max) for (a, b) in pairwise(sorted_records): if (a.checkin and a.checkout and b.checkin) and (a.checkin <= b.checkin <= a.checkout): errors.append('Overlapping records: ({}) and ({})'.format(a, b)) return errors
def iterAllInternal(self, spanMax=1, spanMin=1): for (ak,av), (bk,bv) in pairwise(sorted(self.position.iteritems())): if ak[0] != bk[0]: continue #groupids are different diff = bk[1] - av[0] - 1 #b-beggining-position - a-ending-position if spanMin <= diff <= spanMax: yield ak[0], (ak[1],av[0]), (bk[1],bv[0])
def snakeplot(image, snaxels=None, energy_fn=None, use_prev=False, point_size=10, point_alpha=0.6, subplot=True): pylab.clf() if subplot: ax1=pylab.subplot(2,1,1) ref = pylab.imshow(image, cmap=pylab.cm.gray, aspect='auto') (ylim, xlim) = (pylab.ylim(), pylab.xlim()) if snaxels: ie = numpy.empty(len(snaxels)) ee = ie.copy() ie[:] = 0 ee[:] = 0 for i in range(len(snaxels)-1): current = snaxels[i] next = snaxels[i+1] if i > 0: prev = snaxels[i-1] else: prev = None if energy_fn: if use_prev: (_i, _e) = energy_fn(prev, current, next, discrete=True) else: (_i, _e) = energy_fn(current, next, discrete=True) ie[i] = _i ee[i] = _e dsnake = numpy.array(snaxels) pylab.plot(dsnake[:,0], dsnake[:,1], 'b') if energy_fn: plots.scatter.multiscatter(dsnake[:,0], dsnake[:,1], (ie, ee), s=point_size, alpha=point_alpha, cmap=pylab.cm.hot) pylab.xlim(xlim) pylab.ylim((numpy.max(dsnake[:,1])+100, numpy.min(dsnake[:,1])-100)) if subplot: pylab.subplot(2,1,2, sharex=ax1) for cur, next in util.pairwise(snaxels): index_x = numpy.arange(cur[0], next[0]+1) index_y = numpy.linspace(cur[1], next[1], num=len(index_x), endpoint=True) index_floor_y = numpy.floor(index_y) data_current = image[index_floor_y.astype('i'), index_x.astype('i')] data_next = image[(index_floor_y + 1).astype('i'), index_x.astype('i')] ratio = index_y - index_floor_y # interpolation data = ratio * data_next + (1 - ratio) * data_current pylab.plot(index_x, data) pylab.xlim(xlim) pylab.draw() return ref
def happiness_change(arrangement): arrangement += arrangement[0:1] return (sum(cost[a][b] for a, b in pairwise(arrangement)) + sum(cost[a][b] for a, b in pairwise(reversed(arrangement))))
def build_snake(): global pickedsnake, stepsize, snaxels, snaxels_x, slope tmpsnake = pickedsnake[:] tmpsnake.append([snaxels_x[0], None]) tmpsnake.append([snaxels_x[-1], None]) tmpsnake.sort(key=lambda x: x[0]) near_x = lambda x: numpy.argmin(numpy.abs(numpy.array(snaxels_x)-x)) for a, b in util.pairwise(tmpsnake): ya = a[1] yb = b[1] targets = range(near_x(a[0]), near_x(b[0])+1) results = [] weights = [] if ya: localresult = [] localweights = [] for dst, x in enumerate(range(snaxels_x[targets[0]], snaxels_x[targets[-1]]+1)): ya += slope[round(ya), x] if x in snaxels_x: i = near_x(x) #snaxels[i][1] = round(ya) localweights.insert(0,dst+1) localresult.append(round(ya)) results.append(localresult) weights.append(localweights) if yb: localresult = [] localweights = [] for dst, x in enumerate(range(snaxels_x[targets[-1]], snaxels_x[targets[0]]-1,-1)): yb -= slope[round(yb), x] if x in snaxels_x: i = near_x(x) #snaxels[i][1] = round(yb) localweights.append(dst+1) localresult.insert(0, round(yb)) results.append(localresult) weights.append(localweights) results = numpy.array(results) weights = numpy.array(weights).astype('f') weights /= numpy.sum(weights, axis=0).astype('f') results = numpy.sum(results * weights, axis=0).tolist() for i, j in enumerate(targets): try: snaxels[j][1] = results[i] except IndexError: pass
from __future__ import print_function from itertools import permutations from collections import defaultdict import re from util import Timer, pairwise dist = defaultdict(dict) for line in open('input9.txt'): match = re.match(r'(\w+) to (\w+) = (\d+)', line) src, tgt, length = match.groups() dist[src][tgt] = dist[tgt][src] = int(length) places = set(dist) # Part 1 with Timer() as t: results = [(sum(dist[a][b] for a, b in pairwise(path)), path) for path in permutations(places)] print('Part 1:', sorted(results, key=lambda x: x[0])[0], t) # Part 2 print('Part 2:', sorted(results, key=lambda x: x[0], reverse=True)[0], t)