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
cf204c91fac658b7fb61414d
train
function
def create_folder_if_absent(folder): if not os.path.exists(folder): os.makedirs(folder)
def create_folder_if_absent(folder):
if not os.path.exists(folder): os.makedirs(folder)
...".format(time_to_sleep)) time.sleep(time_to_sleep) download_link(link, folder, filename, retries=retries - 1) else: raise Exception("Something wrong happened while downloading the link: " + link + " :: " + str(error)) def create_folder_if_absent(folder):
64
64
21
8
56
akoufoudakis/bacon
bacon_install.py
Python
create_folder_if_absent
create_folder_if_absent
156
158
156
156
ad8c3fcc0dfb92a2ba6ab9a24dfc95a9d3f5add6
bigcode/the-stack
train
508775e4aaae7bfe6060c454
train
function
def print_mac_notice_if_required(): """ Print this notice for Mac users since their PATH env var is different than in Linux """ if platform.system() == 'Darwin': print("") print("Mac user detected! Please adjust your $PATH variable if" + " necessary to run 'bacon'") ...
def print_mac_notice_if_required():
""" Print this notice for Mac users since their PATH env var is different than in Linux """ if platform.system() == 'Darwin': print("") print("Mac user detected! Please adjust your $PATH variable if" + " necessary to run 'bacon'") print("") print(" $...
nc/da/pig, run:" echo "" echo " bacon update <version>" echo "" echo "To update to a snapshot version of bacon, run:" echo "" echo " bacon update snapshot" echo "" fi """.strip() def print_mac_notice_if_required():
64
64
98
7
57
akoufoudakis/bacon
bacon_install.py
Python
print_mac_notice_if_required
print_mac_notice_if_required
97
109
97
97
ceb18d616f4afe09ec9738e7fa5249b79b63bc52
bigcode/the-stack
train
7e3a1ec88eee238491c9f75f
train
function
def is_root(): return os.geteuid() == 0
def is_root():
return os.geteuid() == 0
.bacon_jar_location, "pig")) os.chmod(filename_bacon, 0o755) os.chmod(filename_pnc, 0o755) os.chmod(filename_da, 0o755) os.chmod(filename_pig, 0o755) def is_root():
64
64
15
4
60
akoufoudakis/bacon
bacon_install.py
Python
is_root
is_root
271
272
271
271
124028e43a31e716a17dbdeb4d505f3b6e7d0aa2
bigcode/the-stack
train
2c9c9a42417eba7eea11660e
train
function
def main(): """ Main entry point to the program """ version = None maven_link = MAVEN_CENTRAL_LINK if len(sys.argv) >= 2: version = sys.argv[1] if sys.argv[1] == 'snapshot': maven_link = MAVEN_SNAPSHOT_LINK bacon_jar_location = USER_BACON_JAR_FOLDER_LOCATION ...
def main():
""" Main entry point to the program """ version = None maven_link = MAVEN_CENTRAL_LINK if len(sys.argv) >= 2: version = sys.argv[1] if sys.argv[1] == 'snapshot': maven_link = MAVEN_SNAPSHOT_LINK bacon_jar_location = USER_BACON_JAR_FOLDER_LOCATION shell_loca...
_bacon, 0o755) os.chmod(filename_pnc, 0o755) os.chmod(filename_da, 0o755) os.chmod(filename_pig, 0o755) def is_root(): return os.geteuid() == 0 def main():
64
64
178
3
60
akoufoudakis/bacon
bacon_install.py
Python
main
main
275
304
275
275
45e4e6d42be5c984c5c4611a887f35e4b73eb2a9
bigcode/the-stack
train
090883709ec13ad2e3752212
train
function
def download_maven_metadata_xml(url, folder): """ Download the maven-metadata.xml for bacon and put it in folder url must be without maven-metadata.xml """ if not url.endswith("/"): url = url + "/" link = url + "maven-metadata.xml" download_link(link, folder, "maven-metadata.xml")
def download_maven_metadata_xml(url, folder):
""" Download the maven-metadata.xml for bacon and put it in folder url must be without maven-metadata.xml """ if not url.endswith("/"): url = url + "/" link = url + "maven-metadata.xml" download_link(link, folder, "maven-metadata.xml")
print("Mac user detected! Please adjust your $PATH variable if" + " necessary to run 'bacon'") print("") print(" $ echo 'export PATH=\"$PATH:${HOME}/bin\"' >> " + "~/.bash_profile") def download_maven_metadata_xml(url, folder):
64
64
81
10
54
akoufoudakis/bacon
bacon_install.py
Python
download_maven_metadata_xml
download_maven_metadata_xml
112
122
112
112
8e2ccb8c2f83afd5a2d6e11cd22fd3b6ae8fb405
bigcode/the-stack
train
2d175174780db427b4da4a3f
train
function
def download_link(link, folder, filename, retries=7): """ Download the link into the folder with name 'filename' Add retries in case the download fails due to stale server content issue on repositories.jboss.org """ print("Downloading: " + link) if sys.version_info[0] >= 3: import ...
def download_link(link, folder, filename, retries=7):
""" Download the link into the folder with name 'filename' Add retries in case the download fails due to stale server content issue on repositories.jboss.org """ print("Downloading: " + link) if sys.version_info[0] >= 3: import urllib.request as request else: import url...
bacon and put it in folder url must be without maven-metadata.xml """ if not url.endswith("/"): url = url + "/" link = url + "maven-metadata.xml" download_link(link, folder, "maven-metadata.xml") def download_link(link, folder, filename, retries=7):
73
73
246
13
60
akoufoudakis/bacon
bacon_install.py
Python
download_link
download_link
125
153
125
125
247eb4a8b99af5548cb145a75de6f7a0d061f53b
bigcode/the-stack
train
490a3b5aa79279618d5c950a
train
class
class TestNats(metricbeat.BaseTest): COMPOSE_SERVICES = ['nats'] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") def test_stats(self): """ nats stats test """ self.render_config_template(modules=[{ "name": "nats", "metricsets":...
class TestNats(metricbeat.BaseTest):
COMPOSE_SERVICES = ['nats'] @unittest.skipUnless(metricbeat.INTEGRATION_TESTS, "integration test") def test_stats(self): """ nats stats test """ self.render_config_template(modules=[{ "name": "nats", "metricsets": ["stats"], "hosts": self....
import os import metricbeat import unittest NATS_FIELDS = metricbeat.COMMON_FIELDS + ["nats"] class TestNats(metricbeat.BaseTest):
33
218
728
9
24
maehue/mqttbeat
vendor/github.com/elastic/beats/metricbeat/tests/system/test_nats.py
Python
TestNats
TestNats
8
110
8
9
eff97fe88ba2c53e0b24abeb15c149726b498e26
bigcode/the-stack
train
e9789143e349a8ed6162245c
train
class
class TestNats1_3(TestNats): COMPOSE_SERVICES = ['nats_1_3']
class TestNats1_3(TestNats):
COMPOSE_SERVICES = ['nats_1_3']
arnings() output = self.read_output_json() self.assertEqual(len(output), 1) evt = output[0] self.assertItemsEqual(self.de_dot(NATS_FIELDS), evt.keys(), evt) self.assert_fields_are_documented(evt) class TestNats1_3(TestNats):
64
64
25
11
53
maehue/mqttbeat
vendor/github.com/elastic/beats/metricbeat/tests/system/test_nats.py
Python
TestNats1_3
TestNats1_3
113
114
113
113
74806bc265229fbda2b8c5ac56d1d9f9aef6c915
bigcode/the-stack
train
c79f00e7122d873cc10c2ee4
train
class
class Incident(Model): __core__ = True objects = IncidentManager() organization = FlexibleForeignKey('sentry.Organization') projects = models.ManyToManyField( 'sentry.Project', related_name='incidents', through=IncidentProject, ) groups = models.ManyToManyField( ...
class Incident(Model):
__core__ = True objects = IncidentManager() organization = FlexibleForeignKey('sentry.Organization') projects = models.ManyToManyField( 'sentry.Project', related_name='incidents', through=IncidentProject, ) groups = models.ManyToManyField( 'sentry.Group', ...
.atomic(): result = self.filter(organization=organization).aggregate(models.Max('identifier')) identifier = result['identifier__max'] if identifier is None: identifier = 1 else: identifier += 1 return super(IncidentManager, sel...
104
104
347
4
99
overquota/sentry
src/sentry/incidents/models.py
Python
Incident
Incident
96
142
96
96
2deabb3fbba753c7fc7dcc591fa8d1981c3f9dff
bigcode/the-stack
train
ce174e0cc42312fd47fc6eea
train
class
class IncidentGroup(Model): __core__ = False group = FlexibleForeignKey('sentry.Group', db_index=False, db_constraint=False) incident = FlexibleForeignKey('sentry.Incident') class Meta: app_label = 'sentry' db_table = 'sentry_incidentgroup' unique_together = (('group', 'inciden...
class IncidentGroup(Model):
__core__ = False group = FlexibleForeignKey('sentry.Group', db_index=False, db_constraint=False) incident = FlexibleForeignKey('sentry.Incident') class Meta: app_label = 'sentry' db_table = 'sentry_incidentgroup' unique_together = (('group', 'incident'), )
entry.Project', db_index=False, db_constraint=False) incident = FlexibleForeignKey('sentry.Incident') class Meta: app_label = 'sentry' db_table = 'sentry_incidentproject' unique_together = (('project', 'incident'), ) class IncidentGroup(Model):
64
64
79
5
59
overquota/sentry
src/sentry/incidents/models.py
Python
IncidentGroup
IncidentGroup
33
42
33
33
02066109be2b7f7062cac25e5ba524e4625c2589
bigcode/the-stack
train
27d8ee6309a8dbae3631244c
train
class
class IncidentStatus(Enum): DETECTED = 0 CREATED = 1 CLOSED = 2
class IncidentStatus(Enum):
DETECTED = 0 CREATED = 1 CLOSED = 2
identifier')) identifier = result['identifier__max'] if identifier is None: identifier = 1 else: identifier += 1 return super(IncidentManager, self).create( organization=organization, identifier=identifier, ...
64
64
25
5
59
overquota/sentry
src/sentry/incidents/models.py
Python
IncidentStatus
IncidentStatus
90
93
90
90
760f21206a106127233372ee8d85f6e5b1f67a7f
bigcode/the-stack
train
7e7d268ae8c2e2991f1cfbfc
train
class
class IncidentManager(BaseManager): def fetch_for_organization(self, organization, projects): return self.filter( organization=organization, projects__in=projects, ) @TimedRetryPolicy.wrap(timeout=5, exceptions=(IntegrityError, )) def create(self, organization, **kwa...
class IncidentManager(BaseManager):
def fetch_for_organization(self, organization, projects): return self.filter( organization=organization, projects__in=projects, ) @TimedRetryPolicy.wrap(timeout=5, exceptions=(IntegrityError, )) def create(self, organization, **kwargs): """ Creates an...
user = FlexibleForeignKey(settings.AUTH_USER_MODEL, db_index=False) last_seen = models.DateTimeField(default=timezone.now) class Meta: app_label = 'sentry' db_table = 'sentry_incidentseen' unique_together = (('user', 'incident'), ) class IncidentManager(BaseManager):
69
69
230
6
63
overquota/sentry
src/sentry/incidents/models.py
Python
IncidentManager
IncidentManager
58
87
58
58
836a9553656dc4279449fce9d252a0145e833f9f
bigcode/the-stack
train
d887737bd10fd239b1fd71e7
train
class
class IncidentSeen(Model): __core__ = False incident = FlexibleForeignKey('sentry.Incident') user = FlexibleForeignKey(settings.AUTH_USER_MODEL, db_index=False) last_seen = models.DateTimeField(default=timezone.now) class Meta: app_label = 'sentry' db_table = 'sentry_incidentseen' ...
class IncidentSeen(Model):
__core__ = False incident = FlexibleForeignKey('sentry.Incident') user = FlexibleForeignKey(settings.AUTH_USER_MODEL, db_index=False) last_seen = models.DateTimeField(default=timezone.now) class Meta: app_label = 'sentry' db_table = 'sentry_incidentseen' unique_together = (...
entry.Group', db_index=False, db_constraint=False) incident = FlexibleForeignKey('sentry.Incident') class Meta: app_label = 'sentry' db_table = 'sentry_incidentgroup' unique_together = (('group', 'incident'), ) class IncidentSeen(Model):
64
64
88
5
59
overquota/sentry
src/sentry/incidents/models.py
Python
IncidentSeen
IncidentSeen
45
55
45
45
7e11f20a99edc8f9061843cab1902cf56ea6a19b
bigcode/the-stack
train
28a0dcd16c47626184c4d900
train
class
class IncidentProject(Model): __core__ = False project = FlexibleForeignKey('sentry.Project', db_index=False, db_constraint=False) incident = FlexibleForeignKey('sentry.Incident') class Meta: app_label = 'sentry' db_table = 'sentry_incidentproject' unique_together = (('project'...
class IncidentProject(Model):
__core__ = False project = FlexibleForeignKey('sentry.Project', db_index=False, db_constraint=False) incident = FlexibleForeignKey('sentry.Incident') class Meta: app_label = 'sentry' db_table = 'sentry_incidentproject' unique_together = (('project', 'incident'), )
models, transaction, ) from django.utils import timezone from enum import Enum from sentry.db.models import ( FlexibleForeignKey, Model, UUIDField, ) from sentry.db.models.manager import BaseManager from sentry.utils.retries import TimedRetryPolicy class IncidentProject(Model):
64
64
79
5
58
overquota/sentry
src/sentry/incidents/models.py
Python
IncidentProject
IncidentProject
21
30
21
21
77c6383edd58ddf8db8f6e1055ccbb9ae50adfbe
bigcode/the-stack
train
7f6417f3760249cbe6db5bbf
train
class
class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t1 and t2: t1.val += t2 t1.left = self.mergeTrees(t1.left, t2.left) t1.right = self.mergeTrees(t1.right, t2.right) if not t1: return t2 return t1
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t1 and t2: t1.val += t2 t1.left = self.mergeTrees(t1.left, t2.left) t1.right = self.mergeTrees(t1.right, t2.right) if not t1: return t2 return t1
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution:
42
64
89
3
38
W-KE/Leetcode-Solutions
617.merge-two-binary-trees.py
Python
Solution
Solution
9
17
9
9
38cfd7d96b8b9a6f70aa78bac3b48d1d3324df2a
bigcode/the-stack
train
4035f6e96d96da1d7391f6c0
train
class
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None
class TreeNode:
def __init__(self, x): self.val = x self.left = None self.right = None
# Definition for a binary tree node. class TreeNode:
12
64
31
4
8
W-KE/Leetcode-Solutions
617.merge-two-binary-trees.py
Python
TreeNode
TreeNode
2
6
2
2
580a88759ef5507f09cbd51ccc061299c77ff559
bigcode/the-stack
train
8b700a976a868e2f98fd6c5c
train
function
def config_mpls(network_instances): """Add config data to mpls object.""" # configure default network instance network_instance = network_instances.NetworkInstance() network_instance.name = "default" network_instance.config.name = "default" # auto-bw tunnel tunnel = network_instance.mpls.ls...
def config_mpls(network_instances):
"""Add config data to mpls object.""" # configure default network instance network_instance = network_instances.NetworkInstance() network_instance.name = "default" network_instance.config.name = "default" # auto-bw tunnel tunnel = network_instance.mpls.lsps.constrained_path.tunnels.Tunnel()...
show this help message and exit -v, --verbose print debugging messages """ from argparse import ArgumentParser from urlparse import urlparse from ydk.path import Repository from ydk.services import CRUDService from ydk.gnmi.providers import gNMIServiceProvider from ydk.models.openconfig import openconfig_netw...
124
125
418
7
118
deom119/ydk-py-samples
samples/basic/crud/gnmi/models/openconfig/openconfig-mpls/gn-create-oc-mpls-52-ydk.py
Python
config_mpls
config_mpls
47
78
47
47
fdfe4e867946519199e18d134a39d81e9671630e
bigcode/the-stack
train
7097d99360ea93abe0b64328
train
class
class Task2(Task1): pass
class Task2(Task1):
pass
tflow import pandas as pd # define 2 tasks that load raw data class Task1(d6tflow.tasks.TaskCache): def run(self): df = pd.DataFrame({'a': range(3)}) self.save(df) # quickly save dataframe class Task2(Task1):
64
64
9
6
57
d6t/d6tflow
docs/example-minimal.py
Python
Task2
Task2
13
14
13
13
c69243fbf575f0fac23844f709504a52ce9cd47a
bigcode/the-stack
train
00e5e5b9728611b9eee081ed
train
class
class Task1(d6tflow.tasks.TaskCache): def run(self): df = pd.DataFrame({'a': range(3)}) self.save(df) # quickly save dataframe
class Task1(d6tflow.tasks.TaskCache):
def run(self): df = pd.DataFrame({'a': range(3)}) self.save(df) # quickly save dataframe
import d6tflow import pandas as pd # define 2 tasks that load raw data class Task1(d6tflow.tasks.TaskCache):
32
64
40
11
20
d6t/d6tflow
docs/example-minimal.py
Python
Task1
Task1
6
10
6
7
1a17be6516dd030d212fdcf6115134714c507b30
bigcode/the-stack
train
8d545d04ee10f384eb91d351
train
class
@d6tflow.requires({'input1': Task1, 'input2': Task2}) class Task3(d6tflow.tasks.TaskCache): multiplier = d6tflow.IntParameter(default=2) def run(self): df1 = self.input()['input1'].load() # quickly load input data df2 = self.input()['input2'].load() # quickly load input data df = df1....
@d6tflow.requires({'input1': Task1, 'input2': Task2}) class Task3(d6tflow.tasks.TaskCache):
multiplier = d6tflow.IntParameter(default=2) def run(self): df1 = self.input()['input1'].load() # quickly load input data df2 = self.input()['input2'].load() # quickly load input data df = df1.join(df2, lsuffix='1', rsuffix='2') df['b'] = df['a1'] * self.multiplier # use task...
.save(df) # quickly save dataframe class Task2(Task1): pass # define another task that depends on data from task1 and task2 @d6tflow.requires({'input1': Task1, 'input2': Task2}) class Task3(d6tflow.tasks.TaskCache):
64
64
132
31
32
d6t/d6tflow
docs/example-minimal.py
Python
Task3
Task3
18
27
18
19
0839c2e66d2038cc1387969163b615ab952e0cc4
bigcode/the-stack
train
9d198480b34c579649d7bcf2
train
function
@pytest.fixture def api_client(): return APIClient(None, None, None, API_URL)
@pytest.fixture def api_client():
return APIClient(None, None, None, API_URL)
import re import json import pytest import responses from nylas import APIClient from nylas.client.errors import * API_URL = 'http://localhost:2222' @pytest.fixture def api_client():
44
64
20
7
37
enterstudio/nylas-python
tests/conftest.py
Python
api_client
api_client
11
13
11
12
71abfe5549da32fed302f703b5c9ff0e02cacc15
bigcode/the-stack
train
7e868b4dc01c48f741f803e8
train
function
@pytest.fixture def mock_account(): response_body = json.dumps([ { "account_id": "4dl0ni6vxomazo73r5ozdo16j", "email_address": "ben.bitdiddle1861@gmail.com", "id": "4dl0ni6vxomazo73r5ozdo16j", "name": "Ben Bitdiddle", "object": "account", ...
@pytest.fixture def mock_account():
response_body = json.dumps([ { "account_id": "4dl0ni6vxomazo73r5ozdo16j", "email_address": "ben.bitdiddle1861@gmail.com", "id": "4dl0ni6vxomazo73r5ozdo16j", "name": "Ben Bitdiddle", "object": "account", "provider": "gmail" } ...
import re import json import pytest import responses from nylas import APIClient from nylas.client.errors import * API_URL = 'http://localhost:2222' @pytest.fixture def api_client(): return APIClient(None, None, None, API_URL) @pytest.fixture def mock_account():
64
64
144
7
57
enterstudio/nylas-python
tests/conftest.py
Python
mock_account
mock_account
16
30
16
17
5c1e4550d024562a639a108eb7008f23d84cac03
bigcode/the-stack
train
d76f416e1a9601f20b51aea6
train
function
@pytest.fixture def mock_save_draft(): save_endpoint = re.compile(API_URL + '/drafts/') response_body = json.dumps({ "id": "4dl0ni6vxomazo73r5oydo16k", "version": "4dw0ni6txomazo33r5ozdo16j" }) responses.add(responses.POST, save_endpoint, content_type='application/json'...
@pytest.fixture def mock_save_draft():
save_endpoint = re.compile(API_URL + '/drafts/') response_body = json.dumps({ "id": "4dl0ni6vxomazo73r5oydo16k", "version": "4dw0ni6txomazo33r5ozdo16j" }) responses.add(responses.POST, save_endpoint, content_type='application/json', status=200, body=re...
account", "provider": "gmail" } ]) responses.add(responses.GET, API_URL + '/n?limit=1&offset=0', content_type='application/json', status=200, body=response_body, match_querystring=True) @pytest.fixture def mock_save_draft():
64
64
104
9
55
enterstudio/nylas-python
tests/conftest.py
Python
mock_save_draft
mock_save_draft
33
42
33
34
cff116a3105868396f9906e80423403d62b4fc02
bigcode/the-stack
train
ed72271f04efd3a4cadcb8e1
train
function
def set_mantle_target(t): global mantle_target if mantle_target is not None and mantle_target != t: root_logger().warning('changing mantle target', mantle_target, t ) mantle_target = t
def set_mantle_target(t):
global mantle_target if mantle_target is not None and mantle_target != t: root_logger().warning('changing mantle target', mantle_target, t ) mantle_target = t
Verilog, DeclareFromVerilogFile, DefineFromVerilog, DefineFromVerilogFile, set_verilog_importer) from .backend.verilog import * # compile from .compile import * from .logging import root_logger mantle_target = None def set_mantle_target(t):
64
64
47
8
55
leonardt/magma
magma/__init__.py
Python
set_mantle_target
set_mantle_target
60
64
60
60
4108575d6d34a7bcbcaebbfa7dd9607b8bf78e14
bigcode/the-stack
train
960e24b04a0637bf7f94f9a3
train
function
def clear_cachedFunctions(): for func in cachedFunctions: func.cache_clear()
def clear_cachedFunctions():
for func in cachedFunctions: func.cache_clear()
try: from functools import lru_cache except ImportError: from backports.functools_lru_cache import lru_cache cachedFunctions = [] def clear_cachedFunctions():
38
64
17
5
33
leonardt/magma
magma/__init__.py
Python
clear_cachedFunctions
clear_cachedFunctions
9
11
9
9
90c26b37afa39cabffc97cd0a08c3dff6fd45f7d
bigcode/the-stack
train
172c1466dea77333b00ec6fc
train
function
def cache_definition(fn): cachedFunctions.append(lru_cache(maxsize=None)(fn)) return cachedFunctions[-1]
def cache_definition(fn):
cachedFunctions.append(lru_cache(maxsize=None)(fn)) return cachedFunctions[-1]
try: from functools import lru_cache except ImportError: from backports.functools_lru_cache import lru_cache cachedFunctions = [] def clear_cachedFunctions(): for func in cachedFunctions: func.cache_clear() def cache_definition(fn):
56
64
25
5
51
leonardt/magma
magma/__init__.py
Python
cache_definition
cache_definition
14
16
14
14
45434f75f57a83b7da0144ee38e9e390c408bac7
bigcode/the-stack
train
7da397bc9e437a7b5ef48fd3
train
class
class Solution: def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ red, white, blue = 0, 0, len(nums)-1 while white <= blue: if nums[white] == 0: nums[red], nums[whit...
class Solution:
def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ red, white, blue = 0, 0, len(nums)-1 while white <= blue: if nums[white] == 0: nums[red], nums[white] = nums[white]...
class Solution:
3
64
145
3
0
sm2774us/amazon_interview_prep_2021
solutions/python3/75.py
Python
Solution
Solution
1
17
1
1
040eb0643d9ba90fd11364d04f489b6eed7a1573
bigcode/the-stack
train
387532c924726f7b24370c3d
train
class
@register_action("speaker.speak") class SpeakerSpeak(UpdateAction): """ Action to let speakers speak. """ model = Speaker() schema = DefaultSchema(Speaker()).get_default_schema( required_properties=["id"], title="Speak schema", description="Schema to let a speaker's speach b...
@register_action("speaker.speak") class SpeakerSpeak(UpdateAction):
""" Action to let speakers speak. """ model = Speaker() schema = DefaultSchema(Speaker()).get_default_schema( required_properties=["id"], title="Speak schema", description="Schema to let a speaker's speach begin.", ) def get_updated_instances(self, payload: ActionPa...
import time from ....models.models import Speaker from ....services.datastore.interface import GetManyRequest from ....shared.exceptions import ActionException from ....shared.patterns import Collection, FullQualifiedId from ...generics.update import UpdateAction from ...util.default_schema import DefaultSchema from ....
90
117
392
14
75
r-peschke/openslides-backend
openslides_backend/action/actions/speaker/speak.py
Python
SpeakerSpeak
SpeakerSpeak
13
65
13
14
48327a980160b1da62d17cf72c65891bc369848d
bigcode/the-stack
train
3019c892b7b2c2dcfa18e2ca
train
function
def parse_args(): metadata_file_svc = os.path.expanduser('~/data/openml-defaults/svc.arff') metadata_file_gb = os.path.expanduser('~/data/openml-defaults/gradient_boosting.arff') metadata_file_adaboost019 = os.path.expanduser('~/projects/openml-pimp/KDD2018/data/arff/adaboost.arff') metadata_file_random...
def parse_args():
metadata_file_svc = os.path.expanduser('~/data/openml-defaults/svc.arff') metadata_file_gb = os.path.expanduser('~/data/openml-defaults/gradient_boosting.arff') metadata_file_adaboost019 = os.path.expanduser('~/projects/openml-pimp/KDD2018/data/arff/adaboost.arff') metadata_file_random_forest019 = os.pa...
import arff import argparse import logging import numpy as np import openmlcontrib import openmldefaults import os import pandas as pd # SSHFS NEMO FREIBURG: # sshfs jv2657@habanero.rcs.columbia.edu:/rigel/home/jv2657/experiments ~/habanero_experiments # # SSHFS GRACE LEIDEN: # ssh -f -N -L 1233:grace.liacs.nl:22 rij...
154
164
549
4
149
pfistfl/openml-defaults
examples/vanilla/multiple_defaults_continuous_on_surrogate.py
Python
parse_args
parse_args
17
45
17
17
219aa0246c3ffacd958638494b9f35dfd2c0bc4c
bigcode/the-stack
train
475c2ba9fbeb4b82cc932b4e
train
function
def run(args): logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s] %(message)s') task_ids = None for arff_file in args.metadata_files: with open(arff_file, 'r') as fp: df = openmlcontrib.meta.arff_to_dataframe(arff.load(fp), None) if task_ids is Non...
def run(args):
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s] %(message)s') task_ids = None for arff_file in args.metadata_files: with open(arff_file, 'r') as fp: df = openmlcontrib.meta.arff_to_dataframe(arff.load(fp), None) if task_ids is None: ...
_argument('--n_configurations', type=int, default=1024) parser.add_argument('--n_estimators', type=int, default=64) parser.add_argument('--minimum_evals', type=int, default=128) parser.add_argument('--random_seed', type=int, default=1) parser.add_argument('--evaluate_on_surrogates', action='store_true')...
129
130
434
4
125
pfistfl/openml-defaults
examples/vanilla/multiple_defaults_continuous_on_surrogate.py
Python
run
run
48
97
48
48
1ab6ba0fd99f5bb0263521be7c9f3690d44377c3
bigcode/the-stack
train
c43bf1350a20b2d3dfbf70d2
train
function
def int_or_str(text): """Helper function for argument parsing.""" try: return int(text) except ValueError: return text
def int_or_str(text):
"""Helper function for argument parsing.""" try: return int(text) except ValueError: return text
#!/usr/bin/env python3 """Play a sine signal.""" import argparse import sys import numpy as np import sounddevice as sd def int_or_str(text):
36
64
31
6
29
blattm/python-sounddevice
examples/play_sine.py
Python
int_or_str
int_or_str
10
15
10
10
d830024af95a63f057a74df3c52035a8e7e12569
bigcode/the-stack
train
7ccc82029f9122a74d008218
train
class
class FileDescriptor(object): """ The descriptor for the file attribute on the model instance. Returns a FieldFile when accessed so you can do stuff like:: >>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size Assigns a file object...
class FileDescriptor(object):
""" The descriptor for the file attribute on the model instance. Returns a FieldFile when accessed so you can do stuff like:: >>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size Assigns a file object on assignment so you can do::...
setattr(self.instance, self.field.name, self.name) # Delete the filesize cache if hasattr(self, '_size'): del self._size self._committed = False if save: self.instance.save() delete.alters_data = True def _get_closed(self): file = getatt...
217
217
724
5
212
MikeAmy/django
django/db/models/fields/files.py
Python
FileDescriptor
FileDescriptor
141
213
141
141
d6a596bc0bf844b4d4c9ec434bc640556e7a8131
bigcode/the-stack
train
15bb73885cf051fdd59ae696
train
class
class FieldFile(File): def __init__(self, instance, field, name): super(FieldFile, self).__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting Fi...
class FieldFile(File):
def __init__(self, instance, field, name): super(FieldFile, self).__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be si...
import datetime import os from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import default_storage from django.db.models import signals from django.db.models.fields import Field from django.utils...
90
256
892
5
85
MikeAmy/django
django/db/models/fields/files.py
Python
FieldFile
FieldFile
16
138
16
16
338e71faa39cb17362e4d687299d20ab409148f6
bigcode/the-stack
train
485fde6e0a56b422f4c854f0
train
class
class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, '_dimensions_cache'): del self._dimensions_cache super(ImageFieldFile, self).delete(save)
class ImageFieldFile(ImageFile, FieldFile):
def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, '_dimensions_cache'): del self._dimensions_cache super(ImageFieldFile, self).delete(save)
to the post_init signal handles the Model.__init__() cases. # Assignment happening outside of Model.__init__() will trigger the # update right here. if previous_file is not None: self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile):
64
64
53
10
54
MikeAmy/django
django/db/models/fields/files.py
Python
ImageFieldFile
ImageFieldFile
369
374
369
369
ed11a6dfe0fcad8dbc36c5fc390c92e6db9fd0f7
bigcode/the-stack
train
9f1ca5ec308d21225fa70ca6
train
class
class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor descrip...
class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class.
attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor description = _("File") def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs): self._primary_key_set_explicitly = 'primary_key' i...
elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.name] = file_copy # Finally, because of the...
256
256
1,111
35
220
MikeAmy/django
django/db/models/fields/files.py
Python
FileField
FileField
216
344
216
219
1c54fdfb3ae331f0a386200ca166ab5131c7bcd4
bigcode/the-stack
train
a70a74e0afba5722804ef5b8
train
class
class ImageFileDescriptor(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) ...
class ImageFileDescriptor(FileDescriptor):
""" Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) super(ImageFileDescriptor, self).__...
, but can probably be removed once form_for_instance # is gone. ModelForm uses a different method to check for an existing file. if 'initial' in kwargs: defaults['required'] = False defaults.update(kwargs) return super(FileField, self).formfield(**defaults) class ImageFileDes...
70
70
236
7
63
MikeAmy/django
django/db/models/fields/files.py
Python
ImageFileDescriptor
ImageFileDescriptor
347
366
347
347
0cb66b2dc824f39298ea1ff699cf9a6bec5a029d
bigcode/the-stack
train
4f3ebdf14b6c859969ce8cbf
train
class
class ImageField(FileField): attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = _("Image") def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field ...
class ImageField(FileField):
attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = _("Image") def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs): self.width_field, self.height_field = width_field, height_field super(ImageField, self...
, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.name) super(ImageFileDescriptor, self).__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11...
256
256
925
6
250
MikeAmy/django
django/db/models/fields/files.py
Python
ImageField
ImageField
377
484
377
377
c3a21e801bdc591a90f61efccbda1e3fa9efe8aa
bigcode/the-stack
train
ecacf5e7213916f662eb9140
train
function
@pytest.mark.asyncio async def test_http_to_https_redirect_middleware_websocket_http2() -> None: app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal sent_events sent_events.append(message) scope = { ...
@pytest.mark.asyncio async def test_http_to_https_redirect_middleware_websocket_http2() -> None:
app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal sent_events sent_events.append(message) scope = { "type": "websocket", "http_version": "2", "scheme": "ws", "raw_path": b"/...
307, "headers": [(b"location", b"wss://localhost%s?a=b" % raw_path)], }, {"type": "websocket.http.response.body"}, ] @pytest.mark.asyncio async def test_http_to_https_redirect_middleware_websocket_http2() -> None:
63
64
192
22
41
justin0mcateer/hypercorn
tests/middleware/test_http_to_https.py
Python
test_http_to_https_redirect_middleware_websocket_http2
test_http_to_https_redirect_middleware_websocket_http2
59
85
59
60
c0965016370f6e006bda2b2c91403051f06b35e8
bigcode/the-stack
train
1141d585a046cdfe0f3e0ace
train
function
@pytest.mark.asyncio @pytest.mark.parametrize("raw_path", [b"/abc", b"/abc%3C"]) async def test_http_to_https_redirect_middleware_websocket(raw_path: bytes) -> None: app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal se...
@pytest.mark.asyncio @pytest.mark.parametrize("raw_path", [b"/abc", b"/abc%3C"]) async def test_http_to_https_redirect_middleware_websocket(raw_path: bytes) -> None:
app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal sent_events sent_events.append(message) scope = { "type": "websocket", "scheme": "ws", "raw_path": raw_path, "query_string"...
?a=b" % raw_path)], }, {"type": "http.response.body"}, ] @pytest.mark.asyncio @pytest.mark.parametrize("raw_path", [b"/abc", b"/abc%3C"]) async def test_http_to_https_redirect_middleware_websocket(raw_path: bytes) -> None:
63
64
208
43
20
justin0mcateer/hypercorn
tests/middleware/test_http_to_https.py
Python
test_http_to_https_redirect_middleware_websocket
test_http_to_https_redirect_middleware_websocket
30
56
30
32
5df76b87dbf17fdf6c42eaa280290a3f18b8f018
bigcode/the-stack
train
f5adfde05972bea9313917e3
train
function
@pytest.mark.asyncio async def test_http_to_https_redirect_middleware_websocket_no_rejection() -> None: app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal sent_events sent_events.append(message) scope = { ...
@pytest.mark.asyncio async def test_http_to_https_redirect_middleware_websocket_no_rejection() -> None:
app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal sent_events sent_events.append(message) scope = { "type": "websocket", "http_version": "2", "scheme": "ws", "raw_path": b"/...
"status": 307, "headers": [(b"location", b"https://localhost/abc?a=b")], }, {"type": "websocket.http.response.body"}, ] @pytest.mark.asyncio async def test_http_to_https_redirect_middleware_websocket_no_rejection() -> None:
63
64
135
23
40
justin0mcateer/hypercorn
tests/middleware/test_http_to_https.py
Python
test_http_to_https_redirect_middleware_websocket_no_rejection
test_http_to_https_redirect_middleware_websocket_no_rejection
88
106
88
89
f6983e0065a5f1384499865db71426ca26aa29ac
bigcode/the-stack
train
91ed05d1bac2d78f813083e8
train
function
@pytest.mark.asyncio @pytest.mark.parametrize("raw_path", [b"/abc", b"/abc%3C"]) async def test_http_to_https_redirect_middleware_http(raw_path: bytes) -> None: app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal sent_ev...
@pytest.mark.asyncio @pytest.mark.parametrize("raw_path", [b"/abc", b"/abc%3C"]) async def test_http_to_https_redirect_middleware_http(raw_path: bytes) -> None:
app = HTTPToHTTPSRedirectMiddleware(empty_framework, "localhost") sent_events = [] async def send(message: dict) -> None: nonlocal sent_events sent_events.append(message) scope = {"type": "http", "scheme": "http", "raw_path": raw_path, "query_string": b"a=b"} await app(scope, None,...
import pytest from hypercorn.middleware import HTTPToHTTPSRedirectMiddleware from ..helpers import empty_framework @pytest.mark.asyncio @pytest.mark.parametrize("raw_path", [b"/abc", b"/abc%3C"]) async def test_http_to_https_redirect_middleware_http(raw_path: bytes) -> None:
63
64
181
42
20
justin0mcateer/hypercorn
tests/middleware/test_http_to_https.py
Python
test_http_to_https_redirect_middleware_http
test_http_to_https_redirect_middleware_http
7
27
7
9
6c612d1708497331f61e4c0cda87d0b32c33febd
bigcode/the-stack
train
2c8ce9c61f8abbaeacdbae0d
train
function
def main(): parser = argparse.ArgumentParser() parser.add_argument('--encoder-config', default=None, type=str) parser.add_argument('--transformer-config', default=None, type=str) parser.add_argument('--decoder-config', default=None, type=str) parser.add_argument('--src-celeb-name', default=None, ty...
def main():
parser = argparse.ArgumentParser() parser.add_argument('--encoder-config', default=None, type=str) parser.add_argument('--transformer-config', default=None, type=str) parser.add_argument('--decoder-config', default=None, type=str) parser.add_argument('--src-celeb-name', default=None, type=str) ...
nn.parameter_scope('netG_decoder'): fake_img = decoder_netG(fake_bod_map_unlinked, test=True) fake_img.persistent = True # load parameters of networks with nn.parameter_scope('netG_decoder'): nn.load_parameters(decoder_param_file) monitor_vis = nm.MonitorImage('result', ...
246
246
820
3
243
saulocatharino/nnabla-examples
GANs/reenactgan/test_reenactment.py
Python
main
main
108
200
108
108
94657cb11858a8bdc18b5de7c5dea92a61b6b492
bigcode/the-stack
train
7ab0a7755e6710b0d015f98a
train
function
def test(encoder_config, transformer_config, decoder_config, encoder_netG, transformer_netG, decoder_netG, src_celeb_name, trg_celeb_name, test_iterator, monitor, encoder_param_file, transformer_param_file, decoder_param_file): # prepare nn.Variable real_img = nn.Variable((1,...
def test(encoder_config, transformer_config, decoder_config, encoder_netG, transformer_netG, decoder_netG, src_celeb_name, trg_celeb_name, test_iterator, monitor, encoder_param_file, transformer_param_file, decoder_param_file): # prepare nn.Variable
real_img = nn.Variable((1, 3, 256, 256)) real_bod_map = nn.Variable((1, 15, 64, 64)) real_bod_map_resize = nn.Variable((1, 15, 256, 256)) # encoder with nn.parameter_scope(encoder_config["model_name"]): _, preds = encoder_netG( real_img, batch_stat=False, ...
# 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 KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. imp...
184
184
614
61
122
saulocatharino/nnabla-examples
GANs/reenactgan/test_reenactment.py
Python
test
test
31
105
31
36
e7b577e38fbeab8a01710412863d551ddd55d8ea
bigcode/the-stack
train
ebf4cf48ce34009f313fde15
train
function
def gray_to_color(image, five=True): W,H = image.shape[0:2] colormap = get_colormap(five) c = image.ravel() output = np.asarray([colormap[i] for i in c]) output = output.reshape((W, H, 3)).astype(np.uint8) return output
def gray_to_color(image, five=True):
W,H = image.shape[0:2] colormap = get_colormap(five) c = image.ravel() output = np.asarray([colormap[i] for i in c]) output = output.reshape((W, H, 3)).astype(np.uint8) return output
0xc4c4e2, 2105408, 255, 0x608080, 6749952, 16737792, 16711884] return {i: f32(key[i]) for i in range(len(key))} def gray_to_color(image, five=True):
63
64
75
9
55
commaai/comma10k
viewer.py
Python
gray_to_color
gray_to_color
19
25
19
19
afc0f19a26dbf11cab82fa1511b1be16e7eaf2d2
bigcode/the-stack
train
a79730362ca0734600314de7
train
function
def fix(im): dat = np.array(im) if im.mode == "P": # palette image pp = np.array(im.getpalette()).reshape((-1, 3)).astype(np.uint8) sh = dat.shape dat = pp[dat.flatten()].reshape(list(sh)+[3]) if dat.shape[2] != 3: # remove alpha dat = dat[:, :, 0:3] return dat
def fix(im):
dat = np.array(im) if im.mode == "P": # palette image pp = np.array(im.getpalette()).reshape((-1, 3)).astype(np.uint8) sh = dat.shape dat = pp[dat.flatten()].reshape(list(sh)+[3]) if dat.shape[2] != 3: # remove alpha dat = dat[:, :, 0:3] return dat
[0:2] colormap = get_colormap(five) c = image.ravel() output = np.asarray([colormap[i] for i in c]) output = output.reshape((W, H, 3)).astype(np.uint8) return output def fix(im):
64
64
97
4
59
commaai/comma10k
viewer.py
Python
fix
fix
27
38
27
27
93cfca587aa79a38feb7474ff231deaa65aaf3a9
bigcode/the-stack
train
146e08b40c43d07a303da428
train
function
def get_colormap(five=True): f32 = lambda x: (x % 256, x//256 % 256, x//(256*256) % 256) if five: key = [2105408, 255, 0x608080, 6749952, 16711884] else: key = [0, 0xc4c4e2, 2105408, 255, 0x608080, 6749952, 16737792, 16711884] return {i: f32(key[i]) for i in range(len(key))}
def get_colormap(five=True):
f32 = lambda x: (x % 256, x//256 % 256, x//(256*256) % 256) if five: key = [2105408, 255, 0x608080, 6749952, 16711884] else: key = [0, 0xc4c4e2, 2105408, 255, 0x608080, 6749952, 16737792, 16711884] return {i: f32(key[i]) for i in range(len(key))}
/bin/env python3 import os import sys import numpy as np from tqdm import tqdm from PIL import Image NOSEGS = os.getenv("NOSEGS") is not None IMGS2 = os.getenv("IMGS2") is not None def get_colormap(five=True):
64
64
134
8
55
commaai/comma10k
viewer.py
Python
get_colormap
get_colormap
11
17
11
11
5302b8092279b414c25ecff4a01c9d9423c8e615
bigcode/the-stack
train
c6102add4c1c01f22604687e
train
function
def main(argv): faspRunner = FASPRunner(pauseSecs=0) # Step 1 - Discovery # query for relevant DRS objects searchClient = DiscoverySearchClient('https://ga4gh-search-adapter-presto-public.prod.dnastack.com/') query = "select submitter_id, read_drs_id drsid from thousand_genomes.onek_genomes.ssd_drs where populat...
def main(argv):
faspRunner = FASPRunner(pauseSecs=0) # Step 1 - Discovery # query for relevant DRS objects searchClient = DiscoverySearchClient('https://ga4gh-search-adapter-presto-public.prod.dnastack.com/') query = "select submitter_id, read_drs_id drsid from thousand_genomes.onek_genomes.ssd_drs where population = 'ACB' limit...
# IMPORTS import sys from fasp.runner import FASPRunner # The implementations we're using from fasp.loc import bdcDRSClient from fasp.search import DiscoverySearchClient from fasp.workflow import DNAStackWESClient def main(argv):
59
64
205
4
54
lifebit-ai/fasp-scripts
fasp/scripts/FASPScript4.py
Python
main
main
12
29
12
13
72c4b14d63ad3d85b075b686243240a676482d0b
bigcode/the-stack
train
a786a8543c05cfcb25c97345
train
class
class CajeroATMChain: def __init__(self): self.chain1=Cajero50ConcreteHandler() self.chain2=Cajero20ConcreteHandler() self.chain3=Cajero10ConcreteHandler() self.chain1.next_succesor(self.chain2) self.chain2.next_succesor(self.chain3)
class CajeroATMChain:
def __init__(self): self.chain1=Cajero50ConcreteHandler() self.chain2=Cajero20ConcreteHandler() self.chain3=Cajero10ConcreteHandler() self.chain1.next_succesor(self.chain2) self.chain2.next_succesor(self.chain3)
antidad // 10 r=cantidad % 10 print (f"Dar {num} de 10") if r !=0: self._next.handle(r) else: self._next.handle(cantidad) #donde creo mis instancias class CajeroATMChain:
64
64
70
6
57
bryanbalderas/DAS_Sistemas
Ene-Jun-2021/perez-gutierrez-julio-cesar/Primer Parcial Julio/Ejercicio 4/cajero_chain.py
Python
CajeroATMChain
CajeroATMChain
59
65
59
59
0eabe341b070562ee099dc2e525cfa2dc91ebc5c
bigcode/the-stack
train
37be5d27300e4471df36717f
train
class
class Cajero10ConcreteHandler(CajeroHandler): def __init__(self): self._next=None def next_succesor(self, next): self._next = next def handle(self, cantidad): if cantidad >= 10: num=cantidad // 10 r=cantidad % 10 print (f"Dar {num} de 10") ...
class Cajero10ConcreteHandler(CajeroHandler):
def __init__(self): self._next=None def next_succesor(self, next): self._next = next def handle(self, cantidad): if cantidad >= 10: num=cantidad // 10 r=cantidad % 10 print (f"Dar {num} de 10") if r !=0: self._next.handl...
: num=cantidad // 20 r=cantidad % 20 print(f"Dar {num} de 20") if r !=0: self._next.handle(r) else: self._next.handle(cantidad) class Cajero10ConcreteHandler(CajeroHandler):
64
64
108
11
53
bryanbalderas/DAS_Sistemas
Ene-Jun-2021/perez-gutierrez-julio-cesar/Primer Parcial Julio/Ejercicio 4/cajero_chain.py
Python
Cajero10ConcreteHandler
Cajero10ConcreteHandler
43
56
43
43
d45c307e962be5422e39b988bb3dfe4a894b1573
bigcode/the-stack
train
ab5492a1774480b8679cd77b
train
class
class Cajero50ConcreteHandler(CajeroHandler): def __init__(self): self._next=None def next_succesor(self, next): self._next = next def handle(self, cantidad): if cantidad >= 50: num=cantidad // 50 r=cantidad % 50 print(f"Dar {num} de 50") ...
class Cajero50ConcreteHandler(CajeroHandler):
def __init__(self): self._next=None def next_succesor(self, next): self._next = next def handle(self, cantidad): if cantidad >= 50: num=cantidad // 50 r=cantidad % 50 print(f"Dar {num} de 50") if r !=0: self._next.handle...
Handler(metaclass=ABCMeta): @abstractstaticmethod def next_succesor(next): """siguiente handler en la cadena""" @abstractstaticmethod def handle(cantidad): """lo que ocurre""" #mis handlers concretos class Cajero50ConcreteHandler(CajeroHandler):
64
64
107
11
52
bryanbalderas/DAS_Sistemas
Ene-Jun-2021/perez-gutierrez-julio-cesar/Primer Parcial Julio/Ejercicio 4/cajero_chain.py
Python
Cajero50ConcreteHandler
Cajero50ConcreteHandler
13
26
13
13
e7c91265a7dad56935426371e7b9be1d04ce6b0e
bigcode/the-stack
train
43aa3224b7bf6684821263c3
train
class
class Cajero20ConcreteHandler(CajeroHandler): def __init__(self): self._next=None def next_succesor(self, next): self._next = next def handle(self, cantidad): if cantidad >= 20: num=cantidad // 20 r=cantidad % 20 print(f"Dar {num} de 20") ...
class Cajero20ConcreteHandler(CajeroHandler):
def __init__(self): self._next=None def next_succesor(self, next): self._next = next def handle(self, cantidad): if cantidad >= 20: num=cantidad // 20 r=cantidad % 20 print(f"Dar {num} de 20") if r !=0: self._next.handle...
: num=cantidad // 50 r=cantidad % 50 print(f"Dar {num} de 50") if r !=0: self._next.handle(r) else: self._next.handle(cantidad) class Cajero20ConcreteHandler(CajeroHandler):
64
64
107
11
53
bryanbalderas/DAS_Sistemas
Ene-Jun-2021/perez-gutierrez-julio-cesar/Primer Parcial Julio/Ejercicio 4/cajero_chain.py
Python
Cajero20ConcreteHandler
Cajero20ConcreteHandler
28
41
28
28
a9c8b0eeb18efc6c7fc0bfb450edd776e25040da
bigcode/the-stack
train
827f187362c78bda226fad63
train
class
class CajeroHandler(metaclass=ABCMeta): @abstractstaticmethod def next_succesor(next): """siguiente handler en la cadena""" @abstractstaticmethod def handle(cantidad): """lo que ocurre"""
class CajeroHandler(metaclass=ABCMeta): @abstractstaticmethod
def next_succesor(next): """siguiente handler en la cadena""" @abstractstaticmethod def handle(cantidad): """lo que ocurre"""
from abc import ABCMeta, abstractstaticmethod #mi Handler class CajeroHandler(metaclass=ABCMeta): @abstractstaticmethod
29
64
50
16
12
bryanbalderas/DAS_Sistemas
Ene-Jun-2021/perez-gutierrez-julio-cesar/Primer Parcial Julio/Ejercicio 4/cajero_chain.py
Python
CajeroHandler
CajeroHandler
4
10
4
5
a9b642a5c8180f395d312e10214544487bb1b2bd
bigcode/the-stack
train
6af4873f91fb07bda5384450
train
class
class PacketCaptureQueryStatusResult(Model): """Status of packet capture session. :param name: The name of the packet capture resource. :type name: str :param id: The ID of the packet capture resource. :type id: str :param capture_start_time: The start time of the packet capture session....
class PacketCaptureQueryStatusResult(Model):
"""Status of packet capture session. :param name: The name of the packet capture resource. :type name: str :param id: The ID of the packet capture resource. :type id: str :param capture_start_time: The start time of the packet capture session. :type capture_start_time: datetime ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # C...
93
126
423
8
84
EnjoyLifeFund/macHighSierra-py36-pkgs
azure/mgmt/network/v2017_03_01/models/packet_capture_query_status_result.py
Python
PacketCaptureQueryStatusResult
PacketCaptureQueryStatusResult
15
52
15
15
7b627ab0b7a291bac32ad022b35c4ca527005013
bigcode/the-stack
train
cfb9e8265933ce9e470b8a09
train
class
class Stripe(BasePayment): backend_form_class = BackendStripeForm description = """ Using this payment method, you can pay using your credit card, including Mastercard, VISA and American Express. """ def __init__(self, *args, **kwargs): super(Stripe, self).__init__(*args, **kwargs) def build_p...
class Stripe(BasePayment):
backend_form_class = BackendStripeForm description = """ Using this payment method, you can pay using your credit card, including Mastercard, VISA and American Express. """ def __init__(self, *args, **kwargs): super(Stripe, self).__init__(*args, **kwargs) def build_payment_url(self, invoicestr...
types <b>checkout.session.completed</b>, <b>charge.refunded</b> and <b>payout.paid</b>. Copy the key from this webhook into the <i>webhook secret</i> field above.""".format( settings.SITEBASE, self.instance.id), }) class Stripe(BasePayment):
72
72
243
5
67
dlangille/pgeu-system
postgresqleu/util/payment/stripe.py
Python
Stripe
Stripe
69
97
69
69
8fa9e7ada0fef60ec376611854b0ac7c5a1635b8
bigcode/the-stack
train
dfd44ec1f340919bfcd6ef87
train
class
class BackendStripeForm(BackendInvoicePaymentMethodForm): published_key = forms.CharField(required=True, label="Publishable key") secret_key = forms.CharField(required=True, label="Secret key", widget=forms.widgets.PasswordInput(render_value=True)) webhook_secret = forms.Cha...
class BackendStripeForm(BackendInvoicePaymentMethodForm):
published_key = forms.CharField(required=True, label="Publishable key") secret_key = forms.CharField(required=True, label="Secret key", widget=forms.widgets.PasswordInput(render_value=True)) webhook_secret = forms.CharField(required=True, label="Webhook secret key", ...
from django import forms from django.conf import settings import re from postgresqleu.util.widgets import StaticTextWidget from postgresqleu.invoices.models import Invoice from postgresqleu.invoices.backendforms import BackendInvoicePaymentMethodForm from postgresqleu.accounting.util import get_account_choices from p...
109
148
495
11
97
dlangille/pgeu-system
postgresqleu/util/payment/stripe.py
Python
BackendStripeForm
BackendStripeForm
16
66
16
16
5b3c1cdaa351c47286f9aa02e9fbc9d9d3e185e4
bigcode/the-stack
train
da456ab0854a8bb271e3f46d
train
function
def mastQuery(request): server='mast.stsci.edu' # Grab Python Version version = '3.6.3' #".".join(map(str, sys.version_info[:3])) # Create Http Header Variables headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-agent":"pyt...
def mastQuery(request):
server='mast.stsci.edu' # Grab Python Version version = '3.6.3' #".".join(map(str, sys.version_info[:3])) # Create Http Header Variables headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain", "User-agent":"python-requests/"+version} ...
# Python 2.x from urllib import pathname2url as urlencode from urllib import urlretrieve try: # Python 3.x import http.client as httplib except ImportError: # Python 2.x import httplib import os def mastQuery(request):
64
64
202
5
58
christopherburke/TESS-ExoClass
code/federate_toiWtce.py
Python
mastQuery
mastQuery
29
59
29
30
642826f3cb345497e29b0c42a2647dfe7622cad1
bigcode/the-stack
train
05d335b825f01cde50592ac7
train
function
def query_othertics(ticWant, searchRad): # find the position of this tic startTime = time.time() request = {'service':'Mast.Catalogs.Filtered.Tic', \ 'params':{'columns':'*', 'filters':[{ \ 'paramName':'ID', 'values':['{:d}'.format(ticWant)]}]}, \ ...
def query_othertics(ticWant, searchRad): # find the position of this tic
startTime = time.time() request = {'service':'Mast.Catalogs.Filtered.Tic', \ 'params':{'columns':'*', 'filters':[{ \ 'paramName':'ID', 'values':['{:d}'.format(ticWant)]}]}, \ 'format':'json', 'removenullcolumns':True} while True: headers, ou...
]] bsttic = trytic[federateResult[0]] bstMatch = int(federateResult[1]) bstStat = federateResult[2] bstPeriodRatio = federateResult[3] bstPeriodRatioFlag = federateResult[4] bstFederateFlag = federateResult[5] nFed = federateResult[6] return bstpn, bsttic, bstMatch, bstStat, bstPeri...
143
143
477
23
119
christopherburke/TESS-ExoClass
code/federate_toiWtce.py
Python
query_othertics
query_othertics
79
129
79
81
70b592f20c77ac227f7cdfcc20abb8f9ea806dc2
bigcode/the-stack
train
403e54ed10455bfd06ce3319
train
function
def genericFed(per, epc, tryper, tryepc, trydur, trypn, trytic, tStart, tEnd): ts = fed.timeseries(tStart, tEnd) federateResult = fed.federateFunction(per, epc, ts, \ tryper, tryepc, trydur) bstpn = trypn[federateResult[0]] bsttic = trytic[federateResult[0]] bstMatch = int(federa...
def genericFed(per, epc, tryper, tryepc, trydur, trypn, trytic, tStart, tEnd):
ts = fed.timeseries(tStart, tEnd) federateResult = fed.federateFunction(per, epc, ts, \ tryper, tryepc, trydur) bstpn = trypn[federateResult[0]] bsttic = trytic[federateResult[0]] bstMatch = int(federateResult[1]) bstStat = federateResult[2] bstPeriodRatio = federateResul...
resp.getheaders() content = resp.read().decode('utf-8') # Close the https connection conn.close() return head,content def genericFed(per, epc, tryper, tryepc, trydur, trypn, trytic, tStart, tEnd):
64
64
198
31
32
christopherburke/TESS-ExoClass
code/federate_toiWtce.py
Python
genericFed
genericFed
63
76
63
63
ca46fd68f1f647c70c166d5f31d9d0d29af6f4a8
bigcode/the-stack
train
bca9393c2ce99a37abbdfe65
train
class
class Operator(object): """ """ z = np.zeros((3, 3)) Dx_mask = np.array([z, [ [0.0, 0.0, 0.0], [-0.5, 0.0, 0.5], [0.0, 0.0, 0.0]], z ]) Dy_mask = Dx_mask.swapaxes(1, 2) Dz_mask = Dx_mask.swapaxes(0, 2) Dxx_mask = np.array([z, [ [0, 0,...
class Operator(object):
""" """ z = np.zeros((3, 3)) Dx_mask = np.array([z, [ [0.0, 0.0, 0.0], [-0.5, 0.0, 0.5], [0.0, 0.0, 0.0]], z ]) Dy_mask = Dx_mask.swapaxes(1, 2) Dz_mask = Dx_mask.swapaxes(0, 2) Dxx_mask = np.array([z, [ [0, 0, 0], [1, -2, 1],...
""" Finite difference masks """ import logging import numpy as np from LoopStructural.utils import getLogger logger = getLogger(__name__) class Operator(object):
33
120
401
4
29
vpicavet/LoopStructural
LoopStructural/interpolators/operator.py
Python
Operator
Operator
12
50
12
12
6dc16f4b3ebbe35391a93da7f66ba989e6188af2
bigcode/the-stack
train
350c53ebd1d944dfedfe1823
train
class
class Volume_actions(extensions.ExtensionDescriptor): """Enable volume actions.""" name = "VolumeActions" alias = "os-volume-actions" updated = "2012-05-31T00:00:00+00:00" def get_controller_extensions(self): controller = VolumeActionsController() extension = extensions.ControllerE...
class Volume_actions(extensions.ExtensionDescriptor):
"""Enable volume actions.""" name = "VolumeActions" alias = "os-volume-actions" updated = "2012-05-31T00:00:00+00:00" def get_controller_extensions(self): controller = VolumeActionsController() extension = extensions.ControllerExtension(self, 'volumes', controller) return [...
': '%s'") % err_msg raise webob.exc.HTTPBadRequest(explanation=msg) update_dict = {'bootable': bootable} self.volume_api.update(context, volume, update_dict) return webob.Response(status_int=http_client.OK) class Volume_actions(extensions.ExtensionDescriptor):
64
64
83
8
56
hashsos/hashcloudos-cinder
cinder/api/contrib/volume_actions.py
Python
Volume_actions
Volume_actions
389
399
389
389
9255c5f5f649d9e32116797998939f54b385f5ce
bigcode/the-stack
train
8dff269869301bbcc0cf4ec3
train
class
class VolumeActionsController(wsgi.Controller): def __init__(self, *args, **kwargs): super(VolumeActionsController, self).__init__(*args, **kwargs) self._key_mgr = None self.volume_api = volume.API() @property def _key_manager(self): # Allows for lazy initialization of the k...
class VolumeActionsController(wsgi.Controller):
def __init__(self, *args, **kwargs): super(VolumeActionsController, self).__init__(*args, **kwargs) self._key_mgr = None self.volume_api = volume.API() @property def _key_manager(self): # Allows for lazy initialization of the key manager if self._key_mgr is None: ...
2.0 (the "License"); 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...
256
256
3,129
8
247
hashsos/hashcloudos-cinder
cinder/api/contrib/volume_actions.py
Python
VolumeActionsController
VolumeActionsController
39
386
39
39
d31d72b03b11f6a02dc2dab1000122d148c6b640
bigcode/the-stack
train
f13fbce15a074bfc56c2cd26
train
function
def generator_new(space): new_generator = instantiate(GeneratorIterator) return space.wrap(new_generator)
def generator_new(space):
new_generator = instantiate(GeneratorIterator) return space.wrap(new_generator)
return W_ReverseSeqIterObject(space, w_seq, index) def frame_new(space): new_frame = instantiate(space.FrameClass) # XXX fish return space.wrap(new_frame) def traceback_new(space): tb = instantiate(PyTraceback) return space.wrap(tb) def generator_new(space):
64
64
21
5
59
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
generator_new
generator_new
61
63
61
61
43d3fb3ed9c1dd8b9dd691d9368b7c91d4923e1e
bigcode/the-stack
train
cbb30c7a60d4830dbb0475ac
train
function
@unwrap_spec(identifier=str) def builtin_code(space, identifier): from pypy.interpreter import gateway try: return gateway.BuiltinCode.find(identifier) except KeyError: raise oefmt(space.w_RuntimeError, "cannot unpickle builtin code: %s", identifier)
@unwrap_spec(identifier=str) def builtin_code(space, identifier):
from pypy.interpreter import gateway try: return gateway.BuiltinCode.find(identifier) except KeyError: raise oefmt(space.w_RuntimeError, "cannot unpickle builtin code: %s", identifier)
) def xrangeiter_new(space, current, remaining, step): from pypy.module.__builtin__.functional import W_XRangeIterator new_iter = W_XRangeIterator(space, current, remaining, step) return space.wrap(new_iter) @unwrap_spec(identifier=str) def builtin_code(space, identifier):
64
64
61
13
51
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
builtin_code
builtin_code
71
78
71
72
cd11660c4a14e047e4a63c4871d550beaf105002
bigcode/the-stack
train
e67e41d1535bff6f9f3d251f
train
function
def traceback_new(space): tb = instantiate(PyTraceback) return space.wrap(tb)
def traceback_new(space):
tb = instantiate(PyTraceback) return space.wrap(tb)
_seq) index = space.int_w(w_index) - space.int_w(w_len) return W_ReverseSeqIterObject(space, w_seq, index) def frame_new(space): new_frame = instantiate(space.FrameClass) # XXX fish return space.wrap(new_frame) def traceback_new(space):
64
64
19
5
59
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
traceback_new
traceback_new
57
59
57
57
530fecbe4da11e37bf705baf579392b0c16893d2
bigcode/the-stack
train
041f212067a50f56ec8f3da5
train
function
def method_new(space, __args__): w_type = space.gettypeobject(Method.typedef) return space.call_args(w_type, __args__)
def method_new(space, __args__):
w_type = space.gettypeobject(Method.typedef) return space.call_args(w_type, __args__)
instantiate(Function) fu.w_func_dict = space.newdict() return space.wrap(fu) def module_new(space, w_name, w_dict): new_mod = Module(space, w_name, w_dict, add_package=False) return space.wrap(new_mod) def method_new(space, __args__):
64
64
32
9
55
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
method_new
method_new
33
35
33
33
c60f750de30b5411138a8e3f9f463422bbd6c1f6
bigcode/the-stack
train
b15bbb501c01a0057b1e213f
train
function
def cell_new(space): return space.wrap(instantiate(Cell))
def cell_new(space):
return space.wrap(instantiate(Cell))
IterObject, W_ReverseSeqIterObject #note: for now we don't use the actual value when creating the Cell. # (i.e. we assume it will be handled by __setstate__) # Stackless does use this so it might be needed here as well. def cell_new(space):
64
64
13
5
59
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
cell_new
cell_new
17
18
17
17
9e2429054d2f163a9df8902ed183a54b25c209e5
bigcode/the-stack
train
488529d0b153198fc34d0385
train
function
@unwrap_spec(identifier=str) def builtin_function(space, identifier): from pypy.interpreter import function try: return function.Function.find(identifier) except KeyError: raise oefmt(space.w_RuntimeError, "cannot unpickle builtin function: %s", identifier)
@unwrap_spec(identifier=str) def builtin_function(space, identifier):
from pypy.interpreter import function try: return function.Function.find(identifier) except KeyError: raise oefmt(space.w_RuntimeError, "cannot unpickle builtin function: %s", identifier)
, identifier): from pypy.interpreter import gateway try: return gateway.BuiltinCode.find(identifier) except KeyError: raise oefmt(space.w_RuntimeError, "cannot unpickle builtin code: %s", identifier) @unwrap_spec(identifier=str) def builtin_function(space, identifier):
64
64
59
13
51
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
builtin_function
builtin_function
80
87
80
81
85d97e5603eab96afb5c9d29cb0fe8d74b139597
bigcode/the-stack
train
51f72b954f599254029963da
train
function
def reversed_new(space, w_seq, w_remaining): from pypy.module.__builtin__.functional import _make_reversed return _make_reversed(space, w_seq, w_remaining)
def reversed_new(space, w_seq, w_remaining):
from pypy.module.__builtin__.functional import _make_reversed return _make_reversed(space, w_seq, w_remaining)
cannot unpickle builtin function: %s", identifier) def enumerate_new(space, w_iter, w_index): from pypy.module.__builtin__.functional import _make_enumerate return _make_enumerate(space, w_iter, w_index) def reversed_new(space, w_seq, w_remaining):
64
64
40
11
53
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
reversed_new
reversed_new
94
96
94
94
c5dafaba1277b3234eccf01df8de429277400e4b
bigcode/the-stack
train
4a778e56f69c435c6cda9614
train
function
def code_new(space, __args__): w_type = space.gettypeobject(PyCode.typedef) return space.call_args(w_type, __args__)
def code_new(space, __args__):
w_type = space.gettypeobject(PyCode.typedef) return space.call_args(w_type, __args__)
use the actual value when creating the Cell. # (i.e. we assume it will be handled by __setstate__) # Stackless does use this so it might be needed here as well. def cell_new(space): return space.wrap(instantiate(Cell)) def code_new(space, __args__):
64
64
33
9
55
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
code_new
code_new
20
22
20
20
e5a02134119be54d26345bad84a9be7e3fdba0bd
bigcode/the-stack
train
712107188085bdcfa783089f
train
function
def builtin_method_new(space, w_instance, w_name): return space.getattr(w_instance, w_name)
def builtin_method_new(space, w_instance, w_name):
return space.getattr(w_instance, w_name)
Module(space, w_name, w_dict, add_package=False) return space.wrap(new_mod) def method_new(space, __args__): w_type = space.gettypeobject(Method.typedef) return space.call_args(w_type, __args__) def builtin_method_new(space, w_instance, w_name):
64
64
23
12
52
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
builtin_method_new
builtin_method_new
37
38
37
37
6f333741bf0ab1c2f32e94a521f6547d7dc74c52
bigcode/the-stack
train
c52c46add3a4cae0188a26dd
train
function
def slp_from_tuple_with_nulls(space, w_tup): tup_w = space.unpackiterable(w_tup) nulls = space.unpackiterable(tup_w[0]) tup_w = tup_w[1:] for w_p in nulls: p = space.int_w(w_p) tup_w[p] = None return tup_w
def slp_from_tuple_with_nulls(space, w_tup):
tup_w = space.unpackiterable(w_tup) nulls = space.unpackiterable(tup_w[0]) tup_w = tup_w[1:] for w_p in nulls: p = space.int_w(w_p) tup_w[p] = None return tup_w
) null_num += 1 w_obj = space.w_None tup[num] = w_obj num += 1 tup[0] = space.newtuple(nulls) return space.newtuple(tup) def slp_from_tuple_with_nulls(space, w_tup):
64
64
79
14
50
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
slp_from_tuple_with_nulls
slp_from_tuple_with_nulls
124
131
124
124
1a9c8c0e7f1e5449e3d7a79fd80d45aaf97d4b4c
bigcode/the-stack
train
347cc1c0bab750c3f2280411
train
function
def seqiter_new(space, w_seq, w_index): return W_SeqIterObject(w_seq, space.int_w(w_index))
def seqiter_new(space, w_seq, w_index):
return W_SeqIterObject(w_seq, space.int_w(w_index))
w_name): return space.getattr(w_instance, w_name) def dictiter_surrogate_new(space, w_lis): # we got a listobject. # simply create an iterator and that's it. return space.iter(w_lis) def seqiter_new(space, w_seq, w_index):
64
64
28
12
52
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
seqiter_new
seqiter_new
45
46
45
45
b74144426aaebeedd0995c085d086708e3557ba6
bigcode/the-stack
train
c817dbc4d711933b1bd8829f
train
function
def enumerate_new(space, w_iter, w_index): from pypy.module.__builtin__.functional import _make_enumerate return _make_enumerate(space, w_iter, w_index)
def enumerate_new(space, w_iter, w_index):
from pypy.module.__builtin__.functional import _make_enumerate return _make_enumerate(space, w_iter, w_index)
def builtin_function(space, identifier): from pypy.interpreter import function try: return function.Function.find(identifier) except KeyError: raise oefmt(space.w_RuntimeError, "cannot unpickle builtin function: %s", identifier) def enumerate_new(space, w_iter, w_index):
64
64
42
11
53
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
enumerate_new
enumerate_new
90
92
90
90
a3f8cb8b780e5d123d322f4266773d4a2a497105
bigcode/the-stack
train
a0575b7f915d33631be522e1
train
function
def func_new(space): fu = instantiate(Function) fu.w_func_dict = space.newdict() return space.wrap(fu)
def func_new(space):
fu = instantiate(Function) fu.w_func_dict = space.newdict() return space.wrap(fu)
less does use this so it might be needed here as well. def cell_new(space): return space.wrap(instantiate(Cell)) def code_new(space, __args__): w_type = space.gettypeobject(PyCode.typedef) return space.call_args(w_type, __args__) def func_new(space):
64
64
28
5
59
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
func_new
func_new
24
27
24
24
b1611dc00b0c05c8d1b49883faf55e785b9edc64
bigcode/the-stack
train
80baeb42ee59661912f444d2
train
function
def reverseseqiter_new(space, w_seq, w_index): w_len = space.len(w_seq) index = space.int_w(w_index) - space.int_w(w_len) return W_ReverseSeqIterObject(space, w_seq, index)
def reverseseqiter_new(space, w_seq, w_index):
w_len = space.len(w_seq) index = space.int_w(w_index) - space.int_w(w_len) return W_ReverseSeqIterObject(space, w_seq, index)
a listobject. # simply create an iterator and that's it. return space.iter(w_lis) def seqiter_new(space, w_seq, w_index): return W_SeqIterObject(w_seq, space.int_w(w_index)) def reverseseqiter_new(space, w_seq, w_index):
64
64
54
14
50
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
reverseseqiter_new
reverseseqiter_new
48
51
48
48
a2f0fb2f72f505b3a90ad8cfc5cf3e0ee08fa416
bigcode/the-stack
train
76ac7b8c8f3201185b386917
train
function
def dictiter_surrogate_new(space, w_lis): # we got a listobject. # simply create an iterator and that's it. return space.iter(w_lis)
def dictiter_surrogate_new(space, w_lis): # we got a listobject. # simply create an iterator and that's it.
return space.iter(w_lis)
return space.call_args(w_type, __args__) def builtin_method_new(space, w_instance, w_name): return space.getattr(w_instance, w_name) def dictiter_surrogate_new(space, w_lis): # we got a listobject. # simply create an iterator and that's it.
64
64
38
30
34
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
dictiter_surrogate_new
dictiter_surrogate_new
40
43
40
42
4621919cec7cecdbb8df0743f2aeadce7f5ef05c
bigcode/the-stack
train
1c9f08dc72c8b3dc956b50b5
train
function
def frame_new(space): new_frame = instantiate(space.FrameClass) # XXX fish return space.wrap(new_frame)
def frame_new(space):
new_frame = instantiate(space.FrameClass) # XXX fish return space.wrap(new_frame)
.int_w(w_index)) def reverseseqiter_new(space, w_seq, w_index): w_len = space.len(w_seq) index = space.int_w(w_index) - space.int_w(w_len) return W_ReverseSeqIterObject(space, w_seq, index) def frame_new(space):
64
64
26
5
59
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
frame_new
frame_new
53
55
53
53
d99dd3cafa4857b92f54804f0af74bfd989fa732
bigcode/the-stack
train
787dc3b0c27ba1e809a61e18
train
function
def module_new(space, w_name, w_dict): new_mod = Module(space, w_name, w_dict, add_package=False) return space.wrap(new_mod)
def module_new(space, w_name, w_dict):
new_mod = Module(space, w_name, w_dict, add_package=False) return space.wrap(new_mod)
): w_type = space.gettypeobject(PyCode.typedef) return space.call_args(w_type, __args__) def func_new(space): fu = instantiate(Function) fu.w_func_dict = space.newdict() return space.wrap(fu) def module_new(space, w_name, w_dict):
64
64
35
11
53
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
module_new
module_new
29
31
29
29
d5dd63beb4ea18e19aa8e9f4296f930e73f4da15
bigcode/the-stack
train
94109ca851806210217eca72
train
function
def slp_into_tuple_with_nulls(space, seq_w): """ create a tuple with the object and store a tuple with the positions of NULLs as first element. """ tup = [None] * (len(seq_w) + 1) w = space.wrap num = 1 nulls = [None for i in seq_w if i is None] null_num = 0 for w_obj in seq_w: ...
def slp_into_tuple_with_nulls(space, seq_w):
""" create a tuple with the object and store a tuple with the positions of NULLs as first element. """ tup = [None] * (len(seq_w) + 1) w = space.wrap num = 1 nulls = [None for i in seq_w if i is None] null_num = 0 for w_obj in seq_w: if w_obj is None: nulls[nu...
ypy.module.__builtin__.functional import _make_reversed return _make_reversed(space, w_seq, w_remaining) # ___________________________________________________________________ # Helper functions for internal use # adopted from prickelpit.c (but almost completely different) def slp_into_tuple_with_nulls(space, se...
64
64
169
13
51
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
slp_into_tuple_with_nulls
slp_into_tuple_with_nulls
104
122
104
104
f61fd33bbff8d6eec7615b61b243049bc9e4e70d
bigcode/the-stack
train
da42a7b32628a8eaf8ba6ed6
train
function
@unwrap_spec(current=int, remaining=int, step=int) def xrangeiter_new(space, current, remaining, step): from pypy.module.__builtin__.functional import W_XRangeIterator new_iter = W_XRangeIterator(space, current, remaining, step) return space.wrap(new_iter)
@unwrap_spec(current=int, remaining=int, step=int) def xrangeiter_new(space, current, remaining, step):
from pypy.module.__builtin__.functional import W_XRangeIterator new_iter = W_XRangeIterator(space, current, remaining, step) return space.wrap(new_iter)
def traceback_new(space): tb = instantiate(PyTraceback) return space.wrap(tb) def generator_new(space): new_generator = instantiate(GeneratorIterator) return space.wrap(new_generator) @unwrap_spec(current=int, remaining=int, step=int) def xrangeiter_new(space, current, remaining, step):
64
64
62
24
40
microvm/pypy-mu
pypy/module/_pickle_support/maker.py
Python
xrangeiter_new
xrangeiter_new
65
69
65
66
86fc57dd24da7a282c964eaef693d58d33d6d841
bigcode/the-stack
train
1569507e0fcfb88f76c54510
train
function
def min_number_of_coins(n, denoms): min_change = [float('inf') for i in range(n+1)] min_change[0] = 0 for coin in denoms: for amount in range(1, n+1): if coin <= amount: cur_min = min(min_change[amount], 1 + min_change[amount - coin]) min_change[amount...
def min_number_of_coins(n, denoms):
min_change = [float('inf') for i in range(n+1)] min_change[0] = 0 for coin in denoms: for amount in range(1, n+1): if coin <= amount: cur_min = min(min_change[amount], 1 + min_change[amount - coin]) min_change[amount] = cur_min ret...
the smallest number of coins needed to make change for that target amount using the given coin denominations. Nonte that an unlimited amount of coins is at your disposal. If it is impossible to make change for the target amount, return -1. """ def min_number_of_coins(n, denoms):
64
64
116
11
53
Surbeivol/daily-coding-problems
solutions/min_number_coins.py
Python
min_number_of_coins
min_number_of_coins
12
21
12
12
b41ed909d0f8ce9b420938967343c826baa9c01a
bigcode/the-stack
train
7a9aa073bccc3bb33aacb960
train
class
class Terminal(object): def __init__(self, node, name, io, optional=False, multi=False, pos=None, renamable=False, removable=False, multiable=False, bypass=None): """ Construct a new terminal. ============== =========================================================================...
class Terminal(object):
def __init__(self, node, name, io, optional=False, multi=False, pos=None, renamable=False, removable=False, multiable=False, bypass=None): """ Construct a new terminal. ============== ================================================================================= **Argum...
# -*- coding: utf-8 -*- from ..Qt import QtCore, QtGui, QtWidgets import weakref from ..graphicsItems.GraphicsObject import GraphicsObject from .. import functions as fn from ..Point import Point translate = QtCore.QCoreApplication.translate class Terminal(object):
61
256
2,164
4
56
marsipu/pyqtgraph
pyqtgraph/flowchart/Terminal.py
Python
Terminal
Terminal
10
275
10
10
51a076715447e3c22b1c7ed271598acb4edd3082
bigcode/the-stack
train
17ef7dcbfac8ba5de0fea320
train
class
class ConnectionItem(GraphicsObject): def __init__(self, source, target=None): GraphicsObject.__init__(self) self.setFlags( self.GraphicsItemFlag.ItemIsSelectable | self.GraphicsItemFlag.ItemIsFocusable ) self.source = source self.target = target...
class ConnectionItem(GraphicsObject):
def __init__(self, source, target=None): GraphicsObject.__init__(self) self.setFlags( self.GraphicsItemFlag.ItemIsSelectable | self.GraphicsItemFlag.ItemIsFocusable ) self.source = source self.target = target self.length = 0 self.hover...
self.term.connectTo(i.term, self.newConnection) gotTarget = True except: self.scene().removeItem(self.newConnection) self.newConnection = None raise ...
256
256
878
7
249
marsipu/pyqtgraph
pyqtgraph/flowchart/Terminal.py
Python
ConnectionItem
ConnectionItem
458
581
458
459
7e276fae55b97b28fa1b465f40b19856f6be1fab
bigcode/the-stack
train
6a97a2ba5eb900764f8a9e69
train
class
class TerminalGraphicsItem(GraphicsObject): def __init__(self, term, parent=None): self.term = term GraphicsObject.__init__(self, parent) self.brush = fn.mkBrush(0,0,0) self.box = QtGui.QGraphicsRectItem(0, 0, 10, 10, self) on_update = self.labelChanged if self.term.isRe...
class TerminalGraphicsItem(GraphicsObject):
def __init__(self, term, parent=None): self.term = term GraphicsObject.__init__(self, parent) self.brush = fn.mkBrush(0,0,0) self.box = QtGui.QGraphicsRectItem(0, 0, 10, 10, self) on_update = self.labelChanged if self.term.isRenamable() else None self.label = TextItem...
State(self): return {'io': self._io, 'multi': self._multi, 'optional': self._optional, 'renamable': self._renamable, 'removable': self._removable, 'multiable': self._multiable} def __lt__(self, other): """When the terminal is multi value, the data passed to the DatTreeWidget for each input or outpu...
256
256
1,320
8
248
marsipu/pyqtgraph
pyqtgraph/flowchart/Terminal.py
Python
TerminalGraphicsItem
TerminalGraphicsItem
296
455
296
297
80971f31de5ffd2b28d6806d33f64408eeb8dfee
bigcode/the-stack
train
3f372d7fbc2168f6b285518b
train
class
class TextItem(QtWidgets.QGraphicsTextItem): def __init__(self, text, parent, on_update): super().__init__(text, parent) self.on_update = on_update def focusOutEvent(self, ev): super().focusOutEvent(ev) if self.on_update is not None: self.on_update() def keyPres...
class TextItem(QtWidgets.QGraphicsTextItem):
def __init__(self, text, parent, on_update): super().__init__(text, parent) self.on_update = on_update def focusOutEvent(self, ev): super().focusOutEvent(ev) if self.on_update is not None: self.on_update() def keyPressEvent(self, ev): if ev.key() == QtCo...
): """When the terminal is multi value, the data passed to the DatTreeWidget for each input or output, is {Terminal: value}. To make this sortable, we provide the < operator. """ return self._name < other._name class TextItem(QtWidgets.QGraphicsTextItem):
64
64
131
10
53
marsipu/pyqtgraph
pyqtgraph/flowchart/Terminal.py
Python
TextItem
TextItem
278
293
278
278
205c05316cafa8085e65bf7b732e3a30b67f7f69
bigcode/the-stack
train
c24a1d87a8bfaeb63264532f
train
function
def main(): from litex.soc.integration.soc import LiteXSoCArgumentParser parser = LiteXSoCArgumentParser(description="LiteX SoC on Colorlight i5") target_group = parser.add_argument_group(title="Target options") target_group.add_argument("--build", action="store_true", help="Build bitstr...
def main():
from litex.soc.integration.soc import LiteXSoCArgumentParser parser = LiteXSoCArgumentParser(description="LiteX SoC on Colorlight i5") target_group = parser.add_argument_group(title="Target options") target_group.add_argument("--build", action="store_true", help="Build bitstream.") t...
phy = self.sdrphy, module = IS42S16160(sys_clk_freq, sdram_rate), l2_cache_size = kwargs.get("l2_size", 8192) ) # Video ------------------------------------------------------------------------------------ if with_video_termina...
161
162
543
3
158
chmousset/litex-boards
litex_boards/targets/muselab_icesugar_pro.py
Python
main
main
132
173
132
132
b339ca269b3ea5d7c75af95415f6731ddc62863d
bigcode/the-stack
train
d71ea9601d7eea3c958a17fd
train
class
class _CRG(Module): def __init__(self, platform, sys_clk_freq, use_internal_osc=False, with_video_pll=False, sdram_rate="1:1"): self.rst = Signal() self.clock_domains.cd_sys = ClockDomain() if sdram_rate == "1:2": self.clock_domains.cd_sys2x = ClockDomain() self...
class _CRG(Module):
def __init__(self, platform, sys_clk_freq, use_internal_osc=False, with_video_pll=False, sdram_rate="1:1"): self.rst = Signal() self.clock_domains.cd_sys = ClockDomain() if sdram_rate == "1:2": self.clock_domains.cd_sys2x = ClockDomain() self.clock_domains.cd_sy...
from litex_boards.platforms import muselab_icesugar_pro from litex.build.lattice.trellis import trellis_args, trellis_argdict from litex.soc.cores.clock import * from litex.soc.integration.soc_core import * from litex.soc.integration.builder import * from litex.soc.cores.video import VideoHDMIPHY from litex.soc.cor...
167
167
557
6
161
chmousset/litex-boards
litex_boards/targets/muselab_icesugar_pro.py
Python
_CRG
_CRG
32
82
32
32
6c556536f92d2f1e22901ca2ae531219826a6d6e
bigcode/the-stack
train
d99c8b9c12d9b74c369b632f
train
class
class BaseSoC(SoCCore): def __init__(self, sys_clk_freq=60e6, with_led_chaser=True, with_spi_flash=False, use_internal_osc=False, sdram_rate="1:1", with_video_terminal=False, with_video_framebuffer=False, **kwargs): platform = muselab_icesugar_pro.Platform() # SoCC...
class BaseSoC(SoCCore):
def __init__(self, sys_clk_freq=60e6, with_led_chaser=True, with_spi_flash=False, use_internal_osc=False, sdram_rate="1:1", with_video_terminal=False, with_video_framebuffer=False, **kwargs): platform = muselab_icesugar_pro.Platform() # SoCCore --------------------...
video_pll.register_clkin(clk, clk_freq) self.clock_domains.cd_hdmi = ClockDomain() self.clock_domains.cd_hdmi5x = ClockDomain() video_pll.create_clkout(self.cd_hdmi, 40e6, margin=0) video_pll.create_clkout(self.cd_hdmi5x, 200e6, margin=0) # SDRAM...
157
157
525
9
148
chmousset/litex-boards
litex_boards/targets/muselab_icesugar_pro.py
Python
BaseSoC
BaseSoC
86
128
86
86
d459234639678824240f3cd134aa89187feda880
bigcode/the-stack
train
a6af45180845cc982f69fd6b
train
class
class Migration(migrations.Migration): dependencies = [ ('bot', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='contact_us', name='date', ), ]
class Migration(migrations.Migration):
dependencies = [ ('bot', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='contact_us', name='date', ), ]
# Generated by Django 2.0.5 on 2018-07-21 10:15 from django.db import migrations class Migration(migrations.Migration):
36
64
47
7
28
amanparmar17/its_our_earth
bot/migrations/0002_remove_contact_us_date.py
Python
Migration
Migration
6
17
6
7
3474d965318dc0abb2cc2fe5b963833ddbdbb611
bigcode/the-stack
train
66e6933c9e376f353589454e
train
class
class RunMainTest(testbase.WarnTestBase): def __setup(self, enable): style.SetGlobalStyle( style.CreateStyleFromConfig( f'{{based_on_style: pep8, ' f'should_not_have_wildcard_imports: {enable}}}')) unformatted_code = textwrap.dedent("""\ ...
class RunMainTest(testbase.WarnTestBase):
def __setup(self, enable): style.SetGlobalStyle( style.CreateStyleFromConfig( f'{{based_on_style: pep8, ' f'should_not_have_wildcard_imports: {enable}}}')) unformatted_code = textwrap.dedent("""\ #!/usr/bin/env python ...
09:40 Created """ import sys import textwrap from yapf.yapflib import style, reformatter from yapf.yapflib.warnings import warnings_utils from yapf.yapflib.yapf_api import FormatCode from yapftests.huawei.options import testbase class RunMainTest(testbase.WarnTestBase):
75
75
252
10
64
akuleshov7/huawei-yapf
yapftests/huawei/options/should_not_have_wildcard_imports_test.py
Python
RunMainTest
RunMainTest
16
49
16
17
3964e9f506ad667525ca402cfc0f71274e7f5618
bigcode/the-stack
train
6b34ddbd644bcffb6d32a1e6
train
function
def test_intent_classifier_logreg(kwik_e_mart_app_path): nlp = NaturalLanguageProcessor(app_path=kwik_e_mart_app_path) features = { 'bag-of-words': {'lengths': [1]}, 'freq': {'bins': 5}, 'in-gaz': {}, 'length': {} } ic = nlp.domains['store_info'].intent_classifier ic....
def test_intent_classifier_logreg(kwik_e_mart_app_path):
nlp = NaturalLanguageProcessor(app_path=kwik_e_mart_app_path) features = { 'bag-of-words': {'lengths': [1]}, 'freq': {'bins': 5}, 'in-gaz': {}, 'length': {} } ic = nlp.domains['store_info'].intent_classifier ic.fit(model_settings={'classifier_type': 'logreg'}, ...
': 'k-fold', 'k': 10 } ic = nlp.domains['store_info'].intent_classifier ic.fit(model_settings={'classifier_type': 'svm'}, param_selection=param_selection_settings) def test_intent_classifier_logreg(kwik_e_mart_app_path):
64
64
171
16
48
jre21/mindmeld
tests/components/test_intent_classifier.py
Python
test_intent_classifier_logreg
test_intent_classifier_logreg
21
39
21
21
cee6d1fac521b30ff94f2beb0f81888f51e460c5
bigcode/the-stack
train
b870384b0c503d8caeadd17b
train
function
def test_intent_classifier_svm(kwik_e_mart_app_path): nlp = NaturalLanguageProcessor(app_path=kwik_e_mart_app_path) search_grid = { 'C': [0.1, 0.5, 1, 5, 10, 50, 100, 1000, 5000], 'kernel': ['linear', 'rbf', 'poly'], } param_selection_settings = { 'grid': search_grid, 'typ...
def test_intent_classifier_svm(kwik_e_mart_app_path):
nlp = NaturalLanguageProcessor(app_path=kwik_e_mart_app_path) search_grid = { 'C': [0.1, 0.5, 1, 5, 10, 50, 100, 1000, 5000], 'kernel': ['linear', 'rbf', 'poly'], } param_selection_settings = { 'grid': search_grid, 'type': 'k-fold', 'k': 10 } ic = nlp.domai...
from mindmeld.components.nlp import NaturalLanguageProcessor from unittest.mock import patch def test_intent_classifier_svm(kwik_e_mart_app_path):
33
64
156
16
16
jre21/mindmeld
tests/components/test_intent_classifier.py
Python
test_intent_classifier_svm
test_intent_classifier_svm
5
18
5
5
cfd62e46f1fb006598fb5e044c65fb2def1f6cb3
bigcode/the-stack
train
808cc5de41a3e70942a1d2b3
train
function
def test_intent_classifier_random_forest(kwik_e_mart_app_path, caplog): nlp = NaturalLanguageProcessor(app_path=kwik_e_mart_app_path) search_grid = { 'n_estimators': [5, 10, 15, 20], 'criterion': ['gini', 'entropy'], 'warm_start': [True, False], } param_selection_settings = { ...
def test_intent_classifier_random_forest(kwik_e_mart_app_path, caplog):
nlp = NaturalLanguageProcessor(app_path=kwik_e_mart_app_path) search_grid = { 'n_estimators': [5, 10, 15, 20], 'criterion': ['gini', 'entropy'], 'warm_start': [True, False], } param_selection_settings = { 'grid': search_grid, 'type': 'k-fold', 'k': 10 ...
'logreg'}, features=features) features = { 'bag-of-words': {'lengths': [1, 2]}, 'freq': {'bins': 5}, 'in-gaz': {}, 'length': {} } ic.fit(model_settings={'classifier_type': 'logreg'}, features=features) def test_intent_classifier_random_forest(kwik_e_mar...
92
92
309
20
72
jre21/mindmeld
tests/components/test_intent_classifier.py
Python
test_intent_classifier_random_forest
test_intent_classifier_random_forest
42
72
42
42
b888db0a8cc0200b119d0fc8cef480f12dcde8bf
bigcode/the-stack
train
8384666ca9b69f0a2faf09c4
train
class
class Command(BaseCsvStationsCsvAddressesImporter): council_id = "E06000057" addresses_name = "mayor.2019-05-02/Version 1/MAYORAL DATA.csv" stations_name = "mayor.2019-05-02/Version 1/MAYORAL DATA.csv" elections = ["mayor.2019-05-02"] csv_delimiter = "," def get_station_hash(self, record): ...
class Command(BaseCsvStationsCsvAddressesImporter):
council_id = "E06000057" addresses_name = "mayor.2019-05-02/Version 1/MAYORAL DATA.csv" stations_name = "mayor.2019-05-02/Version 1/MAYORAL DATA.csv" elections = ["mayor.2019-05-02"] csv_delimiter = "," def get_station_hash(self, record): return "-".join([record.col1.strip()]) def ...
from uk_geo_utils.helpers import Postcode from data_collection.base_importers import BaseCsvStationsCsvAddressesImporter from data_finder.helpers import geocode_point_only, PostcodeError from data_collection.addresshelpers import ( format_residential_address, format_polling_station_address, ) class Command(Base...
68
119
398
9
59
mtravis/UK-Polling-Stations
polling_stations/apps/data_collection/management/commands/import_northumberland.py
Python
Command
Command
10
71
10
10
4c23fbb7f7b03278dbcfeb760545d3cb8e74b292
bigcode/the-stack
train
d5a654fbcf22c65b4265eb0f
train
class
class FirmataLight(FirmataPinEntity, LightEntity): """Representation of a light on a Firmata board.""" def __init__( self, api: FirmataBoardPin, config_entry: ConfigEntry, name: str, pin: FirmataPinType, ) -> None: """Initialize the light pin entity.""" ...
class FirmataLight(FirmataPinEntity, LightEntity):
"""Representation of a light on a Firmata board.""" def __init__( self, api: FirmataBoardPin, config_entry: ConfigEntry, name: str, pin: FirmataPinType, ) -> None: """Initialize the light pin entity.""" super().__init__(api, config_entry, name, pin) ...
except FirmataPinUsedException: _LOGGER.error( "Could not setup light on pin %s since pin already in use", light[CONF_PIN], ) continue name = light[CONF_NAME] light_entity = FirmataLight(api, config_entry, name, pin) new...
96
96
322
13
83
MrDelik/core
homeassistant/components/firmata/light.py
Python
FirmataLight
FirmataLight
56
101
56
56
a6d72f75c94f8f41fe3b055318b44d9f2e3b985c
bigcode/the-stack
train
bbea2badfb12b6bee0ac61d1
train
function
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Firmata lights.""" new_entities = [] board = hass.data[DOMAIN][config_entry.entry_id] for light in board.lights: pin = light[CONF_PIN] ...
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None:
"""Set up the Firmata lights.""" new_entities = [] board = hass.data[DOMAIN][config_entry.entry_id] for light in board.lights: pin = light[CONF_PIN] pin_mode = light[CONF_PIN_MODE] initial = light[CONF_INITIAL_STATE] minimum = light[CONF_MINIMUM] maximum = light[...
FirmataPinEntity from .pin import FirmataBoardPin, FirmataPinUsedException, FirmataPWMOutput _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None:
66
66
222
32
34
MrDelik/core
homeassistant/components/firmata/light.py
Python
async_setup_entry
async_setup_entry
24
53
24
28
f2ec39ae3d70837c0e8ae017fc1b9a793c04e2cf
bigcode/the-stack
train
d99c6c04f463c93157da9c6b
train
class
class TestTimedeltaIndex(tm.TestCase): _multiprocess_can_split_ = True def test_pass_TimedeltaIndex_to_index(self): rng = timedelta_range('1 days','10 days') idx = Index(rng, dtype=object) expected = Index(rng.to_pytimedelta(), dtype=object) self.assert_numpy_array_equal(idx....
class TestTimedeltaIndex(tm.TestCase):
_multiprocess_can_split_ = True def test_pass_TimedeltaIndex_to_index(self): rng = timedelta_range('1 days','10 days') idx = Index(rng, dtype=object) expected = Index(rng.to_pytimedelta(), dtype=object) self.assert_numpy_array_equal(idx.values, expected.values) def test_...
# NaT is datetime, not timedelta assert_frame_equal(actual, dfn) actual = df1 - pd.NaT assert_frame_equal(actual, dfn) def test_apply_to_timedelta(self): timedelta_NaT = pd.to_timedelta('NaT') list_of_valid_strings = ['00:00:01', '00:00:02'] a = pd.to_timedelta(li...
256
256
5,186
9
247
pjkundert/wikienergy
disaggregator/build/pandas/pandas/tseries/tests/test_timedeltas.py
Python
TestTimedeltaIndex
TestTimedeltaIndex
781
1,302
781
781
4b4c69cbf060d36a801a24604421e51b321cbf65
bigcode/the-stack
train
e2a5f4380dfb1e94e9e45246
train
class
class TestTimedeltas(tm.TestCase): _multiprocess_can_split_ = True def setUp(self): pass def test_construction(self): expected = np.timedelta64(10,'D').astype('m8[ns]').view('i8') self.assertEqual(Timedelta(10,unit='d').value, expected) self.assertEqual(Timedelta(10.0,unit...
class TestTimedeltas(tm.TestCase):
_multiprocess_can_split_ = True def setUp(self): pass def test_construction(self): expected = np.timedelta64(10,'D').astype('m8[ns]').view('i8') self.assertEqual(Timedelta(10,unit='d').value, expected) self.assertEqual(Timedelta(10.0,unit='d').value, expected) self...
# pylint: disable-msg=E1101,W0612 from __future__ import division from datetime import datetime, timedelta, time import nose from distutils.version import LooseVersion import numpy as np import pandas as pd from pandas import (Index, Series, DataFrame, Timestamp, Timedelta, TimedeltaIndex, isnull, notnull, ...
243
256
8,418
8
234
pjkundert/wikienergy
disaggregator/build/pandas/pandas/tseries/tests/test_timedeltas.py
Python
TestTimedeltas
TestTimedeltas
29
779
29
29
653dac98855d836ce74d34dd33bafbfc3e46a3af
bigcode/the-stack
train
2e7b115cab9ae056cc68115b
train
class
class TestSlicing(tm.TestCase): def test_partial_slice(self): rng = timedelta_range('1 day 10:11:12', freq='h',periods=500) s = Series(np.arange(len(rng)), index=rng) result = s['5 day':'6 day'] expected = s.iloc[86:134] assert_series_equal(result, expected) result...
class TestSlicing(tm.TestCase):
def test_partial_slice(self): rng = timedelta_range('1 day 10:11:12', freq='h',periods=500) s = Series(np.arange(len(rng)), index=rng) result = s['5 day':'6 day'] expected = s.iloc[86:134] assert_series_equal(result, expected) result = s['5 day':] expected =...
kind) self.assertIs(index, joined) def test_factorize(self): idx1 = TimedeltaIndex(['1 day','1 day','2 day', '2 day','3 day','3 day']) exp_arr = np.array([0, 0, 1, 1, 2, 2]) exp_idx = TimedeltaIndex(['1 day','2 day','3 day']) arr, idx = i...
231
231
770
8
223
pjkundert/wikienergy
disaggregator/build/pandas/pandas/tseries/tests/test_timedeltas.py
Python
TestSlicing
TestSlicing
1,304
1,375
1,304
1,305
72a8c692dfd315c624a078456c7ba18ba550bdd9
bigcode/the-stack
train
83236203923244da591eb6f1
train
class
class TestCitiBuy: """Tests the CitiBuy class""" def test_init(self, test_citibuy): """Tests that the mock CitiBuy db was populated correctly""" # setup query = "SELECT TOP 5 PO_NBR, RELEASE_NBR FROM PO_HEADER" # execution results = test_citibuy.execute_stmt(query) ...
class TestCitiBuy:
"""Tests the CitiBuy class""" def test_init(self, test_citibuy): """Tests that the mock CitiBuy db was populated correctly""" # setup query = "SELECT TOP 5 PO_NBR, RELEASE_NBR FROM PO_HEADER" # execution results = test_citibuy.execute_stmt(query) print(results.re...
import pytest import sqlalchemy from dgs_fiscal.systems import CitiBuy @pytest.fixture(scope="session", name="test_citibuy") def fixture_citibuy(): """Creates an instance of the CitiBuy class for integration testing""" return CitiBuy() class TestCitiBuy:
63
64
119
6
57
department-of-general-services/priority-vendor-aging-report
app/tests/integration_tests/citibuy/test_client.py
Python
TestCitiBuy
TestCitiBuy
13
26
13
13
639d18a3465e9dca6d90f2ff2eb3f9ad6d5802bb
bigcode/the-stack
train