content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def column_to_list(data, index): """Transforma uma coluna da lista de linhas em uma list. INPUT: data: list de linhas que serão filtradas pela coluna index, ex: { 'foo1', 'bar1', 'foo11' ,'bar11'} { 'foo2', 'bar2', 'foo22' ,'bar22'} { 'foo3', 'bar3', 'foo33' ,'bar33'} index: posiçao ...
8d6b9e37fe056ba794103c242f18f811c8f866ae
671,492
from typing import List from typing import Callable def _calculate_forces(r: List[float], force_function: Callable, force_coefficients: List[float] ) -> List[float]: """Calculate the forces on each particle""" forces = [] ...
f6ae192ae7ce0266c11d03d618be2651bbf08b91
671,493
import random def point_swap(chrom1, chrom2): """Swaps genes between two points in an input and output chromosone""" swap_pos = random.randint(0, 6) # Randomly picks pos to swap at return chrom1[swap_pos:] + chrom2[:swap_pos]
1b8cbff6dce1c3ddfb0a9f837f9fda96e6c2cec0
671,494
def rk4(ode, x, u, h): """ rk4 Runge-Kutta-4 Integrator :param ode: differential equation :param x: State :param u: Controls(zero order hold) :param h: step size :return: next state after integration """ k1 = ode(x, u) k2 = ode(x + (h / 2.0) * k1, u) k3 = ode(x + (h / 2.0) *...
33c9e7984ac94197636d4c272479fcc63de15209
671,496
def owner_name(): """Returns the name of the site owner.""" return '<dz:owner_name>'
b59d379c3db12bf5f6f3ad297ac35ef72fe3a487
671,497
def another_func(): """ more diff text """ a = 2 b = 3 return a + b
5f09316149818ee7ac20d61ca5291804f1dea3b7
671,498
import socket import pickle def getServerInfo(ip: str, modelName: str, dataGroupName: str): """ 获取模型信息及数据库信息 """ address = (ip, 11451) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client.connect(address) client.sendall(b'555') data = client.recv(8) ...
23822f1ef258464ccbcf19bc4cbc3f2e5c70137b
671,499
def kwarg_parser(func, kwargs): """Utility function for parsing keyword arguments""" func_kwargs = dict() args = func.__code__.co_varnames for arg in args: if arg in kwargs: func_kwargs[arg] = kwargs.pop(arg) return func_kwargs, kwargs
fd6f68da844dcc25048ca551167626222facedf3
671,501
import argparse def parse_args(): """Parse args from command line. Returns: args object. """ parser = argparse.ArgumentParser(description="Run cornac model..") # If the following settings are specified with command line, # these settings will be updated. parser.add_argument( ...
89a0489f72a478e8bfc9dac1f352ff5a132e4c07
671,503
def points_phones(phones): """ Retrieve all phones which have points payment avaiable :param: list of phones """ lista = [] for phone in phones: if phone['pontos'] == 'Disponível': lista.append(phone) return lista
0bb6e36873cb640ae6c7e972eed0bd4fe9e9e319
671,504
def list_to_id_dict(base, attribute): """ Return a dict from an attribute in a list of dicts. """ ret = {} for d in base: ret[d[attribute]] = d return ret
4aa4686b273591984f08c91de6b8a9ec6fda9ffd
671,505
def detect_repeat_frauders(form_df, threshold=0.8): """ Detect the fraudulous workers i.e. the one who repeated the same word too many times """ form_df = form_df.copy() columns = [col for col in form_df.columns if col not in [ "Timestamp", "WorkerID"]] form_df["vocsize"] = form_df[colum...
b6ddcfba80b7dd1db0c0bb64d3df9ae004543116
671,506
def nth_replace(string, old, new, n=1, option='only nth'): # https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string """ This function replaces occurrences of string 'old' with string 'new'. There are three types of replacement of string 'old': 1) 'only nth' repla...
eedc655af4d2e10a1db755a5c8d0fbde2879ab64
671,507
def translate_inequality(param_name): """ Replace GT or LT at the end of a param name by '>' or '<' to achieve Twilio-like inequalities. """ for suffix, replacement in (('GT', '>'), ('LT', '<')): if param_name.endswith(suffix): return param_name[:-len(suffix)] + replacement ...
71594fedf9bd7e95607de61152ddd5cd931c3d25
671,508
def filterTimeSeriesData( filterFunc, featureTimeList, windowSize, index, useEdgePadding ): """ Filter time-stamped data values within a window filterFunc could be medianFilter() or znormFilter() It's ok to have other values in the list. eg featureTimeList: [(time_0, .., featureA_0, ..), ...
f8f71f82b9f7efbfb809ca3335079040fb2f991c
671,509
def item_order(node): """ Extracts item order value from a project tree node. :param Node node: project tree node. :return: item order value or -1 if not present. :rtype: int """ return node.item.order if node.item.order else -1
d5094f505d1b69ec09a2279f86f3b0b382cff439
671,510
import math def RayleighNumber(g, alpha, deltaT, nu, kappa, H): """ Calculate the Rayleigh number: Ra = g alpha delta T H^3 ------------------- nu kappa """ return (g * alpha * deltaT * math.pow(H, 3.0)) / (nu * kappa)
d3e609b40ffdd8458dd3306f73b6d38c53f556a8
671,511
def ex_sync(): """ sync { begin writeln("#1 line."); begin writeln("#2 line."); begin writeln("#3 line."); begin writeln("#4 line."); begin writeln("#5 line."); } """ return None
6f74792135cc21205af262506ece79ba1bf5d122
671,512
import typing import warnings def format_timestamp(ts: typing.Union[int, float]) -> str: """ Function for formatting start/end timestamps. Somewhat more condensed than the standard Pandas formatting. :param ts: The timestamps in microseconds. Rendered as integers, since `idelib` times...
0b4ea26210b79a87cb49642f74a459961f761bbf
671,513
def hex_to_int(color): """ :hex_to_int: converts a string hexadecimal rgb code to a tuple rgb code consisting or integer values for each channel. :param color: string | hex code for a color (does not include the hashtag) :return: (r, g, b) | a tuple rgb code in integer form ...
f02ffca88cec926b530caa0fc20fc614dc4376a9
671,514
def analyze_text(text): """Analyze the given text for the frequencies of its characters.""" # Initialize Dictionary frequencies = {} count = 0 for c in text: c = c.lower() if c in frequencies: frequencies[c] += 1 else: frequencies[c] = 1 coun...
d7312446fe27e8bb7ff6577e94271491d11e3cd9
671,515
from typing import Any from typing import Union from typing import List from typing import Dict def get_level_lengths( levels: Any, sentinel: Union[bool, object, str] = "" ) -> List[Dict[int, int]]: """For each index in each level the function returns lengths of indexes. Parameters ---------- lev...
0e19b8eea448fa75b5aefc0e892690b32c11c027
671,516
import os def write_parameters_file(problem_file, params, working_path): """ Write the parameters file used by the `lkh_solver` node to solve a TSP instance. Parameters ---------- problem_file: str Path to the problem file (`.tsp` file) params: SolverParameters Parameters to be pased to the LKH...
fada2f7f59a4e45f715669197a05342b3b2ddeea
671,518
from typing import Dict from typing import Any def _generate_delete_response_with_errors(num_rows=1) -> Dict[str, Any]: """Generates a Content API delete response with errors. Args: num_rows: The number of rows to generate. Returns: A Content API response with errors (item not found). """ response...
6f7a2d56a46abf06101bd5c094b2f874a8618e51
671,519
import os def get_location(base_dir, location_file, location_line): """ Generates location that PyCharm resolves to file :param base_dir: base directory to resolve relative path against :param location_file: path to file :param location_line: line number """ my_file = str(location_file).ls...
d3303234130b14fd38dbd17ae5fcfd22df889a50
671,520
def two_sum(nums, target): """ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.""" '''# Brute force O(n^2). for i in range(len(nu...
46fcccfd4cb56c0449fd9a6125e6dcfb1e725500
671,521
import re def osFindValue(obj, searchTerm, searchMethod): """Internal helper method! Generic search method to search a string or int for a searchTerm. Different search methods can be provided for different ways of searching. Args: obj (str|int): The object that is being searched in se...
54a9008fdfcb78cc256c4d5c95cf097573e8ae36
671,522
def calc_auc(raw_arr): """Summary Args: raw_arr (TYPE): Description Returns: TYPE: Description """ # sort by pred value, from small to big arr = sorted(raw_arr, key=lambda d: d[2]) auc = 0.0 fp1, tp1, fp2, tp2 = 0.0, 0.0, 0.0, 0.0 for record in arr: fp2 += re...
6ca6cfc8e63f974eb40d9a6abbb3838962505abd
671,523
def round_to_nearest_increment(x :float, tick_size : float = 0.25) -> float: """ rounds a price value to the nearest increment of `tick_size` Parameters ----------- x : float the price value tick_size: float the size of the tick. E.G. for ES = 0.25, for CL = 0.01 """ val = round(tick_size * r...
be4a51e5a8fa0d23fcce4f6b8d4f47494d0c9c07
671,524
def input_size_needed(output_size, num_layers): """Utility function to compute image size for a given U-Net output The U-Net crops some border of the image during prediction, it can be tedious to check if an input size is valid output_size: width/height of the output image num_layer: number of layers ...
fe084b12028ea9e22e3a1a8aefe40c85d4bf7357
671,525
def prob4(A): """Make a copy of 'A' and set all negative entries of the copy to 0. Return the copy. Example: >>> A = np.array([-3,-1,3]) >>> prob4(A) array([0, 0, 3]) """ B = A.copy() B[A < 0] = 0 return B
d4ae66b35d2061ab4c1981cc9d9e7fdd7cb14061
671,526
def calcSlope(y1, y2, x1, x2): """ Calculate slope between two points """ if x2-x1 == 0: slope = 0 else: slope = (y2 - y1) / (x2 - x1) return slope
e55b393512dcdd4fa193f0fc99fc1106d965a8b5
671,527
import uuid def unique_instance_id(): """Creates a unique id for the database.""" return f"test-instance-{uuid.uuid4().hex[:10]}"
053bb86e91d1afdc6e5e4f4831e27de2046212eb
671,528
import hashlib def compute_md5(filepath) -> str: """Compute the md5 hash for a file at `filepath`. Args: filepath: The path to the file """ with open(filepath, 'rb') as f: # pylint: disable=invalid-name hash_str = hashlib.md5(f.read()).hexdigest() return hash_str
e3ff96cc99b68cdca2a4897161c5c4f46b56fcb5
671,529
def generate_gcp_project_link(project_id: str) -> str: """Generates a Slack markdown GCP link from the given `project_id`. Args: project_id: The project ID of which to hyperlink. Returns: The generated hyperlink. """ return ('<https://console.cloud.google.com/home/' + ...
756575347a1b69d9c230fd58a20cbbfc9c7cd3e2
671,531
def banner_command(argv): """Return sanitized command-line description. |argv| must be a list of command-line parameters, e.g. sys.argv. Return a string corresponding to the command, with platform-specific paths removed.""" # Remove path from first parameter argv = argv[:] argv[0] ...
a0a384e00f5b4ad3b59b76c32e8fc761552461a4
671,532
import torch def add_time(in_tensor, t): """ Add one more dimension to the end of the input tnesor :param in_tensor: input :param t: time :return: concatenated tensor """ bs, c, w, h = in_tensor.shape return torch.cat((in_tensor, t.expand(bs, 1, w, h)), dim=1)
21d69880cbce54c74cb4a6a84846e71a9f383889
671,533
import platform def os_is_windows(): """ Checks if the os is windows :return: True is windows :rtype: bool """ return platform.system() == "Windows"
e563ef27205753863b4b20663ed3a1b363bdd5a7
671,536
import json def load_json(fpath): """ Load a file from json Args: fpath (string or pathlib.Path object): Path to a json file Returns: python object parsed from json """ with open(fpath, "r") as infile: return json.load(infile)
4b294be5bd76a0d47a792a90ee5c00d71de9e604
671,537
def description(trigger): """ Substitute some important macros, namely `{HOST.NAME}`. """ s = trigger.description.val if trigger.hosts: s = s.replace('{HOST.NAME}', ', '.join(i.text for i in trigger.hosts)) return s
b6116f953d1984e3ebee819af25a28a790a9e98c
671,538
def to_string(text, encoding='utf8', errors='strict'): """Convert a string (bytestring in `encoding` or unicode), to unicode.""" if isinstance(text, str): return text return str(text, encoding, errors=errors)
af3937b434f7458086fd7734a45ef67b006c9e9f
671,539
import struct def parse_task_packet(packet, offset=0): """ Parse a result packet- [2 bytes] - type [2 bytes] - total # of packets [2 bytes] - packet # [2 bytes] - task/result ID [4 bytes] - length [X...] - result data +------+--------------------+--...
097e5975fdedfc2eefa3d33b66c15b51f3f82d21
671,540
def slope(first_point, second_point): """ Returns the slope between 2 points :param first_point: first point (x,y) :param second_point: second point (x,y) :return: the slope """ return 0. if first_point[0] == second_point[0] else\ ((float(first_point[1]) - float(second_point[1])) / ...
8b8738af96279a112cc0cf01591d8d7bf5de429b
671,541
def get_amount(message): """Get the amount of money from a message""" allowed = "()[]{}+-*/^0123456789." expression, hide = [], 0 for token in message.content: if token == '<': hide += 1 if hide == 0 and token in allowed: if token == '^': token =...
1b8e2ef26a22597861b1eec14ba7b7e89007a4c8
671,542
def trim_traces(traces): """ Trim traces to the same length :param traces: :return: """ max_start_time = max([x.stats.starttime for x in traces]) min_end_time = min([x.stats.endtime for x in traces]) trimmed = [x.slice(max_start_time, min_end_time) for x in traces] return trimmed
5a50743239e077269800c72aabd284e8d778d8ac
671,543
def calc_error(data, reference=None): """Calculate the error against a reference.""" if reference is None: return None error = data - reference error.metadata = data.metadata name = data.long_name if name is None: name = data.name() error.long_name = '{} error'.format(name) ...
11dde5c6f61973bc9e996db7da326e354519e66d
671,544
from typing import Optional import sys def read_from_stdin_buffer() -> Optional[str]: """ read from buffer if stdin file descriptor is open, otherwise return empty string """ if sys.stdin.isatty(): return None return sys.stdin.buffer.read().decode("utf-8") or None
3b7b1b249293b44657bcca4172a10f58aafd3657
671,545
def stateLabel(s, state_type): """Returns the short-hand label of the state. Parameters: s (State): a State object. state_type (string): either 'e' or 'g' for excited state or ground state. The ground state is primed. Returns: string: "J=...
30b65e12bcec505539f148b339e37a91a14222d0
671,547
import sys def import_module(import_str): """Import a module.""" __import__(import_str) return sys.modules[import_str]
7b62ef72f99b0f598468e131f1e44f19674a9ce0
671,548
def context() -> dict: """ Returns @context of the jsonld. :return: """ context = { "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "owl": "http://www.w3.org/2002/07/owl#", "xsd": "https://www.w3.org/TR/xmlschema-2/#", "defines": { "@reverse": "http://www...
ff25842b7d9c638a7a37f4950ab6d037842687b2
671,549
import numpy def tensorquad(x,wx,y,wy): """Combine two quadrules in the x and y direction into a 2D tensor rule""" nx=len(x) ny=len(y) m=numpy.mgrid[0:nx,0:ny].reshape(2,-1) x2=numpy.vstack((x[m[0]],y[m[1]])) w2=wx[m[0]]*wy[m[1]] return x2,w2
beb4b5ff6d45c456c4f39dde85c40e7f008fc353
671,550
def is_void(line): """Test if it is a void line""" for i in line: if i!=' ' and i!='\t' and i!='\n': return False return True
839da53b6068dbcf2f082ae78a13045b74221bf0
671,551
def nested_lookup(n, idexs): """Function to fetch a nested sublist given its nested indices. Parameters ---------- n: list, the main list in which to look for the sublist idexs: list, the indices of the sublist Returns ------- list: sublist with given indices """...
ba4927e749be979fa297384fa9345db78243fa93
671,552
import re def compare_formulas(formulas, charges=[]): """ compares formulas :param charges: charges of molecules as list of integers :param charge_hydrogen_balance_accepted: boolean, that indecates, wether differences in the number of H atoms are accepted, if the difference is accounted for in the...
b8f198b88198b78f7fd6ce59a1b6606c20290815
671,553
from typing import Any from typing import TypeGuard import numbers def is_integer(x: Any) -> TypeGuard[int]: """Return true if x is an integer.""" return isinstance(x, numbers.Integral) and not isinstance(x, bool)
98af5e48e0418605668159b3fdbd3dd45bbaaade
671,554
import os def find_executable(executable, path=None): """Finds a location of an executable in the locations listed in 'path' :param executable File to search. :type executable string :param path Lookup directories separated by a path s...
de84fd8f932d2610da480d68805dc5f9c858da6b
671,556
def nodes_test_in_train(nodes_list, index): """ Given list of nodes for each time stamp and an index separating between train and test examples, return the nodes in the test set that are also in the training set. :param nodes_list: List of lists of nodes for each time stamp. :param index: Index indi...
d115bd782cb758954c55471b6d244b7f97944101
671,557
from typing import Pattern import re def _compile_re(pattern: str, dotall: bool = False) -> Pattern[str]: """Compile regular expression.""" flags = re.IGNORECASE | re.MULTILINE | re.VERBOSE if dotall: flags |= re.DOTALL return re.compile(pattern, flags)
a16b7741fd625cf1d1d60f6a13dfb0180de88d2a
671,558
import os import subprocess import re def get_target_modules(): """ If the `MODULE_NAME` and `MODULE_VERSION(S)` are specified, calculate the target modules from those env vars. Otherwise, calculate target modules based on changed files from the main branch. """ modules = [] if "MODULE_NAME" i...
dff261f585e62ab95c220d093ed8612c65b25a10
671,559
import os def get_directory_name(path): """ Gets the directory name in the given path. :param str path: the path (can be a file). :rtype: str :return: the directory name in the given path. """ return os.path.basename(os.path.dirname(path))
d99b48f4679afd2f40fcdd77a28875c8f99bceb0
671,562
def is_tied(board): """Checks if there are no moves left to be played""" return all(value != 0 for value in board.values())
474565b347c39718582fa31215174958e1907c99
671,563
from typing import List def error_detail(error: Exception) -> List[str]: """Convert an Exception to API representation.""" return [type(error).__name__] + [str(a) for a in error.args]
c9b5e117ef7f6effc0f78b3f0f860f33f5ca9a34
671,564
def retrieve_pendulum_data(filename = "pendulum.dat"): """ Gets pendulum data from filename and outputs a 2d list of output[0] = L and output[1] = T """ L_list = [] T_list = [] with open(filename, 'r') as infile: for line in infile: data = line.split() try: ...
8d8fdc0e7cb042881e6d1be5b2453985cf8a9481
671,565
def element_wise_list_division(numerator, denominator): """ Simple function to find the quotients of two lists. """ return [num / den for num, den in zip(numerator, denominator)]
9cfd61048c23342b161a536b719a95d3795ea472
671,566
import time def time_elapsed(fun): """Function to be used as a decorator for measuring time elapsed.""" def wrapper(*args, **kwargs): t0 = time.time() fun(*args, **kwargs) print("\nTime elapsed = %s" % (time.time() - t0)) return wrapper
7aaad9d53a6c0ab3006f166a3100218a3389b6fa
671,567
async def fixture_test_uris(player): """Return the first three songs in the database to use in playlist tests.""" test_songs = ( await player.async_query("songs", "0", "3", "search:Beatles", "tags:u") )["titles_loop"] assert len(test_songs) == 3 test_uris = [i["url"] for i in test_songs] ...
b89c0b137cdcb69ce0c82f493c9819a9cab8f8f3
671,568
import os import shutil def calc_pi_callgrind_dot(data_dir, tmpdir): """Builds a temporary directory containing the calc-pi callgrind DOT file.""" gprof_dot_dir = os.path.join(data_dir, "gprof2dot-cpi") gprof_dot_file = os.path.join(gprof_dot_dir, "callgrind.dot.64042.0.1") shutil.copy(gprof_dot_file...
d7c9d98f1eaf798e7371c312464c4205a5b9b11e
671,569
def move_down(self, point): """ Moves down one line, attempting to maintain column position. """ eof_x, eof_y = self.view.rowcol(self.view.size()) x, y = self.view.rowcol(point) #print('row={} col={} eof_row={} eof_col={}'.format(x, y, eof_x, eof_y)) if x == eof_x: # The size is the ...
a0ac13c972dcf42b69dff9cc94a0bdc062d68d22
671,571
def selection_sort(lst: list) -> list: """This is a selection sort algorithm implementation Parameters ---------- lst: list The unsorted list Returns ------- list A sorted list in ascending order References ---------- https://en.wikipedia.org/wiki/Selec...
04875848f4dc412b8de2c2b703eef9e595262beb
671,572
def has_velocities(trajectory): """Check that velocities are defined for this trajectory.""" for point in trajectory.points: if len(point.velocities) != len(point.positions): return False return True
66480d1caa72024d8eb1ecda173dd9cd24b633f1
671,573
from typing import List from typing import Tuple import re def make_proj_stack(err_msg: str) -> List[Tuple[str,int]]: """extracts file path and line number from E0449 messages into a list""" e0449 = re.compile(r"error(?:\[E0449\])?\: unnecessary visibility qualifier(?:\n|\r\n)\s+--> ([\w\\/\.]+)\:(\d+)") ...
f8163caf4ae7562db1d81b8abe4ff3b78c344c70
671,574
def pyimpl_universe_getitem(universe, handle): """Implement `universe_getitem`.""" return universe.get(handle)
58cefe6da1c5761fa0f164a7d2e98f8135796c78
671,575
def create_data_tables_dict(): """Return a dictionary for storing data table information Returns a dictionary that can be used with 'add_data_table' and 'add_data_table_entry' to store information about a data table. It can be converted to JSON to be sent back to the data manager. """ d = ...
d1aa8f48b0a7abf485d9f9bd1ad53049850e125f
671,576
def indexing(itt, postpix, det=None): """ Some annoying book-keeping for instrument placement. Parameters ---------- itt : int postpix : int det : int, optional Returns ------- """ # Deal with single chip if det is not None: tt = 0 else: tt = itt ...
25b269baa738adbd369d2d4660198b0b0b3f24c0
671,578
def __Node_str(self): """Give node infos.""" s = '\tID: ' + str(self.id()) + \ ', Marker: ' + str(self.marker()) s += '\t' + str(self.pos()) + '\n' return s
3186a648271fb500311faec42713c58d35331f2b
671,579
def chunks(l, n): """ Yield successive n-sized chunks from l. """ out = [] lens = (len(l) / n) for i in range(0, lens): out.append(l[i * n:i * n + n]) out.append(l[lens * n:]) return out[:-1]
e3d6c7e16c390de1692aa9cb1d128b3fa9ee7850
671,580
def find_cols(defline, header_char='='): """ return a sorted list of (start, end) indexes into defline that are the beginning and ending indexes of column definitions based on a reStructuredText table header line. Note that this is a braindead simple version that only understands header_chars an...
b0219b3465deb40251428493fb5a60a21d849667
671,581
def frompct(x): """ Convert Percent values to Decimal fraction >>> frompct([1.0, 2.3, 80.0, -23.0, 100.0]) [0.01, 0.023, 0.8, -0.23, 1.0] """ return x / 100.0
29552d0f0fd1901ff28af0e6ea501f825d08935d
671,582
def flatten(seq): """ >>> flatten([1 , [2, 2], [2, [3, 3, 3]]]) [1, 2, 2, 2, 3, 3, 3] """ # flatten fonction from C:\Python26\Lib\compiler\ast.py, # compiler is deprecated in py2.6 l = [] for elt in seq: t = type(elt) if t is tuple or t is list or t is set: ...
a0db618aa2fca1077b13fa5d96314f327e91b56e
671,583
def _invalidates_cache(f): """ Decorator for rruleset methods which may invalidate the cached length. """ def inner_func(self, *args, **kwargs): rv = f(self, *args, **kwargs) self._invalidate_cache() return rv return inner_func
5275cb72470df4da16156ea7ce8f158f0fc9ad1b
671,584
def validate_distro_version(version, supported_versions): """ Return True if the version is valid. For Ubuntu, possible supported version values are of the form '12.04 (precise)' where either the number of the version name is acceptable. """ if version in supported_versions: return True...
b5eac0d459e3afeec186e7b0c502d9e54301837d
671,585
def clean(angr_answer): """ angr deals in byte strings, which are not always null-terminated, so clean things up a bit. """ # angr can return non-ascii characters into stdout; we don't want to decode # these, since we're assuming flags are ascii printable. return angr_answer.decode("utf-8", errors="ignore")
31ef1cef21bf381e6eecbb2857ca0d322c142b45
671,586
import math def calculate_ratio(numerator_pair, denominator_pair): """ Computes a derived estimate and its MOE for the ratio between the numerator and denominator arguments where the numerator does not represent a subset of the denominator. Args: numerator (list): a two-item sequence with...
e8ee12f562baefb486f1cb10c4158dab90abff9f
671,587
import socket def getHost(ip): """ This method returns the 'True Host' name for a given IP address """ try: data = socket.gethostbyaddr(ip) host = repr(data[0]) return host except Exception: # fail gracefully return False
daf26b2522fc01358a2d41bddd8c613bb96ff49a
671,588
def json(path, _pod): """Retrieves a json file from the pod.""" return _pod.read_json(path)
d5d62b698fee0ed62400c6a40cbe76cd7319ec96
671,589
import struct def ReadBulk(tbk_file,start,end,size,fmt): """ Readling multiple continious lines from .tbk. tbk_file: .tbk start: start index. end: end index. size: bytes fmt: f,s,c...,values of dtype_fmt. """ R=[] f=open(tbk_file,'rb') f.seek(start) while start <= end: ...
fb3a9089aca47b3222d07caca5d8eea264968d72
671,590
from typing import Callable from typing import Tuple from typing import Mapping from typing import Union def _find_one_tree(tree: dict, func: Callable, args: Tuple, kwargs: Mapping, ) -> Union[dict, None]: """ Find one item in the spe...
a279176b6ec28ca3dc00c5a5b65c708e0dbd9bb6
671,591
from datetime import datetime def str_date_to_date(date_from, date_to): """ Convert two dates in str format to date object Format: YYYYMMDD :param date_from: beginning of the interval :param date_to: end of the interval :return: from_date and to_date equivalent of given in date objects ""...
e4a8ae97e8af9fc3547f57b3671143c7da4a1de1
671,592
import itertools import re def apply_constraints(phash, size, nonalphanumeric): """ Fiddle with the password a bit after hashing it so that it will get through most website filters. We require one upper and lower case, one digit, and we look at the user's password to determine if there should be a...
2e2cd7be59853c4610df46ccb458ad37c4f59bfa
671,593
def rankAnomalousPoint(sampleErrors: list, rankingMap: dict) -> dict: """Adds a new list of sample errors to the majority voting map. Args: sampleErrors: A list of `(name, distance)` tuples. rankingMap: A mapping between counter names and vote count lists. Returns: A updated rankin...
8cac4fc4c83241a37bf6d7837e7006e846ed7744
671,594
import socket import logging def is_online(): """ Test if the system is online. This breaks when TFBS_footprinter3 outlasts Google. """ REMOTE_SERVER = "www.google.com" try: host = socket.gethostbyname(REMOTE_SERVER) s = socket.create_connection((host, 80), 2) return T...
9f8ad4d722e710a81fbf1cda02bfbb9e4885db70
671,595
def percentage(part, total): """ Calculate percentage. """ return (part / total) * 100
308fb6cdadf531942a2ce9524d6721247214f016
671,596
def listget(lst, ind, default=None): """ Returns `lst[ind]` if it exists, `default` otherwise. >>> listget(['a'], 0) 'a' >>> listget(['a'], 1) >>> listget(['a'], 1, 'b') 'b' """ if len(lst)-1 < ind: return default return lst[ind]
bfb88e6748b5a14e399783a7bf24777ec371b48d
671,597
def unquoteNS(ns): """Un-quotes a namespace from a URL-secure version.""" ns = ns.replace('_sl_', '/') ns = ns.replace('_co_', ':') return ns
9530cdc00baf54e6004202f893304b9b7c7cbaf2
671,598
def mergeObjectProperties(objectToMergeFrom, objectToMergeTo): """ Used to copy properties from one object to another if there isn't a naming conflict; """ for property in objectToMergeFrom.__dict__: #Check to make sure it can't be called... ie a method. #Also make sure the objectobjectT...
1490ddbfc805fda1e52663653e838c3714a8a766
671,600
def pre_process_data(linelist): """Empty Fields within ICD data point are changed from Null to 0""" for index in range(len(linelist)): if not linelist[index]: linelist[index] = '0' return linelist
93ac3380d2c915639cfde0e8be06e756169c3956
671,601
def _truncate_lines(infile, line, c): """Replace long sequences of single characters with a shorter version. """ if set(line) == set(c) and len(line) > 64: line = c * 64 return line
3e21f63d71788e45cadd1f7f5c57310a614eab02
671,602
def json_default(o): """ Defining the default behavior of conversion of a class to a JSON-able object. Essentially makes a dictionary out of the class and returns it. Returns a list of all its elements in case of a set. :param o: The object to convert to JSON. :return: JSON-able version of the c...
40322266415905f88602f18d68412c84f1c97a46
671,603
def safeEval(data, eval=eval): """A safe replacement for eval.""" return eval(data, {"__builtins__":{}}, {})
9db81446728cbc3bfe66f1e80cc6cb7d92831493
671,604
import requests def extra_metadata_helper(project_url, headers): """ Build extra metadata dict to help with other integrations. Parameters ---------- project_url: str The url to the project info headers: dict Figshare Authorization header Returns ------- Extra...
6e8e01988bace721d277f1ac8689441b1a7abe1c
671,605