_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
87
6.4k
title
stringclasses
1 value
language
stringclasses
1 value
meta_information
dict
d20401
test
def to_snake_case(text): """Convert to snake case. :param str text: :rtype: str :return: """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
PYTHON
{ "dummy_field": "" }
d20402
test
def println(msg): """ Convenience function to print messages on a single line in the terminal """ sys.stdout.write(msg) sys.stdout.flush() sys.stdout.write('\x08' * len(msg)) sys.stdout.flush()
PYTHON
{ "dummy_field": "" }
d20403
test
def force_iterable(f): """Will make any functions return an iterable objects by wrapping its result in a list.""" def wrapper(*args, **kwargs): r = f(*args, **kwargs) if hasattr(r, '__iter__'): return r else: return [r] return wrapper
PYTHON
{ "dummy_field": "" }
d20404
test
def _float_feature(value): """Wrapper for inserting float features into Example proto.""" if not isinstance(value, list): value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value))
PYTHON
{ "dummy_field": "" }
d20405
test
def _interval_to_bound_points(array): """ Helper function which returns an array with the Intervals' boundaries. """ array_boundaries = np.array([x.left for x in array]) array_boundaries = np.concatenate( (array_boundaries, np.array([array[-1].right]))) return array_boundaries
PYTHON
{ "dummy_field": "" }
d20406
test
def commajoin_as_strings(iterable): """ Join the given iterable with ',' """ return _(u',').join((six.text_type(i) for i in iterable))
PYTHON
{ "dummy_field": "" }
d20407
test
def checkbox_uncheck(self, force_check=False): """ Wrapper to uncheck a checkbox """ if self.get_attribute('checked'): self.click(force_click=force_check)
PYTHON
{ "dummy_field": "" }
d20408
test
def _requiredSize(shape, dtype): """ Determines the number of bytes required to store a NumPy array with the specified shape and datatype. """ return math.floor(np.prod(np.asarray(shape, dtype=np.uint64)) * np.dtype(dtype).itemsize)
PYTHON
{ "dummy_field": "" }
d20409
test
def csv_to_numpy(string_like, dtype=None): # type: (str) -> np.array """Convert a CSV object to a numpy array. Args: string_like (str): CSV string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. Returns: (np.array): numpy array """ stream = StringIO(string_like) return np.genfromtxt(stream, dtype=dtype, delimiter=',')
PYTHON
{ "dummy_field": "" }
d20410
test
def remove_elements(target, indices): """Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the future...""" copied = list(target) for index in reversed(indices): del copied[index] return copied
PYTHON
{ "dummy_field": "" }
d20411
test
def get_propety_by_name(pif, name): """Get a property by name""" warn("This method has been deprecated in favor of get_property_by_name") return next((x for x in pif.properties if x.name == name), None)
PYTHON
{ "dummy_field": "" }
d20412
test
def is_in(self, search_list, pair): """ If pair is in search_list, return the index. Otherwise return -1 """ index = -1 for nr, i in enumerate(search_list): if(np.all(i == pair)): return nr return index
PYTHON
{ "dummy_field": "" }
d20413
test
def _is_iterable(item): """ Checks if an item is iterable (list, tuple, generator), but not string """ return isinstance(item, collections.Iterable) and not isinstance(item, six.string_types)
PYTHON
{ "dummy_field": "" }
d20414
test
def get_from_gnucash26_date(date_str: str) -> date: """ Creates a datetime from GnuCash 2.6 date string """ date_format = "%Y%m%d" result = datetime.strptime(date_str, date_format).date() return result
PYTHON
{ "dummy_field": "" }
d20415
test
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
PYTHON
{ "dummy_field": "" }
d20416
test
def _split(string, splitters): """Splits a string into parts at multiple characters""" part = '' for character in string: if character in splitters: yield part part = '' else: part += character yield part
PYTHON
{ "dummy_field": "" }
d20417
test
def index(self, item): """ Not recommended for use on large lists due to time complexity, but it works -> #int list index of @item """ for i, x in enumerate(self.iter()): if x == item: return i return None
PYTHON
{ "dummy_field": "" }
d20418
test
def _dotify(cls, data): """Add dots.""" return ''.join(char if char in cls.PRINTABLE_DATA else '.' for char in data)
PYTHON
{ "dummy_field": "" }
d20419
test
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
PYTHON
{ "dummy_field": "" }
d20420
test
def cprint(string, fg=None, bg=None, end='\n', target=sys.stdout): """Print a colored string to the target handle. fg and bg specify foreground- and background colors, respectively. The remaining keyword arguments are the same as for Python's built-in print function. Colors are returned to their defaults before the function returns. """ _color_manager.set_color(fg, bg) target.write(string + end) target.flush() # Needed for Python 3.x _color_manager.set_defaults()
PYTHON
{ "dummy_field": "" }
d20421
test
def visit_BinOp(self, node): """ Return type depend from both operand of the binary operation. """ args = [self.visit(arg) for arg in (node.left, node.right)] return list({frozenset.union(*x) for x in itertools.product(*args)})
PYTHON
{ "dummy_field": "" }
d20422
test
def sort_filenames(filenames): """ sort a list of files by filename only, ignoring the directory names """ basenames = [os.path.basename(x) for x in filenames] indexes = [i[0] for i in sorted(enumerate(basenames), key=lambda x:x[1])] return [filenames[x] for x in indexes]
PYTHON
{ "dummy_field": "" }
d20423
test
def set_xlimits(self, row, column, min=None, max=None): """Set x-axis limits of a subplot. :param row,column: specify the subplot. :param min: minimal axis value :param max: maximum axis value """ subplot = self.get_subplot_at(row, column) subplot.set_xlimits(min, max)
PYTHON
{ "dummy_field": "" }
d20424
test
def world_to_view(v): """world coords to view coords; v an eu.Vector2, returns (float, float)""" return v.x * config.scale_x, v.y * config.scale_y
PYTHON
{ "dummy_field": "" }
d20425
test
def sort_data(x, y): """Sort the data.""" xy = sorted(zip(x, y)) x, y = zip(*xy) return x, y
PYTHON
{ "dummy_field": "" }
d20426
test
def bisect_index(a, x): """ Find the leftmost index of an element in a list using binary search. Parameters ---------- a: list A sorted list. x: arbitrary The element. Returns ------- int The index. """ i = bisect.bisect_left(a, x) if i != len(a) and a[i] == x: return i raise ValueError
PYTHON
{ "dummy_field": "" }
d20427
test
def save_notebook(work_notebook, write_file): """Saves the Jupyter work_notebook to write_file""" with open(write_file, 'w') as out_nb: json.dump(work_notebook, out_nb, indent=2)
PYTHON
{ "dummy_field": "" }
d20428
test
def _remove_dict_keys_with_value(dict_, val): """Removes `dict` keys which have have `self` as value.""" return {k: v for k, v in dict_.items() if v is not val}
PYTHON
{ "dummy_field": "" }
d20429
test
def clean_out_dir(directory): """ Delete all the files and subdirectories in a directory. """ if not isinstance(directory, path): directory = path(directory) for file_path in directory.files(): file_path.remove() for dir_path in directory.dirs(): dir_path.rmtree()
PYTHON
{ "dummy_field": "" }
d20430
test
def push(h, x): """Push a new value into heap.""" h.push(x) up(h, h.size()-1)
PYTHON
{ "dummy_field": "" }
d20431
test
def chmod_add_excute(filename): """ Adds execute permission to file. :param filename: :return: """ st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC)
PYTHON
{ "dummy_field": "" }
d20432
test
def fetch_event(urls): """ This parallel fetcher uses gevent one uses gevent """ rs = (grequests.get(u) for u in urls) return [content.json() for content in grequests.map(rs)]
PYTHON
{ "dummy_field": "" }
d20433
test
def copy(obj): def copy(self): """ Copy self to a new object. """ from copy import deepcopy return deepcopy(self) obj.copy = copy return obj
PYTHON
{ "dummy_field": "" }
d20434
test
def clean(s): """Removes trailing whitespace on each line.""" lines = [l.rstrip() for l in s.split('\n')] return '\n'.join(lines)
PYTHON
{ "dummy_field": "" }
d20435
test
def get_python(self): """Only return cursor instance if configured for multiselect""" if self.multiselect: return super(MultiSelectField, self).get_python() return self._get()
PYTHON
{ "dummy_field": "" }
d20436
test
def _index_ordering(redshift_list): """ :param redshift_list: list of redshifts :return: indexes in acending order to be evaluated (from z=0 to z=z_source) """ redshift_list = np.array(redshift_list) sort_index = np.argsort(redshift_list) return sort_index
PYTHON
{ "dummy_field": "" }
d20437
test
def go_to_new_line(self): """Go to the end of the current line and create a new line""" self.stdkey_end(False, False) self.insert_text(self.get_line_separator())
PYTHON
{ "dummy_field": "" }
d20438
test
def rgba_bytes_tuple(self, x): """Provides the color corresponding to value `x` in the form of a tuple (R,G,B,A) with int values between 0 and 255. """ return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))
PYTHON
{ "dummy_field": "" }
d20439
test
def date_to_datetime(x): """Convert a date into a datetime""" if not isinstance(x, datetime) and isinstance(x, date): return datetime.combine(x, time()) return x
PYTHON
{ "dummy_field": "" }
d20440
test
def purge_dict(idict): """Remove null items from a dictionary """ odict = {} for key, val in idict.items(): if is_null(val): continue odict[key] = val return odict
PYTHON
{ "dummy_field": "" }
d20441
test
def pprint(obj, verbose=False, max_width=79, newline='\n'): """ Like `pretty` but print to stdout. """ printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline) printer.pretty(obj) printer.flush() sys.stdout.write(newline) sys.stdout.flush()
PYTHON
{ "dummy_field": "" }
d20442
test
def determine_interactive(self): """Determine whether we're in an interactive shell. Sets interactivity off if appropriate. cf http://stackoverflow.com/questions/24861351/how-to-detect-if-python-script-is-being-run-as-a-background-process """ try: if not sys.stdout.isatty() or os.getpgrp() != os.tcgetpgrp(sys.stdout.fileno()): self.interactive = 0 return False except Exception: self.interactive = 0 return False if self.interactive == 0: return False return True
PYTHON
{ "dummy_field": "" }
d20443
test
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
PYTHON
{ "dummy_field": "" }
d20444
test
def insert_one(self, mongo_collection, doc, mongo_db=None, **kwargs): """ Inserts a single document into a mongo collection https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one """ collection = self.get_collection(mongo_collection, mongo_db=mongo_db) return collection.insert_one(doc, **kwargs)
PYTHON
{ "dummy_field": "" }
d20445
test
def _read_json_file(self, json_file): """ Helper function to read JSON file as OrderedDict """ self.log.debug("Reading '%s' JSON file..." % json_file) with open(json_file, 'r') as f: return json.load(f, object_pairs_hook=OrderedDict)
PYTHON
{ "dummy_field": "" }
d20446
test
async def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel""" if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect()
PYTHON
{ "dummy_field": "" }
d20447
test
def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
PYTHON
{ "dummy_field": "" }
d20448
test
async def _send_plain_text(self, request: Request, stack: Stack): """ Sends plain text using `_send_text()`. """ await self._send_text(request, stack, None)
PYTHON
{ "dummy_field": "" }
d20449
test
def get_numbers(s): """Extracts all integers from a string an return them in a list""" result = map(int, re.findall(r'[0-9]+', unicode(s))) return result + [1] * (2 - len(result))
PYTHON
{ "dummy_field": "" }
d20450
test
def _format_title_string(self, title_string): """ format mpv's title """ return self._title_string_format_text_tag(title_string.replace(self.icy_tokkens[0], self.icy_title_prefix))
PYTHON
{ "dummy_field": "" }
d20451
test
def downsample(array, k): """Choose k random elements of array.""" length = array.shape[0] indices = random.sample(xrange(length), k) return array[indices]
PYTHON
{ "dummy_field": "" }
d20452
test
def get_file_string(filepath): """Get string from file.""" with open(os.path.abspath(filepath)) as f: return f.read()
PYTHON
{ "dummy_field": "" }
d20453
test
def distance(vec1, vec2): """Calculate the distance between two Vectors""" if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): dist_vec = vec2 - vec1 return dist_vec.length() else: raise TypeError("vec1 and vec2 must be Vector2's")
PYTHON
{ "dummy_field": "" }
d20454
test
def get_dimension_array(array): """ Get dimension of an array getting the number of rows and the max num of columns. """ if all(isinstance(el, list) for el in array): result = [len(array), len(max([x for x in array], key=len,))] # elif array and isinstance(array, list): else: result = [len(array), 1] return result
PYTHON
{ "dummy_field": "" }
d20455
test
def fft_bandpassfilter(data, fs, lowcut, highcut): """ http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/#comment-16801 """ fft = np.fft.fft(data) # n = len(data) # timestep = 1.0 / fs # freq = np.fft.fftfreq(n, d=timestep) bp = fft.copy() # Zero out fft coefficients # bp[10:-10] = 0 # Normalise # bp *= real(fft.dot(fft))/real(bp.dot(bp)) bp *= fft.dot(fft) / bp.dot(bp) # must multipy by 2 to get the correct amplitude ibp = 12 * np.fft.ifft(bp) return ibp
PYTHON
{ "dummy_field": "" }
d20456
test
def comma_delimited_to_list(list_param): """Convert comma-delimited list / string into a list of strings :param list_param: Comma-delimited string :type list_param: str | unicode :return: A list of strings :rtype: list """ if isinstance(list_param, list): return list_param if isinstance(list_param, str): return list_param.split(',') else: return []
PYTHON
{ "dummy_field": "" }
d20457
test
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None: """ Process an iterable of dictionaries. For each dictionary ``d``, delete ``d[key]`` if it exists. """ for d in dict_list: d.pop(key, None)
PYTHON
{ "dummy_field": "" }
d20458
test
def set_value(self, value): """Set value of the checkbox. Parameters ---------- value : bool value for the checkbox """ if value: self.setChecked(Qt.Checked) else: self.setChecked(Qt.Unchecked)
PYTHON
{ "dummy_field": "" }
d20459
test
def Softsign(a): """ Softsign op. """ return np.divide(a, np.add(np.abs(a), 1)),
PYTHON
{ "dummy_field": "" }
d20460
test
def rlognormal(mu, tau, size=None): """ Return random lognormal variates. """ return np.random.lognormal(mu, np.sqrt(1. / tau), size)
PYTHON
{ "dummy_field": "" }
d20461
test
def __len__(self): """Get a list of the public data attributes.""" return len([i for i in (set(dir(self)) - self._STANDARD_ATTRS) if i[0] != '_'])
PYTHON
{ "dummy_field": "" }
d20462
test
def read(self): """https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image""" stream = BytesIO() self.cam.capture(stream, format='png') # "Rewind" the stream to the beginning so we can read its content stream.seek(0) return Image.open(stream)
PYTHON
{ "dummy_field": "" }
d20463
test
def logout(cache): """ Logs out the current session by removing it from the cache. This is expected to only occur when a session has """ cache.set(flask.session['auth0_key'], None) flask.session.clear() return True
PYTHON
{ "dummy_field": "" }
d20464
test
def save(self): """Saves the updated model to the current entity db. """ self.session.add(self) self.session.flush() return self
PYTHON
{ "dummy_field": "" }
d20465
test
def do_next(self, args): """Step over the next statement """ self._do_print_from_last_cmd = True self._interp.step_over() return True
PYTHON
{ "dummy_field": "" }
d20466
test
def is_string(obj): """Is this a string. :param object obj: :rtype: bool """ if PYTHON3: str_type = (bytes, str) else: str_type = (bytes, str, unicode) return isinstance(obj, str_type)
PYTHON
{ "dummy_field": "" }
d20467
test
def log_loss(preds, labels): """Logarithmic loss with non-necessarily-binary labels.""" log_likelihood = np.sum(labels * np.log(preds)) / len(preds) return -log_likelihood
PYTHON
{ "dummy_field": "" }
d20468
test
def __init__(self, master=None, compound=tk.RIGHT, autohidescrollbar=True, **kwargs): """ Create a Listbox with a vertical scrollbar. :param master: master widget :type master: widget :param compound: side for the Scrollbar to be on (:obj:`tk.LEFT` or :obj:`tk.RIGHT`) :type compound: str :param autohidescrollbar: whether to use an :class:`~ttkwidgets.AutoHideScrollbar` or a :class:`ttk.Scrollbar` :type autohidescrollbar: bool :param kwargs: keyword arguments passed on to the :class:`tk.Listbox` initializer """ ttk.Frame.__init__(self, master) self.columnconfigure(1, weight=1) self.rowconfigure(0, weight=1) self.listbox = tk.Listbox(self, **kwargs) if autohidescrollbar: self.scrollbar = AutoHideScrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview) else: self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.listbox.yview) self.config_listbox(yscrollcommand=self.scrollbar.set) if compound is not tk.LEFT and compound is not tk.RIGHT: raise ValueError("Invalid compound value passed: {0}".format(compound)) self.__compound = compound self._grid_widgets()
PYTHON
{ "dummy_field": "" }
d20469
test
def most_significant_bit(lst: np.ndarray) -> int: """ A helper function that finds the position of the most significant bit in a 1darray of 1s and 0s, i.e. the first position where a 1 appears, reading left to right. :param lst: a 1d array of 0s and 1s with at least one 1 :return: the first position in lst that a 1 appears """ return np.argwhere(np.asarray(lst) == 1)[0][0]
PYTHON
{ "dummy_field": "" }
d20470
test
def _tab(content): """ Helper funcation that converts text-based get response to tab separated values for additional manipulation. """ response = _data_frame(content).to_csv(index=False,sep='\t') return response
PYTHON
{ "dummy_field": "" }
d20471
test
def normalize(data): """Normalize the data to be in the [0, 1] range. :param data: :return: normalized data """ out_data = data.copy() for i, sample in enumerate(out_data): out_data[i] /= sum(out_data[i]) return out_data
PYTHON
{ "dummy_field": "" }
d20472
test
def is_finite(value: Any) -> bool: """Return true if a value is a finite number.""" return isinstance(value, int) or (isinstance(value, float) and isfinite(value))
PYTHON
{ "dummy_field": "" }
d20473
test
def remove_blank_lines(string): """ Removes all blank lines in @string -> #str without blank lines """ return "\n".join(line for line in string.split("\n") if len(line.strip()))
PYTHON
{ "dummy_field": "" }
d20474
test
def _repr(obj): """Show the received object as precise as possible.""" vals = ", ".join("{}={!r}".format( name, getattr(obj, name)) for name in obj._attribs) if vals: t = "{}(name={}, {})".format(obj.__class__.__name__, obj.name, vals) else: t = "{}(name={})".format(obj.__class__.__name__, obj.name) return t
PYTHON
{ "dummy_field": "" }
d20475
test
def find_duplicates(l: list) -> set: """ Return the duplicates in a list. The function relies on https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list . Parameters ---------- l : list Name Returns ------- set Duplicated values >>> find_duplicates([1,2,3]) set() >>> find_duplicates([1,2,1]) {1} """ return set([x for x in l if l.count(x) > 1])
PYTHON
{ "dummy_field": "" }
d20476
test
def label_saves(name): """Labels plots and saves file""" plt.legend(loc=0) plt.ylim([0, 1.025]) plt.xlabel('$U/D$', fontsize=20) plt.ylabel('$Z$', fontsize=20) plt.savefig(name, dpi=300, format='png', transparent=False, bbox_inches='tight', pad_inches=0.05)
PYTHON
{ "dummy_field": "" }
d20477
test
def dag_longest_path(graph, source, target): """ Finds the longest path in a dag between two nodes """ if source == target: return [source] allpaths = nx.all_simple_paths(graph, source, target) longest_path = [] for l in allpaths: if len(l) > len(longest_path): longest_path = l return longest_path
PYTHON
{ "dummy_field": "" }
d20478
test
def itemlist(item, sep, suppress_trailing=True): """Create a list of items seperated by seps.""" return condense(item + ZeroOrMore(addspace(sep + item)) + Optional(sep.suppress() if suppress_trailing else sep))
PYTHON
{ "dummy_field": "" }
d20479
test
def to_list(self): """Convert this confusion matrix into a 2x2 plain list of values.""" return [[int(self.table.cell_values[0][1]), int(self.table.cell_values[0][2])], [int(self.table.cell_values[1][1]), int(self.table.cell_values[1][2])]]
PYTHON
{ "dummy_field": "" }
d20480
test
def cross_v2(vec1, vec2): """Return the crossproduct of the two vectors as a Vec2. Cross product doesn't really make sense in 2D, but return the Z component of the 3d result. """ return vec1.y * vec2.x - vec1.x * vec2.y
PYTHON
{ "dummy_field": "" }
d20481
test
def Fsphere(q, R): """Scattering form-factor amplitude of a sphere normalized to F(q=0)=V Inputs: ------- ``q``: independent variable ``R``: sphere radius Formula: -------- ``4*pi/q^3 * (sin(qR) - qR*cos(qR))`` """ return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R * np.cos(q * R))
PYTHON
{ "dummy_field": "" }
d20482
test
def is_readable_dir(path): """Returns whether a path names an existing directory we can list and read files from.""" return os.path.isdir(path) and os.access(path, os.R_OK) and os.access(path, os.X_OK)
PYTHON
{ "dummy_field": "" }
d20483
test
def assert_exactly_one_true(bool_list): """This method asserts that only one value of the provided list is True. :param bool_list: List of booleans to check :return: True if only one value is True, False otherwise """ assert isinstance(bool_list, list) counter = 0 for item in bool_list: if item: counter += 1 return counter == 1
PYTHON
{ "dummy_field": "" }
d20484
test
def EnumValueName(self, enum, value): """Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the value is not a valid value for the enum. """ return self.enum_types_by_name[enum].values_by_number[value].name
PYTHON
{ "dummy_field": "" }
d20485
test
def POINTER(obj): """ Create ctypes pointer to object. Notes ----- This function converts None to a real NULL pointer because of bug in how ctypes handles None on 64-bit platforms. """ p = ctypes.POINTER(obj) if not isinstance(p.from_param, classmethod): def from_param(cls, x): if x is None: return cls() else: return x p.from_param = classmethod(from_param) return p
PYTHON
{ "dummy_field": "" }
d20486
test
def md5_string(s): """ Shortcut to create md5 hash :param s: :return: """ m = hashlib.md5() m.update(s) return str(m.hexdigest())
PYTHON
{ "dummy_field": "" }
d20487
test
def intersect(d1, d2): """Intersect dictionaries d1 and d2 by key *and* value.""" return dict((k, d1[k]) for k in d1 if k in d2 and d1[k] == d2[k])
PYTHON
{ "dummy_field": "" }
d20488
test
def remove_elements(target, indices): """Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the future...""" copied = list(target) for index in reversed(indices): del copied[index] return copied
PYTHON
{ "dummy_field": "" }
d20489
test
def convertToBool(): """ Convert a byte value to boolean (0 or 1) if the global flag strictBool is True """ if not OPTIONS.strictBool.value: return [] REQUIRES.add('strictbool.asm') result = [] result.append('pop af') result.append('call __NORMALIZE_BOOLEAN') result.append('push af') return result
PYTHON
{ "dummy_field": "" }
d20490
test
def append_query_parameter(url, parameters, ignore_if_exists=True): """ quick and dirty appending of query parameters to a url """ if ignore_if_exists: for key in parameters.keys(): if key + "=" in url: del parameters[key] parameters_str = "&".join(k + "=" + v for k, v in parameters.items()) append_token = "&" if "?" in url else "?" return url + append_token + parameters_str
PYTHON
{ "dummy_field": "" }
d20491
test
def pid_exists(pid): """ Determines if a system process identifer exists in process table. """ try: os.kill(pid, 0) except OSError as exc: return exc.errno == errno.EPERM else: return True
PYTHON
{ "dummy_field": "" }
d20492
test
def is_static(*p): """ A static value (does not change at runtime) which is known at compile time """ return all(is_CONST(x) or is_number(x) or is_const(x) for x in p)
PYTHON
{ "dummy_field": "" }
d20493
test
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
PYTHON
{ "dummy_field": "" }
d20494
test
def _(f, x): """ filter for dict, note `f` should have signature: `f::key->value->bool` """ return {k: v for k, v in x.items() if f(k, v)}
PYTHON
{ "dummy_field": "" }
d20495
test
def from_file(file_path) -> dict: """ Load JSON file """ with io.open(file_path, 'r', encoding='utf-8') as json_stream: return Json.parse(json_stream, True)
PYTHON
{ "dummy_field": "" }
d20496
test
def shape_list(l,shape,dtype): """ Shape a list of lists into the appropriate shape and data type """ return np.array(l, dtype=dtype).reshape(shape)
PYTHON
{ "dummy_field": "" }
d20497
test
def dtypes(self): """Returns all column names and their data types as a list. >>> df.dtypes [('age', 'int'), ('name', 'string')] """ return [(str(f.name), f.dataType.simpleString()) for f in self.schema.fields]
PYTHON
{ "dummy_field": "" }
d20498
test
def random_str(size=10): """ create random string of selected size :param size: int, length of the string :return: the string """ return ''.join(random.choice(string.ascii_lowercase) for _ in range(size))
PYTHON
{ "dummy_field": "" }
d20499
test
def try_cast_int(s): """(str) -> int All the digits in a given string are concatenated and converted into a single number. """ try: temp = re.findall('\d', str(s)) temp = ''.join(temp) return int(temp) except: return s
PYTHON
{ "dummy_field": "" }
d20500
test
def column_names(self, table): """An iterable of column names, for a particular table or view.""" table_info = self.execute( u'PRAGMA table_info(%s)' % quote(table)) return (column['name'] for column in table_info)
PYTHON
{ "dummy_field": "" }