content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def sort_pulsar_dict(pulsar_dict): """ Sorts a pulsar dict by frequency Parameters: ----------- pulsar_dict: dictionary A dictionary of profiles from get_data_from_epndb returns: -------- pulsar_dict: dictionary The same dictionary sorted by frequency """ freq_l...
4fc0880bb96337f4def3bee5373bdaef63039df9
115,884
def sum_power(n): """Sums digits of 2^n.""" digits = [2] for _ in range(n-1): for i in range(len(digits)-1, -1, -1): d = digits[i] if 2*d > 9: digits[i] = (2*d)%10 if i == len(digits)-1: digits.append((2*d) // 10) ...
38da5319e3e09a1a5c32607073bd94f4dd1a4459
115,890
def n_of(parser, n): """Consumes n of parser, returning a list of the results. """ return [parser() for i in range(n)]
ac5ad5ec18d30f6b221027e25ad624a09e1c2a1c
115,891
def get_stations_by_town(stations): """ Returns a dictionary consisting of a (key, value) pair of towns (key) and a list of the stations inside of them (value) """ towns = {} # dictionary of towns for station in stations: town = station.town if town in towns: towns[t...
cc18f6304f4a05894131173ce36b7dec2e95220a
115,897
from typing import Union from pathlib import Path import glob import re def get_latest_version(file_pattern: Union[str, Path]) -> int: """Assuming the file pattern select list of files tagged with an integer version for every run, this function return the latest version number that you can use to name your ne...
19a4a3cc34ca3d148c8baef96084dda8e174c13c
115,901
def Location(child): """ Return x,y offset of Region See comment in Region.Child() Args: child: '0','1','2','3' Returns: (x,y): lower-left origin """ childnum = int(child) x = childnum & 1 # mask the y bit y = childnum >> 1 # shift over the y bit y = not y return (x,y)
ad27314cf34ecc1515507de129507ca14bcf7732
115,903
def date_second(date): """Find the second from the given date.""" return date.second
774d3def41b78a8a967b9ae25da8713129429966
115,912
import re def remove_string_extras(mytext: str): """ remove_string_extras - removes extra characters from a string. everything except A-Za-z0-9 .,; """ return re.sub(r"[^A-Za-z0-9 .,;]+", "", mytext)
c17da9638225647d3f13a4f9d4cea2b06696e2ab
115,913
def sqr_norm_l2(x): """ Computes the squared l_2 norm of a vector """ return x.T @ x
7aef78a90db6fb797134ef0de1d57c9efacecf7e
115,916
def near(a, b, eps = 0.0000001): """ returns whether numerical values a and b are within a specific epsilon environment """ diff = abs(a-b) return diff < eps
6bc0f2f23caf7864f0e5d5c1260ed8d0b7b2d3d9
115,917
def get_variable_indices(atom): """ Gets the indexes of the variables in the atom. :param atom: the atom :type atom: Atom :return: the indices of the variables :rtype: list[int] """ indexes = [] for i in range(atom.arity()): if not atom.terms[i].is_constant(): in...
7daf0faab7c8c4470313d7b609b7589b87153bfa
115,919
import six def get_first(predicate, source): """Searches for an item that matches the conditions. :param predicate: Defines the conditions of the item to search for :param source: Iterable collection of items :return: The first item that matches the conditions defined by the specified pr...
cfaa1abd9dc70ca1fbc452e2a8f6678f8438af74
115,920
def clean_tag(tag): """ Removes unwanted elements from a tag. :param tag: a bs4.element.Tag object containg an infobox that should be clean :return: cleaned_tag: a bs4.element.Tag object that has had nuisance elements removed """ cleaned_tag = tag for sup in cleaned_tag('sup'): sup.d...
e85bc836e95e9d935be6cf4bcef8f14a381f4e48
115,927
def get_weekday_occurrence(day): """Calculate how often this weekday has already occurred in a given month. :type day: datetime.date :returns: weekday (0=Monday, ..., 6=Sunday), occurrence :rtype: tuple(int, int) """ xthday = 1 + (day.day - 1) // 7 return day.weekday(), xthday
7b22eefe629cd51312d7a8be0908438ab7fef7d6
115,929
def div_ceil(n, d): """Integer divide that sounds up (to an int). See https://stackoverflow.com/a/54585138/5397207 Examples >>> div_ceil(6, 2) 3 >>> div_ceil(7, 2) 4 >>> div_ceil(8, 2) 4 >>> div_ceil(9, 2) 5 """ return (n + d - 1) // d
eaf647f7d6991804e3465d3166cbea6987087944
115,930
def sanitize_string(str): """ sanitize a string by removing /, \\, and -, and convert to PascalCase """ for strip in ["/", "\\", "-"]: str = str.replace(strip, " ") components = str.split() return "".join(x.title() for x in components)
fdc4a94dc4e5c3dc3ef30d8fbf67ab9814190a27
115,931
def visit_level(t, n, act): """ Visit each node of BinaryTree t at level n and act on it. Return the number of nodes visited visited. @param BinaryTree|None t: binary tree to visit @param int n: level to visit @param (BinaryTree)->Any act: function to execute on nodes at level n @rtype: in...
e3286dadc9bc77c1b0a08ddaee31d6bce2722f6c
115,932
def _get_segment_from_id(segment_obj_list, segment_id): """ Get a segment from a list, based on a segment id """ found_segment_obj = None for segment_obj in segment_obj_list: if segment_obj.id == segment_id: found_segment_obj = segment_obj break return found_segment_obj
6cb9a649a40a1c52fdcac7db68e7fd5457344ebd
115,933
def is_rc_supported_for_platform(taskgen): """ Check if the platform supports rc compiling, following these rules: 1. MSVC base target platform 2. Non static library :param tg: The task generator to determine the platform and target type :return: True if windows rc compiling is supported, False if not """ p...
03c7d8332f72dbe69cab36f326e1348d15fb46a1
115,938
def get_prefered_quotation_from_string(string): """ Tries to determin the quotation (`"` or `'`) used in a given string. `"` is the default and used when no quotations are found or the amount of `"` and `'` are equal """ return "'" if string.count("'") > string.count('"') else '"'
505c9bcffeb66b7c1f866580274a48e98c4ca915
115,944
def strip_filter(text): """Trim whitespace.""" return text.strip() if text else text
3669789e3ed401e639c63d33675f04548528b89e
115,953
def player_color(player_name): """Return color of a player given his name """ return { 1 : (0, 255, 0), 2 : (0, 0, 255), 3 : (255, 0, 0), 4 : (255, 255, 0), 5 : (0, 255, 255), 6 : (255, 0, 255), 7 : (224, 224, 224), 8 : (153, 153, 255) }[pl...
ddd38eb23016ae01e9cbce9f36b04d2d8fe2c52a
115,955
def animation(object, *commands): """ animation(object, *commands) -> None Does operations on an animation curve. The following commands are supported: - B{clear} deletes all the keys from the animation. - B{erase} C{index I{last_index}} removes all keyframes between index and last_index ...
bc9f3d9c8950e1e225490d07e7d818b031a8f5cb
115,957
from typing import Any def short(obj: Any, width: int = 45) -> str: """ Elides an object string representation to the specified length, adding ellipsis (...) and the remaining glyph count to the end of the string. Returns the string as-is if string representation is shorter than the specified width. ...
347b885112a364c115cee88b422c7ff244e9c65b
115,959
def get_num_classes(DATASET: str) -> int: """Get the number of classes to be classified by dataset.""" if DATASET == 'MELD': NUM_CLASSES = 7 elif DATASET == 'IEMOCAP': NUM_CLASSES = 6 else: raise ValueError return NUM_CLASSES
4f4d6a17d9f569b9b92599a375c207494d5deb89
115,960
import hashlib def create_checksum(edi_message: str) -> str: """ Creates a SHA-256 checksum for an EDI message. :param edi_message: The input EDI message :returns: The SHA-256 checksum as a hex digest """ return hashlib.sha256(edi_message.encode("utf-8")).hexdigest()
97f1273db531f827f58c34f466b62f1b90853a9f
115,967
def chinese_cycle(date): """Return 'cycle' element of a Chinese date, date.""" return date[0]
0734a1062e81ffd661b9fe3cb12bdbcd34a793be
115,974
def modified_from_status(status_out): """ Return a generator of modified files from git status output. The output is expected to be in the format returned by ``git status --porcelain`` """ stripped = (ln.strip() for ln in status_out.split('\n')) modded = (ln for ln in stripped if ln.startswith(...
b9675be71388b76753cf530d9f1e3aed98d05505
115,977
def get_op_bbox(frame): """ Arguments: frame: dictionary of joint indices to normalized coords [x, y, conf]. ie {0: [.5, .5, .98]} Returns: 4 normalized bounding box coordinates x1, x2, y1, y2 """ x1 = 1 x2 = 0 y1 = 1 y2 = 0 for key in frame: joint = frame[ke...
0e60225f29e7cf8da44f206b62dd4e9fbc913515
115,978
def truncate_float(value, digits_after_point=2): """ Truncate long float numbers >>> truncate_float(1.1477784, 2) 1.14 """ pow_10 = 10 ** digits_after_point return (float(int(value * pow_10))) / pow_10
aad8c20e94b45b916629a43b19bd7b72b8b2612a
115,980
def score_n1(matrix, matrix_size): """\ Implements the penalty score feature 1. ISO/IEC 18004:2015(E) -- 7.8.3 Evaluation of data masking results - Table 11 (page 54) ============================================ ======================== ====== Feature Ev...
09f2140db4684f53793e94c8aa93f40e3c3eebb9
115,982
def anything(_): """ This predicate will always return True, and thus matches anything. :param _: The argument, which is ignored. :return: True """ return True
a15774a645f32ca22bc285054f41f3b0997db4d6
115,983
from typing import Sequence import string def int_to_base( n: int, base: int, numerals: Sequence[str] = '0123456789' + string.ascii_lowercase, ) -> str: """Forms a string representation of a non-negative integer in a given base. Args: n: A non-negative integer value. base: The bas...
75b2f7fc0d5b897444bbb397dab93730ef907889
115,985
def module_index(pmt_index): """Returns the module number given the 0-indexed pmt number""" return pmt_index//19
bc7b608aa26ec2f1ff2f26e9cc3be2f7b8f25e99
115,987
def combine(*projectors): """ Given a list of projectors as *args, return another projector which calls each projector in turn and merges the resulting dictionaries. """ def combined(instance): result = {} for projector in projectors: projection = projector(instance) ...
88e46c3bfef9822094b612be7664cadf2fa185c5
115,997
def RGBtoRGBW(R, G, B): """ convert RGB to RGBW color :param R: red value (0;255) :param G: green value (0;255) :param B: blue value (0;255) :return: RGBW tuple (0;255) """ W = min(R, G, B) R -= W G -= W B -= W return R, G, B, W
83fe3702ab1bbcf0aa7d2d61606aee9fa28aa023
115,999
def _set_iraf_section(section_list): """ Convert python list containing section information into string using IRAF syntax """ assert len(section_list) == 4 [y1, y2, x1, x2] = section_list y1 += 1 x1 += 1 return "[{:d}:{:d},{:d}:{:d}]".format(x1, x2, y1, y2)
280aac1a94f6980f3b9ab83fd4274ff29543b34e
116,000
def name_from_path(path): """Returns name of a module given its path, i.e. strips '.py' """ return path[0:-3]
ec0decc3c62e50435c33b99420ce2cde7343d26d
116,006
def resort_list(liste, idx_list, n_x): """ Make sure list is in the same order as some index_variable. Parameters ---------- liste : List of lists. idx_list : List with indices as finished by multiprocessing. n_x : Int. Number of observations. Returns ------- weights : As above...
5ca6b802253e0a56d18c19a5f7f728e3bca6d371
116,007
def status2str(num): """ Return YubiHSM response status code as string. """ known = {0x80: 'YSM_STATUS_OK', 0x81: 'YSM_KEY_HANDLE_INVALID', 0x82: 'YSM_AEAD_INVALID', 0x83: 'YSM_OTP_INVALID', 0x84: 'YSM_OTP_REPLAY', 0x85: 'YSM_ID_DUPLICATE', ...
e67acae9598eed69e8b5f073b4eed081b6d434ea
116,009
def grab_genius(author, song, genius): """ Grabs the lyrics from genius of a given song Parameters ---------- author : String Name of the author song : String Name of the song genius : Genius Genius access to API Returns ------- String The lyri...
df0ff070e3e66a77879a2fe26798cc9e4698653c
116,012
def _partition(M): """Evenly partition a matrix into 4 blocks (2-by-2). """ block_size = M.shape[0] // 2 M_11 = M[: block_size, : block_size] M_12 = M[: block_size, block_size :] M_21 = M[block_size :, : block_size] M_22 = M[block_size :, block_size :] return (M_11, M_12, M_21, M_22)
5cfec5686fa5c0e30b5e5e36e8ee539e94193996
116,014
def mk_task_map(task, qualified=True): """returns a map of information about the given task function. when `qualified` is `False`, the path to the task is truncated to just the task name""" path = "%s.%s" % (task.__module__.split('.')[-1], task.__name__) unqualified_path = task.__name__ description ...
0d05d1a6cd1589185b594686b39c371f6c37b120
116,015
import time def _time_left(stime, timeout): """ Return time remaining since ``stime`` before given ``timeout``. This function assists determining the value of ``timeout`` for class method :meth:`~.Terminal.kbhit` and similar functions. :arg float stime: starting time for measurement :arg flo...
c14ddf228f24f4fa68bf636abfff8636007743e4
116,019
def GetMappingsForTesterKeyName(user): """Returns a str used to uniquely identify mappings for a given user..""" return 'RunTesterMap_Tester_%s' % str(user.user_id())
00173c8ba30174748e04fd405ec9819ebc9817b1
116,022
import re def curlify(content: str) -> str: """ Adds a pair of curly braces to the content. If the content already contains curly brackets, nothing will happen. Example: - curlify("Hello") returns "{Hello}". - curlify("{Hello}") returns "{Hello}". """ curlify_pattern = re.compile(r'^{.*}$...
a45b6805eb3250f74fea913478d93f49e09b12cf
116,029
def infer_season_from_date(date): """ Looks at a date and infers the season based on that: Year-1 if month is Aug or before; returns year otherwise. :param date: str, YYYY-MM-DD :return: int, the season. 2007-08 would be 2007. """ season, month, day = [int(x) for x in date.split('-')] if m...
111fc42ac1771451551e22cd93687516bc6fd932
116,035
def rewrite_event_to_message(logger, name, event_dict): """ Rewrite the default structlog `event` to a `message`. """ event = event_dict.pop('event', None) if event is not None: event_dict['message'] = event return event_dict
c5a6e2222b08bb6309aea81136791d4a3b3eac1d
116,036
def rpartition(seq, n): """ Partition sequence in groups of n starting from the end of sequence. """ seq = list(seq) out = [] while seq: new = [] for _ in range(n): if not seq: break new.append(seq.pop()) out.append(new[::-1]) r...
c6a973f87139067e58dbfa2bf782f813dd67a243
116,043
def PyObject_Call(space, w_obj, w_args, w_kw): """ Call a callable Python object, with arguments given by the tuple args, and named arguments given by the dictionary kw. If no named arguments are needed, kw may be NULL. args must not be NULL, use an empty tuple if no arguments are needed. Returns th...
b7139b67477bd09fc6039ca3b1af1dc16c3c28ac
116,044
def expected_workload(L,p): """ Return expected number of votes that need to be counted. L = input list of precincts: (size,name) pairs. p = input list of auditing probabilities. """ return sum([p[i]*L[i][0] for i in range(len(L))])
33434476c95780660ccef05d1de3f30ee429ffdd
116,045
def name2community(name): """ Given the string name of a community, recover the community. """ return str(name).split()
e2509aadcad4db6030de53342fe20d6dfb2ee3a9
116,047
import torch from typing import Tuple def colorize_noise(img: torch.Tensor, color_min: Tuple[int, int, int] = (-255, -255, -255), color_max: Tuple[int, int, int] = (255, 255, 255), p: float = 1) -> torch.Tensor: """ Colorizes given noise images by asserting random color values to pixels tha...
2c1c8593e6dc4ee1eb3a3f4b1326bfb8e089b108
116,048
def is_java_ref(S): # @UnusedVariable """ Return True is S looks like a reference to a java class or package in a class file. """ return False
7b05387c367e02dd448664ab6d918e69cdd9d25d
116,052
def rect2poly(ll, ur): """ Convert rectangle defined by lower left/upper right to a closed polygon representation. """ x0, y0 = ll x1, y1 = ur return [ [x0, y0], [x0, y1], [x1, y1], [x1, y0], [x0, y0] ]
b0e63db99ac9f5ab5c9f27041a43d592bbe186a9
116,056
def compareRecord(recA , recB, attr_comp_list): """Generate the similarity vector for the given record pair by comparing attribute values according to the comparison function and attribute numbers in the given attribute comparison list. Parameter Description: recA : List of first reco...
79e7ad8b2d8e248f24ded9ce9264a9784e963476
116,057
def get_id_numbers(data, endpoint): """Return a list of the specified endpoint's primary id numbers.""" ids = set() id_field = '{0:s}_id'.format(endpoint) for rec in data: ids.add(rec.get(id_field)) return list(ids)
337d988f4c8831d24d570c8b5480cb4e289fcd28
116,060
def nth_root(x, n): """Finds the nearest integer root of a number.""" upper = 1 while upper ** n <= x: upper *= 2 mid, lower = None, upper // 2 while lower != upper: mid = (lower + upper) // 2 mid_n = mid ** n if lower < mid and mid_n < x: lower = mid ...
30ffc4f06104e9dc12c4a125afb4cd2c66b599bd
116,066
def product(iterable): """ Calculate the product of the elements of an iterable """ res = 1 for x in iterable: res *= x return res
af8133cc42ee6527a06602bd7b0e742fdfabeb41
116,068
import re def get_auth_header_values(header_string): """ Returns a dict mapping the header keys to their values """ # Get the header key and value (value matches any non-quote contained in quotes) reg = re.compile(r'(\w+)="([^"]+)"') return dict(reg.findall(header_string))
8e9b49fdfaa37f44cbdf0725536cb1f9f787eb6e
116,071
def count_var_match(var_names, relation): """ Count the number of common variables between agt_vars and the dimensions or relation. :param var_names: a list of variable names :param relation: a relation object :return: the number of common variable """ match = 0 for v in relation.di...
24f450e2cfa8ee193d7e04b14621ac2c43b611bd
116,072
def get_virtuals_asm_policies(bigip): """ Returns a dict of policy_name --> virtual servers """ params = { '$select': 'name,virtualServers,manualVirtualServers', # '$filter': "attachedPoliciesReferences/link eq '*'", } url_base_asm = f'https://{bigip.ip}/mgmt/tm/asm/policies'...
7d17342039bd448bec36ad73c66a4a2914696567
116,073
def compare(context, object_field, raw_data, raw_field): """ Compare an object field value against the raw field value it should have come from. Args: context (str): The context of the comparison, used for printing error messages. object_field (Any): The value of the object field being comp...
55763de771dc977f39c57687d2f53336bc24cf14
116,077
import base64 def is_base64(text: bytes) -> bool: """Check if the string is base64. :param text: Text to check. :return: Whether it is base64. """ try: base64.decodebytes(text) except: return False return True
5557275ee22599ae6aa589d0a3c8af84021ddc6a
116,079
def format_query(query): """ Given query=" word1 word2 word3 Returns " word1 OR word2 OR word3" """ words = query.split() # print words text = "" for idx in range(len(words) - 1): text = text + words[idx] + " OR " text = text + words[-1] return text
04b00f6153057515ae5091d1210080f2be1be28a
116,084
import re def parse_thickness(filename): """ Parses an .opm file and returns the thickness if any. Args: filename: .opm file. Returns: Either half of the bilayer thickness or None if not present. """ thicknesses = [] with open(filename, "r") as fh: for line in fh:...
26e2a52ee09fe5d39ed61a74a13a30f3b8d7b4e6
116,089
def eh_posicao(p): """ Pretende descobrir se o argumento inserido e ou nao uma posicao de um tabuleiro. :param p: Um int, posicao de um tabuleiro (1 a 9). :return: Um bool, veracidade do argumento. """ if type(p) != int: return False elif not 1 <= p <= 9: # posicoes de 1 a 9 re...
4a37fc6ef2c6ea38ca0edeb41f1bc302fa73e644
116,092
def parse_behave_table(context_table): """Cast behave's table to a dict.""" return next( dict(zip(context_table.headings, row)) for row in context_table.rows )
3499dbdfb19d33fd1790e61e89a6da2c4132165d
116,093
def payoff_call(underlying, strike, gearing=1.0): """payoff_call Payoff of call option. :param float underlying: :param float strike: :param float gearing: Coefficient of this option. Default value is 1. :return: payoff call option. :rtype: float """ return gearing * max(underlying ...
e676c9c84f5e5406884cfd0000cdc9a8c5e59105
116,094
import random def fisherYatesShuffle(arr): """ https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle for i from n−1 downto 1 do j ← random integer such that 0 ≤ j ≤ i exchange a[j] and a[i] """ for i in range(len(arr)-1, 0, -1): j = random.randint(0, i) arr[i], arr[j...
979d5004f34600aa1b5977ac17a986c75b01dfa5
116,095
def nextmonth(yr, mo): """get next month from yr/mo pair""" return (yr+mo / 12, mo % 12+1)
149b203b7988980e1ab3f9ca02b3817874437a64
116,097
def hydraulic_resistance_coefficient(Eg, Re, ke, d): """ :param Eg: Coefficient of hydraulic efficiency. If no data: Eg=0.95 for pipelines with scraper system; Eg=0.92 for pipelines without scrapper system. Dimensionless :param Re: Reynolds number. Dimensionless :param ke: equivalent pipe roughness,...
d67c3feaf882b2e583491d30de5733ce11852324
116,099
def get_sigint_handler(client): """ Return a SIGINT handler for the provided SlippiCommClient object """ def handler(signum, stack): print("Caught SIGINT, stopping client") client.shutdown() exit(0) return handler
2f47c9d4030b91026f8d35d3a88450ca462284e2
116,102
import hashlib def hash_file(content: bytes) -> str: """ Create a hash from the given content """ sha1sum = hashlib.new("sha1") sha1sum.update(content) return sha1sum.hexdigest()
0c1f4bd63c578ff3f40b8ea8e407e9ab6abe98b1
116,106
def check_weights(nodes_with_a_weight): """ Ensure that the sum of the values is 1 :param nodes_with_a_weight: a list of Node objects with a weight attribute """ weights = [n['weight'] for n in nodes_with_a_weight] if abs(sum(weights) - 1.) > 1E-12: raise ValueError('The weights do not ...
d65a1b13e7f0b69b69ada731793184fd838e6e4b
116,110
def listify(list_or_value): """ Given a list or a value transforms it to a list Arguments: list_or_value (str or list): List or a value Returns: A list """ if isinstance(list_or_value, list): return list_or_value else: return [list_or_value]
a3d28b4d858e391987885dae3b733df6001745e2
116,117
def network_is_bogon(network): """ Returns if the passed ipaddress network is a bogon Arguments: - network <ipaddress.IPv4Network|ipaddress.IPv6Network> Return: - bool """ return not network.is_global or network.is_reserved
b729a6dcd907a833d4bdedf581e58b8b515f3e07
116,118
def _extrapolate_constant(to_time, from_sample): """Extrapolate a power rating to an earlier or later time. This models a constant power rating before (or after) the `from_sample` input to the `to_time`. It returns a power sample, of the same class as the `from_sample` but at the time specified in...
e16b488d90e39534ae2647b27740c92928bc2a40
116,119
import hashlib def sha256d(data): """Compute the Double SHA-256 hash.""" sha = hashlib.sha256(data).digest() return hashlib.sha256(sha).digest()
f7693652de1b6c9f300fa2c14f7ee92861d69f02
116,120
def get_lr_metric(optimizer): """ Function for returning the learning rate in the keras model.fit history, as if it were a metric. :param optimizer: a tensorflow optimizer instances :return: float32, the learning rate """ def lr(y_true, y_pred): # return optimizer._decayed_lr(tf.float32...
c382d5b536907f8e36afd13419a2916ae877704f
116,126
def get_items(obj): """Get the items of a dict-like or list-like object.""" if hasattr(obj, 'items'): items = obj.items() else: items = enumerate(obj) return items
7a1b9c702915b4e9f8c5fe506de12e6b3e2dab58
116,132
def chk_pfx( msg, p ): """check if msg content contains the given prefix""" return msg[:len(p)] == p
b031ff7765502c52fc8e27e791fe7078b874c911
116,133
from typing import OrderedDict def commits_diff_between_branches(base, divergent, repo): """ Get the commits in branch `divergent` that are not in `base`. :param base: :param divergent: :param repo: :return: an `OrderedDict whose keys are the sha1 of the commits and values ...
c6cd08910422c053586c783a2ecef4e4bfbe304f
116,137
import math def miter_butt(points, width, weights, shifts, nib=None): """Represent weighted data points via varying linewidth. Parameters ---------- points : list of 2-tuple Vertices of linear spline. width : float Overall linewidth scaling factor. weights : list of float ...
f955e58af33b22122dff1ed3def9cc057b258b4b
116,140
def _vv(vec1, vec2): """ Computes the inner product ``< vec1 | vec 2 >``. """ return (vec1[..., None, :] @ vec2[..., None])[..., 0, 0]
186f9f1cb56ab753557c66ec0b42e589aa3f85e2
116,142
def _key(oid): """Create a key for an OID. Args: oid: SNMP OID Returns: result: Key value """ # Initialize key variables result = '' limit = 8 table = { '.1.3.6.1.2.1.2.2.1.1': 'ifIndex', '.1.3.6.1.2.1.2.2.1.10': 'ifInOctets', '.1.3.6.1.2.1.2.2....
bbde372e38990b57c6106ae52437e0028b4c0649
116,143
def compute_zT(rho, seebeck, kappa, temperature): """Returns the thermoelectric figure of merit. Note: All inputs should have SI units. """ return seebeck ** 2 * temperature / (rho * kappa)
035dd75573f4fc5b9927699e10533de244f43054
116,146
def prettify(soup): """ Prettify HTML source. The HTML source is in a soup object. The return value is a string! """ return soup.prettify()
a12ac0fcbf854ab327375f20a3039ec5da9a55d8
116,150
from datetime import datetime def read_log_file(path): """ Parse a LabView log file and return a dictionary of the parameters. Parses the text of a file line-by-line according to how they're written. Several values present in only newer log files are attempted and excepted as None. Failure to parse o...
b9f060d4392267ef5862dd4ff44ea8a62be203ef
116,152
import hashlib def get_sha1_sums(file_bytes): """ Hashes bytes with the SHA-1 algorithm """ return hashlib.sha1(file_bytes).hexdigest()
c2dd9ea4875a8dbd8fa7d554530b1c6c4aef4eac
116,153
def normalize(prices): """Normalize pandas DataFrame by divide by first row""" return prices / prices.iloc[0]
29bad57437372eb72fd227620fda93f48244f741
116,159
import itertools def pairwise(iterable): """This function is used to create pairwise pairs for the input iterable. An example is given below.""" # pairwise('ABCDEFG') --> AB BC CD DE EF FG a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
613bbc69fada73e9c13417f5d6a92227a109c982
116,161
def bytes_to_mac(addr_bytes): """Convert address bytes to MAC.""" return ":".join(f"{b:02x}" for b in reversed(addr_bytes))
52d12d48ce581b72aab83482b614230473a6a5ad
116,163
def check_fields(fields, args): """Check that every field given in fields is included in args.args. - fields (tuple): fieldes to be searched in args - args (dict): dictionary whose keys will be checked against fields """ for field in fields: if field not in args: return False ...
fa6558ef9fdd1cba4c9f0a46b6e910ecbba9a6b4
116,164
import csv def lodict2csv(listofdicts, out, fnames=None, header=True): """ Write a dictionary list with csv formatting to the stream out. :param fnames: when provided as a list, it is used as the column selection, otherwise all keys occuring at least once are used. :param header: s...
228936ae84b6977504573376895070f96c986a9a
116,169
import ast def get_full_scope(series): """Get a string of all the words in scope including the cue, in order. """ idx_1 = ast.literal_eval(series["scopes_idx"]) idx_2 = ast.literal_eval(series["cues_idx"]) scope = " ".join([s for i1, i2, s in zip(idx_1, idx_2, series["sent"].split(" ")) if i1 or i2]) ...
d4178faf6a1b90b25934b6f4610573cdc98a1877
116,180
def get_tr1(name): """In libstd++ the tr1 namespace needs special care. Return either an empty string or tr1::, useful for appending to search patterns. Args: name (str): the name of the declaration Returns: str: an empty string or "tr1::" """ tr1 = "" if "tr1" in name...
c44d1f2830fb0f0ee6fcfeda331a46868676363c
116,181
def parse_line(line): """ Parses a log line and returns its components :param line: :return: tuple """ addr, insn, insnty, val, flow = "", "", "", "", "" parts = line.rstrip().split(" | ") if len(parts) == 5: addr, insn, insnty, val, flow = parts elif len(parts) == 4: ...
a611f5b483495b2230c615e8adb845e0a16548d7
116,185
def parse_pmofn_qr_part(data): """Parses the QR as a P M-of-N part, extracting the part's content, index, and total""" of_index = data.index("of") space_index = data.index(" ") part_index = int(data[1:of_index]) part_total = int(data[of_index + 2 : space_index]) return data[space_index + 1 :], p...
e682731bf471017eed6d22d6bb5bf36af258c963
116,187
def crop(img): """Returns a cropped image to pre-defined shape.""" return img[75:275, 125:425]
571ca0f44637dbd4eabc903d643fcaf346c34df9
116,188