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
fd00e32474199431e3536217
train
function
def reverse_dict(D): return {v: k for k, v in D.items()}
def reverse_dict(D):
return {v: k for k, v in D.items()}
ij, jk in zip(self.ree, feed_input)} self.purity = purity self.recovery = recovery self.target_rees = target # -- end class ##################################################################################################### #------------------------------HELPER FUNCTIONS...
64
64
18
5
58
solventx/solventx
solventx/solventx.py
Python
reverse_dict
reverse_dict
469
470
469
469
5b0aa6701f6ae521c9753edfe9eccc923e8e5227
bigcode/the-stack
train
d1136118ebc96b30df0c178b
train
function
def flatten(iter): if type(iter) == dict: return np.array(list(iter.values())).reshape(1, -1)[0] elif type(iter) == list: return np.array(iter).reshape(1, -1)[0]
def flatten(iter):
if type(iter) == dict: return np.array(list(iter.values())).reshape(1, -1)[0] elif type(iter) == list: return np.array(iter).reshape(1, -1)[0]
y[count:count+nsy] = [obj.mix.species_moles[obj.canteranames.index(ij)] for ij in obj.canteravars] # # update aq and org variable vector count += nsy return yI-y def flatten(iter):
63
64
52
4
58
solventx/solventx
solventx/solventx.py
Python
flatten
flatten
639
643
639
639
033480797982ee16d19423b44011777e49a238d1
bigcode/the-stack
train
cb3e8830cded50430639dd52
train
function
def get_next(item_num, dir): ''' returns next node number in tree in dir specified 0 level: 0 / \ 1 2 1 / \ / \ 3 4 5 6 2 get_next(2, 'left') => 5 get_next(1, 'right') => 4 ''' item_num = int(item_num) level, po...
def get_next(item_num, dir):
''' returns next node number in tree in dir specified 0 level: 0 / \ 1 2 1 / \ / \ 3 4 5 6 2 get_next(2, 'left') => 5 get_next(1, 'right') => 4 ''' item_num = int(item_num) level, pos = get_level(item_num) n...
name, num = var.split('-') if name == 'Scrub': return None else: child = get_next(num,name) if str(child) in mod_nums: return 'Extraction-'+str(child) else: return None def get_next(item_num, dir):
63
64
166
8
54
solventx/solventx
solventx/solventx.py
Python
get_next
get_next
527
545
527
527
2707b8f08063475c22c4465f9ce950cb5ee4936f
bigcode/the-stack
train
f56c1d71bf5ea7908a2e6b08
train
class
class Adam(Optimizer): r"""Implements Adam algorithm. It has been proposed in `Adam\: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) ...
class Adam(Optimizer):
r"""Implements Adam algorithm. It has been proposed in `Adam\: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[floa...
import math import torch from .optimizer import Optimizer class Adam(Optimizer):
18
256
1,190
5
12
wangxiaodong1021/HCC_Prognostic
optim/adam.py
Python
Adam
Adam
6
114
6
6
26fdaedee07b8cba609f13c479f4f6a221d75b28
bigcode/the-stack
train
379f5a0dd417278ea94f9acb
train
class
class Graph: def __init__(self,total): self.adj = defaultdict(list) self.totalNodes = total def addEdge(self, x, y): self.adj[x].append(y)
class Graph:
def __init__(self,total): self.adj = defaultdict(list) self.totalNodes = total def addEdge(self, x, y): self.adj[x].append(y)
from collections import defaultdict class Graph:
8
64
45
3
4
pritsheth/Algorithms-Python
GraphAlgorithms/TopologicalSort.py
Python
Graph
Graph
4
10
4
4
b19d0ad1f2b7c76555de17ca7341d69570197dbf
bigcode/the-stack
train
9dd253756374c40ab0f03584
train
function
@login_required @permission_required('django_export_celery.view_exportjob', raise_exception=True) @require_http_methods(["GET"]) def download_file(request, *args, **kwargs): pk = kwargs.get('pk') try: job = ExportJob.objects.get(pk=pk) if job.file: filename = job.file.name.split('/')...
@login_required @permission_required('django_export_celery.view_exportjob', raise_exception=True) @require_http_methods(["GET"]) def download_file(request, *args, **kwargs):
pk = kwargs.get('pk') try: job = ExportJob.objects.get(pk=pk) if job.file: filename = job.file.name.split('/')[-1] response = HttpResponse(job.file, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % filename ...
permission_required from django.views.decorators.http import require_http_methods from django.contrib import messages from .models import ExportJob @login_required @permission_required('django_export_celery.view_exportjob', raise_exception=True) @require_http_methods(["GET"]) def download_file(request, *args, **kwarg...
64
64
150
38
25
mrtoffou/django-export-celery
src/django_export_celery/views.py
Python
download_file
download_file
10
25
10
13
37b32c850facb388b28e2f6f0e8b2813b3ac1504
bigcode/the-stack
train
52e0a3dc04f0f005fff351c2
train
function
def test_async_handler_returning_none(): app = create_app(asgi=True) class SimpleHandler(media.BaseHandler): def serialize(self, media, content_type): return json.dumps(media).encode() def deserialize(self, stream, content_type, content_length): return None handler...
def test_async_handler_returning_none():
app = create_app(asgi=True) class SimpleHandler(media.BaseHandler): def serialize(self, media, content_type): return json.dumps(media).encode() def deserialize(self, stream, content_type, content_length): return None handlers = media.Handlers({'application/json': S...
resp.media = await req.get_media() app.add_route('/', ResourceAsync()) doc = {'event': 'serialized'} result = testing.simulate_post(app, '/', json=doc) assert result.status_code == 200 assert result.json == doc def test_async_handler_returning_none():
64
64
168
8
55
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
test_async_handler_returning_none
test_async_handler_returning_none
229
252
229
229
5b2794d3878d13553e597246fa1aa321a05e57ca
bigcode/the-stack
train
365b4308a4964a6d88298752
train
function
def test_deserialization_raises(asgi): app = create_app(asgi) class SuchException(Exception): pass class FaultyHandler(media.BaseHandler): def deserialize(self, stream, content_type, content_length): raise SuchException('Wow such error.') def deserialize_async(self, st...
def test_deserialization_raises(asgi):
app = create_app(asgi) class SuchException(Exception): pass class FaultyHandler(media.BaseHandler): def deserialize(self, stream, content_type, content_length): raise SuchException('Wow such error.') def deserialize_async(self, stream, content_type, content_length): ...
= ['application/javacript', len(body)] if asgi: if not ASGI_SUPPORTED: pytest.skip('ASGI requires Python 3.6+') from falcon.asgi.stream import BoundedStream s = BoundedStream(testing.ASGIRequestEventEmitter(body)) args.insert(0, s) result = falcon.async_to_sy...
125
125
419
9
115
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
test_deserialization_raises
test_deserialization_raises
113
166
113
113
bb52f342595f56bac356eba8cbcd065c79a3382b
bigcode/the-stack
train
e00bf2544fee1a9d6b6c5340
train
function
def test_async_methods_not_overridden(): app = create_app(asgi=True) class SimpleHandler(media.BaseHandler): def serialize(self, media, content_type): return json.dumps(media).encode() def deserialize(self, stream, content_type, content_length): return json.load(stream)...
def test_async_methods_not_overridden():
app = create_app(asgi=True) class SimpleHandler(media.BaseHandler): def serialize(self, media, content_type): return json.dumps(media).encode() def deserialize(self, stream, content_type, content_length): return json.load(stream) handlers = media.Handlers({'applica...
result = testing.simulate_get(app, '/', headers={'Accept': 'text/xml'}) assert result.status_code == 500 result = testing.simulate_post(app, '/', json={}, headers={'Accept': 'text/xml'}) assert result.status_code == 500 def test_async_methods_not_overridden():
64
64
167
8
55
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
test_async_methods_not_overridden
test_async_methods_not_overridden
203
226
203
203
04894613c078a645e39f292f83b5ef7ec07c88a9
bigcode/the-stack
train
f70af26f82bbab995b226815
train
function
@pytest.mark.parametrize('func, body, expected', SERIALIZATION_PARAM_LIST) def test_serialization(asgi, func, body, expected): handler = media.JSONHandler(dumps=func) args = (body, b'application/javacript') if asgi: result = falcon.async_to_sync(handler.serialize_async, *args) else: re...
@pytest.mark.parametrize('func, body, expected', SERIALIZATION_PARAM_LIST) def test_serialization(asgi, func, body, expected):
handler = media.JSONHandler(dumps=func) args = (body, b'application/javacript') if asgi: result = falcon.async_to_sync(handler.serialize_async, *args) else: result = handler.serialize(*args) # NOTE(nZac) PyPy and CPython render the final string differently. One # includes spac...
"}'), ] DESERIALIZATION_PARAM_LIST += [ (rapidjson.loads, b'{"test": "value"}', {'test': 'value'}), ] @pytest.mark.parametrize('func, body, expected', SERIALIZATION_PARAM_LIST) def test_serialization(asgi, func, body, expected):
63
64
134
28
35
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
test_serialization
test_serialization
74
87
74
75
4f3e90df77ee82bab4ca0f8948add618183f5331
bigcode/the-stack
train
c48d5d612dcb2e6c65e4c3fd
train
class
class TestBaseHandler: def test_defaultError(self): h = media.BaseHandler() def test(call): with pytest.raises(NotImplementedError) as e: call() assert e.value.args == () test(lambda: h.serialize({}, 'my-type')) test(lambda: h.deserialize(''...
class TestBaseHandler:
def test_defaultError(self): h = media.BaseHandler() def test(call): with pytest.raises(NotImplementedError) as e: call() assert e.value.args == () test(lambda: h.serialize({}, 'my-type')) test(lambda: h.deserialize('', 'my-type', 0)) d...
Resource: def on_get(self, req, resp): raise falcon.HTTPForbidden() app.add_route('/', Resource()) result = testing.simulate_get(app, '/') assert result.status_code == 403 assert result.json == falcon.HTTPForbidden().to_dict() class TestBaseHandler:
64
64
201
5
59
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
TestBaseHandler
TestBaseHandler
273
297
273
273
ee607ada800cd2753e1746699f728c4a5ee38970
bigcode/the-stack
train
fae7b7fba87330506ad5efd2
train
function
def test_json_err_no_handler(asgi): app = create_app(asgi) handlers = media.Handlers({falcon.MEDIA_URLENCODED: media.URLEncodedFormHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class Resource: def on_get(self, req, resp): raise...
def test_json_err_no_handler(asgi):
app = create_app(asgi) handlers = media.Handlers({falcon.MEDIA_URLENCODED: media.URLEncodedFormHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class Resource: def on_get(self, req, resp): raise falcon.HTTPForbidden() app.add...
[await req.get_media()] app.add_route('/', ResourceAsync()) doc = {'event': 'serialized'} result = testing.simulate_post(app, '/', json=doc) assert result.status_code == 200 assert result.json == [None] def test_json_err_no_handler(asgi):
64
64
120
9
55
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
test_json_err_no_handler
test_json_err_no_handler
255
270
255
255
32751d8081fed62a91635708c5c8762e22fe2689
bigcode/the-stack
train
2d3bf390912d7a3e1b0afdcc
train
function
def test_sync_methods_not_overridden(asgi): app = create_app(asgi) class FaultyHandler(media.BaseHandler): pass handlers = media.Handlers({'application/json': FaultyHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class Resource: ...
def test_sync_methods_not_overridden(asgi):
app = create_app(asgi) class FaultyHandler(media.BaseHandler): pass handlers = media.Handlers({'application/json': FaultyHandler()}) app.req_options.media_handlers = handlers app.resp_options.media_handlers = handlers class Resource: def on_get(self, req, resp): re...
# I suppose we'll have to look at what is logged. app._error_handlers.clear() with pytest.raises(SuchException): testing.simulate_get(app, '/') with pytest.raises(SuchException): testing.simulate_post(app, '/', json={}) def test_sync_methods_not_overridden(asgi):
67
67
226
10
57
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
test_sync_methods_not_overridden
test_sync_methods_not_overridden
169
200
169
169
2f681840e384c928496c33ce5d6c7dce99b049a1
bigcode/the-stack
train
fbd3fd58d67eb3b4f4bcf441
train
function
@pytest.mark.parametrize('func, body, expected', DESERIALIZATION_PARAM_LIST) def test_deserialization(asgi, func, body, expected): handler = media.JSONHandler(loads=func) args = ['application/javacript', len(body)] if asgi: if not ASGI_SUPPORTED: pytest.skip('ASGI requires Python 3.6+'...
@pytest.mark.parametrize('func, body, expected', DESERIALIZATION_PARAM_LIST) def test_deserialization(asgi, func, body, expected):
handler = media.JSONHandler(loads=func) args = ['application/javacript', len(body)] if asgi: if not ASGI_SUPPORTED: pytest.skip('ASGI requires Python 3.6+') from falcon.asgi.stream import BoundedStream s = BoundedStream(testing.ASGIRequestEventEmitter(body)) a...
differently. One # includes spaces and the other doesn't. This replace will normalize that. assert result.replace(b' ', b'') == expected # noqa @pytest.mark.parametrize('func, body, expected', DESERIALIZATION_PARAM_LIST) def test_deserialization(asgi, func, body, expected):
64
64
158
29
34
ashutoshvarma/falcon
tests/test_media_handlers.py
Python
test_deserialization
test_deserialization
90
110
90
91
749d1fdf60c1dbdba486ab73a9d3f00b0e59733c
bigcode/the-stack
train
a3c0f586de68d3e9c2901802
train
class
class Migration(migrations.Migration): dependencies = [ ('wagtailusers', '0005_make_related_name_wagtail_specific'), ] operations = [ migrations.AddField( model_name='userprofile', name='preferred_language', field=models.CharField(default='', help_text='...
class Migration(migrations.Migration):
dependencies = [ ('wagtailusers', '0005_make_related_name_wagtail_specific'), ] operations = [ migrations.AddField( model_name='userprofile', name='preferred_language', field=models.CharField(default='', help_text='Select language for the admin', max_leng...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-27 22:18 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
54
64
84
7
46
patphongs/wagtail
wagtail/wagtailusers/migrations/0006_userprofile_prefered_language.py
Python
Migration
Migration
8
20
8
9
116dd6428a30943091c72d062ed9802d39081dcd
bigcode/the-stack
train
49dee0691b7d15581970eaf0
train
class
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
class TreeNode:
def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
""" Question Source:Leetcode Level: Easy Topic: Tree Solver: Tayyrov Date: 17.04.2022 """ class TreeNode:
35
64
39
4
31
tayyrov/Daily_Coding_Challenge
April/Day17-Increasing Order Search Tree.py
Python
TreeNode
TreeNode
10
14
10
10
739311e7db0b435b49f41c5cca2fe76c2f0375f6
bigcode/the-stack
train
2fcefc432583c08ce3bfa54b
train
class
class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: lst = [] def dfs(node): if not node: return dfs(node.left) lst.append(node.val) dfs(node.right) return node dfs(root) ans = Tr...
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode: lst = [] def dfs(node): if not node: return dfs(node.left) lst.append(node.val) dfs(node.right) return node dfs(root) ans = TreeNode(lst[0]) ...
Topic: Tree Solver: Tayyrov Date: 17.04.2022 """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution:
64
64
100
3
60
tayyrov/Daily_Coding_Challenge
April/Day17-Increasing Order Search Tree.py
Python
Solution
Solution
15
34
15
15
94da8074f4093b822df4d96d872bd2b874c9f2c8
bigcode/the-stack
train
6aa4b86cabd4ad595c7fcb7b
train
class
class AwaitableGetOutputResult(GetOutputResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetOutputResult( datasource=self.datasource, diagnostics=self.diagnostics, etag=self.etag, id=self.i...
class AwaitableGetOutputResult(GetOutputResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetOutputResult( datasource=self.datasource, diagnostics=self.diagnostics, etag=self.etag, id=self.id, name=self.name, serialization=self.serialization, ty...
.get(self, "serialization") @property @pulumi.getter def type(self) -> str: """ Resource type """ return pulumi.get(self, "type") class AwaitableGetOutputResult(GetOutputResult): # pylint: disable=using-constant-test
64
64
80
21
43
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/streamanalytics/v20160301/get_output.py
Python
AwaitableGetOutputResult
AwaitableGetOutputResult
103
115
103
104
a69f6c2b1d2c97344209b001d7dd896f028a7f59
bigcode/the-stack
train
e21e8afd35442696c988285f
train
function
def get_output(job_name: Optional[str] = None, output_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOutputResult: """ An output object, containing all information associated with the...
def get_output(job_name: Optional[str] = None, output_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetOutputResult:
""" An output object, containing all information associated with the named output. All outputs are contained under a streaming job. :param str job_name: The name of the streaming job. :param str output_name: The name of the output. :param str resource_group_name: The name of the resource group tha...
return GetOutputResult( datasource=self.datasource, diagnostics=self.diagnostics, etag=self.etag, id=self.id, name=self.name, serialization=self.serialization, type=self.type) def get_output(job_name: Optional[str] = None, ...
96
96
321
53
43
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/streamanalytics/v20160301/get_output.py
Python
get_output
get_output
118
147
118
121
976deb98c46b8c3402000a8e9fcda94d076a133c
bigcode/the-stack
train
d6e9c703c9ccb099d0aead57
train
class
@pulumi.output_type class GetOutputResult: """ An output object, containing all information associated with the named output. All outputs are contained under a streaming job. """ def __init__(__self__, datasource=None, diagnostics=None, etag=None, id=None, name=None, serialization=None, type=None): ...
@pulumi.output_type class GetOutputResult:
""" An output object, containing all information associated with the named output. All outputs are contained under a streaming job. """ def __init__(__self__, datasource=None, diagnostics=None, etag=None, id=None, name=None, serialization=None, type=None): if datasource and not isinstance(dataso...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
116
215
717
11
105
pulumi/pulumi-azure-nextgen
sdk/python/pulumi_azure_nextgen/streamanalytics/v20160301/get_output.py
Python
GetOutputResult
GetOutputResult
18
100
18
19
fb9649cd12ee16173a7e2c9ad438f356f6631cdd
bigcode/the-stack
train
fdc9cb4c21e1983ae50b70e9
train
class
class Runner: pipe = [ OriginsArchive(), # Note that you need to have thought about the storage layer for this Categorise(), Geolocate(), Normalise(), # Containers() # Keeping this one uncommented until we have reporting context information being imported ] def proce...
class Runner:
pipe = [ OriginsArchive(), # Note that you need to have thought about the storage layer for this Categorise(), Geolocate(), Normalise(), # Containers() # Keeping this one uncommented until we have reporting context information being imported ] def process_event(self,...
lp.models.events import PipelineEvent, CoreEvent from nglp.config import settings LOG = logging.getLogger("event_handler") app = faust.App('events_handler', broker=settings.kafka_broker, value_serializer='json') topic = app.topic('events') topic_oid = app.topic('oids') class Runner:
64
64
209
3
61
mauromsl/NGLP-Analytics
nglp/pipeline/runner.py
Python
Runner
Runner
26
54
26
26
766ebc17ec3be39807ec21f7294af965c26f0508
bigcode/the-stack
train
6b8c9870cdfb8a5c2c660cf8
train
function
@app.agent(topic) async def handle_event(stream): r = Runner() async for event in stream: await r.process_log(event)
@app.agent(topic) async def handle_event(stream):
r = Runner() async for event in stream: await r.process_log(event)
(exp) core = CoreEvent(event_obj.raw) core.save() send_event = json.dumps({"oids": event_obj.object_ids, "event_id" : unique_id}) #send to oid topic await topic_oid.send(value=send_event) @app.agent(topic) async def handle_event(stream):
64
64
29
10
54
mauromsl/NGLP-Analytics
nglp/pipeline/runner.py
Python
handle_event
handle_event
57
61
57
58
7674f08934bf58608031c475bb7cc37caefb41a5
bigcode/the-stack
train
48803019c01914dacc2c8b1f
train
function
def setup(): firstRun = True print("Config not found") config["last_fetch"] = time.strftime("%Y-%m-%d %H:%M:%S %z") config["watch_list"] = [] exitFlag = False while not exitFlag: inputStr = input("Enter search keywords (empty to exit): ") if inputStr != '': config["wa...
def setup():
firstRun = True print("Config not found") config["last_fetch"] = time.strftime("%Y-%m-%d %H:%M:%S %z") config["watch_list"] = [] exitFlag = False while not exitFlag: inputStr = input("Enter search keywords (empty to exit): ") if inputStr != '': config["watch_list"].ap...
from xml.dom import minidom from urllib.request import urlopen import urllib.parse import time import os import json firstRun = False def setup():
36
64
137
3
32
chihimng/anime-fetcher
fetcher.py
Python
setup
setup
9
23
9
9
7d054cedf0e4434a993b134dc41fff9b34c1caca
bigcode/the-stack
train
d6c5fc4f5bd80c9864b7e4ed
train
function
def get_node_name(): node_name = None node_name_key = 'NODE_NAME' if os.path.exists(ENV_FILE_PATH): with open(ENV_FILE_PATH, "r") as fenv: for line in fenv.readlines(): if line.find(node_name_key) != -1: node_name = line.split('=')[1].strip() ...
def get_node_name():
node_name = None node_name_key = 'NODE_NAME' if os.path.exists(ENV_FILE_PATH): with open(ENV_FILE_PATH, "r") as fenv: for line in fenv.readlines(): if line.find(node_name_key) != -1: node_name = line.split('=')[1].strip() break ...
os.chmod(os.path.join(croot, fs_name), perm_mask_rwx) for fs_name in cfiles: os.chown(os.path.join(croot, fs_name), uid, gid) os.chmod(os.path.join(croot, fs_name), perm_mask_rw) def get_node_name():
64
64
101
5
59
rantwijk/indy-node
data/migrations/deb/1_3_396_to_1_3_397.py
Python
get_node_name
get_node_name
44
57
44
44
3e6a6a90f2eb08e84d9215ad9bf747180a3b4385
bigcode/the-stack
train
8f28d6b1cdb710d5dc04e1e0
train
function
def migrate_all(): node_name = get_node_name() if node_name is None: logger.error("Could not get node name") return False config = getConfig() config_helper = NodeConfigHelper(node_name, config) leveldb_ledger_dir = config_helper.ledger_dir rocksdb_ledger_dir = os.path.join(con...
def migrate_all():
node_name = get_node_name() if node_name is None: logger.error("Could not get node name") return False config = getConfig() config_helper = NodeConfigHelper(node_name, config) leveldb_ledger_dir = config_helper.ledger_dir rocksdb_ledger_dir = os.path.join(config_helper.ledger_d...
not migrate_storage(leveldb_ledger_dir, rocksdb_ledger_dir, db_name, True): logger.error("Could not migrate {}, DB path: {}" .format(db_name, os.path.join(leveldb_ledger_dir, db_name))) return False # Migrate other storages with non-integer keys for db_name in ...
156
156
520
4
151
rantwijk/indy-node
data/migrations/deb/1_3_396_to_1_3_397.py
Python
migrate_all
migrate_all
125
190
125
125
d504223fb36a9501ad20bd48baacf391e6d1bf77
bigcode/the-stack
train
c944681d04e254159e8227d7
train
function
def set_own_perm(usr, dir): uid = pwd.getpwnam(usr).pw_uid gid = grp.getgrnam(usr).gr_gid perm_mask_rw = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP perm_mask_rwx = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP os.chown(dir, uid, gid) os.c...
def set_own_perm(usr, dir):
uid = pwd.getpwnam(usr).pw_uid gid = grp.getgrnam(usr).gr_gid perm_mask_rw = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP perm_mask_rwx = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP os.chown(dir, uid, gid) os.chmod(dir, perm_mask_rwx) ...
_keys import KeyValueStorageRocksdbIntKeys from indy_common.config_util import getConfig from indy_common.config_helper import NodeConfigHelper logger = getlogger() ENV_FILE_PATH = "/etc/indy/indy.env" ledger_types = ['pool', 'domain', 'config'] def set_own_perm(usr, dir):
69
69
230
10
59
rantwijk/indy-node
data/migrations/deb/1_3_396_to_1_3_397.py
Python
set_own_perm
set_own_perm
27
41
27
27
813ed85fefbbfab87df2449757acdf59b60d24db
bigcode/the-stack
train
6a0609d55ded26e2f345d7da
train
function
def archive_leveldb_ledger(node_name, leveldb_ledger_dir): leveldb_ledger_archive_name = node_name + "_ledger_leveldb.tar.gz" leveldb_ledger_archive_path = os.path.join("/tmp", leveldb_ledger_archive_name) tar = tarfile.open(leveldb_ledger_archive_path, "w:gz") tar.add(leveldb_ledger_dir, arcname=node_n...
def archive_leveldb_ledger(node_name, leveldb_ledger_dir):
leveldb_ledger_archive_name = node_name + "_ledger_leveldb.tar.gz" leveldb_ledger_archive_path = os.path.join("/tmp", leveldb_ledger_archive_name) tar = tarfile.open(leveldb_ledger_archive_path, "w:gz") tar.add(leveldb_ledger_dir, arcname=node_name) tar.close() logger.info("Archive of LevelDB-ba...
(): if line.find(node_name_key) != -1: node_name = line.split('=')[1].strip() break else: logger.error("Path to env file does not exist") return node_name def archive_leveldb_ledger(node_name, leveldb_ledger_dir):
64
64
114
15
48
rantwijk/indy-node
data/migrations/deb/1_3_396_to_1_3_397.py
Python
archive_leveldb_ledger
archive_leveldb_ledger
60
67
60
60
dabaeb61281dc1c644a36d4e4eaf7fd053ff700e
bigcode/the-stack
train
01e0dcf4b1b78587580f1e36
train
function
def migrate_storages(leveldb_ledger_dir, rocksdb_ledger_dir): # Migrate transaction logs, they use integer keys for ledger_type in ledger_types: db_name = ledger_type + "_transactions" if not migrate_storage(leveldb_ledger_dir, rocksdb_ledger_dir, db_name, True): logger.error("Could ...
def migrate_storages(leveldb_ledger_dir, rocksdb_ledger_dir): # Migrate transaction logs, they use integer keys
for ledger_type in ledger_types: db_name = ledger_type + "_transactions" if not migrate_storage(leveldb_ledger_dir, rocksdb_ledger_dir, db_name, True): logger.error("Could not migrate {}, DB path: {}" .format(db_name, os.path.join(leveldb_ledger_dir, db_name))) ...
Could not put key/value to RocksDB storage '{}'".format(db_name)) return False leveldb_storage.close() rocksdb_storage.close() return True def migrate_storages(leveldb_ledger_dir, rocksdb_ledger_dir): # Migrate transaction logs, they use integer keys
64
64
201
29
34
rantwijk/indy-node
data/migrations/deb/1_3_396_to_1_3_397.py
Python
migrate_storages
migrate_storages
106
122
106
107
b11e311fe09d2f9c9c3ea7721e56bd0446796f81
bigcode/the-stack
train
97eb073c24782a6e00b46ecb
train
function
def migrate_storage(level_db_dir, rocks_db_dir, db_name, is_db_int_keys): if is_db_int_keys is True: KeyValueStorageLeveldbCls = KeyValueStorageLeveldbIntKeys KeyValueStorageRocksdbCls = KeyValueStorageRocksdbIntKeys else: KeyValueStorageLeveldbCls = KeyValueStorageLeveldb KeyVal...
def migrate_storage(level_db_dir, rocks_db_dir, db_name, is_db_int_keys):
if is_db_int_keys is True: KeyValueStorageLeveldbCls = KeyValueStorageLeveldbIntKeys KeyValueStorageRocksdbCls = KeyValueStorageRocksdbIntKeys else: KeyValueStorageLeveldbCls = KeyValueStorageLeveldb KeyValueStorageRocksdbCls = KeyValueStorageRocksdb try: leveldb_sto...
("/tmp", leveldb_ledger_archive_name) tar = tarfile.open(leveldb_ledger_archive_path, "w:gz") tar.add(leveldb_ledger_dir, arcname=node_name) tar.close() logger.info("Archive of LevelDB-based ledger created: {}" .format(leveldb_ledger_archive_path)) def migrate_storage(level_db_dir, rocks...
89
89
298
19
70
rantwijk/indy-node
data/migrations/deb/1_3_396_to_1_3_397.py
Python
migrate_storage
migrate_storage
70
103
70
70
2246feb801acf73c7882f52dc50e2c963768acee
bigcode/the-stack
train
a8d3397c77143d55782a4088
train
function
def get_input_file_from_file_id( file_id: str, expected_file_type: FileType = None ) -> Union["raw.types.InputPhoto", "raw.types.InputDocument"]: try: decoded = FileId.decode(file_id) except Exception: raise ValueError(f'Failed to decode "{file_id}". The value does not represent an exist...
def get_input_file_from_file_id( file_id: str, expected_file_type: FileType = None ) -> Union["raw.types.InputPhoto", "raw.types.InputDocument"]:
try: decoded = FileId.decode(file_id) except Exception: raise ValueError(f'Failed to decode "{file_id}". The value does not represent an existing local file, ' f'HTTP URL, or valid file id.') file_type = decoded.file_type if expected_file_type is not None and f...
.InputBotInlineMessageMediaAuto( reply_markup=await self.reply_markup.write(client) if self.reply_markup else None, message=message, entities=entities ) ) ) def get_input_file_from_file_id( file_id: str, expected_fil...
80
80
269
39
41
Awesome-RJ/WilliamButcherBot
wbb/core/types/InlineQueryResult.py
Python
get_input_file_from_file_id
get_input_file_from_file_id
237
269
237
240
105ebfa152a9f077a2fb53667c34df649c45569f
bigcode/the-stack
train
196954119ccaad68a41d0017
train
class
class InlineQueryResultAudio(InlineQueryResult): """Link to an audio. By default, this audio will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the audio. Parameters: audio_url (``str``):...
class InlineQueryResultAudio(InlineQueryResult):
"""Link to an audio. By default, this audio will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the audio. Parameters: audio_url (``str``): A valid URL for the embedded audio p...
from typing import Optional, List, Union from pyrogram import raw, types, utils from pyrogram.file_id import FileType, FileId, PHOTO_TYPES, DOCUMENT_TYPES from pyrogram.parser import Parser from pyrogram.types import InlineQueryResult import pyrogram class InlineQueryResultAudio(InlineQueryResult):
67
256
989
10
56
Awesome-RJ/WilliamButcherBot
wbb/core/types/InlineQueryResult.py
Python
InlineQueryResultAudio
InlineQueryResultAudio
9
140
9
9
53bc390b560b85d8cd0da0cc510bf51a8eecd9a7
bigcode/the-stack
train
32326c0e8b3628d145df15c2
train
class
class InlineQueryResultCachedDocument(InlineQueryResult): """Link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. ...
class InlineQueryResultCachedDocument(InlineQueryResult):
"""Link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use input_message_content to send a message with the specified content instead of the file. Parameters: title (``str``): Title ...
self.caption_entities )).values() return raw.types.InputBotInlineResult( id=self.id, type=self.type, title=self.title, description=self.description, thumb=thumb, content=audio, send_message=( await self...
206
206
688
11
195
Awesome-RJ/WilliamButcherBot
wbb/core/types/InlineQueryResult.py
Python
InlineQueryResultCachedDocument
InlineQueryResultCachedDocument
151
235
151
151
9d027b899054653e7ac027feb7a5c3fecd0efc8f
bigcode/the-stack
train
737a991eaf7fd6cd7f91ce08
train
function
def nl2br(v, is_xhtml= True ): if is_xhtml: return v.replace('\n','<br />\n') else : return v.replace('\n','<br>\n')
def nl2br(v, is_xhtml= True ):
if is_xhtml: return v.replace('\n','<br />\n') else : return v.replace('\n','<br>\n')
decode('utf8') value = re.sub(r'[^\w\s-]', '-', value).strip().lower() value = re.sub(r'[-\s]+', '-', value) return value CACHE_NAME = 'pandasreporter' def nl2br(v, is_xhtml= True ):
64
64
46
12
52
Metatab/publicdata_census
src/publicdata/census/util.py
Python
nl2br
nl2br
86
90
86
86
66b905553ef0151fdc76b9677b5d6f35edec3bc5
bigcode/the-stack
train
898751431dc454d3678405cd
train
function
def sub_geoids(v): """Replace state abbreviations and state fips codes with state and national geoids""" from geoid.censusnames import stusab from geoid.acs import Us, State, AcsGeoid if len(v) == 2: v = v.upper() stmap = { v:k for k,v in stusab.items() } if v == 'US': ...
def sub_geoids(v):
"""Replace state abbreviations and state fips codes with state and national geoids""" from geoid.censusnames import stusab from geoid.acs import Us, State, AcsGeoid if len(v) == 2: v = v.upper() stmap = { v:k for k,v in stusab.items() } if v == 'US': return str(U...
# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the # MIT License, included in this distribution as LICENSE """ """ def sub_geoids(v):
40
64
154
6
34
Metatab/publicdata_census
src/publicdata/census/util.py
Python
sub_geoids
sub_geoids
8
33
8
8
650384c516082edeb11fc88310ad70a4cd30beeb
bigcode/the-stack
train
b902f9dc13726530663670e8
train
function
def melt(df): """Melt a census dataframe into two value columns, for the estimate and margin""" import pandas as pd # Intial melt melted = pd.melt(df, id_vars=list(df.columns[:9]), value_vars=list(df.columns[9:])) melted = melted[['gvid', 'variable', 'value']] # Make two seperate frames for es...
def melt(df):
"""Melt a census dataframe into two value columns, for the estimate and margin""" import pandas as pd # Intial melt melted = pd.melt(df, id_vars=list(df.columns[:9]), value_vars=list(df.columns[9:])) melted = melted[['gvid', 'variable', 'value']] # Make two seperate frames for estimates and ma...
pass return str(AcsGeoid.parse(v)) def sub_summarylevel(v): """Replace summary level names with SL numbers""" from geoid.core import names try: int(v) return v except ValueError: return names[v.lower()] def melt(df):
63
64
199
4
59
Metatab/publicdata_census
src/publicdata/census/util.py
Python
melt
melt
47
65
47
47
7653f93c0221a20948ba89c621c8115c33a308ba
bigcode/the-stack
train
b0e6fe2ec253d7fe6176b88c
train
function
def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata from six import text_type value = text_type(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignor...
def slugify(value):
""" Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens.type( """ import re import unicodedata from six import text_type value = text_type(value) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf8') ...
'm90'] margins['variable'] = margins.ovariable.str.replace('_m90', '') # Join the estimates to the margins. final = estimates.join(margins.set_index(['gvid', 'variable']).drop('ovariable', 1)) return final def slugify(value):
64
64
121
5
58
Metatab/publicdata_census
src/publicdata/census/util.py
Python
slugify
slugify
68
80
68
68
f2a907e6821460df17745aa2d34317ce7bc56390
bigcode/the-stack
train
09b8a34a8776667eb94eb989
train
function
def sub_summarylevel(v): """Replace summary level names with SL numbers""" from geoid.core import names try: int(v) return v except ValueError: return names[v.lower()]
def sub_summarylevel(v):
"""Replace summary level names with SL numbers""" from geoid.core import names try: int(v) return v except ValueError: return names[v.lower()]
()) if v in stmap: return str(State(stmap[v])) # Maybe it is a state number try: v = int(v) return str(State(v)) except ValueError: pass return str(AcsGeoid.parse(v)) def sub_summarylevel(v):
64
64
46
6
58
Metatab/publicdata_census
src/publicdata/census/util.py
Python
sub_summarylevel
sub_summarylevel
35
44
35
35
0bdfb9bfa4caf04edba7ac28b0992e6c38f1ccda
bigcode/the-stack
train
fc29660b9550b0716b8c0a1d
train
function
def test_obs_loading_ok(): theory = DomainTheory() theory.load('test/probBLOCKS-domain.pddl', 'test/probBLOCKS-4-2.pddl') with open('test/bw_4_2_good_obs.json') as instream: in_obs = json.loads(instream.read()) assert in_obs['type'] == 'actions' obs = theory.match_observations(in_obs['obse...
def test_obs_loading_ok():
theory = DomainTheory() theory.load('test/probBLOCKS-domain.pddl', 'test/probBLOCKS-4-2.pddl') with open('test/bw_4_2_good_obs.json') as instream: in_obs = json.loads(instream.read()) assert in_obs['type'] == 'actions' obs = theory.match_observations(in_obs['observations']) assert len(...
br.domain import DomainTheory, ObservationNotMatched def test_action_index(): theory = DomainTheory() theory.load('test/probBLOCKS-domain.pddl', 'test/probBLOCKS-4-2.pddl') assert len(theory.index) == 4 def test_obs_loading_ok():
64
64
105
6
57
miquelramirez/pgpbr
test/test_obs_compiler.py
Python
test_obs_loading_ok
test_obs_loading_ok
22
31
22
22
dee79a4ef0307a5c9e6156b1e60578372bd63c0d
bigcode/the-stack
train
c8ce360ef1523e5575e10a82
train
function
def test_action_index(): theory = DomainTheory() theory.load('test/probBLOCKS-domain.pddl', 'test/probBLOCKS-4-2.pddl') assert len(theory.index) == 4
def test_action_index():
theory = DomainTheory() theory.load('test/probBLOCKS-domain.pddl', 'test/probBLOCKS-4-2.pddl') assert len(theory.index) == 4
valuators from tarski.theories import Theory from tarski.io.fstrips import ParsingError, FstripsReader from tarski.syntax import * from tarski.grounding import LPGroundingStrategy from pypgbr.domain import DomainTheory, ObservationNotMatched def test_action_index():
64
64
48
5
58
miquelramirez/pgpbr
test/test_obs_compiler.py
Python
test_action_index
test_action_index
16
20
16
17
6d447dcc9fd8f7673be133c4ae64bbc71b7f0f24
bigcode/the-stack
train
d3b25d5a39ebb7206c34adeb
train
function
def test_obs_loading_fails(): theory = DomainTheory() theory.load('test/probBLOCKS-domain.pddl', 'test/probBLOCKS-4-2.pddl') with open('test/bw_4_2_bad_obs.json') as instream: in_obs = json.loads(instream.read()) assert in_obs['type'] == 'actions' with pytest.raises(ObservationNotMatched):...
def test_obs_loading_fails():
theory = DomainTheory() theory.load('test/probBLOCKS-domain.pddl', 'test/probBLOCKS-4-2.pddl') with open('test/bw_4_2_bad_obs.json') as instream: in_obs = json.loads(instream.read()) assert in_obs['type'] == 'actions' with pytest.raises(ObservationNotMatched): obs = theory.match_ob...
2_good_obs.json') as instream: in_obs = json.loads(instream.read()) assert in_obs['type'] == 'actions' obs = theory.match_observations(in_obs['observations']) assert len(obs) == len(in_obs['observations']) def test_obs_loading_fails():
64
64
102
7
57
miquelramirez/pgpbr
test/test_obs_compiler.py
Python
test_obs_loading_fails
test_obs_loading_fails
33
42
33
33
40574fd7b2046cf706a1c229cbff2591aef0d8e8
bigcode/the-stack
train
746221da99a955f048ff7455
train
class
class brocade_sec_services(object): """Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def telnet_sa_telnet_server_shutdown(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") teln...
class brocade_sec_services(object):
"""Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def telnet_sa_telnet_server_shutdown(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") telnet_sa = ET.SubElement(config, "telne...
#!/usr/bin/env python import xml.etree.ElementTree as ET class brocade_sec_services(object):
22
256
5,163
7
14
bdeetz/pynos
pynos/versions/ver_7/ver_7_1_0/yang/brocade_sec_services.py
Python
brocade_sec_services
brocade_sec_services
5
498
5
5
92913507ff909830ced60107ac9890ac9e59ea24
bigcode/the-stack
train
5e78995b183c178cbaaeb92c
train
class
class DefaultCLI(password.Password): """A Plugin that provides typical authentication options for CLIs. This plugin provides standard username and password authentication options as well as allowing users to override with a custom token and endpoint. """ def __init__(self, endpoint=None, token=Non...
class DefaultCLI(password.Password):
"""A Plugin that provides typical authentication options for CLIs. This plugin provides standard username and password authentication options as well as allowing users to override with a custom token and endpoint. """ def __init__(self, endpoint=None, token=None, **kwargs): super(DefaultCL...
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 IS" BASIS...
154
155
517
6
148
prasoon-uta/IBM-coud-storage
venv/Lib/site-packages/keystoneclient/auth/identity/generic/cli.py
Python
DefaultCLI
DefaultCLI
20
82
20
20
1aa27928d2de4a750ca7bd84993d9118ea4409d2
bigcode/the-stack
train
11490a16eeeaad18802d4de6
train
function
def get_cached_property_name(obj): if isinstance(obj, types.FunctionType): name = obj.__name__ elif isinstance(obj, str): name = obj else: raise ValueError("Invalid argument '%s'"%obj) return '_cached_'+name
def get_cached_property_name(obj):
if isinstance(obj, types.FunctionType): name = obj.__name__ elif isinstance(obj, str): name = obj else: raise ValueError("Invalid argument '%s'"%obj) return '_cached_'+name
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ import types def get_cached_property_name(obj):
64
64
58
7
56
BEL-Public/cached-property
cached_property/cached_property.py
Python
get_cached_property_name
get_cached_property_name
18
25
18
18
232a3690009f3a9c5a91b864d9691946b9419a0b
bigcode/the-stack
train
437b76a2fe2d6b55d1072b8a
train
function
def drop_cache(obj, prop_name, permissive=False): cached_name = get_cached_property_name(prop_name) if hasattr(obj, cached_name): delattr(obj, cached_name) else: if not permissive: raise ValueError("Property '%s' not cached in object '%s'"%(prop_name, obj))
def drop_cache(obj, prop_name, permissive=False):
cached_name = get_cached_property_name(prop_name) if hasattr(obj, cached_name): delattr(obj, cached_name) else: if not permissive: raise ValueError("Property '%s' not cached in object '%s'"%(prop_name, obj))
try: return getattr(self, cached_name) except AttributeError: ans = fn(self) setattr(self, cached_name, ans) return ans _cached_property.__doc__ = fn.__doc__ return _cached_property def drop_cache(obj, prop_name, permissive=False):
64
64
70
12
51
BEL-Public/cached-property
cached_property/cached_property.py
Python
drop_cache
drop_cache
41
47
41
41
be6fc4bdb87fad8424146482062da622da63884c
bigcode/the-stack
train
9f876552871da10a38b72516
train
function
def cached_property(fn): cached_name = get_cached_property_name(fn) @property def _cached_property(self): try: return getattr(self, cached_name) except AttributeError: ans = fn(self) setattr(self, cached_name, ans) return ans _cached_prope...
def cached_property(fn):
cached_name = get_cached_property_name(fn) @property def _cached_property(self): try: return getattr(self, cached_name) except AttributeError: ans = fn(self) setattr(self, cached_name, ans) return ans _cached_property.__doc__ = fn.__doc__ ...
def get_cached_property_name(obj): if isinstance(obj, types.FunctionType): name = obj.__name__ elif isinstance(obj, str): name = obj else: raise ValueError("Invalid argument '%s'"%obj) return '_cached_'+name def cached_property(fn):
64
64
79
5
58
BEL-Public/cached-property
cached_property/cached_property.py
Python
cached_property
cached_property
27
39
27
27
6854e8ee637e3370204ad03679b4872e00f133f4
bigcode/the-stack
train
3564b6532b54e3a1793d9439
train
function
def get_text_chunk(parser): for action, element in parser.read_events(): if element.tag == 's': yield etree.tostring(element, pretty_print=True)
def get_text_chunk(parser):
for action, element in parser.read_events(): if element.tag == 's': yield etree.tostring(element, pretty_print=True)
see what results you get! # take some xml; can use console, but try to have something written in the script that preserves some of your experiments, should run/work. # separate script from lxml import etree parser = etree.XMLPullParser(events=('end',)) def get_text_chunk(parser):
64
64
35
6
58
python-for-humanists-penn/python-for-humanists-penn.github.io
4_25_2019/4_25_2019.py
Python
get_text_chunk
get_text_chunk
183
186
183
183
8a4a92376fbf84e9a89a9df2ac8c1da8199076da
bigcode/the-stack
train
a289d6cf887a4843d4486bac
train
function
def file_name(data): parts = [] parts.append(data['year']) # get = method = () parts.extend(data['author'].split()) # position: default value (defined by individual function) parts.extend(data['title'].split()[0:3]) # expression #.extend joins lists together name = '-'.join(parts) # join always...
def file_name(data):
parts = [] parts.append(data['year']) # get = method = () parts.extend(data['author'].split()) # position: default value (defined by individual function) parts.extend(data['title'].split()[0:3]) # expression #.extend joins lists together name = '-'.join(parts) # join always accepts a sequence ...
name # 4. save all of the dictionaries to a csv file # # Today: 1.: write a function that takes one of our dictionaries that has been output by the function above (line 60), and returns a file name for that dictionary #============================================================================== def file_nam...
64
64
102
5
58
python-for-humanists-penn/python-for-humanists-penn.github.io
4_25_2019/4_25_2019.py
Python
file_name
file_name
117
124
117
117
b3f7195edca0f6043d651de7c17ee290818ae7eb
bigcode/the-stack
train
ed7101b0e2ea1814d5cf832b
train
function
def get_article(text): data = {} data["author"] = text["author"] data["title"] = text["title"] data["journal"] = text["journal"] data["volume"] = text["volume"] data["year"] = text["year"] data["text"] = column_one(text.get_text()) return data
def get_article(text):
data = {} data["author"] = text["author"] data["title"] = text["title"] data["journal"] = text["journal"] data["volume"] = text["volume"] data["year"] = text["year"] data["text"] = column_one(text.get_text()) return data
-memory sequence [anything that can be looped over in a for-loop] of all text-tags # print(raw_html) ## we want: journal, title, volume, year, + get the CSV itself ## write a function that takes text object, processes it, and returns data def get_article(text):
64
64
76
5
58
python-for-humanists-penn/python-for-humanists-penn.github.io
4_25_2019/4_25_2019.py
Python
get_article
get_article
28
37
28
28
69ac76cb78ddbe9d765e544ea55c0da1322c381d
bigcode/the-stack
train
5401223badd5d80fc5a8583e
train
function
def column_one(text): #creates an empty list_of_words # create in for-loop: takes text in format #split string into lines #take each line and split it into its constituent fields #take the first field from each line #append it to a list list_of_words = [] lines = text.spl...
def column_one(text): #creates an empty list_of_words # create in for-loop: takes text in format #split string into lines #take each line and split it into its constituent fields #take the first field from each line #append it to a list
list_of_words = [] lines = text.splitlines() for line in lines: fields = line.split("\t") #"\t" signifies tab character, instead of comma-separated item1 = fields[0] list_of_words.append(item1) return " ".join(list_of_words)
def column_one(text): #creates an empty list_of_words # create in for-loop: takes text in format #split string into lines #take each line and split it into its constituent fields #take the first field from each line #append it to a list
64
64
129
64
0
python-for-humanists-penn/python-for-humanists-penn.github.io
4_25_2019/4_25_2019.py
Python
column_one
column_one
40
55
40
46
b28a69afd1ea9db0f8667057da8d0702e184ce5c
bigcode/the-stack
train
317287d9729624d51468b68b
train
function
def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('user', 'passwordReset')
def downgrade(): ### commands auto generated by Alembic - please adjust! ###
op.drop_column('user', 'passwordReset')
upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('passwordReset', sa.String(length=128), nullable=True)) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ###
63
64
28
17
46
toadicus/KerbalStuff
alembic/versions/f9897e968a_add_password_reset_to_schema.py
Python
downgrade
downgrade
23
25
23
24
9297c71247bd8f3a38dfa7e8f9afe9b823fc9ac2
bigcode/the-stack
train
dff4fcda45076bd9f2ec0dd5
train
function
def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('user', sa.Column('passwordReset', sa.String(length=128), nullable=True))
def upgrade(): ### commands auto generated by Alembic - please adjust! ###
op.add_column('user', sa.Column('passwordReset', sa.String(length=128), nullable=True))
305 """ # revision identifiers, used by Alembic. revision = 'f9897e968a' down_revision = '59c74736a7f' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ###
64
64
39
17
46
toadicus/KerbalStuff
alembic/versions/f9897e968a_add_password_reset_to_schema.py
Python
upgrade
upgrade
17
19
17
18
f29b7205ceed234eb0c7d003f23a9b888de4b216
bigcode/the-stack
train
2984f6b338f67f17b0ef4d56
train
class
class MolecularGraphTest(unittest.TestCase): @classmethod @unittest.skipIf(import_failed, "molecule package relies on openbabel") def setUpClass(cls): with open(os.path.join(module_dir, 'qm9', '000001.json'), 'r') as f: cls.qm9_000001 = json.load(f) cls.mol = mol_from_smiles(cls...
class MolecularGraphTest(unittest.TestCase): @classmethod @unittest.skipIf(import_failed, "molecule package relies on openbabel")
def setUpClass(cls): with open(os.path.join(module_dir, 'qm9', '000001.json'), 'r') as f: cls.qm9_000001 = json.load(f) cls.mol = mol_from_smiles(cls.qm9_000001['smiles']) @unittest.skipIf(import_failed, "molecule package relies on openbabel") def setUp(self) -> None: se...
_graph(self): mol = Molecule(['C', 'H', 'O'], [[0, 0, 0], [1, 0, 0], [2, 0, 0]]) graph = SimpleMolGraph().convert(mol) self.assertListEqual(to_list(graph['atom']), [6, 1, 8]) self.assertTrue(np.allclose(graph['bond'], [1, 2, 1, 1, 2, 1])) self.assertListEqual(to_list(graph['index...
256
256
2,557
30
226
davidtangGT/MEGNET
megnet/data/tests/test_molecule.py
Python
MolecularGraphTest
MolecularGraphTest
47
264
47
50
a2c2b51734e0550615f4c315200039c6a4b0e58d
bigcode/the-stack
train
416b0cdf29d0e98be25a12bb
train
class
class QM9Test(unittest.TestCase): def test_simple_molecule_graph(self): mol = Molecule(['C', 'H', 'O'], [[0, 0, 0], [1, 0, 0], [2, 0, 0]]) graph = SimpleMolGraph().convert(mol) self.assertListEqual(to_list(graph['atom']), [6, 1, 8]) self.assertTrue(np.allclose(graph['bond'], [1, 2, 1...
class QM9Test(unittest.TestCase):
def test_simple_molecule_graph(self): mol = Molecule(['C', 'H', 'O'], [[0, 0, 0], [1, 0, 0], [2, 0, 0]]) graph = SimpleMolGraph().convert(mol) self.assertListEqual(to_list(graph['atom']), [6, 1, 8]) self.assertTrue(np.allclose(graph['bond'], [1, 2, 1, 1, 2, 1])) self.assertLi...
.path.abspath(__file__)) def equal(x, y): if isinstance(x, list): return all([i == j for i, j in zip(x, y)]) if isinstance(x, float): return abs(x-y) < 0.01 else: return x == y class QM9Test(unittest.TestCase):
72
72
240
8
63
davidtangGT/MEGNET
megnet/data/tests/test_molecule.py
Python
QM9Test
QM9Test
32
44
32
32
ea651347b61413ffede38cf4fc379cb71793ebbd
bigcode/the-stack
train
1b459a98994d4e280d0c19d4
train
function
def equal(x, y): if isinstance(x, list): return all([i == j for i, j in zip(x, y)]) if isinstance(x, float): return abs(x-y) < 0.01 else: return x == y
def equal(x, y):
if isinstance(x, list): return all([i == j for i, j in zip(x, y)]) if isinstance(x, float): return abs(x-y) < 0.01 else: return x == y
.data.molecule import MolecularGraph, MolecularGraphBatchGenerator,\ pybel, mol_from_smiles, ring_to_vector if pybel is None: import_failed = True else: import_failed = False module_dir = os.path.dirname(os.path.abspath(__file__)) def equal(x, y):
63
64
58
6
57
davidtangGT/MEGNET
megnet/data/tests/test_molecule.py
Python
equal
equal
23
29
23
23
d14d04631cdb276bddf65aebdb749a9adb748bfc
bigcode/the-stack
train
804b6a1e8b25d5ce7f56981a
train
function
def collate_fn(batch): """ 动态padding, batch为一部分sample """ def padding(indice, max_length, pad_idx=0): """ pad 函数 """ pad_indice = [item + [pad_idx] * max(0, max_length - len(item)) for item in indice] return torch.tensor(pad_indice) token_ids_src = [data["to...
def collate_fn(batch):
""" 动态padding, batch为一部分sample """ def padding(indice, max_length, pad_idx=0): """ pad 函数 """ pad_indice = [item + [pad_idx] * max(0, max_length - len(item)) for item in indice] return torch.tensor(pad_indice) token_ids_src = [data["token_ids_src"] for data ...
=256) token_ids_tgt = tokenizer.encode(tgt, max_length=256) output = { "token_ids_src": token_ids_src, "token_ids_tgt": token_ids_tgt, } return output def __len__(self): return len(self.sents_src) def collate_fn(batch):
72
72
241
6
66
longquan0609/bert_seq2seq
examples/bart_auto_title_train.py
Python
collate_fn
collate_fn
78
101
78
78
99324c61077da78b7294104fd3f845cd40aa3fc2
bigcode/the-stack
train
31abc987a9c2c3aec2e0a73a
train
function
def read_file(): src = [] tgt = [] with open(src_dir,'r',encoding='utf-8') as f: lines = f.readlines() for line in lines: src.append(line.strip('\n').lower()) with open(tgt_dir,'r',encoding='utf-8') as f: lines = f.readlines() for line in lines: ...
def read_file():
src = [] tgt = [] with open(src_dir,'r',encoding='utf-8') as f: lines = f.readlines() for line in lines: src.append(line.strip('\n').lower()) with open(tgt_dir,'r',encoding='utf-8') as f: lines = f.readlines() for line in lines: tgt.append(line....
art_autotile.bin" ## 训练完模型 保存在哪里 batch_size = 8 lr = 1e-5 tokenizer = BertTokenizer.from_pretrained(vocab_path) word2idx = tokenizer.vocab model = BartForConditionalGeneration.from_pretrained(model_path) def read_file():
64
64
97
4
60
longquan0609/bert_seq2seq
examples/bart_auto_title_train.py
Python
read_file
read_file
29
44
29
29
3d7cdde930e79797b99f949f224254f17d3140ba
bigcode/the-stack
train
3b9431191a362a07470282a9
train
class
class Trainer: def __init__(self): # 加载数据 self.sents_src, self.sents_tgt = read_file() # 判断是否有可用GPU self.device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") print("device: " + str(self.device)) # 定义模型 self.model = ExtendModel(model, tokeni...
class Trainer:
def __init__(self): # 加载数据 self.sents_src, self.sents_tgt = read_file() # 判断是否有可用GPU self.device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu") print("device: " + str(self.device)) # 定义模型 self.model = ExtendModel(model, tokenizer=tokenizer, ...
len__(self): return len(self.sents_src) def collate_fn(batch): """ 动态padding, batch为一部分sample """ def padding(indice, max_length, pad_idx=0): """ pad 函数 """ pad_indice = [item + [pad_idx] * max(0, max_length - len(item)) for item in indice] return torch...
256
256
890
3
252
longquan0609/bert_seq2seq
examples/bart_auto_title_train.py
Python
Trainer
Trainer
104
178
104
104
59d4386a62e4ddaf51802075de90e4ec84f2638c
bigcode/the-stack
train
bb61a7e4c956c071bcb765f1
train
class
class SeqDataset(Dataset): """ 针对特定数据集,定义一个相关的取数据的方式 """ def __init__(self, sents_src, sents_tgt): ## 一般init函数是加载所有数据 super(SeqDataset, self).__init__() # 读原始数据 self.sents_src = sents_src self.sents_tgt = sents_tgt self.idx2word = {k: v for v, k in word2...
class SeqDataset(Dataset):
""" 针对特定数据集,定义一个相关的取数据的方式 """ def __init__(self, sents_src, sents_tgt): ## 一般init函数是加载所有数据 super(SeqDataset, self).__init__() # 读原始数据 self.sents_src = sents_src self.sents_tgt = sents_tgt self.idx2word = {k: v for v, k in word2idx.items()} def __get...
.readlines() for line in lines: src.append(line.strip('\n').lower()) with open(tgt_dir,'r',encoding='utf-8') as f: lines = f.readlines() for line in lines: tgt.append(line.strip('\n').lower()) return src, tgt class SeqDataset(Dataset):
70
70
234
6
63
longquan0609/bert_seq2seq
examples/bart_auto_title_train.py
Python
SeqDataset
SeqDataset
47
75
47
47
5d7744cd4d5c1a334e00e595ce7e85e1413efafe
bigcode/the-stack
train
6550273515dcadadb7ded601
train
function
def check_data_directory(): """Check to make sure correct file structure exists for data processing.""" print("Check directories") dirtype = {} dirtype['data/external'] = ['olx','tanqeeb','wuzzuf'] dirtype['data/interim'] = ['olx','tanqeeb','wuzzuf'] dirtype['data/processed'] = ['finaldb'] ...
def check_data_directory():
"""Check to make sure correct file structure exists for data processing.""" print("Check directories") dirtype = {} dirtype['data/external'] = ['olx','tanqeeb','wuzzuf'] dirtype['data/interim'] = ['olx','tanqeeb','wuzzuf'] dirtype['data/processed'] = ['finaldb'] dirtype['figures'] = ['o...
import os from config import FileConfig def check_data_directory():
14
68
229
5
8
natc79/MENAJobData
step1_download/src/set_directories.py
Python
check_data_directory
check_data_directory
5
24
5
5
53a940e5c48142b0b99bb060aae1e5affe7d0a94
bigcode/the-stack
train
d15f8c4bad8da6999c2e3dad
train
class
class ListQueryView(PermissionRequiredMixin, ExplorerContextMixin, ListView): permission_required = 'view_permission_list' model = Query def recently_viewed(self): qll = QueryLog.objects.filter( run_by_user=self.request.user, query_id__isnull=False ).order_by( '-run...
class ListQueryView(PermissionRequiredMixin, ExplorerContextMixin, ListView):
permission_required = 'view_permission_list' model = Query def recently_viewed(self): qll = QueryLog.objects.filter( run_by_user=self.request.user, query_id__isnull=False ).order_by( '-run_at' ).select_related('query') ret = [] tracker = [] ...
# -*- coding: utf-8 -*- import re from collections import Counter from django.forms.models import model_to_dict from django.views.generic import ListView from explorer import app_settings from explorer.models import Query, QueryLog from explorer.utils import ( url_get_query_id, allowed_query_pks ) from explor...
101
238
796
16
84
sciyoshi/django-sql-explorer
explorer/views/list.py
Python
ListQueryView
ListQueryView
18
121
18
19
fcf741e94263a34b267b0aff97b442b8059a3d74
bigcode/the-stack
train
e17570543d95e4b1c54cf13b
train
class
class ListQueryLogView(PermissionRequiredMixin, ExplorerContextMixin, ListView): context_object_name = "recent_logs" model = QueryLog paginate_by = 20 permission_required = 'view_permission' def get_queryset(self): kwargs = {'sql__isnull': False} if url_get_query_id(self.request): ...
class ListQueryLogView(PermissionRequiredMixin, ExplorerContextMixin, ListView):
context_object_name = "recent_logs" model = QueryLog paginate_by = 20 permission_required = 'view_permission' def get_queryset(self): kwargs = {'sql__isnull': False} if url_get_query_id(self.request): kwargs['query_id'] = url_get_query_id(self.request) return Que...
, 'run_count': q.querylog_set.count(), 'created_by_user': str(q.created_by_user) if q.created_by_user else None }) dict_list.append(model_dict) return dict_list class ListQueryLogView(PermissionRequiredMixin, ExplorerContextMixin, ListV...
64
64
98
17
46
sciyoshi/django-sql-explorer
explorer/views/list.py
Python
ListQueryLogView
ListQueryLogView
124
135
124
125
9e2ab3e8bccd4e299289fb718bbbb58a0364415f
bigcode/the-stack
train
6cf84b49caad235578a3fe7b
train
class
class handler: #class PlatBaseShopEdit: def GET(self): if helper.logged(helper.PRIV_USER,'PLAT_BASE_SHOP'): render = helper.create_render(globals={'str':str}) user_data=web.input(base_shop='') if user_data.base_shop=='': return render.info('错误的参数!') db_shop=db.base_shop.find_one({...
class handler: #class PlatBaseShopEdit:
def GET(self): if helper.logged(helper.PRIV_USER,'PLAT_BASE_SHOP'): render = helper.create_render(globals={'str':str}) user_data=web.input(base_shop='') if user_data.base_shop=='': return render.info('错误的参数!') db_shop=db.base_shop.find_one({'_id':ObjectId(user_data.base_shop)}) if db_shop!=No...
#!/usr/bin/env python # -*- coding: utf-8 -*- import web from bson.objectid import ObjectId from config import setting import helper, lbs db = setting.db_web url = ('/plat/base_shop_edit') class handler: #class PlatBaseShopEdit:
62
236
789
12
50
jack139/fair
src/plat/base_shop_edit.py
Python
handler
handler
13
91
13
13
04d027c7039ab69fa89283e2094b8d57b8d8f6bc
bigcode/the-stack
train
d1b2b1131617316683c5bf9e
train
class
@tvm.script.ir_module class WeightStreamOnly: @T.prim_func def main(placeholder: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_write: T.Buffer[(1, 16, 16, 8), "int8"]) -> None: buffer = T.buffer_var("uint8", "") buffer_1 = T.buffer_var("uint8", "") buffer_2 = T.buffer_var("uint8", "") ...
@tvm.script.ir_module class WeightStreamOnly: @T.prim_func
def main(placeholder: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_write: T.Buffer[(1, 16, 16, 8), "int8"]) -> None: buffer = T.buffer_var("uint8", "") buffer_1 = T.buffer_var("uint8", "") buffer_2 = T.buffer_var("uint8", "") buffer_3 = T.buffer_var("uint8", "") buffer_4 = T.buf...
32, 16, 0, 16, T.load("uint8", placeholder_3.data, 0), 0, 0, 0, T.float32(0.5), 10, "NHWC", 512, 32, 1, "uint8", 16, 16, 8, 16, 0, 16, T.load("uint8", ethosu_conv2d_1.data, 0), 0, 0, 0, T.float32(0.25), 14, "NHWC", 128, 8, 1, 1, 1, 1, 1, 1, 1, T.load("uint8", placeholder_global, 0), 0, 12, T.load("uint8", placeholder_...
256
256
1,636
19
237
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
WeightStreamOnly
WeightStreamOnly
89
127
89
91
cfc327578d40de35d022181ac95fa4b627229cb0
bigcode/the-stack
train
b78971a1c249b451690bd532
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMaxBroadcasting: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMaxBroadcasting: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffer...
, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "MIN", 1, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise MAX with broadcasting tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseMaxBroadcasting: @T.pri...
122
122
408
25
97
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseMaxBroadcasting
SingleEthosuBinaryElementwiseMaxBroadcasting
1,341
1,351
1,341
1,343
e99f5d73ed10656cee883c75c1708d2eda01bd82
bigcode/the-stack
train
38e25f90af821a69b0411d58
train
function
def test_translate_ethosu_pooling(): def extract_ethosu_pooling_extern_call(mod): # There should only be a single function assert len(mod.functions.items()) == 1 primfunc = mod.functions.items()[0][1] ethosu_pooling_calls = list() def populate_ethosu_pooling_calls(stmt): ...
def test_translate_ethosu_pooling():
def extract_ethosu_pooling_extern_call(mod): # There should only be a single function assert len(mod.functions.items()) == 1 primfunc = mod.functions.items()[0][1] ethosu_pooling_calls = list() def populate_ethosu_pooling_calls(stmt): if ( isinst...
3], dtype="int8", elem_offset=0, align=128, offset_factor=1) # body T.evaluate(T.call_extern("ethosu_pooling", "int8", 5, 9, 3, 5, 0, 9, T.load("int8", placeholder_4.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "int8", 5, 5, 3, 5, 0, 5, T.load("int8", ethosu_write_2.data, 0), 0, 0, 0, T.floa...
256
256
886
8
247
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_translate_ethosu_pooling
test_translate_ethosu_pooling
1,000
1,054
1,000
1,000
479169440a9ac3579d0b1fa6d40c34949927d72e
bigcode/the-stack
train
da44cb32759c986131bebe1f
train
class
@tvm.script.ir_module class SingleEthosuPooling: @T.prim_func def main(placeholder: T.handle, placeholder_3: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_4 = T.match_buffer(placeholder, [1, 5, 9, 3...
@tvm.script.ir_module class SingleEthosuPooling: @T.prim_func
def main(placeholder: T.handle, placeholder_3: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_4 = T.match_buffer(placeholder, [1, 5, 9, 3], dtype="int8", elem_offset=0, align=128, offset_factor=1) ...
2, dtype="uint8") verify(_npu_ops) # This will be only 1 if all allocated scratch is used. assert np.prod(tvmbaw_workspace_mask) == 1 # This will be only 1 if all constant tensors is read at least once. assert np.prod(constant_tensor_read_mask) == 1 # fmt: off """A ethosu_pool...
113
113
379
20
93
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuPooling
SingleEthosuPooling
986
996
986
988
9168aaff46f1f0507a719d339b64b264434ff8b5
bigcode/the-stack
train
9beed79129a8c382caa42042
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShr: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int32", e...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShr: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int32", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buff...
_2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "MAX", 0, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise SHR tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseShr: @T.prim_func
121
121
406
23
98
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseShr
SingleEthosuBinaryElementwiseShr
1,142
1,152
1,142
1,144
54585c3ee3726cf12e025edf7e53e4da467abeff
bigcode/the-stack
train
3b03b73645f8727d38edd7e6
train
class
@tvm.script.ir_module class SingleEthosuDepthwiseConv2D: @T.prim_func def main(placeholder: T.handle, placeholder_1: T.handle, placeholder_2: T.handle, ethosu_depthwise_conv2d: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder...
@tvm.script.ir_module class SingleEthosuDepthwiseConv2D: @T.prim_func
def main(placeholder: T.handle, placeholder_1: T.handle, placeholder_2: T.handle, ethosu_depthwise_conv2d: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_4 = T.match_buffer(placeholder_1, [3, 3, 2, 1], dtype="int8", elem_offset...
else: assert npu_op.activation.op_type == ref["activation"]["op"] assert npu_op.activation.min == ref["activation"]["min"] assert npu_op.activation.max == ref["activation"]["max"] # Compare rounding mode assert npu_op.rounding_mode == ref["roundin...
157
157
525
24
133
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuDepthwiseConv2D
SingleEthosuDepthwiseConv2D
520
532
520
522
c5d8c61b31b670f11f1e3a0172b21bb81d58e1c0
bigcode/the-stack
train
21afed112f861f0af74218ff
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMinBroadcasting: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMinBroadcasting: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffer...
0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "MUL", 1, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise MIN with broadcasting tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseMinBroadcasting: @T.prim...
122
122
408
25
97
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseMinBroadcasting
SingleEthosuBinaryElementwiseMinBroadcasting
1,325
1,335
1,325
1,327
ca33425e991bddc16c70a7557c175472d70e4200
bigcode/the-stack
train
80026b4a7be8e416ef9cd199
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShl: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int32", e...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShl: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int32", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buff...
2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "SHR", 0, "NONE", 0, 0, "TFL", dtype="int32")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise SHL tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseShl: @T.prim_func
122
122
408
24
98
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseShl
SingleEthosuBinaryElementwiseShl
1,158
1,168
1,158
1,160
3221bed421e41cbeee5b490e21758e15fb735c57
bigcode/the-stack
train
78589d4e733e81c2d5fb1fac
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseAddBroadcasting: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseAddBroadcasting: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffer...
pu_op.activation is None else: assert npu_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU assert npu_op.activation.min == 10 assert npu_op.activation.max == 100 # Compare rounding mode assert npu_op.rounding_mode == vapi.NpuRoundingMode.TFL # fmt: off """A ethosu_binary_...
122
122
408
25
97
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseAddBroadcasting
SingleEthosuBinaryElementwiseAddBroadcasting
1,279
1,289
1,279
1,281
f390a37cce77e84ae7ec3d8c69ea7e5ee3f66ee1
bigcode/the-stack
train
f44a9b52fb2ff0f56bd53dfb
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShlBroadcasting: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShlBroadcasting: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype="int32", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffe...
0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "SHR", 1, "NONE", 0, 0, "TFL", dtype="int32")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise SHL with broadcasting tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseShlBroadcasting: @T.prim_f...
123
123
410
26
97
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseShlBroadcasting
SingleEthosuBinaryElementwiseShlBroadcasting
1,373
1,383
1,373
1,375
c9c8deef6a971e0ba87917cd4274d9e517f4bf3f
bigcode/the-stack
train
47f4a47da4aad4a18942ed6d
train
function
def test_assign_addresses(): test_cases = [ { # Stimulus "tir_module": WeightStreamOnly, "param_dict": { WeightStreamOnly["main"].attrs["constants"]["buffer"]: np.random.randint( np.iinfo("uint8").min, np.iinfo("uint8").max, [128], "uin...
def test_assign_addresses():
test_cases = [ { # Stimulus "tir_module": WeightStreamOnly, "param_dict": { WeightStreamOnly["main"].attrs["constants"]["buffer"]: np.random.randint( np.iinfo("uint8").min, np.iinfo("uint8").max, [128], "uint8" ), ...
, 16, 1, 0, 1, T.load("int16", ethosu_write_2, 0), 0, 0, 0, T.float32(0.0023205536417663097), -128, "NHWC", 1, 1, 1, "int16", 1, 1, 1, 1, 0, 1, T.load("int16", placeholder_d_global_1, 0), 0, 0, 0, T.float32(0.0078125018482064768), 0, "NHWC", 1, 1, 1, "int8", 1, 1, 16, 1, 0, 1, T.load("int8", ethosu_write_1.data, 0), 0,...
256
256
3,115
5
250
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_assign_addresses
test_assign_addresses
691
981
691
691
49d80a2d0e98ca4159c41659796206c54efa6208
bigcode/the-stack
train
a05c0a0ea8eef0f33946b7e5
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMul: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", el...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMul: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffe...
_write_2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "SUB", 0, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise MUL tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseMul: @T.prim_func
122
122
407
23
99
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseMul
SingleEthosuBinaryElementwiseMul
1,094
1,104
1,094
1,096
eab6d4f752538d72ec77511fb3e8b811e6739460
bigcode/the-stack
train
7e38bfcbb53d981f0f22a986
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShrBroadcasting: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseShrBroadcasting: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype="int32", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffe...
, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "MAX", 1, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise SHR with broadcasting tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseShrBroadcasting: @T.pri...
122
122
408
25
97
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseShrBroadcasting
SingleEthosuBinaryElementwiseShrBroadcasting
1,357
1,367
1,357
1,359
15296a956c674cff18ad41d83403919cbd8ec1e5
bigcode/the-stack
train
6c1b11c30174528ad308b6da
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseSubBroadcasting: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseSubBroadcasting: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffer...
, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "ADD", 1, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise SUB with broadcasting tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseSubBroadcasting: @T.prim...
122
122
408
25
97
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseSubBroadcasting
SingleEthosuBinaryElementwiseSubBroadcasting
1,294
1,304
1,294
1,296
955afd71b95917729fbd77f16b9eccc2ab0e621a
bigcode/the-stack
train
5c97f4483f7af02fcd242675
train
function
def test_translate_ethosu_conv2d(): test_cases = [ { # Stimulus "tir_module": SingleEthosUConv2D, "param_dict": { 1: np.random.randint( np.iinfo("uint8").min, np.iinfo("uint8").max, [1, 1, 3, 16], "uint8" ), ...
def test_translate_ethosu_conv2d():
test_cases = [ { # Stimulus "tir_module": SingleEthosUConv2D, "param_dict": { 1: np.random.randint( np.iinfo("uint8").min, np.iinfo("uint8").max, [1, 1, 3, 16], "uint8" ), 2: np.random.randint(np.iinfo("i...
), "ethosu_conv2d_3": ( [2048], "uint8", tir_to_cs_translator.BufferType.scratch, ), }, }, ] for test_case in test_cases: # With Target Hooks the TIR module needs a target attached # ...
256
256
3,132
9
247
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_translate_ethosu_conv2d
test_translate_ethosu_conv2d
266
515
266
266
04b0823eccc38a6a8043845ba55a9ef665183c11
bigcode/the-stack
train
2f55c4dbd6385abbbbdc9020
train
function
def test_translate_ethosu_copy(): def extract_ethosu_copy_extern_calls(mod): """This function will obtain all ethosu_conv2d calls from a NPU TIR module Parameters ---------- mod : tvm.IRModule This is a NPU TIR Module Returns ------- list ...
def test_translate_ethosu_copy():
def extract_ethosu_copy_extern_calls(mod): """This function will obtain all ethosu_conv2d calls from a NPU TIR module Parameters ---------- mod : tvm.IRModule This is a NPU TIR Module Returns ------- list of tvm.tir.Call object...
=1).__dict__ ) assert npu_op.padding == vapi.NpuPadding(top=0, left=0, bottom=0, right=0) # Compare activation assert npu_op.activation.op_type == vapi.NpuActivationOp.NONE_OR_RELU assert npu_op.activation.min == 0 assert npu_op.activation.max == pytest.approx(23.4) # Compare rounding mode ...
164
164
548
7
156
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_translate_ethosu_copy
test_translate_ethosu_copy
595
661
595
595
8e1b8ab5652d7493fae294ef4f57befbb4298a95
bigcode/the-stack
train
ce78898f07879163d17e6955
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseAdd: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer( placeholder, [270], dty...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseAdd: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer( placeholder, [270], dtype="int8", elem_offset=0, align=128, offset_factor=1 ) ethosu_w...
Op.NONE_OR_RELU assert npu_op.activation.min == 10 assert npu_op.activation.max == 100 # Compare rounding mode assert npu_op.rounding_mode == vapi.NpuRoundingMode.TFL # Compare ifm upscaling assert npu_op.ifm_upscale == vapi.NpuResamplingMode.NONE # fmt: off """A ethosu_binary_elementwise ADD ...
123
123
413
23
100
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseAdd
SingleEthosuBinaryElementwiseAdd
1,059
1,074
1,059
1,061
d48969a367b6b83eb0216feaf14c85c6479305fe
bigcode/the-stack
train
d269a96866b4164aa0dad949
train
function
def test_buffer_info_extraction(): test_cases = [ { # Stimulus "tir_module": SingleEthosUConv2D, "param_dict": { tvm.tir.Var("placeholder_4", "uint8"): np.random.randint( np.iinfo("uint8").min, np.iinfo("uint8").max, [1, 1, 3, 16], "uin...
def test_buffer_info_extraction():
test_cases = [ { # Stimulus "tir_module": SingleEthosUConv2D, "param_dict": { tvm.tir.Var("placeholder_4", "uint8"): np.random.randint( np.iinfo("uint8").min, np.iinfo("uint8").max, [1, 1, 3, 16], "uint8" ), ...
tern("ethosu_conv2d", "int8", 16, 16, 16, 16, 0, 16, T.load("int8", ethosu_write_1, 0), 0, 0, 0, T.float32(0.5), 10, "NHWC", 256, 16, 1, "int8", 16, 16, 2, 16, 0, 16, T.load("int8", ethosu_write.data, 6), 0, 0, 0, T.float32(0.25), 14, "NHWC", 128, 8, 1, 1, 1, 1, 1, 1, 1, T.load("uint8", placeholder_global, 0), 80, 12, ...
252
252
842
7
244
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_buffer_info_extraction
test_buffer_info_extraction
181
263
181
181
bc60bffc955a50102ca82ef3341ed7482ab4e621
bigcode/the-stack
train
0524d5ce2626376dc9bc8f28
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMulBroadcasting: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMulBroadcasting: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [27], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffer...
, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "SUB", 1, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise MUL with broadcasting tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseMulBroadcasting: @T.prim...
122
122
409
25
97
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseMulBroadcasting
SingleEthosuBinaryElementwiseMulBroadcasting
1,309
1,319
1,309
1,311
b66606c307254dc814bb69dfdd8159fea2b22d03
bigcode/the-stack
train
9218eaf0e479b2dfee7fbca3
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMax: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", el...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMax: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffe...
_2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "MIN", 0, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise Max tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseMax: @T.prim_func
121
121
406
23
98
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseMax
SingleEthosuBinaryElementwiseMax
1,126
1,136
1,126
1,128
a44488312c661819cc64a97ce5ca9b3c21598a53
bigcode/the-stack
train
923e51f659ebbff2fe9a7e24
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMin: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", el...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseMin: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffe...
2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "MUL", 0, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise MIN tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseMin: @T.prim_func
121
121
406
23
98
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseMin
SingleEthosuBinaryElementwiseMin
1,110
1,120
1,110
1,112
59e808aa14878683177321cb873bbd45d2c6ba04
bigcode/the-stack
train
6d1c310db985a46d25b4a006
train
class
@tvm.script.ir_module class MixedConstantDatatypes: @T.prim_func def main(placeholder_4: T.Buffer[(1, 8, 16, 16), "int8"], ethosu_write_1: T.Buffer[(1, 1, 1, 16), "int8"]) -> None: buffer = T.buffer_var("uint8", "") buffer_1 = T.buffer_var("uint8", "") buffer_2 = T.buffer_var("int16", ""...
@tvm.script.ir_module class MixedConstantDatatypes: @T.prim_func
def main(placeholder_4: T.Buffer[(1, 8, 16, 16), "int8"], ethosu_write_1: T.Buffer[(1, 1, 1, 16), "int8"]) -> None: buffer = T.buffer_var("uint8", "") buffer_1 = T.buffer_var("uint8", "") buffer_2 = T.buffer_var("int16", "") # function attr dict T.func_attr({"from_legacy_te_s...
max, [8], "int32"), }, # Reference outputs "ref": [ { "src": "placeholder_4", "dest": "placeholder_global", "length": 256, }, { "src": "placeholder_5", ...
256
256
907
20
235
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
MixedConstantDatatypes
MixedConstantDatatypes
665
687
665
667
b4b757019dadd8f0d3de7a7c27fe2ba734aaadfb
bigcode/the-stack
train
1840082774ea277d1d98a4b9
train
class
@tvm.script.ir_module class MultiEthosUCopy: @T.prim_func def main(placeholder_3: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_conv2d_1: T.Buffer[(1, 16, 16, 8), "int8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_5 = T.buffer_var("...
@tvm.script.ir_module class MultiEthosUCopy: @T.prim_func
def main(placeholder_3: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_conv2d_1: T.Buffer[(1, 16, 16, 8), "int8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_5 = T.buffer_var("uint8", "") placeholder_4 = T.buffer_var("uint8", "") ...
25), 14, "NHWC", 64, 8, 1, 1, 1, 1, 1, 1, 1, T.load("uint8", placeholder_9, 0), 0, 12, T.load("uint8", placeholder_5, 0), 0, 0, 0, 0, 0, "CLIP", 0, 255, "TFL", "NONE", dtype="uint8")) # fmt: on # fmt: off """A sample tir test case with copy operations for translator""" @tvm.script.ir_module class MultiEthosUCopy: ...
148
148
494
21
127
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
MultiEthosUCopy
MultiEthosUCopy
70
83
70
72
5940f9b2a67d2909311f04c000c04a15d1f57e35
bigcode/the-stack
train
a8da8280b733e391025d591f
train
class
@tvm.script.ir_module class MixedRead: @T.prim_func def main(placeholder: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_write: T.Buffer[(1, 16, 16, 8), "int8"]) -> None: buffer = T.buffer_var("uint8", "") buffer_1 = T.buffer_var("uint8", "") buffer_2 = T.buffer_var("uint8", "") buffe...
@tvm.script.ir_module class MixedRead: @T.prim_func
def main(placeholder: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_write: T.Buffer[(1, 16, 16, 8), "int8"]) -> None: buffer = T.buffer_var("uint8", "") buffer_1 = T.buffer_var("uint8", "") buffer_2 = T.buffer_var("uint8", "") buffer_3 = T.buffer_var("uint8", "") buffer_4 = T.buf...
16, 0, 16, T.load("int8", placeholder.data, 0), 0, 0, 0, T.float32(0.5), 10, "NHWC", 512, 32, 1, "int8", 16, 16, 2, 16, 0, 16, T.load("int8", ethosu_write.data, 6), 0, 0, 0, T.float32(0.25), 14, "NHWC", 128, 8, 1, 1, 1, 1, 1, 1, 1, T.load("uint8", placeholder_global, 0), 112, 12, T.load("uint8", placeholder_d_global, 0...
256
256
1,957
18
238
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
MixedRead
MixedRead
133
177
133
135
823a77e876231545bf1e0a4b3c851cbbb35bd3da
bigcode/the-stack
train
d845a66848949d721eb4f96b
train
class
@tvm.script.ir_module class SingleEthosuBinaryElementwiseSub: @T.prim_func def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", el...
@tvm.script.ir_module class SingleEthosuBinaryElementwiseSub: @T.prim_func
def main(placeholder: T.handle, ethosu_write: T.handle) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_2 = T.match_buffer(placeholder, [270], dtype="int8", elem_offset=0, align=128, offset_factor=1) ethosu_write_2 = T.match_buffe...
_2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "ADD", 0, "CLIP", 10, 100, "TFL", dtype="int8")) __tvm_meta__ = None # fmt: on # fmt: off """A ethosu_binary_elementwise SUB tir testcase for the translator""" @tvm.script.ir_module class SingleEthosuBinaryElementwiseSub: @T.prim_func
121
121
406
23
98
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosuBinaryElementwiseSub
SingleEthosuBinaryElementwiseSub
1,079
1,089
1,079
1,081
be307daf38fdc985c7bc03adc36fe5afff559d5c
bigcode/the-stack
train
8923fd95061fcb956c4aed42
train
class
@tvm.script.ir_module class MultiEthosUConv2D: @T.prim_func def main(placeholder_6: T.Buffer[(1, 8, 8, 3), "int8"], ethosu_conv2d_1: T.Buffer[(1, 8, 8, 8), "int8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_9 = T.buffer_var("uin...
@tvm.script.ir_module class MultiEthosUConv2D: @T.prim_func
def main(placeholder_6: T.Buffer[(1, 8, 8, 3), "int8"], ethosu_conv2d_1: T.Buffer[(1, 8, 8, 8), "int8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_9 = T.buffer_var("uint8", "") placeholder_7 = T.buffer_var("uint8", "") ...
8, T.load("uint8", placeholder_3.data, 0), 0, 0, 0, T.float32(0.5), 10, "NHWC", 24, 3, 1, "uint8", 8, 8, 16, 8, 0, 8, T.load("uint8", ethosu_conv2d_1.data, 0), 0, 0, 0, T.float32(0.25), 14, "NHWC", 128, 16, 1, 1, 1, 1, 1, 1, 1, T.load("uint8", placeholder_4, 0), 0, 12, T.load("uint8", placeholder_5, 0), 0, 0, 0, 0, 0,...
256
256
1,177
23
233
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
MultiEthosUConv2D
MultiEthosUConv2D
48
64
48
50
cb08a16c946e9bbe0174f8b521f54d543de0c5c6
bigcode/the-stack
train
046308bfcde6cddbc006222c
train
function
@pytest.mark.parametrize("operator_type", ["ADD", "SUB", "MUL", "MIN", "MAX", "SHR", "SHL"]) def test_translate_ethosu_binary_elementwise_broadcasting(operator_type): if operator_type == "SHR" or operator_type == "SHL": data_type = vapi.NpuDataType.INT32 data_type_bytes = 4 else: data_ty...
@pytest.mark.parametrize("operator_type", ["ADD", "SUB", "MUL", "MIN", "MAX", "SHR", "SHL"]) def test_translate_ethosu_binary_elementwise_broadcasting(operator_type):
if operator_type == "SHR" or operator_type == "SHL": data_type = vapi.NpuDataType.INT32 data_type_bytes = 4 else: data_type = vapi.NpuDataType.INT8 data_type_bytes = 1 def extract_ethosu_binary_elementwise_broadcasting_call_extern(mod): # There should only be a singl...
, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "int32", 1, 3, 1, 1, 0, 3, T.load("int32", placeholder_2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 1, 1, 1, "int32", 2, 3, 4, 2, 0, 3, T.load("int32", ethosu_write_2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 12, 4, 1, "SHL", 1, "CLIP", 10, 100, "TFL", dtype="int32"))...
256
256
1,558
45
210
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_translate_ethosu_binary_elementwise_broadcasting
test_translate_ethosu_binary_elementwise_broadcasting
1,387
1,491
1,387
1,388
b533c3dadc2aa9bf8cec1e424397bfeff3f1adbb
bigcode/the-stack
train
d6363d20583de5e033593991
train
function
def test_translate_ethosu_depthwise_conv2d(): def extract_ethosu_depthwise_conv2d_extern_call(mod): # There should only be a single function assert len(mod.functions.items()) == 1 primfunc = mod.functions.items()[0][1] ethosu_depthwise_conv2d_calls = list() def populate_eth...
def test_translate_ethosu_depthwise_conv2d():
def extract_ethosu_depthwise_conv2d_extern_call(mod): # There should only be a single function assert len(mod.functions.items()) == 1 primfunc = mod.functions.items()[0][1] ethosu_depthwise_conv2d_calls = list() def populate_ethosu_depthwise_conv2d_calls(stmt): ...
8", 8, 8, 3, 8, 0, 8, T.load("int8", placeholder_3.data, 0), 0, 0, 0, T.float32(0.6), 11, "NHWC", 24, 3, 1, "int8", 6, 7, 3, 6, 0, 7, T.load("int8", ethosu_depthwise_conv2d_1.data, 0), 0, 0, 0, T.float32(0.26), 15, "NHWC", 21, 3, 1, 2, 3, 1, 1, 1, 1, T.load("int8", placeholder_4.data, 0), 18, 13, T.load("uint8", placeh...
256
256
938
11
244
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_translate_ethosu_depthwise_conv2d
test_translate_ethosu_depthwise_conv2d
536
592
536
536
4e1491978ad0e86d3b17daaeb183bf847d9ce941
bigcode/the-stack
train
bfe51b187a3823a4daaf2200
train
class
@tvm.script.ir_module class SingleEthosUConv2D: @T.prim_func def main(placeholder_3: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_conv2d_1: T.Buffer[(1, 8, 8, 16), "int8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_4 = T.buffer_var...
@tvm.script.ir_module class SingleEthosUConv2D: @T.prim_func
def main(placeholder_3: T.Buffer[(1, 16, 16, 32), "int8"], ethosu_conv2d_1: T.Buffer[(1, 8, 8, 16), "int8"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) placeholder_4 = T.buffer_var("uint8", "") placeholder_5 = T.buffer_var("uint8", "") ...
.importorskip("ethosu.vela") import numpy as np import tvm from tvm.tir import stmt_functor from tvm.script import tir as T from tvm.relay.backend.contrib.ethosu import tir_to_cs_translator from tvm.relay.backend.contrib.ethosu import util import ethosu.vela.api as vapi # fmt: off """A sample tir test case for trans...
112
112
375
23
89
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
SingleEthosUConv2D
SingleEthosUConv2D
33
42
33
35
65f2c910d9f5fee0f56c95cf06d0872742e6b3ff
bigcode/the-stack
train
642550faac490a0581187a8d
train
function
@pytest.mark.parametrize("operator_type", ["ADD", "SUB", "MUL", "MIN", "MAX", "SHR", "SHL"]) def test_translate_ethosu_binary_elementwise(operator_type): if operator_type == "SHR" or operator_type == "SHL": data_type = vapi.NpuDataType.INT32 data_type_bytes = 4 else: data_type = vapi.Npu...
@pytest.mark.parametrize("operator_type", ["ADD", "SUB", "MUL", "MIN", "MAX", "SHR", "SHL"]) def test_translate_ethosu_binary_elementwise(operator_type):
if operator_type == "SHR" or operator_type == "SHL": data_type = vapi.NpuDataType.INT32 data_type_bytes = 4 else: data_type = vapi.NpuDataType.INT8 data_type_bytes = 1 def extract_ethosu_binary_elementwise_call_extern(mod): # There should only be a single function ...
), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "int32", 5, 9, 3, 5, 0, 9, T.load("int32", placeholder_2.data, 135), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "int32", 5, 9, 3, 5, 0, 9, T.load("int32", ethosu_write_2.data, 0), 0, 0, 0, T.float32(1.0), 0, "NHWC", 27, 3, 1, "SHL", 0, "CLIP", 10, 100, "TFL", dtype="i...
256
256
1,531
42
213
cli99/tvm
tests/python/contrib/test_ethosu/test_tir_to_cs_translator.py
Python
test_translate_ethosu_binary_elementwise
test_translate_ethosu_binary_elementwise
1,172
1,274
1,172
1,173
0906a84166e2d3af08a07bb983fc805739e7f604
bigcode/the-stack
train
78e0282fe1e0f21b1e53f20d
train
class
class TestStorageCloudBucketFacets(unittest.TestCase): """StorageCloudBucketFacets unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test StorageCloudBucketFacets include_option is a boolean, when False ...
class TestStorageCloudBucketFacets(unittest.TestCase):
"""StorageCloudBucketFacets unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test StorageCloudBucketFacets include_option is a boolean, when False only required params are included, when Tru...
um.io Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import datetime import nodeum_sdk from nodeum_sdk.models.storage_cloud_bucket_facets import StorageCloudBucketFacets # noqa: E501 from nodeum_sdk.rest import ApiException class TestStorageCloudBucketFa...
77
77
259
11
65
nodeum-io/nodeum-sdk-python
test/test_storage_cloud_bucket_facets.py
Python
TestStorageCloudBucketFacets
TestStorageCloudBucketFacets
23
57
23
23
b914b214208d45c42e85e2b62581cda6491a3d1c
bigcode/the-stack
train
6c2a153a93a6fc8edeb1781c
train
class
@paramunittest.parametrized(*login_xls) class Login(unittest.TestCase): def setParameters(self, case_name, method, token, email, password, result, code, msg): """ set params :param case_name: :param method: :param token: :param email: :param password:...
@paramunittest.parametrized(*login_xls) class Login(unittest.TestCase):
def setParameters(self, case_name, method, token, email, password, result, code, msg): """ set params :param case_name: :param method: :param token: :param email: :param password: :param result: :param code: :param msg: ...
import unittest import paramunittest import readConfig as readConfig from common import Log as Log from common import common from common import configHttp as ConfigHttp login_xls = common.get_xls("userCase.xlsx", "login") localReadConfig = readConfig.ReadConfig() configHttp = ConfigHttp.ConfigHttp() info = {...
89
219
732
17
72
liberjiang/interface_framework
interfaceTest/testCase/user/testLogin.py
Python
Login
Login
14
124
14
15
daea98f5f3f376fe4451c8245f010120909f1107
bigcode/the-stack
train
047ed3eaed95bf45fd50a37f
train
class
class MalwareSubjectReference(maec.Entity): _binding = package_binding _binding_class = package_binding.MalwareSubjectReferenceType _namespace = _namespace malware_subject_idref = fields.TypedField("malware_subject_idref") def __init__(self, malware_subject_idref = None): super(MalwareSubj...
class MalwareSubjectReference(maec.Entity):
_binding = package_binding _binding_class = package_binding.MalwareSubjectReferenceType _namespace = _namespace malware_subject_idref = fields.TypedField("malware_subject_idref") def __init__(self, malware_subject_idref = None): super(MalwareSubjectReference, self).__init__() self....
# MAEC Malware Subject Reference Class # Copyright (c) 2015, The MITRE Corporation # All rights reserved from mixbox import fields import maec from . import _namespace import maec.bindings.maec_package as package_binding class MalwareSubjectReference(maec.Entity):
63
64
92
8
54
colbyprior/python-maec
maec/package/malware_subject_reference.py
Python
MalwareSubjectReference
MalwareSubjectReference
12
21
12
12
8ad6a1b08e8f5a40cbc37f492e4f9a4a7bb6f240
bigcode/the-stack
train
e1f3fe751eb697b99afd13ad
train
class
class MenuInfo(models.Model): category = models.CharField(max_length=20) name = models.CharField(max_length=20, unique=True) price = models.FloatField() stock = models.IntegerField() ingredient = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=400, blank=Tr...
class MenuInfo(models.Model):
category = models.CharField(max_length=20) name = models.CharField(max_length=20, unique=True) price = models.FloatField() stock = models.IntegerField() ingredient = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=400, blank=True) onSale = models.Boolea...
from django.db import models # Create your models here. class MenuInfo(models.Model):
18
64
119
6
12
IrisNotSiri/yayaTest
api/yaya_backend/menu/models.py
Python
MenuInfo
MenuInfo
5
14
5
5
c4a6e766274e4ff03b3f4ab92f1b9b1257d1870c
bigcode/the-stack
train
bfe2267d5daf1100bbf869cf
train
class
class FromBlockParams(NamedTuple): slot: Slot = None
class FromBlockParams(NamedTuple):
slot: Slot = None
Root for Merkle tree root of SignedSerializable # Merkle tree root with signature field included HashTreeRoot = NewType("HashTreeRoot", Hash32) # Merkle tree root with signature field excluded SigningRoot = NewType("SigningRoot", Hash32) class FromBlockParams(NamedTuple):
64
64
15
8
56
renaynay/trinity
eth2/beacon/typing.py
Python
FromBlockParams
FromBlockParams
33
34
33
33
ba0c537bd7906bc0a1e93d77d2ed24810f38c0af
bigcode/the-stack
train
d77221d989fa881f35127f2b
train
class
class ModelTests(TestCase): def test_create_user_with_email_successful(self): """Test Creating a new user with an email is successful""" email = 'test@gmail.com' password = 'Testpass123' user = get_user_model().objects.create_user( email=email, password=passw...
class ModelTests(TestCase):
def test_create_user_with_email_successful(self): """Test Creating a new user with an email is successful""" email = 'test@gmail.com' password = 'Testpass123' user = get_user_model().objects.create_user( email=email, password=password ) self.a...
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@gmail.com', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password) class ModelTests(TestC...
67
147
492
6
61
JDHDEV/recipe-app-api
app/core/tests/test_models.py
Python
ModelTests
ModelTests
14
87
14
15
2f5b1e4d7a5f70da9d23785e45764cd42595a065
bigcode/the-stack
train
d0229fba9c14ebe44cb934e5
train
function
def sample_user(email='test@gmail.com', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password)
def sample_user(email='test@gmail.com', password='testpass'):
"""Create a sample user""" return get_user_model().objects.create_user(email, password)
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@gmail.com', password='testpass'):
41
64
34
14
26
JDHDEV/recipe-app-api
app/core/tests/test_models.py
Python
sample_user
sample_user
9
11
9
9
11b619586b8842fc0e32d9475287ee5728a38af1
bigcode/the-stack
train
33a98ea6a9f256d47e90bc14
train
function
def parse_ssl_cert_reqs(query_value): # type: (str) -> Any """Given the query parameter for ssl_cert_reqs, return the SSL constant or None.""" if ssl_available: query_value_to_constant = { 'CERT_REQUIRED': ssl.CERT_REQUIRED, 'CERT_OPTIONAL': ssl.CERT_OPTIONAL, 'CE...
def parse_ssl_cert_reqs(query_value): # type: (str) -> Any
"""Given the query parameter for ssl_cert_reqs, return the SSL constant or None.""" if ssl_available: query_value_to_constant = { 'CERT_REQUIRED': ssl.CERT_REQUIRED, 'CERT_OPTIONAL': ssl.CERT_OPTIONAL, 'CERT_NONE': ssl.CERT_NONE, 'required': ssl.CERT_REQUI...
Any, str) -> Any """Sanitize url, or do nothing if url undefined.""" if isinstance(url, str) and '://' in url: return sanitize_url(url, mask) return url def parse_ssl_cert_reqs(query_value): # type: (str) -> Any
64
64
129
19
44
kaiix/kombu
kombu/utils/url.py
Python
parse_ssl_cert_reqs
parse_ssl_cert_reqs
114
128
114
115
bb0558e5783bc9b5bf0ba5a66a67750e49825685
bigcode/the-stack
train