_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q261700 | _distances | validation | def _distances(value_domain, distance_metric, n_v):
"""Distances of the different possible values.
Parameters
----------
value_domain : array_like, with shape (V,)
Possible values V the units can take.
If the level of measurement is not nominal, it must be ordered.
distance_metric ... | python | {
"resource": ""
} |
q261701 | _reliability_data_to_value_counts | validation | def _reliability_data_to_value_counts(reliability_data, value_domain):
"""Return the value counts given the reliability data.
Parameters
----------
reliability_data : ndarray, with shape (M, N)
Reliability data matrix which has the rate the i coder gave to the j unit, where M is the number of r... | python | {
"resource": ""
} |
q261702 | alpha | validation | def alpha(reliability_data=None, value_counts=None, value_domain=None, level_of_measurement='interval',
dtype=np.float64):
"""Compute Krippendorff's alpha.
See https://en.wikipedia.org/wiki/Krippendorff%27s_alpha for more information.
Parameters
----------
reliability_data : array_like, ... | python | {
"resource": ""
} |
q261703 | CDF.inquire | validation | def inquire(self):
"""Maps to fortran CDF_Inquire.
Assigns parameters returned by CDF_Inquire
to pysatCDF instance. Not intended
for regular direct use by user.
"""
name = copy.deepcopy(self.fname)
stats = fortran_cdf.inquire(name)
# break out fortran ... | python | {
"resource": ""
} |
q261704 | CDF._read_all_z_variable_info | validation | def _read_all_z_variable_info(self):
"""Gets all CDF z-variable information, not data though.
Maps to calls using var_inquire. Gets information on
data type, number of elements, number of dimensions, etc.
"""
self.z_variable_info = {}
self.z_variable_names_by_num = {}
... | python | {
"resource": ""
} |
q261705 | CDF.load_all_variables | validation | def load_all_variables(self):
"""Loads all variables from CDF.
Note this routine is called automatically
upon instantiation.
"""
self.data = {}
# need to add r variable names
file_var_names = self.z_variable_info.keys()
# collect variabl... | python | {
"resource": ""
} |
q261706 | CDF._call_multi_fortran_z | validation | def _call_multi_fortran_z(self, names, data_types, rec_nums,
dim_sizes, input_type_code, func,
epoch=False, data_offset=None, epoch16=False):
"""Calls fortran functions to load CDF variable data
Parameters
----------
names : li... | python | {
"resource": ""
} |
q261707 | CDF._read_all_attribute_info | validation | def _read_all_attribute_info(self):
"""Read all attribute properties, g, r, and z attributes"""
num = copy.deepcopy(self._num_attrs)
fname = copy.deepcopy(self.fname)
out = fortran_cdf.inquire_all_attr(fname, num, len(fname))
status = out[0]
names = out[1].astype('U')
... | python | {
"resource": ""
} |
q261708 | CDF._call_multi_fortran_z_attr | validation | def _call_multi_fortran_z_attr(self, names, data_types, num_elems,
entry_nums, attr_nums, var_names,
input_type_code, func, data_offset=None):
"""Calls Fortran function that reads attribute data.
data_offset translates unsign... | python | {
"resource": ""
} |
q261709 | _uptime_linux | validation | def _uptime_linux():
"""Returns uptime in seconds or None, on Linux."""
# With procfs
try:
f = open('/proc/uptime', 'r')
up = float(f.readline().split()[0])
f.close()
return up
except (IOError, ValueError):
pass
# Without procfs (really?)
try:
lib... | python | {
"resource": ""
} |
q261710 | _boottime_linux | validation | def _boottime_linux():
"""A way to figure out the boot time directly on Linux."""
global __boottime
try:
f = open('/proc/stat', 'r')
for line in f:
if line.startswith('btime'):
__boottime = int(line.split()[1])
if datetime is None:
raise NotIm... | python | {
"resource": ""
} |
q261711 | _uptime_amiga | validation | def _uptime_amiga():
"""Returns uptime in seconds or None, on AmigaOS."""
global __boottime
try:
__boottime = os.stat('RAM:').st_ctime
return time.time() - __boottime
except (NameError, OSError):
return None | python | {
"resource": ""
} |
q261712 | _uptime_minix | validation | def _uptime_minix():
"""Returns uptime in seconds or None, on MINIX."""
try:
f = open('/proc/uptime', 'r')
up = float(f.read())
f.close()
return up
except (IOError, ValueError):
return None | python | {
"resource": ""
} |
q261713 | _uptime_plan9 | validation | def _uptime_plan9():
"""Returns uptime in seconds or None, on Plan 9."""
# Apparently Plan 9 only has Python 2.2, which I'm not prepared to
# support. Maybe some Linuxes implement /dev/time, though, someone was
# talking about it somewhere.
try:
# The time file holds one 32-bit number repres... | python | {
"resource": ""
} |
q261714 | _uptime_solaris | validation | def _uptime_solaris():
"""Returns uptime in seconds or None, on Solaris."""
global __boottime
try:
kstat = ctypes.CDLL('libkstat.so')
except (AttributeError, OSError):
return None
# kstat doesn't have uptime, but it does have boot time.
# Unfortunately, getting at it isn't perfe... | python | {
"resource": ""
} |
q261715 | _uptime_syllable | validation | def _uptime_syllable():
"""Returns uptime in seconds or None, on Syllable."""
global __boottime
try:
__boottime = os.stat('/dev/pty/mst/pty0').st_mtime
return time.time() - __boottime
except (NameError, OSError):
return None | python | {
"resource": ""
} |
q261716 | uptime | validation | def uptime():
"""Returns uptime in seconds if even remotely possible, or None if not."""
if __boottime is not None:
return time.time() - __boottime
return {'amiga': _uptime_amiga,
'aros12': _uptime_amiga,
'beos5': _uptime_beos,
'cygwin': _uptime_linux,
... | python | {
"resource": ""
} |
q261717 | boottime | validation | def boottime():
"""Returns boot time if remotely possible, or None if not."""
global __boottime
if __boottime is None:
up = uptime()
if up is None:
return None
if __boottime is None:
_boottime_linux()
if datetime is None:
raise RuntimeError('datetime mod... | python | {
"resource": ""
} |
q261718 | _initfile | validation | def _initfile(path, data="dict"):
"""Initialize an empty JSON file."""
data = {} if data.lower() == "dict" else []
# The file will need to be created if it doesn't exist
if not os.path.exists(path): # The file doesn't exist
# Raise exception if the directory that should contain the file doesn't... | python | {
"resource": ""
} |
q261719 | _BaseFile._data | validation | def _data(self):
"""A simpler version of data to avoid infinite recursion in some cases.
Don't use this.
"""
if self.is_caching:
return self.cache
with open(self.path, "r") as f:
return json.load(f) | python | {
"resource": ""
} |
q261720 | _BaseFile.data | validation | def data(self, data):
"""Overwrite the file with new data. You probably shouldn't do
this yourself, it's easy to screw up your whole file with this."""
if self.is_caching:
self.cache = data
else:
fcontents = self.file_contents
with open(self.path, "w")... | python | {
"resource": ""
} |
q261721 | _BaseFile._updateType | validation | def _updateType(self):
"""Make sure that the class behaves like the data structure that it
is, so that we don't get a ListFile trying to represent a dict."""
data = self._data()
# Change type if needed
if isinstance(data, dict) and isinstance(self, ListFile):
self.__c... | python | {
"resource": ""
} |
q261722 | File.with_data | validation | def with_data(path, data):
"""Initialize a new file that starts out with some data. Pass data
as a list, dict, or JSON string.
"""
# De-jsonize data if necessary
if isinstance(data, str):
data = json.loads(data)
# Make sure this is really a new file
i... | python | {
"resource": ""
} |
q261723 | ZabbixPlugin.is_configured | validation | def is_configured(self, project, **kwargs):
"""
Check if plugin is configured.
"""
params = self.get_option
return bool(params('server_host', project) and params('server_port', project)) | python | {
"resource": ""
} |
q261724 | ZabbixPlugin.post_process | validation | def post_process(self, group, event, is_new, is_sample, **kwargs):
"""
Process error.
"""
if not self.is_configured(group.project):
return
host = self.get_option('server_host', group.project)
port = int(self.get_option('server_port', group.project))
p... | python | {
"resource": ""
} |
q261725 | PingTransmitter.ping | validation | def ping(self):
"""
Sending ICMP packets.
:return: ``ping`` command execution result.
:rtype: :py:class:`.PingResult`
:raises ValueError: If parameters not valid.
"""
self.__validate_ping_param()
ping_proc = subprocrunner.SubprocessRunner(self.__get_pin... | python | {
"resource": ""
} |
q261726 | PingParsing.parse | validation | def parse(self, ping_message):
"""
Parse ping command output.
Args:
ping_message (str or :py:class:`~pingparsing.PingResult`):
``ping`` command output.
Returns:
:py:class:`~pingparsing.PingStats`: Parsed result.
"""
try:
... | python | {
"resource": ""
} |
q261727 | EmailAddress.send_confirmation | validation | def send_confirmation(self):
"""
Send a verification email for the email address.
"""
confirmation = EmailConfirmation.objects.create(email=self)
confirmation.send() | python | {
"resource": ""
} |
q261728 | EmailAddress.send_duplicate_notification | validation | def send_duplicate_notification(self):
"""
Send a notification about a duplicate signup.
"""
email_utils.send_email(
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=[self.email],
subject=_("Registration Attempt"),
template_name="rest... | python | {
"resource": ""
} |
q261729 | EmailAddress.set_primary | validation | def set_primary(self):
"""
Set this email address as the user's primary email.
"""
query = EmailAddress.objects.filter(is_primary=True, user=self.user)
query = query.exclude(pk=self.pk)
# The transaction is atomic so there is never a gap where a user
# has no pri... | python | {
"resource": ""
} |
q261730 | EmailConfirmation.confirm | validation | def confirm(self):
"""
Mark the instance's email as verified.
"""
self.email.is_verified = True
self.email.save()
signals.email_verified.send(email=self.email, sender=self.__class__)
logger.info("Verified email address: %s", self.email.email) | python | {
"resource": ""
} |
q261731 | EmailConfirmation.is_expired | validation | def is_expired(self):
"""
Determine if the confirmation has expired.
Returns:
bool:
``True`` if the confirmation has expired and ``False``
otherwise.
"""
expiration_time = self.created_at + datetime.timedelta(days=1)
return ti... | python | {
"resource": ""
} |
q261732 | EmailConfirmation.send | validation | def send(self):
"""
Send a verification email to the user.
"""
context = {
"verification_url": app_settings.EMAIL_VERIFICATION_URL.format(
key=self.key
)
}
email_utils.send_email(
context=context,
from_email... | python | {
"resource": ""
} |
q261733 | UserFactory._create | validation | def _create(cls, model_class, *args, **kwargs):
"""
Create a new user instance.
Args:
model_class:
The type of model to create an instance of.
args:
Positional arguments to create the instance with.
kwargs:
Keyw... | python | {
"resource": ""
} |
q261734 | EmailSerializer.create | validation | def create(self, validated_data):
"""
Create a new email and send a confirmation to it.
Returns:
The newly creating ``EmailAddress`` instance.
"""
email_query = models.EmailAddress.objects.filter(
email=self.validated_data["email"]
)
if e... | python | {
"resource": ""
} |
q261735 | EmailSerializer.update | validation | def update(self, instance, validated_data):
"""
Update the instance the serializer is bound to.
Args:
instance:
The instance the serializer is bound to.
validated_data:
The data to update the serializer with.
Returns:
... | python | {
"resource": ""
} |
q261736 | EmailSerializer.validate_is_primary | validation | def validate_is_primary(self, is_primary):
"""
Validate the provided 'is_primary' parameter.
Returns:
The validated 'is_primary' value.
Raises:
serializers.ValidationError:
If the user attempted to mark an unverified email as
thei... | python | {
"resource": ""
} |
q261737 | EmailVerificationSerializer.validate | validation | def validate(self, data):
"""
Validate the provided data.
Returns:
dict:
The validated data.
Raises:
serializers.ValidationError:
If the provided password is invalid.
"""
user = self._confirmation.email.user
... | python | {
"resource": ""
} |
q261738 | EmailVerificationSerializer.validate_key | validation | def validate_key(self, key):
"""
Validate the provided confirmation key.
Returns:
str:
The validated confirmation key.
Raises:
serializers.ValidationError:
If there is no email confirmation with the given key or
th... | python | {
"resource": ""
} |
q261739 | PasswordResetRequestSerializer.save | validation | def save(self):
"""
Send out a password reset if the provided data is valid.
If the provided email address exists and is verified, a reset
email is sent to the address.
Returns:
The password reset token if it was returned and ``None``
otherwise.
... | python | {
"resource": ""
} |
q261740 | PasswordResetSerializer.save | validation | def save(self):
"""
Reset the user's password if the provided information is valid.
"""
token = models.PasswordResetToken.objects.get(
key=self.validated_data["key"]
)
token.email.user.set_password(self.validated_data["password"])
token.email.user.sav... | python | {
"resource": ""
} |
q261741 | PasswordResetSerializer.validate_key | validation | def validate_key(self, key):
"""
Validate the provided reset key.
Returns:
The validated key.
Raises:
serializers.ValidationError:
If the provided key does not exist.
"""
if not models.PasswordResetToken.valid_tokens.filter(key=ke... | python | {
"resource": ""
} |
q261742 | RegistrationSerializer.create | validation | def create(self, validated_data):
"""
Create a new user from the data passed to the serializer.
If the provided email has not been verified yet, the user is
created and a verification email is sent to the address.
Otherwise we send a notification to the email address that
... | python | {
"resource": ""
} |
q261743 | ResendVerificationSerializer.save | validation | def save(self):
"""
Resend a verification email to the provided address.
If the provided email is already verified no action is taken.
"""
try:
email = models.EmailAddress.objects.get(
email=self.validated_data["email"], is_verified=False
... | python | {
"resource": ""
} |
q261744 | EmailAddressManager.create | validation | def create(self, *args, **kwargs):
"""
Create a new email address.
"""
is_primary = kwargs.pop("is_primary", False)
with transaction.atomic():
email = super(EmailAddressManager, self).create(*args, **kwargs)
if is_primary:
email.set_prima... | python | {
"resource": ""
} |
q261745 | ValidPasswordResetTokenManager.get_queryset | validation | def get_queryset(self):
"""
Return all unexpired password reset tokens.
"""
oldest = timezone.now() - app_settings.PASSWORD_RESET_EXPIRATION
queryset = super(ValidPasswordResetTokenManager, self).get_queryset()
return queryset.filter(created_at__gt=oldest) | python | {
"resource": ""
} |
q261746 | Command.handle | validation | def handle(self, *args, **kwargs):
"""
Handle execution of the command.
"""
cutoff = timezone.now()
cutoff -= app_settings.CONFIRMATION_EXPIRATION
cutoff -= app_settings.CONFIRMATION_SAVE_PERIOD
queryset = models.EmailConfirmation.objects.filter(
crea... | python | {
"resource": ""
} |
q261747 | BaseBackend.get_user | validation | def get_user(self, user_id):
"""
Get a user by their ID.
Args:
user_id:
The ID of the user to fetch.
Returns:
The user with the specified ID if they exist and ``None``
otherwise.
"""
try:
return get_user_mo... | python | {
"resource": ""
} |
q261748 | VerifiedEmailBackend.authenticate | validation | def authenticate(self, request, email=None, password=None, username=None):
"""
Attempt to authenticate a set of credentials.
Args:
request:
The request associated with the authentication attempt.
email:
The user's email address.
... | python | {
"resource": ""
} |
q261749 | authenticate | validation | def authenticate(username, password, service='login', encoding='utf-8',
resetcred=True):
"""Returns True if the given username and password authenticate for the
given service. Returns False otherwise.
``username``: the username to authenticate
``password``: the password in plain text... | python | {
"resource": ""
} |
q261750 | SerializerSaveView.post | validation | def post(self, request):
"""
Save the provided data using the class' serializer.
Args:
request:
The request being made.
Returns:
An ``APIResponse`` instance. If the request was successful
the response will have a 200 status code and c... | python | {
"resource": ""
} |
q261751 | ReferrerTree.get_repr | validation | def get_repr(self, obj, referent=None):
"""Return an HTML tree block describing the given object."""
objtype = type(obj)
typename = str(objtype.__module__) + "." + objtype.__name__
prettytype = typename.replace("__builtin__.", "")
name = getattr(obj, "__name__", "")
if n... | python | {
"resource": ""
} |
q261752 | ReferrerTree.get_refkey | validation | def get_refkey(self, obj, referent):
"""Return the dict key or attribute name of obj which refers to
referent."""
if isinstance(obj, dict):
for k, v in obj.items():
if v is referent:
return " (via its %r key)" % k
for k in dir(obj) + ['__d... | python | {
"resource": ""
} |
q261753 | Tree.walk | validation | def walk(self, maxresults=100, maxdepth=None):
"""Walk the object tree, ignoring duplicates and circular refs."""
log.debug("step")
self.seen = {}
self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore)
# Ignore the calling frame, its builtins, globals and locals
... | python | {
"resource": ""
} |
q261754 | get_finder | validation | def get_finder(import_path):
"""
Imports the media fixtures files finder class described by import_path, where
import_path is the full Python path to the class.
"""
Finder = import_string(import_path)
if not issubclass(Finder, BaseFinder):
raise ImproperlyConfigured('Finder "%s" is not a... | python | {
"resource": ""
} |
q261755 | FileSystemFinder.find | validation | def find(self, path, all=False):
"""
Looks for files in the extra locations
as defined in ``MEDIA_FIXTURES_FILES_DIRS``.
"""
matches = []
for prefix, root in self.locations:
if root not in searched_locations:
searched_locations.append(root)
... | python | {
"resource": ""
} |
q261756 | FileSystemFinder.list | validation | def list(self, ignore_patterns):
"""
List all files in all locations.
"""
for prefix, root in self.locations:
storage = self.storages[root]
for path in utils.get_files(storage, ignore_patterns):
yield path, storage | python | {
"resource": ""
} |
q261757 | AppDirectoriesFinder.list | validation | def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yie... | python | {
"resource": ""
} |
q261758 | AppDirectoriesFinder.find | validation | def find(self, path, all=False):
"""
Looks for files in the app directories.
"""
matches = []
for app in self.apps:
app_location = self.storages[app].location
if app_location not in searched_locations:
searched_locations.append(app_location... | python | {
"resource": ""
} |
q261759 | AppDirectoriesFinder.find_in_app | validation | def find_in_app(self, app, path):
"""
Find a requested media file in an app's media fixtures locations.
"""
storage = self.storages.get(app, None)
if storage:
# only try to find a file if the source dir actually exists
if storage.exists(path):
... | python | {
"resource": ""
} |
q261760 | Command.set_options | validation | def set_options(self, **options):
"""
Set instance variables based on an options dict
"""
self.interactive = options['interactive']
self.verbosity = options['verbosity']
self.symlink = options['link']
self.clear = options['clear']
self.dry_run = options['d... | python | {
"resource": ""
} |
q261761 | Command.collect | validation | def collect(self):
"""
Perform the bulk of the work of collectmedia.
Split off from handle() to facilitate testing.
"""
if self.symlink and not self.local:
raise CommandError("Can't symlink to a remote destination.")
if self.clear:
self.clear_dir... | python | {
"resource": ""
} |
q261762 | Command.clear_dir | validation | def clear_dir(self, path):
"""
Deletes the given relative path using the destination storage backend.
"""
dirs, files = self.storage.listdir(path)
for f in files:
fpath = os.path.join(path, f)
if self.dry_run:
self.log("Pretending to delete... | python | {
"resource": ""
} |
q261763 | Command.delete_file | validation | def delete_file(self, path, prefixed_path, source_storage):
"""
Checks if the target file should be deleted if it already exists
"""
if self.storage.exists(prefixed_path):
try:
# When was the target file modified last time?
target_last_modified... | python | {
"resource": ""
} |
q261764 | Command.link_file | validation | def link_file(self, path, prefixed_path, source_storage):
"""
Attempt to link ``path``
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.symlinked_files:
return self.log("Skipping '%s' (already linked earlier)" % path)
# Delete the... | python | {
"resource": ""
} |
q261765 | Command.copy_file | validation | def copy_file(self, path, prefixed_path, source_storage):
"""
Attempt to copy ``path`` with storage
"""
# Skip this file if it was already copied earlier
if prefixed_path in self.copied_files:
return self.log("Skipping '%s' (already copied earlier)" % path)
# ... | python | {
"resource": ""
} |
q261766 | BaseSpaceContainer.cur_space | validation | def cur_space(self, name=None):
"""Set the current space to Space ``name`` and return it.
If called without arguments, the current space is returned.
Otherwise, the current space is set to the space named ``name``
and the space is returned.
"""
if name is None:
... | python | {
"resource": ""
} |
q261767 | EditableSpaceContainer.new_space | validation | def new_space(self, name=None, bases=None, formula=None, refs=None):
"""Create a child space.
Args:
name (str, optional): Name of the space. Defaults to ``SpaceN``,
where ``N`` is a number determined automatically.
bases (optional): A space or a sequence of space... | python | {
"resource": ""
} |
q261768 | EditableSpaceContainer.new_space_from_excel | validation | def new_space_from_excel(
self,
book,
range_,
sheet=None,
name=None,
names_row=None,
param_cols=None,
space_param_order=None,
cells_param_order=None,
transpose=False,
names_col=None,
param_rows=None,
):
"""Create... | python | {
"resource": ""
} |
q261769 | EditableSpaceContainerImpl.new_space | validation | def new_space(
self,
name=None,
bases=None,
formula=None,
*,
refs=None,
source=None,
is_derived=False,
prefix=""
):
"""Create a new child space.
Args:
name (str): Name of the space. If omitted, the space is
... | python | {
"resource": ""
} |
q261770 | get_node | validation | def get_node(obj, args, kwargs):
"""Create a node from arguments and return it"""
if args is None and kwargs is None:
return (obj,)
if kwargs is None:
kwargs = {}
return obj, _bind_args(obj, args, kwargs) | python | {
"resource": ""
} |
q261771 | node_get_args | validation | def node_get_args(node):
"""Return an ordered mapping from params to args"""
obj = node[OBJ]
key = node[KEY]
boundargs = obj.formula.signature.bind(*key)
boundargs.apply_defaults()
return boundargs.arguments | python | {
"resource": ""
} |
q261772 | get_object | validation | def get_object(name: str):
"""Get a modelx object from its full name."""
# TODO: Duplicate of system.get_object
elms = name.split(".")
parent = get_models()[elms.pop(0)]
while len(elms) > 0:
obj = elms.pop(0)
parent = getattr(parent, obj)
return parent | python | {
"resource": ""
} |
q261773 | _get_node | validation | def _get_node(name: str, args: str):
"""Get node from object name and arg string
Not Used. Left for future reference purpose.
"""
obj = get_object(name)
args = ast.literal_eval(args)
if not isinstance(args, tuple):
args = (args,)
return obj.node(*args) | python | {
"resource": ""
} |
q261774 | custom_showwarning | validation | def custom_showwarning(
message, category, filename="", lineno=-1, file=None, line=None
):
"""Hook to override default showwarning.
https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
"""
if file is None:
file = sys.stderr
if file is None:
... | python | {
"resource": ""
} |
q261775 | custom_showtraceback | validation | def custom_showtraceback(
self,
exc_tuple=None,
filename=None,
tb_offset=None,
exception_only=False,
running_compiled_code=False,
):
"""Custom showtraceback for monkey-patching IPython's InteractiveShell
https://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook
"""
... | python | {
"resource": ""
} |
q261776 | CallStack.tracemessage | validation | def tracemessage(self, maxlen=6):
"""
if maxlen > 0, the message is shortened to maxlen traces.
"""
result = ""
for i, value in enumerate(self):
result += "{0}: {1}\n".format(i, get_node_repr(value))
result = result.strip("\n")
lines = result.split("\... | python | {
"resource": ""
} |
q261777 | System.setup_ipython | validation | def setup_ipython(self):
"""Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from start_kernel in spyder-modelx.
... | python | {
"resource": ""
} |
q261778 | System.restore_ipython | validation | def restore_ipython(self):
"""Restore default IPython showtraceback"""
if not self.is_ipysetup:
return
shell_class = type(self.shell)
shell_class.showtraceback = shell_class.default_showtraceback
del shell_class.default_showtraceback
self.is_ipysetup = False | python | {
"resource": ""
} |
q261779 | System.restore_python | validation | def restore_python(self):
"""Restore Python settings to the original states"""
orig = self.orig_settings
sys.setrecursionlimit(orig["sys.recursionlimit"])
if "sys.tracebacklimit" in orig:
sys.tracebacklimit = orig["sys.tracebacklimit"]
else:
if hasattr(sy... | python | {
"resource": ""
} |
q261780 | System.get_object | validation | def get_object(self, name):
"""Retrieve an object by its absolute name."""
parts = name.split(".")
model_name = parts.pop(0)
return self.models[model_name].get_object(".".join(parts)) | python | {
"resource": ""
} |
q261781 | show_tree | validation | def show_tree(model=None):
"""Display the model tree window.
Args:
model: :class:`Model <modelx.core.model.Model>` object.
Defaults to the current model.
Warnings:
For this function to work with Spyder, *Graphics backend* option
of Spyder must be set to *inline*.
""... | python | {
"resource": ""
} |
q261782 | get_interfaces | validation | def get_interfaces(impls):
"""Get interfaces from their implementations."""
if impls is None:
return None
elif isinstance(impls, OrderMixin):
result = OrderedDict()
for name in impls.order:
result[name] = impls[name].interface
return result
elif isinstance(i... | python | {
"resource": ""
} |
q261783 | get_impls | validation | def get_impls(interfaces):
"""Get impls from their interfaces."""
if interfaces is None:
return None
elif isinstance(interfaces, Mapping):
return {name: interfaces[name]._impl for name in interfaces}
elif isinstance(interfaces, Sequence):
return [interfaces._impl for interfaces... | python | {
"resource": ""
} |
q261784 | Impl.update_lazyevals | validation | def update_lazyevals(self):
"""Update all LazyEvals in self
self.lzy_evals must be set to LazyEval object(s) enough to
update all owned LazyEval objects.
"""
if self.lazy_evals is None:
return
elif isinstance(self.lazy_evals, LazyEval):
self.lazy_... | python | {
"resource": ""
} |
q261785 | Interface._to_attrdict | validation | def _to_attrdict(self, attrs=None):
"""Get extra attributes"""
result = self._baseattrs
for attr in attrs:
if hasattr(self, attr):
result[attr] = getattr(self, attr)._to_attrdict(attrs)
return result | python | {
"resource": ""
} |
q261786 | convert_args | validation | def convert_args(args, kwargs):
"""If args and kwargs contains Cells, Convert them to their values."""
found = False
for arg in args:
if isinstance(arg, Cells):
found = True
break
if found:
args = tuple(
arg.value if isinstance(arg, Cells) else arg f... | python | {
"resource": ""
} |
q261787 | shareable_parameters | validation | def shareable_parameters(cells):
"""Return parameter names if the parameters are shareable among cells.
Parameters are shareable among multiple cells when all the cells
have the parameters in the same order if they ever have any.
For example, if cells are foo(), bar(x), baz(x, y), then
('x', 'y') ... | python | {
"resource": ""
} |
q261788 | Cells.copy | validation | def copy(self, space=None, name=None):
"""Make a copy of itself and return it."""
return Cells(space=space, name=name, formula=self.formula) | python | {
"resource": ""
} |
q261789 | CellNode.value | validation | def value(self):
"""Return the value of the cells."""
if self.has_value:
return self._impl[OBJ].get_value(self._impl[KEY])
else:
raise ValueError("Value not found") | python | {
"resource": ""
} |
q261790 | _get_col_index | validation | def _get_col_index(name):
"""Convert column name to index."""
index = string.ascii_uppercase.index
col = 0
for c in name.upper():
col = col * 26 + index(c) + 1
return col | python | {
"resource": ""
} |
q261791 | _get_range | validation | def _get_range(book, range_, sheet):
"""Return a range as nested dict of openpyxl cells."""
filename = None
if isinstance(book, str):
filename = book
book = opxl.load_workbook(book, data_only=True)
elif isinstance(book, opxl.Workbook):
pass
else:
raise TypeError
... | python | {
"resource": ""
} |
q261792 | read_range | validation | def read_range(filepath, range_expr, sheet=None, dict_generator=None):
"""Read values from an Excel range into a dictionary.
`range_expr` ie either a range address string, such as "A1", "$C$3:$E$5",
or a defined name string for a range, such as "NamedRange1".
If a range address is provided, `sheet` arg... | python | {
"resource": ""
} |
q261793 | _get_namedrange | validation | def _get_namedrange(book, rangename, sheetname=None):
"""Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def ... | python | {
"resource": ""
} |
q261794 | SpaceGraph.get_mro | validation | def get_mro(self, space):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Code modified from
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
Args:
bases: sequence of direct base spaces.
Returns:
mro as ... | python | {
"resource": ""
} |
q261795 | _alter_code | validation | def _alter_code(code, **attrs):
"""Create a new code object by altering some of ``code`` attributes
Args:
code: code objcect
attrs: a mapping of names of code object attrs to their values
"""
PyCode_New = ctypes.pythonapi.PyCode_New
PyCode_New.argtypes = (
ctypes.c_int,
... | python | {
"resource": ""
} |
q261796 | alter_freevars | validation | def alter_freevars(func, globals_=None, **vars):
"""Replace local variables with free variables
Warnings:
This function does not work.
"""
if globals_ is None:
globals_ = func.__globals__
frees = tuple(vars.keys())
oldlocs = func.__code__.co_names
newlocs = tuple(name for ... | python | {
"resource": ""
} |
q261797 | fix_lamdaline | validation | def fix_lamdaline(source):
"""Remove the last redundant token from lambda expression
lambda x: return x)
^
Return string without irrelevant tokens
returned from inspect.getsource on lamda expr returns
"""
# Using undocumented generate_tokens due to a tokenize.tokenize bug... | python | {
"resource": ""
} |
q261798 | find_funcdef | validation | def find_funcdef(source):
"""Find the first FuncDef ast object in source"""
try:
module_node = compile(
source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
)
except SyntaxError:
return find_funcdef(fix_lamdaline(source))
for node in ast.walk(module_node):
... | python | {
"resource": ""
} |
q261799 | extract_params | validation | def extract_params(source):
"""Extract parameters from a function definition"""
funcdef = find_funcdef(source)
params = []
for node in ast.walk(funcdef.args):
if isinstance(node, ast.arg):
if node.arg not in params:
params.append(node.arg)
return params | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.