code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
current_nodes = [self]
leaves = []
while len(current_nodes) > 0:
next_nodes = []
for node in current_nodes:
if node.left is None and node.right is None:
leaves.append(node)
continue
if node.... | def leaves(self) | Return the leaf nodes of the binary tree.
A leaf node is any node that does not have child nodes.
:return: List of leaf nodes.
:rtype: [binarytree.Node]
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
... | 1.698474 | 1.94756 | 0.872104 |
properties = _get_tree_properties(self)
properties.update({
'is_bst': _is_bst(self),
'is_balanced': _is_balanced(self) >= 0
})
return properties | def properties(self) | Return various properties of the binary tree.
:return: Binary tree properties.
:rtype: dict
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
... | 5.00016 | 7.416539 | 0.67419 |
node_stack = []
result = []
node = self
while True:
if node is not None:
node_stack.append(node)
node = node.left
elif len(node_stack) > 0:
node = node_stack.pop()
result.append(node)
... | def inorder(self) | Return the nodes in the binary tree using in-order_ traversal.
An in-order_ traversal visits left subtree, root, then right subtree.
.. _in-order: https://en.wikipedia.org/wiki/Tree_traversal
:return: List of nodes.
:rtype: [binarytree.Node]
**Example**:
.. doctest::... | 1.878722 | 2.465797 | 0.761913 |
node_stack = [self]
result = []
while len(node_stack) > 0:
node = node_stack.pop()
result.append(node)
if node.right is not None:
node_stack.append(node.right)
if node.left is not None:
node_stack.append(n... | def preorder(self) | Return the nodes in the binary tree using pre-order_ traversal.
A pre-order_ traversal visits root, left subtree, then right subtree.
.. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal
:return: List of nodes.
:rtype: [binarytree.Node]
**Example**:
.. doctest... | 1.707882 | 2.301873 | 0.741953 |
node_stack = []
result = []
node = self
while True:
while node is not None:
if node.right is not None:
node_stack.append(node.right)
node_stack.append(node)
node = node.left
node = node... | def postorder(self) | Return the nodes in the binary tree using post-order_ traversal.
A post-order_ traversal visits left subtree, right subtree, then root.
.. _post-order: https://en.wikipedia.org/wiki/Tree_traversal
:return: List of nodes.
:rtype: [binarytree.Node]
**Example**:
.. doct... | 1.792573 | 2.163114 | 0.8287 |
current_nodes = [self]
result = []
while len(current_nodes) > 0:
next_nodes = []
for node in current_nodes:
result.append(node)
if node.left is not None:
next_nodes.append(node.left)
if node.rig... | def levelorder(self) | Return the nodes in the binary tree using level-order_ traversal.
A level-order_ traversal visits nodes left to right, level by level.
.. _level-order:
https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search
:return: List of nodes.
:rtype: [binarytree.Node]
... | 1.747797 | 2.082999 | 0.839077 |
# type: (Optional[Text], Optional[Text]) -> BaseBackend
backend = backend or ORGS_INVITATION_BACKEND
class_module, class_name = backend.rsplit(".", 1)
mod = import_module(class_module)
return getattr(mod, class_name)(namespace=namespace) | def invitation_backend(backend=None, namespace=None) | Returns a specified invitation backend
Args:
backend: dotted path to the invitation backend class
namespace: URL namespace to use
Returns:
an instance of an InvitationBackend | 3.258252 | 5.776921 | 0.564012 |
# type: (Optional[Text], Optional[Text]) -> BaseBackend
backend = backend or ORGS_REGISTRATION_BACKEND
class_module, class_name = backend.rsplit(".", 1)
mod = import_module(class_module)
return getattr(mod, class_name)(namespace=namespace) | def registration_backend(backend=None, namespace=None) | Returns a specified registration backend
Args:
backend: dotted path to the registration backend class
namespace: URL namespace to use
Returns:
an instance of an RegistrationBackend | 3.342334 | 6.063863 | 0.551189 |
class OrganizationRegistrationForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = org_model
exclude = ("is_active", "users")
def save(self, *args, **kwargs):
self.instance.is_active = False
super(OrganizationR... | def org_registration_form(org_model) | Generates a registration ModelForm for the given organization model class | 2.454501 | 2.390118 | 1.026937 |
try:
user = get_user_model().objects.get(
email__iexact=self.cleaned_data["email"]
)
except get_user_model().MultipleObjectsReturned:
raise forms.ValidationError(
_("This email address has been used multiple times.")
... | def save(self, *args, **kwargs) | The save method should create a new OrganizationUser linking the User
matching the provided email address. If not matching User is found it
should kick off the registration process. It needs to create a User in
order to link it to the Organization. | 2.349583 | 2.21657 | 1.060008 |
is_active = True
try:
user = get_user_model().objects.get(email=self.cleaned_data["email"])
except get_user_model().DoesNotExist:
user = invitation_backend().invite_by_email(
self.cleaned_data["email"],
**{
"dom... | def save(self, **kwargs) | Create the organization, then get the user, then make the owner. | 2.935928 | 2.63089 | 1.115945 |
# type: (Text, AbstractUser, AbstractBaseOrganization) -> OrganizationInvitationBase
try:
invitee = self.user_model.objects.get(email__iexact=email)
except self.user_model.DoesNotExist:
invitee = None
# TODO allow sending just the OrganizationUser instan... | def invite_by_email(self, email, user, organization, **kwargs) | Primary interface method by which one user invites another to join
Args:
email:
request:
**kwargs:
Returns:
an invitation instance
Raises:
MultipleObjectsReturned if multiple matching users are found | 3.612952 | 4.747854 | 0.760965 |
# type: (OrganizationInvitationBase) -> bool
return self.email_message(
invitation.invitee_identifier,
self.invitation_subject,
self.invitation_body,
invitation.invited_by,
**kwargs
).send() | def send_invitation(self, invitation, **kwargs) | Sends an invitation message for a specific invitation.
This could be overridden to do other things, such as sending a confirmation
email to the sender.
Args:
invitation:
Returns: | 5.316541 | 6.954588 | 0.764465 |
from_email = "%s %s <%s>" % (
sender.first_name,
sender.last_name,
email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[1],
)
reply_to = "%s %s <%s>" % (sender.first_name, sender.last_name, sender.email)
headers = {"Reply-To": reply_to}
... | def email_message(
self,
recipient, # type: Text
subject_template, # type: Text
body_template, # type: Text
sender=None, # type: Optional[AbstractUser]
message_class=EmailMessage,
**kwargs
) | Returns an invitation email message. This can be easily overridden.
For instance, to send an HTML message, use the EmailMultiAlternatives message_class
and attach the additional conent. | 2.338998 | 2.284465 | 1.023871 |
try:
cls.module_registry[module]["OrgModel"]._meta.get_field("users")
except FieldDoesNotExist:
cls.module_registry[module]["OrgModel"].add_to_class(
"users",
models.ManyToManyField(
USER_MODEL,
thro... | def update_org(cls, module) | Adds the `users` field to the organization model | 2.926535 | 2.584506 | 1.132338 |
try:
cls.module_registry[module]["OrgUserModel"]._meta.get_field("user")
except FieldDoesNotExist:
cls.module_registry[module]["OrgUserModel"].add_to_class(
"user",
models.ForeignKey(
USER_MODEL,
rel... | def update_org_users(cls, module) | Adds the `user` field to the organization user model and the link to
the specific organization model. | 1.793379 | 1.633563 | 1.097833 |
try:
cls.module_registry[module]["OrgOwnerModel"]._meta.get_field(
"organization_user"
)
except FieldDoesNotExist:
cls.module_registry[module]["OrgOwnerModel"].add_to_class(
"organization_user",
models.OneToOneF... | def update_org_owner(cls, module) | Creates the links to the organization and organization user for the owner. | 1.874336 | 1.713965 | 1.093568 |
try:
cls.module_registry[module]["OrgInviteModel"]._meta.get_field("invited_by")
except FieldDoesNotExist:
cls.module_registry[module]["OrgInviteModel"].add_to_class(
"invited_by",
models.ForeignKey(
USER_MODEL,
... | def update_org_invite(cls, module) | Adds the links to the organization and to the organization user | 1.558729 | 1.534208 | 1.015983 |
return "{0}_{1}".format(
self._meta.app_label.lower(), self.__class__.__name__.lower()
) | def user_relation_name(self) | Returns the string name of the related name to the user.
This provides a consistent interface across different organization
model classes. | 4.216812 | 3.793839 | 1.111489 |
if hasattr(self.user, "get_full_name"):
return self.user.get_full_name()
return "{0}".format(self.user) | def name(self) | Returns the connected user's full name or string representation if the
full name method is unavailable (e.g. on a custom user class). | 3.551901 | 2.831607 | 1.254377 |
org_user = self.organization.add_user(user, **self.activation_kwargs())
self.invitee = user
self.save()
return org_user | def activate(self, user) | Updates the `invitee` value and saves the instance
Provided as a way of extending the behavior.
Args:
user: the newly created user
Returns:
the linking organization user | 6.176212 | 5.356549 | 1.153021 |
if hasattr(self, "organization_user"):
return self.organization_user
organization_pk = self.kwargs.get("organization_pk", None)
user_pk = self.kwargs.get("user_pk", None)
self.organization_user = get_object_or_404(
self.get_user_model().objects.select_rel... | def get_object(self) | Returns the OrganizationUser object based on the primary keys for both
the organization and the organization user. | 2.378586 | 2.151841 | 1.105373 |
# Parse the token
try:
ts_b36, hash = token.split("-")
except ValueError:
return False
try:
ts = base36_to_int(ts_b36)
except ValueError:
return False
# Check that the timestamp/uid has not been tampered with
... | def check_token(self, user, token) | Check that a password reset token is correct for a given user. | 4.027878 | 3.675324 | 1.095924 |
org_model = kwargs.pop("model", None) or kwargs.pop(
"org_model", None
) or default_org_model()
kwargs.pop("org_user_model", None) # Discard deprecated argument
org_owner_model = org_model.owner.related.related_model
try:
# Django 1.9
org_user_model = org_model.organiz... | def create_organization(
user,
name,
slug=None,
is_active=None,
org_defaults=None,
org_user_defaults=None,
**kwargs
) | Returns a new organization, also creating an initial organization user who
is the owner.
The specific models can be specified if a custom organization app is used.
The simplest way would be to use a partial.
>>> from organizations.utils import create_organization
>>> from myapp.models import Accou... | 2.215972 | 2.218038 | 0.999069 |
fields = dict([(field.name, field) for field in model._meta.fields])
return getattr(fields[model_field], attr) | def model_field_attr(model, model_field, attr) | Returns the specified attribute for the specified field on the model class. | 2.824593 | 2.742651 | 1.029877 |
if not hasattr(self, "form_class"):
raise AttributeError(_("You must define a form_class"))
return self.form_class(**kwargs) | def get_form(self, **kwargs) | Returns the form for registering or inviting a user | 3.601847 | 3.72434 | 0.96711 |
try:
relation_name = self.org_model().user_relation_name
except TypeError:
# No org_model specified, raises a TypeError because NoneType is
# not callable. This the most sensible default:
relation_name = "organizations_organization"
organi... | def activate_organizations(self, user) | Activates the related organizations for the user.
It only activates the related organizations by model type - that is, if
there are multiple types of organizations then only organizations in
the provided model class are activated. | 6.286587 | 6.125688 | 1.026266 |
try:
user = self.user_model.objects.get(id=user_id, is_active=False)
except self.user_model.DoesNotExist:
raise Http404(_("Your URL may have expired."))
if not RegistrationTokenGenerator().check_token(user, token):
raise Http404(_("Your URL may have ... | def activate_view(self, request, user_id, token) | View function that activates the given User by setting `is_active` to
true if the provided information is verified. | 2.172362 | 2.184312 | 0.994529 |
if user.is_active:
return False
token = RegistrationTokenGenerator().make_token(user)
kwargs.update({"token": token})
self.email_message(
user, self.reminder_subject, self.reminder_body, sender, **kwargs
).send() | def send_reminder(self, user, sender=None, **kwargs) | Sends a reminder email to the specified user | 4.120022 | 4.219953 | 0.97632 |
if sender:
try:
display_name = sender.get_full_name()
except (AttributeError, TypeError):
display_name = sender.get_username()
from_email = "%s <%s>" % (
display_name, email.utils.parseaddr(settings.DEFAULT_FROM_EMAIL)[... | def email_message(
self,
user,
subject_template,
body_template,
sender=None,
message_class=EmailMessage,
**kwargs
) | Returns an email message for a new user. This can be easily overridden.
For instance, to send an HTML message, use the EmailMultiAlternatives message_class
and attach the additional conent. | 2.285553 | 2.198557 | 1.03957 |
try:
user = self.user_model.objects.get(email=email)
except self.user_model.DoesNotExist:
user = self.user_model.objects.create(
username=self.get_username(),
email=email,
password=self.user_model.objects.make_random_passwo... | def register_by_email(self, email, sender=None, request=None, **kwargs) | Returns a User object filled with dummy data and not active, and sends
an invitation email. | 2.016287 | 2.00606 | 1.005098 |
if user.is_active:
return False
token = self.get_token(user)
kwargs.update({"token": token})
self.email_message(
user, self.activation_subject, self.activation_body, sender, **kwargs
).send() | def send_activation(self, user, sender=None, **kwargs) | Invites a user to join the site | 3.381951 | 3.566803 | 0.948174 |
try:
if request.user.is_authenticated():
return redirect("organization_add")
except TypeError:
if request.user.is_authenticated:
return redirect("organization_add")
form = org_registration_form(self.org_model)(request.POST or None)... | def create_view(self, request) | Initiates the organization and user account creation process | 2.202793 | 2.141173 | 1.028778 |
try:
user = self.user_model.objects.get(email=email)
except self.user_model.DoesNotExist:
# TODO break out user creation process
if "username" in inspect.getargspec(
self.user_model.objects.create_user
).args:
user ... | def invite_by_email(self, email, sender=None, request=None, **kwargs) | Creates an inactive user with the information we know and then sends
an invitation email for that user to complete registration.
If your project uses email in a different way then you should make to
extend this method as it only checks the `email` attribute for Users. | 2.151868 | 2.129338 | 1.01058 |
if user.is_active:
return False
token = self.get_token(user)
kwargs.update({"token": token})
self.email_message(
user, self.invitation_subject, self.invitation_body, sender, **kwargs
).send()
return True | def send_invitation(self, user, sender=None, **kwargs) | An intermediary function for sending an invitation email that
selects the templates, generating the token, and ensuring that the user
has not already joined the site. | 3.34565 | 3.294924 | 1.015395 |
if not user.is_active:
return False
self.email_message(
user, self.notification_subject, self.notification_body, sender, **kwargs
).send()
return True | def send_notification(self, user, sender=None, **kwargs) | An intermediary function for sending an notification email informing
a pre-existing, active user that they have been added to a new
organization. | 4.180814 | 4.735067 | 0.882947 |
users_count = self.users.all().count()
if users_count == 0:
is_admin = True
# TODO get specific org user?
org_user = self._org_user_model.objects.create(
user=user, organization=self, is_admin=is_admin
)
if users_count == 0:
# ... | def add_user(self, user, is_admin=False) | Adds a new user and if the first user makes the user an admin and
the owner. | 3.494553 | 3.300638 | 1.058751 |
org_user = self._org_user_model.objects.get(user=user, organization=self)
org_user.delete()
# User removed signal
user_removed.send(sender=self, user=user) | def remove_user(self, user) | Deletes a user from an organization. | 4.773029 | 4.038393 | 1.181913 |
is_admin = kwargs.pop("is_admin", False)
users_count = self.users.all().count()
if users_count == 0:
is_admin = True
org_user, created = self._org_user_model.objects.get_or_create(
organization=self, user=user, defaults={"is_admin": is_admin}
)
... | def get_or_add_user(self, user, **kwargs) | Adds a new user to the organization, and if it's the first user makes
the user an admin and the owner. Uses the `get_or_create` method to
create or return the existing user.
`user` should be a user instance, e.g. `auth.User`.
Returns the same tuple as the `get_or_create` method, the
... | 2.789866 | 2.550682 | 1.093773 |
old_owner = self.owner.organization_user
self.owner.organization_user = new_owner
self.owner.save()
# Owner changed signal
owner_changed.send(sender=self, old=old_owner, new=new_owner) | def change_owner(self, new_owner) | Changes ownership of an organization. | 3.681262 | 3.3383 | 1.102736 |
return True if self.organization_users.filter(
user=user, is_admin=True
) else False | def is_admin(self, user) | Returns True is user is an admin in the organization, otherwise false | 6.965381 | 5.230572 | 1.331667 |
from organizations.exceptions import OwnershipRequired
try:
if self.organization.owner.organization_user.pk == self.pk:
raise OwnershipRequired(
_(
"Cannot delete organization owner "
"before organi... | def delete(self, using=None) | If the organization user is also the owner, this should not be deleted
unless it's part of a cascade from the Organization.
If there is no owner then the deletion should proceed. | 8.489153 | 7.340519 | 1.156479 |
from organizations.exceptions import OrganizationMismatch
if self.organization_user.organization.pk != self.organization.pk:
raise OrganizationMismatch
else:
super(AbstractBaseOrganizationOwner, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | Extends the default save method by verifying that the chosen
organization user is associated with the organization.
Method validates against the primary key of the organization because
when validating an inherited model it may be checking an instance of
`Organization` against an instanc... | 6.576055 | 4.556627 | 1.443185 |
parser = argparse.ArgumentParser(description='Convert ULog to KML')
parser.add_argument('filename', metavar='file.ulg', help='ULog input file')
parser.add_argument('-o', '--output', dest='output_filename',
help="output filename", default='track.kml')
parser.add_argument('-... | def main() | Command line interface | 2.879434 | 2.885156 | 0.998017 |
x = max([x, 0])
colors_arr = [simplekml.Color.red, simplekml.Color.green, simplekml.Color.blue,
simplekml.Color.violet, simplekml.Color.yellow, simplekml.Color.orange,
simplekml.Color.burlywood, simplekml.Color.azure, simplekml.Color.lightblue,
simplekm... | def _kml_default_colors(x) | flight mode to color conversion | 2.436793 | 2.413771 | 1.009538 |
default_style = {
'extrude': False,
'line_width': 3
}
used_style = default_style
if style is not None:
for key in style:
used_style[key] = style[key]
if not isinstance(position_topic_name, list):
position_topic_name = [position_topic_name]
... | def convert_ulog2kml(ulog_file_name, output_file_name, position_topic_name=
'vehicle_gps_position', colors=_kml_default_colors, altitude_offset=0,
minimum_interval_s=0.1, style=None, camera_trigger_topic_name=None) | Coverts and ULog file to a CSV file.
:param ulog_file_name: The ULog filename to open and read
:param output_file_name: KML Output file name
:param position_topic_name: either name of a topic (must have 'lon', 'lat' &
'alt' fields), or a list of topic names
:param colors: lambda function wit... | 2.630103 | 2.520136 | 1.043635 |
data = ulog.data_list
topic_instance = 0
cur_dataset = [elem for elem in data
if elem.name == camera_trigger_topic_name and elem.multi_id == topic_instance]
if len(cur_dataset) > 0:
cur_dataset = cur_dataset[0]
pos_lon = cur_dataset.data['lon']
pos_lat ... | def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset) | Add camera trigger points to the map | 2.80298 | 2.665483 | 1.051585 |
parser = argparse.ArgumentParser(
description='Extract the raw gps communication from an ULog file')
parser.add_argument('filename', metavar='file.ulg', help='ULog input file')
def is_valid_directory(parser, arg):
if not os.path.isdir(arg):
parser.error('The direct... | def main() | Command line interface | 2.665493 | 2.656722 | 1.003301 |
return [elem for elem in self._data_list
if elem.name == name and elem.multi_id == multi_instance][0] | def get_dataset(self, name, multi_instance=0) | get a specific dataset.
example:
try:
gyro_data = ulog.get_dataset('sensor_gyro')
except (KeyError, IndexError, ValueError) as error:
print(type(error), "(sensor_gyro):", error)
:param name: name of the dataset
:param multi_instance: the multi_id, defaul... | 6.32483 | 5.671854 | 1.115126 |
if msg_info.key in self._msg_info_multiple_dict:
if msg_info.is_continued:
self._msg_info_multiple_dict[msg_info.key][-1].append(msg_info.value)
else:
self._msg_info_multiple_dict[msg_info.key].append([msg_info.value])
else:
se... | def _add_message_info_multiple(self, msg_info) | add a message info multiple to self._msg_info_multiple_dict | 1.96871 | 1.652282 | 1.19151 |
if isinstance(log_file, str):
self._file_handle = open(log_file, "rb")
else:
self._file_handle = log_file
# parse the whole file
self._read_file_header()
self._last_timestamp = self._start_timestamp
self._read_file_definitions()
... | def _load_file(self, log_file, message_name_filter_list) | load and parse an ULog file into memory | 3.396372 | 3.172439 | 1.070587 |
if read_until is None:
read_until = 1 << 50 # make it larger than any possible log file
try:
# pre-init reusable objects
header = self._MessageHeader()
msg_data = self._MessageData()
while True:
data = self._file_han... | def _read_file_data(self, message_name_filter_list, read_until=None) | read the file data section
:param read_until: an optional file offset: if set, parse only up to
this offset (smaller than) | 3.026786 | 3.002519 | 1.008082 |
# We need to handle 2 cases:
# - corrupt file (we do our best to read the rest of the file)
# - new ULog message type got added (we just want to skip the message)
if header.msg_type == 0 or header.msg_size == 0 or header.msg_size > 10000:
if not self._file_corrupt an... | def _check_file_corruption(self, header) | check for file corruption based on an unknown message type in the header | 5.856185 | 5.452462 | 1.074044 |
if key_name in self._msg_info_dict:
val = self._msg_info_dict[key_name]
return ((val >> 24) & 0xff, (val >> 16) & 0xff, (val >> 8) & 0xff, val & 0xff)
return None | def get_version_info(self, key_name='ver_sw_release') | get the (major, minor, patch, type) version information as tuple.
Returns None if not found
definition of type is:
>= 0: development
>= 64: alpha version
>= 128: beta version
>= 192: RC version
== 255: release version | 2.234154 | 2.185542 | 1.022242 |
version = self.get_version_info(key_name)
if not version is None and version[3] >= 64:
type_str = ''
if version[3] < 128: type_str = ' (alpha)'
elif version[3] < 192: type_str = ' (beta)'
elif version[3] < 255: type_str = ' (RC)'
retur... | def get_version_info_str(self, key_name='ver_sw_release') | get version information in the form 'v1.2.3 (RC)', or None if version
tag either not found or it's a development version | 2.585657 | 2.449822 | 1.055447 |
parser = argparse.ArgumentParser(description='Convert ULog to CSV')
parser.add_argument('filename', metavar='file.ulg', help='ULog input file')
parser.add_argument(
'-m', '--messages', dest='messages',
help=("Only consider given messages. Must be a comma-separated list of"
... | def main() | Command line interface | 3.202885 | 3.204958 | 0.999353 |
msg_filter = messages.split(',') if messages else None
ulog = ULog(ulog_file_name, msg_filter)
data = ulog.data_list
output_file_prefix = ulog_file_name
# strip '.ulg'
if output_file_prefix.lower().endswith('.ulg'):
output_file_prefix = output_file_prefix[:-4]
# write to dif... | def convert_ulog2csv(ulog_file_name, messages, output, delimiter) | Coverts and ULog file to a CSV file.
:param ulog_file_name: The ULog filename to open and read
:param messages: A list of message names
:param output: Output file path
:param delimiter: CSV delimiter
:return: None | 3.046809 | 3.101909 | 0.982237 |
m1, s1 = divmod(int(ulog.start_timestamp/1e6), 60)
h1, m1 = divmod(m1, 60)
m2, s2 = divmod(int((ulog.last_timestamp - ulog.start_timestamp)/1e6), 60)
h2, m2 = divmod(m2, 60)
print("Logging start time: {:d}:{:02d}:{:02d}, duration: {:d}:{:02d}:{:02d}".format(
h1, m1, s1, h2, m2, s2))
... | def show_info(ulog, verbose) | Show general information from an ULog | 2.654045 | 2.653331 | 1.000269 |
parser = argparse.ArgumentParser(description='Display information from an ULog file')
parser.add_argument('filename', metavar='file.ulg', help='ULog input file')
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='Verbose output', default=False)
... | def main() | Commande line interface | 2.641922 | 2.621634 | 1.007739 |
parser = argparse.ArgumentParser(description='Display logged messages from an ULog file')
parser.add_argument('filename', metavar='file.ulg', help='ULog input file')
args = parser.parse_args()
ulog_file_name = args.filename
msg_filter = [] # we don't need the data messages
ulog = ULog(u... | def main() | Commande line interface | 3.615132 | 3.54272 | 1.02044 |
parser = argparse.ArgumentParser(description='Extract parameters from an ULog file')
parser.add_argument('filename', metavar='file.ulg', help='ULog input file')
parser.add_argument('-d', '--delimiter', dest='delimiter', action='store',
help='Use delimiter in CSV (default is \'... | def main() | Commande line interface | 1.921724 | 1.919935 | 1.000932 |
mav_type = self._ulog.initial_parameters.get('MAV_TYPE', None)
if mav_type == 1: # fixed wing always uses EKF2
return 'EKF2'
mc_est_group = self._ulog.initial_parameters.get('SYS_MC_EST_GROUP', None)
return {0: 'INAV',
1: 'LPE',
2: '... | def get_estimator(self) | return the configured estimator as string from initial parameters | 6.349438 | 5.630481 | 1.12769 |
self._add_roll_pitch_yaw_to_message('vehicle_attitude')
self._add_roll_pitch_yaw_to_message('vehicle_vision_attitude')
self._add_roll_pitch_yaw_to_message('vehicle_attitude_groundtruth')
self._add_roll_pitch_yaw_to_message('vehicle_attitude_setpoint', '_d') | def add_roll_pitch_yaw(self) | convenience method to add the fields 'roll', 'pitch', 'yaw' to the
loaded data using the quaternion fields (does not update field_data).
Messages are: 'vehicle_attitude.q' and 'vehicle_attitude_setpoint.q_d',
'vehicle_attitude_groundtruth.q' and 'vehicle_vision_attitude.q' | 3.346507 | 1.858368 | 1.800777 |
ret_val = []
for key in self._ulog.initial_parameters:
param_val = self._ulog.initial_parameters[key]
if key.startswith('RC_MAP_') and param_val == channel + 1:
ret_val.append(key[7:].capitalize())
if len(ret_val) > 0:
return ret_val
... | def get_configured_rc_input_names(self, channel) | find all RC mappings to a given channel and return their names
:param channel: input channel (0=first)
:return: list of strings or None | 4.320639 | 4.22786 | 1.021945 |
directory = os.path.abspath(directory)
config = load_config(directory)
to_err = draft
click.echo("Loading template...", err=to_err)
if config["template"] is None:
template = pkg_resources.resource_string(
__name__, "templates/template.rst"
).decode("utf8")
else:... | def __main(draft, directory, project_name, project_version, project_date, answer_yes) | The main entry point. | 3.044418 | 3.037898 | 1.002146 |
content = OrderedDict()
fragment_filenames = []
for key, val in sections.items():
if fragment_directory is not None:
section_dir = os.path.join(base_directory, val, fragment_directory)
else:
section_dir = os.path.join(base_directory, val)
files = os.li... | def find_fragments(base_directory, sections, fragment_directory, definitions) | Sections are a dictonary of section names to paths. | 2.873085 | 2.848692 | 1.008563 |
# Based on Python 3's textwrap.indent
def prefixed_lines():
for line in text.splitlines(True):
yield (prefix + line if line.strip() else line)
return u"".join(prefixed_lines()) | def indent(text, prefix) | Adds `prefix` to the beginning of non-empty lines in `text`. | 3.253721 | 3.444002 | 0.94475 |
jinja_template = Template(template, trim_blocks=True)
data = OrderedDict()
for section_name, section_value in fragments.items():
data[section_name] = OrderedDict()
for category_name, category_value in section_value.items():
# Suppose we start with an ordering like this:... | def render_fragments(template, issue_format, fragments, definitions, underlines, wrap) | Render the fragments into a news file. | 2.948184 | 2.943806 | 1.001487 |
a = 3 / 8 if n <= 10 else 0.5
return (np.arange(n) + 1 - a) / (n + 1 - 2 * a) | def _ppoints(n, a=0.5) | Ordinates For Probability Plotting.
Numpy analogue or `R`'s `ppoints` function.
Parameters
----------
n : int
Number of points generated
a : float
Offset fraction (typically between 0 and 1)
Returns
-------
p : array
Sequence of probabilities at which to evalua... | 4.674747 | 6.23789 | 0.749411 |
# Check that stasmodels is installed
from pingouin.utils import _is_statsmodels_installed
_is_statsmodels_installed(raise_error=True)
from statsmodels.api import stats
from statsmodels.formula.api import ols
# Check that covariates are numeric ('float', 'int')
assert all([data[covar[i]... | def ancovan(dv=None, covar=None, between=None, data=None,
export_filename=None) | ANCOVA with n covariates.
This is an internal function. The main call to this function should be done
by the :py:func:`pingouin.ancova` function.
Parameters
----------
dv : string
Name of column containing the dependant variable.
covar : string
Name(s) of columns containing the... | 3.508712 | 2.968722 | 1.181893 |
# Check extension
d, ext = op.splitext(dname)
if ext.lower() == '.csv':
dname = d
# Check that dataset exist
if dname not in dts['dataset'].values:
raise ValueError('Dataset does not exist. Valid datasets names are',
dts['dataset'].values)
# Load dat... | def read_dataset(dname) | Read example datasets.
Parameters
----------
dname : string
Name of dataset to read (without extension).
Must be a valid dataset present in pingouin.datasets
Returns
-------
data : pd.DataFrame
Dataset
Examples
--------
Load the ANOVA dataset
>>> from ... | 4.244759 | 5.309356 | 0.799487 |
assert tail in ['two-sided', 'upper', 'lower'], 'Wrong tail argument.'
assert isinstance(estimate, (int, float))
bootstat = np.asarray(bootstat)
assert bootstat.ndim == 1, 'bootstat must be a 1D array.'
n_boot = bootstat.size
assert n_boot >= 1, 'bootstat must have at least one value.'
... | def _perm_pval(bootstat, estimate, tail='two-sided') | Compute p-values from a permutation test.
Parameters
----------
bootstat : 1D array
Permutation distribution.
estimate : float or int
Point estimate.
tail : str
'upper': one-sided p-value (upper tail)
'lower': one-sided p-value (lower tail)
'two-sided': two-s... | 2.148579 | 2.154421 | 0.997289 |
if 'F' in df.keys():
print('\n=============\nANOVA SUMMARY\n=============\n')
if 'A' in df.keys():
print('\n==============\nPOST HOC TESTS\n==============\n')
print(tabulate(df, headers="keys", showindex=False, floatfmt=floatfmt,
tablefmt=tablefmt))
print('') | def print_table(df, floatfmt=".3f", tablefmt='simple') | Pretty display of table.
See: https://pypi.org/project/tabulate/.
Parameters
----------
df : DataFrame
Dataframe to print (e.g. ANOVA summary)
floatfmt : string
Decimal number formatting
tablefmt : string
Table format (e.g. 'simple', 'plain', 'html', 'latex', 'grid') | 4.325255 | 4.285407 | 1.009298 |
import os.path as op
extension = op.splitext(fname.lower())[1]
if extension == '':
fname = fname + '.csv'
table.to_csv(fname, index=None, sep=',', encoding='utf-8',
float_format='%.4f', decimal='.') | def _export_table(table, fname) | Export DataFrame to .csv | 3.410904 | 3.168677 | 1.076444 |
if x.ndim == 1:
# 1D arrays
x_mask = ~np.isnan(x)
else:
# 2D arrays
ax = 1 if axis == 'rows' else 0
x_mask = ~np.any(np.isnan(x), axis=ax)
# Check if missing values are present
if ~x_mask.all():
ax = 0 if axis == 'rows' else 1
ax = 0 if x.ndim... | def _remove_na_single(x, axis='rows') | Remove NaN in a single array.
This is an internal Pingouin function. | 2.557142 | 2.499004 | 1.023264 |
# Safety checks
x = np.asarray(x)
assert x.size > 1, 'x must have more than one element.'
assert axis in ['rows', 'columns'], 'axis must be rows or columns.'
if y is None:
return _remove_na_single(x, axis=axis)
elif isinstance(y, (int, float, str)):
return _remove_na_single... | def remove_na(x, y=None, paired=False, axis='rows') | Remove missing values along a given axis in one or more (paired) numpy
arrays.
Parameters
----------
x, y : 1D or 2D arrays
Data. ``x`` and ``y`` must have the same number of dimensions.
``y`` can be None to only remove missing values in ``x``.
paired : bool
Indicates if the... | 2.285095 | 2.482 | 0.920667 |
# Safety checks
assert isinstance(aggregate, str), 'aggregate must be a str.'
assert isinstance(within, (str, list)), 'within must be str or list.'
assert isinstance(subject, str), 'subject must be a string.'
assert isinstance(data, pd.DataFrame), 'Data must be a DataFrame.'
idx_cols = _fl... | def remove_rm_na(dv=None, within=None, subject=None, data=None,
aggregate='mean') | Remove missing values in long-format repeated-measures dataframe.
Parameters
----------
dv : string or list
Dependent variable(s), from which the missing values should be removed.
If ``dv`` is not specified, all the columns in the dataframe are
considered. ``dv`` must be numeric.
... | 4.033256 | 3.81918 | 1.056053 |
result = []
# Remove None
x = list(filter(None.__ne__, x))
for el in x:
x_is_iter = isinstance(x, collections.Iterable)
if x_is_iter and not isinstance(el, (str, tuple)):
result.extend(_flatten_list(el))
else:
result.append(el)
return result | def _flatten_list(x) | Flatten an arbitrarily nested list into a new list.
This can be useful to select pandas DataFrame columns.
From https://stackoverflow.com/a/16176969/10581531
Examples
--------
>>> from pingouin.utils import _flatten_list
>>> x = ['X1', ['M1', 'M2'], 'Y1', ['Y2']]
>>> _flatten_list(x)
... | 2.678454 | 3.748447 | 0.71455 |
# Check that data is a dataframe
if not isinstance(data, pd.DataFrame):
raise ValueError('Data must be a pandas dataframe.')
# Check that both dv and data are provided.
if any(v is None for v in [dv, data]):
raise ValueError('DV and data must be specified')
# Check that dv is a ... | def _check_dataframe(dv=None, between=None, within=None, subject=None,
effects=None, data=None) | Check dataframe | 2.857942 | 2.820945 | 1.013115 |
if bf >= 1e4 or bf <= 1e-4:
out = np.format_float_scientific(bf, precision=precision, trim=trim)
else:
out = np.format_float_positional(bf, precision=precision, trim=trim)
return out | def _format_bf(bf, precision=3, trim='0') | Format BF10 to floating point or scientific notation. | 2.38458 | 2.143653 | 1.112391 |
from scipy.special import gamma
# Function to be integrated
def fun(g, r, n):
return np.exp(((n - 2) / 2) * np.log(1 + g) + (-(n - 1) / 2)
* np.log(1 + (1 - r**2) * g) + (-3 / 2)
* np.log(g) + - n / (2 * g))
# JZS Bayes factor calculation
in... | def bayesfactor_pearson(r, n) | Bayes Factor of a Pearson correlation.
Parameters
----------
r : float
Pearson correlation coefficient
n : int
Sample size
Returns
-------
bf : str
Bayes Factor (BF10).
The Bayes Factor quantifies the evidence in favour of the alternative
hypothesis.... | 5.013548 | 3.229557 | 1.552395 |
from scipy.stats import gmean
# Geometric mean
geo_mean = gmean(x)
# Geometric standard deviation
gstd = np.exp(np.sqrt(np.sum((np.log(x / geo_mean))**2) / (len(x) - 1)))
# Geometric z-score
return np.log(x / geo_mean) / np.log(gstd) | def gzscore(x) | Geometric standard (Z) score.
Parameters
----------
x : array_like
Array of raw values
Returns
-------
gzscore : array_like
Array of geometric z-scores (same shape as x)
Notes
-----
Geometric Z-scores are better measures of dispersion than arithmetic
z-scores w... | 3.001783 | 3.495718 | 0.858703 |
from scipy.stats import anderson as ads
k = len(args)
from_dist = np.zeros(k, 'bool')
sig_level = np.zeros(k)
for j in range(k):
st, cr, sig = ads(args[j], dist=dist)
from_dist[j] = True if (st > cr).any() else False
sig_level[j] = sig[np.argmin(np.abs(st - cr))]
if... | def anderson(*args, dist='norm') | Anderson-Darling test of distribution.
Parameters
----------
sample1, sample2,... : array_like
Array of sample data. May be different lengths.
dist : string
Distribution ('norm', 'expon', 'logistic', 'gumbel')
Returns
-------
from_dist : boolean
True if data comes f... | 3.141508 | 3.428428 | 0.916312 |
if not _check_eftype(eftype):
err = "Could not interpret input '{}'".format(eftype)
raise ValueError(err)
if not isinstance(tval, float):
err = "T-value must be float"
raise ValueError(err)
# Compute Cohen d (Lakens, 2013)
if nx is not None and ny is not None:
... | def compute_effsize_from_t(tval, nx=None, ny=None, N=None, eftype='cohen') | Compute effect size from a T-value.
Parameters
----------
tval : float
T-value
nx, ny : int, optional
Group sample sizes.
N : int, optional
Total sample size (will not be used if nx and ny are specified)
eftype : string, optional
desired output effect size
R... | 4.072371 | 3.744373 | 1.087598 |
# Check that sklearn is installed
from pingouin.utils import _is_sklearn_installed
_is_sklearn_installed(raise_error=True)
from scipy.stats import chi2
from sklearn.covariance import MinCovDet
X = np.column_stack((x, y))
nrows, ncols = X.shape
gval = np.sqrt(chi2.ppf(0.975, 2))
... | def skipped(x, y, method='spearman') | Skipped correlation (Rousselet and Pernet 2012).
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
method : str
Method used to compute the correlation after outlier removal. Can be
either 'spearman' (default) or 'pearson'.... | 3.191869 | 3.028901 | 1.053804 |
n, m = b.shape
MD = np.zeros((n, n_boot))
nr = np.arange(n)
xB = np.random.choice(nr, size=(n_boot, n), replace=True)
# Bootstrap the MD
for i in np.arange(n_boot):
s1 = b[xB[i, :], 0]
s2 = b[xB[i, :], 1]
X = np.column_stack((s1, s2))
mu = X.mean(0)
... | def bsmahal(a, b, n_boot=200) | Bootstraps Mahalanobis distances for Shepherd's pi correlation.
Parameters
----------
a : ndarray (shape=(n, 2))
Data
b : ndarray (shape=(n, 2))
Data
n_boot : int
Number of bootstrap samples to calculate.
Returns
-------
m : ndarray (shape=(n,))
Mahalano... | 3.05934 | 3.106973 | 0.984669 |
from scipy.stats import spearmanr
X = np.column_stack((x, y))
# Bootstrapping on Mahalanobis distance
m = bsmahal(X, X, n_boot)
# Determine outliers
outliers = (m >= 6)
# Compute correlation
r, pval = spearmanr(x[~outliers], y[~outliers])
# (optional) double the p-value to ... | def shepherd(x, y, n_boot=200) | Shepherd's Pi correlation, equivalent to Spearman's rho after outliers
removal.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
n_boot : int
Number of bootstrap samples to calculate.
Returns
-------
r : float
... | 5.023576 | 4.186525 | 1.199939 |
from scipy.stats import t
X = np.column_stack((x, y))
nx = X.shape[0]
M = np.tile(np.median(X, axis=0), nx).reshape(X.shape)
W = np.sort(np.abs(X - M), axis=0)
m = int((1 - beta) * nx)
omega = W[m - 1, :]
P = (X - M) / omega
P[np.isinf(P)] = 0
P[np.isnan(P)] = 0
# Loop ... | def percbend(x, y, beta=.2) | Percentage bend correlation (Wilcox 1994).
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
beta : float
Bending constant for omega (0 <= beta <= 0.5).
Returns
-------
r : float
Percentage bend correlation co... | 2.881965 | 2.841762 | 1.014147 |
# Pairwise Euclidean distances
b = squareform(pdist(y, metric='euclidean'))
# Double centering
B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()
# Compute squared distance covariances
dcov2_yy = np.vdot(B, B) / n2
dcov2_xy = np.vdot(A, B) / n2
return np.sqrt(dcov2... | def _dcorr(y, n2, A, dcov2_xx) | Helper function for distance correlation bootstrapping. | 2.605836 | 2.592235 | 1.005247 |
# Mediator(s) model (M(j) ~ X + covar)
beta_m = []
for j in range(n_mediator):
if mtype == 'linear':
beta_m.append(linear_regression(X_val[idx], M_val[idx, j],
coef_only=True)[1])
else:
beta_m.append(logistic_regression... | def _point_estimate(X_val, XM_val, M_val, y_val, idx, n_mediator,
mtype='linear') | Point estimate of indirect effect based on bootstrap sample. | 3.399992 | 3.324722 | 1.02264 |
# Bias of bootstrap estimates
z0 = norm.ppf(np.sum(ab_estimates < sample_point) / n_boot)
# Adjusted intervals
adjusted_ll = norm.cdf(2 * z0 + norm.ppf(alpha / 2)) * 100
adjusted_ul = norm.cdf(2 * z0 + norm.ppf(1 - alpha / 2)) * 100
ll = np.percentile(ab_estimates, q=adjusted_ll)
ul = ... | def _bca(ab_estimates, sample_point, n_boot, alpha=0.05) | Get (1 - alpha) * 100 bias-corrected confidence interval estimate
Note that this is similar to the "cper" module implemented in
:py:func:`pingouin.compute_bootci`.
Parameters
----------
ab_estimates : 1d array-like
Array with bootstrap estimates for each sample.
sample_point : float
... | 3.043114 | 3.239449 | 0.939393 |
if estimate == 0:
out = 1
else:
out = 2 * min(sum(boot > 0), sum(boot < 0)) / len(boot)
return min(out, 1) | def _pval_from_bootci(boot, estimate) | Compute p-value from bootstrap distribution.
Similar to the pval function in the R package mediation.
Note that this is less accurate than a permutation test because the
bootstrap distribution is not conditioned on a true null hypothesis. | 3.711453 | 4.027623 | 0.9215 |
aov = anova(data=self, dv=dv, between=between, detailed=detailed,
export_filename=export_filename)
return aov | def _anova(self, dv=None, between=None, detailed=False, export_filename=None) | Return one-way and two-way ANOVA. | 2.74787 | 2.685799 | 1.023111 |
aov = welch_anova(data=self, dv=dv, between=between,
export_filename=export_filename)
return aov | def _welch_anova(self, dv=None, between=None, export_filename=None) | Return one-way Welch ANOVA. | 2.878437 | 2.998499 | 0.959959 |
aov = rm_anova(data=self, dv=dv, within=within, subject=subject,
correction=correction, detailed=detailed,
export_filename=export_filename)
return aov | def _rm_anova(self, dv=None, within=None, subject=None, detailed=False,
correction='auto', export_filename=None) | One-way and two-way repeated measures ANOVA. | 2.307785 | 2.772773 | 0.832302 |
aov = mixed_anova(data=self, dv=dv, between=between, within=within,
subject=subject, correction=correction,
export_filename=export_filename)
return aov | def _mixed_anova(self, dv=None, between=None, within=None, subject=None,
correction=False, export_filename=None) | Two-way mixed ANOVA. | 2.164557 | 2.48643 | 0.870548 |
stats = pairwise_corr(data=self, columns=columns, covar=covar,
tail=tail, method=method, padjust=padjust,
export_filename=export_filename)
return stats | def _pairwise_corr(self, columns=None, covar=None, tail='two-sided',
method='pearson', padjust='none', export_filename=None) | Pairwise (partial) correlations. | 2.087238 | 2.421217 | 0.862062 |
stats = partial_corr(data=self, x=x, y=y, covar=covar, x_covar=x_covar,
y_covar=y_covar, tail=tail, method=method)
return stats | def _partial_corr(self, x=None, y=None, covar=None, x_covar=None, y_covar=None,
tail='two-sided', method='pearson') | Partial and semi-partial correlation. | 2.05617 | 2.008122 | 1.023927 |
V = self.cov() # Covariance matrix
Vi = np.linalg.pinv(V) # Inverse covariance matrix
D = np.diag(np.sqrt(1 / np.diag(Vi)))
pcor = -1 * (D @ Vi @ D) # Partial correlation matrix
pcor[np.diag_indices_from(pcor)] = 1
return pd.DataFrame(pcor, index=V.index, columns=V.columns) | def pcorr(self) | Partial correlation matrix (:py:class:`pandas.DataFrame` method).
Returns
----------
pcormat : :py:class:`pandas.DataFrame`
Partial correlation matrix.
Notes
-----
This function calculates the pairwise partial correlations for each pair of
variables in a :py:class:`pandas.DataFrame... | 3.378307 | 4.100721 | 0.823832 |
stats = mediation_analysis(data=self, x=x, m=m, y=y, covar=covar,
alpha=alpha, n_boot=n_boot, seed=seed,
return_dist=return_dist)
return stats | def _mediation_analysis(self, x=None, m=None, y=None, covar=None,
alpha=0.05, n_boot=500, seed=None, return_dist=False) | Mediation analysis. | 2.120529 | 2.113443 | 1.003353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.