_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
87
6.4k
title
stringclasses
1 value
language
stringclasses
1 value
meta_information
dict
d420
train
def columns(self): """Return names of all the addressable columns (including foreign keys) referenced in user supplied model""" res = [col['name'] for col in self.column_definitions] res.extend([col['name'] for col in self.foreign_key_definitions]) return res
PYTHON
{ "dummy_field": "" }
d424
train
def angle(x0, y0, x1, y1): """ Returns the angle between two points. """ return degrees(atan2(y1-y0, x1-x0))
PYTHON
{ "dummy_field": "" }
d425
train
def delete_duplicates(seq): """ Remove duplicates from an iterable, preserving the order. Args: seq: Iterable of various type. Returns: list: List of unique objects. """ seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))]
PYTHON
{ "dummy_field": "" }
d429
train
def get_colors(img): """ Returns a list of all the image's colors. """ w, h = img.size return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]
PYTHON
{ "dummy_field": "" }
d430
train
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": "" }
d432
train
def check_precomputed_distance_matrix(X): """Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix. """ tmp = X.copy() tmp[np.isinf(tmp)] = 1 check_array(tmp)
PYTHON
{ "dummy_field": "" }
d434
train
def linedelimited (inlist,delimiter): """ Returns a string composed of elements in inlist, with each element separated by 'delimiter.' Used by function writedelimited. Use '\t' for tab-delimiting. Usage: linedelimited (inlist,delimiter) """ outstr = '' for item in inlist: if type(item) != StringType: item = str(item) outstr = outstr + item + delimiter outstr = outstr[0:-1] return outstr
PYTHON
{ "dummy_field": "" }
d435
train
def get_month_start_end_day(): """ Get the month start date a nd end date """ t = date.today() n = mdays[t.month] return (date(t.year, t.month, 1), date(t.year, t.month, n))
PYTHON
{ "dummy_field": "" }
d436
train
def dequeue(self, block=True): """Dequeue a record and return item.""" return self.queue.get(block, self.queue_get_timeout)
PYTHON
{ "dummy_field": "" }
d437
train
def return_value(self, *args, **kwargs): """Extracts the real value to be returned from the wrapping callable. :return: The value the double should return when called. """ self._called() return self._return_value(*args, **kwargs)
PYTHON
{ "dummy_field": "" }
d438
train
def get_best_encoding(stream): """Returns the default stream encoding if not found.""" rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding() if is_ascii_encoding(rv): return 'utf-8' return rv
PYTHON
{ "dummy_field": "" }
d440
train
def we_are_in_lyon(): """Check if we are on a Lyon machine""" import socket try: hostname = socket.gethostname() ip = socket.gethostbyname(hostname) except socket.gaierror: return False return ip.startswith("134.158.")
PYTHON
{ "dummy_field": "" }
d442
train
def is_callable(*p): """ True if all the args are functions and / or subroutines """ import symbols return all(isinstance(x, symbols.FUNCTION) for x in p)
PYTHON
{ "dummy_field": "" }
d444
train
def eqstr(a, b): """ Determine whether two strings are equivalent. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eqstr_c.html :param a: Arbitrary character string. :type a: str :param b: Arbitrary character string. :type b: str :return: True if A and B are equivalent. :rtype: bool """ return bool(libspice.eqstr_c(stypes.stringToCharP(a), stypes.stringToCharP(b)))
PYTHON
{ "dummy_field": "" }
d445
train
def get_by(self, name): """get element by name""" return next((item for item in self if item.name == name), None)
PYTHON
{ "dummy_field": "" }
d446
train
def validate(self, *args, **kwargs): # pylint: disable=arguments-differ """ Validate a parameter dict against a parameter schema from an ocrd-tool.json Args: obj (dict): schema (dict): """ return super(ParameterValidator, self)._validate(*args, **kwargs)
PYTHON
{ "dummy_field": "" }
d447
train
def get_parent_dir(name): """Get the parent directory of a filename.""" parent_dir = os.path.dirname(os.path.dirname(name)) if parent_dir: return parent_dir return os.path.abspath('.')
PYTHON
{ "dummy_field": "" }
d450
train
def show_guestbook(): """Returns all existing guestbook records.""" cursor = flask.g.db.execute( 'SELECT name, message FROM entry ORDER BY id DESC;') entries = [{'name': row[0], 'message': row[1]} for row in cursor.fetchall()] return jinja2.Template(LAYOUT).render(entries=entries)
PYTHON
{ "dummy_field": "" }
d452
train
def rank(idx, dim): """Calculate the index rank according to Bertran's notation.""" idxm = multi_index(idx, dim) out = 0 while idxm[-1:] == (0,): out += 1 idxm = idxm[:-1] return out
PYTHON
{ "dummy_field": "" }
d453
train
def get_last_commit(git_path=None): """ Get the HEAD commit SHA1 of repository in current dir. """ if git_path is None: git_path = GIT_PATH line = get_last_commit_line(git_path) revision_id = line.split()[1] return revision_id
PYTHON
{ "dummy_field": "" }
d454
train
def csvpretty(csvfile: csvfile=sys.stdin): """ Pretty print a CSV file. """ shellish.tabulate(csv.reader(csvfile))
PYTHON
{ "dummy_field": "" }
d455
train
def array_dim(arr): """Return the size of a multidimansional array. """ dim = [] while True: try: dim.append(len(arr)) arr = arr[0] except TypeError: return dim
PYTHON
{ "dummy_field": "" }
d458
train
def is_static(self, filename): """Check if a file is a static file (which should be copied, rather than compiled using Jinja2). A file is considered static if it lives in any of the directories specified in ``staticpaths``. :param filename: the name of the file to check """ if self.staticpaths is None: # We're not using static file support return False for path in self.staticpaths: if filename.startswith(path): return True return False
PYTHON
{ "dummy_field": "" }
d460
train
def serve_static(request, path, insecure=False, **kwargs): """Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{% javascript %}`` or ``{% stylesheet %}`` template tags. You can use this view by adding the following to any :file:`urls.py`:: urlpatterns += static('static/', view='pipeline.views.serve_static') """ # Follow the same logic Django uses for determining access to the # static-serving view. if not django_settings.DEBUG and not insecure: raise ImproperlyConfigured("The staticfiles view can only be used in " "debug mode or if the --insecure " "option of 'runserver' is used") if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED: # Collect only the requested file, in order to serve the result as # fast as possible. This won't interfere with the template tags in any # way, as those will still cause Django to collect all media. default_collector.collect(request, files=[path]) return serve(request, path, document_root=django_settings.STATIC_ROOT, **kwargs)
PYTHON
{ "dummy_field": "" }
d461
train
def items(cls): """ All values for this enum :return: list of tuples """ return [ cls.PRECIPITATION, cls.WIND, cls.TEMPERATURE, cls.PRESSURE ]
PYTHON
{ "dummy_field": "" }
d467
train
def _get_local_ip(): """ Get the local ip of this device :return: Ip of this computer :rtype: str """ return set([x[4][0] for x in socket.getaddrinfo( socket.gethostname(), 80, socket.AF_INET )]).pop()
PYTHON
{ "dummy_field": "" }
d471
train
def last_day(year=_year, month=_month): """ get the current month's last day :param year: default to current year :param month: default to current month :return: month's last day """ last_day = calendar.monthrange(year, month)[1] return datetime.date(year=year, month=month, day=last_day)
PYTHON
{ "dummy_field": "" }
d473
train
def get_obj_cols(df): """ Returns names of 'object' columns in the DataFrame. """ obj_cols = [] for idx, dt in enumerate(df.dtypes): if dt == 'object' or is_category(dt): obj_cols.append(df.columns.values[idx]) return obj_cols
PYTHON
{ "dummy_field": "" }
d475
train
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
PYTHON
{ "dummy_field": "" }
d481
train
def get(s, delimiter='', format="diacritical"): """Return pinyin of string, the string must be unicode """ return delimiter.join(_pinyin_generator(u(s), format=format))
PYTHON
{ "dummy_field": "" }
d482
train
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
PYTHON
{ "dummy_field": "" }
d483
train
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
PYTHON
{ "dummy_field": "" }
d484
train
def center_eigenvalue_diff(mat): """Compute the eigvals of mat and then find the center eigval difference.""" N = len(mat) evals = np.sort(la.eigvals(mat)) diff = np.abs(evals[N/2] - evals[N/2-1]) return diff
PYTHON
{ "dummy_field": "" }
d488
train
def clear_es(): """Clear all indexes in the es core""" # TODO: should receive a catalog slug. ESHypermap.es.indices.delete(ESHypermap.index_name, ignore=[400, 404]) LOGGER.debug('Elasticsearch: Index cleared')
PYTHON
{ "dummy_field": "" }
d489
train
def get_idx_rect(index_list): """Extract the boundaries from a list of indexes""" rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list])) return ( min(rows), max(rows), min(cols), max(cols) )
PYTHON
{ "dummy_field": "" }
d490
train
def _get_node_parent(self, age, pos): """Get the parent node of node, whch is located in tree's node list. Returns: object: The parent node. """ return self.nodes[age][int(pos / self.comp)]
PYTHON
{ "dummy_field": "" }
d492
train
def dedup_list(l): """Given a list (l) will removing duplicates from the list, preserving the original order of the list. Assumes that the list entrie are hashable.""" dedup = set() return [ x for x in l if not (x in dedup or dedup.add(x))]
PYTHON
{ "dummy_field": "" }
d493
train
def tf2(): """Provide the root module of a TF-2.0 API for use within TensorBoard. Returns: The root module of a TF-2.0 API, if available. Raises: ImportError: if a TF-2.0 API is not available. """ # Import the `tf` compat API from this file and check if it's already TF 2.0. if tf.__version__.startswith('2.'): return tf elif hasattr(tf, 'compat') and hasattr(tf.compat, 'v2'): # As a fallback, try `tensorflow.compat.v2` if it's defined. return tf.compat.v2 raise ImportError('cannot import tensorflow 2.0 API')
PYTHON
{ "dummy_field": "" }
d499
train
def get_bottomrect_idx(self, pos): """ Determine if cursor is on bottom right corner of a hot spot.""" for i, r in enumerate(self.link_bottom_rects): if r.Contains(pos): return i return -1
PYTHON
{ "dummy_field": "" }
d501
train
def table_top_abs(self): """Returns the absolute position of table top""" table_height = np.array([0, 0, self.table_full_size[2]]) return string_to_array(self.floor.get("pos")) + table_height
PYTHON
{ "dummy_field": "" }
d502
train
def plot_epsilon_residuals(self): """Plots the epsilon residuals for the variogram fit.""" fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(range(self.epsilon.size), self.epsilon, c='k', marker='*') ax.axhline(y=0.0) plt.show()
PYTHON
{ "dummy_field": "" }
d503
train
def get_property_by_name(pif, name): """Get a property by name""" return next((x for x in pif.properties if x.name == name), None)
PYTHON
{ "dummy_field": "" }
d505
train
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
PYTHON
{ "dummy_field": "" }
d508
train
def get_element_with_id(self, id): """Return the element with the specified ID.""" # Should we maintain a hashmap of ids to make this more efficient? Probably overkill. # TODO: Elements can contain nested elements (captions, footnotes, table cells, etc.) return next((el for el in self.elements if el.id == id), None)
PYTHON
{ "dummy_field": "" }
d509
train
def vector_distance(a, b): """The Euclidean distance between two vectors.""" a = np.array(a) b = np.array(b) return np.linalg.norm(a - b)
PYTHON
{ "dummy_field": "" }
d511
train
def euclidean(c1, c2): """Square of the euclidean distance""" diffs = ((i - j) for i, j in zip(c1, c2)) return sum(x * x for x in diffs)
PYTHON
{ "dummy_field": "" }
d512
train
def get_free_memory_win(): """Return current free memory on the machine for windows. Warning : this script is really not robust Return in MB unit """ stat = MEMORYSTATUSEX() ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) return int(stat.ullAvailPhys / 1024 / 1024)
PYTHON
{ "dummy_field": "" }
d515
train
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return result[0]
PYTHON
{ "dummy_field": "" }
d518
train
def title(self): """ The title of this window """ with switch_window(self._browser, self.name): return self._browser.title
PYTHON
{ "dummy_field": "" }
d519
train
def visit_BoolOp(self, node): """ Return type may come from any boolop operand. """ return sum((self.visit(value) for value in node.values), [])
PYTHON
{ "dummy_field": "" }
d520
train
def __get_xml_text(root): """ Return the text for the given root node (xml.dom.minidom). """ txt = "" for e in root.childNodes: if (e.nodeType == e.TEXT_NODE): txt += e.data return txt
PYTHON
{ "dummy_field": "" }
d522
train
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": "" }
d523
train
def get_order(self, codes): """Return evidence codes in order shown in code2name.""" return sorted(codes, key=lambda e: [self.ev2idx.get(e)])
PYTHON
{ "dummy_field": "" }
d524
train
def equal(list1, list2): """ takes flags returns indexes of True values """ return [item1 == item2 for item1, item2 in broadcast_zip(list1, list2)]
PYTHON
{ "dummy_field": "" }
d525
train
def select(self, cmd, *args, **kwargs): """ Execute the SQL command and return the data rows as tuples """ self.cursor.execute(cmd, *args, **kwargs) return self.cursor.fetchall()
PYTHON
{ "dummy_field": "" }
d526
train
def go_to_parent_directory(self): """Go to parent directory""" self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))
PYTHON
{ "dummy_field": "" }
d529
train
def exp_fit_fun(x, a, tau, c): """Function used to fit the exponential decay.""" # pylint: disable=invalid-name return a * np.exp(-x / tau) + c
PYTHON
{ "dummy_field": "" }
d531
train
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
PYTHON
{ "dummy_field": "" }
d532
train
def searchlast(self,n=10): """Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type.""" solutions = deque([], n) for solution in self: solutions.append(solution) return solutions
PYTHON
{ "dummy_field": "" }
d534
train
def _text_to_graphiz(self, text): """create a graphviz graph from text""" dot = Source(text, format='svg') return dot.pipe().decode('utf-8')
PYTHON
{ "dummy_field": "" }
d535
train
def get_colors(img): """ Returns a list of all the image's colors. """ w, h = img.size return [color[:3] for count, color in img.convert('RGB').getcolors(w * h)]
PYTHON
{ "dummy_field": "" }
d536
train
def _round_half_hour(record): """ Round a time DOWN to half nearest half-hour. """ k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30)) return datetime(k.year, k.month, k.day, k.hour, k.minute, 0)
PYTHON
{ "dummy_field": "" }
d538
train
def threads_init(gtk=True): """Enables multithreading support in Xlib and PyGTK. See the module docstring for more info. :Parameters: gtk : bool May be set to False to skip the PyGTK module. """ # enable X11 multithreading x11.XInitThreads() if gtk: from gtk.gdk import threads_init threads_init()
PYTHON
{ "dummy_field": "" }
d539
train
def security(self): """Print security object information for a pdf document""" return {k: v for i in self.pdf.resolvedObjects.items() for k, v in i[1].items()}
PYTHON
{ "dummy_field": "" }
d540
train
def enable_gtk3(self, app=None): """Enable event loop integration with Gtk3 (gir bindings). Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for Gtk3, which allows the Gtk3 to integrate with terminal based applications like IPython. """ from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3 self.set_inputhook(create_inputhook_gtk3(self._stdin_file)) self._current_gui = GUI_GTK
PYTHON
{ "dummy_field": "" }
d541
train
def dot(a, b): """Take arrays `a` and `b` and form the dot product between the last axis of `a` and the first of `b`. """ b = numpy.asarray(b) return numpy.dot(a, b.reshape(b.shape[0], -1)).reshape(a.shape[:-1] + b.shape[1:])
PYTHON
{ "dummy_field": "" }
d542
train
def guess_encoding(text, default=DEFAULT_ENCODING): """Guess string encoding. Given a piece of text, apply character encoding detection to guess the appropriate encoding of the text. """ result = chardet.detect(text) return normalize_result(result, default=default)
PYTHON
{ "dummy_field": "" }
d544
train
def __gzip(filename): """ Compress a file returning the new filename (.gz) """ zipname = filename + '.gz' file_pointer = open(filename,'rb') zip_pointer = gzip.open(zipname,'wb') zip_pointer.writelines(file_pointer) file_pointer.close() zip_pointer.close() return zipname
PYTHON
{ "dummy_field": "" }
d545
train
def forceupdate(self, *args, **kw): """Like a bulk :meth:`forceput`.""" self._update(False, self._ON_DUP_OVERWRITE, *args, **kw)
PYTHON
{ "dummy_field": "" }
d547
train
def rfft2d_freqs(h, w): """Computes 2D spectrum frequencies.""" fy = np.fft.fftfreq(h)[:, None] # when we have an odd input dimension we need to keep one additional # frequency and later cut off 1 pixel if w % 2 == 1: fx = np.fft.fftfreq(w)[: w // 2 + 2] else: fx = np.fft.fftfreq(w)[: w // 2 + 1] return np.sqrt(fx * fx + fy * fy)
PYTHON
{ "dummy_field": "" }
d550
train
def h5ToDict(h5, readH5pyDataset=True): """ Read a hdf5 file into a dictionary """ h = h5py.File(h5, "r") ret = unwrapArray(h, recursive=True, readH5pyDataset=readH5pyDataset) if readH5pyDataset: h.close() return ret
PYTHON
{ "dummy_field": "" }
d551
train
def current_zipfile(): """A function to vend the current zipfile, if any""" if zipfile.is_zipfile(sys.argv[0]): fd = open(sys.argv[0], "rb") return zipfile.ZipFile(fd)
PYTHON
{ "dummy_field": "" }
d552
train
def __unixify(self, s): """ stupid windows. converts the backslash to forwardslash for consistency """ return os.path.normpath(s).replace(os.sep, "/")
PYTHON
{ "dummy_field": "" }
d555
train
def apply(f, obj, *args, **kwargs): """Apply a function in parallel to each element of the input""" return vectorize(f)(obj, *args, **kwargs)
PYTHON
{ "dummy_field": "" }
d560
train
def _heappush_max(heap, item): """ why is this not in heapq """ heap.append(item) heapq._siftdown_max(heap, 0, len(heap) - 1)
PYTHON
{ "dummy_field": "" }
d561
train
def _remove_keywords(d): """ copy the dict, filter_keywords Parameters ---------- d : dict """ return { k:v for k, v in iteritems(d) if k not in RESERVED }
PYTHON
{ "dummy_field": "" }
d563
train
def uniq(seq): """ Return a copy of seq without duplicates. """ seen = set() return [x for x in seq if str(x) not in seen and not seen.add(str(x))]
PYTHON
{ "dummy_field": "" }
d567
train
def ci(a, which=95, axis=None): """Return a percentile range from an array of values.""" p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
PYTHON
{ "dummy_field": "" }
d569
train
def tuple_search(t, i, v): """ Search tuple array by index and value :param t: tuple array :param i: index of the value in each tuple :param v: value :return: the first tuple in the array with the specific index / value """ for e in t: if e[i] == v: return e return None
PYTHON
{ "dummy_field": "" }
d571
train
def area(x,y): """ Calculate the area of a polygon given as x(...),y(...) Implementation of Shoelace formula """ # http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
PYTHON
{ "dummy_field": "" }
d577
train
def _get_compiled_ext(): """Official way to get the extension of compiled files (.pyc or .pyo)""" for ext, mode, typ in imp.get_suffixes(): if typ == imp.PY_COMPILED: return ext
PYTHON
{ "dummy_field": "" }
d579
train
def inh(table): """ inverse hyperbolic sine transformation """ t = [] for i in table: t.append(np.ndarray.tolist(np.arcsinh(i))) return t
PYTHON
{ "dummy_field": "" }
d581
train
def median(lst): """ Calcuates the median value in a @lst """ #: http://stackoverflow.com/a/24101534 sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1])/2.0
PYTHON
{ "dummy_field": "" }
d583
train
def iter_finds(regex_obj, s): """Generate all matches found within a string for a regex and yield each match as a string""" if isinstance(regex_obj, str): for m in re.finditer(regex_obj, s): yield m.group() else: for m in regex_obj.finditer(s): yield m.group()
PYTHON
{ "dummy_field": "" }
d587
train
def find_lt(a, x): """Find rightmost value less than x.""" i = bs.bisect_left(a, x) if i: return i - 1 raise ValueError
PYTHON
{ "dummy_field": "" }
d588
train
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return result[0]
PYTHON
{ "dummy_field": "" }
d592
train
def apply_fit(xy,coeffs): """ Apply the coefficients from a linear fit to an array of x,y positions. The coeffs come from the 'coeffs' member of the 'fit_arrays()' output. """ x_new = coeffs[0][2] + coeffs[0][0]*xy[:,0] + coeffs[0][1]*xy[:,1] y_new = coeffs[1][2] + coeffs[1][0]*xy[:,0] + coeffs[1][1]*xy[:,1] return x_new,y_new
PYTHON
{ "dummy_field": "" }
d600
train
def get_document_frequency(self, term): """ Returns the number of documents the specified term appears in. """ if term not in self._terms: raise IndexError(TERM_DOES_NOT_EXIST) else: return len(self._terms[term])
PYTHON
{ "dummy_field": "" }
d606
train
def is_password_valid(password): """ Check if a password is valid """ pattern = re.compile(r"^.{4,75}$") return bool(pattern.match(password))
PYTHON
{ "dummy_field": "" }
d610
train
def gauss_pdf(x, mu, sigma): """Normalized Gaussian""" return 1 / np.sqrt(2 * np.pi) / sigma * np.exp(-(x - mu) ** 2 / 2. / sigma ** 2)
PYTHON
{ "dummy_field": "" }
d612
train
def ExecuteRaw(self, position, command): """Send a command string to gdb.""" self.EnsureGdbPosition(position[0], None, None) return gdb.execute(command, to_string=True)
PYTHON
{ "dummy_field": "" }
d616
train
def uniqueID(size=6, chars=string.ascii_uppercase + string.digits): """A quick and dirty way to get a unique string""" return ''.join(random.choice(chars) for x in xrange(size))
PYTHON
{ "dummy_field": "" }
d618
train
def _generate_key_map(entity_list, key, entity_class): """ Helper method to generate map from key to entity object for given list of dicts. Args: entity_list: List consisting of dict. key: Key in each dict which will be key in the map. entity_class: Class representing the entity. Returns: Map mapping key to entity object. """ key_map = {} for obj in entity_list: key_map[obj[key]] = entity_class(**obj) return key_map
PYTHON
{ "dummy_field": "" }
d620
train
def _rndPointDisposition(dx, dy): """Return random disposition point.""" x = int(random.uniform(-dx, dx)) y = int(random.uniform(-dy, dy)) return (x, y)
PYTHON
{ "dummy_field": "" }
d622
train
def sine_wave(frequency): """Emit a sine wave at the given frequency.""" xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1]) ts = xs / FLAGS.sample_rate return tf.sin(2 * math.pi * frequency * ts)
PYTHON
{ "dummy_field": "" }
d624
train
def bitsToString(arr): """Returns a string representing a numpy array of 0's and 1's""" s = array('c','.'*len(arr)) for i in xrange(len(arr)): if arr[i] == 1: s[i]='*' return s
PYTHON
{ "dummy_field": "" }
d627
train
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": "" }
d628
train
def uniqueID(size=6, chars=string.ascii_uppercase + string.digits): """A quick and dirty way to get a unique string""" return ''.join(random.choice(chars) for x in xrange(size))
PYTHON
{ "dummy_field": "" }
d631
train
def copy(self): """ Return a copy of the dictionary. This is a middle-deep copy; the copy is independent of the original in all attributes that have mutable types except for: * The values in the dictionary Note that the Python functions :func:`py:copy.copy` and :func:`py:copy.deepcopy` can be used to create completely shallow or completely deep copies of objects of this class. """ result = NocaseDict() result._data = self._data.copy() # pylint: disable=protected-access return result
PYTHON
{ "dummy_field": "" }
d632
train
def longest_run(da, dim='time'): """Return the length of the longest consecutive run of True values. Parameters ---------- arr : N-dimensional array (boolean) Input array dim : Xarray dimension (default = 'time') Dimension along which to calculate consecutive run Returns ------- N-dimensional array (int) Length of longest run of True values along dimension """ d = rle(da, dim=dim) rl_long = d.max(dim=dim) return rl_long
PYTHON
{ "dummy_field": "" }