anchor stringlengths 16 95 | positive stringlengths 87 6.25k | negative stringlengths 87 6.4k |
|---|---|---|
how to make booleans in python global | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def notin(arg, values):
"""
Like isin, but checks whether this expression's value(s) are not
contained in the passed values. See isin docs for full usage.
"""
op = ops.NotContains(arg, values)
return op.to_expr() |
how to make booleans in python global | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def visit_BoolOp(self, node):
""" Return type may come from any boolop operand. """
return sum((self.visit(value) for value in node.values), []) |
how to make booleans in python global | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | 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(... |
how to make booleans in python global | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def check_oneof(**kwargs):
"""Raise ValueError if more than one keyword argument is not none.
Args:
kwargs (dict): The keyword arguments sent to the function.
Returns: None
Raises:
ValueError: If more than one entry in kwargs is not none.
"""
# Sanity check: If no keyword argu... |
how to make booleans in python global | def less_strict_bool(x):
"""Idempotent and None-safe version of strict_bool."""
if x is None:
return False
elif x is True or x is False:
return x
else:
return strict_bool(x) | def _or(ctx, *logical):
"""
Returns TRUE if any argument is TRUE
"""
for arg in logical:
if conversions.to_boolean(arg, ctx):
return True
return False |
how to make multiple slices in a list in python | def batch(items, size):
"""Batches a list into a list of lists, with sub-lists sized by a specified
batch size."""
return [items[x:x + size] for x in xrange(0, len(items), size)] | def Slice(a, begin, size):
"""
Slicing op.
"""
return np.copy(a)[[slice(*tpl) for tpl in zip(begin, begin+size)]], |
how to make multiple slices in a list in python | def batch(items, size):
"""Batches a list into a list of lists, with sub-lists sized by a specified
batch size."""
return [items[x:x + size] for x in xrange(0, len(items), size)] | def grow_slice(slc, size):
"""
Grow a slice object by 1 in each direction without overreaching the list.
Parameters
----------
slc: slice
slice object to grow
size: int
list length
Returns
-------
slc: slice
extended slice
"""
return slice(max(0, s... |
how to make multiple slices in a list in python | def batch(items, size):
"""Batches a list into a list of lists, with sub-lists sized by a specified
batch size."""
return [items[x:x + size] for x in xrange(0, len(items), size)] | def get_axis(array, axis, slice_num):
"""Returns a fixed axis"""
slice_list = [slice(None)] * array.ndim
slice_list[axis] = slice_num
slice_data = array[tuple(slice_list)].T # transpose for proper orientation
return slice_data |
how to make multiple slices in a list in python | def batch(items, size):
"""Batches a list into a list of lists, with sub-lists sized by a specified
batch size."""
return [items[x:x + size] for x in xrange(0, len(items), size)] | def iget_list_column_slice(list_, start=None, stop=None, stride=None):
""" iterator version of get_list_column """
if isinstance(start, slice):
slice_ = start
else:
slice_ = slice(start, stop, stride)
return (row[slice_] for row in list_) |
how to make multiple slices in a list in python | def batch(items, size):
"""Batches a list into a list of lists, with sub-lists sized by a specified
batch size."""
return [items[x:x + size] for x in xrange(0, len(items), size)] | def _split_arrs(array_2d, slices):
"""
Equivalent to numpy.split(array_2d, slices),
but avoids fancy indexing
"""
if len(array_2d) == 0:
return np.empty(0, dtype=np.object)
rtn = np.empty(len(slices) + 1, dtype=np.object)
start = 0
for i, s in enumerate(slices):
rtn[i] =... |
how to make python round a float to int | def intround(value):
"""Given a float returns a rounded int. Should give the same result on
both Py2/3
"""
return int(decimal.Decimal.from_float(
value).to_integral_value(decimal.ROUND_HALF_EVEN)) | def round_to_float(number, precision):
"""Round a float to a precision"""
rounded = Decimal(str(floor((number + precision / 2) // precision))
) * Decimal(str(precision))
return float(rounded) |
how to make python round a float to int | def intround(value):
"""Given a float returns a rounded int. Should give the same result on
both Py2/3
"""
return int(decimal.Decimal.from_float(
value).to_integral_value(decimal.ROUND_HALF_EVEN)) | def specialRound(number, rounding):
"""A method used to round a number in the way that UsefulUtils rounds."""
temp = 0
if rounding == 0:
temp = number
else:
temp = round(number, rounding)
if temp % 1 == 0:
return int(temp)
else:
return float(temp) |
how to make python round a float to int | def intround(value):
"""Given a float returns a rounded int. Should give the same result on
both Py2/3
"""
return int(decimal.Decimal.from_float(
value).to_integral_value(decimal.ROUND_HALF_EVEN)) | def py3round(number):
"""Unified rounding in all python versions."""
if abs(round(number) - number) == 0.5:
return int(2.0 * round(number / 2.0))
return int(round(number)) |
how to make python round a float to int | def intround(value):
"""Given a float returns a rounded int. Should give the same result on
both Py2/3
"""
return int(decimal.Decimal.from_float(
value).to_integral_value(decimal.ROUND_HALF_EVEN)) | def round_float(f, digits, rounding=ROUND_HALF_UP):
"""
Accurate float rounding from http://stackoverflow.com/a/15398691.
"""
return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits),
rounding=rounding) |
how to make python round a float to int | def intround(value):
"""Given a float returns a rounded int. Should give the same result on
both Py2/3
"""
return int(decimal.Decimal.from_float(
value).to_integral_value(decimal.ROUND_HALF_EVEN)) | def round_to_int(number, precision):
"""Round a number to a precision"""
precision = int(precision)
rounded = (int(number) + precision / 2) // precision * precision
return rounded |
python response raise for status | def raise_for_not_ok_status(response):
"""
Raises a `requests.exceptions.HTTPError` if the response has a non-200
status code.
"""
if response.code != OK:
raise HTTPError('Non-200 response code (%s) for url: %s' % (
response.code, uridecode(response.request.absoluteURI)))
re... | def handle_errors(resp):
"""raise a descriptive exception on a "bad request" response"""
if resp.status_code == 400:
raise ApiException(json.loads(resp.content).get('message'))
return resp |
python response raise for status | def raise_for_not_ok_status(response):
"""
Raises a `requests.exceptions.HTTPError` if the response has a non-200
status code.
"""
if response.code != OK:
raise HTTPError('Non-200 response code (%s) for url: %s' % (
response.code, uridecode(response.request.absoluteURI)))
re... | def __init__(self, response):
"""Initialize a ResponseException instance.
:param response: A requests.response instance.
"""
self.response = response
super(ResponseException, self).__init__(
"received {} HTTP response".format(response.status_code)
) |
python response raise for status | def raise_for_not_ok_status(response):
"""
Raises a `requests.exceptions.HTTPError` if the response has a non-200
status code.
"""
if response.code != OK:
raise HTTPError('Non-200 response code (%s) for url: %s' % (
response.code, uridecode(response.request.absoluteURI)))
re... | def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):
"""webargs error handler that uses Flask-RESTful's abort function to return
a JSON error response to the client.
"""
abort(error_status_code, errors=err.messages) |
python response raise for status | def raise_for_not_ok_status(response):
"""
Raises a `requests.exceptions.HTTPError` if the response has a non-200
status code.
"""
if response.code != OK:
raise HTTPError('Non-200 response code (%s) for url: %s' % (
response.code, uridecode(response.request.absoluteURI)))
re... | def handle_exception(error):
"""Simple method for handling exceptions raised by `PyBankID`.
:param flask_pybankid.FlaskPyBankIDError error: The exception to handle.
:return: The exception represented as a dictionary.
:rtype: dict
"""
response = jsonify(error.to_dict())
... |
python response raise for status | def raise_for_not_ok_status(response):
"""
Raises a `requests.exceptions.HTTPError` if the response has a non-200
status code.
"""
if response.code != OK:
raise HTTPError('Non-200 response code (%s) for url: %s' % (
response.code, uridecode(response.request.absoluteURI)))
re... | def lambda_failure_response(*args):
"""
Helper function to create a Lambda Failure Response
:return: A Flask Response
"""
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) |
python return shapes ofarrays | def out_shape_from_array(arr):
"""Get the output shape from an array."""
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],) | def getTuple(self):
""" Returns the shape of the region as (x, y, w, h) """
return (self.x, self.y, self.w, self.h) |
python return shapes ofarrays | def out_shape_from_array(arr):
"""Get the output shape from an array."""
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],) | def array(self):
"""
The underlying array of shape (N, L, I)
"""
return numpy.array([self[sid].array for sid in sorted(self)]) |
python return shapes ofarrays | def out_shape_from_array(arr):
"""Get the output shape from an array."""
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],) | def get_shape(self):
"""
Return a tuple of this array's dimensions. This is done by
querying the Dim children. Note that once it has been
created, it is also possible to examine an Array object's
.array attribute directly, and doing that is much faster.
"""
return tuple(int(c.pcdata) for c in self.getEl... |
python return shapes ofarrays | def out_shape_from_array(arr):
"""Get the output shape from an array."""
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],) | def get_shape(img):
"""Return the shape of img.
Paramerers
-----------
img:
Returns
-------
shape: tuple
"""
if hasattr(img, 'shape'):
shape = img.shape
else:
shape = img.get_data().shape
return shape |
python return shapes ofarrays | def out_shape_from_array(arr):
"""Get the output shape from an array."""
arr = np.asarray(arr)
if arr.ndim == 1:
return arr.shape
else:
return (arr.shape[1],) | def _check_2d_shape(X):
"""Check shape of array or sparse matrix.
Assure that X is always 2D: Unlike numpy we always deal with 2D arrays.
"""
if X.dtype.names is None and len(X.shape) != 2:
raise ValueError('X needs to be 2-dimensional, not '
'{}-dimensional.'.format(le... |
python round to another significant digit | def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | def round_to_x_digits(number, digits):
"""
Returns 'number' rounded to 'digits' digits.
"""
return round(number * math.pow(10, digits)) / math.pow(10, digits) |
python round to another significant digit | def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | def round_sig(x, sig):
"""Round the number to the specified number of significant figures"""
return round(x, sig - int(floor(log10(abs(x)))) - 1) |
python round to another significant digit | def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | def round_to_n(x, n):
"""
Round to sig figs
"""
return round(x, -int(np.floor(np.log10(x))) + (n - 1)) |
python round to another significant digit | def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | def specialRound(number, rounding):
"""A method used to round a number in the way that UsefulUtils rounds."""
temp = 0
if rounding == 0:
temp = number
else:
temp = round(number, rounding)
if temp % 1 == 0:
return int(temp)
else:
return float(temp) |
python round to another significant digit | def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | def round_figures(x, n):
"""Returns x rounded to n significant figures."""
return round(x, int(n - math.ceil(math.log10(abs(x))))) |
how to perform outer join python | def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
left_as='left', right_as='right'):
""" Performs a join using the union join function. """
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) | def right_outer(self):
"""
Performs Right Outer Join
:return right_outer: dict
"""
self.get_collections_data()
right_outer_join = self.merge_join_docs(
set(self.collections_data['right'].keys()))
return right_outer_join |
how to perform outer join python | def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
left_as='left', right_as='right'):
""" Performs a join using the union join function. """
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) | def get_join_cols(by_entry):
""" helper function used for joins
builds left and right join list for join function
"""
left_cols = []
right_cols = []
for col in by_entry:
if isinstance(col, str):
left_cols.append(col)
right_cols.append(col)
else:
left_cols.append(col[0])
right... |
how to perform outer join python | def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
left_as='left', right_as='right'):
""" Performs a join using the union join function. """
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) | def _grammatical_join_filter(l, arg=None):
"""
:param l: List of strings to join
:param arg: A pipe-separated list of final_join (" and ") and
initial_join (", ") strings. For example
:return: A string that grammatically concatenates the items in the list.
"""
if not arg:
arg = " and... |
how to perform outer join python | def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
left_as='left', right_as='right'):
""" Performs a join using the union join function. """
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) | def _py2_and_3_joiner(sep, joinable):
"""
Allow '\n'.join(...) statements to work in Py2 and Py3.
:param sep:
:param joinable:
:return:
"""
if ISPY3:
sep = bytes(sep, DEFAULT_ENCODING)
joined = sep.join(joinable)
return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined |
how to perform outer join python | def merge(left, right, how='inner', key=None, left_key=None, right_key=None,
left_as='left', right_as='right'):
""" Performs a join using the union join function. """
return join(left, right, how, key, left_key, right_key,
join_fn=make_union_join(left_as, right_as)) | def join(self):
"""Note that the Executor must be close()'d elsewhere,
or join() will never return.
"""
self.inputfeeder_thread.join()
self.pool.join()
self.resulttracker_thread.join()
self.failuretracker_thread.join() |
how to print first 20 lines in file handling python | def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default |
how to print first 20 lines in file handling python | def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) | def get_lines(handle, line):
"""
Get zero-indexed line from an open file-like.
"""
for i, l in enumerate(handle):
if i == line:
return l |
how to print first 20 lines in file handling python | def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) | def readline( file, skip_blank=False ):
"""Read a line from provided file, skipping any blank or comment lines"""
while 1:
line = file.readline()
#print "every line: %r" % line
if not line: return None
if line[0] != '#' and not ( skip_blank and line.isspace() ):
retu... |
how to print first 20 lines in file handling python | def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) | def getLinesFromLogFile(stream):
"""
Returns all lines written to the passed in stream
"""
stream.flush()
stream.seek(0)
lines = stream.readlines()
return lines |
how to print first 20 lines in file handling python | def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) | def head_and_tail_print(self, n=5):
"""Display the first and last n elements of a DataFrame."""
from IPython import display
display.display(display.HTML(self._head_and_tail_table(n))) |
python scipy sparse matrix | def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP | def is_sparse_vector(x):
""" x is a 2D sparse matrix with it's first shape equal to 1.
"""
return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1 |
python scipy sparse matrix | def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP | def sparse_to_matrix(sparse):
"""
Take a sparse (n,3) list of integer indexes of filled cells,
turn it into a dense (m,o,p) matrix.
Parameters
-----------
sparse: (n,3) int, index of filled cells
Returns
------------
dense: (m,o,p) bool, matrix of filled cells
"""
sparse =... |
python scipy sparse matrix | def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP | def sp_rand(m,n,a):
"""
Generates an mxn sparse 'd' matrix with round(a*m*n) nonzeros.
"""
if m == 0 or n == 0: return spmatrix([], [], [], (m,n))
nnz = min(max(0, int(round(a*m*n))), m*n)
nz = matrix(random.sample(range(m*n), nnz), tc='i')
return spmatrix(normal(nnz,1), nz%m, matrix([int(ii... |
python scipy sparse matrix | def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP | def build_columns(self, X, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse arr... |
python scipy sparse matrix | def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP | def _first_and_last_element(arr):
"""Returns first and last element of numpy array or sparse matrix."""
if isinstance(arr, np.ndarray) or hasattr(arr, 'data'):
# numpy array or sparse matrix with .data attribute
data = arr.data if sparse.issparse(arr) else arr
return data.flat[0], data.f... |
python scipy wav write | def write_wav(path, samples, sr=16000):
"""
Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rat... | def readwav(filename):
"""Read a WAV file and returns the data and sample rate
::
from spectrum.io import readwav
readwav()
"""
from scipy.io.wavfile import read as readwav
samplerate, signal = readwav(filename)
return signal, samplerate |
python scipy wav write | def write_wav(path, samples, sr=16000):
"""
Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rat... | def write_wave(path, audio, sample_rate):
"""Writes a .wav file.
Takes path, PCM audio data, and sample rate.
"""
with contextlib.closing(wave.open(path, 'wb')) as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(sample_rate)
wf.writeframes(audio) |
python scipy wav write | def write_wav(path, samples, sr=16000):
"""
Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rat... | def save_to_16bit_wave_file(fname, sig, rate):
"""
Save a given signal ``sig`` to file ``fname`` as a 16-bit one-channel wave
with the given ``rate`` sample rate.
"""
with closing(wave.open(fname, "wb")) as wave_file:
wave_file.setnchannels(1)
wave_file.setsampwidth(2)
wave_file.setframerate(rate)... |
python scipy wav write | def write_wav(path, samples, sr=16000):
"""
Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rat... | def data_from_file(file):
"""Return (first channel data, sample frequency, sample width) from a .wav
file."""
fp = wave.open(file, 'r')
data = fp.readframes(fp.getnframes())
channels = fp.getnchannels()
freq = fp.getframerate()
bits = fp.getsampwidth()
# Unpack bytes -- warning currentl... |
python scipy wav write | def write_wav(path, samples, sr=16000):
"""
Write to given samples to a wav file.
The samples are expected to be floating point numbers
in the range of -1.0 to 1.0.
Args:
path (str): The path to write the wav to.
samples (np.array): A float array .
sr (int): The sampling rat... | 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 coefficie... |
python see if stdin | def stdin_readable():
"""Determine whether stdin has any data to read."""
if not WINDOWS:
try:
return bool(select([sys.stdin], [], [], 0)[0])
except Exception:
logger.log_exc()
try:
return not sys.stdin.isatty()
except Exception:
logger.log_exc()
... | def _stdin_ready_posix():
"""Return True if there's something to read on stdin (posix version)."""
infds, outfds, erfds = select.select([sys.stdin],[],[],0)
return bool(infds) |
python see if stdin | def stdin_readable():
"""Determine whether stdin has any data to read."""
if not WINDOWS:
try:
return bool(select([sys.stdin], [], [], 0)[0])
except Exception:
logger.log_exc()
try:
return not sys.stdin.isatty()
except Exception:
logger.log_exc()
... | def read_stdin():
""" Read text from stdin, and print a helpful message for ttys. """
if sys.stdin.isatty() and sys.stdout.isatty():
print('\nReading from stdin until end of file (Ctrl + D)...')
return sys.stdin.read() |
python see if stdin | def stdin_readable():
"""Determine whether stdin has any data to read."""
if not WINDOWS:
try:
return bool(select([sys.stdin], [], [], 0)[0])
except Exception:
logger.log_exc()
try:
return not sys.stdin.isatty()
except Exception:
logger.log_exc()
... | def _using_stdout(self):
"""
Return whether the handler is using sys.stdout.
"""
if WINDOWS and colorama:
# Then self.stream is an AnsiToWin32 object.
return self.stream.wrapped is sys.stdout
return self.stream is sys.stdout |
python see if stdin | def stdin_readable():
"""Determine whether stdin has any data to read."""
if not WINDOWS:
try:
return bool(select([sys.stdin], [], [], 0)[0])
except Exception:
logger.log_exc()
try:
return not sys.stdin.isatty()
except Exception:
logger.log_exc()
... | def redirect_std():
"""
Connect stdin/stdout to controlling terminal even if the scripts input and output
were redirected. This is useful in utilities based on termenu.
"""
stdin = sys.stdin
stdout = sys.stdout
if not sys.stdin.isatty():
sys.stdin = open_raw("/dev/tty", "r", 0)
i... |
python see if stdin | def stdin_readable():
"""Determine whether stdin has any data to read."""
if not WINDOWS:
try:
return bool(select([sys.stdin], [], [], 0)[0])
except Exception:
logger.log_exc()
try:
return not sys.stdin.isatty()
except Exception:
logger.log_exc()
... | def _read_stdin():
"""
Generator for reading from standard input in nonblocking mode.
Other ways of reading from ``stdin`` in python waits, until the buffer is
big enough, or until EOF character is sent.
This functions yields immediately after each line.
"""
line = sys.stdin.readline()
... |
python select columns with condition | def selecttrue(table, field, complement=False):
"""Select rows where the given field evaluates `True`."""
return select(table, field, lambda v: bool(v), complement=complement) | def select_if(df, fun):
"""Selects columns where fun(ction) is true
Args:
fun: a function that will be applied to columns
"""
def _filter_f(col):
try:
return fun(df[col])
except:
return False
cols = list(filter(_filter_f, df.columns))
return df[c... |
python select columns with condition | def selecttrue(table, field, complement=False):
"""Select rows where the given field evaluates `True`."""
return select(table, field, lambda v: bool(v), complement=complement) | def selectnotin(table, field, value, complement=False):
"""Select rows where the given field is not a member of the given value."""
return select(table, field, lambda v: v not in value,
complement=complement) |
python select columns with condition | def selecttrue(table, field, complement=False):
"""Select rows where the given field evaluates `True`."""
return select(table, field, lambda v: bool(v), complement=complement) | def remove_rows_matching(df, column, match):
"""
Return a ``DataFrame`` with rows where `column` values match `match` are removed.
The selected `column` series of values from the supplied Pandas ``DataFrame`` is compared
to `match`, and those rows that match are removed from the DataFrame.
:param ... |
python select columns with condition | def selecttrue(table, field, complement=False):
"""Select rows where the given field evaluates `True`."""
return select(table, field, lambda v: bool(v), complement=complement) | def apply_filters(df, filters):
"""Basic filtering for a dataframe."""
idx = pd.Series([True]*df.shape[0])
for k, v in list(filters.items()):
if k not in df.columns:
continue
idx &= (df[k] == v)
return df.loc[idx] |
python select columns with condition | def selecttrue(table, field, complement=False):
"""Select rows where the given field evaluates `True`."""
return select(table, field, lambda v: bool(v), complement=complement) | def selectin(table, field, value, complement=False):
"""Select rows where the given field is a member of the given value."""
return select(table, field, lambda v: v in value,
complement=complement) |
how to read yaml file from python | def load_yaml(filepath):
"""Convenience function for loading yaml-encoded data from disk."""
with open(filepath) as f:
txt = f.read()
return yaml.load(txt) | def load_yaml_file(file_path: str):
"""Load a YAML file from path"""
with codecs.open(file_path, 'r') as f:
return yaml.safe_load(f) |
how to read yaml file from python | def load_yaml(filepath):
"""Convenience function for loading yaml-encoded data from disk."""
with open(filepath) as f:
txt = f.read()
return yaml.load(txt) | def getYamlDocument(filePath):
"""
Return a yaml file's contents as a dictionary
"""
with open(filePath) as stream:
doc = yaml.load(stream)
return doc |
how to read yaml file from python | def load_yaml(filepath):
"""Convenience function for loading yaml-encoded data from disk."""
with open(filepath) as f:
txt = f.read()
return yaml.load(txt) | def load_yaml(file):
"""If pyyaml > 5.1 use full_load to avoid warning"""
if hasattr(yaml, "full_load"):
return yaml.full_load(file)
else:
return yaml.load(file) |
how to read yaml file from python | def load_yaml(filepath):
"""Convenience function for loading yaml-encoded data from disk."""
with open(filepath) as f:
txt = f.read()
return yaml.load(txt) | def load_yaml(yaml_file: str) -> Any:
"""
Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list
"""
with open(yaml_file, 'r') as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader) |
how to read yaml file from python | def load_yaml(filepath):
"""Convenience function for loading yaml-encoded data from disk."""
with open(filepath) as f:
txt = f.read()
return yaml.load(txt) | def _ParseYamlFromFile(filedesc):
"""Parses given YAML file."""
content = filedesc.read()
return yaml.Parse(content) or collections.OrderedDict() |
python set the current file | def load_file(self, filename):
"""Read in file contents and set the current string."""
with open(filename, 'r') as sourcefile:
self.set_string(sourcefile.read()) | def in_directory(path):
"""Context manager (with statement) that changes the current directory
during the context.
"""
curdir = os.path.abspath(os.curdir)
os.chdir(path)
yield
os.chdir(curdir) |
python set the current file | def load_file(self, filename):
"""Read in file contents and set the current string."""
with open(filename, 'r') as sourcefile:
self.set_string(sourcefile.read()) | def set_history_file(self, path):
"""Set path to history file. "" produces no file."""
if path:
self.history = prompt_toolkit.history.FileHistory(fixpath(path))
else:
self.history = prompt_toolkit.history.InMemoryHistory() |
python set the current file | def load_file(self, filename):
"""Read in file contents and set the current string."""
with open(filename, 'r') as sourcefile:
self.set_string(sourcefile.read()) | def dir_path(dir):
"""with dir_path(path) to change into a directory."""
old_dir = os.getcwd()
os.chdir(dir)
yield
os.chdir(old_dir) |
python set the current file | def load_file(self, filename):
"""Read in file contents and set the current string."""
with open(filename, 'r') as sourcefile:
self.set_string(sourcefile.read()) | def writefile(openedfile, newcontents):
"""Set the contents of a file."""
openedfile.seek(0)
openedfile.truncate()
openedfile.write(newcontents) |
python set the current file | def load_file(self, filename):
"""Read in file contents and set the current string."""
with open(filename, 'r') as sourcefile:
self.set_string(sourcefile.read()) | def set_executable(filename):
"""Set the exectuable bit on the given filename"""
st = os.stat(filename)
os.chmod(filename, st.st_mode | stat.S_IEXEC) |
python set to value of dictionary if exists else defaul | def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct | def set_if_empty(self, param, default):
""" Set the parameter to the default if it doesn't exist """
if not self.has(param):
self.set(param, default) |
python set to value of dictionary if exists else defaul | def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct | def dict_of_sets_add(dictionary, key, value):
# type: (DictUpperBound, Any, Any) -> None
"""Add value to a set in a dictionary by key
Args:
dictionary (DictUpperBound): Dictionary to which to add values
key (Any): Key within dictionary
value (Any): Value to add to set in dictionary
... |
python set to value of dictionary if exists else defaul | def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct | def setdefault(obj, field, default):
"""Set an object's field to default if it doesn't have a value"""
setattr(obj, field, getattr(obj, field, default)) |
python set to value of dictionary if exists else defaul | def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct | def update(self, dictionary=None, **kwargs):
"""
Adds/overwrites all the keys and values from the dictionary.
"""
if not dictionary == None: kwargs.update(dictionary)
for k in list(kwargs.keys()): self[k] = kwargs[k] |
python set to value of dictionary if exists else defaul | def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct | def call_fset(self, obj, value) -> None:
"""Store the given custom value and call the setter function."""
vars(obj)[self.name] = self.fset(obj, value) |
python set type to string | def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | def _cast_to_type(self, value):
""" Convert the value to its string representation"""
if isinstance(value, str) or value is None:
return value
return str(value) |
python set type to string | def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | def visit_Str(self, node):
""" Set the pythonic string type. """
self.result[node] = self.builder.NamedType(pytype_to_ctype(str)) |
python set type to string | def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | def getTypeStr(_type):
r"""Gets the string representation of the given type.
"""
if isinstance(_type, CustomType):
return str(_type)
if hasattr(_type, '__name__'):
return _type.__name__
return '' |
python set type to string | def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | def force_to_string(unknown):
"""
converts and unknown type to string for display purposes.
"""
result = ''
if type(unknown) is str:
result = unknown
if type(unknown) is int:
result = str(unknown)
if type(unknown) is float:
result = str(unknown)
if type(unkno... |
python set type to string | def check_str(obj):
""" Returns a string for various input types """
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | def to_str(obj):
"""Attempts to convert given object to a string object
"""
if not isinstance(obj, str) and PY3 and isinstance(obj, bytes):
obj = obj.decode('utf-8')
return obj if isinstance(obj, string_types) else str(obj) |
how to retreive json data from dynamic url using python | def get_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the
object.
"""
response = urlopen(url)
data = response.read().decode('utf-8')
return json.loads(data) | def get(url):
"""Recieving the JSON file from uulm"""
response = urllib.request.urlopen(url)
data = response.read()
data = data.decode("utf-8")
data = json.loads(data)
return data |
how to retreive json data from dynamic url using python | def get_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the
object.
"""
response = urlopen(url)
data = response.read().decode('utf-8')
return json.loads(data) | def process_response(self, response):
"""
Load a JSON response.
:param Response response: The HTTP response.
:return dict: The JSON-loaded content.
"""
if response.status_code != 200:
raise TwilioException('Unable to fetch page', response)
return jso... |
how to retreive json data from dynamic url using python | def get_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the
object.
"""
response = urlopen(url)
data = response.read().decode('utf-8')
return json.loads(data) | def read_json(location):
"""Open and load JSON from file.
location (Path): Path to JSON file.
RETURNS (dict): Loaded JSON content.
"""
location = ensure_path(location)
with location.open('r', encoding='utf8') as f:
return ujson.load(f) |
how to retreive json data from dynamic url using python | def get_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the
object.
"""
response = urlopen(url)
data = response.read().decode('utf-8')
return json.loads(data) | def load_parameters(self, source):
"""For JSON, the source it the file path"""
with open(source) as parameters_source:
return json.loads(parameters_source.read()) |
how to retreive json data from dynamic url using python | def get_jsonparsed_data(url):
"""Receive the content of ``url``, parse it as JSON and return the
object.
"""
response = urlopen(url)
data = response.read().decode('utf-8')
return json.loads(data) | 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 sine wave with periods | 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) | def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE):
"""
Returns value of a sine wave at a given frequency and framerate
for a given sample i
"""
omega = 2.0 * pi * float(frequency)
sine = sin(omega * (float(i) / float(framerate)))
return float(amplitude) * sine |
python sine wave with periods | 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) | def constant(times: np.ndarray, amp: complex) -> np.ndarray:
"""Continuous constant pulse.
Args:
times: Times to output pulse for.
amp: Complex pulse amplitude.
"""
return np.full(len(times), amp, dtype=np.complex_) |
python sine wave with periods | 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) | def asin(x):
"""
Inverse sine
"""
if isinstance(x, UncertainFunction):
mcpts = np.arcsin(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.arcsin(x) |
python sine wave with periods | 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) | def fourier_series(x, f, n=0):
"""
Returns a symbolic fourier series of order `n`.
:param n: Order of the fourier series.
:param x: Independent variable
:param f: Frequency of the fourier series
"""
# Make the parameter objects for all the terms
a0, *cos_a = parameters(','.join(['a{}'.f... |
python sine wave with periods | 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) | def sinwave(n=4,inc=.25):
"""
Returns a DataFrame with the required format for
a surface (sine wave) plot
Parameters:
-----------
n : int
Ranges for X and Y axis (-n,n)
n_y : int
Size of increment along the axis
"""
x=np.arange(-n,n,inc)
y=np.arange(-n,n,inc)
X,Y=np.meshgrid(x,y)
R = np.sqrt(X**2... |
how to run flake8 python | def lint(args):
"""Run lint checks using flake8."""
application = get_current_application()
if not args:
args = [application.name, 'tests']
args = ['flake8'] + list(args)
run.main(args, standalone_mode=False) | def rpc_fix_code_with_black(self, source, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
source = get_source(source)
return fix_code_with_black(source, directory) |
how to run flake8 python | def lint(args):
"""Run lint checks using flake8."""
application = get_current_application()
if not args:
args = [application.name, 'tests']
args = ['flake8'] + list(args)
run.main(args, standalone_mode=False) | def cpp_checker(code, working_directory):
"""Return checker."""
return gcc_checker(code, '.cpp',
[os.getenv('CXX', 'g++'), '-std=c++0x'] + INCLUDE_FLAGS,
working_directory=working_directory) |
how to run flake8 python | def lint(args):
"""Run lint checks using flake8."""
application = get_current_application()
if not args:
args = [application.name, 'tests']
args = ['flake8'] + list(args)
run.main(args, standalone_mode=False) | def autobuild_python_test(path):
"""Add pytest unit tests to be built as part of build/test/output."""
env = Environment(tools=[])
target = env.Command(['build/test/output/pytest.log'], [path],
action=env.Action(run_pytest, "Running python unit tests"))
env.AlwaysBuild(target) |
how to run flake8 python | def lint(args):
"""Run lint checks using flake8."""
application = get_current_application()
if not args:
args = [application.name, 'tests']
args = ['flake8'] + list(args)
run.main(args, standalone_mode=False) | def clean():
"""clean - remove build artifacts."""
run('rm -rf build/')
run('rm -rf dist/')
run('rm -rf puzzle.egg-info')
run('find . -name __pycache__ -delete')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name *~ -delete')
log.info('cleaned up') |
how to run flake8 python | def lint(args):
"""Run lint checks using flake8."""
application = get_current_application()
if not args:
args = [application.name, 'tests']
args = ['flake8'] + list(args)
run.main(args, standalone_mode=False) | def clean(dry_run='n'):
"""Wipes compiled and cached python files. To simulate: pynt clean[dry_run=y]"""
file_patterns = ['*.pyc', '*.pyo', '*~']
dir_patterns = ['__pycache__']
recursive_pattern_delete(project_paths.root, file_patterns, dir_patterns, dry_run=bool(dry_run.lower() == 'y')) |
how to run python script in deburger mode | def stub_main():
"""setuptools blah: it still can't run a module as a script entry_point"""
from google.apputils import run_script_module
import butcher.main
run_script_module.RunScriptModule(butcher.main) | def page_guiref(arg_s=None):
"""Show a basic reference about the GUI Console."""
from IPython.core import page
page.page(gui_reference, auto_html=True) |
how to run python script in deburger mode | def stub_main():
"""setuptools blah: it still can't run a module as a script entry_point"""
from google.apputils import run_script_module
import butcher.main
run_script_module.RunScriptModule(butcher.main) | def demo(quiet, shell, speed, prompt, commentecho):
"""Run a demo doitlive session."""
run(
DEMO,
shell=shell,
speed=speed,
test_mode=TESTING,
prompt_template=prompt,
quiet=quiet,
commentecho=commentecho,
) |
how to run python script in deburger mode | def stub_main():
"""setuptools blah: it still can't run a module as a script entry_point"""
from google.apputils import run_script_module
import butcher.main
run_script_module.RunScriptModule(butcher.main) | def _handle_shell(self,cfg_file,*args,**options):
"""Command 'supervisord shell' runs the interactive command shell."""
args = ("--interactive",) + args
return supervisorctl.main(("-c",cfg_file) + args) |
how to run python script in deburger mode | def stub_main():
"""setuptools blah: it still can't run a module as a script entry_point"""
from google.apputils import run_script_module
import butcher.main
run_script_module.RunScriptModule(butcher.main) | def IPYTHON_MAIN():
"""Decide if the Ipython command line is running code."""
import pkg_resources
runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
return (
getattr(runner_frame, "function", None)
== pkg_resources.load_entry_point("ipython", "console_scripts", "ipython"... |
how to run python script in deburger mode | def stub_main():
"""setuptools blah: it still can't run a module as a script entry_point"""
from google.apputils import run_script_module
import butcher.main
run_script_module.RunScriptModule(butcher.main) | def bash(filename):
"""Runs a bash script in the local directory"""
sys.stdout.flush()
subprocess.call("bash {}".format(filename), shell=True) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.