uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bb68a52698d3fa4773022102 | train | function | def test_package_contents(expect):
names = [name for name in dir(pomace) if not name.startswith("_")]
expect(names).contains("auto")
expect(names).contains("Page")
expect(names).contains("visit")
expect(names).excludes("get_distribution")
| def test_package_contents(expect):
| names = [name for name in dir(pomace) if not name.startswith("_")]
expect(names).contains("auto")
expect(names).contains("Page")
expect(names).contains("visit")
expect(names).excludes("get_distribution")
| # pylint: disable=unused-variable,expression-not-assigned
import os
from pathlib import Path
import pytest
import pomace
from pomace.config import settings
def test_package_contents(expect):
| 41 | 64 | 59 | 6 | 34 | jonesclarence37/pomace | tests/test_api.py | Python | test_package_contents | test_package_contents | 12 | 17 | 12 | 12 | 575163adb5eb7a6216a513e3b288fd100a5a009b | bigcode/the-stack | train |
879c36f06e0e2954c1c79288 | train | function | def describe_freeze():
def it_disables_automatic_actions(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
page.actions = []
page.datafile.save()
pomace.freeze()
try:
page.click_foobar()
expect(dir(page)).excludes("cl... | def describe_freeze():
| def it_disables_automatic_actions(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
page.actions = []
page.datafile.save()
pomace.freeze()
try:
page.click_foobar()
expect(dir(page)).excludes("click_foobar")
fi... | _caller(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
path = Path(__file__).parent / "sites" / "example.com" / "@" / "default.yml"
expect(page.datafile.path) == path
def describe_freeze():
| 64 | 64 | 81 | 5 | 58 | jonesclarence37/pomace | tests/test_api.py | Python | describe_freeze | describe_freeze | 32 | 43 | 32 | 32 | 812935b827aeb1e1e2bb337f430345423f5f67b2 | bigcode/the-stack | train |
e9c7cd91104c92cd0b537044 | train | function | def describe_visit():
def it_launches_a_browser(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
expect(page).contains("Example Domain")
@pytest.mark.skipif(os.name == "nt", reason="Path differs on Windows")
def it_saves_data_relative_to_caller(expect):
... | def describe_visit():
| def it_launches_a_browser(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
expect(page).contains("Example Domain")
@pytest.mark.skipif(os.name == "nt", reason="Path differs on Windows")
def it_saves_data_relative_to_caller(expect):
page = pomace.vi... |
def test_package_contents(expect):
names = [name for name in dir(pomace) if not name.startswith("_")]
expect(names).contains("auto")
expect(names).contains("Page")
expect(names).contains("visit")
expect(names).excludes("get_distribution")
def describe_visit():
| 64 | 64 | 128 | 4 | 60 | jonesclarence37/pomace | tests/test_api.py | Python | describe_visit | describe_visit | 20 | 29 | 20 | 20 | 570b941ca3e8abb5885dc2557e21761d2e3e90b9 | bigcode/the-stack | train |
00f88ad8152a135ac9564ab6 | train | class | class InlineModelAdmin(BaseModelAdmin):
"""
Options for inline editing of ``model`` instances.
Provide ``fk_name`` to specify the attribute name of the ``ForeignKey``
from ``model`` to its parent. This is required if ``model`` has more than
one ``ForeignKey`` to its parent.
"""
model = None... | class InlineModelAdmin(BaseModelAdmin):
| """
Options for inline editing of ``model`` instances.
Provide ``fk_name`` to specify the attribute name of the ``ForeignKey``
from ``model`` to its parent. This is required if ``model`` has more than
one ``ForeignKey`` to its parent.
"""
model = None
fk_name = None
formset = BaseIn... | /object_history.html"
], context)
def _create_formsets(self, request, obj, change):
"Helper function to generate formsets for add/change_view."
formsets = []
inline_instances = []
prefixes = {}
get_formsets_args = [request]
if change:
get_formsets... | 256 | 256 | 1,517 | 8 | 247 | jmcdono362/django | django/contrib/admin/options.py | Python | InlineModelAdmin | InlineModelAdmin | 1,865 | 2,034 | 1,865 | 1,865 | 6f6d1144cf89a6326917d58b044745a5681e13da | bigcode/the-stack | train |
a49e0cefbe9159fbb31979b1 | train | class | class TabularInline(InlineModelAdmin):
template = 'admin/edit_inline/tabular.html'
| class TabularInline(InlineModelAdmin):
| template = 'admin/edit_inline/tabular.html'
|
# be able to do anything with the intermediate model.
return self.has_change_permission(request, obj)
return super().has_delete_permission(request, obj)
class StackedInline(InlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
class TabularInline(InlineModelAdmin):
| 64 | 64 | 20 | 9 | 55 | jmcdono362/django | django/contrib/admin/options.py | Python | TabularInline | TabularInline | 2,041 | 2,042 | 2,041 | 2,041 | 84a47671433f187bb4e7ad525ea32c546da24b1b | bigcode/the-stack | train |
66bf824ab8e893b5c3726e39 | train | class | class BaseModelAdmin(metaclass=forms.MediaDefiningClass):
"""Functionality common to both ModelAdmin and InlineAdmin."""
autocomplete_fields = ()
raw_id_fields = ()
fields = None
exclude = None
fieldsets = None
form = forms.ModelForm
filter_vertical = ()
filter_horizontal = ()
r... | class BaseModelAdmin(metaclass=forms.MediaDefiningClass):
| """Functionality common to both ModelAdmin and InlineAdmin."""
autocomplete_fields = ()
raw_id_fields = ()
fields = None
exclude = None
fieldsets = None
form = forms.ModelForm
filter_vertical = ()
filter_horizontal = ()
radio_fields = {}
prepopulated_fields = {}
formfiel... | return 'radiolist' if radio_style == VERTICAL else 'radiolist inline'
class IncorrectLookupParameters(Exception):
pass
# Defaults for formfield_overrides. ModelAdmin subclasses can change this
# by adding to ModelAdmin.formfield_overrides.
FORMFIELD_FOR_DBFIELD_DEFAULTS = {
models.DateTimeField: {
... | 256 | 256 | 3,624 | 13 | 243 | jmcdono362/django | django/contrib/admin/options.py | Python | BaseModelAdmin | BaseModelAdmin | 98 | 510 | 98 | 98 | 54e13a6122bc99f9ef254bd0aa425dcb464ebea6 | bigcode/the-stack | train |
6785a7aad3983c3ef3442e5c | train | function | def get_content_type_for_model(obj):
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level.
from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get_for_model(obj, for_concrete_model=Fal... | def get_content_type_for_model(obj):
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level.
| from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get_for_model(obj, for_concrete_model=False)
|
IS_POPUP_VAR = '_popup'
TO_FIELD_VAR = '_to_field'
HORIZONTAL, VERTICAL = 1, 2
def get_content_type_for_model(obj):
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level.
| 64 | 64 | 62 | 35 | 28 | jmcdono362/django | django/contrib/admin/options.py | Python | get_content_type_for_model | get_content_type_for_model | 60 | 64 | 60 | 62 | 51df9cf9b4043306cd5df6ae7f46cc95438b633a | bigcode/the-stack | train |
a97d9ed33904b330f8dac3b7 | train | class | class IncorrectLookupParameters(Exception):
pass
| class IncorrectLookupParameters(Exception):
| pass
| at the module level.
from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get_for_model(obj, for_concrete_model=False)
def get_ul_class(radio_style):
return 'radiolist' if radio_style == VERTICAL else 'radiolist inline'
class IncorrectLookupParameters(Exception):
| 64 | 64 | 9 | 6 | 58 | jmcdono362/django | django/contrib/admin/options.py | Python | IncorrectLookupParameters | IncorrectLookupParameters | 71 | 72 | 71 | 71 | 8a16b10380bee0f0a306796f2ad53bf2e79ca1ff | bigcode/the-stack | train |
a211673d9e584b2e44aed706 | train | class | class ModelAdmin(BaseModelAdmin):
"""Encapsulate all admin options and functionality for a given model."""
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
list_per_page = 100
list_max_show_all = 200
list_editable = ()
search_fields = ... | class ModelAdmin(BaseModelAdmin):
| """Encapsulate all admin options and functionality for a given model."""
list_display = ('__str__',)
list_display_links = ()
list_filter = ()
list_select_related = False
list_per_page = 100
list_max_show_all = 200
list_editable = ()
search_fields = ()
date_hierarchy = None
s... | Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to delete the `obj`
model instance. If `obj` is None, this should return True if th... | 256 | 256 | 11,238 | 7 | 249 | jmcdono362/django | django/contrib/admin/options.py | Python | ModelAdmin | ModelAdmin | 513 | 1,862 | 513 | 513 | fda7a2e379b0ad51587d61e0857263484fe60e2e | bigcode/the-stack | train |
9a866cc54e8e6b69658de5df | train | class | class StackedInline(InlineModelAdmin):
template = 'admin/edit_inline/stacked.html'
| class StackedInline(InlineModelAdmin):
| template = 'admin/edit_inline/stacked.html'
| individual permissions. The user needs
# to have the change permission for the related model in order to
# be able to do anything with the intermediate model.
return self.has_change_permission(request, obj)
return super().has_delete_permission(request, obj)
class StackedInli... | 64 | 64 | 21 | 9 | 55 | jmcdono362/django | django/contrib/admin/options.py | Python | StackedInline | StackedInline | 2,037 | 2,038 | 2,037 | 2,037 | cbc342767c6c151b70eefe0b31f353e0eb1fea73 | bigcode/the-stack | train |
c30e9bf33f8e7c54adb40c67 | train | function | def get_ul_class(radio_style):
return 'radiolist' if radio_style == VERTICAL else 'radiolist inline'
| def get_ul_class(radio_style):
| return 'radiolist' if radio_style == VERTICAL else 'radiolist inline'
| (obj):
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level.
from django.contrib.contenttypes.models import ContentType
return ContentType.objects.get_for_model(obj, for_concrete_model=False)
def get_ul_class(radio_sty... | 64 | 64 | 26 | 8 | 56 | jmcdono362/django | django/contrib/admin/options.py | Python | get_ul_class | get_ul_class | 67 | 68 | 67 | 67 | 2be5420e743dccc9aeb6cf13e27fb3d6c1a42c24 | bigcode/the-stack | train |
c557bbac71e06c712e23ea7a | train | class | class TestSendEmailSendGrid(unittest.TestCase):
# Unit test for sendgrid.send_email()
def setUp(self):
self.recepients = ['foo@foo.com', 'bar@bar.com']
self.subject = 'sendgrid-send-email unit test'
self.html_content = '<b>Foo</b> bar'
self.carbon_copy = ['foo-cc@foo.com', 'bar-c... | class TestSendEmailSendGrid(unittest.TestCase):
# Unit test for sendgrid.send_email()
| def setUp(self):
self.recepients = ['foo@foo.com', 'bar@bar.com']
self.subject = 'sendgrid-send-email unit test'
self.html_content = '<b>Foo</b> bar'
self.carbon_copy = ['foo-cc@foo.com', 'bar-cc@bar.com']
self.bcc = ['foo-bcc@foo.com', 'bar-bcc@bar.com']
self.expecte... | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | 232 | 256 | 885 | 20 | 211 | robobario/airflow | tests/contrib/utils/test_sendgrid.py | Python | TestSendEmailSendGrid | TestSendEmailSendGrid | 30 | 111 | 30 | 31 | ce9ee93c0ccf62f77da4ed9fa111614c090ea8a7 | bigcode/the-stack | train |
9a1097cb6c21b1013db59ff7 | train | class | class TestInteractions(TestCaseQt):
@contextlib.contextmanager
def defaultPlot(self):
try:
widget = silx_plot.PlotWidget()
widget.show()
self.qWaitForWindowExposed(widget)
yield widget
finally:
widget.close()
widget = None
... | class TestInteractions(TestCaseQt):
@contextlib.contextmanager
| def defaultPlot(self):
try:
widget = silx_plot.PlotWidget()
widget.show()
self.qWaitForWindowExposed(widget)
yield widget
finally:
widget.close()
widget = None
self.qWait()
@contextlib.contextmanager
def ima... | = "MIT"
__date__ = "28/06/2018"
import unittest
import contextlib
import numpy
import logging
from silx.gui import qt
from silx.utils import deprecation
from silx.utils import testutils
from silx.gui.utils.testutils import TestCaseQt
from silx.utils.testutils import ParametricTestCase
from silx.gui.plot import Plo... | 256 | 256 | 2,160 | 14 | 242 | t20100/silx | src/silx/gui/plot/tools/test/testProfile.py | Python | TestInteractions | TestInteractions | 62 | 306 | 62 | 64 | 7e9c3e1bf8a7f4e47f70247229db32feb15beb48 | bigcode/the-stack | train |
32a2da62acf84d18195c9529 | train | class | class TestGetProfilePlot(TestCaseQt):
def setUp(self):
self.plot = None
super(TestGetProfilePlot, self).setUp()
def tearDown(self):
if self.plot is not None:
manager = self.plot.getProfileToolbar().getProfileManager()
manager.clearProfile()
manager =... | class TestGetProfilePlot(TestCaseQt):
| def setUp(self):
self.plot = None
super(TestGetProfilePlot, self).setUp()
def tearDown(self):
if self.plot is not None:
manager = self.plot.getProfileToolbar().getProfileManager()
manager.clearProfile()
manager = None
self.plot.setAttribut... | 1)
self.mouseMove(plot2D, pos=pos2)
self.mouseRelease(plot2D, qt.Qt.LeftButton, pos=pos2)
manager = toolBar.getProfileManager()
roi = manager.getCurrentRoi()
roi.setProfileMethod("sum")
roi.setProfileType("2D")
roi.setProfileLineWidth(3)
for _ in range(2... | 181 | 181 | 606 | 9 | 172 | t20100/silx | src/silx/gui/plot/tools/test/testProfile.py | Python | TestGetProfilePlot | TestGetProfilePlot | 576 | 657 | 576 | 577 | 8e4203f8b04df99c42e747016dc0140d118eab65 | bigcode/the-stack | train |
05ea8c8c0c339f58c5748dbb | train | class | class TestDeprecatedProfileToolBar(TestCaseQt):
"""Tests old features of the ProfileToolBar widget."""
def setUp(self):
self.plot = None
super(TestDeprecatedProfileToolBar, self).setUp()
def tearDown(self):
if self.plot is not None:
self.plot.setAttribute(qt.Qt.WA_Delet... | class TestDeprecatedProfileToolBar(TestCaseQt):
| """Tests old features of the ProfileToolBar widget."""
def setUp(self):
self.plot = None
super(TestDeprecatedProfileToolBar, self).setUp()
def tearDown(self):
if self.plot is not None:
self.plot.setAttribute(qt.Qt.WA_DeleteOnClose)
self.plot.close()
... | :
curveItem = self.toolBar.getProfilePlot().getAllCurves()[0]
if method == 'sum':
self.assertTrue(curveItem.getData()[1].max() > 10000)
elif method == 'mean':
self.assertTrue(curveItem.getData... | 120 | 120 | 402 | 10 | 110 | t20100/silx | src/silx/gui/plot/tools/test/testProfile.py | Python | TestDeprecatedProfileToolBar | TestDeprecatedProfileToolBar | 433 | 483 | 433 | 433 | cdf3b2ae1ae06eba630a79b16a2c73de411eabc6 | bigcode/the-stack | train |
4ab8dea0573156d39bec6431 | train | class | class TestProfileToolBar(TestCaseQt, ParametricTestCase):
"""Tests for ProfileToolBar widget."""
def setUp(self):
super(TestProfileToolBar, self).setUp()
self.plot = PlotWindow()
self.toolBar = Profile.ProfileToolBar(plot=self.plot)
self.plot.addToolBar(self.toolBar)
se... | class TestProfileToolBar(TestCaseQt, ParametricTestCase):
| """Tests for ProfileToolBar widget."""
def setUp(self):
super(TestProfileToolBar, self).setUp()
self.plot = PlotWindow()
self.toolBar = Profile.ProfileToolBar(plot=self.plot)
self.plot.addToolBar(self.toolBar)
self.plot.show()
self.qWaitForWindowExposed(self.plo... | ._DefaultImageStackProfileRoiEditor),
(rois.ProfileImageStackLineROI, editors._DefaultImageStackProfileRoiEditor),
(rois.ProfileImageStackCrossROI, editors._DefaultImageStackProfileRoiEditor),
]
with self.defaultPlot() as plot:
profileManager = manager.ProfileManager(... | 256 | 256 | 1,009 | 14 | 242 | t20100/silx | src/silx/gui/plot/tools/test/testProfile.py | Python | TestProfileToolBar | TestProfileToolBar | 309 | 430 | 309 | 309 | 86705466e3ccefa4abcc754b39f076eb8f434afd | bigcode/the-stack | train |
09f0853e2a6ced3e31721e0e | train | class | class TestProfile3DToolBar(TestCaseQt):
"""Tests for Profile3DToolBar widget.
"""
def setUp(self):
super(TestProfile3DToolBar, self).setUp()
self.plot = StackView()
self.plot.show()
self.qWaitForWindowExposed(self.plot)
self.plot.setStack(numpy.array([
[[... | class TestProfile3DToolBar(TestCaseQt):
| """Tests for Profile3DToolBar widget.
"""
def setUp(self):
super(TestProfile3DToolBar, self).setUp()
self.plot = StackView()
self.plot.show()
self.qWaitForWindowExposed(self.plot)
self.plot.setStack(numpy.array([
[[0, 1, 2], [3, 4, 5]],
[[6, 7... | .ProfileToolBar(parent=self.plot,
plot=self.plot,
profileWindow=profileWindow)
self.plot.show()
self.qWaitForWindowExposed(self.plot)
profileWindow.show()
self.qWaitForWindowExposed(profileWindow)
... | 247 | 247 | 824 | 11 | 236 | t20100/silx | src/silx/gui/plot/tools/test/testProfile.py | Python | TestProfile3DToolBar | TestProfile3DToolBar | 486 | 573 | 486 | 486 | a2014f1473c5b3c02b46395c0c9f4051e20d1589 | bigcode/the-stack | train |
4f86a1e0efa1191657e0bfd6 | train | class | class TestRois(TestCaseQt):
def test_init(self):
"""Check that the constructor is not called twice"""
roi = rois.ProfileImageVerticalLineROI()
if qt.BINDING == "PyQt5":
# the profile ROI + the shape
self.assertEqual(roi.receivers(roi.sigRegionChanged), 2)
| class TestRois(TestCaseQt):
| def test_init(self):
"""Check that the constructor is not called twice"""
roi = rois.ProfileImageVerticalLineROI()
if qt.BINDING == "PyQt5":
# the profile ROI + the shape
self.assertEqual(roi.receivers(roi.sigRegionChanged), 2)
| .profile import rois
from silx.gui.plot.tools.profile import editors
from silx.gui.plot.items import roi as roi_items
from silx.gui.plot.tools.profile import manager
from silx.gui import plot as silx_plot
_logger = logging.getLogger(__name__)
class TestRois(TestCaseQt):
| 64 | 64 | 74 | 8 | 56 | t20100/silx | src/silx/gui/plot/tools/test/testProfile.py | Python | TestRois | TestRois | 52 | 59 | 52 | 53 | fbaeabf26adc91d48b86f2d3bbd68b3c773527d8 | bigcode/the-stack | train |
e250027f479694408dbe5653 | train | function | @receiver(post_save, sender=get_user_model())
def post_save_user(sender, instance, created, **kwargs):
if created:
Profile.objects.create(
user=instance, custom_data={"connect": True, "dietary": None, "gender": None, "special_needs": None}
)
send_task("evan.tasks.users.update_aff... | @receiver(post_save, sender=get_user_model())
def post_save_user(sender, instance, created, **kwargs):
| if created:
Profile.objects.create(
user=instance, custom_data={"connect": True, "dietary": None, "gender": None, "special_needs": None}
)
send_task("evan.tasks.users.update_affiliation", (instance.id,))
else:
instance.profile.updated_at = timezone.now()
insta... | return f"{self.user.first_name} {self.user.last_name}"
@property
def to_email(self) -> str:
return f"{self.name} <{self.email}>"
@receiver(post_save, sender=get_user_model())
def post_save_user(sender, instance, created, **kwargs):
| 63 | 64 | 97 | 23 | 40 | eillarra/evan | evan/models/users.py | Python | post_save_user | post_save_user | 50 | 59 | 50 | 51 | b331815a0012a322a911872c60a7f50f79fba618 | bigcode/the-stack | train |
6df8705dfec8e00ae4f10870 | train | class | class Profile(models.Model):
"""
A user profile complements the base User model with extra information.
"""
user = models.OneToOneField(get_user_model(), primary_key=True, related_name="profile", on_delete=models.CASCADE)
position = models.CharField(max_length=190, null=True, blank=True)
affili... | class Profile(models.Model):
| """
A user profile complements the base User model with extra information.
"""
user = models.OneToOneField(get_user_model(), primary_key=True, related_name="profile", on_delete=models.CASCADE)
position = models.CharField(max_length=190, null=True, blank=True)
affiliation = models.CharField(max_... | models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from django_countries.fields import CountryField
from evan.functions import send_task
class ProfileManager(models.Manager):
def get_queryset(self):
return super().get_queryset().s... | 70 | 70 | 235 | 5 | 65 | eillarra/evan | evan/models/users.py | Python | Profile | Profile | 16 | 47 | 16 | 16 | 82ff523c75a3ca5cb85f568ec8d52f92a80b5157 | bigcode/the-stack | train |
c2980a39360b71bfefc41cc4 | train | class | class ProfileManager(models.Manager):
def get_queryset(self):
return super().get_queryset().select_related("user")
| class ProfileManager(models.Manager):
| def get_queryset(self):
return super().get_queryset().select_related("user")
| from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from django_countries.fields import CountryField
from evan.functions import send_task
class ProfileManager(models.Manager):
| 60 | 64 | 24 | 6 | 53 | eillarra/evan | evan/models/users.py | Python | ProfileManager | ProfileManager | 11 | 13 | 11 | 11 | 7115ffa84740f4235d7d38c3b644dd2f5de109bd | bigcode/the-stack | train |
d843fa5c1de503824fd7f095 | train | function | def write_redirect_html(out_path, to_url):
with open(out_path, 'w') as f:
f.write(f'''<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url={to_url}">
<script type="text/javascript">
window.location.href = "{to_ur... | def write_redirect_html(out_path, to_url):
| with open(out_path, 'w') as f:
f.write(f'''<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url={to_url}">
<script type="text/javascript">
window.location.href = "{to_url}"
</script>
<title>Page R... | args.save_raw_single_page:
shutil.copytree(test_dir, args.save_raw_single_page)
test.test_single_page(os.path.join(test_dir, 'single', 'index.html'), lang)
logging.info(f'Finished building single page version for {lang}')
def write_redirect_html(out_path, to_url... | 63 | 64 | 137 | 10 | 53 | namikhnenko/ClickHouse | docs/tools/build.py | Python | write_redirect_html | write_redirect_html | 220 | 235 | 220 | 220 | 9fa12d670d11d74db6866c58ff151a12afeedd9c | bigcode/the-stack | train |
17c81e110fee9892c3647035 | train | function | def build_redirects(args):
lang_re_fragment = args.lang.replace(',', '|')
rewrites = []
with open(os.path.join(args.docs_dir, 'redirects.txt'), 'r') as f:
for line in f:
from_path, to_path = line.split(' ', 1)
build_redirect_html(args, from_path, to_path)
from_pa... | def build_redirects(args):
| lang_re_fragment = args.lang.replace(',', '|')
rewrites = []
with open(os.path.join(args.docs_dir, 'redirects.txt'), 'r') as f:
for line in f:
from_path, to_path = line.split(' ', 1)
build_redirect_html(args, from_path, to_path)
from_path = '^/docs/(' + lang_re_f... | = args.version_prefix + '/' if args.version_prefix else '/'
target_path = to_path.replace('.md', '/')
to_url = f'/docs{version_prefix}{lang}/{target_path}'
to_url = to_url.strip()
write_redirect_html(out_path, to_url)
def build_redirects(args):
| 64 | 64 | 177 | 6 | 58 | namikhnenko/ClickHouse | docs/tools/build.py | Python | build_redirects | build_redirects | 253 | 266 | 253 | 253 | cbe1657549f14e8f709d89573c1a2e4ef46ba169 | bigcode/the-stack | train |
bc4bc7a70081407506ee50e5 | train | function | def build_docs(args):
tasks = []
for lang in args.lang.split(','):
if lang:
tasks.append((lang, args,))
util.run_function_in_parallel(build_for_lang, tasks, threads=False)
build_redirects(args)
| def build_docs(args):
| tasks = []
for lang in args.lang.split(','):
if lang:
tasks.append((lang, args,))
util.run_function_in_parallel(build_for_lang, tasks, threads=False)
build_redirects(args)
| ('.md', '/')
rewrites.append(' '.join(['rewrite', from_path, to_path, 'permanent;']))
with open(os.path.join(args.docs_output_dir, 'redirects.conf'), 'w') as f:
f.write('\n'.join(rewrites))
def build_docs(args):
| 64 | 64 | 51 | 5 | 59 | namikhnenko/ClickHouse | docs/tools/build.py | Python | build_docs | build_docs | 269 | 275 | 269 | 269 | 995ca8e8dad765275cc02e05ff1fcda6783508d7 | bigcode/the-stack | train |
6beb7a52adc75d0863d0fbbe | train | function | def build_for_lang(lang, args):
logging.info(f'Building {lang} docs')
os.environ['SINGLE_PAGE'] = '0'
config_path = os.path.join(args.docs_dir, f'toc_{lang}.yml')
if args.is_stable_release and not os.path.exists(config_path):
logging.warning(f'Skipping {lang} docs, because {config} does not exi... | def build_for_lang(lang, args):
| logging.info(f'Building {lang} docs')
os.environ['SINGLE_PAGE'] = '0'
config_path = os.path.join(args.docs_dir, f'toc_{lang}.yml')
if args.is_stable_release and not os.path.exists(config_path):
logging.warning(f'Skipping {lang} docs, because {config} does not exist')
return
try:
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse
import datetime
import logging
import os
import shutil
import subprocess
import sys
import time
import livereload
import markdown.util
from mkdocs import config
from mkdocs import exceptions
from mkdocs.commands im... | 202 | 240 | 801 | 8 | 193 | namikhnenko/ClickHouse | docs/tools/build.py | Python | build_for_lang | build_for_lang | 44 | 147 | 44 | 44 | 6ea050554c8ff806af2e61c1f02d23e101c3ac4d | bigcode/the-stack | train |
138b07b8a4cc8dd81dfc7eeb | train | class | class ClickHouseMarkdown(markdown.extensions.Extension):
class ClickHousePreprocessor(markdown.util.Processor):
def run(self, lines):
for line in lines:
if '<!--hide-->' not in line:
yield line
def extendMarkdown(self, md):
md.preprocessors.regist... | class ClickHouseMarkdown(markdown.extensions.Extension):
| class ClickHousePreprocessor(markdown.util.Processor):
def run(self, lines):
for line in lines:
if '<!--hide-->' not in line:
yield line
def extendMarkdown(self, md):
md.preprocessors.register(self.ClickHousePreprocessor(), 'clickhouse_preprocesso... | markdown.util
from mkdocs import config
from mkdocs import exceptions
from mkdocs.commands import build as mkdocs_build
from concatenate import concatenate
from website import build_website, minify_website
import mdx_clickhouse
import test
import util
class ClickHouseMarkdown(markdown.extensions.Extension):
| 64 | 64 | 77 | 9 | 54 | namikhnenko/ClickHouse | docs/tools/build.py | Python | ClickHouseMarkdown | ClickHouseMarkdown | 30 | 38 | 30 | 30 | cc42a6947ec3b85a6937a3a3ee9991a87817a5e7 | bigcode/the-stack | train |
f95d3ef4f4798e9852c5bbad | train | function | def build_redirect_html(args, from_path, to_path):
for lang in args.lang.split(','):
out_path = os.path.join(args.docs_output_dir, lang, from_path.replace('.md', '/index.html'))
out_dir = os.path.dirname(out_path)
try:
os.makedirs(out_dir)
except OSError:
pass... | def build_redirect_html(args, from_path, to_path):
| for lang in args.lang.split(','):
out_path = os.path.join(args.docs_output_dir, lang, from_path.replace('.md', '/index.html'))
out_dir = os.path.dirname(out_path)
try:
os.makedirs(out_dir)
except OSError:
pass
version_prefix = args.version_prefix + '/'... | </script>
<title>Page Redirection</title>
</head>
<body>
If you are not redirected automatically, follow this <a href="{to_url}">link</a>.
</body>
</html>''')
def build_redirect_html(args, from_path, to_path):
| 64 | 64 | 133 | 12 | 52 | namikhnenko/ClickHouse | docs/tools/build.py | Python | build_redirect_html | build_redirect_html | 238 | 250 | 238 | 238 | 0e9a71fd234b3e71be44a73b1ac14bc7cbb4ed83 | bigcode/the-stack | train |
a09488dfa881237b056ce72b | train | function | def build_single_page_version(lang, args, cfg):
logging.info(f'Building single page version for {lang}')
os.environ['SINGLE_PAGE'] = '1'
with util.autoremoved_file(os.path.join(args.docs_dir, lang, 'single.md')) as single_md:
concatenate(lang, args.docs_dir, single_md)
with util.temp_dir()... | def build_single_page_version(lang, args, cfg):
| logging.info(f'Building single page version for {lang}')
os.environ['SINGLE_PAGE'] = '1'
with util.autoremoved_file(os.path.join(args.docs_dir, lang, 'single.md')) as single_md:
concatenate(lang, args.docs_dir, single_md)
with util.temp_dir() as site_temp:
with util.temp_dir() ... | .superfences',
'extra',
{
'toc': {
'permalink': True,
'slugify': mdx_clickhouse.slugify
}
}
],
plugins=plugins,
extra={
'stable_rele... | 177 | 177 | 593 | 11 | 166 | namikhnenko/ClickHouse | docs/tools/build.py | Python | build_single_page_version | build_single_page_version | 150 | 217 | 150 | 150 | f0001c18e2ac059e133885f14544fb0f320a10f2 | bigcode/the-stack | train |
b58bab4176d68dccea21641e | train | function | def build(args):
if os.path.exists(args.output_dir):
shutil.rmtree(args.output_dir)
if not args.skip_website:
build_website(args)
build_docs(args)
from github import build_releases
build_releases(args, build_docs)
if not args.skip_website:
minify_website(args)
fo... | def build(args):
| if os.path.exists(args.output_dir):
shutil.rmtree(args.output_dir)
if not args.skip_website:
build_website(args)
build_docs(args)
from github import build_releases
build_releases(args, build_docs)
if not args.skip_website:
minify_website(args)
for static_redirect... | f.write('\n'.join(rewrites))
def build_docs(args):
tasks = []
for lang in args.lang.split(','):
if lang:
tasks.append((lang, args,))
util.run_function_in_parallel(build_for_lang, tasks, threads=False)
build_redirects(args)
def build(args):
| 64 | 64 | 159 | 4 | 60 | namikhnenko/ClickHouse | docs/tools/build.py | Python | build | build | 278 | 302 | 278 | 278 | 94124c1b372ba934c7a1f5d872835f2f666f22c6 | bigcode/the-stack | train |
73e1d6f25e20685d0f89db09 | train | class | class DateEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
return str(obj)
| class DateEncoder(json.JSONEncoder):
| def default(self, obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
else:
return str(obj)
|
import json
class DateEncoder(json.JSONEncoder):
| 11 | 64 | 37 | 7 | 3 | PanDAWMS/panda-bigmon-core-new | core/libs/DateEncoder.py | Python | DateEncoder | DateEncoder | 5 | 10 | 5 | 5 | b354198adc0dc682f54b93f96be0645def54cc31 | bigcode/the-stack | train |
c7f18ca7fde8a4aacfe2d42e | train | class | class Migration(migrations.Migration):
dependencies = [
('signalpings', '0006_srpsignal'),
]
operations = [
migrations.AddField(
model_name='hrappsignal',
name='notify_comments',
field=models.BooleanField(default=True),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('signalpings', '0006_srpsignal'),
]
operations = [
migrations.AddField(
model_name='hrappsignal',
name='notify_comments',
field=models.BooleanField(default=True),
),
]
| # Generated by Django 3.1.3 on 2020-12-25 11:50
from django.db import migrations, models
class Migration(migrations.Migration):
| 38 | 64 | 61 | 7 | 30 | soratidus999/allianceauth-signal-pings | signalpings/migrations/0007_hrappsignal_notify_comments.py | Python | Migration | Migration | 6 | 18 | 6 | 7 | d2e59d0665babb1763a7522a9408a0e2495d3a21 | bigcode/the-stack | train |
4ecd807b7fbb07f990eab55f | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('restaurants', '0008_auto_20180410_1133'),
]
operations = [
migrations.AddField(
model_name='restaurantlocation',
name='owner',
fi... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('restaurants', '0008_auto_20180410_1133'),
]
operations = [
migrations.AddField(
model_name='restaurantlocation',
name='owner',
field=models.ForeignKey(default=1, on_dele... | : utf-8 -*-
# Generated by Django 1.11.2 on 2018-04-10 10:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 64 | 64 | 94 | 7 | 56 | DocteurNo/Try-Django-1.11 | src/restaurants/migrations/0009_restaurantlocation_owner.py | Python | Migration | Migration | 10 | 24 | 10 | 11 | 6c3c9912e72e5acd608ceb267174ce8f0eabe209 | bigcode/the-stack | train |
61314bfd7bd26a8083c49a90 | train | function | def gen_mock_fopen(line_to_tweet, line_char):
"""
Sideeffect generator that sets the expected
last_line.txt data.
:param line_to_tweet: (int) represents row in data.txt
:param line_char: (int) represents coloum in data.txt
:return: function
"""
def mock_fopen(file, mode="r", *args, **kw... | def gen_mock_fopen(line_to_tweet, line_char):
| """
Sideeffect generator that sets the expected
last_line.txt data.
:param line_to_tweet: (int) represents row in data.txt
:param line_char: (int) represents coloum in data.txt
:return: function
"""
def mock_fopen(file, mode="r", *args, **kwargs):
"""
Sideeffect for call... | import unittest
from unittest.mock import patch
import logging
import bot
logger = logging.getLogger("unittests")
logger.setLevel(logging.DEBUG)
# These are used to mock lastline.txt
def gen_mock_fopen(line_to_tweet, line_char):
| 54 | 77 | 259 | 13 | 40 | rhnvrm/ConstAssemblyBot | test_bot.py | Python | gen_mock_fopen | gen_mock_fopen | 10 | 42 | 10 | 10 | 0420cc70adfa6dd37c13ff4da793624c0770a209 | bigcode/the-stack | train |
1012142a6b90ded8895c2ee5 | train | class | class TestBot(unittest.TestCase):
"""
Mock twitter API and file opening to test bot without affecting its state
"""
@patch("bot.tweepy.API")
@patch("bot.open", new=gen_mock_fopen(45, 0))
def test_basic(self, mocked_api):
bot.run()
# Get the args list from update_status
... | class TestBot(unittest.TestCase):
| """
Mock twitter API and file opening to test bot without affecting its state
"""
@patch("bot.tweepy.API")
@patch("bot.open", new=gen_mock_fopen(45, 0))
def test_basic(self, mocked_api):
bot.run()
# Get the args list from update_status
call_list = mocked_api.return_val... | _tweet: (int) represents row in data.txt
:param line_char: (int) represents coloum in data.txt
:return: function
"""
def mock_fopen(file, mode="r", *args, **kwargs):
"""
Sideeffect for calling open in main file,
uses args to serve either the data.txt as is
or mocked last... | 231 | 231 | 773 | 7 | 223 | rhnvrm/ConstAssemblyBot | test_bot.py | Python | TestBot | TestBot | 45 | 128 | 45 | 45 | 6fdca501bc29b6ba1a2a11068b155f73d7d70b0b | bigcode/the-stack | train |
b64c63c19435662fd07cf98f | train | function | def generate_report(reportfolderbase, time_in_secs, time_HMS, extraction_type, image_input_path):
control = None
side_heading = \
"""<h6 class="sidebar-heading justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
{0}
</h6>
"""
list_item = \
"""
<li class="nav-i... | def generate_report(reportfolderbase, time_in_secs, time_HMS, extraction_type, image_input_path):
| control = None
side_heading = \
"""<h6 class="sidebar-heading justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
{0}
</h6>
"""
list_item = \
"""
<li class="nav-item">
<a class="nav-link {0}" href="{1}">
<span data-feather="{2}"></span> {3}
... | = 'file-plus'
elif category == 'WIFI PROFILES': icon = 'wifi'
elif category == 'SQLITE JOURNALING': icon = 'book-open'
elif category == 'GOOGLE NOW & QUICKSEARCH': icon = 'search'
elif category == 'RECENT ACTIVITY': icon = 'activity'
elif category == 'NOW PLAYING': icon = 'music'
eli... | 256 | 256 | 882 | 22 | 233 | mastenp/ALEAPP | scripts/report.py | Python | generate_report | generate_report | 64 | 146 | 64 | 65 | 576fb62402177915caa4f7630d294bbdf12cfe07 | bigcode/the-stack | train |
518c6bc83bea41c7c96fccd5 | train | function | def create_index_html(reportfolderbase, time_in_secs, time_HMS, extraction_type, image_input_path, nav_list_data):
'''Write out the index.html page to the report folder'''
content = '<br />'
content += """
<div class="card " style="padding: 20px;">
<h2 class="card-title">Case Information</h2>
... | def create_index_html(reportfolderbase, time_in_secs, time_HMS, extraction_type, image_input_path, nav_list_data):
| '''Write out the index.html page to the report folder'''
content = '<br />'
content += """
<div class="card " style="padding: 20px;">
<h2 class="card-title">Case Information</h2>
""" # CARD start
case_list = [ ['Extraction location', image_input_path],
['Extrac... | location__,"logo.jpg")))
#logfunc(str(os.path.join(__location__,"logo.jpg")))
shutil.copy2(os.path.join(__location__,"logo.jpg"), elements_folder)
shutil.copy2(os.path.join(__location__,"dashboard.css"), elements_folder)
shutil.copy2(os.path.join(__location__,"feather.min.js"), elements_folder)
... | 172 | 172 | 576 | 27 | 144 | mastenp/ALEAPP | scripts/report.py | Python | create_index_html | create_index_html | 154 | 208 | 154 | 154 | a2fd1592e8da67bec09622fc0df466e6e028c06b | bigcode/the-stack | train |
eecdee4b513cfd38b6a03a75 | train | function | def generate_key_val_table_without_headings(title, data_list, html_escape=True, width="70%"):
'''Returns the html code for a key-value table (2 cols) without col names'''
code = ''
if title:
code += f'<h2>{title}</h2>'
table_header_code = \
"""
<div class="table-responsive">
... | def generate_key_val_table_without_headings(title, data_list, html_escape=True, width="70%"):
| '''Returns the html code for a key-value table (2 cols) without col names'''
code = ''
if title:
code += f'<h2>{title}</h2>'
table_header_code = \
"""
<div class="table-responsive">
<table class="table table-bordered table-hover table-sm" width={}>
<tbody>... | + body_main_data_title.format(body_heading, body_description))
f.write(content)
f.write(thank_you_note)
f.write(credits_code)
f.write(body_main_trailer + body_end + page_footer)
f.close()
def generate_key_val_table_without_headings(title, data_list, html_escape=True, width="70%"):
| 72 | 72 | 240 | 22 | 50 | mastenp/ALEAPP | scripts/report.py | Python | generate_key_val_table_without_headings | generate_key_val_table_without_headings | 210 | 240 | 210 | 210 | 19fad595e2937ecf38fb2da4674a6ec59cf97a42 | bigcode/the-stack | train |
6a09cd473adb8b2396eaa8ac | train | function | def insert_sidebar_code(data, sidebar_code, filename):
pos = data.find(body_sidebar_dynamic_data_placeholder)
if pos < 0:
logfunc(f'Error, could not find {body_sidebar_dynamic_data_placeholder} in file {filename}')
return data
else:
ret = data[0 : pos] + sidebar_code + data[pos + len... | def insert_sidebar_code(data, sidebar_code, filename):
| pos = data.find(body_sidebar_dynamic_data_placeholder)
if pos < 0:
logfunc(f'Error, could not find {body_sidebar_dynamic_data_placeholder} in file {filename}')
return data
else:
ret = data[0 : pos] + sidebar_code + data[pos + len(body_sidebar_dynamic_data_placeholder):]
retur... | row in data_list:
code += '<tr>' + ''.join( ('<td>{}</td>'.format(str(x)) for x in row) ) + '</tr>'
# Add footer
code += table_footer_code
return code
def insert_sidebar_code(data, sidebar_code, filename):
| 64 | 64 | 86 | 11 | 52 | mastenp/ALEAPP | scripts/report.py | Python | insert_sidebar_code | insert_sidebar_code | 242 | 249 | 242 | 242 | c58b084f6c1e21621a98862521e810edd1bf6153 | bigcode/the-stack | train |
50021e31e2a3d10480e54245 | train | function | def get_icon_name(category, artifact):
''' Returns the icon name from the feathericons collection. To add an icon type for
an artifact, select one of the types from ones listed @ feathericons.com
If no icon is available, the alert triangle is returned as default icon.
'''
category = categor... | def get_icon_name(category, artifact):
| ''' Returns the icon name from the feathericons collection. To add an icon type for
an artifact, select one of the types from ones listed @ feathericons.com
If no icon is available, the alert triangle is returned as default icon.
'''
category = category.upper()
artifact = artifact.upper... | import html
import os
import pathlib
import shutil
import sqlite3
import sys
from collections import OrderedDict
from scripts.html_parts import *
from scripts.ilapfuncs import logfunc
from scripts.version_info import aleapp_version, aleapp_contributors
def get_icon_name(category, artifact):
| 63 | 204 | 681 | 8 | 54 | mastenp/ALEAPP | scripts/report.py | Python | get_icon_name | get_icon_name | 13 | 62 | 13 | 13 | aceaf8ad079b8a49a3e2cc65df8a40e59587fe06 | bigcode/the-stack | train |
9b65fdba3e38938859830923 | train | function | def mark_item_active(data, itemname):
'''Finds itemname in data, then marks that node as active. Return value is changed data'''
pos = data.find(f'" href="{itemname}"')
if pos < 0:
logfunc(f'Error, could not find {itemname} in {data}')
return data
else:
ret = data[0 : pos] + " ac... | def mark_item_active(data, itemname):
| '''Finds itemname in data, then marks that node as active. Return value is changed data'''
pos = data.find(f'" href="{itemname}"')
if pos < 0:
logfunc(f'Error, could not find {itemname} in {data}')
return data
else:
ret = data[0 : pos] + " active" + data[pos:]
return ret
| func(f'Error, could not find {body_sidebar_dynamic_data_placeholder} in file {filename}')
return data
else:
ret = data[0 : pos] + sidebar_code + data[pos + len(body_sidebar_dynamic_data_placeholder):]
return ret
def mark_item_active(data, itemname):
| 64 | 64 | 97 | 9 | 54 | mastenp/ALEAPP | scripts/report.py | Python | mark_item_active | mark_item_active | 251 | 259 | 251 | 251 | ed8580b5ea9f46c292a0793daa825af88a54d5fd | bigcode/the-stack | train |
e38013f6fc176f9e9a6a3c63 | train | function | def get_file_content(path):
f = open(path, 'r', encoding='utf8')
data = f.read()
f.close()
return data
| def get_file_content(path):
| f = open(path, 'r', encoding='utf8')
data = f.read()
f.close()
return data
| elements_folder)
shutil.copy2(os.path.join(__location__,"feather.min.js"), elements_folder)
shutil.copytree(os.path.join(__location__,"MDB-Free_4.13.0"), os.path.join(elements_folder, 'MDB-Free_4.13.0'))
def get_file_content(path):
| 64 | 64 | 34 | 6 | 58 | mastenp/ALEAPP | scripts/report.py | Python | get_file_content | get_file_content | 148 | 152 | 148 | 148 | 9752cf53f5240967a62880b0266af4dc18f84361 | bigcode/the-stack | train |
c004b074e6da1f39373c3c0c | train | function | def _truncate(hmac_sha_):
"""
truncate SHA value.
"""
offset = int(hmac_sha_[-1], 16)
binary = int(hmac_sha_[(offset *2):((offset*2)+8)], 16) & 0x7FFFFFFF
return str(binary)
| def _truncate(hmac_sha_):
| """
truncate SHA value.
"""
offset = int(hmac_sha_[-1], 16)
binary = int(hmac_sha_[(offset *2):((offset*2)+8)], 16) & 0x7FFFFFFF
return str(binary)
| _required_padding(secret_)
key = base64.b32decode(s, True)
msg = struct.pack(">Q", intervals_no_)
h = hmac.new(key, msg, digestmod=sha_).hexdigest()
return _truncate(h)[-digits_:]
def _truncate(hmac_sha_):
| 64 | 64 | 67 | 8 | 56 | pyizza/totp | totp/__init__.py | Python | _truncate | _truncate | 33 | 39 | 33 | 33 | 96dfa30bfa0166f73f212408fcdc3ce7b5b9aaa2 | bigcode/the-stack | train |
c4e5a50f8f20d59dac80301d | train | function | def _add_required_padding(key_):
"""
Add padding '=='.
"""
if len(key_) % MULTIPLIER:
key_ += '=' * (MULTIPLIER - len(key_) % MULTIPLIER)
return key_
| def _add_required_padding(key_):
| """
Add padding '=='.
"""
if len(key_) % MULTIPLIER:
key_ += '=' * (MULTIPLIER - len(key_) % MULTIPLIER)
return key_
| truncate SHA value.
"""
offset = int(hmac_sha_[-1], 16)
binary = int(hmac_sha_[(offset *2):((offset*2)+8)], 16) & 0x7FFFFFFF
return str(binary)
def _add_required_padding(key_):
| 64 | 64 | 54 | 8 | 56 | pyizza/totp | totp/__init__.py | Python | _add_required_padding | _add_required_padding | 41 | 47 | 41 | 41 | fc04b02031e6ff21bf734c34bde612c8b0321b5e | bigcode/the-stack | train |
60de88245b7bee384c388c2c | train | function | def get_totp(secret_, interval_=30, sha_=1, digits_=6, c_time_=time.time()):
"""
Get time based OTP using given secret and time.
secret: base32 encoded string.
interval: TOTP interval length.
sha_: hashlib digest method.
digits: output token length.
c_time: current time.
"""
encoded_... | def get_totp(secret_, interval_=30, sha_=1, digits_=6, c_time_=time.time()):
| """
Get time based OTP using given secret and time.
secret: base32 encoded string.
interval: TOTP interval length.
sha_: hashlib digest method.
digits: output token length.
c_time: current time.
"""
encoded_secret = base64.b32encode(secret_)
interval = int(math.floor(c_time_))//i... | 224,
256: hashlib.sha256,
384: hashlib.sha384,
512: hashlib.sha512,
}
return hashlib_.get(sha_, hashlib.sha1)
def get_totp(secret_, interval_=30, sha_=1, digits_=6, c_time_=time.time()):
| 64 | 64 | 122 | 24 | 40 | pyizza/totp | totp/__init__.py | Python | get_totp | get_totp | 63 | 75 | 63 | 63 | 79ce0b98ce1ce0a4a085dad30492b2de5733d30a | bigcode/the-stack | train |
4534b5d6f8a1f88fe7dd435c | train | function | def _get_sha(sha_):
"""
Set HASH algorithm to use.
"""
hashlib_ = {
1: hashlib.sha1,
224: hashlib.sha224,
256: hashlib.sha256,
384: hashlib.sha384,
512: hashlib.sha512,
}
return hashlib_.get(sha_, hashlib.sha1)
| def _get_sha(sha_):
| """
Set HASH algorithm to use.
"""
hashlib_ = {
1: hashlib.sha1,
224: hashlib.sha224,
256: hashlib.sha256,
384: hashlib.sha384,
512: hashlib.sha512,
}
return hashlib_.get(sha_, hashlib.sha1)
| (binary)
def _add_required_padding(key_):
"""
Add padding '=='.
"""
if len(key_) % MULTIPLIER:
key_ += '=' * (MULTIPLIER - len(key_) % MULTIPLIER)
return key_
def _get_sha(sha_):
| 64 | 64 | 78 | 8 | 56 | pyizza/totp | totp/__init__.py | Python | _get_sha | _get_sha | 49 | 60 | 49 | 49 | 0a68d6cfc40ae0c4d03978e93e56085471b01cf5 | bigcode/the-stack | train |
956eb127554d84a93751fdb8 | train | function | def _generate(secret_, intervals_no_, sha_, digits_):
s = _add_required_padding(secret_)
key = base64.b32decode(s, True)
msg = struct.pack(">Q", intervals_no_)
h = hmac.new(key, msg, digestmod=sha_).hexdigest()
return _truncate(h)[-digits_:]
| def _generate(secret_, intervals_no_, sha_, digits_):
| s = _add_required_padding(secret_)
key = base64.b32decode(s, True)
msg = struct.pack(">Q", intervals_no_)
h = hmac.new(key, msg, digestmod=sha_).hexdigest()
return _truncate(h)[-digits_:]
| version:1.0.0
author: Aniket Hande
license: MIT
"""
import hmac
import base64
import struct
import hashlib
import time
import array
import math
MULTIPLIER = 8
def _generate(secret_, intervals_no_, sha_, digits_):
| 64 | 64 | 74 | 13 | 50 | pyizza/totp | totp/__init__.py | Python | _generate | _generate | 26 | 31 | 26 | 26 | 0b318042e2f58e05d12a81dd2af02356ecc9285d | bigcode/the-stack | train |
030952e45c169094f175aea7 | train | class | class RemovalCommand(TransformationCommand):
def __init__(self, target_point):
super().__init__(TransformationType.REMOVE, target_point)
| class RemovalCommand(TransformationCommand):
| def __init__(self, target_point):
super().__init__(TransformationType.REMOVE, target_point)
| __, type(other).__name__))
com = InsertionCommand(self.target_point)
com.callable_objects = self.callable_objects + other.callable_objects
com.callable_objects = sorted(com.callable_objects, key=lambda x: x[1])
return com
class RemovalCommand(TransformationCommand):
| 64 | 64 | 30 | 7 | 56 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | RemovalCommand | RemovalCommand | 247 | 249 | 247 | 247 | 9e50103664f7a940a3ac0860cb2f1317e4c537cf | bigcode/the-stack | train |
95daf8b2de9b1d78586ca1b1 | train | class | class AfterLayer(LayerPoint):
def __init__(self, layer_name, instance_index=0, out_port=0):
super().__init__(TargetType.AFTER_LAYER, layer_name)
self._instance_index = instance_index
self._out_port = out_port
@property
def instance_index(self):
return self._instance_index
... | class AfterLayer(LayerPoint):
| def __init__(self, layer_name, instance_index=0, out_port=0):
super().__init__(TargetType.AFTER_LAYER, layer_name)
self._instance_index = instance_index
self._out_port = out_port
@property
def instance_index(self):
return self._instance_index
@property
def out_port(... | == other.layer_name \
and self.instance_index == other.instance_index \
and self.in_port == other.in_port
return False
def __str__(self):
return ' '.join([super().__str__(),
self.instance_index,
self.in_port])
... | 64 | 64 | 185 | 7 | 57 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | AfterLayer | AfterLayer | 154 | 179 | 154 | 154 | 9eaaa59287333a2674c6b4f6edbf6c18e39a0cfc | bigcode/the-stack | train |
5311c87c89f1314cca833da3 | train | class | class InsertionCommand(TransformationCommand):
def __init__(self, target_point, callable_object=None, priority=None):
super().__init__(TransformationType.INSERT, target_point)
self.callable_objects = []
if callable_object is not None:
_priority = TransformationPriority.DEFAULT_PR... | class InsertionCommand(TransformationCommand):
| def __init__(self, target_point, callable_object=None, priority=None):
super().__init__(TransformationType.INSERT, target_point)
self.callable_objects = []
if callable_object is not None:
_priority = TransformationPriority.DEFAULT_PRIORITY \
if priority is None el... | self.layer_name == other.layer_name and \
self.weights_attr_name == other.weights_attr_name and \
self.operation_name == other.operation_name
return False
def __str__(self):
return super().__str__() + ' ' + self.operation_name
class InsertionCommand(Transforma... | 64 | 64 | 203 | 8 | 55 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | InsertionCommand | InsertionCommand | 223 | 244 | 223 | 223 | 8f5a14f8dcdb2e20417d9177047b28a611937bdc | bigcode/the-stack | train |
d534491ed6bb0ad67aa9ce1a | train | class | class LayerWeight(LayerPoint):
def __init__(self, layer_name, weights_attr_name):
super().__init__(TargetType.WEIGHT_OPERATION, layer_name)
self._weights_attr_name = weights_attr_name
@property
def weights_attr_name(self):
return self._weights_attr_name
def __eq__(self, other):... | class LayerWeight(LayerPoint):
| def __init__(self, layer_name, weights_attr_name):
super().__init__(TargetType.WEIGHT_OPERATION, layer_name)
self._weights_attr_name = weights_attr_name
@property
def weights_attr_name(self):
return self._weights_attr_name
def __eq__(self, other):
if self.__class__ is o... | other.layer_name \
and self.instance_index == other.instance_index \
and self._out_port == other.out_port
return False
def __str__(self):
return ' '.join([super().__str__(),
self.instance_index,
self.out_port])... | 64 | 64 | 144 | 7 | 57 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | LayerWeight | LayerWeight | 182 | 199 | 182 | 182 | 0bf6c80a5581817065d4b3e1db6d3110b4eab9e3 | bigcode/the-stack | train |
811606b8137a7b1d3976aedf | train | class | class TransformationCommand:
"""
The base class for all transformation commands
"""
def __init__(self, command_type, target_point):
"""
Constructor
:param command_type: transformation command type
:param target_point: target point, the object in the model
to whic... | class TransformationCommand:
| """
The base class for all transformation commands
"""
def __init__(self, command_type, target_point):
"""
Constructor
:param command_type: transformation command type
:param target_point: target point, the object in the model
to which the transformation command ... |
def __eq__(self, other):
if self.__class__ is other.__class__:
return self.type == other.type
return False
def __str__(self):
return str(self.type)
def __hash__(self):
return hash(str(self))
class TransformationCommand:
| 64 | 64 | 189 | 4 | 60 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | TransformationCommand | TransformationCommand | 68 | 100 | 68 | 68 | 5a69d225f99e33519795c840c3eac20722fa7cd9 | bigcode/the-stack | train |
4d70209ecd81655996a6d5a6 | train | class | class TargetType(OrderedEnum):
LAYER = 0
BEFORE_LAYER = 1
AFTER_LAYER = 2
WEIGHT_OPERATION = 3
| class TargetType(OrderedEnum):
| LAYER = 0
BEFORE_LAYER = 1
AFTER_LAYER = 2
WEIGHT_OPERATION = 3
| 0
SPARSIFICATION_PRIORITY = 2
QUANTIZATION_PRIORITY = 11
PRUNING_PRIORITY = 1
class TransformationType(OrderedEnum):
INSERT = 0
MULTI_INSERT = 1
REMOVE = 2
class TargetType(OrderedEnum):
| 64 | 64 | 36 | 7 | 56 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | TargetType | TargetType | 30 | 34 | 30 | 30 | d67825201bef7aab249bddc6c7a5e56420d80fa2 | bigcode/the-stack | train |
7eb1dbb1b23798a1dc9f1ca5 | train | class | class TransformationPriority(OrderedEnum):
DEFAULT_PRIORITY = 0
SPARSIFICATION_PRIORITY = 2
QUANTIZATION_PRIORITY = 11
PRUNING_PRIORITY = 1
| class TransformationPriority(OrderedEnum):
| DEFAULT_PRIORITY = 0
SPARSIFICATION_PRIORITY = 2
QUANTIZATION_PRIORITY = 11
PRUNING_PRIORITY = 1
|
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from beta.nncf.utils.ordered_enum import OrderedEnum
class Transformatio... | 64 | 64 | 41 | 7 | 56 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | TransformationPriority | TransformationPriority | 17 | 21 | 17 | 17 | 9255bc06e097c1907125ff312a27d2c8ba695b76 | bigcode/the-stack | train |
864bc37255e9654f6606555c | train | class | class LayerPoint(TargetPoint):
def __init__(self, target_type, layer_name):
super().__init__(target_type)
self._layer_name = layer_name
@property
def layer_name(self):
return self._layer_name
def __eq__(self, other):
if self.__class__ is other.__class__:
ret... | class LayerPoint(TargetPoint):
| def __init__(self, target_type, layer_name):
super().__init__(target_type)
self._layer_name = layer_name
@property
def layer_name(self):
return self._layer_name
def __eq__(self, other):
if self.__class__ is other.__class__:
return self.type == other.type and... | , command):
return self.__class__ == command.__class__ and \
self.type == command.type and \
self.target_point == command.target_point
def union(self, other):
pass
def __add__(self, other):
return self.union(other)
class LayerPoint(TargetPoint):
| 64 | 64 | 116 | 6 | 58 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | LayerPoint | LayerPoint | 103 | 118 | 103 | 103 | 09bc73ed38dc39b9833f3bf600a4e5871c747c7b | bigcode/the-stack | train |
f2556473bc7cfd3b87d37cf8 | train | class | class BeforeLayer(LayerPoint):
def __init__(self, layer_name, instance_index=0, in_port=0):
super().__init__(TargetType.BEFORE_LAYER, layer_name)
self._instance_index = instance_index
self._in_port = in_port
@property
def instance_index(self):
return self._instance_index
... | class BeforeLayer(LayerPoint):
| def __init__(self, layer_name, instance_index=0, in_port=0):
super().__init__(TargetType.BEFORE_LAYER, layer_name)
self._instance_index = instance_index
self._in_port = in_port
@property
def instance_index(self):
return self._instance_index
@property
def in_port(sel... | _name
return False
def __str__(self):
return super().__str__() + ' ' + self.layer_name
class Layer(LayerPoint):
def __init__(self, layer_name):
super().__init__(TargetType.LAYER, layer_name)
class BeforeLayer(LayerPoint):
| 64 | 64 | 185 | 7 | 57 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | BeforeLayer | BeforeLayer | 126 | 151 | 126 | 126 | 92844ada912c347f7352611ecae5752f9eec4284 | bigcode/the-stack | train |
eaa49ccd21baea6ed1a50ad6 | train | class | class TransformationType(OrderedEnum):
INSERT = 0
MULTI_INSERT = 1
REMOVE = 2
| class TransformationType(OrderedEnum):
| INSERT = 0
MULTI_INSERT = 1
REMOVE = 2
| the License.
"""
from beta.nncf.utils.ordered_enum import OrderedEnum
class TransformationPriority(OrderedEnum):
DEFAULT_PRIORITY = 0
SPARSIFICATION_PRIORITY = 2
QUANTIZATION_PRIORITY = 11
PRUNING_PRIORITY = 1
class TransformationType(OrderedEnum):
| 64 | 64 | 27 | 7 | 56 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | TransformationType | TransformationType | 24 | 27 | 24 | 24 | aba12f13e74baaf1b126d04943c6d40ee5ad9b52 | bigcode/the-stack | train |
75cf9c7a07164f839384bf55 | train | class | class MultipleInsertionCommands(TransformationCommand):
def __init__(self, target_point, check_target_point_fn=None, commands=None):
super().__init__(TransformationType.MULTI_INSERT, target_point)
self.check_target_point_fn = self.check_target_point \
if check_target_point_fn is None els... | class MultipleInsertionCommands(TransformationCommand):
| def __init__(self, target_point, check_target_point_fn=None, commands=None):
super().__init__(TransformationType.MULTI_INSERT, target_point)
self.check_target_point_fn = self.check_target_point \
if check_target_point_fn is None else check_target_point_fn
self._commands = []
... | , _ in self.callable_objects]
def union(self, other):
if not self.check_command_compatibility(other):
raise ValueError('{} and {} commands could not be united'.format(
type(self).__name__, type(other).__name__))
com = InsertionCommand(self.target_point)
com.call... | 141 | 141 | 473 | 8 | 133 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | MultipleInsertionCommands | MultipleInsertionCommands | 252 | 314 | 252 | 252 | 03b15f7ce8138eb0fea4aad76ee1959a6be2cbde | bigcode/the-stack | train |
72eaf4bd16601377a5de3ac2 | train | class | class Layer(LayerPoint):
def __init__(self, layer_name):
super().__init__(TargetType.LAYER, layer_name)
| class Layer(LayerPoint):
| def __init__(self, layer_name):
super().__init__(TargetType.LAYER, layer_name)
| self, other):
if self.__class__ is other.__class__:
return self.type == other.type and self.layer_name == other.layer_name
return False
def __str__(self):
return super().__str__() + ' ' + self.layer_name
class Layer(LayerPoint):
| 64 | 64 | 29 | 6 | 57 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | Layer | Layer | 121 | 123 | 121 | 121 | 512878df96151212744f85a5fe3d48ee54ef15a0 | bigcode/the-stack | train |
d1f2c847919f6f48c947ab5f | train | class | class LayerWeightOperation(LayerWeight):
def __init__(self, layer_name, weights_attr_name, operation_name):
super().__init__(layer_name, weights_attr_name)
self._operation_name = operation_name
@property
def operation_name(self):
return self._operation_name
def __eq__(self, oth... | class LayerWeightOperation(LayerWeight):
| def __init__(self, layer_name, weights_attr_name, operation_name):
super().__init__(layer_name, weights_attr_name)
self._operation_name = operation_name
@property
def operation_name(self):
return self._operation_name
def __eq__(self, other):
if self.__class__ is other._... | return self.type == other.type and \
self.layer_name == other.layer_name and \
self.weights_attr_name == other.weights_attr_name
return False
def __str__(self):
return super().__str__() + ' ' + self.weights_attr_name
class LayerWeightOperation(LayerWeight):
| 64 | 64 | 150 | 8 | 55 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | LayerWeightOperation | LayerWeightOperation | 202 | 220 | 202 | 202 | bd9c225dba82ade86593e3dc3fc74b3952da7c37 | bigcode/the-stack | train |
a8c5ce9b352179d2abd1c272 | train | class | class TargetPoint:
"""
The base class for all TargetPoints
TargetPoint specifies the object in the model graph to which the
transformation command will be applied. It can be layer, weight and etc.
"""
def __init__(self, target_type):
"""
Constructor
:param target_type: ... | class TargetPoint:
| """
The base class for all TargetPoints
TargetPoint specifies the object in the model graph to which the
transformation command will be applied. It can be layer, weight and etc.
"""
def __init__(self, target_type):
"""
Constructor
:param target_type: target point type
... | (OrderedEnum):
INSERT = 0
MULTI_INSERT = 1
REMOVE = 2
class TargetType(OrderedEnum):
LAYER = 0
BEFORE_LAYER = 1
AFTER_LAYER = 2
WEIGHT_OPERATION = 3
class TargetPoint:
| 64 | 64 | 158 | 4 | 59 | wei1tang/nncf | beta/nncf/tensorflow/graph/transformations/commands.py | Python | TargetPoint | TargetPoint | 37 | 65 | 37 | 37 | bcd650ff84f11610e5bce34f3f3fc0033560b5b4 | bigcode/the-stack | train |
87840eee2b03614580111027 | train | function | def return_security_group(context, instance_id, security_group_id):
pass
| def return_security_group(context, instance_id, security_group_id):
| pass
| import flavors
import nova.conf
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_instance
from nova.tests.unit.image import fake
CONF = nova.conf.CONF
def return_security_group(context, instance_id, security_group_id):
| 64 | 64 | 16 | 13 | 50 | bopopescu/nova-16 | nova/tests/unit/api/openstack/compute/test_multiple_create.py | Python | return_security_group | return_security_group | 37 | 38 | 37 | 37 | 8bd9b5290ac47df0a18db0b78c60364ff69ebad9 | bigcode/the-stack | train |
d9b600aeb809704087d80e0a | train | class | class MultiCreateExtensionTestV21(test.TestCase):
validation_error = exception.ValidationError
def setUp(self):
"""Shared implementation for tests below that create instance."""
super(MultiCreateExtensionTestV21, self).setUp()
self.flags(verbose=True,
enable_instance... | class MultiCreateExtensionTestV21(test.TestCase):
| validation_error = exception.ValidationError
def setUp(self):
"""Shared implementation for tests below that create instance."""
super(MultiCreateExtensionTestV21, self).setUp()
self.flags(verbose=True,
enable_instance_password=True)
self.instance_cache_num = ... | compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY... | 256 | 256 | 3,806 | 11 | 244 | bopopescu/nova-16 | nova/tests/unit/api/openstack/compute/test_multiple_create.py | Python | MultiCreateExtensionTestV21 | MultiCreateExtensionTestV21 | 41 | 494 | 41 | 41 | 8b01150502b4d9b69451bfe2abe8e19296c8eb4a | bigcode/the-stack | train |
e654717b67a45973ef7b33b2 | train | class | class Config():
def __init__(self):
"""Initialize hyperparameters and load vocabs"""
if not os.path.exists(self.dir_output):
os.makedirs(self.dir_output)
cwd = os.getcwd()
# dataset sentences
filename_dev = os.path.join(cwd, "data/dev.txt")
filename_test = os.path.... | class Config():
| def __init__(self):
"""Initialize hyperparameters and load vocabs"""
if not os.path.exists(self.dir_output):
os.makedirs(self.dir_output)
cwd = os.getcwd()
# dataset sentences
filename_dev = os.path.join(cwd, "data/dev.txt")
filename_test = os.path.join(cwd, "data... | import os
import transformers
class Config():
| 9 | 182 | 607 | 3 | 5 | AUTH-MINT/LongSeq | model/config.py | Python | Config | Config | 5 | 81 | 5 | 5 | 90dfce9acd376f047d535e3c584d2a8833646e0d | bigcode/the-stack | train |
90132de53b652274dbbf76a0 | train | class | class TestPluginParamType(AiidaTestCase):
"""Tests for the `PluginParamType`."""
def test_group_definition(self):
"""
Test the various accepted syntaxes of defining supported entry point groups. Both single
values as well as tuples should be allowed. The `aiida.` prefix should also be o... | class TestPluginParamType(AiidaTestCase):
| """Tests for the `PluginParamType`."""
def test_group_definition(self):
"""
Test the various accepted syntaxes of defining supported entry point groups. Both single
values as well as tuples should be allowed. The `aiida.` prefix should also be optional.
"""
param = Plugi... | # -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | 160 | 256 | 2,257 | 11 | 148 | louisponet/aiida-core | tests/cmdline/params/types/test_plugin.py | Python | TestPluginParamType | TestPluginParamType | 19 | 240 | 19 | 19 | bdacbd9f3cc0efc945ff5ac85b4adc54ec56e096 | bigcode/the-stack | train |
e5bc5a84ebe4ce793b600c52 | train | class | class FATDirectoryEntry:
"""Represents directory entries in FAT (files & directories)."""
#: Marks a directory entry as empty
FREE_DIR_ENTRY_MARK = 0xE5
#: Marks all directory entries after this one as empty
LAST_DIR_ENTRY_MARK = 0x00
#: Bit set in DIR_Attr if entry is read-only
ATTR_READ_... | class FATDirectoryEntry:
| """Represents directory entries in FAT (files & directories)."""
#: Marks a directory entry as empty
FREE_DIR_ENTRY_MARK = 0xE5
#: Marks all directory entries after this one as empty
LAST_DIR_ENTRY_MARK = 0x00
#: Bit set in DIR_Attr if entry is read-only
ATTR_READ_ONLY = 0x01
#: Bit se... | # -*- coding: utf-8 -*-
"""Directory entry operations with PyFAT."""
import posixpath
import struct
from time import timezone
from pyfatfs.DosDateTime import DosDateTime
from pyfatfs.EightDotThree import EightDotThree
from pyfatfs._exceptions import PyFATException, NotAnLFNEntryException,\
BrokenLFNEntryExceptio... | 105 | 256 | 3,871 | 5 | 99 | abrasive/pyfatfs | pyfatfs/FATDirectoryEntry.py | Python | FATDirectoryEntry | FATDirectoryEntry | 18 | 507 | 18 | 18 | dd5c2e128937d1f133b732605fa1e235fab19cd5 | bigcode/the-stack | train |
8bf17bd86b9de660001b97c5 | train | function | def make_lfn_entry(dir_name: str,
short_name: EightDotThree):
"""Generate a `FATLongDirectoryEntry` instance from directory name.
:param dir_name: Long name of directory
:param short_name: `EightDotThree` class instance
:raises: `PyFATException` if entry name does not require an LFN
... | def make_lfn_entry(dir_name: str,
short_name: EightDotThree):
| """Generate a `FATLongDirectoryEntry` instance from directory name.
:param dir_name: Long name of directory
:param short_name: `EightDotThree` class instance
:raises: `PyFATException` if entry name does not require an LFN
entry or the name exceeds the FAT limitation of 255 characters
"... | (LDIR_Ord))
mapped_entries = dict(zip(self.FAT_LONG_DIRECTORY_VARS,
(LDIR_Ord, LDIR_Name1, LDIR_Attr, LDIR_Type,
LDIR_Chksum, LDIR_Name2, LDIR_FstClusLO,
LDIR_Name3)))
self.lfn_entries[LDIR_Ord] = m... | 176 | 176 | 587 | 18 | 157 | abrasive/pyfatfs | pyfatfs/FATDirectoryEntry.py | Python | make_lfn_entry | make_lfn_entry | 642 | 704 | 642 | 643 | c9bbdb265cfe1d74c291b6e866bd3ef3c74e6f70 | bigcode/the-stack | train |
465697cd185031134b887298 | train | class | class FATLongDirectoryEntry(object):
"""Represents long file name (LFN) entries."""
#: LFN entry header layout in struct formatted string
FAT_LONG_DIRECTORY_LAYOUT = "<B10sBBB12sH4s"
#: LFN header fields when extracted with `FAT_LONG_DIRECTORY_LAYOUT`
FAT_LONG_DIRECTORY_VARS = ["LDIR_Ord", "LDIR_Na... | class FATLongDirectoryEntry(object):
| """Represents long file name (LFN) entries."""
#: LFN entry header layout in struct formatted string
FAT_LONG_DIRECTORY_LAYOUT = "<B10sBBB12sH4s"
#: LFN header fields when extracted with `FAT_LONG_DIRECTORY_LAYOUT`
FAT_LONG_DIRECTORY_VARS = ["LDIR_Ord", "LDIR_Name1", "LDIR_Attr",
... | = None
if name in [sn, ln]:
self.__dirs.remove(dir_entry)
return
raise PyFATException(f"Cannot remove '{name}', no such "
f"file or directory!", errno=errno.ENOENT)
def __repr__(self):
"""String-represent directory entry by ... | 256 | 256 | 1,267 | 7 | 249 | abrasive/pyfatfs | pyfatfs/FATDirectoryEntry.py | Python | FATLongDirectoryEntry | FATLongDirectoryEntry | 510 | 639 | 510 | 510 | cfc1e6c924b34dc3aeba3f17f403360facf53f9d | bigcode/the-stack | train |
2bfce5db532fc60dd7eb1a0f | train | function | def get_ts_masked_cam(start_date, end_date, var, member, CLM_lat, mask):
print("Start to convert",var)
count_time_start = time.time()
# read raw data
var_raw = xr.open_dataset("/glade/collections/cdg/data/cesmLE/CESM-CAM5-BGC-LE/atm/proc/tseries/daily/" \
+ var + "/b.e1... | def get_ts_masked_cam(start_date, end_date, var, member, CLM_lat, mask):
| print("Start to convert",var)
count_time_start = time.time()
# read raw data
var_raw = xr.open_dataset("/glade/collections/cdg/data/cesmLE/CESM-CAM5-BGC-LE/atm/proc/tseries/daily/" \
+ var + "/b.e11.BRCP85C5CNBDRD.f09_g16."+member+".cam.h1." + var + ".20060101-20801231.... | # This script is used to store different members as csv
# The results are at "/glade/scratch/zhonghua/urban_heat_train/data/"
import pandas as pd
import numpy as np
import xarray as xr
import datetime
import cftime
import time
import gc
def get_ts_masked_cam(start_date, end_date, var, member, CLM_lat, mask):
| 84 | 95 | 318 | 22 | 61 | zzheng93/code_uhws | 1_data_prep/CESM_raw_nc_to_csv/CESM_raw_nc_to_csv.py | Python | get_ts_masked_cam | get_ts_masked_cam | 12 | 34 | 12 | 12 | f83c21059049fe0b1ed45266ee3903e5f438f001 | bigcode/the-stack | train |
1d0852dc48196d821e889491 | train | function | def get_df(start_date, end_date, member):
print("start_date:", start_date)
print("end_date:", end_date)
print("member:", member)
# load the urban maximal temperature
TREFMXAV_U = xr.open_dataset("/glade/collections/cdg/data/cesmLE/CESM-CAM5-BGC-LE/lnd/proc/tseries/daily/TREFMXAV_U/b.e11.BRCP85C5CNB... | def get_df(start_date, end_date, member):
| print("start_date:", start_date)
print("end_date:", end_date)
print("member:", member)
# load the urban maximal temperature
TREFMXAV_U = xr.open_dataset("/glade/collections/cdg/data/cesmLE/CESM-CAM5-BGC-LE/lnd/proc/tseries/daily/TREFMXAV_U/b.e11.BRCP85C5CNBDRD.f09_g16."+member+".clm2.h1.TREFMXAV_U.... | _lat)
# apply the mask
var_reg_mask = var_reg.where(mask)
# plot the figure figure
#var_reg_mask.loc[start_date[:4]+"-03-28"].plot()
#Another way to plot
#TREFMXAV_U["TREFMXAV_U"].sel(time=TREFMXAV_U.time[int(len(TREFMXAV_U["TREFMXAV_U"].time)*1/74)]).plot()
#plt.show()
# rename the Dat... | 174 | 174 | 582 | 11 | 162 | zzheng93/code_uhws | 1_data_prep/CESM_raw_nc_to_csv/CESM_raw_nc_to_csv.py | Python | get_df | get_df | 37 | 86 | 37 | 37 | e00eaf4322d97857bb8ea32447b76d7562984703 | bigcode/the-stack | train |
a32d262c95e1a3a8ffe0bcbe | train | class | class GrafanaTriggerHistory(models.Model):
grafana_trigger_his_id = models.AutoField("Grafana障害取得履歴ID", primary_key=True)
grafana_adapter_id = models.IntegerField("Grafana監視マスタID")
trigger_id = models.CharField("トリガーID", max_length=256)
lastchange = models.Integer... | class GrafanaTriggerHistory(models.Model):
| grafana_trigger_his_id = models.AutoField("Grafana障害取得履歴ID", primary_key=True)
grafana_adapter_id = models.IntegerField("Grafana監視マスタID")
trigger_id = models.CharField("トリガーID", max_length=256)
lastchange = models.IntegerField("トリガー最終更新日時")
last_update_timesta... | db_table = 'OASE_T_GRAFANA_MONITORING_HISTORY'
def __str__(self):
return str(self.grafana_monitoring_his_id)
#------------------------------------------------
# DOSL19002:Grafana障害取得履歴管理
#------------------------------------------------
class GrafanaTriggerHistory(models.Model):
| 64 | 64 | 184 | 8 | 55 | Masa-Yasuno/oase | oase-root/web_app/models/Grafana_monitoring_models.py | Python | GrafanaTriggerHistory | GrafanaTriggerHistory | 98 | 111 | 98 | 98 | 406be27af622389eecf35698e5460da6b4454752 | bigcode/the-stack | train |
118b3a6f0fb087ff805f6944 | train | class | class GrafanaMatchInfo(models.Model):
grafana_match_id = models.AutoField("Grafana突合情報ID", primary_key=True)
grafana_adapter_id = models.IntegerField("Grafana監視マスタID")
data_object_id = models.IntegerField("データオブジェクトID")
grafana_response_key = models.CharField("Grafana応答情報key", ma... | class GrafanaMatchInfo(models.Model):
| grafana_match_id = models.AutoField("Grafana突合情報ID", primary_key=True)
grafana_adapter_id = models.IntegerField("Grafana監視マスタID")
data_object_id = models.IntegerField("データオブジェクトID")
grafana_response_key = models.CharField("Grafana応答情報key", max_length=128)
last_update_timestam... | ', 'rule_type_id'), )
def __str__(self):
return "%s(%s)" % (self.grafana_disp_name, str(self.grafana_adapter_id))
#------------------------------------------------
# DOSL18002:Grafana突合情報
#------------------------------------------------
class GrafanaMatchInfo(models.Model):
| 64 | 64 | 166 | 8 | 55 | Masa-Yasuno/oase | oase-root/web_app/models/Grafana_monitoring_models.py | Python | GrafanaMatchInfo | GrafanaMatchInfo | 63 | 75 | 63 | 63 | f628d9202bdf244e915f6cbf27ca6b4ac1c090da | bigcode/the-stack | train |
1e6d322944ac63c06bf1a073 | train | class | class GrafanaAdapter(models.Model):
grafana_adapter_id = models.AutoField("Grafana監視マスタID", primary_key=True)
grafana_disp_name = models.CharField("Grafana表示名", max_length=64, unique=True)
uri = models.CharField("URI", max_length=512)
username = models.CharField("接続... | class GrafanaAdapter(models.Model):
| grafana_adapter_id = models.AutoField("Grafana監視マスタID", primary_key=True)
grafana_disp_name = models.CharField("Grafana表示名", max_length=64, unique=True)
uri = models.CharField("URI", max_length=512)
username = models.CharField("接続ユーザ", max_length=64)
password ... | :Grafana監視マスタ
# DOSL18002:Grafana突合情報
# DOSL19001:Grafana監視履歴管理
# DOSL19002:Grafana障害取得履歴管理
#
#-------------------------------------------------------------------------------
#------------------------------------------------
# DOSL18001:Grafana監視マスタ
#------------------------------------------------
class GrafanaAda... | 82 | 82 | 275 | 7 | 74 | Masa-Yasuno/oase | oase-root/web_app/models/Grafana_monitoring_models.py | Python | GrafanaAdapter | GrafanaAdapter | 40 | 57 | 40 | 40 | 2de4c2e0abae99b81fa9ea99fe82917a3f74648e | bigcode/the-stack | train |
c7dca6f6ad09c3b78b3a715e | train | class | class GrafanaMonitoringHistory(models.Model):
grafana_monitoring_his_id = models.AutoField("Grafana監視履歴ID", primary_key=True)
grafana_adapter_id = models.IntegerField("Grafana監視マスタID")
grafana_lastchange = models.DateTimeField("Grafana最終更新日時")
status = models... | class GrafanaMonitoringHistory(models.Model):
| grafana_monitoring_his_id = models.AutoField("Grafana監視履歴ID", primary_key=True)
grafana_adapter_id = models.IntegerField("Grafana監視マスタID")
grafana_lastchange = models.DateTimeField("Grafana最終更新日時")
status = models.IntegerField("ステータス")
status_update_id ... | )
class Meta:
db_table = 'OASE_T_GRAFANA_MATCH_INFO'
def __str__(self):
return str(self.grafana_match_id)
#------------------------------------------------
# DOSL19001:Grafana監視履歴管理
#------------------------------------------------
class GrafanaMonitoringHistory(models.Model):
| 64 | 64 | 192 | 8 | 55 | Masa-Yasuno/oase | oase-root/web_app/models/Grafana_monitoring_models.py | Python | GrafanaMonitoringHistory | GrafanaMonitoringHistory | 80 | 93 | 80 | 80 | 46aa8cb3a0692212dd3c185032cb6e005b309278 | bigcode/the-stack | train |
ad67c83a13b9213a8264c546 | train | class | class TestViews(TestSetUp):
# anon checking of list of all ladders and list endpoints
def test_check_topicwise_list_all_lists_view(self):
test_url = reverse('topicwise-list')
res = self.client.get(test_url)
self.assertEqual(res.status_code, 200)
def test_check_topicwise_ladder_all_... | class TestViews(TestSetUp):
# anon checking of list of all ladders and list endpoints
| def test_check_topicwise_list_all_lists_view(self):
test_url = reverse('topicwise-list')
res = self.client.get(test_url)
self.assertEqual(res.status_code, 200)
def test_check_topicwise_ladder_all_ladders_view(self):
test_url = reverse('topicwise-ladder')
res = self.clien... | from .test_setup import TestSetUp
from user.models import User, Profile
from django.urls import reverse
from rest_framework.test import APIClient
from lists.models import Solved, ListInfo
from problem.models import Problem
class TestViews(TestSetUp):
# anon checking of list of all ladders and list endpoints
| 68 | 256 | 1,531 | 21 | 46 | Sreelayavuyyuru/Backend | codedigger/lists/tests/test_views.py | Python | TestViews | TestViews | 9 | 173 | 9 | 11 | df44d70b31e946a62458d6fa58a5a505ad77cf93 | bigcode/the-stack | train |
12d9a4c80c353ca4f12e3af5 | train | class | class cuEdgeTracer(tracer.tracerBase.Tracer):
def __init__(self):
super().__init__('cuEdge', source=[
"ftrace"], compatible={'machine': ["aarch64"]})
def prepare(self, conf: dict, debug: bool):
"Handle Input Options"
"Handle Output Options"
optForFtrace = {
... | class cuEdgeTracer(tracer.tracerBase.Tracer):
| def __init__(self):
super().__init__('cuEdge', source=[
"ftrace"], compatible={'machine': ["aarch64"]})
def prepare(self, conf: dict, debug: bool):
"Handle Input Options"
"Handle Output Options"
optForFtrace = {
"collector": {
"ftrace": {... | to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tracer.tracerBase
import sys
import os
im... | 83 | 83 | 279 | 12 | 70 | hito0512/Vitis-AI | tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/tracer/cuEdge.py | Python | cuEdgeTracer | cuEdgeTracer | 23 | 58 | 23 | 23 | 3646e0f15a13449eeb6b9c6a97ebabbe38886dc4 | bigcode/the-stack | train |
4a18549ae7c70baf0cd3721a | train | class | class Firebase:
@staticmethod
async def _getInstallation(settings: FirebaseSettings) -> Optional[Installation]:
url = f"https://firebaseinstallations.googleapis.com/v1/projects/{settings.appName}/installations"
headers = {"Content-Type": "application/json", "x-goog-api-key": settings.publicKey}
... | class Firebase:
@staticmethod
| async def _getInstallation(settings: FirebaseSettings) -> Optional[Installation]:
url = f"https://firebaseinstallations.googleapis.com/v1/projects/{settings.appName}/installations"
headers = {"Content-Type": "application/json", "x-goog-api-key": settings.publicKey}
data = {"fid": "dIsVQ2QVRT... | from string import hexdigits
from random import choice
import aiohttp
from type.credentials import GoogleCredentials, FirebaseCredentials
from type.settings import FirebaseSettings
from dataclasses import dataclass
from typing import Optional
@dataclass()
class Installation:
token: str
iid: str
class Firebas... | 68 | 126 | 420 | 7 | 60 | lastrise/Push-Server | firebase.py | Python | Firebase | Firebase | 17 | 55 | 17 | 18 | b7a9adee49400b2ea062e9cc7379499ab6d71df0 | bigcode/the-stack | train |
55686b5651c70e5bf16436c8 | train | class | @dataclass()
class Installation:
token: str
iid: str
| @dataclass()
class Installation:
| token: str
iid: str
| from string import hexdigits
from random import choice
import aiohttp
from type.credentials import GoogleCredentials, FirebaseCredentials
from type.settings import FirebaseSettings
from dataclasses import dataclass
from typing import Optional
@dataclass()
class Installation:
| 51 | 64 | 16 | 6 | 44 | lastrise/Push-Server | firebase.py | Python | Installation | Installation | 11 | 14 | 11 | 12 | 24f73ef2905d3876f221c33a10f2bc16da32d36e | bigcode/the-stack | train |
fb14e514f0a8fc54a71e89ec | train | function | def make_venv(envdir: str, python: str) -> None:
env = dict(os.environ, VIRTUALENV_NO_DOWNLOAD='1')
cmd = (sys.executable, '-mvirtualenv', envdir, '-p', python)
cmd_output_b(*cmd, env=env, cwd='/')
| def make_venv(envdir: str, python: str) -> None:
| env = dict(os.environ, VIRTUALENV_NO_DOWNLOAD='1')
cmd = (sys.executable, '-mvirtualenv', envdir, '-p', python)
cmd_output_b(*cmd, env=env, cwd='/')
| .realpath(sys.executable)
_make_venv(env_dir, python)
with in_env(prefix, version):
helpers.run_setup_cmd(prefix, install)
return in_env, healthy, run_hook, install_environment
def make_venv(envdir: str, python: str) -> None:
| 64 | 64 | 67 | 17 | 46 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | make_venv | make_venv | 202 | 205 | 202 | 202 | c7cf28b3feefc6162d1c96abd52e5523f9e6663c | bigcode/the-stack | train |
98e53c6335ee0663b1676abc | train | function | def _sys_executable_matches(version: str) -> bool:
if version == 'python':
return True
elif not version.startswith('python'):
return False
try:
info = tuple(int(p) for p in version[len('python'):].split('.'))
except ValueError:
return False
return sys.version_info[:... | def _sys_executable_matches(version: str) -> bool:
| if version == 'python':
return True
elif not version.startswith('python'):
return False
try:
info = tuple(int(p) for p in version[len('python'):].split('.'))
except ValueError:
return False
return sys.version_info[:len(info)] == info
|
# Give a best-effort try for windows
default_folder_name = exe.replace('.', '')
if os.path.exists(fr'C:\{default_folder_name}\python.exe'):
return exe
# We tried!
return C.DEFAULT
def _sys_executable_matches(version: str) -> bool:
| 64 | 64 | 79 | 13 | 50 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | _sys_executable_matches | _sys_executable_matches | 104 | 115 | 104 | 104 | 2c9eadd413f86f670b2ba6ce00c985325dfc6e81 | bigcode/the-stack | train |
cdf89bfd6dbea19b6999b307 | train | function | def _find_by_py_launcher(
version: str,
) -> Optional[str]: # pragma: no cover (windows only)
if version.startswith('python'):
num = version[len('python'):]
try:
cmd = ('py', f'-{num}', '-c', 'import sys; print(sys.executable)')
return cmd_output(*cmd)[1].strip()
... | def _find_by_py_launcher(
version: str,
) -> Optional[str]: # pragma: no cover (windows only)
| if version.startswith('python'):
num = version[len('python'):]
try:
cmd = ('py', f'-{num}', '-c', 'import sys; print(sys.executable)')
return cmd_output(*cmd)[1].strip()
except CalledProcessError:
pass
return None
| THONHOME', UNSET),
('VIRTUAL_ENV', venv),
('PATH', (bin_dir(venv), os.pathsep, Var('PATH'))),
)
def _find_by_py_launcher(
version: str,
) -> Optional[str]: # pragma: no cover (windows only)
| 64 | 64 | 93 | 27 | 37 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | _find_by_py_launcher | _find_by_py_launcher | 44 | 54 | 44 | 46 | fd2a7c62f8944f412db1cdefebc97159f052fa3f | bigcode/the-stack | train |
89485d10a8800fdf36a83479 | train | function | def _find_by_sys_executable() -> Optional[str]:
def _norm(path: str) -> Optional[str]:
_, exe = os.path.split(path.lower())
exe, _, _ = exe.partition('.exe')
if exe not in {'python', 'pythonw'} and find_executable(exe):
return exe
return None
# On linux, I see these ... | def _find_by_sys_executable() -> Optional[str]:
| def _norm(path: str) -> Optional[str]:
_, exe = os.path.split(path.lower())
exe, _, _ = exe.partition('.exe')
if exe not in {'python', 'pythonw'} and find_executable(exe):
return exe
return None
# On linux, I see these common sys.executables:
#
# system `pyth... | = version[len('python'):]
try:
cmd = ('py', f'-{num}', '-c', 'import sys; print(sys.executable)')
return cmd_output(*cmd)[1].strip()
except CalledProcessError:
pass
return None
def _find_by_sys_executable() -> Optional[str]:
| 69 | 69 | 230 | 12 | 56 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | _find_by_sys_executable | _find_by_sys_executable | 57 | 77 | 57 | 57 | a59b42c3f68e07973f59141cacc9c57cebfb0656 | bigcode/the-stack | train |
f5b241679329b96c2e27d62c | train | function | def bin_dir(venv: str) -> str:
"""On windows there's a different directory for the virtualenv"""
bin_part = 'Scripts' if os.name == 'nt' else 'bin'
return os.path.join(venv, bin_part)
| def bin_dir(venv: str) -> str:
| """On windows there's a different directory for the virtualenv"""
bin_part = 'Scripts' if os.name == 'nt' else 'bin'
return os.path.join(venv, bin_part)
|
from pre_commit.prefix import Prefix
from pre_commit.util import CalledProcessError
from pre_commit.util import clean_path_on_failure
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
ENVIRONMENT_DIR = 'py_env'
def bin_dir(venv: str) -> str:
| 64 | 64 | 55 | 12 | 52 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | bin_dir | bin_dir | 29 | 32 | 29 | 29 | 151628532bfb3964237c4fb1c408b5b6ee948721 | bigcode/the-stack | train |
235b1aa526c03a04f1aaecc9 | train | function | def py_interface(
_dir: str,
_make_venv: Callable[[str, str], None],
) -> Tuple[
Callable[[Prefix, str], ContextManager[None]],
Callable[[Prefix, str], bool],
Callable[[Hook, Sequence[str], bool], Tuple[int, bytes]],
Callable[[Prefix, str, Sequence[str]], None],
]:
@contextlib.contex... | def py_interface(
_dir: str,
_make_venv: Callable[[str, str], None],
) -> Tuple[
Callable[[Prefix, str], ContextManager[None]],
Callable[[Prefix, str], bool],
Callable[[Hook, Sequence[str], bool], Tuple[int, bytes]],
Callable[[Prefix, str, Sequence[str]], None],
]:
@contextlib.contex... | def in_env(
prefix: Prefix,
language_version: str,
) -> Generator[None, None, None]:
envdir = prefix.path(helpers.environment_dir(_dir, language_version))
with envcontext(get_env_patch(envdir)):
yield
def healthy(prefix: Prefix, language_version: str) -> ... | the default
# place on windows
if version.startswith('python'):
default_folder_name = version.replace('.', '')
return fr'C:\{default_folder_name}\python.exe'
# Otherwise assume it is a path
return os.path.expanduser(version)
def py_interface(
_dir: str,
... | 140 | 140 | 468 | 85 | 55 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | py_interface | py_interface | 143 | 199 | 143 | 152 | 2920260a11e8c52977aa1ddf9f842d0941e4f96a | bigcode/the-stack | train |
5a71e0987e5dbcd96bbde690 | train | function | def norm_version(version: str) -> str:
# first see if our current executable is appropriate
if _sys_executable_matches(version):
return sys.executable
if os.name == 'nt': # pragma: no cover (windows)
version_exec = _find_by_py_launcher(version)
if version_exec:
return v... | def norm_version(version: str) -> str:
# first see if our current executable is appropriate
| if _sys_executable_matches(version):
return sys.executable
if os.name == 'nt': # pragma: no cover (windows)
version_exec = _find_by_py_launcher(version)
if version_exec:
return version_exec
# Try looking up by name
version_exec = find_executable(version)
... | try:
info = tuple(int(p) for p in version[len('python'):].split('.'))
except ValueError:
return False
return sys.version_info[:len(info)] == info
def norm_version(version: str) -> str:
# first see if our current executable is appropriate
| 64 | 64 | 174 | 21 | 42 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | norm_version | norm_version | 118 | 140 | 118 | 119 | 7942eccfde608af25a47c05735a17508d6c9a923 | bigcode/the-stack | train |
815f5d0dfde45ee2677f99e5 | train | function | @functools.lru_cache(maxsize=1)
def get_default_version() -> str: # pragma: no cover (platform dependent)
# First attempt from `sys.executable` (or the realpath)
exe = _find_by_sys_executable()
if exe:
return exe
# Next try the `pythonX.X` executable
exe = f'python{sys.version_info[0]}.{sy... | @functools.lru_cache(maxsize=1)
def get_default_version() -> str: # pragma: no cover (platform dependent)
# First attempt from `sys.executable` (or the realpath)
| exe = _find_by_sys_executable()
if exe:
return exe
# Next try the `pythonX.X` executable
exe = f'python{sys.version_info[0]}.{sys.version_info[1]}'
if find_executable(exe):
return exe
if _find_by_py_launcher(exe):
return exe
# Give a best-effort try for windows
... | exe = _norm(path)
if exe:
return exe
return None
@functools.lru_cache(maxsize=1)
def get_default_version() -> str: # pragma: no cover (platform dependent)
# First attempt from `sys.executable` (or the realpath)
| 64 | 64 | 173 | 46 | 17 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | get_default_version | get_default_version | 80 | 101 | 80 | 82 | 94efe94297bdcff0d5509cef3ebebf49aa6cf610 | bigcode/the-stack | train |
db3f6c589f70a60333772aec | train | function | def get_env_patch(venv: str) -> PatchesT:
return (
('PIP_DISABLE_PIP_VERSION_CHECK', '1'),
('PYTHONHOME', UNSET),
('VIRTUAL_ENV', venv),
('PATH', (bin_dir(venv), os.pathsep, Var('PATH'))),
)
| def get_env_patch(venv: str) -> PatchesT:
| return (
('PIP_DISABLE_PIP_VERSION_CHECK', '1'),
('PYTHONHOME', UNSET),
('VIRTUAL_ENV', venv),
('PATH', (bin_dir(venv), os.pathsep, Var('PATH'))),
)
| : str) -> str:
"""On windows there's a different directory for the virtualenv"""
bin_part = 'Scripts' if os.name == 'nt' else 'bin'
return os.path.join(venv, bin_part)
def get_env_patch(venv: str) -> PatchesT:
| 64 | 64 | 71 | 15 | 49 | ashiazed/pre-commit | pre_commit/languages/python.py | Python | get_env_patch | get_env_patch | 35 | 41 | 35 | 35 | 481b6f89eb44211a5d07410888c9b08369dbab27 | bigcode/the-stack | train |
766c7e2e0954a08d14d66bc3 | train | function | @click.group()
def entry():
pass
| @click.group()
def entry():
| pass
|
from dm_engine import dm_task
from auth.bkiam.sync_users import migrate_iam_autho
from auth.sync_business import sync_leader, sync_members
from auth.sync_data_managers import init, sync, transmit_meta_operation_record
click.disable_unicode_literals_warning = True
@click.group()
def entry():
| 64 | 64 | 9 | 6 | 57 | Chromico/bk-base | src/datamgr/datamanager/auth/tasks.py | Python | entry | entry | 32 | 34 | 32 | 33 | c4fd518803007afb1a53dbd9457237cfb0a5b85a | bigcode/the-stack | train |
03833dd0807601abbdcea358 | train | function | @pytest.fixture(name='pyramid_request')
def pyramid_request_fixture(web_app) -> PyramidRequest:
with open_pyramid_request(web_app.registry) as request:
yield request
| @pytest.fixture(name='pyramid_request')
def pyramid_request_fixture(web_app) -> PyramidRequest:
| with open_pyramid_request(web_app.registry) as request:
yield request
| ) -> WebApp:
app_env_fabric = partial(create_app_env, apps=pyramid_apps, pyramid_settings=pyramid_settings)
with WebApp(app_env_fabric) as web_app:
yield web_app
@pytest.fixture(name='pyramid_request')
def pyramid_request_fixture(web_app) -> PyramidRequest:
| 64 | 64 | 36 | 19 | 44 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | pyramid_request_fixture | pyramid_request_fixture | 95 | 98 | 95 | 96 | 8128c903aae5e21ebacdd3b7f53f8325878d326d | bigcode/the-stack | train |
84b77aba001fcb2e72f34732 | train | class | @implementer(ISecurityPolicy)
class TestingSecurityPolicy:
def __init__(self, realm='Realm'):
self.realm = realm
self.helper = RestAclHelper()
def identity(self, request: PyramidRequest):
credentials = extract_http_basic_credentials(request)
if credentials:
return c... | @implementer(ISecurityPolicy)
class TestingSecurityPolicy:
| def __init__(self, realm='Realm'):
self.realm = realm
self.helper = RestAclHelper()
def identity(self, request: PyramidRequest):
credentials = extract_http_basic_credentials(request)
if credentials:
return credentials.username
def authenticated_userid(self, requ... | .scripting import prepare
from pyramid.settings import aslist
from zope.interface import implementer
from .webapp import WebApp
from ..authorization import RestAclHelper
from ..typing import PyramidRequest
from ..utils import open_pyramid_request
@implementer(ISecurityPolicy)
class TestingSecurityPolicy:
| 64 | 64 | 186 | 12 | 51 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | TestingSecurityPolicy | TestingSecurityPolicy | 22 | 49 | 22 | 24 | 1c584c463363407f88a4866ac7dfa80bf9be37a6 | bigcode/the-stack | train |
1172dd8fcabf4cf9c9480607 | train | function | @pytest.fixture(name='app_config')
def app_config_fixture(web_app):
return Configurator(registry=web_app.registry)
| @pytest.fixture(name='app_config')
def app_config_fixture(web_app):
| return Configurator(registry=web_app.registry)
| (app_env_fabric) as web_app:
yield web_app
@pytest.fixture(name='pyramid_request')
def pyramid_request_fixture(web_app) -> PyramidRequest:
with open_pyramid_request(web_app.registry) as request:
yield request
@pytest.fixture(name='app_config')
def app_config_fixture(web_app):
| 64 | 64 | 25 | 14 | 49 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | app_config_fixture | app_config_fixture | 101 | 103 | 101 | 102 | 82523a119530a168f25ae74895775e0d8d17ac88 | bigcode/the-stack | train |
a0f02d1299c6fe6d5eda012a | train | function | def create_app_env(apps=None, pyramid_settings=None):
global_config = {
'apps': '\n'.join(apps or []),
}
settings = pyramid_settings or {}
settings['testing'] = True
wsgi_app = simple_app(global_config, **settings)
env = prepare()
env['app'] = wsgi_app
return env
| def create_app_env(apps=None, pyramid_settings=None):
| global_config = {
'apps': '\n'.join(apps or []),
}
settings = pyramid_settings or {}
settings['testing'] = True
wsgi_app = simple_app(global_config, **settings)
env = prepare()
env['app'] = wsgi_app
return env
| TestingSecurityPolicy())
apps = global_config.get('apps', '')
if not isinstance(apps, (list, tuple)):
apps = aslist(apps)
for app in apps:
config.include(app)
return config.make_wsgi_app()
def create_app_env(apps=None, pyramid_settings=None):
| 64 | 64 | 79 | 12 | 52 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | create_app_env | create_app_env | 66 | 75 | 66 | 66 | 699495b3c2d2401d22ecd967c8e2df671528138b | bigcode/the-stack | train |
6b57e49d6e527cae4b3dabe8 | train | function | @pytest.fixture(name='pyramid_settings', scope='session')
def pyramid_settings_fixture():
return {}
| @pytest.fixture(name='pyramid_settings', scope='session')
def pyramid_settings_fixture():
| return {}
| _app(global_config, **settings)
env = prepare()
env['app'] = wsgi_app
return env
@pytest.fixture(name='pyramid_apps', scope='session')
def pyramid_apps_fixture():
return []
@pytest.fixture(name='pyramid_settings', scope='session')
def pyramid_settings_fixture():
| 63 | 64 | 20 | 17 | 46 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | pyramid_settings_fixture | pyramid_settings_fixture | 83 | 85 | 83 | 84 | c62e663fe6b8ed7dd6fcf23a4ae8811c6be87066 | bigcode/the-stack | train |
5269a2ef6ef0827cf8d56dd2 | train | function | @pytest.fixture(name='web_app')
def web_app_fixture(pyramid_apps, pyramid_settings) -> WebApp:
app_env_fabric = partial(create_app_env, apps=pyramid_apps, pyramid_settings=pyramid_settings)
with WebApp(app_env_fabric) as web_app:
yield web_app
| @pytest.fixture(name='web_app')
def web_app_fixture(pyramid_apps, pyramid_settings) -> WebApp:
| app_env_fabric = partial(create_app_env, apps=pyramid_apps, pyramid_settings=pyramid_settings)
with WebApp(app_env_fabric) as web_app:
yield web_app
| @pytest.fixture(name='pyramid_apps', scope='session')
def pyramid_apps_fixture():
return []
@pytest.fixture(name='pyramid_settings', scope='session')
def pyramid_settings_fixture():
return {}
@pytest.fixture(name='web_app')
def web_app_fixture(pyramid_apps, pyramid_settings) -> WebApp:
| 63 | 64 | 62 | 22 | 41 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | web_app_fixture | web_app_fixture | 88 | 92 | 88 | 89 | 2e7e383c90d922c3bdaefeaf4871f8614f47dd6a | bigcode/the-stack | train |
ce1f619f3b764bd2f1764301 | train | function | @pytest.fixture(name='pyramid_apps', scope='session')
def pyramid_apps_fixture():
return []
| @pytest.fixture(name='pyramid_apps', scope='session')
def pyramid_apps_fixture():
| return []
| settings = pyramid_settings or {}
settings['testing'] = True
wsgi_app = simple_app(global_config, **settings)
env = prepare()
env['app'] = wsgi_app
return env
@pytest.fixture(name='pyramid_apps', scope='session')
def pyramid_apps_fixture():
| 64 | 64 | 20 | 17 | 46 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | pyramid_apps_fixture | pyramid_apps_fixture | 78 | 80 | 78 | 79 | 8e4762bb0d2e2d0e7c99e9574f7048c1253461f8 | bigcode/the-stack | train |
cb1e9e53c62faf5d1bebf8cd | train | function | def simple_app(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
with Configurator(settings=settings) as config:
config.set_security_policy(TestingSecurityPolicy())
apps = global_config.get('apps', '')
if not isinstance(apps, (list, tuple)):
... | def simple_app(global_config, **settings):
| """This function returns a Pyramid WSGI application."""
with Configurator(settings=settings) as config:
config.set_security_policy(TestingSecurityPolicy())
apps = global_config.get('apps', '')
if not isinstance(apps, (list, tuple)):
apps = aslist(apps)
for app in app... | (context, principals, permission)
def remember(self, request: PyramidRequest, userid, **kw):
pass
def forget(self, request: PyramidRequest, **kw):
return [('WWW-Authenticate', 'Basic realm="%s"' % self.realm)]
def simple_app(global_config, **settings):
| 63 | 64 | 89 | 9 | 54 | Cykooz/restfw | src/restfw/testing/fixtures.py | Python | simple_app | simple_app | 52 | 63 | 52 | 52 | 7e7760c0bbea7c746f0964d2a6f3379a0fa568f6 | bigcode/the-stack | train |
48638f78ef50ce991c7a1a5e | train | class | class HTTPKernelClient(AsyncKernelClient):
"""Communicates with a single kernel indirectly via a websocket to a gateway server.
There are five channels associated with each kernel:
* shell: for request/reply calls to the kernel.
* iopub: for the kernel to publish results to frontends.
* hb: for mo... | class HTTPKernelClient(AsyncKernelClient):
| """Communicates with a single kernel indirectly via a websocket to a gateway server.
There are five channels associated with each kernel:
* shell: for request/reply calls to the kernel.
* iopub: for the kernel to publish results to frontends.
* hb: for monitoring the kernel's heartbeat.
* stdi... | @staticmethod
def serialize_datetime(dt):
if isinstance(dt, (datetime.date, datetime.datetime)):
return dt.timestamp()
def start(self) -> None:
pass
def stop(self) -> None:
if not self.empty():
# If unprocessed messages are detected, drain the queue collect... | 256 | 256 | 1,290 | 9 | 247 | kwimp/logManagement | elyra/http_kernel_manager.py | Python | HTTPKernelClient | HTTPKernelClient | 255 | 401 | 255 | 255 | 6dc4415e3d2813924f48371e35849efcc302feaa | bigcode/the-stack | train |
838e5ee898c5b059b1684bf1 | train | class | class HBChannelQueue(ChannelQueue):
def is_beating(self) -> bool:
# Just use the is_alive status for now
return self.is_alive()
| class HBChannelQueue(ChannelQueue):
| def is_beating(self) -> bool:
# Just use the is_alive status for now
return self.is_alive()
| return
if len(msgs):
self.log.warning("Stopping channel '{}' with {} unprocessed non-status messages: {}.".
format(self.channel_name, len(msgs), msgs))
def is_alive(self) -> bool:
return self.channel_socket is not None
class HBChannelQueue(Chann... | 64 | 64 | 34 | 7 | 56 | kwimp/logManagement | elyra/http_kernel_manager.py | Python | HBChannelQueue | HBChannelQueue | 248 | 252 | 248 | 249 | 4c94b560990b3b0589e370dc205b9d3b0f8e7b1a | bigcode/the-stack | train |
05e5c7df91187854298e6392 | train | class | class ChannelQueue(Queue):
channel_name: str = None
def __init__(self, channel_name: str, channel_socket: websocket.WebSocket, log: Logger):
super().__init__()
self.channel_name = channel_name
self.channel_socket = channel_socket
self.log = log
async def get_msg(self, *arg... | class ChannelQueue(Queue):
| channel_name: str = None
def __init__(self, channel_name: str, channel_socket: websocket.WebSocket, log: Logger):
super().__init__()
self.channel_name = channel_name
self.channel_socket = channel_socket
self.log = log
async def get_msg(self, *args, **kwargs) -> dict:
... | POST', body=json_encode({}))
self.log.debug("Interrupt kernel response: %d %s", response.code, response.reason)
async def is_alive(self):
"""Is the kernel process still running?"""
if self.has_kernel:
# Go ahead and issue a request to get the kernel
self.kernel =... | 133 | 133 | 446 | 6 | 127 | kwimp/logManagement | elyra/http_kernel_manager.py | Python | ChannelQueue | ChannelQueue | 196 | 245 | 196 | 197 | 23dbfbbf5720bf9178d3db99e53d38af5763fb63 | bigcode/the-stack | train |
51e6d3a9a99eb6c4ba869000 | train | class | class HTTPKernelManager(AsyncKernelManager):
"""Manages a single kernel remotely via a Gateway Server. """
kernel_id = None
kernel = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.base_endpoint = url_path_join(GatewayClient.instance().url, GatewayClient.instance().k... | class HTTPKernelManager(AsyncKernelManager):
| """Manages a single kernel remotely via a Gateway Server. """
kernel_id = None
kernel = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.base_endpoint = url_path_join(GatewayClient.instance().url, GatewayClient.instance().kernels_endpoint)
self.kernel = None
... | ");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES... | 256 | 256 | 1,278 | 9 | 246 | kwimp/logManagement | elyra/http_kernel_manager.py | Python | HTTPKernelManager | HTTPKernelManager | 37 | 190 | 37 | 37 | 526b487f4257ec100ff9d13435ecc97c7699e4f0 | bigcode/the-stack | train |
ac340a99446538931300d1e0 | train | function | def read_anchors(anchors_path):
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
anchors = np.array(anchors).reshape(-1, 2)
return anchors
| def read_anchors(anchors_path):
| with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
anchors = np.array(anchors).reshape(-1, 2)
return anchors
| else:
raise ValueError('Composition of empty sequence not supported.')
def read_classes(classes_path):
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
def read_anchors(anchors_path):
| 64 | 64 | 57 | 8 | 55 | just-youssef/YOLO-Car-Detection-Model | yad2k/utils/utils.py | Python | read_anchors | read_anchors | 37 | 42 | 37 | 37 | 789dd5ba9bfb4aebad68401f39550e0bf7ab0bd0 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.