anchor stringlengths 16 95 | positive stringlengths 87 6.25k | negative stringlengths 87 6.4k |
|---|---|---|
how to save a variable to a text file in python | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() | def write_text(filename: str, text: str) -> None:
"""
Writes text to a file.
"""
with open(filename, 'w') as f: # type: TextIO
print(text, file=f) |
how to save a variable to a text file in python | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() | def save(self, fname: str):
"""
Saves this training state to fname.
"""
with open(fname, "wb") as fp:
pickle.dump(self, fp) |
how to save a variable to a text file in python | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() | def write_str2file(pathname, astr):
"""writes a string to file"""
fname = pathname
fhandle = open(fname, 'wb')
fhandle.write(astr)
fhandle.close() |
how to save a variable to a text file in python | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() | def write_document(doc, fnm):
"""Write a Text document to file.
Parameters
----------
doc: Text
The document to save.
fnm: str
The filename to save the document
"""
with codecs.open(fnm, 'wb', 'ascii') as f:
f.write(json.dumps(doc, indent=2)) |
how to save a variable to a text file in python | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() | def save(self, fname):
""" Saves the dictionary in json format
:param fname: file to save to
"""
with open(fname, 'wb') as f:
json.dump(self, f) |
how to save an excel sheet as a new file python | def save_excel(self, fd):
""" Saves the case as an Excel spreadsheet.
"""
from pylon.io.excel import ExcelWriter
ExcelWriter(self).write(fd) | def save_notebook(work_notebook, write_file):
"""Saves the Jupyter work_notebook to write_file"""
with open(write_file, 'w') as out_nb:
json.dump(work_notebook, out_nb, indent=2) |
how to save an excel sheet as a new file python | def save_excel(self, fd):
""" Saves the case as an Excel spreadsheet.
"""
from pylon.io.excel import ExcelWriter
ExcelWriter(self).write(fd) | def __init__(self, filename, formatting_info=False, handle_ambiguous_date=None):
"""Initialize the ExcelWorkbook instance."""
super().__init__(filename)
self.workbook = xlrd.open_workbook(self.filename, formatting_info=formatting_info)
self.handle_ambiguous_date = handle_ambiguous_date |
how to save an excel sheet as a new file python | def save_excel(self, fd):
""" Saves the case as an Excel spreadsheet.
"""
from pylon.io.excel import ExcelWriter
ExcelWriter(self).write(fd) | def _save_file(self, filename, contents):
"""write the html file contents to disk"""
with open(filename, 'w') as f:
f.write(contents) |
how to save an excel sheet as a new file python | def save_excel(self, fd):
""" Saves the case as an Excel spreadsheet.
"""
from pylon.io.excel import ExcelWriter
ExcelWriter(self).write(fd) | def tab(self, output):
"""Output data in excel-compatible tab-delimited format"""
import csv
csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab)
csvwriter.writerows(output) |
how to save an excel sheet as a new file python | def save_excel(self, fd):
""" Saves the case as an Excel spreadsheet.
"""
from pylon.io.excel import ExcelWriter
ExcelWriter(self).write(fd) | def write_document(doc, fnm):
"""Write a Text document to file.
Parameters
----------
doc: Text
The document to save.
fnm: str
The filename to save the document
"""
with codecs.open(fnm, 'wb', 'ascii') as f:
f.write(json.dumps(doc, indent=2)) |
how to save something on python | def pickle_save(thing,fname):
"""save something to a pickle file"""
pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL)
return thing | def save(self, fname: str):
"""
Saves this training state to fname.
"""
with open(fname, "wb") as fp:
pickle.dump(self, fp) |
how to save something on python | def pickle_save(thing,fname):
"""save something to a pickle file"""
pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL)
return thing | def save(variable, filename):
"""Save variable on given path using Pickle
Args:
variable: what to save
path (str): path of the output
"""
fileObj = open(filename, 'wb')
pickle.dump(variable, fileObj)
fileObj.close() |
how to save something on python | def pickle_save(thing,fname):
"""save something to a pickle file"""
pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL)
return thing | def save(self, fname):
""" Saves the dictionary in json format
:param fname: file to save to
"""
with open(fname, 'wb') as f:
json.dump(self, f) |
how to save something on python | def pickle_save(thing,fname):
"""save something to a pickle file"""
pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL)
return thing | def write(self):
"""Write content back to file."""
with open(self.path, 'w') as file_:
file_.write(self.content) |
how to save something on python | def pickle_save(thing,fname):
"""save something to a pickle file"""
pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL)
return thing | def write_str2file(pathname, astr):
"""writes a string to file"""
fname = pathname
fhandle = open(fname, 'wb')
fhandle.write(astr)
fhandle.close() |
python soft link removal | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... | def remove_this_tlink(self,tlink_id):
"""
Removes the tlink for the given tlink identifier
@type tlink_id: string
@param tlink_id: the tlink identifier to be removed
"""
for tlink in self.get_tlinks():
if tlink.get_id() == tlink_id:
self.node.r... |
python soft link removal | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... | def remove_links(text):
"""
Helper function to remove the links from the input text
Args:
text (str): A string
Returns:
str: the same text, but with any substring that matches the regex
for a link removed and replaced with a space
Example:
>>> from tweet_parser.get... |
python soft link removal | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... | def symlink(source, destination):
"""Create a symbolic link"""
log("Symlinking {} as {}".format(source, destination))
cmd = [
'ln',
'-sf',
source,
destination,
]
subprocess.check_call(cmd) |
python soft link removal | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... | def replacing_symlink(source, link_name):
"""Create symlink that overwrites any existing target.
"""
with make_tmp_name(link_name) as tmp_link_name:
os.symlink(source, tmp_link_name)
replace_file_or_dir(link_name, tmp_link_name) |
python soft link removal | def symlink_remove(link):
"""Remove a symlink. Used for model shortcut links.
link (unicode / Path): The path to the symlink.
"""
# https://stackoverflow.com/q/26554135/6400719
if os.path.isdir(path2str(link)) and is_windows:
# this should only be on Py2.7 and windows
os.rmdir(path2... | def create_symlink(source, link_name):
"""
Creates symbolic link for either operating system.
http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows
"""
os_symlink = getattr(os, "symlink", None)
if isinstance(os_symlink, collections.Callable):
os_symlink(source, link_n... |
python sorted iterator dictionary | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value | def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) |
python sorted iterator dictionary | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value | def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t :... |
python sorted iterator dictionary | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value | def revrank_dict(dict, key=lambda t: t[1], as_tuple=False):
""" Reverse sorts a #dict by a given key, optionally returning it as a
#tuple. By default, the @dict is sorted by it's value.
@dict: the #dict you wish to sorts
@key: the #sorted key to use
@as_tuple: returns result as a #t... |
python sorted iterator dictionary | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value | def format_result(input):
"""From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python
"""
items = list(iteritems(input))
return OrderedDict(sorted(items, key=lambda x: x[0])) |
python sorted iterator dictionary | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value | def itervalues(d, **kw):
"""Return an iterator over the values of a dictionary."""
if not PY2:
return iter(d.values(**kw))
return d.itervalues(**kw) |
python spacy how to remove stopwords and lower | def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.... | def wordify(text):
"""Generate a list of words given text, removing punctuation.
Parameters
----------
text : unicode
A piece of english text.
Returns
-------
words : list
List of words.
"""
stopset = set(nltk.corpus.stopwords.words('english'))
tokens = nltk.Wor... |
python spacy how to remove stopwords and lower | def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.... | def remove_prefix(text, prefix):
"""
Remove the prefix from the text if it exists.
>>> remove_prefix('underwhelming performance', 'underwhelming ')
'performance'
>>> remove_prefix('something special', 'sample')
'something special'
"""
null, prefix, rest = text.rpartition(prefix)
return rest |
python spacy how to remove stopwords and lower | def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.... | def clean(self, text):
"""Remove all unwanted characters from text."""
return ''.join([c for c in text if c in self.alphabet]) |
python spacy how to remove stopwords and lower | def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.... | def sanitize_word(s):
"""Remove non-alphanumerical characters from metric word.
And trim excessive underscores.
"""
s = re.sub('[^\w-]+', '_', s)
s = re.sub('__+', '_', s)
return s.strip('_') |
python spacy how to remove stopwords and lower | def _removeStopwords(text_list):
"""
Removes stopwords contained in a list of words.
:param text_string: A list of strings.
:type text_string: list.
:returns: The input ``text_list`` with stopwords removed.
:rtype: list
"""
output_list = []
for word in text_list:
if word.... | def get_stoplist(language):
"""Returns an built-in stop-list for the language as a set of words."""
file_path = os.path.join("stoplists", "%s.txt" % language)
try:
stopwords = pkgutil.get_data("justext", file_path)
except IOError:
raise ValueError(
"Stoplist for language '%s'... |
how to set python path in windows 7 | def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
re... | def get_python():
"""Determine the path to the virtualenv python"""
if sys.platform == 'win32':
python = path.join(VE_ROOT, 'Scripts', 'python.exe')
else:
python = path.join(VE_ROOT, 'bin', 'python')
return python |
how to set python path in windows 7 | def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
re... | def GetPythonLibraryDirectoryPath():
"""Retrieves the Python library directory path."""
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path |
how to set python path in windows 7 | def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
re... | def venv():
"""Install venv + deps."""
try:
import virtualenv # NOQA
except ImportError:
sh("%s -m pip install virtualenv" % PYTHON)
if not os.path.isdir("venv"):
sh("%s -m virtualenv venv" % PYTHON)
sh("venv\\Scripts\\pip install -r %s" % (REQUIREMENTS_TXT)) |
how to set python path in windows 7 | def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
re... | def home_lib(home):
"""Return the lib dir under the 'home' installation scheme"""
if hasattr(sys, 'pypy_version_info'):
lib = 'site-packages'
else:
lib = os.path.join('lib', 'python')
return os.path.join(home, lib) |
how to set python path in windows 7 | def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
re... | def vsh(cmd, *args, **kw):
""" Execute a command installed into the active virtualenv.
"""
args = '" "'.join(i.replace('"', r'\"') for i in args)
easy.sh('"%s" "%s"' % (venv_bin(cmd), args)) |
how to set value in python data frame | def SetValue(self, row, col, value):
"""
Set value in the pandas DataFrame
"""
self.dataframe.iloc[row, col] = value | def set_cell_value(cell, value):
"""
Convenience method for setting the value of an openpyxl cell
This is necessary since the value property changed from internal_value
to value between version 1.* and 2.*.
"""
if OPENPYXL_MAJOR_VERSION > 1:
cell.value = value
else:
cell.int... |
how to set value in python data frame | def SetValue(self, row, col, value):
"""
Set value in the pandas DataFrame
"""
self.dataframe.iloc[row, col] = value | def traverse_setter(obj, attribute, value):
"""
Traverses the object and sets the supplied attribute on the
object. Supports Dimensioned and DimensionedPlot types.
"""
obj.traverse(lambda x: setattr(x, attribute, value)) |
how to set value in python data frame | def SetValue(self, row, col, value):
"""
Set value in the pandas DataFrame
"""
self.dataframe.iloc[row, col] = value | 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) |
how to set value in python data frame | def SetValue(self, row, col, value):
"""
Set value in the pandas DataFrame
"""
self.dataframe.iloc[row, col] = value | def set_property(self, key, value):
"""
Update only one property in the dict
"""
self.properties[key] = value
self.sync_properties() |
how to set value in python data frame | def SetValue(self, row, col, value):
"""
Set value in the pandas DataFrame
"""
self.dataframe.iloc[row, col] = value | def _set_property(self, val, *args):
"""Private method that sets the value currently of the property"""
val = UserClassAdapter._set_property(self, val, *args)
if val:
Adapter._set_property(self, val, *args)
return val |
python split underscore reverse | def case_us2mc(x):
""" underscore to mixed case notation """
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x) | def camelcase_underscore(name):
""" Convert camelcase names to underscore """
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() |
python split underscore reverse | def case_us2mc(x):
""" underscore to mixed case notation """
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x) | def us2mc(string):
"""Transform an underscore_case string to a mixedCase string"""
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string) |
python split underscore reverse | def case_us2mc(x):
""" underscore to mixed case notation """
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x) | def camel_to_underscore(string):
"""Convert camelcase to lowercase and underscore.
Recipe from http://stackoverflow.com/a/1176023
Args:
string (str): The string to convert.
Returns:
str: The converted string.
"""
string = FIRST_CAP_RE.sub(r'\1_\2', string)
return ALL_CAP_R... |
python split underscore reverse | def case_us2mc(x):
""" underscore to mixed case notation """
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x) | def camel_to_under(name):
"""
Converts camel-case string to lowercase string separated by underscores.
Written by epost (http://stackoverflow.com/questions/1175208).
:param name: String to be converted
:return: new String with camel-case converted to lowercase, underscored
"""
s1 = re.sub(... |
python split underscore reverse | def case_us2mc(x):
""" underscore to mixed case notation """
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x) | def camelcase_to_slash(name):
""" Converts CamelCase to camel/case
code ripped from http://stackoverflow.com/questions/1175208/does-the-python-standard-library-have-function-to-convert-camelcase-to-camel-cas
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1/\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\... |
python spyder kernel died restarting | def restart(self, reset=False):
"""
Quit and Restart Spyder application.
If reset True it allows to reset spyder on restart.
"""
# Get start path to use in restart script
spyder_start_directory = get_module_path('spyder')
restart_script = osp.join(spyder_start_di... | def go_to_background():
""" Daemonize the running process. """
try:
if os.fork():
sys.exit()
except OSError as errmsg:
LOGGER.error('Fork failed: {0}'.format(errmsg))
sys.exit('Fork failed') |
python spyder kernel died restarting | def restart(self, reset=False):
"""
Quit and Restart Spyder application.
If reset True it allows to reset spyder on restart.
"""
# Get start path to use in restart script
spyder_start_directory = get_module_path('spyder')
restart_script = osp.join(spyder_start_di... | def wait_for_shutdown_signal(
self,
please_stop=False, # ASSIGN SIGNAL TO STOP EARLY
allow_exit=False, # ALLOW "exit" COMMAND ON CONSOLE TO ALSO STOP THE APP
wait_forever=True # IGNORE CHILD THREADS, NEVER EXIT. False => IF NO CHILD THREADS LEFT, THEN EXIT
):
"""
... |
python spyder kernel died restarting | def restart(self, reset=False):
"""
Quit and Restart Spyder application.
If reset True it allows to reset spyder on restart.
"""
# Get start path to use in restart script
spyder_start_directory = get_module_path('spyder')
restart_script = osp.join(spyder_start_di... | def gevent_monkey_patch_report(self):
"""
Report effective gevent monkey patching on the logs.
"""
try:
import gevent.socket
import socket
if gevent.socket.socket is socket.socket:
self.log("gevent monkey patching is active")
... |
python spyder kernel died restarting | def restart(self, reset=False):
"""
Quit and Restart Spyder application.
If reset True it allows to reset spyder on restart.
"""
# Get start path to use in restart script
spyder_start_directory = get_module_path('spyder')
restart_script = osp.join(spyder_start_di... | def stop(self, timeout=None):
"""Stop the thread."""
logger.debug("docker plugin - Close thread for container {}".format(self._container.name))
self._stopper.set() |
python spyder kernel died restarting | def restart(self, reset=False):
"""
Quit and Restart Spyder application.
If reset True it allows to reset spyder on restart.
"""
# Get start path to use in restart script
spyder_start_directory = get_module_path('spyder')
restart_script = osp.join(spyder_start_di... | async def restart(request):
"""
Returns OK, then waits approximately 1 second and restarts container
"""
def wait_and_restart():
log.info('Restarting server')
sleep(1)
os.system('kill 1')
Thread(target=wait_and_restart).start()
return web.json_response({"message": "restar... |
how to sort a dictionary in descending orderpython | def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t :... | def revrank_dict(dict, key=lambda t: t[1], as_tuple=False):
""" Reverse sorts a #dict by a given key, optionally returning it as a
#tuple. By default, the @dict is sorted by it's value.
@dict: the #dict you wish to sorts
@key: the #sorted key to use
@as_tuple: returns result as a #t... |
how to sort a dictionary in descending orderpython | def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t :... | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value |
how to sort a dictionary in descending orderpython | def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t :... | def sort_key(val):
"""Sort key for sorting keys in grevlex order."""
return numpy.sum((max(val)+1)**numpy.arange(len(val)-1, -1, -1)*val) |
how to sort a dictionary in descending orderpython | def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t :... | def sortlevel(self, level=None, ascending=True, sort_remaining=None):
"""
For internal compatibility with with the Index API.
Sort the Index. This is for compat with MultiIndex
Parameters
----------
ascending : boolean, default True
False to sort in descendi... |
how to sort a dictionary in descending orderpython | def sort_dict(d, key=None, reverse=False):
"""
Sorts a dict by value.
Args:
d: Input dictionary
key: Function which takes an tuple (key, object) and returns a value to
compare and sort by. By default, the function compares the values
of the dict i.e. key = lambda t :... | def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) |
python sqlalchemy this transaction is inactive | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transa... | def in_transaction(self):
"""Check if this database is in a transactional context."""
if not hasattr(self.local, 'tx'):
return False
return len(self.local.tx) > 0 |
python sqlalchemy this transaction is inactive | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transa... | def execute(self, sql, params=None):
"""Just a pointer to engine.execute
"""
# wrap in a transaction to ensure things are committed
# https://github.com/smnorris/pgdata/issues/3
with self.engine.begin() as conn:
result = conn.execute(sql, params)
return result |
python sqlalchemy this transaction is inactive | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transa... | def destroy(self):
""" Destroy the SQLStepQueue tables in the database """
with self._db_conn() as conn:
for table_name in self._tables:
conn.execute('DROP TABLE IF EXISTS %s' % table_name)
return self |
python sqlalchemy this transaction is inactive | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transa... | def _executemany(self, cursor, query, parameters):
"""The function is mostly useful for commands that update the database:
any result set returned by the query is discarded."""
try:
self._log(query)
cursor.executemany(query, parameters)
except OperationalError ... |
python sqlalchemy this transaction is inactive | def commit(self, session=None):
"""Merge modified objects into parent transaction.
Once commited a transaction object is not usable anymore
:param:session: current sqlalchemy Session
"""
if self.__cleared:
return
if self._parent:
# nested transa... | def emit_db_sequence_updates(engine):
"""Set database sequence objects to match the source db
Relevant only when generated from SQLAlchemy connection.
Needed to avoid subsequent unique key violations after DB build."""
if engine and engine.name == 'postgresql':
# not implemented for othe... |
python start fnction asynchronously | def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start() | async def _thread_coro(self, *args):
""" Coroutine called by MapAsync. It's wrapping the call of
run_in_executor to run the synchronous function as thread """
return await self._loop.run_in_executor(
self._executor, self._function, *args) |
python start fnction asynchronously | def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start() | def runcoro(async_function):
"""
Runs an asynchronous function without needing to use await - useful for lambda
Args:
async_function (Coroutine): The asynchronous function to run
"""
future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)
result = future.result()
re... |
python start fnction asynchronously | def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start() | def _run_sync(self, method: Callable, *args, **kwargs) -> Any:
"""
Utility method to run commands synchronously for testing.
"""
if self.loop.is_running():
raise RuntimeError("Event loop is already running.")
if not self.is_connected:
self.loop.run_until_... |
python start fnction asynchronously | def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start() | def wait_run_in_executor(func, *args, **kwargs):
"""
Run blocking code in a different thread and wait
for the result.
:param func: Run this function in a different thread
:param args: Parameters of the function
:param kwargs: Keyword parameters of the function
:returns: Return the result of... |
python start fnction asynchronously | def asynchronous(function, event):
"""
Runs the function asynchronously taking care of exceptions.
"""
thread = Thread(target=synchronous, args=(function, event))
thread.daemon = True
thread.start() | def run_task(func):
"""
Decorator to wrap an async function in an event loop.
Use for main sync interface methods.
"""
def _wrapped(*a, **k):
loop = asyncio.get_event_loop()
return loop.run_until_complete(func(*a, **k))
return _wrapped |
how to specify a function return enumerated type, python | def get_function_class(function_name):
"""
Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance)
"""
if function_name in _known_functions:
return _known_functions[function_na... | def return_type(type_name, formatter=None):
"""Specify that this function returns a typed value.
Args:
type_name (str): A type name known to the global typedargs type system
formatter (str): An optional name of a formatting function specified
for the type given in type_name.
"""... |
how to specify a function return enumerated type, python | def get_function_class(function_name):
"""
Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance)
"""
if function_name in _known_functions:
return _known_functions[function_na... | def getEventTypeNameFromEnum(self, eType):
"""returns the name of an EVREvent enum value"""
fn = self.function_table.getEventTypeNameFromEnum
result = fn(eType)
return result |
how to specify a function return enumerated type, python | def get_function_class(function_name):
"""
Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance)
"""
if function_name in _known_functions:
return _known_functions[function_na... | def Value(self, name):
"""Returns the value coresponding to the given enum name."""
if name in self._enum_type.values_by_name:
return self._enum_type.values_by_name[name].number
raise ValueError('Enum %s has no value defined for name %s' % (
self._enum_type.name, name)) |
how to specify a function return enumerated type, python | def get_function_class(function_name):
"""
Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance)
"""
if function_name in _known_functions:
return _known_functions[function_na... | def unpack_out(self, name):
return self.parse("""
$enum = $enum_class($value.value)
""", enum_class=self._import_type(), value=name)["enum"] |
how to specify a function return enumerated type, python | def get_function_class(function_name):
"""
Return the type for the requested function
:param function_name: the function to return
:return: the type for that function (i.e., this is a class, not an instance)
"""
if function_name in _known_functions:
return _known_functions[function_na... | def to_python(self, value):
"""
Convert a string from a form into an Enum value.
"""
if value is None:
return value
if isinstance(value, self.enum):
return value
return self.enum[value] |
how to stop a python program running in the background | def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread ... | def stop(self, timeout=None):
""" Initiates a graceful stop of the processes """
self.stopping = True
for process in list(self.processes):
self.stop_process(process, timeout=timeout) |
how to stop a python program running in the background | def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread ... | def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for _ in range(1 + timeout * freq):
ret = p.poll()
if ret is not None:
logging.info("Shutdown gracefully.")
return ret
time.sleep(1 / fr... |
how to stop a python program running in the background | def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread ... | def stop(self, timeout=None):
"""Stop the thread."""
logger.debug("docker plugin - Close thread for container {}".format(self._container.name))
self._stopper.set() |
how to stop a python program running in the background | def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread ... | async def stop(self):
"""Stop the current task process.
Starts with SIGTERM, gives the process 1 second to terminate, then kills it
"""
# negate pid so that signals apply to process group
pgid = -self.process.pid
try:
os.kill(pgid, signal.SIGTERM)
... |
how to stop a python program running in the background | def timeout_thread_handler(timeout, stop_event):
"""A background thread to kill the process if it takes too long.
Args:
timeout (float): The number of seconds to wait before killing
the process.
stop_event (Event): An optional event to cleanly stop the background
thread ... | async def terminate(self):
"""Terminate a running script."""
self.proc.terminate()
await asyncio.wait_for(self.proc.wait(), self.kill_delay)
if self.proc.returncode is None:
self.proc.kill()
await self.proc.wait()
await super().terminate() |
python stop logging for unit tests | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | def kill_test_logger(logger):
"""Cleans up a test logger object by removing all of its handlers.
Args:
logger: The logging object to clean up.
"""
for h in list(logger.handlers):
logger.removeHandler(h)
if isinstance(h, logging.FileHandler):
h.close() |
python stop logging for unit tests | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | def should_skip_logging(func):
"""
Should we skip logging for this handler?
"""
disabled = strtobool(request.headers.get("x-request-nolog", "false"))
return disabled or getattr(func, SKIP_LOGGING, False) |
python stop logging for unit tests | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | def log_stop(logger):
"""log stop"""
handlers = logger.handlers[:]
for handler in handlers:
handler.close()
logger.removeHandler(handler) |
python stop logging for unit tests | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | def stoplog(self):
""" Stop logging.
@return: 1 on success and 0 on error
@rtype: integer
"""
if self._file_logger:
self.logger.removeHandler(_file_logger)
self._file_logger = None
return 1 |
python stop logging for unit tests | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | def stop_logging():
"""Stop logging to logfile and console."""
from . import log
logger = logging.getLogger("gromacs")
logger.info("GromacsWrapper %s STOPPED logging", get_version())
log.clear_handlers(logger) |
python str is valid date | def _validate_date_str(str_):
"""Validate str as a date and return string version of date"""
if not str_:
return None
# Convert to datetime so we can validate it's a real date that exists then
# convert it back to the string.
try:
date = datetime.strptime(str_, DATE_FMT)
except... | def valid_date(x: str) -> bool:
"""
Retrun ``True`` if ``x`` is a valid YYYYMMDD date;
otherwise return ``False``.
"""
try:
if x != dt.datetime.strptime(x, DATE_FORMAT).strftime(DATE_FORMAT):
raise ValueError
return True
except ValueError:
return False |
python str is valid date | def _validate_date_str(str_):
"""Validate str as a date and return string version of date"""
if not str_:
return None
# Convert to datetime so we can validate it's a real date that exists then
# convert it back to the string.
try:
date = datetime.strptime(str_, DATE_FMT)
except... | def is_date(thing):
"""Checks if the given thing represents a date
:param thing: The object to check if it is a date
:type thing: arbitrary object
:returns: True if we have a date object
:rtype: bool
"""
# known date types
date_types = (datetime.datetime,
datetime.date... |
python str is valid date | def _validate_date_str(str_):
"""Validate str as a date and return string version of date"""
if not str_:
return None
# Convert to datetime so we can validate it's a real date that exists then
# convert it back to the string.
try:
date = datetime.strptime(str_, DATE_FMT)
except... | def get_date(date):
"""
Get the date from a value that could be a date object or a string.
:param date: The date object or string.
:returns: The date object.
"""
if type(date) is str:
return datetime.strptime(date, '%Y-%m-%d').date()
else:
return date |
python str is valid date | def _validate_date_str(str_):
"""Validate str as a date and return string version of date"""
if not str_:
return None
# Convert to datetime so we can validate it's a real date that exists then
# convert it back to the string.
try:
date = datetime.strptime(str_, DATE_FMT)
except... | def string_to_date(value):
"""
Return a Python date that corresponds to the specified string
representation.
@param value: string representation of a date.
@return: an instance ``datetime.datetime`` represented by the string.
"""
if isinstance(value, datetime.date):
return value
... |
python str is valid date | def _validate_date_str(str_):
"""Validate str as a date and return string version of date"""
if not str_:
return None
# Convert to datetime so we can validate it's a real date that exists then
# convert it back to the string.
try:
date = datetime.strptime(str_, DATE_FMT)
except... | def is_date_type(cls):
"""Return True if the class is a date type."""
if not isinstance(cls, type):
return False
return issubclass(cls, date) and not issubclass(cls, datetime) |
how to take the average value each day on group of datetime strings in python | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | def median_date(dt_list):
"""Calcuate median datetime from datetime list
"""
#dt_list_sort = sorted(dt_list)
idx = len(dt_list)/2
if len(dt_list) % 2 == 0:
md = mean_date([dt_list[idx-1], dt_list[idx]])
else:
md = dt_list[idx]
return md |
how to take the average value each day on group of datetime strings in python | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | def moving_average(array, n=3):
"""
Calculates the moving average of an array.
Parameters
----------
array : array
The array to have the moving average taken of
n : int
The number of points of moving average to take
Returns
-------
MovingAverageArray : array
... |
how to take the average value each day on group of datetime strings in python | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | def moving_average(a, n):
"""Moving average over one-dimensional array.
Parameters
----------
a : np.ndarray
One-dimensional array.
n : int
Number of entries to average over. n=2 means averaging over the currrent
the previous entry.
Returns
-------
An array view... |
how to take the average value each day on group of datetime strings in python | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | def moving_average(arr: np.ndarray, n: int = 3) -> np.ndarray:
""" Calculate the moving overage over an array.
Algorithm from: https://stackoverflow.com/a/14314054
Args:
arr (np.ndarray): Array over which to calculate the moving average.
n (int): Number of elements over which to calculate ... |
how to take the average value each day on group of datetime strings in python | def mean_date(dt_list):
"""Calcuate mean datetime from datetime list
"""
dt_list_sort = sorted(dt_list)
dt_list_sort_rel = [dt - dt_list_sort[0] for dt in dt_list_sort]
avg_timedelta = sum(dt_list_sort_rel, timedelta())/len(dt_list_sort_rel)
return dt_list_sort[0] + avg_timedelta | def average(arr):
"""average of the values, must have more than 0 entries.
:param arr: list of numbers
:type arr: number[] a number array
:return: average
:rtype: float
"""
if len(arr) == 0:
sys.stderr.write("ERROR: no content in array to take average\n")
sys.exit()
if len(arr) == 1: return a... |
python string % substitution float | def format_float(value): # not used
"""Modified form of the 'g' format specifier.
"""
string = "{:g}".format(value).replace("e+", "e")
string = re.sub("e(-?)0*(\d+)", r"e\1\2", string)
return string | def energy_string_to_float( string ):
"""
Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.
Args:
string (str): The string to convert.
Return
(float)
"""
energy_re = re.compile( "(-?\d+\.\d+)" )
return float( energy_re.match( string ).group(0) ) |
python string % substitution float | def format_float(value): # not used
"""Modified form of the 'g' format specifier.
"""
string = "{:g}".format(value).replace("e+", "e")
string = re.sub("e(-?)0*(\d+)", r"e\1\2", string)
return string | def string_format_func(s):
"""
Function used internally to format string data for output to XML.
Escapes back-slashes and quotes, and wraps the resulting string in
quotes.
"""
return u"\"%s\"" % unicode(s).replace(u"\\", u"\\\\").replace(u"\"", u"\\\"") |
python string % substitution float | def format_float(value): # not used
"""Modified form of the 'g' format specifier.
"""
string = "{:g}".format(value).replace("e+", "e")
string = re.sub("e(-?)0*(\d+)", r"e\1\2", string)
return string | def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None |
python string % substitution float | def format_float(value): # not used
"""Modified form of the 'g' format specifier.
"""
string = "{:g}".format(value).replace("e+", "e")
string = re.sub("e(-?)0*(\d+)", r"e\1\2", string)
return string | def safe_format(s, **kwargs):
"""
:type s str
"""
return string.Formatter().vformat(s, (), defaultdict(str, **kwargs)) |
python string % substitution float | def format_float(value): # not used
"""Modified form of the 'g' format specifier.
"""
string = "{:g}".format(value).replace("e+", "e")
string = re.sub("e(-?)0*(\d+)", r"e\1\2", string)
return string | def clean_float(v):
"""Remove commas from a float"""
if v is None or not str(v).strip():
return None
return float(str(v).replace(',', '')) |
how to test for maximum of a random integer function python | def random_int(maximum_value):
""" Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value.
:param maximum_value: maximum integer value
:return: int
"""
if maximum_value == 0:
return 0
elif maximum_value == 1:
return random_bits(1)
bits = math.floor(math.log2(maximum_value))
re... | def random_int(self, min=0, max=9999, step=1):
"""
Returns a random integer between two values.
:param min: lower bound value (inclusive; default=0)
:param max: upper bound value (inclusive; default=9999)
:param step: range step (default=1)
:returns: random integer betwe... |
how to test for maximum of a random integer function python | def random_int(maximum_value):
""" Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value.
:param maximum_value: maximum integer value
:return: int
"""
if maximum_value == 0:
return 0
elif maximum_value == 1:
return random_bits(1)
bits = math.floor(math.log2(maximum_value))
re... | def simulate(self):
"""Generates a random integer in the available range."""
min_ = (-sys.maxsize - 1) if self._min is None else self._min
max_ = sys.maxsize if self._max is None else self._max
return random.randint(min_, max_) |
how to test for maximum of a random integer function python | def random_int(maximum_value):
""" Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value.
:param maximum_value: maximum integer value
:return: int
"""
if maximum_value == 0:
return 0
elif maximum_value == 1:
return random_bits(1)
bits = math.floor(math.log2(maximum_value))
re... | def positive_integer(anon, obj, field, val):
"""
Returns a random positive integer (for a Django PositiveIntegerField)
"""
return anon.faker.positive_integer(field=field) |
how to test for maximum of a random integer function python | def random_int(maximum_value):
""" Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value.
:param maximum_value: maximum integer value
:return: int
"""
if maximum_value == 0:
return 0
elif maximum_value == 1:
return random_bits(1)
bits = math.floor(math.log2(maximum_value))
re... | def endless_permutations(N, random_state=None):
"""
Generate an endless sequence of random integers from permutations of the
set [0, ..., N).
If we call this N times, we will sweep through the entire set without
replacement, on the (N+1)th call a new permutation will be created, etc.
Parameter... |
how to test for maximum of a random integer function python | def random_int(maximum_value):
""" Random generator (PyCrypto getrandbits wrapper). The result is a non-negative value.
:param maximum_value: maximum integer value
:return: int
"""
if maximum_value == 0:
return 0
elif maximum_value == 1:
return random_bits(1)
bits = math.floor(math.log2(maximum_value))
re... | def qrandom(n):
"""
Creates an array of n true random numbers obtained from the quantum random
number generator at qrng.anu.edu.au
This function requires the package quantumrandom and an internet connection.
Args:
n (int):
length of the random array
Return:
array of ints:
array of tru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.