query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
how to empty array
python
def emptyArray(key, add_label=None): """An array that starts empty""" result = { 'key': key, 'startEmpty': True } if add_label is not None: result['add'] = add_label result['style'] = {'add': 'btn-success'} return result
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/schemata/defaultform.py#L165-L175
how to empty array
python
def drop_empty(arr): """ Drop empty array element :param arr: :return: """ return [x for x in arr if not isinstance(x, list) or len(x) > 0]
https://github.com/crocs-muni/roca/blob/74ad6ce63c428d83dcffce9c5e26ef7b9e30faa5/roca/detect.py#L161-L167
how to empty array
python
def isEmpty(self): """ Is a given array, string, or object empty? An "empty" object has no enumerable own-properties. """ if self.obj is None: return True if self._clean.isString(): ret = self.obj.strip() is "" elif self._clean.isDict(): ret = len(self.obj.keys()) == 0 else: ret = len(self.obj) == 0 return self._wrap(ret)
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L1055-L1068
how to empty array
python
def empty(self, shape, complex=False): """ A wrapper around np.empty which automatically sets the correct type and returns an empty array. :param shape: The shape of the array in np.empty format """ if complex: return np.empty(shape, dtype=self.complex, order=self.order) return np.empty(shape, dtype=self.float, order=self.order)
https://github.com/krischer/mtspec/blob/06561b6370f13fcb2e731470ba0f7314f4b2362d/mtspec/multitaper.py#L775-L784
how to empty array
python
def write_array_empty(self, key, value): """ write a 0-len array """ # ugly hack for length 0 axes arr = np.empty((1,) * value.ndim) self._handle.create_array(self.group, key, arr) getattr(self.group, key)._v_attrs.value_type = str(value.dtype) getattr(self.group, key)._v_attrs.shape = value.shape
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/pytables.py#L2702-L2709
how to empty array
python
def empty(self, name, **kwargs): """Create an array. Keyword arguments as per :func:`zarr.creation.empty`.""" return self._write_op(self._empty_nosync, name, **kwargs)
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L858-L861
how to empty array
python
def empty(self): """ Clear out the buffer and return all data that was in it. :return: any data that was in the buffer prior to clearing it out, as a `str` """ self._lock.acquire() try: out = self._buffer_tobytes() del self._buffer[:] if (self._event is not None) and not self._closed: self._event.clear() return out finally: self._lock.release()
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L180-L196
how to empty array
python
def unpack_nullterm_array(array): """Takes a null terminated array, copies the values into a list and frees each value and the list. """ addrs = cast(array, POINTER(ctypes.c_void_p)) l = [] i = 0 value = array[i] while value: l.append(value) free(addrs[i]) i += 1 value = array[i] free(addrs) return l
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/clib/glib.py#L300-L315
how to empty array
python
def empty(shape, dtype=None, **kwargs): """Create an array of given shape and type, without initializing entries. Args: shape (sequence of ints): 2D shape of the array. dtype (data-type, optional): Desired data-type for the array. kwargs (optional): Other arguments of the array (*coords, attrs, and name). Returns: array (decode.array): Decode array without initializing entries. """ data = np.empty(shape, dtype) return dc.array(data, **kwargs)
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L109-L121
how to empty array
python
def make_empty_table(row_count, column_count): """ Make an empty table Parameters ---------- row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell will be an empty str ('') """ table = [] while row_count > 0: row = [] for column in range(column_count): row.append('') table.append(row) row_count -= 1 return table
https://github.com/doakey3/DashTable/blob/744cfb6a717fa75a8092c83ebcd49b2668023681/dashtable/dashutils/make_empty_table.py#L1-L24
how to empty array
python
def _create_empty_array(self, frames, always_2d, dtype): """Create an empty array with appropriate shape.""" import numpy as np if always_2d or self.channels > 1: shape = frames, self.channels else: shape = frames, return np.empty(shape, dtype, order='C')
https://github.com/bastibe/SoundFile/blob/161e930da9c9ea76579b6ee18a131e10bca8a605/soundfile.py#L1284-L1291
how to empty array
python
def clean_empty(self, d=DEFAULT): """Returns a copy of d without empty leaves. https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict/35263074 """ if d is DEFAULT: d = self if isinstance(d, list): return [v for v in (self.clean_empty(v) for v in d) if v or v == 0] elif isinstance(d, type(self)): return type(self)({k: v for k, v in ((k, self.clean_empty(v)) for k, v in d.items()) if v or v == 0}) elif isinstance(d, dict): return {k: v for k, v in ((k, self.clean_empty(v)) for k, v in d.items()) if v or v == 0} return d
https://github.com/Enteee/pdml2flow/blob/bc9efe379b0b2406bfbbbd8e0f678b1f63805c66/pdml2flow/autovivification.py#L21-L34
how to empty array
python
def _free_array(self, handle: int): """Frees the memory for the array with the given handle. Args: handle: The handle of the array whose memory should be freed. This handle must come from the _create_array method. """ with self._lock: if self._arrays[handle] is not None: self._arrays[handle] = None self._count -= 1
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/mem_manager.py#L102-L112
how to empty array
python
def empty(stype, shape, ctx=None, dtype=None): """Returns a new array of given shape and type, without initializing entries. Parameters ---------- stype: string The storage type of the empty array, such as 'row_sparse', 'csr', etc shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the current default context). dtype : str or numpy.dtype, optional An optional value type (default is `float32`). Returns ------- CSRNDArray or RowSparseNDArray A created array. """ if isinstance(shape, int): shape = (shape, ) if ctx is None: ctx = current_context() if dtype is None: dtype = mx_real_t assert(stype is not None) if stype in ('csr', 'row_sparse'): return zeros(stype, shape, ctx=ctx, dtype=dtype) else: raise Exception("unknown stype : " + str(stype))
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L1547-L1576
how to empty array
python
def empty_like(array, dtype=None, keepmeta=True): """Create an array of empty with the same shape and type as the input array. Args: array (xarray.DataArray): The shape and data-type of it define these same attributes of the output array. dtype (data-type, optional): If spacified, this function overrides the data-type of the output array. keepmeta (bool, optional): Whether *coords, attrs, and name of the input array are kept in the output one. Default is True. Returns: array (decode.array): Decode array without initializing entries. """ if keepmeta: return dc.empty(array.shape, dtype, tcoords=array.dca.tcoords, chcoords=array.dca.chcoords, scalarcoords=array.dca.scalarcoords, attrs=array.attrs, name=array.name ) else: return dc.empty(array.shape, dtype)
https://github.com/deshima-dev/decode/blob/e789e174cd316e7ec8bc55be7009ad35baced3c0/decode/core/array/functions.py#L185-L205
how to empty array
python
def _is_empty(self): """ True if this cell contains only a single empty ``<w:p>`` element. """ block_items = list(self.iter_block_items()) if len(block_items) > 1: return False p = block_items[0] # cell must include at least one <w:p> element if len(p.r_lst) == 0: return True return False
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/oxml/table.py#L557-L567
how to empty array
python
def empty(self, start=None, stop=None): """Empty the range from start to stop. Like delete, but no Error is raised if the entire range isn't mapped. """ self.set(NOT_SET, start=start, stop=stop)
https://github.com/mlenzen/collections-extended/blob/ee9e86f6bbef442dbebcb3a5970642c5c969e2cf/collections_extended/range_map.py#L348-L353
how to empty array
python
def vstack_empty(tup): """ A thin wrapper for numpy.vstack that ignores empty lists. Parameters ------------ tup: tuple or list of arrays with the same number of columns Returns ------------ stacked: (n,d) array, with same number of columns as constituent arrays. """ # filter out empty arrays stackable = [i for i in tup if len(i) > 0] # if we only have one array just return it if len(stackable) == 1: return np.asanyarray(stackable[0]) # if we have nothing return an empty numpy array elif len(stackable) == 0: return np.array([]) # otherwise just use vstack as normal return np.vstack(stackable)
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/util.py#L1777-L1799
how to empty array
python
def remove_arrays(code, count=1): """removes arrays and replaces them with ARRAY_LVALS returns new code and replacement dict *NOTE* has to be called AFTER remove objects""" res = '' last = '' replacements = {} for e in bracket_split(code, ['[]']): if e[0] == '[': if is_array(last): name = ARRAY_LVAL % count res += ' ' + name replacements[name] = e count += 1 else: # pseudo array. But pseudo array can contain true array. for example a[['d'][3]] has 2 pseudo and 1 true array cand, new_replacements, count = remove_arrays(e[1:-1], count) res += '[%s]' % cand replacements.update(new_replacements) else: res += e last = e return res, replacements, count
https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/objects.py#L129-L150
how to empty array
python
def is_empty(self): """Asserts that val is empty.""" if len(self.val) != 0: if isinstance(self.val, str_types): self._err('Expected <%s> to be empty string, but was not.' % self.val) else: self._err('Expected <%s> to be empty, but was not.' % self.val) return self
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L348-L355
how to empty array
python
def newarray(self, length, value=0): """Initialise empty row""" if self.bitdepth > 8: return array('H', [value] * length) else: return bytearray([value] * length)
https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L1604-L1609
how to empty array
python
def check_array(array): "Converts to flattened numpy arrays and ensures its not empty." if len(array) < 1: raise ValueError('Input array is empty! Must have atleast 1 element.') return np.ma.masked_invalid(array).flatten()
https://github.com/raamana/hiwenet/blob/b12699b3722fd0a6a835e7d7ca4baf58fb181809/hiwenet/utils.py#L72-L78
how to empty array
python
def emptyTrash(self): """ If a section has items in the Trash, use this option to empty the Trash. """ key = '/library/sections/%s/emptyTrash' % self.key self._server.query(key, method=self._server._session.put)
https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L413-L416
how to empty array
python
def empty(self): """Removes all children from the list""" self._selected_item = None self._selected_key = None super(ListView, self).empty()
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2077-L2081
how to empty array
python
def unwind(self, path, include_array_index=None, preserve_null_and_empty_arrays=False): """ Adds an unwind stage to deconstruct an array :param path: Field path to an array field :param include_array_index: The name of a new field to hold the array index of the element. :param preserve_null_and_empty_arrays: If true, if the path is null, missing, or an empty array, $unwind outputs the document. If false, $unwind does not output a document if the path is null, missing, or an empty array. :return: The current object """ unwind_query = {} unwind_query['$unwind'] = path if path[0] == '$' else '$' + path if include_array_index: unwind_query['includeArrayIndex'] = include_array_index if preserve_null_and_empty_arrays: unwind_query['preserveNullAndEmptyArrays'] = True self._q.append(unwind_query) return self
https://github.com/MosesSymeonidis/aggregation_builder/blob/a1f4b580401d400c53206e9c020e413166254274/aggregation_builder/query_builder.py#L112-L130
how to empty array
python
def is_not_empty(self, value, strict=False): """if value is not empty""" value = stringify(value) if value is not None: return self.shout('Value %r is empty', strict, value)
https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/check.py#L18-L23
how to empty array
python
def to_nullable_array(value): """ Converts value into array object. Single values are converted into arrays with a single element. :param value: the value to convert. :return: array object or None when value is None. """ # Shortcuts if value == None: return None if type(value) == list: return value if type(value) in [tuple, set]: return list(value) return [value]
https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/convert/ArrayConverter.py#L23-L41
how to empty array
python
def without(self, *values): """ Return a version of the array that does not contain the specified value(s). """ if self._clean.isDict(): newlist = {} for i, k in enumerate(self.obj): # if k not in values: # use indexof to check identity if _(values).indexOf(k) is -1: newlist.set(k, self.obj[k]) else: newlist = [] for i, v in enumerate(self.obj): # if v not in values: # use indexof to check identity if _(values).indexOf(v) is -1: newlist.append(v) return self._wrap(newlist)
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L561-L579
how to empty array
python
def empty(self, return_cards=False): """ Empties the stack, removing all cards from it, and returns them. :arg bool return_cards: Whether or not to return the cards. :returns: If ``return_cards=True``, a list containing the cards removed from the Stack. """ cards = list(self.cards) self.cards = [] if return_cards: return cards
https://github.com/Trebek/pydealer/blob/2ac583dd8c55715658c740b614387775f4dda333/pydealer/stack.py#L326-L342
how to empty array
python
def clean_empty_string(obj): """ Replace empty form values with None, since the is_html_input() check in Field won't work after we convert to JSON. (FIXME: What about allow_blank=True?) """ if obj == '': return None if isinstance(obj, list): return [ None if item == '' else item for item in obj ] if isinstance(obj, dict): for key in obj: obj[key] = clean_empty_string(obj[key]) return obj
https://github.com/wq/html-json-forms/blob/4dfbfabeee924ba832a7a387ab3b02b6d51d9701/html_json_forms/utils.py#L285-L301
how to empty array
python
def save_array(self): """Save array""" title = _( "Save array") if self.array_filename is None: self.array_filename = getcwd_or_home() self.redirect_stdio.emit(False) filename, _selfilter = getsavefilename(self, title, self.array_filename, _("NumPy arrays")+" (*.npy)") self.redirect_stdio.emit(True) if filename: self.array_filename = filename data = self.delegate.get_value( self.currentIndex() ) try: import numpy as np np.save(self.array_filename, data) except Exception as error: QMessageBox.critical(self, title, _("<b>Unable to save array</b>" "<br><br>Error message:<br>%s" ) % str(error))
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L1157-L1177
how to empty array
python
def uniq(self, isSorted=False, iterator=None): """ Produce a duplicate-free version of the array. If the array has already been sorted, you have the option of using a faster algorithm. Aliased as `unique`. """ ns = self.Namespace() ns.results = [] ns.array = self.obj initial = self.obj if iterator is not None: initial = _(ns.array).map(iterator) def by(memo, value, index): if ((_.last(memo) != value or not len(memo)) if isSorted else not _.include(memo, value)): memo.append(value) ns.results.append(ns.array[index]) return memo ret = _.reduce(initial, by) return self._wrap(ret)
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L597-L619
how to empty array
python
def _ensure_array(self, key, value): """Ensure an array field""" if key not in self._json_dict: self._json_dict[key] = [] self._size += 2 # brackets self._ensure_field(key) if len(self._json_dict[key]) > 0: # this array already has an entry, so add comma and space self._size += 2 if isinstance(value, str): self._size += 2 # quotes self._size += len(str(value)) self._json_dict[key].append(value)
https://github.com/kentik/kentikapi-py/blob/aa94c0b7eaf88409818b97967d7293e309e11bab/kentikapi/v5/tagging.py#L164-L180
how to empty array
python
def free(self): """Free the underlying C array""" if self._ptr is None: return Gauged.array_free(self.ptr) FloatArray.ALLOCATIONS -= 1 self._ptr = None
https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/structures/float_array.py#L59-L65
how to empty array
python
def empty(self): ''' Method to empty attributes, particularly for use when object is deleted but remains as variable ''' self.resource = None self.delivery = None self.data = None self.stream = False self.mimetype = None self.location = None
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L1686-L1698
how to empty array
python
def _clear_empty_values(args): ''' Scrap junk data from a dict. ''' result = {} for param in args: if args[param] is not None: result[param] = args[param] return result
https://github.com/xmunoz/sodapy/blob/dad2ca9560cde0acb03bdb4423260e891ca40d7b/sodapy/__init__.py#L534-L542
how to empty array
python
def erase(self): """Erases the flash contents of the device. This erases the flash memory of the target device. If this method fails, the device may be left in an inoperable state. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes erased. """ try: # This has to be in a try-catch, as the device may not be in a # state where it can halt, but we still want to try and erase. if not self.halted(): self.halt() except errors.JLinkException: # Can't halt, so just continue to erasing. pass res = self._dll.JLINK_EraseChip() if res < 0: raise errors.JLinkEraseException(res) return res
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L1920-L1945
how to empty array
python
def make2d(array, cols=None, dtype=None): ''' Make a 2D array from an array of arrays. The `cols' and `dtype' arguments can be omitted if the array is not empty. ''' if not len(array): if cols is None or dtype is None: raise RuntimeError( "cols and dtype must be specified for empty array" ) return _np.empty((0, cols), dtype=dtype) return _np.vstack(array)
https://github.com/dranjan/python-plyfile/blob/9f8e8708d3a071229cf292caae7d13264e11c88b/plyfile.py#L91-L103
how to empty array
python
def flush(self): """Flush tables and arrays to disk""" self.log.info('Flushing tables and arrays to disk...') for tab in self._tables.values(): tab.flush() self._write_ndarrays_cache_to_disk()
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/hdf5.py#L450-L455
how to empty array
python
def not_empty(value, allow_empty = False, **kwargs): """Validate that ``value`` is not empty. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` """ if not value and allow_empty: return None elif not value: raise errors.EmptyValueError('value was empty') return value
https://github.com/insightindustry/validator-collection/blob/8c8047a0fa36cc88a021771279898278c4cc98e3/validator_collection/validators.py#L343-L365
how to empty array
python
def empty(cls): """ Returns an empty set. An empty set is unbounded and only contain the empty set. >>> intrange.empty() in intrange.empty() True It is unbounded but the boundaries are not infinite. Its boundaries are returned as ``None``. Every set contains the empty set. """ self = cls.__new__(cls) self._range = _empty_internal_range return self
https://github.com/runfalk/spans/blob/59ed73407a569c3be86cfdb4b8f438cb8c794540/spans/types.py#L92-L106
how to empty array
python
def dump_array( the_array, write, array_name ): """dumps a given encoding""" write( " static const unsigned char " + array_name + "[" + repr( len( the_array ) ) + "L] =\n" ) write( " {\n" ) line = "" comma = " " col = 0 for value in the_array: line += comma line += "%3d" % ord( value ) comma = "," col += 1 if col == 16: col = 0 comma = ",\n " if len( line ) > 1024: write( line ) line = "" write( line + "\n };\n\n\n" )
https://github.com/aholkner/bacon/blob/edf3810dcb211942d392a8637945871399b0650d/native/Vendor/FreeType/src/tools/glnames.py#L5210-L5235
how to empty array
python
def _validate_empty(self, empty, field, value): """ {'type': 'boolean'} """ if isinstance(value, Iterable) and len(value) == 0: self._drop_remaining_rules( 'allowed', 'forbidden', 'items', 'minlength', 'maxlength', 'regex', 'validator') if not empty: self._error(field, errors.EMPTY_NOT_ALLOWED)
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/cerberus/validator.py#L1005-L1012
how to empty array
python
def truncate(self, table): """Empty a table by deleting all of its rows.""" if isinstance(table, (list, set, tuple)): for t in table: self._truncate(t) else: self._truncate(table)
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/remove.py#L5-L11
how to empty array
python
def erase_all(self): """! @brief Erase all the flash. @exception FlashEraseFailure """ assert self._active_operation == self.Operation.ERASE assert self.is_erase_all_supported # update core register to execute the erase_all subroutine result = self._call_function_and_wait(self.flash_algo['pc_eraseAll']) # check the return code if result != 0: raise FlashEraseFailure('erase_all error: %i' % result, result_code=result)
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/flash/flash.py#L324-L338
how to empty array
python
def clear(self): ''' Clear the undo list. ''' self._undos.clear() self._redos.clear() self._savepoint = None self._receiver = self._undos
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/undo.py#L246-L251
how to empty array
python
def empty_like(array, dtype=None): """ Create a shared memory array from the shape of array. """ array = numpy.asarray(array) if dtype is None: dtype = array.dtype return anonymousmemmap(array.shape, dtype)
https://github.com/rainwoodman/sharedmem/blob/b23e59c1ed0e28f7b6c96c17a04d55c700e06e3a/sharedmem/sharedmem.py#L785-L791
how to empty array
python
def isempty(result): ''' Finds out if a scraping result should be considered empty. ''' if isinstance(result, list): for element in result: if isinstance(element, list): if not isempty(element): return False else: if element is not None: return False else: if result is not None: return False return True
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/utils.py#L6-L20
how to empty array
python
def strip_empty_values(obj): """Recursively strips empty values.""" if isinstance(obj, dict): new_obj = {} for key, val in obj.items(): new_val = strip_empty_values(val) if new_val is not None: new_obj[key] = new_val return new_obj or None elif isinstance(obj, (list, tuple, set)): new_obj = [] for val in obj: new_val = strip_empty_values(val) if new_val is not None: new_obj.append(new_val) return type(obj)(new_obj) or None elif obj or obj is False or obj == 0: return obj else: return None
https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L145-L164
how to empty array
python
def Flush(self): """Flush all items from cache.""" while self._age: node = self._age.PopLeft() self.KillObject(node.data) self._hash = dict()
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/utils.py#L358-L364
how to empty array
python
def clear_list_value(self, value): """ Clean the argument value to eliminate None or Falsy values if needed. """ # Don't go any further: this value is empty. if not value: return self.empty_value # Clean empty items if wanted if self.clean_empty: value = [v for v in value if v] return value or self.empty_value
https://github.com/peopledoc/django-agnocomplete/blob/9bf21db2f2036ba5059b843acd32902a09192053/agnocomplete/fields.py#L163-L173
how to empty array
python
def empty(cls: Type[BoardT], *, chess960: bool = False) -> BoardT: """Creates a new empty board. Also see :func:`~chess.Board.clear()`.""" return cls(None, chess960=chess960)
https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3422-L3424
how to empty array
python
def make_empty(self, axes=None): """ return an empty BlockManager with the items axis of len 0 """ if axes is None: axes = [ensure_index([])] + [ensure_index(a) for a in self.axes[1:]] # preserve dtype if possible if self.ndim == 1: blocks = np.array([], dtype=self.array_dtype) else: blocks = [] return self.__class__(blocks, axes)
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/internals/managers.py#L120-L131
how to empty array
python
def remove_empty(self, tag): """ Remove non-self-closing tags with no children *and* no content. """ has_children = len(tag.contents) has_text = len(list(tag.stripped_strings)) if not has_children and not has_text and not tag.is_empty_element: tag.extract()
https://github.com/nprapps/copydoc/blob/e1ab09b287beb0439748c319cf165cbc06c66624/copydoc.py#L155-L162
how to empty array
python
def set_empty(self, row, column): """Keep one of the subplots completely empty. :param row,column: specify the subplot. """ subplot = self.get_subplot_at(row, column) subplot.set_empty()
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/multi_plot.py#L77-L84
how to empty array
python
def is_empty(self): ''' Returns: bool: Check if the index is empty. ''' return all(all(index[r].is_empty() for r in index) for index in self.indexes)
https://github.com/ekzhu/datasketch/blob/b3e4129987890a2beb04f2c0b6dc618ae35f2e14/datasketch/lshensemble.py#L211-L217
how to empty array
python
def _unpack_object_array(inp, source, prescatter): """Unpack Array[Object] with a scatter for referencing in input calls. There is no shorthand syntax for referencing all items in an array, so we explicitly unpack them with a scatter. """ raise NotImplementedError("Currently not used with record/struct/object improvements") base_rec, attr = source.rsplit(".", 1) new_name = "%s_%s_unpack" % (inp["name"], base_rec.replace(".", "_")) prescatter[base_rec].append((new_name, attr, _to_variable_type(inp["type"]["items"]))) return new_name, prescatter
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/scripts/cwltool2wdl.py#L121-L131
how to empty array
python
def _drop_empty_props(self, item): """Remove properties with empty strings from nested dicts. """ if isinstance(item, list): return [self._drop_empty_props(i) for i in item] if isinstance(item, dict): return { k: self._drop_empty_props(v) for k, v in item.items() if v != '' } return item
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/rest_api/sawtooth_rest_api/route_handlers.py#L975-L985
how to empty array
python
def empty(cls, labels=None): """Creates an empty table. Column labels are optional. [Deprecated] Args: ``labels`` (None or list): If ``None``, a table with 0 columns is created. If a list, each element is a column label in a table with 0 rows. Returns: A new instance of ``Table``. """ warnings.warn("Table.empty(labels) is deprecated. Use Table(labels)", FutureWarning) if labels is None: return cls() values = [[] for label in labels] return cls(values, labels)
https://github.com/data-8/datascience/blob/4cee38266903ca169cea4a53b8cc39502d85c464/datascience/tables.py#L69-L85
how to empty array
python
def drop_empty(rows): """Transpose the columns into rows, remove all of the rows that are empty after the first cell, then transpose back. The result is that columns that have a header but no data in the body are removed, assuming the header is the first row. """ return zip(*[col for col in zip(*rows) if bool(filter(bool, col[1:]))])
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1184-L1188
how to empty array
python
def array(self, dtype=None): """An implementation of __array__()""" t = self._t # timestamp (12) through last enum (76) if 11 <= t < 77: dtype = dtypeof(self) a = numpy.empty(len(self), dtype) k2a(a, self) return a # table (98) if t == 98: if dtype is None: dtype = list(zip(self.cols, (dtypeof(c) for c in self.flip.value))) dtype = numpy.dtype(dtype) a = numpy.empty(int(self.count), dtype) for c in dtype.fields: k2a(a[c], self[c]) return a return numpy.array(list(self), dtype)
https://github.com/KxSystems/pyq/blob/ad7b807abde94615a7344aaa930bb01fb1552cc5/src/pyq/_n.py#L148-L166
how to empty array
python
def _clean_empty(d): """Remove None values from a dict.""" if not isinstance(d, (dict, list)): return d if isinstance(d, list): return [v for v in (_clean_empty(v) for v in d) if v is not None] return { k: v for k, v in ((k, _clean_empty(v)) for k, v in d.items()) if v is not None }
https://github.com/frictionlessdata/goodtables-py/blob/3e7d6891d2f4e342dfafbe0e951e204ccc252a44/goodtables/inspector.py#L330-L340
how to empty array
python
def is_empty(self): """Return True if the table has no columns or the only column is the id""" if len(self.columns) == 0: return True if len(self.columns) == 1 and self.columns[0].name == 'id': return True return False
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L206-L214
how to empty array
python
def empty(self, **kwargs): """Empties cached sitetree data.""" cache.delete('sitetrees') cache.delete('sitetrees_reset') kwargs.get('init', True) and self.init()
https://github.com/idlesign/django-sitetree/blob/61de4608e6e415247c75fe8691027d7c4ed0d1e7/sitetree/sitetreeapp.py#L334-L339
how to empty array
python
def toarray(self): """ Returns the contents as a local array. Will likely cause memory problems for large objects. """ rdd = self._rdd if self._ordered else self._rdd.sortByKey() x = rdd.values().collect() return asarray(x).reshape(self.shape)
https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L1006-L1014
how to empty array
python
def discard(self, element): """Remove an element. Do not raise an exception if absent.""" key = self._transform(element) if key in self._elements: del self._elements[key]
https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/element_transform_set.py#L53-L57
how to empty array
python
def clean(self, elements): ''' Removes empty or incomplete answers. ''' cleanelements = [] for i in xrange(len(elements)): if isempty(elements[i]): return [] next = elements[i] if isinstance(elements[i], (list, tuple)): next = self.clean(elements[i]) if next: cleanelements.append(elements[i]) return cleanelements
https://github.com/lltk/lltk/blob/d171de55c1b97695fddedf4b02401ae27bf1d634/lltk/scraping.py#L156-L168
how to empty array
python
def unpack_zeroterm_array(ptr): """Converts a zero terminated array to a list and frees each element and the list itself. If an item is returned all yielded before are invalid. """ assert ptr index = 0 current = ptr[index] while current: yield current free(ffi.cast("gpointer", current)) index += 1 current = ptr[index] free(ffi.cast("gpointer", ptr))
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/cffilib/glib/glib.py#L244-L260
how to empty array
python
def _xxhash(self): """ An xxhash.b64 hash of the array. Returns ------------- xx: int, xxhash.xxh64 hash of array. """ # repeat the bookkeeping to get a contiguous array inside # the function to avoid additional function calls # these functions are called millions of times so everything helps if self._modified_x or not hasattr(self, '_hashed_xx'): if self.flags['C_CONTIGUOUS']: hasher = xxhash.xxh64(self) self._hashed_xx = hasher.intdigest() else: # the case where we have sliced our nice # contiguous array into a non- contiguous block # for example (note slice *after* track operation): # t = util.tracked_array(np.random.random(10))[::-1] contiguous = np.ascontiguousarray(self) hasher = xxhash.xxh64(contiguous) self._hashed_xx = hasher.intdigest() self._modified_x = False return self._hashed_xx
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/caching.py#L195-L219
how to empty array
python
def clear(self, omit_item_evicted=False): """Empty the cache and optionally invoke item_evicted callback.""" if not omit_item_evicted: items = self._dict.items() for key, value in items: self._evict_item(key, value) self._dict.clear()
https://github.com/quora/qcore/blob/fa5cd438eea554db35fd29cbc8dfbde69f09961c/qcore/caching.py#L209-L215
how to empty array
python
def _remove_empty_lines(self, lines): """ Iterate through the lines and remove any that are either empty or contain only one whitespace value Parameters ---------- lines : array-like The array of lines that we are to filter. Returns ------- filtered_lines : array-like The same array of lines with the "empty" ones removed. """ ret = [] for l in lines: # Remove empty lines and lines with only one whitespace value if (len(l) > 1 or len(l) == 1 and (not isinstance(l[0], str) or l[0].strip())): ret.append(l) return ret
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/parsers.py#L2912-L2934
how to empty array
python
def remove_null(obj): ''' reads through a list or set and strips any null values''' if isinstance(obj, set): try: obj.remove(None) except: pass elif isinstance(obj, list): for item in obj: if not is_not_null(item): obj.remove(item) return obj
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L290-L301
how to empty array
python
def flatten(self, shallow=None): """ Return a completely flattened version of an array. """ return self._wrap(self._flatten(self.obj, shallow))
https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L556-L559
how to empty array
python
def clear(self): """"Removes all elements from the collection and resets the error handling """ self.bad = False self.errors = {} self._collection.clear()
https://github.com/networks-lab/metaknowledge/blob/8162bf95e66bb6f9916081338e6e2a6132faff75/metaknowledge/mkCollection.py#L161-L166
how to empty array
python
def trim_empty_rows(self): """Remove all trailing empty rows.""" if self.nrows != 0: row_index = 0 for row_index, row in enumerate(reversed(self.rows)): if not self.is_row_empty(row): break self.nrows = len(self.rows) - row_index self.rows = self.rows[:self.nrows] return self
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L138-L147
how to empty array
python
def do_expand_array(self, array_name, depth=0): """Do recurrent array expansion, returning a set of keywords. Exception is thrown when there are cyclical dependencies between arrays or if the ``@array`` name references an undefined array. :param str array_name: The name of the array to expand. :param int depth: The recursion depth counter. :return set: The final set of array entries. """ if depth > self.master._depth: raise Exception("deep recursion detected") if not array_name in self.master._array: raise Exception("array '%s' not defined" % (array_name)) ret = list(self.master._array[array_name]) for array in self.master._array[array_name]: if array.startswith('@'): ret.remove(array) expanded = self.do_expand_array(array[1:], depth+1) ret.extend(expanded) return set(ret)
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L509-L531
how to empty array
python
def is_cell_empty(self, cell): """Checks if the cell is empty.""" if cell is None: return True elif self._is_cell_empty: return self._is_cell_empty(cell) else: return cell is None
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/data_table.py#L87-L94
how to empty array
python
def empty_bucket(outputs_file): """Empty the bucket associated to the test deployment.""" with open(outputs_file, "r") as f: outputs = yaml.load(f) bucket = outputs["storage"]["BucketName"] print("Emptying bucket {} ...".format(bucket)) os.system("aws s3 rm s3://{} --recursive".format(bucket)) print("Bucket {} has been emptied".format(bucket))
https://github.com/humilis/humilis-firehose/blob/8611e4b18d534bbafb638597da1304fc87be62b5/scripts/empty-bucket.py#L9-L18
how to empty array
python
def set_empty_for_all(self, row_column_list): """Keep all specified subplots completely empty. :param row_column_list: a list containing (row, column) tuples to specify the subplots, or None to indicate *all* subplots. :type row_column_list: list or None """ for row, column in row_column_list: self.set_empty(row, column)
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/multi_plot.py#L86-L95
how to empty array
python
def create_empty(cls, val=0x00): """Create an empty Userdata object. val: value to fill the empty user data fields with (default is 0x00) """ userdata_dict = {} for i in range(1, 15): key = 'd{}'.format(i) userdata_dict.update({key: val}) return userdata_dict
https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/messages/userdata.py#L150-L159
how to empty array
python
def is_empty_object(n, last): """n may be the inside of block or object""" if n.strip(): return False # seems to be but can be empty code last = last.strip() markers = { ')', ';', } if not last or last[-1] in markers: return False return True
https://github.com/PiotrDabkowski/Js2Py/blob/c0fa43f5679cf91ca8986c5747fcb07a433dc584/js2py/legecy_translators/objects.py#L23-L35
how to empty array
python
def zeros(shape, ctx=None, dtype=None, stype=None, **kwargs): """Return a new array of given shape and type, filled with zeros. Parameters ---------- shape : int or tuple of int The shape of the empty array ctx : Context, optional An optional device context (default is the current default context) dtype : str or numpy.dtype, optional An optional value type (default is `float32`) stype: string, optional The storage type of the empty array, such as 'row_sparse', 'csr', etc. Returns ------- NDArray, CSRNDArray or RowSparseNDArray A created array Examples -------- >>> mx.nd.zeros((1,2), mx.cpu(), stype='csr') <CSRNDArray 1x2 @cpu(0)> >>> mx.nd.zeros((1,2), mx.cpu(), 'float16', stype='row_sparse').asnumpy() array([[ 0., 0.]], dtype=float16) """ if stype is None or stype == 'default': return _zeros_ndarray(shape, ctx, dtype, **kwargs) else: return _zeros_sparse_ndarray(stype, shape, ctx, dtype, **kwargs)
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/utils.py#L40-L69
how to empty array
python
def de_blank(val): """Remove blank elements in `val` and return `ret`""" ret = list(val) if type(val) == list: for idx, item in enumerate(val): if item.strip() == '': ret.remove(item) else: ret[idx] = item.strip() return ret
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/card.py#L117-L126
how to empty array
python
def is_empty(self): """ Test interval emptiness. :return: True if interval is empty, False otherwise. """ return ( self._lower > self._upper or (self._lower == self._upper and (self._left == OPEN or self._right == OPEN)) )
https://github.com/AlexandreDecan/python-intervals/blob/eda4da7dd39afabab2c1689e0b5158abae08c831/intervals.py#L355-L364
how to empty array
python
def remove_na_arraylike(arr): """ Return array-like containing only true/non-NaN values, possibly empty. """ if is_extension_array_dtype(arr): return arr[notna(arr)] else: return arr[notna(lib.values_from_object(arr))]
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/missing.py#L523-L530
how to empty array
python
def remove_empty_from_dict(dictionary): """ Remove empty items from dictionary d :param dictionary: :return: """ if isinstance(dictionary, dict): return dict( (k, remove_empty_from_dict(v)) for k, v in iteritems( dictionary) if v and remove_empty_from_dict(v)) elif isinstance(dictionary, list): return [remove_empty_from_dict(v) for v in dictionary if v and remove_empty_from_dict(v)] return dictionary
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/tools.py#L396-L410
how to empty array
python
def empty( self, node ): """Calculate empty space as a fraction of total space""" overall = self.overall( node ) if overall: return (overall - self.children_sum( self.children(node), node))/float(overall) return 0
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/profilers/visual/runsnakerun/squaremap/squaremap.py#L463-L468
how to empty array
python
def clear(self, exclude=None): """ Remove all elements in the cache. """ if exclude is None: self.cache = {} else: self.cache = {k: v for k, v in self.cache.items() if k in exclude}
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/caching.py#L408-L416
how to empty array
python
def erase(self, partition, timeout_ms=None): """Erases the given partition.""" self._simple_command('erase', arg=partition, timeout_ms=timeout_ms)
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/openhtf/plugs/usb/fastboot_protocol.py#L290-L292
how to empty array
python
def save_array(self, array, name=None, partname=None, rootpath='.', raw=False, as_int=True): """ Standard array saving routine Parameters ----------- array : array Array to save to file name : str, optional Default 'array.tif'. Filename of array to save. Over-writes partname. partname : str, optional Part of the filename to save (with the coordinates appended) rootpath : str, optional Default '.'. Which directory to save file raw : bool, optional Default False. If true will save a .npz of the array. If false, will save a geotiff as_int : bool, optional Default True. If true will save array as an integer array ( excellent compression). If false will save as float array. """ if name is None and partname is not None: fnl_file = self.get_full_fn(partname, rootpath) tmp_file = os.path.join(rootpath, partname, self.get_fn(partname + '_tmp')) elif name is not None: fnl_file = name tmp_file = fnl_file + '_tmp.tiff' else: fnl_file = 'array.tif' if not raw: s_file = self.elev.clone_traits() s_file.raster_data = np.ma.masked_array(array) count = 10 while count > 0 and (s_file.raster_data.mask.sum() > 0 \ or np.isnan(s_file.raster_data).sum() > 0): s_file.inpaint() count -= 1 s_file.export_to_geotiff(tmp_file) if as_int: cmd = "gdalwarp -multi -wm 2000 -co BIGTIFF=YES -of GTiff -co compress=lzw -ot Int16 -co TILED=YES -wo OPTIMIZE_SIZE=YES -r near -t_srs %s %s %s" \ % (self.save_projection, tmp_file, fnl_file) else: cmd = "gdalwarp -multi -wm 2000 -co BIGTIFF=YES -of GTiff -co compress=lzw -co TILED=YES -wo OPTIMIZE_SIZE=YES -r near -t_srs %s %s %s" \ % (self.save_projection, tmp_file, fnl_file) print "<<"*4, cmd, ">>"*4 subprocess.call(cmd) os.remove(tmp_file) else: np.savez_compressed(fnl_file, array)
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/dem_processing.py#L631-L684
how to empty array
python
def is_empty(value, msg=None, except_=None, inc_zeros=True): ''' is defined, but null or empty like value ''' if hasattr(value, 'empty'): # dataframes must check for .empty # since they don't define truth value attr # take the negative, since below we're # checking for cases where value 'is_null' value = not bool(value.empty) elif inc_zeros and value in ZEROS: # also consider 0, 0.0, 0L as 'empty' # will check for the negative below value = True else: pass _is_null = is_null(value, except_=False) result = bool(_is_null or not value) if except_: return is_true(result, msg=msg, except_=except_) else: return bool(result)
https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/utils.py#L637-L658
how to empty array
python
def allZero(buffer): """ Tries to determine if a buffer is empty. @type buffer: str @param buffer: Buffer to test if it is empty. @rtype: bool @return: C{True} if the given buffer is empty, i.e. full of zeros, C{False} if it doesn't. """ allZero = True for byte in buffer: if byte != "\x00": allZero = False break return allZero
https://github.com/crackinglandia/pype32/blob/192fd14dfc0dd36d953739a81c17fbaf5e3d6076/pype32/utils.py#L65-L81
how to empty array
python
def break_array(a, threshold=numpy.pi, other=None): """Create a array which masks jumps >= threshold. Extra points are inserted between two subsequent values whose absolute difference differs by more than threshold (default is pi). Other can be a secondary array which is also masked according to *a*. Returns (*a_masked*, *other_masked*) (where *other_masked* can be ``None``) """ assert len(a.shape) == 1, "Only 1D arrays supported" if other is not None and a.shape != other.shape: raise ValueError("arrays must be of identical shape") # jump occurs after the index in break breaks = numpy.where(numpy.abs(numpy.diff(a)) >= threshold)[0] # insert a blank after breaks += 1 # is this needed?? -- no, but leave it here as a reminder #f2 = numpy.diff(a, 2) #up = (f2[breaks - 1] >= 0) # >0: up, <0: down # sort into up and down breaks: #breaks_up = breaks[up] #breaks_down = breaks[~up] # new array b including insertions for all the breaks m = len(breaks) b = numpy.empty((len(a) + m)) # calculate new indices for breaks in b, taking previous insertions into account b_breaks = breaks + numpy.arange(m) mask = numpy.zeros_like(b, dtype=numpy.bool) mask[b_breaks] = True b[~mask] = a b[mask] = numpy.NAN if other is not None: c = numpy.empty_like(b) c[~mask] = other c[mask] = numpy.NAN ma_c = numpy.ma.array(c, mask=mask) else: ma_c = None return numpy.ma.array(b, mask=mask), ma_c
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L1165-L1213
how to empty array
python
def rm_empty_fields(x): """ (Recursive) Go through N number of nested data types and remove all empty entries. :param any x: Unknown :return any x: Unknown """ # No logger here because the function is recursive. # Int types don't matter. Return as-is. if not isinstance(x, int) and not isinstance(x, float): if isinstance(x, str) or x is None: try: # Remove new line characters and carriage returns x = x.rstrip() except AttributeError: # None types don't matter. Keep going. pass if x in EMPTY: # Substitute empty entries with "" x = '' elif isinstance(x, list): # Recurse once for each item in the list for i, v in enumerate(x): x[i] = rm_empty_fields(x[i]) # After substitutions, remove empty entries. for i in x: # Many 0 values are important (coordinates, m/m/m/m). Don't remove them. if not i and i not in [0, 0.0]: x.remove(i) elif isinstance(x, dict): # First, go through and substitute "" (empty string) entry for any values in EMPTY for k, v in x.items(): x[k] = rm_empty_fields(v) # After substitutions, go through and delete the key-value pair. # This has to be done after we come back up from recursion because we cannot pass keys down. for key in list(x.keys()): if not x[key] and x[key] not in [0, 0.0]: del x[key] return x
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L602-L640
how to empty array
python
def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/write_buffer.py#L39-L43
how to empty array
python
def is_empty(self): """ Check whether this interval is empty. :rtype: bool """ if self.bounds[1] < self.bounds[0]: return True if self.bounds[1] == self.bounds[0]: return not (self.included[0] and self.included[1])
https://github.com/jreinhardt/constraining-order/blob/04d00e4cad0fa9bedf15f2e89b8fd667c0495edc/src/constrainingorder/sets.py#L240-L249
how to empty array
python
def clear(self): """ Removes all data from the buffer. """ self.io.seek(0) self.io.truncate() for item in self.monitors: item[2] = 0
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/util/buffer.py#L137-L144
how to empty array
python
def fillna(self, value): """ Create new SArray with all missing values (None or NaN) filled in with the given value. The size of the new SArray will be the same as the original SArray. If the given value is not the same type as the values in the SArray, `fillna` will attempt to convert the value to the original SArray's type. If this fails, an error will be raised. Parameters ---------- value : type convertible to SArray's type The value used to replace all missing values Returns ------- out : SArray A new SArray with all missing values filled """ with cython_context(): return SArray(_proxy = self.__proxy__.fill_missing_values(value))
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L2673-L2695
how to empty array
python
def delete_garbage(self): """ Delete items that are no longer referenced. This operation is safe to perform at any time. """ self.connection.query( "DELETE FROM `{db}`.`{tab}` WHERE ".format(tab=self.table_name, db=self.database) + " AND ".join( 'hash NOT IN (SELECT {column_name} FROM {referencing_table})'.format(**ref) for ref in self.references) or "TRUE") print('Deleted %d items' % self.connection.query("SELECT ROW_COUNT()").fetchone()[0])
https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/external.py#L147-L157
how to empty array
python
def clear(self, asset_manager_id): """ This method deletes all the data for an asset_manager_id. It should be used with extreme caution. In production it is almost always better to Inactivate rather than delete. """ self.logger.info('Clear Assets - Asset Manager: %s', asset_manager_id) url = '%s/clear/%s' % (self.endpoint, asset_manager_id) response = self.session.delete(url) if response.ok: count = response.json().get('count', 'Unknown') self.logger.info('Deleted %s Assets.', count) return count else: self.logger.error(response.text) response.raise_for_status()
https://github.com/amaas-fintech/amaas-core-sdk-python/blob/347b71f8e776b2dde582b015e31b4802d91e8040/amaascore/assets/interface.py#L248-L261