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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2fc21dfac6715c557172f7b5 | train | function | def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in ... | def post(url, data=None, json=None, **kwargs):
| r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*... | Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault("allow_redirects", False)
return request("head", url, **kwargs)
def post(url, data=None, json=None, **kwargs):
| 64 | 64 | 149 | 13 | 51 | aitoehigie/britecore_flask | venv/lib/python3.6/site-packages/requests/api.py | Python | post | post | 104 | 116 | 104 | 104 | 3d2c1af03738c988a37139feedcd8795f72fcd0f | bigcode/the-stack | train |
eb293f1af0d466e7ec025570 | train | function | def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :cla... | def request(method, url, **kwargs):
| """Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :class:`Request`.
:param data: (opti... | # -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
| 63 | 208 | 694 | 9 | 53 | aitoehigie/britecore_flask | venv/lib/python3.6/site-packages/requests/api.py | Python | request | request | 16 | 60 | 16 | 16 | f672e2eaa5da7db85e2443eab8566129640cc25e | bigcode/the-stack | train |
b884283ed575daa970854459 | train | function | def put(url, data=None, **kwargs):
r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of t... | def put(url, data=None, **kwargs):
| r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\... | :param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request("post", url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
| 64 | 64 | 143 | 10 | 54 | aitoehigie/britecore_flask | venv/lib/python3.6/site-packages/requests/api.py | Python | put | put | 119 | 131 | 119 | 119 | b4fba8251607fcfccf5e5c4646ee357e35dd8fe2 | bigcode/the-stack | train |
a6b284f782b88fd1e3fcda5e | train | function | def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return... | def get(url, params=None, **kwargs):
| r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object... | , thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
def get(url, params=None, **kwargs):
| 64 | 64 | 126 | 10 | 54 | aitoehigie/britecore_flask | venv/lib/python3.6/site-packages/requests/api.py | Python | get | get | 63 | 75 | 63 | 63 | 629bfda45b5e185feb1236fca5821193062b6f4c | bigcode/the-stack | train |
b39e27d60ea6bdb111f0f4d0 | train | function | def patch(url, data=None, **kwargs):
r"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body ... | def patch(url, data=None, **kwargs):
| r"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \... | Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request("put", url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
| 64 | 64 | 143 | 10 | 54 | aitoehigie/britecore_flask | venv/lib/python3.6/site-packages/requests/api.py | Python | patch | patch | 134 | 146 | 134 | 134 | 6798e838f892d155791fdd1415625c22c0f59b56 | bigcode/the-stack | train |
94f77bb7fb7aae0278bd397e | train | function | def head(url, **kwargs):
r"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault("allow_redirects", False)
r... | def head(url, **kwargs):
| r"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault("allow_redirects", False)
return request("head", url... | param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault("allow_redirects", True)
return request("options", url, **kwargs)
def head(url, **kwargs):
| 64 | 64 | 91 | 7 | 57 | aitoehigie/britecore_flask | venv/lib/python3.6/site-packages/requests/api.py | Python | head | head | 91 | 101 | 91 | 91 | 1da904b30395014aea691d557340f5e4c89064d1 | bigcode/the-stack | train |
91c4e97650742374a2ab4ee1 | train | function | def options(url, **kwargs):
r"""Sends an OPTIONS request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault("allow_redirects", True)... | def options(url, **kwargs):
| r"""Sends an OPTIONS request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault("allow_redirects", True)
return request("options... | *kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault("allow_redirects", True)
return request("get", url, params=params, **kwargs)
def options(url, **kwargs):
| 64 | 64 | 91 | 7 | 57 | aitoehigie/britecore_flask | venv/lib/python3.6/site-packages/requests/api.py | Python | options | options | 78 | 88 | 78 | 78 | 2b09eca963b535d0d4ef8a046bca9d84669651f1 | bigcode/the-stack | train |
e1dc4f881d7f4863ad100d63 | train | class | class Visual(object):
"""The Visual class has similar behavior compare to a function closure
The Visual class saves the visualizing function, arguments, and
keyworded arguments together so that a "visual" can be redrawn.
Its behavior is very similar to a function closure. The only
difference is th... | class Visual(object):
| """The Visual class has similar behavior compare to a function closure
The Visual class saves the visualizing function, arguments, and
keyworded arguments together so that a "visual" can be redrawn.
Its behavior is very similar to a function closure. The only
difference is that the arguments and k... | # Copyright (C) 2017--2019 Lia Medeiros & Chi-kwan Chan
# Copyright (C) 2017--2019 Steward Observatory
#
# This file is part of ehtplot.
#
# ehtplot is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either versi... | 250 | 256 | 1,298 | 4 | 245 | zzpwahaha/VimbaCamJILA | VimbaCam/ColorMap/ehtplot/build/lib/ehtplot/visual.py | Python | Visual | Visual | 34 | 193 | 34 | 34 | 05945b1fec037147a95e0167aaefa34ec36eb50f | bigcode/the-stack | train |
e05fa678df9ed910c77c6da5 | train | function | def main():
N = int(input())
for i in range(N, 0, -1):
print("*" * i)
| def main():
| N = int(input())
for i in range(N, 0, -1):
print("*" * i)
| def main():
| 3 | 64 | 29 | 3 | 0 | jaeheeLee17/BOJ_Algorithms | Level3_ForStatements/2440.py | Python | main | main | 1 | 4 | 1 | 1 | c2c18a3778a497ff7c0c2dd0bd772ad41d61490f | bigcode/the-stack | train |
efa834edf42c27068d1eb300 | train | class | class DataLakeStoreAccountProperties(Model):
"""
Data Lake Store account properties information
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar provisioning_state: Gets the status of the Data Lake Store account
while being provisioned. Possible va... | class DataLakeStoreAccountProperties(Model):
| """
Data Lake Store account properties information
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar provisioning_state: Gets the status of the Data Lake Store account
while being provisioned. Possible values include: 'Failed', 'Creating',
'Run... | , Version 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" BA... | 162 | 162 | 541 | 8 | 153 | HydAu/AzureSDKForPython | azure-mgmt-datalake-store/azure/mgmt/datalake/store/account/models/data_lake_store_account_properties.py | Python | DataLakeStoreAccountProperties | DataLakeStoreAccountProperties | 25 | 76 | 25 | 25 | 01bf913b3a68346e986eee45971185a208d14837 | bigcode/the-stack | train |
9c85382b17bafdcd81787534 | train | class | class gnomAD:
def __init__(self,
masterfiles: Union[str,List],
namedexfile : str,
folder: str = 'gNOMAD',
store_in_memory: bool = False):
"""
Instantiation starts the settings. But the settings can be changed.
``split`` spl... | class gnomAD:
| def __init__(self,
masterfiles: Union[str,List],
namedexfile : str,
folder: str = 'gNOMAD',
store_in_memory: bool = False):
"""
Instantiation starts the settings. But the settings can be changed.
``split`` splits the file in... | in veps]
def to_dict(self) -> Dict:
return self.__dict__
@classmethod
def from_line(cls, line: str):
"""
This takes one millisecond per line.
:param line:
:return:
"""
multidata = cls.parse_line(line)
variant = []
for data in multida... | 256 | 256 | 990 | 5 | 250 | CMD-Oxford/MichelaNGLo-protein-module | michelanglo_protein/generate/split_gnomAD.py | Python | gnomAD | gnomAD | 81 | 182 | 81 | 82 | 21edc03a71aa021726ad5e475cc2d41b4f90fbef | bigcode/the-stack | train |
0706a05a000235be9ad2f68a | train | class | class gnomADVariant:
"""This is the same as the namedtuple but with more stuff. It does not get written. to_dict does."""
def __init__(self, symbol: str, identifier: str, from_residue: str, residue_index: Union[str, int], to_residue: str, impact: str, count: int, homozygous: int):
self.symbol = symbol
... | class gnomADVariant:
| """This is the same as the namedtuple but with more stuff. It does not get written. to_dict does."""
def __init__(self, symbol: str, identifier: str, from_residue: str, residue_index: Union[str, int], to_residue: str, impact: str, count: int, homozygous: int):
self.symbol = symbol
self.id = iden... | __doc__ = """
This script is actually independent of settings.
Entry point: ``gnomAD().split().write()``
"""
import os, time
import gzip
import json
from pprint import PrettyPrinter
pprint = PrettyPrinter().pprint
from collections import defaultdict, namedtuple
from typing import Union, Dict, List
from warnings im... | 82 | 256 | 907 | 6 | 75 | CMD-Oxford/MichelaNGLo-protein-module | michelanglo_protein/generate/split_gnomAD.py | Python | gnomADVariant | gnomADVariant | 20 | 79 | 20 | 20 | 24cceae3996a3bb760e411c7044eda24eaaac40c | bigcode/the-stack | train |
098b11399763ed4e20954ccc | train | class | class enum_dyn(BaseEnumDyn):
##################################################
## CHEETAH GENERATED METHODS
def __init__(self, *args, **KWs):
super(enum_dyn, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = '... | class enum_dyn(BaseEnumDyn):
##################################################
## CHEETAH GENERATED METHODS
| def __init__(self, *args, **KWs):
super(enum_dyn, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
if k i... | SL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '3.2.6.post2'
__CHEETAH_versionTuple__ = (3, 2, 6, 'post', 2)
__CHEETAH_genTime__ = 1649276667.9655128
__CHEETAH_genTimestamp__ = 'Wed Apr 6 16:24:27 2022'
__CHEETAH_src__ = '_enum_dyn.tmpl'
__CHEETAH_sr... | 256 | 256 | 2,431 | 18 | 237 | Amourspirit/ooo_uno_tmpl | template/_enum_dyn.py | Python | enum_dyn | enum_dyn | 52 | 256 | 52 | 57 | d92bcb58fa232cb26eeda38cea666f5c4df6982f | bigcode/the-stack | train |
bdbab902b5113913dbae63d2 | train | class | class ImageReference(Model):
"""The image reference.
:param publisher: Publisher of the image.
:type publisher: str
:param offer: Offer of the image.
:type offer: str
:param sku: SKU of the image.
:type sku: str
:param version: Version of the image.
:type version: str
"""
_... | class ImageReference(Model):
| """The image reference.
:param publisher: Publisher of the image.
:type publisher: str
:param offer: Offer of the image.
:type offer: str
:param sku: SKU of the image.
:type sku: str
:param version: Version of the image.
:type version: str
"""
_validation = {
'publi... | .
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# ------------------------------------------------------------------------... | 68 | 68 | 228 | 5 | 62 | v-Ajnava/azure-sdk-for-python | azure-mgmt-batchai/azure/mgmt/batchai/models/image_reference.py | Python | ImageReference | ImageReference | 15 | 45 | 15 | 15 | 6f7b60533f84b11750acd25ab1fdf3cb8d073abf | bigcode/the-stack | train |
69b234e6ccc6b0f111390cd8 | train | class | class Migration(migrations.Migration):
dependencies = [
('crowdsourcing', '0013_auto_20151221_2208'),
]
operations = [
migrations.AlterField(
model_name='task',
name='data',
field=django.contrib.postgres.fields.jsonb.JSONField(null=True),
),
... | class Migration(migrations.Migration):
| dependencies = [
('crowdsourcing', '0013_auto_20151221_2208'),
]
operations = [
migrations.AlterField(
model_name='task',
name='data',
field=django.contrib.postgres.fields.jsonb.JSONField(null=True),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-24 01:34
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
| 59 | 64 | 70 | 7 | 51 | AKSHANSH47/crowdsource-platform2 | crowdsourcing/migrations/0014_auto_20151224_0134.py | Python | Migration | Migration | 9 | 21 | 9 | 10 | 830fb75c732a69963e09957670a46d85f056c283 | bigcode/the-stack | train |
8b405adaad7eb7da908184b5 | train | class | class Player:
id = ""
name = ""
role = ""
battingStyle = ""
bowlingStyle = ""
country = ""
battingInfo = {}
bowlingInfo = {}
isDeleted = False
# Author : Deepak Terse
# Return nothing
# Args player dictionary
def __init__(self, player):
self.id = player["id"]... | class Player:
| id = ""
name = ""
role = ""
battingStyle = ""
bowlingStyle = ""
country = ""
battingInfo = {}
bowlingInfo = {}
isDeleted = False
# Author : Deepak Terse
# Return nothing
# Args player dictionary
def __init__(self, player):
self.id = player["id"]
self.... | 17 July 2019
Modified At : 21 July 2019
Description : Class definition for model Player
"""
import json
from app import app
import os
# Author : Deepak Terse
# This is class of Bowler with __init__ function to add new player
class Player:
| 64 | 64 | 131 | 3 | 60 | deepak-sankey/python-design-patterns | app/models/player.py | Python | Player | Player | 14 | 34 | 14 | 14 | 3d72691fe488a978559850a909904644e632dece | bigcode/the-stack | train |
7586007fe2dc6f9ac6b03fbe | train | function | def main():
for folder in tqdm(glob(DATASET_LOCATION + '/*'), desc='Creating Variants'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
generate_variant(img_path, *get_background())
| def main():
| for folder in tqdm(glob(DATASET_LOCATION + '/*'), desc='Creating Variants'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
generate_variant(img_path, *get_background())
| 0, 2))
def get_background():
background = (randint(110, 255), randint(110, 255), randint(110, 255))
prefix = reduce(lambda x, y: str(x) + '_' +str(y), background)
return background, prefix
def main():
| 64 | 64 | 53 | 3 | 60 | Ankurvish06/hand | generate_dataset.py | Python | main | main | 44 | 48 | 44 | 44 | b02aab6ab454257aba65f766e1a1c67a202a5b9e | bigcode/the-stack | train |
b00d6875c2430b481f8b72a3 | train | function | def delete_orig_image():
for folder in tqdm(glob(DATASET_LOCATION + '/*'), desc='Deleting Original Images'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
os.remove(img_path)
| def delete_orig_image():
| for folder in tqdm(glob(DATASET_LOCATION + '/*'), desc='Deleting Original Images'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
os.remove(img_path)
| Images'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
img_file = cv2.imread(img_path)
cv2.imwrite(img_path, cv2.resize(img_file, None, fx=0.025, fy=0.025))
def delete_orig_image():
| 64 | 64 | 52 | 5 | 59 | Ankurvish06/hand | generate_dataset.py | Python | delete_orig_image | delete_orig_image | 57 | 61 | 57 | 57 | 26d050183e706c44e50ce8da792372ef46ade1e0 | bigcode/the-stack | train |
1bc1fe0fe69657e326d134ec | train | function | def blur_image(img):
return img # cv2.GaussianBlur(img, (3, 7), randint(0, 2))
| def blur_image(img):
| return img # cv2.GaussianBlur(img, (3, 7), randint(0, 2))
| , bg_img)
# variant_gray = cv2.cvtColor(variant_wbg, cv2.COLOR_BGR2GRAY)
# blur the image
variant_blurred = blur_image(mask)
# save variant image
save_variant(variant_blurred, img_path, prefix)
def blur_image(img):
| 64 | 64 | 30 | 5 | 59 | Ankurvish06/hand | generate_dataset.py | Python | blur_image | blur_image | 36 | 37 | 36 | 36 | c988f5514b61008491ca9404780a34430ea7077d | bigcode/the-stack | train |
4db636b72d390a81dca6c3d5 | train | function | def save_variant(variant, img_path, prefix):
new_img_file_path = os.path.join(os.path.dirname(img_path), prefix + '_' + os.path.basename(img_path))
cv2.imwrite(new_img_file_path, variant)
| def save_variant(variant, img_path, prefix):
| new_img_file_path = os.path.join(os.path.dirname(img_path), prefix + '_' + os.path.basename(img_path))
cv2.imwrite(new_img_file_path, variant)
| from glob import glob
import os
import shutil
import cv2
from random import randint
from tqdm import tqdm
from functools import reduce
DATASET_LOCATION = '/home/aspire/Downloads/RBL/English/Hnd/Img'
def save_variant(variant, img_path, prefix):
| 61 | 64 | 47 | 11 | 50 | Ankurvish06/hand | generate_dataset.py | Python | save_variant | save_variant | 12 | 14 | 12 | 12 | 9bdf0ebfd6110657e2315600054b5ebddba1d469 | bigcode/the-stack | train |
be46d370ace07428e3268bd4 | train | function | def resize_all():
for folder in tqdm(glob(DATASET_LOCATION + '/*'), desc='Resizing Images'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
img_file = cv2.imread(img_path)
cv2.imwrite(img_path, cv2.resize(img_file, None, fx=0.025, fy=0.025))... | def resize_all():
| for folder in tqdm(glob(DATASET_LOCATION + '/*'), desc='Resizing Images'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
img_file = cv2.imread(img_path)
cv2.imwrite(img_path, cv2.resize(img_file, None, fx=0.025, fy=0.025))
| )
return background, prefix
def main():
for folder in tqdm(glob(DATASET_LOCATION + '/*'), desc='Creating Variants'):
if os.path.isdir(folder):
for img_path in glob(folder + '/img*.png'):
generate_variant(img_path, *get_background())
def resize_all():
| 64 | 64 | 81 | 4 | 60 | Ankurvish06/hand | generate_dataset.py | Python | resize_all | resize_all | 50 | 55 | 50 | 50 | 270ba72b0cb7bc69d7d3833f28b96a2551c88c5e | bigcode/the-stack | train |
1baa630cbe865aa9bdbfda78 | train | function | def get_background():
background = (randint(110, 255), randint(110, 255), randint(110, 255))
prefix = reduce(lambda x, y: str(x) + '_' +str(y), background)
return background, prefix
| def get_background():
| background = (randint(110, 255), randint(110, 255), randint(110, 255))
prefix = reduce(lambda x, y: str(x) + '_' +str(y), background)
return background, prefix
| image
variant_blurred = blur_image(mask)
# save variant image
save_variant(variant_blurred, img_path, prefix)
def blur_image(img):
return img # cv2.GaussianBlur(img, (3, 7), randint(0, 2))
def get_background():
| 64 | 64 | 56 | 4 | 60 | Ankurvish06/hand | generate_dataset.py | Python | get_background | get_background | 39 | 42 | 39 | 39 | 9c5bd38f8a7ebf8bcfd7abbb16f0f7999900caed | bigcode/the-stack | train |
41eb0dff656fb6aef9991f1e | train | function | def generate_variant(img_path, background, prefix):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY_INV)
mask_inv = cv2.bitwise_not(mask)
rows, cols, shape = img.shape
# Create background image
# bg_img = img... | def generate_variant(img_path, background, prefix):
| img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY_INV)
mask_inv = cv2.bitwise_not(mask)
rows, cols, shape = img.shape
# Create background image
# bg_img = img.copy()
# bg_img[0:rows, 0:cols] = background
... | /RBL/English/Hnd/Img'
def save_variant(variant, img_path, prefix):
new_img_file_path = os.path.join(os.path.dirname(img_path), prefix + '_' + os.path.basename(img_path))
cv2.imwrite(new_img_file_path, variant)
def generate_variant(img_path, background, prefix):
| 66 | 66 | 220 | 10 | 56 | Ankurvish06/hand | generate_dataset.py | Python | generate_variant | generate_variant | 16 | 34 | 16 | 16 | d6118eacbaeab591a970e46c2f8a6c802f1dd025 | bigcode/the-stack | train |
2256d562e1ea27c0963ae784 | train | class | class SoftWindowFunction(function.Function):
def check_type_forward(self, in_types):
pass
def forward(self, inputs):
a_h, b_h, k_h, cs, k_prev = inputs
if not type_check.same_types(*inputs):
raise ValueError("numpy and cupy must not be used together\n"
... | class SoftWindowFunction(function.Function):
| def check_type_forward(self, in_types):
pass
def forward(self, inputs):
a_h, b_h, k_h, cs, k_prev = inputs
if not type_check.same_types(*inputs):
raise ValueError("numpy and cupy must not be used together\n"
"type(a_h): {0}, type(b_h): {1}, type... | import chainer
from chainer import function
from chainer import cuda
from chainer.utils import type_check
class SoftWindowFunction(function.Function):
| 31 | 207 | 690 | 7 | 23 | kristofbc/handwriting-synthesis | src/models/functions/connection/soft_window.py | Python | SoftWindowFunction | SoftWindowFunction | 6 | 71 | 6 | 6 | 49ec7cc03e82185da52235e23de777a02230c16f | bigcode/the-stack | train |
faf54b55cee6774e1e7be856 | train | function | def soft_window(a_h, b_h, k_h, cs, k_prev):
"""
Perform the SoftWindow call
"""
return SoftWindowFunction()(a_h, b_h, k_h, cs, k_prev)
| def soft_window(a_h, b_h, k_h, cs, k_prev):
| """
Perform the SoftWindow call
"""
return SoftWindowFunction()(a_h, b_h, k_h, cs, k_prev)
| (us - self.k_h), axis=2)
g_k_h = xp.exp(k_h) * g_k_p
return g_a_h, g_b_h, g_k_h, None, g_k_p,
def soft_window(a_h, b_h, k_h, cs, k_prev):
| 64 | 64 | 48 | 17 | 47 | kristofbc/handwriting-synthesis | src/models/functions/connection/soft_window.py | Python | soft_window | soft_window | 74 | 78 | 74 | 74 | 2bf63eaa64fc4c3a5901c29bad790cea3937f36d | bigcode/the-stack | train |
0bef983866475943e8639afe | train | function | def convert(res):
y=np.array(res).squeeze()
return y
| def convert(res):
| y=np.array(res).squeeze()
return y
|
real=convert(result)
recored['filename'].append(img_file)
recored['pred'].append(real)
else:
print(res.status_code)
break
df=pd.DataFrame(recored)
df.to_csv('result.csv')
print(df.head())
def convert(res):
| 63 | 64 | 17 | 4 | 59 | terry-ss/timm_kits | flask/post.py | Python | convert | convert | 30 | 32 | 30 | 30 | e96fccadc95e1c2dfe029daecbf55338c9ca50a8 | bigcode/the-stack | train |
7f498fb2e1a1c8bc12afac2c | train | function | def test_img(project,port):
url=f'http://127.0.0.1:{port}/{project}'
print(url)
img_dir='img/'
pbar=tqdm(list(list_images(img_dir)),colour='green')
recored={'filename':[],'pred':[]}
for img_file in pbar:
data={'filename':img_file,'mask':False}
res=requests.post(url=url,da... | def test_img(project,port):
| url=f'http://127.0.0.1:{port}/{project}'
print(url)
img_dir='img/'
pbar=tqdm(list(list_images(img_dir)),colour='green')
recored={'filename':[],'pred':[]}
for img_file in pbar:
data={'filename':img_file,'mask':False}
res=requests.post(url=url,data=data)
if res.stat... | import requests
from pathlib import Path
import cv2
from tqdm import tqdm
import numpy as np
from imutils.paths import list_images
import pandas as pd
def test_img(project,port):
| 42 | 64 | 171 | 7 | 34 | terry-ss/timm_kits | flask/post.py | Python | test_img | test_img | 9 | 28 | 9 | 9 | 1b73147425881a1d50e6875ab7acaa49f6e6b660 | bigcode/the-stack | train |
db715f516499021bc7c0e54b | train | function | def Relief(X, y):
X, y = check_X_y(X, y, ensure_min_samples=4)
if np.sum(y == 0) < 2 or np.sum(y == 1) < 2:
raise ValueError('Input y should have at least 2 samples for each class')
n_sample, n_feature = X.shape
# initial weight all is zero
weight = np.zeros((n_feature,))
# feature r... | def Relief(X, y):
| X, y = check_X_y(X, y, ensure_min_samples=4)
if np.sum(y == 0) < 2 or np.sum(y == 1) < 2:
raise ValueError('Input y should have at least 2 samples for each class')
n_sample, n_feature = X.shape
# initial weight all is zero
weight = np.zeros((n_feature,))
# feature range
max_min =... | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# author: jeremy.zhang(szujeremy@gmail.com, Shenzhen University, China)
import numpy as np
from .utils import check_X_y
def Relief(X, y):
| 53 | 109 | 365 | 6 | 46 | kangzh015/radiomics | skradiomics/feature_selection/Relief.py | Python | Relief | Relief | 10 | 52 | 10 | 10 | f2f69ea913bc2994c8e6720759926b9071096dbd | bigcode/the-stack | train |
a0df5f739cf4071fe73b9999 | train | class | class Synthesizer:
def __init__(self, name):
"""Synthesizers Wrapper
Useful to use the FoldsLoader.
Input:
- name: of the form 'CL-<n_train>', with <n_train> an integer
"""
name_split = name.split('-')
self.problem = name_split[0]
nb = int(name_split... | class Synthesizer:
| def __init__(self, name):
"""Synthesizers Wrapper
Useful to use the FoldsLoader.
Input:
- name: of the form 'CL-<n_train>', with <n_train> an integer
"""
name_split = name.split('-')
self.problem = name_split[0]
nb = int(name_split[1])
# para... |
from .classification import CLSynthesizer
from .interval_regression import IRSynthesizer
from .multilabels import MLSynthesizer
from .ranking import RKSynthesizer
class Synthesizer:
| 48 | 84 | 283 | 5 | 42 | VivienCabannes/infimum_loss | dataloader/synthetic/engine.py | Python | Synthesizer | Synthesizer | 8 | 41 | 8 | 8 | 7781be3411fd034ca97f1fddd52cdf7d3e8bcf1c | bigcode/the-stack | train |
ef44ca7b8f55b8f4944865dd | train | function | def test_list_renders(admin_client):
response = admin_client.get(admin_link)
assert response.status_code == 200
| def test_list_renders(admin_client):
| response = admin_client.get(admin_link)
assert response.status_code == 200
| admin:permissions:index")
def create_form_data(data_dict):
return mock_role_form_data(Role(), data_dict)
def test_link_is_registered_in_admin_nav(admin_client):
response = admin_client.get(reverse("misago:admin:index"))
assert_contains(response, admin_link)
def test_list_renders(admin_client):
| 64 | 64 | 26 | 8 | 56 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_list_renders | test_list_renders | 23 | 25 | 23 | 23 | 72857e90282faed315a5d7d1bbec3263004d4624 | bigcode/the-stack | train |
f1202dacfffd11b04e1d9159 | train | function | def test_link_is_registered_in_admin_nav(admin_client):
response = admin_client.get(reverse("misago:admin:index"))
assert_contains(response, admin_link)
| def test_link_is_registered_in_admin_nav(admin_client):
| response = admin_client.get(reverse("misago:admin:index"))
assert_contains(response, admin_link)
|
from ... import ACL_CACHE
from ...models import Role
from ..test import mock_role_form_data
admin_link = reverse("misago:admin:permissions:index")
def create_form_data(data_dict):
return mock_role_form_data(Role(), data_dict)
def test_link_is_registered_in_admin_nav(admin_client):
| 64 | 64 | 33 | 11 | 53 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_link_is_registered_in_admin_nav | test_link_is_registered_in_admin_nav | 18 | 20 | 18 | 18 | a3941f3d0658691708f5aa6d259850158333cc01 | bigcode/the-stack | train |
7f5d7d4881b5e0bada706827 | train | function | def create_form_data(data_dict):
return mock_role_form_data(Role(), data_dict)
| def create_form_data(data_dict):
| return mock_role_form_data(Role(), data_dict)
| .test import AdminTestCase
from ....cache.test import assert_invalidates_cache
from ....test import assert_contains
from ... import ACL_CACHE
from ...models import Role
from ..test import mock_role_form_data
admin_link = reverse("misago:admin:permissions:index")
def create_form_data(data_dict):
| 64 | 64 | 18 | 7 | 57 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | create_form_data | create_form_data | 14 | 15 | 14 | 14 | 3043e71b46b2cde4e2410ac22b4351c29fb31502 | bigcode/the-stack | train |
0d5d016ae1f7542a7bd9af87 | train | function | def test_special_role_cant_be_deleted(admin_client, role):
role.special_role = "Test"
role.save()
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
role.refresh_from_db()
| def test_special_role_cant_be_deleted(admin_client, role):
| role.special_role = "Test"
role.save()
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
role.refresh_from_db()
| test_role_can_be_deleted(admin_client, role):
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
with pytest.raises(Role.DoesNotExist):
role.refresh_from_db()
def test_special_role_cant_be_deleted(admin_client, role):
| 64 | 64 | 57 | 13 | 51 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_special_role_cant_be_deleted | test_special_role_cant_be_deleted | 81 | 89 | 81 | 81 | 70ee1307841a81819b010e9860baf912bfa2fc7d | bigcode/the-stack | train |
8de5996c6265f38a778eed0b | train | function | def test_deleting_role_invalidates_acl_cache(admin_client, role):
with assert_invalidates_cache(ACL_CACHE):
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
| def test_deleting_role_invalidates_acl_cache(admin_client, role):
| with assert_invalidates_cache(ACL_CACHE):
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
| _deleted(admin_client, role):
role.special_role = "Test"
role.save()
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
role.refresh_from_db()
def test_deleting_role_invalidates_acl_cache(admin_client, role):
| 64 | 64 | 50 | 14 | 50 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_deleting_role_invalidates_acl_cache | test_deleting_role_invalidates_acl_cache | 92 | 96 | 92 | 92 | f69bb4d33d4c49b07792c2bd83aa0322eafafca1 | bigcode/the-stack | train |
b2ab96c190f91404473326e2 | train | function | def test_edit_role_form_renders(admin_client, role):
response = admin_client.get(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk})
)
assert response.status_code == 200
| def test_edit_role_form_renders(admin_client, role):
| response = admin_client.get(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk})
)
assert response.status_code == 200
| (
reverse("misago:admin:permissions:new"),
data=create_form_data({"name": "Test Role"}),
)
Role.objects.get(name="Test Role")
@pytest.fixture
def role(db):
return Role.objects.create(name="Test Role")
def test_edit_role_form_renders(admin_client, role):
| 64 | 64 | 49 | 12 | 52 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_edit_role_form_renders | test_edit_role_form_renders | 47 | 51 | 47 | 47 | 24b1185f5fe3b924a15fb86d870b24c8f08564dc | bigcode/the-stack | train |
6b38c773a3eecd0c988714d3 | train | function | def test_users_with_role_view_redirects_to_admin_users_list(admin_client, role):
response = admin_client.get(
reverse("misago:admin:permissions:users", kwargs={"pk": role.pk})
)
assert response.status_code == 302
assert reverse("misago:admin:users:index") in response["location"]
| def test_users_with_role_view_redirects_to_admin_users_list(admin_client, role):
| response = admin_client.get(
reverse("misago:admin:permissions:users", kwargs={"pk": role.pk})
)
assert response.status_code == 302
assert reverse("misago:admin:users:index") in response["location"]
| leting_role_invalidates_acl_cache(admin_client, role):
with assert_invalidates_cache(ACL_CACHE):
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
def test_users_with_role_view_redirects_to_admin_users_list(admin_client, role):
| 64 | 64 | 71 | 17 | 47 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_users_with_role_view_redirects_to_admin_users_list | test_users_with_role_view_redirects_to_admin_users_list | 99 | 104 | 99 | 99 | 414452ec6de7d7fedd9cafaa364b75466267efc4 | bigcode/the-stack | train |
06a71a6c530b39a4bc98f109 | train | function | def test_editing_role_invalidates_acl_cache(admin_client, role):
with assert_invalidates_cache(ACL_CACHE):
admin_client.post(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk}),
data=create_form_data({"name": "Role"}),
)
| def test_editing_role_invalidates_acl_cache(admin_client, role):
| with assert_invalidates_cache(ACL_CACHE):
admin_client.post(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk}),
data=create_form_data({"name": "Role"}),
)
| .post(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk}),
data=create_form_data({"name": "Edited Role"}),
)
role.refresh_from_db()
assert role.name == "Edited Role"
def test_editing_role_invalidates_acl_cache(admin_client, role):
| 64 | 64 | 61 | 14 | 50 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_editing_role_invalidates_acl_cache | test_editing_role_invalidates_acl_cache | 64 | 69 | 64 | 64 | 1ee2fc48d7ac210203b3e0a42b8b65e7b94fbf14 | bigcode/the-stack | train |
93d09fe6d744afc89949ca1b | train | function | @pytest.fixture
def role(db):
return Role.objects.create(name="Test Role")
| @pytest.fixture
def role(db):
| return Role.objects.create(name="Test Role")
| .status_code == 200
def test_new_role_can_be_created(admin_client):
response = admin_client.post(
reverse("misago:admin:permissions:new"),
data=create_form_data({"name": "Test Role"}),
)
Role.objects.get(name="Test Role")
@pytest.fixture
def role(db):
| 64 | 64 | 17 | 7 | 57 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | role | role | 42 | 44 | 42 | 43 | a7108f9ad97ab4226033766bdfb9f8c9f418631e | bigcode/the-stack | train |
8d549cef4dcb613e4b649f52 | train | function | def test_role_can_be_edited(admin_client, role):
response = admin_client.post(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk}),
data=create_form_data({"name": "Edited Role"}),
)
role.refresh_from_db()
assert role.name == "Edited Role"
| def test_role_can_be_edited(admin_client, role):
| response = admin_client.post(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk}),
data=create_form_data({"name": "Edited Role"}),
)
role.refresh_from_db()
assert role.name == "Edited Role"
| Test Role")
def test_edit_role_form_renders(admin_client, role):
response = admin_client.get(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk})
)
assert response.status_code == 200
def test_role_can_be_edited(admin_client, role):
| 64 | 64 | 67 | 12 | 51 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_role_can_be_edited | test_role_can_be_edited | 54 | 61 | 54 | 54 | 0ebff46ceb0621e3e7ebcdc774f53390f91b80be | bigcode/the-stack | train |
be977b223b2ffbf73f145cae | train | function | def test_new_role_can_be_created(admin_client):
response = admin_client.post(
reverse("misago:admin:permissions:new"),
data=create_form_data({"name": "Test Role"}),
)
Role.objects.get(name="Test Role")
| def test_new_role_can_be_created(admin_client):
| response = admin_client.post(
reverse("misago:admin:permissions:new"),
data=create_form_data({"name": "Test Role"}),
)
Role.objects.get(name="Test Role")
| ):
response = admin_client.get(admin_link)
assert response.status_code == 200
def test_new_role_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:permissions:new"))
assert response.status_code == 200
def test_new_role_can_be_created(admin_client):
| 64 | 64 | 51 | 10 | 53 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_new_role_can_be_created | test_new_role_can_be_created | 33 | 39 | 33 | 33 | 86449d91e7fcac3aa9eab565d5af2127af8ecc3f | bigcode/the-stack | train |
92541ffcda3f1273654c0b26 | train | function | def test_new_role_form_renders(admin_client):
response = admin_client.get(reverse("misago:admin:permissions:new"))
assert response.status_code == 200
| def test_new_role_form_renders(admin_client):
| response = admin_client.get(reverse("misago:admin:permissions:new"))
assert response.status_code == 200
| _in_admin_nav(admin_client):
response = admin_client.get(reverse("misago:admin:index"))
assert_contains(response, admin_link)
def test_list_renders(admin_client):
response = admin_client.get(admin_link)
assert response.status_code == 200
def test_new_role_form_renders(admin_client):
| 64 | 64 | 35 | 10 | 53 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_new_role_form_renders | test_new_role_form_renders | 28 | 30 | 28 | 28 | eeca4b8fec2004bbd9a90477a24eb2a61ab49fad | bigcode/the-stack | train |
ce26c13a75bd6a38cc4403a5 | train | function | def test_role_can_be_deleted(admin_client, role):
admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
with pytest.raises(Role.DoesNotExist):
role.refresh_from_db()
| def test_role_can_be_deleted(admin_client, role):
| admin_client.post(
reverse("misago:admin:permissions:delete", kwargs={"pk": role.pk})
)
with pytest.raises(Role.DoesNotExist):
role.refresh_from_db()
| _cache(admin_client, role):
with assert_invalidates_cache(ACL_CACHE):
admin_client.post(
reverse("misago:admin:permissions:edit", kwargs={"pk": role.pk}),
data=create_form_data({"name": "Role"}),
)
def test_role_can_be_deleted(admin_client, role):
| 64 | 64 | 52 | 11 | 53 | vascoalramos/misago-deployment | misago/misago/acl/admin/tests/test_admin_views.py | Python | test_role_can_be_deleted | test_role_can_be_deleted | 72 | 78 | 72 | 72 | 8edf476d31b5bce366097528e69af4867aa76737 | bigcode/the-stack | train |
e079677d2724415f51cba708 | train | class | class Exchange(ba.Actor, itf.IOrderReq, itf.IMDRtn):
"""
the exchange actor.
"""
center: cb.CallBackManager
broker: cb.CallBackManager
orders: tp.DefaultDict[str, tp.DefaultDict[cn.BS, tp.Deque[td.OrderReq]]]
ticks: tp.Dict[str, md.Tick]
def __init__(self, center: cb.CallBackManager, br... | class Exchange(ba.Actor, itf.IOrderReq, itf.IMDRtn):
| """
the exchange actor.
"""
center: cb.CallBackManager
broker: cb.CallBackManager
orders: tp.DefaultDict[str, tp.DefaultDict[cn.BS, tp.Deque[td.OrderReq]]]
ticks: tp.Dict[str, md.Tick]
def __init__(self, center: cb.CallBackManager, broker: cb.CallBackManager):
center.bind(md.Tic... | [x.od.s].get(c=acc.contracts[x.od.s], ts=acc.orders[x.id])
def on_open(self, x: md.Open):
self.gateway.route(x=x)
pass
def on_close(self, x: md.Close):
self.gateway.route(x=x)
self.a.orders = {k: v for k, v in self.a.orders.items() if not v.ok}
pass
def on_tick(sel... | 177 | 177 | 593 | 18 | 158 | goodchinas/pyxq | pyxq/actor/__init__.py | Python | Exchange | Exchange | 188 | 255 | 188 | 188 | f19139bb51a3a2bdb73799ab51dee3b257ed790c | bigcode/the-stack | train |
4cbd8a911a5803dc685e0ce1 | train | class | class Broker(ba.Actor, itf.IOrderReq, itf.IOrderRsp, itf.IPaReq, itf.IMDRtn):
"""
the broker actor that account service.
"""
a: account.Account
center: cb.CallBackManager
gateway: cb.CallBackManager
exchange: cb.CallBackManager
def __init__(self, a: account.Account,
cen... | class Broker(ba.Actor, itf.IOrderReq, itf.IOrderRsp, itf.IPaReq, itf.IMDRtn):
| """
the broker actor that account service.
"""
a: account.Account
center: cb.CallBackManager
gateway: cb.CallBackManager
exchange: cb.CallBackManager
def __init__(self, a: account.Account,
center: cb.CallBackManager,
gateway: cb.CallBackManager,
... | , self.on_canceled)
broker.bind(td.Rejected.key, self.on_rejected)
broker.bind(md.Open.key, self.on_open)
broker.bind(md.Close.key, self.on_close)
broker.bind(md.Tick.key, self.on_tick)
broker.bind(md.OrderBook.key, self.on_order_book)
self.a = a
self.center = cen... | 256 | 256 | 1,062 | 30 | 225 | goodchinas/pyxq | pyxq/actor/__init__.py | Python | Broker | Broker | 65 | 185 | 65 | 65 | 7e8cc8e10c8fb4f68659a5731de94fe17bb05d62 | bigcode/the-stack | train |
7f92cfa3b43d750915fdeac8 | train | class | class GateWay(ba.Actor, itf.IMDRtn, itf.IOrderRsp, itf.IFactor, itf.IGateWayInit):
"""
the local gateway father class.
"""
a: account.Account
broker: cb.CallBackManager
center: cb.CallBackManager
def init(self, a: account.Account, center: cb.CallBackManager, broker: cb.CallBackManager):
... | class GateWay(ba.Actor, itf.IMDRtn, itf.IOrderRsp, itf.IFactor, itf.IGateWayInit):
| """
the local gateway father class.
"""
a: account.Account
broker: cb.CallBackManager
center: cb.CallBackManager
def init(self, a: account.Account, center: cb.CallBackManager, broker: cb.CallBackManager):
center.bind(md.Factor.key, self.on_factor)
broker.bind(td.Trade.key, s... | """
the actor model.
"""
import typing as tp
from collections import deque, defaultdict
from .. import ba, cb, itf, cn
from ..msg import md, td, pa
from ..service import account
class GateWay(ba.Actor, itf.IMDRtn, itf.IOrderRsp, itf.IFactor, itf.IGateWayInit):
| 78 | 107 | 359 | 32 | 45 | goodchinas/pyxq | pyxq/actor/__init__.py | Python | GateWay | GateWay | 12 | 62 | 12 | 12 | 2d51f934b2d25321ed3f3dad8927de4f38e51475 | bigcode/the-stack | train |
14d6727c0003c400c0f97afc | train | class | class MemcacheInspectorTests(unittest.TestCase):
now_time = time.time()
now = datetime.datetime.fromtimestamp(now_time)
mc = MC
def setUp(self):
for i in range(len(self.mc)):
self.mc[i]['client'].set('foo', 'bar')
self.mc[i]['client'].set('myaddr', self.mc[i]['addr'])
... | class MemcacheInspectorTests(unittest.TestCase):
| now_time = time.time()
now = datetime.datetime.fromtimestamp(now_time)
mc = MC
def setUp(self):
for i in range(len(self.mc)):
self.mc[i]['client'].set('foo', 'bar')
self.mc[i]['client'].set('myaddr', self.mc[i]['addr'])
if i == 0:
self.mc[i]['... | #!/usr/bin/env python
import datetime
import logging
import subprocess
import time
import unittest
import memcache
from memcacheinspector import *
logging.basicConfig(level=logging.DEBUG)
# These tests assume that memcached is already running.
_PORT = 11222
MC = []
for i in range(2):
mc = {}
mc['addr'] = ... | 127 | 256 | 1,044 | 9 | 118 | brondsem/memcacheinspector | tests/memcacheinspectortests.py | Python | MemcacheInspectorTests | MemcacheInspectorTests | 27 | 126 | 27 | 27 | bae28b054fbb2ded33ebf43be0f362ef7a9bbc05 | bigcode/the-stack | train |
a5c14ae5e3404db24d0ac82e | train | function | def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
"""
Replace non-padding symbols with their position numbers. Position numbers begin at
padding_idx+1. Padding symbols are ignored. This is modified from fairseq's
`utils.make_positions`.
Args:
x: torch... | def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
| """
Replace non-padding symbols with their position numbers. Position numbers begin at
padding_idx+1. Padding symbols are ignored. This is modified from fairseq's
`utils.make_positions`.
Args:
x: torch.Tensor x:
Returns: torch.Tensor
"""
# The series of casts and type-conversio... | ,
QuantizedBertLayer,
QuantizedBertPooler,
QuantizedBertModel,
QuantizedBertForSequenceClassification,
)
from quantization.autoquant_utils import quantize_model
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
| 64 | 64 | 157 | 20 | 43 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | create_position_ids_from_input_ids | create_position_ids_from_input_ids | 26 | 41 | 26 | 26 | 99db3e9e213fd434830354980217c58f47956945 | bigcode/the-stack | train |
de218b826b6d4d0a161bf730 | train | class | class QuantizedRobertaEmbeddings(QuantizedBertEmbeddings):
def __init__(self, org_model, **quant_params):
super().__init__(org_model, **quant_params)
self.padding_idx = org_model.padding_idx
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
"""We are provided embeddings ... | class QuantizedRobertaEmbeddings(QuantizedBertEmbeddings):
| def __init__(self, org_model, **quant_params):
super().__init__(org_model, **quant_params)
self.padding_idx = org_model.padding_idx
def create_position_ids_from_inputs_embeds(self, inputs_embeds):
"""We are provided embeddings directly. We cannot infer which are padded so just generate... | numbers. Position numbers begin at
padding_idx+1. Padding symbols are ignored. This is modified from fairseq's
`utils.make_positions`.
Args:
x: torch.Tensor x:
Returns: torch.Tensor
"""
# The series of casts and type-conversions here are carefully balanced to both work with ONNX
#... | 142 | 142 | 474 | 15 | 126 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaEmbeddings | QuantizedRobertaEmbeddings | 44 | 107 | 44 | 44 | cd40055cc5e6c45e7da95ba86eaa8fc73712ab6b | bigcode/the-stack | train |
45d2d3316b9b149d6337675e | train | class | class QuantizedRobertaModel(QuantizedBertModel):
def __init__(self, org_model, **quant_params):
super().__init__(org_model, **quant_params)
# update quantized components
self.embeddings = QuantizedRobertaEmbeddings(org_model.embeddings, **quant_params)
self.encoder = quantize_model(... | class QuantizedRobertaModel(QuantizedBertModel):
| def __init__(self, org_model, **quant_params):
super().__init__(org_model, **quant_params)
# update quantized components
self.embeddings = QuantizedRobertaEmbeddings(org_model.embeddings, **quant_params)
self.encoder = quantize_model(
org_model.encoder, specials={Roberta... | _model.crossattention, specials=attention_specials, **quant_params
)
self.output = QuantizedRobertaOutput(org_model.output, **quant_params)
class QuantizedRobertaPooler(QuantizedBertPooler):
pass
class QuantizedRobertaModel(QuantizedBertModel):
| 64 | 64 | 135 | 13 | 50 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaModel | QuantizedRobertaModel | 145 | 158 | 145 | 145 | 47bba80afeec7eacb752075debe44c59a39f4db7 | bigcode/the-stack | train |
84985c0ab44a9c30e9fd6c2b | train | class | class QuantizedRobertaPooler(QuantizedBertPooler):
pass
| class QuantizedRobertaPooler(QuantizedBertPooler):
| pass
| self.add_cross_attention:
self.crossattention = quantize_model(
org_model.crossattention, specials=attention_specials, **quant_params
)
self.output = QuantizedRobertaOutput(org_model.output, **quant_params)
class QuantizedRobertaPooler(QuantizedBertPooler):
| 64 | 64 | 18 | 15 | 49 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaPooler | QuantizedRobertaPooler | 141 | 142 | 141 | 141 | b20c75f991da77d56332a8ac65dcd8c5d4d7012b | bigcode/the-stack | train |
39686ffcac921761301c2ce0 | train | class | class QuantizedRobertaLayer(QuantizedBertLayer):
def __init__(self, org_model, **quant_params):
super().__init__(org_model, **quant_params)
# update quantized components
attention_specials = {
RobertaSelfAttention: QuantizedRobertaSelfAttention,
RobertaSelfOutput: Qu... | class QuantizedRobertaLayer(QuantizedBertLayer):
| def __init__(self, org_model, **quant_params):
super().__init__(org_model, **quant_params)
# update quantized components
attention_specials = {
RobertaSelfAttention: QuantizedRobertaSelfAttention,
RobertaSelfOutput: QuantizedRobertaSelfOutput,
}
self.... | QuantizedRobertaSelfAttention(QuantizedBertSelfAttention):
pass
class QuantizedRobertaSelfOutput(QuantizedBertSelfOutput):
pass
class QuantizedRobertaOutput(QuantizedBertOutput):
pass
class QuantizedRobertaLayer(QuantizedBertLayer):
| 64 | 64 | 158 | 13 | 50 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaLayer | QuantizedRobertaLayer | 122 | 138 | 122 | 122 | 95f34d4b33d4cf53a6767a4f2990a40d8ad93648 | bigcode/the-stack | train |
4ad316eb06614fbb2a14505e | train | class | class QuantizedRobertaOutput(QuantizedBertOutput):
pass
| class QuantizedRobertaOutput(QuantizedBertOutput):
| pass
| eddings)
embeddings = self.dropout(embeddings)
return embeddings
class QuantizedRobertaSelfAttention(QuantizedBertSelfAttention):
pass
class QuantizedRobertaSelfOutput(QuantizedBertSelfOutput):
pass
class QuantizedRobertaOutput(QuantizedBertOutput):
| 64 | 64 | 16 | 13 | 50 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaOutput | QuantizedRobertaOutput | 118 | 119 | 118 | 118 | 124430f991787f39e9d612240b21a8fe7405d700 | bigcode/the-stack | train |
dc42d40f86db38da9d4fc9ae | train | class | class QuantizedRobertaSelfAttention(QuantizedBertSelfAttention):
pass
| class QuantizedRobertaSelfAttention(QuantizedBertSelfAttention):
| pass
| .position_embeddings(position_ids)
embeddings += position_embeddings
embeddings = self.sum_pos_embd_act_quantizer(embeddings)
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class QuantizedRobertaSelfAttention(QuantizedBertSel... | 64 | 64 | 18 | 15 | 48 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaSelfAttention | QuantizedRobertaSelfAttention | 110 | 111 | 110 | 110 | 4bd65caed95b88977bfb2c377e35197be02d1db5 | bigcode/the-stack | train |
a89b7d19807aaf5143adad68 | train | class | class QuantizedRobertaForSequenceClassification(QuantizedBertForSequenceClassification):
def __init__(self, org_model, quant_setup=None, **quant_params):
super().__init__(org_model, quant_setup=quant_setup, **quant_params)
# update quantization components
self.roberta = QuantizedRobertaMode... | class QuantizedRobertaForSequenceClassification(QuantizedBertForSequenceClassification):
| def __init__(self, org_model, quant_setup=None, **quant_params):
super().__init__(org_model, quant_setup=quant_setup, **quant_params)
# update quantization components
self.roberta = QuantizedRobertaModel(org_model=org_model.roberta, **quant_params)
self.classifier = quantize_model(o... | def __init__(self, org_model, **quant_params):
super().__init__(org_model, **quant_params)
# update quantized components
self.embeddings = QuantizedRobertaEmbeddings(org_model.embeddings, **quant_params)
self.encoder = quantize_model(
org_model.encoder, specials={Roberta... | 139 | 139 | 464 | 17 | 122 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaForSequenceClassification | QuantizedRobertaForSequenceClassification | 161 | 220 | 161 | 161 | 671a23a33551c8b3364928a0507c575d1d016e7c | bigcode/the-stack | train |
dfd187213cd12ef009412f31 | train | class | class QuantizedRobertaSelfOutput(QuantizedBertSelfOutput):
pass
| class QuantizedRobertaSelfOutput(QuantizedBertSelfOutput):
| pass
| d_act_quantizer(embeddings)
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class QuantizedRobertaSelfAttention(QuantizedBertSelfAttention):
pass
class QuantizedRobertaSelfOutput(QuantizedBertSelfOutput):
| 64 | 64 | 18 | 15 | 48 | vuiseng9/transformer-quantization | models/quantized_roberta.py | Python | QuantizedRobertaSelfOutput | QuantizedRobertaSelfOutput | 114 | 115 | 114 | 114 | abc9a28e89fe880ac40047c2cb0a42787b340f1a | bigcode/the-stack | train |
6f26a7456b228e91f2bdd112 | train | function | def rel(filename):
return os.path.join(self_dir, filename)
| def rel(filename):
| return os.path.join(self_dir, filename)
| .add_argument("--gen-all", help='generate everything', action='store_true')
args = parser.parse_args()
if args is False:
SystemExit
self_dir = os.path.dirname(os.path.realpath(__file__))
def output(filename):
return os.path.join(args.output_dir, filename)
def rel(filename):
| 64 | 64 | 14 | 4 | 60 | gentaiscool/ros-vrep-slam | src/v_repExtRosInterface/v_repStubsGen/generate.py | Python | rel | rel | 34 | 35 | 34 | 34 | 6f11afd508800e0c1157e2549fbd234ac5a77bbd | bigcode/the-stack | train |
96e4ea9237f389e87fe893c2 | train | function | def output(filename):
return os.path.join(args.output_dir, filename)
| def output(filename):
| return os.path.join(args.output_dir, filename)
| generate deprecated functions mapping for V-REP', action='store_true')
parser.add_argument("--gen-all", help='generate everything', action='store_true')
args = parser.parse_args()
if args is False:
SystemExit
self_dir = os.path.dirname(os.path.realpath(__file__))
def output(filename):
| 63 | 64 | 15 | 4 | 59 | gentaiscool/ros-vrep-slam | src/v_repExtRosInterface/v_repStubsGen/generate.py | Python | output | output | 31 | 32 | 31 | 31 | ef9c25992a241942538d1be0ec3eb14931025b3f | bigcode/the-stack | train |
14b1845bd26a3a5f769fc729 | train | function | def runsubprocess(what, args):
child = subprocess.Popen(args)
child.communicate()
if child.returncode != 0:
print('failed to run %s' % what)
sys.exit(1)
| def runsubprocess(what, args):
| child = subprocess.Popen(args)
child.communicate()
if child.returncode != 0:
print('failed to run %s' % what)
sys.exit(1)
| .parse_args()
if args is False:
SystemExit
self_dir = os.path.dirname(os.path.realpath(__file__))
def output(filename):
return os.path.join(args.output_dir, filename)
def rel(filename):
return os.path.join(self_dir, filename)
def runsubprocess(what, args):
| 64 | 64 | 48 | 9 | 55 | gentaiscool/ros-vrep-slam | src/v_repExtRosInterface/v_repStubsGen/generate.py | Python | runsubprocess | runsubprocess | 37 | 42 | 37 | 37 | 212c2b61508fa1fc4f4fae798456d5243e3ddd35 | bigcode/the-stack | train |
154060fceffddc9743c49de8 | train | function | def runtool(what, *args):
print('running %s' % what)
runsubprocess(what, ['python', rel(what + '.py')] + list(args))
| def runtool(what, *args):
| print('running %s' % what)
runsubprocess(what, ['python', rel(what + '.py')] + list(args))
| .path.join(self_dir, filename)
def runsubprocess(what, args):
child = subprocess.Popen(args)
child.communicate()
if child.returncode != 0:
print('failed to run %s' % what)
sys.exit(1)
def runtool(what, *args):
| 64 | 64 | 40 | 9 | 55 | gentaiscool/ros-vrep-slam | src/v_repExtRosInterface/v_repStubsGen/generate.py | Python | runtool | runtool | 44 | 46 | 44 | 44 | 2642b59edc6d877ba10a9b33eadd53aa7ba3f97f | bigcode/the-stack | train |
d55bd8f2a14b1cca86b0e6d2 | train | function | def runprogram(what, *args):
print('running %s' % what)
runsubprocess(what, [what] + list(args))
| def runprogram(what, *args):
| print('running %s' % what)
runsubprocess(what, [what] + list(args))
| failed to run %s' % what)
sys.exit(1)
def runtool(what, *args):
print('running %s' % what)
runsubprocess(what, ['python', rel(what + '.py')] + list(args))
def runprogram(what, *args):
| 64 | 64 | 33 | 9 | 55 | gentaiscool/ros-vrep-slam | src/v_repExtRosInterface/v_repStubsGen/generate.py | Python | runprogram | runprogram | 48 | 50 | 48 | 48 | b18702f0599fa6aa5dd7415539ad6f6ca78e4310 | bigcode/the-stack | train |
361c3416852df00b72246bed | train | class | class CondWGAN_D(WGAN_D):
def __init__(self,inputch=2):
super(CondWGAN_D, self).__init__(inputch)
self.labfc1 = nn.Linear(10, 28*28)
def forward(self, x,lab):#batch, width, height, channel=1
d_in = torch.cat((x.view(x.size(0), -1), self.labfc1(lab)), -1)
x = d_... | class CondWGAN_D(WGAN_D):
| def __init__(self,inputch=2):
super(CondWGAN_D, self).__init__(inputch)
self.labfc1 = nn.Linear(10, 28*28)
def forward(self, x,lab):#batch, width, height, channel=1
d_in = torch.cat((x.view(x.size(0), -1), self.labfc1(lab)), -1)
x = d_in.view(d_in.size(0), 2,28,... | Sat Jan 25 23:20:20 2020
"""
import torch
from torch import nn
#引入本地代码库
from code_22_wGan import device,displayAndTest,train, WGAN_G,WGAN_D
class CondWGAN_D(WGAN_D):
| 64 | 64 | 134 | 9 | 54 | aianaconda/pytorch-GNN-1st | code_23_condWGAN.py | Python | CondWGAN_D | CondWGAN_D | 17 | 25 | 17 | 17 | e8a75695f98cbc7390ccc591b92d3eb47c7bd137 | bigcode/the-stack | train |
8b0314b745cc0e574a7622d4 | train | class | class CondWGAN_G(WGAN_G):
def __init__(self, input_size,input_n=2):
super(CondWGAN_G, self).__init__(input_size,input_n)
self.labfc1 = nn.Linear(10,input_size)
def forward(self, x,lab):
d_in = torch.cat((x, self.labfc1(lab)), -1)
return super(CondWGAN_G, self).forward(d_i... | class CondWGAN_G(WGAN_G):
| def __init__(self, input_size,input_n=2):
super(CondWGAN_G, self).__init__(input_size,input_n)
self.labfc1 = nn.Linear(10,input_size)
def forward(self, x,lab):
d_in = torch.cat((x, self.labfc1(lab)), -1)
return super(CondWGAN_G, self).forward(d_in,lab)
| x.view(x.size(0), -1), self.labfc1(lab)), -1)
x = d_in.view(d_in.size(0), 2,28,28)
return super(CondWGAN_D, self).forward(x,lab)
class CondWGAN_G(WGAN_G):
| 64 | 64 | 98 | 9 | 55 | aianaconda/pytorch-GNN-1st | code_23_condWGAN.py | Python | CondWGAN_G | CondWGAN_G | 28 | 35 | 28 | 28 | 95908d860b159aa474dcff2db5ae85010327dd4d | bigcode/the-stack | train |
f6caf68471febc68b0bec8e7 | train | function | def ppkeywd(tok):
if util.is_prefixed(tok):
return tok[0] + ':' + tok[1]
else:
return tok
| def ppkeywd(tok):
| if util.is_prefixed(tok):
return tok[0] + ':' + tok[1]
else:
return tok
| self.tokenizer.skip_tok() # skip the ';'
else:
error.err_add(self.ctx.errors, self.pos, 'INCOMPLETE_STATEMENT',
(keywd, tok))
raise error.Abort
return stmt
# FIXME: tmp debug
import sys
def ppkeywd(tok):
| 64 | 64 | 34 | 6 | 57 | visiontrail/pyang | pyang/yang_parser.py | Python | ppkeywd | ppkeywd | 346 | 350 | 346 | 346 | 502ad9003a5d945dee0054459ce7da568ff25ac4 | bigcode/the-stack | train |
036630a3d07edfcc9c4faf8d | train | class | class YangParser(object):
def __init__(self, extra={}):
pass
def parse(self, ctx, ref, text):
"""Parse the string `text` containing a YANG statement.
Return a Statement on success or None on failure
"""
self.ctx = ctx
self.pos = error.Position(ref)
self... | class YangParser(object):
| def __init__(self, extra={}):
pass
def parse(self, ctx, ref, text):
"""Parse the string `text` containing a YANG statement.
Return a Statement on success or None on failure
"""
self.ctx = ctx
self.pos = error.Position(ref)
self.top = None
try:
... | if i == buflen:
# whitespace only on this line; keep it as is
i = 0
elif need_quote == True:
error.err_add(self.errors, self.pos, 'EXPECTED_QUOTED_STRING', ())
raise error.Abort
else:
# unquoted strin... | 196 | 196 | 656 | 5 | 190 | visiontrail/pyang | pyang/yang_parser.py | Python | YangParser | YangParser | 258 | 341 | 258 | 258 | d62c65bf360bf34a854527badfe963ff6fa5554d | bigcode/the-stack | train |
968201e3740cf4aefab66503 | train | class | class YangTokenizer(object):
def __init__(self, text, pos, errors,
max_line_len=None, keep_comments=False,
strict_quoting = False):
self.lines = collections.deque(text.splitlines(True))
self.pos = pos
self.buf = ''
self.offset = 0
"""Position... | class YangTokenizer(object):
| def __init__(self, text, pos, errors,
max_line_len=None, keep_comments=False,
strict_quoting = False):
self.lines = collections.deque(text.splitlines(True))
self.pos = pos
self.buf = ''
self.offset = 0
"""Position on line. Used to remove lea... | """ This module implements a generic YANG parser.
The parser does not check any keywords or grammar.
"""
import collections
from . import error
from . import statements
from . import syntax
from . import util
class YangTokenizer(object):
| 49 | 256 | 1,966 | 5 | 43 | visiontrail/pyang | pyang/yang_parser.py | Python | YangTokenizer | YangTokenizer | 13 | 256 | 13 | 13 | c52133924119bcc5096c955b9b2482401562c322 | bigcode/the-stack | train |
6eca570bf5e4a51b50089268 | train | function | def pp(s, indent=0):
sys.stdout.write(" " * indent + ppkeywd(s.raw_keyword))
if s.arg is not None:
sys.stdout.write(" '" + s.arg + "'")
if s.substmts == []:
sys.stdout.write(";\n")
else:
sys.stdout.write(" {\n")
for ss in s.substmts:
pp(ss, indent+4)
s... | def pp(s, indent=0):
| sys.stdout.write(" " * indent + ppkeywd(s.raw_keyword))
if s.arg is not None:
sys.stdout.write(" '" + s.arg + "'")
if s.substmts == []:
sys.stdout.write(";\n")
else:
sys.stdout.write(" {\n")
for ss in s.substmts:
pp(ss, indent+4)
sys.stdout.write(" " *... | , tok))
raise error.Abort
return stmt
# FIXME: tmp debug
import sys
def ppkeywd(tok):
if util.is_prefixed(tok):
return tok[0] + ':' + tok[1]
else:
return tok
def pp(s, indent=0):
| 64 | 64 | 102 | 8 | 55 | visiontrail/pyang | pyang/yang_parser.py | Python | pp | pp | 352 | 362 | 352 | 352 | 64251fadd594dbaec599a056bd86d809859e4c3e | bigcode/the-stack | train |
5efb41e616d4f427c80a4146 | train | class | class Migration(migrations.Migration):
dependencies = [
("payments", "0011_rename_ordertoken_order_field"),
]
operations = [
migrations.AlterField(
model_name="additionalproduct",
name="service",
field=models.CharField(
choices=[
... | class Migration(migrations.Migration):
| dependencies = [
("payments", "0011_rename_ordertoken_order_field"),
]
operations = [
migrations.AlterField(
model_name="additionalproduct",
name="service",
field=models.CharField(
choices=[
("electricity", "Electricity... | # Generated by Django 3.1 on 2020-10-20 11:54
from django.db import migrations, models
import payments
class Migration(migrations.Migration):
| 39 | 102 | 343 | 7 | 31 | City-of-Helsinki/berth-reservations | payments/migrations/0012_add_storage_on_ice_product.py | Python | Migration | Migration | 8 | 62 | 8 | 9 | a35b9039a56b6343ae5b627b5eed8e8495565151 | bigcode/the-stack | train |
9a096450cd6cf81dd792572a | train | class | class Mock(object):
"""Used to fake the presence of Python C-extensions for documentation
building. See
http://docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
"""
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwar... | class Mock(object):
| """Used to fake the presence of Python C-extensions for documentation
building. See
http://docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
"""
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return ... | .I18n
import bridgedb.Main
import bridgedb.persistent
import bridgedb.runner
import bridgedb.Stability
import bridgedb.Storage
import bridgedb.test
import bridgedb.Tests
import bridgedb.Util
import gen_bridge_descriptors
class Mock(object):
| 64 | 64 | 166 | 4 | 59 | wfn/bridgedb | doc/sphinx/source/conf.py | Python | Mock | Mock | 50 | 70 | 50 | 50 | 4f1866c891a97811c09fa82ea42430ac0f1ea1d3 | bigcode/the-stack | train |
fc4716f16bdc5c94669610ee | train | function | @pytest.mark.parametrize('legacy_dir_exists, xdg_config_home, result', [
(False, '~/.config', '~/.config/dwim'),
(False, '/user/test/config/', '/user/test/config/dwim'),
(True, '~/.config', '~/.dwim'),
(True, '/user/test/config/', '~/.dwim')])
def test_get_user_dir_path(mocker, environ, settings, legacy... | @pytest.mark.parametrize('legacy_dir_exists, xdg_config_home, result', [
(False, '~/.config', '~/.config/dwim'),
(False, '/user/test/config/', '/user/test/config/dwim'),
(True, '~/.config', '~/.dwim'),
(True, '/user/test/config/', '~/.dwim')])
def test_get_user_dir_path(mocker, environ, settings, legacy... | mocker.patch('dwim.conf.Path.is_dir',
return_value=legacy_dir_exists)
if xdg_config_home is not None:
environ['XDG_CONFIG_HOME'] = xdg_config_home
else:
environ.pop('XDG_CONFIG_HOME', None)
path = settings._get_user_dir_path().as_posix()
assert path == os.path.expa... | @pytest.mark.parametrize('legacy_dir_exists, xdg_config_home, result', [
(False, '~/.config', '~/.config/dwim'),
(False, '/user/test/config/', '/user/test/config/dwim'),
(True, '~/.config', '~/.dwim'),
(True, '/user/test/config/', '~/.dwim')])
def test_get_user_dir_path(mocker, environ, settings, legacy... | 101 | 64 | 183 | 101 | 0 | aoeu/DWIM | tests/test_conf.py | Python | test_get_user_dir_path | test_get_user_dir_path | 107 | 123 | 107 | 113 | f77017dd8b423a7e8566baab93a09a224ca7b2d5 | bigcode/the-stack | train |
c41eaeced1927432c648e557 | train | function | @pytest.mark.usefixture('environ')
def test_settings_defaults(load_source, settings):
load_source.return_value = object()
settings.init()
for key, val in const.DEFAULT_SETTINGS.items():
assert getattr(settings, key) == val
| @pytest.mark.usefixture('environ')
def test_settings_defaults(load_source, settings):
| load_source.return_value = object()
settings.init()
for key, val in const.DEFAULT_SETTINGS.items():
assert getattr(settings, key) == val
| _source(mocker):
return mocker.patch('dwim.conf.load_source')
@pytest.fixture
def environ(monkeypatch):
data = {}
monkeypatch.setattr('dwim.conf.os.environ', data)
return data
@pytest.mark.usefixture('environ')
def test_settings_defaults(load_source, settings):
| 64 | 64 | 50 | 17 | 46 | aoeu/DWIM | tests/test_conf.py | Python | test_settings_defaults | test_settings_defaults | 20 | 25 | 20 | 21 | 0fdbd80e9ec71c149aa71bfa44eb8ab5db60b899 | bigcode/the-stack | train |
509e3c24f92a076f23cbada4 | train | function | @pytest.fixture
def environ(monkeypatch):
data = {}
monkeypatch.setattr('dwim.conf.os.environ', data)
return data
| @pytest.fixture
def environ(monkeypatch):
| data = {}
monkeypatch.setattr('dwim.conf.os.environ', data)
return data
| import pytest
import six
import os
from mock import Mock
from dwim import const
@pytest.fixture
def load_source(mocker):
return mocker.patch('dwim.conf.load_source')
@pytest.fixture
def environ(monkeypatch):
| 50 | 64 | 31 | 9 | 41 | aoeu/DWIM | tests/test_conf.py | Python | environ | environ | 13 | 17 | 13 | 14 | 7d784e8e6017a46a3342f2146efb15e3154b1e33 | bigcode/the-stack | train |
0dc2843a6c57a645cdd7c109 | train | class | class TestInitializeSettingsFile(object):
def test_ignore_if_exists(self, settings):
settings_path_mock = Mock(is_file=Mock(return_value=True), open=Mock())
settings.user_dir = Mock(joinpath=Mock(return_value=settings_path_mock))
settings._init_settings_file()
assert settings_path_mo... | class TestInitializeSettingsFile(object):
| def test_ignore_if_exists(self, settings):
settings_path_mock = Mock(is_file=Mock(return_value=True), open=Mock())
settings.user_dir = Mock(joinpath=Mock(return_value=settings_path_mock))
settings._init_settings_file()
assert settings_path_mock.is_file.call_count == 1
assert ... | .slow_commands == ['lein', 'react-native', './gradlew']
def test_from_env_with_DEFAULT(self, environ, settings):
environ.update({'DWIM_RULES': 'DEFAULT_RULES:bash:lisp'})
settings.init()
assert settings.rules == const.DEFAULT_RULES + ['bash', 'lisp']
class TestInitializeSettingsFile(object)... | 74 | 74 | 248 | 7 | 67 | aoeu/DWIM | tests/test_conf.py | Python | TestInitializeSettingsFile | TestInitializeSettingsFile | 82 | 104 | 82 | 82 | 7aa831b1e54dc00ffbb93b4253824a7c59475fa3 | bigcode/the-stack | train |
82cc06cebf89feb4c123cbc6 | train | class | @pytest.mark.usefixture('environ')
class TestSettingsFromFile(object):
def test_from_file(self, load_source, settings):
load_source.return_value = Mock(rules=['test'],
wait_command=10,
require_confirmation=True,
... | @pytest.mark.usefixture('environ')
class TestSettingsFromFile(object):
| def test_from_file(self, load_source, settings):
load_source.return_value = Mock(rules=['test'],
wait_command=10,
require_confirmation=True,
no_colors=True,
... | .mark.usefixture('environ')
def test_settings_defaults(load_source, settings):
load_source.return_value = object()
settings.init()
for key, val in const.DEFAULT_SETTINGS.items():
assert getattr(settings, key) == val
@pytest.mark.usefixture('environ')
class TestSettingsFromFile(object):
| 64 | 64 | 196 | 15 | 48 | aoeu/DWIM | tests/test_conf.py | Python | TestSettingsFromFile | TestSettingsFromFile | 28 | 52 | 28 | 29 | bcb630b57c2a78e01f1ea9c7a5bc89d32b6677f2 | bigcode/the-stack | train |
d74550d5bd1d6c22b9120bed | train | function | @pytest.fixture
def load_source(mocker):
return mocker.patch('dwim.conf.load_source')
| @pytest.fixture
def load_source(mocker):
| return mocker.patch('dwim.conf.load_source')
| import pytest
import six
import os
from mock import Mock
from dwim import const
@pytest.fixture
def load_source(mocker):
| 29 | 64 | 21 | 9 | 19 | aoeu/DWIM | tests/test_conf.py | Python | load_source | load_source | 8 | 10 | 8 | 9 | 9f47ee2c14dbdd6f849838d07a874ca2a36705a8 | bigcode/the-stack | train |
43216431628597fd46b14a6e | train | class | @pytest.mark.usefixture('load_source')
class TestSettingsFromEnv(object):
def test_from_env(self, environ, settings):
environ.update({'DWIM_RULES': 'bash:lisp',
'DWIM_EXCLUDE_RULES': 'git:vim',
'DWIM_WAIT_COMMAND': '55',
'DWIM_REQUIRE_C... | @pytest.mark.usefixture('load_source')
class TestSettingsFromEnv(object):
| def test_from_env(self, environ, settings):
environ.update({'DWIM_RULES': 'bash:lisp',
'DWIM_EXCLUDE_RULES': 'git:vim',
'DWIM_WAIT_COMMAND': '55',
'DWIM_REQUIRE_CONFIRMATION': 'true',
'DWIM_NO_COLORS': 'false',
... | ']
def test_from_file_with_DEFAULT(self, load_source, settings):
load_source.return_value = Mock(rules=const.DEFAULT_RULES + ['test'],
wait_command=10,
exclude_rules=[],
require_confirmat... | 86 | 86 | 287 | 15 | 71 | aoeu/DWIM | tests/test_conf.py | Python | TestSettingsFromEnv | TestSettingsFromEnv | 55 | 79 | 55 | 56 | b99ae854d4e07b055c7dcb1d71b450f5350a0f5f | bigcode/the-stack | train |
c23f711e490f5e286a53bdf7 | train | function | def df_maintenance_probabilties():
choice_ml, choices = _create_repl_prob_plot(DICT_POLICIES_4292, keys)
states = np.arange(choice_ml.shape[0]) * BIN_SIZE
return pd.DataFrame(
{
"milage_thousands": states,
0.0: choice_ml[:, 0],
keys[1]: choices[0][:, 0],
... | def df_maintenance_probabilties():
| choice_ml, choices = _create_repl_prob_plot(DICT_POLICIES_4292, keys)
states = np.arange(choice_ml.shape[0]) * BIN_SIZE
return pd.DataFrame(
{
"milage_thousands": states,
0.0: choice_ml[:, 0],
keys[1]: choices[0][:, 0],
keys[2]: choices[1][:, 0],
... | scripts_figures.global_vals_funcs import DISC_FAC
from scripts_figures.global_vals_funcs import PARAMS
from scripts_figures.global_vals_funcs import SPEC_DICT
keys = [0.0, 0.5, 0.95]
max_state = 30
def df_maintenance_probabilties():
| 64 | 64 | 105 | 8 | 55 | robustzurcher/analysis | python/scripts_figures/ex_post/maintenace_probabilities.py | Python | df_maintenance_probabilties | df_maintenance_probabilties | 21 | 31 | 21 | 21 | 8f3c7b5cb9fb5a731104fa2024710f1d6f810e52 | bigcode/the-stack | train |
6b3ff1d76c8ee24a2351c94d | train | function | def _create_repl_prob_plot(file, keys):
ev_ml = np.dot(DICT_POLICIES_4292[0.0][1], DICT_POLICIES_4292[0.0][0])
num_states = ev_ml.shape[0]
costs = calc_obs_costs(num_states, lin_cost, PARAMS, COST_SCALE)
choice_ml = choice_prob_gumbel(ev_ml, costs, DISC_FAC)
choices = []
for omega in keys[1:]:
... | def _create_repl_prob_plot(file, keys):
| ev_ml = np.dot(DICT_POLICIES_4292[0.0][1], DICT_POLICIES_4292[0.0][0])
num_states = ev_ml.shape[0]
costs = calc_obs_costs(num_states, lin_cost, PARAMS, COST_SCALE)
choice_ml = choice_prob_gumbel(ev_ml, costs, DISC_FAC)
choices = []
for omega in keys[1:]:
choices += [
choice_p... | (np.append(states[::5], end))
plt.xlim(right=end)
ax.legend()
fig.savefig(
f"{DIR_FIGURES}/fig-application-maintenance-probabilities"
f"{SPEC_DICT[color]['file']}"
)
def _create_repl_prob_plot(file, keys):
| 64 | 64 | 166 | 11 | 53 | robustzurcher/analysis | python/scripts_figures/ex_post/maintenace_probabilities.py | Python | _create_repl_prob_plot | _create_repl_prob_plot | 72 | 86 | 72 | 72 | 5bbcc8232b024291d95dbcfc6fa2369356a9b517 | bigcode/the-stack | train |
ee61c5b98d932a189d0ddd6e | train | function | def get_maintenance_probabilities():
choice_ml, choices = _create_repl_prob_plot(DICT_POLICIES_4292, keys)
states = np.arange(max_state) * BIN_SIZE
for color in COLOR_OPTS:
fig, ax = plt.subplots(1, 1)
ax.plot(
states,
choice_ml[:max_state, 0],
color=SPE... | def get_maintenance_probabilities():
| choice_ml, choices = _create_repl_prob_plot(DICT_POLICIES_4292, keys)
states = np.arange(max_state) * BIN_SIZE
for color in COLOR_OPTS:
fig, ax = plt.subplots(1, 1)
ax.plot(
states,
choice_ml[:max_state, 0],
color=SPEC_DICT[color]["colors"][0],
... | _4292, keys)
states = np.arange(choice_ml.shape[0]) * BIN_SIZE
return pd.DataFrame(
{
"milage_thousands": states,
0.0: choice_ml[:, 0],
keys[1]: choices[0][:, 0],
keys[2]: choices[1][:, 0],
}
)
def get_maintenance_probabilities():
| 87 | 87 | 293 | 7 | 80 | robustzurcher/analysis | python/scripts_figures/ex_post/maintenace_probabilities.py | Python | get_maintenance_probabilities | get_maintenance_probabilities | 34 | 69 | 34 | 35 | 396d1206ef7fa1e64ae385200caf487e6cee9ec1 | bigcode/the-stack | train |
ecf1ea5d367efdfd627275da | train | function | def _get_brown_perspective_camera():
camera = types.BrownPerspectiveCamera()
camera.width = 800
camera.height = 600
camera.focal_x = 0.6
camera.focal_y = 0.7
camera.c_x = 0.1
camera.c_y = -0.05
camera.k1 = -0.1
camera.k2 = 0.01
camera.p1 = 0.001
camera.p2 = 0.002
camera.k... | def _get_brown_perspective_camera():
| camera = types.BrownPerspectiveCamera()
camera.width = 800
camera.height = 600
camera.focal_x = 0.6
camera.focal_y = 0.7
camera.c_x = 0.1
camera.c_y = -0.05
camera.k1 = -0.1
camera.k2 = 0.01
camera.p1 = 0.001
camera.p2 = 0.002
camera.k3 = 0.01
camera_cpp = pygeometry.... | 6
camera.k1 = -0.1
camera.k2 = 0.01
camera_cpp = pygeometry.Camera.create_perspective(
camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
def _get_brown_perspective_camera():
| 64 | 64 | 191 | 10 | 53 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | _get_brown_perspective_camera | _get_brown_perspective_camera | 202 | 219 | 202 | 202 | 0072d21e4dc4eefb8612b385617252f4103ad0dc | bigcode/the-stack | train |
35960332aa7f915e3af57587 | train | function | def _get_spherical_camera():
camera = types.SphericalCamera()
camera.width = 800
camera.height = 600
camera_cpp = pygeometry.Camera.create_spherical()
return camera, camera_cpp
| def _get_spherical_camera():
| camera = types.SphericalCamera()
camera.width = 800
camera.height = 600
camera_cpp = pygeometry.Camera.create_spherical()
return camera, camera_cpp
| 0.1
camera.k2 = 0.01
camera.transition = 0.5
camera_cpp = pygeometry.Camera.create_dual(
camera.transition, camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
def _get_spherical_camera():
| 64 | 64 | 47 | 7 | 56 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | _get_spherical_camera | _get_spherical_camera | 247 | 252 | 247 | 247 | 2f88ea9856f970bbd77c55312c7f472d9bafd91b | bigcode/the-stack | train |
3b73996bab8a8a8d336ed166 | train | function | def test_single_vs_many():
points = np.array([[1, 2, 3], [4, 5, 6]], dtype=float)
pixels = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=float)
depths = np.array([1, 2], dtype=float)
pose = types.Pose([1, 2, 3], [4, 5, 6])
t_single = [pose.transform(p) for p in points]
t_many = pose.transform_many(p... | def test_single_vs_many():
| points = np.array([[1, 2, 3], [4, 5, 6]], dtype=float)
pixels = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=float)
depths = np.array([1, 2], dtype=float)
pose = types.Pose([1, 2, 3], [4, 5, 6])
t_single = [pose.transform(p) for p in points]
t_many = pose.transform_many(points)
assert np.allclo... | 6])
assert type(p.translation) == np.ndarray
assert p.translation.dtype == float
def test_pose_inverse():
p = types.Pose([1, 2, 3], [4, 5, 6])
inverse = p.inverse()
identity = p.compose(inverse)
assert np.allclose(identity.rotation, [0, 0, 0])
assert np.allclose(identity.translation, [0, ... | 104 | 104 | 349 | 6 | 98 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_single_vs_many | test_single_vs_many | 151 | 187 | 151 | 151 | f4559e615de4bdb3c8183d245957a2a5577a7349 | bigcode/the-stack | train |
ee1dfb81ef9d2165ec02a96e | train | function | def test_dual_camera_projection():
"""Test dual projection--backprojection loop."""
if not context.OPENCV3:
return
for camera in _get_dual_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, ... | def test_dual_camera_projection():
| """Test dual projection--backprojection loop."""
if not context.OPENCV3:
return
for camera in _get_dual_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
| ENCV3:
return
for camera in _get_fisheye_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
def test_dual_camera_projection():
| 64 | 64 | 78 | 7 | 57 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_dual_camera_projection | test_dual_camera_projection | 112 | 120 | 112 | 112 | 8f37ac80c2d005328b8cddf42a8e81fedb583742 | bigcode/the-stack | train |
7e47bcc154cb34110b0ce31c | train | function | def test_fisheye_camera_projection():
"""Test fisheye projection--backprojection loop."""
if not context.OPENCV3:
return
for camera in _get_fisheye_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclos... | def test_fisheye_camera_projection():
| """Test fisheye projection--backprojection loop."""
if not context.OPENCV3:
return
for camera in _get_fisheye_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
| projection--backprojection loop."""
for camera in _get_perspective_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
def test_fisheye_camera_projection():
| 64 | 64 | 82 | 8 | 56 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_fisheye_camera_projection | test_fisheye_camera_projection | 101 | 109 | 101 | 101 | c1117a296a98d46639f33acfe196186d3bda2fb0 | bigcode/the-stack | train |
b0a13c14c14282a64d1c53e4 | train | function | def _get_perspective_camera():
camera = types.PerspectiveCamera()
camera.width = 800
camera.height = 600
camera.focal = 0.6
camera.k1 = -0.1
camera.k2 = 0.01
camera_cpp = pygeometry.Camera.create_perspective(
camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
| def _get_perspective_camera():
| camera = types.PerspectiveCamera()
camera.width = 800
camera.height = 600
camera.focal = 0.6
camera.k1 = -0.1
camera.k2 = 0.01
camera_cpp = pygeometry.Camera.create_perspective(
camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
| if hasattr(camera, 'back_project'):
q_single = [camera.back_project(p, d)
for p, d in zip(pixels, depths)]
q_many = camera.back_project_many(pixels, depths)
assert np.allclose(q_single, q_many)
def _get_perspective_camera():
| 64 | 64 | 93 | 8 | 56 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | _get_perspective_camera | _get_perspective_camera | 190 | 199 | 190 | 190 | 48eef8dc3fddd2ee839122257323333a9ac86b5d | bigcode/the-stack | train |
5bc73ee69d2e82fbb74a3182 | train | function | def test_pose_inverse():
p = types.Pose([1, 2, 3], [4, 5, 6])
inverse = p.inverse()
identity = p.compose(inverse)
assert np.allclose(identity.rotation, [0, 0, 0])
assert np.allclose(identity.translation, [0, 0, 0])
| def test_pose_inverse():
| p = types.Pose([1, 2, 3], [4, 5, 6])
inverse = p.inverse()
identity = p.compose(inverse)
assert np.allclose(identity.rotation, [0, 0, 0])
assert np.allclose(identity.translation, [0, 0, 0])
| 2, 3])
assert type(p.rotation) == np.ndarray
assert p.rotation.dtype == float
assert np.allclose(p.translation, [4, 5, 6])
assert type(p.translation) == np.ndarray
assert p.translation.dtype == float
def test_pose_inverse():
| 64 | 64 | 77 | 5 | 58 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_pose_inverse | test_pose_inverse | 143 | 148 | 143 | 143 | 786a76a37504b13434ecaaf4fba3c34da61d48a0 | bigcode/the-stack | train |
06c556ac6acbfdcbdf5e105e | train | function | def _get_fisheye_camera():
camera = types.FisheyeCamera()
camera.width = 800
camera.height = 600
camera.focal = 0.6
camera.k1 = -0.1
camera.k2 = 0.01
camera_cpp = pygeometry.Camera.create_fisheye(
camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
| def _get_fisheye_camera():
| camera = types.FisheyeCamera()
camera.width = 800
camera.height = 600
camera.focal = 0.6
camera.k1 = -0.1
camera.k2 = 0.01
camera_cpp = pygeometry.Camera.create_fisheye(
camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
| (
camera.focal_x, camera.focal_y / camera.focal_x,
[camera.c_x, camera.c_y],
[camera.k1, camera.k2, camera.k3, camera.p1, camera.p2])
return camera, camera_cpp
def _get_fisheye_camera():
| 64 | 64 | 93 | 8 | 55 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | _get_fisheye_camera | _get_fisheye_camera | 222 | 231 | 222 | 222 | 28c80958e9e8ecec9aba9907676059944ffff28a | bigcode/the-stack | train |
6ff38ae554f6bbce86a6209c | train | function | def _get_dual_camera():
camera = types.DualCamera()
camera.width = 800
camera.height = 600
camera.focal = 0.3
camera.k1 = -0.1
camera.k2 = 0.01
camera.transition = 0.5
camera_cpp = pygeometry.Camera.create_dual(
camera.transition, camera.focal, camera.k1, camera.k2)
return ca... | def _get_dual_camera():
| camera = types.DualCamera()
camera.width = 800
camera.height = 600
camera.focal = 0.3
camera.k1 = -0.1
camera.k2 = 0.01
camera.transition = 0.5
camera_cpp = pygeometry.Camera.create_dual(
camera.transition, camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
| 0.6
camera.k1 = -0.1
camera.k2 = 0.01
camera_cpp = pygeometry.Camera.create_fisheye(
camera.focal, camera.k1, camera.k2)
return camera, camera_cpp
def _get_dual_camera():
| 64 | 64 | 102 | 7 | 56 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | _get_dual_camera | _get_dual_camera | 234 | 244 | 234 | 234 | 5b1d5c645cfb35f92831c0af702c26cff14a62b1 | bigcode/the-stack | train |
69b883759b2e7b03adcb8bdd | train | function | def test_perspective_camera_projection():
"""Test perspectiive projection--backprojection loop."""
for camera in _get_perspective_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
| def test_perspective_camera_projection():
| """Test perspectiive projection--backprojection loop."""
for camera in _get_perspective_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
| == camera
assert reconstruction.get_camera(1) is None
assert reconstruction.get_shot(shot0.id) == shot0
assert reconstruction.get_shot(shot1.id) == shot1
assert reconstruction.get_shot(2) is None
def test_perspective_camera_projection():
| 64 | 64 | 70 | 8 | 55 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_perspective_camera_projection | test_perspective_camera_projection | 92 | 98 | 92 | 92 | eb5cb2b0ef9b08746c0e28fc269289240b7811d5 | bigcode/the-stack | train |
6a80a1fdfa8c3948c2fa203a | train | function | def test_spherical_camera_projection():
"""Test spherical projection--backprojection loop."""
for camera in _get_spherical_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
| def test_spherical_camera_projection():
| """Test spherical projection--backprojection loop."""
for camera in _get_spherical_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
| .OPENCV3:
return
for camera in _get_dual_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
def test_spherical_camera_projection():
| 64 | 64 | 66 | 7 | 57 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_spherical_camera_projection | test_spherical_camera_projection | 123 | 129 | 123 | 123 | dc165f22b6133f921f4350c8257ceb6babadca1b | bigcode/the-stack | train |
9a6c2acd0f2e74300261f63f | train | function | def test_reconstruction_class_initialization():
# Instantiate Reconstruction
reconstruction = types.Reconstruction()
# Instantiate camera instrinsics
camera = types.PerspectiveCamera()
camera.id = 'apple iphone 4s back camera 4.28mm f/2.4'
camera.focal = 0.9722222222222222
camera.k1 = 0.00... | def test_reconstruction_class_initialization():
# Instantiate Reconstruction
| reconstruction = types.Reconstruction()
# Instantiate camera instrinsics
camera = types.PerspectiveCamera()
camera.id = 'apple iphone 4s back camera 4.28mm f/2.4'
camera.focal = 0.9722222222222222
camera.k1 = 0.006094395128698237
camera.k2 = -0.0004952058188617129
camera.height = 2448
... | theta": {
"projection_type": "equirectangular"
}
},
"shots" : {
'im1': {
"camera": "theta",
"rotation": [0.0, 0.0, 0.0],
"translation": [0.0, 0.0, 0.0],
},
'im2': {
"camera": "theta",
"rotation": [0, 0, 0.0]... | 147 | 147 | 492 | 13 | 134 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_reconstruction_class_initialization | test_reconstruction_class_initialization | 36 | 89 | 36 | 38 | 776c469ce037283027bf2cf53020fa00df22022e | bigcode/the-stack | train |
198b2c8a855b49283b96125c | train | function | def test_pose_properties():
"""Test pose constructor, getters and setters."""
p = types.Pose([1, 2, 3], [4, 5, 6])
assert np.allclose(p.rotation, [1, 2, 3])
assert type(p.rotation) == np.ndarray
assert p.rotation.dtype == float
assert np.allclose(p.translation, [4, 5, 6])
assert type(p.trans... | def test_pose_properties():
| """Test pose constructor, getters and setters."""
p = types.Pose([1, 2, 3], [4, 5, 6])
assert np.allclose(p.rotation, [1, 2, 3])
assert type(p.rotation) == np.ndarray
assert p.rotation.dtype == float
assert np.allclose(p.translation, [4, 5, 6])
assert type(p.translation) == np.ndarray
as... | """Test spherical projection--backprojection loop."""
for camera in _get_spherical_camera():
pixel = [0.1, 0.2]
bearing = camera.pixel_bearing(pixel)
projected = camera.project(bearing)
assert np.allclose(pixel, projected)
def test_pose_properties():
| 64 | 64 | 109 | 5 | 59 | santelelle/OpenSfM | opensfm/test/test_types.py | Python | test_pose_properties | test_pose_properties | 132 | 140 | 132 | 132 | 707129a9918c4a49d11a42e3f5953101d2bd739a | bigcode/the-stack | train |
bee1fe45582876698d761001 | train | class | class ApplicationsApiTests(APITestCase, URLPatternsTestCase):
urlpatterns = [path("api/", include(formidable.urls.common_urls))]
list_url = reverse("application-list")
def setUp(self) -> None:
self.form: Form = FormFactory.create()
self.section: Section = SectionFactory.create(form=self.for... | class ApplicationsApiTests(APITestCase, URLPatternsTestCase):
| urlpatterns = [path("api/", include(formidable.urls.common_urls))]
list_url = reverse("application-list")
def setUp(self) -> None:
self.form: Form = FormFactory.create()
self.section: Section = SectionFactory.create(form=self.form)
self.fields: List[Field] = FieldFactory.create_batc... | , URLPatternsTestCase
import formidable.urls
from administration.models import User
from formidable.models import Form, Section, Field
from tests.formidable.factories import (
FormFactory,
SectionFactory,
FieldFactory,
UserFactory,
)
class ApplicationsApiTests(APITestCase, URLPatternsTestCase):
| 64 | 64 | 183 | 13 | 51 | danpercic86/formidable-backend | src/tests/formidable/api/test_applications_api.py | Python | ApplicationsApiTests | ApplicationsApiTests | 17 | 33 | 17 | 17 | 3463c6d5ea21b8a5e1d26cc2c899116c1d148198 | bigcode/the-stack | train |
e2279dad03aa6879c09424b0 | train | function | def _jupyter_server_extension_paths():
return [{"module": "qiime2.jupyter"}]
| def _jupyter_server_extension_paths():
| return [{"module": "qiime2.jupyter"}]
| ='qiime2'))
__website__ = 'https://qiime2.org'
__all__ = ['Artifact', 'Visualization', 'Metadata', 'MetadataColumn',
'CategoricalMetadataColumn', 'NumericMetadataColumn']
# Used by `jupyter serverextension enable`
def _jupyter_server_extension_paths():
| 64 | 64 | 21 | 8 | 56 | emollier/qiime2 | qiime2/__init__.py | Python | _jupyter_server_extension_paths | _jupyter_server_extension_paths | 30 | 31 | 30 | 30 | 9f234bd003a00af8d94c21d2d0cb0ac7e4ff54f5 | bigcode/the-stack | train |
d1855de5bdf7de4a906d5384 | train | function | def parse_line(line):
line = line.strip().split()
e1, relation, e2 = line[0].strip(), line[1].strip(), line[2].strip()
return e1, relation, e2
| def parse_line(line):
| line = line.strip().split()
e1, relation, e2 = line[0].strip(), line[1].strip(), line[2].strip()
return e1, relation, e2
| split()])
with open(relation_file) as f:
for line in f:
relation_emb.append([float(val) for val in line.strip().split()])
return np.array(entity_emb, dtype=np.float32), np.array(relation_emb, dtype=np.float32)
def parse_line(line):
| 64 | 64 | 50 | 5 | 59 | ansonb/RECON | GAT_sep_space/preprocess.py | Python | parse_line | parse_line | 42 | 45 | 42 | 42 | 16f59abc3b234c50294acf5f2761fc0076cca74f | bigcode/the-stack | train |
55998f27865338b94b656c2e | train | function | def init_embeddings(entity_file, relation_file):
entity_emb, relation_emb = [], []
with open(entity_file) as f:
for line in f:
entity_emb.append([float(val) for val in line.strip().split()])
with open(relation_file) as f:
for line in f:
relation_emb.append([float(va... | def init_embeddings(entity_file, relation_file):
| entity_emb, relation_emb = [], []
with open(entity_file) as f:
for line in f:
entity_emb.append([float(val) for val in line.strip().split()])
with open(relation_file) as f:
for line in f:
relation_emb.append([float(val) for val in line.strip().split()])
return ... | len(line.strip().split()) > 1:
relation, relation_id = line.strip().split(
)[0].strip(), line.strip().split()[1].strip()
relation2id[relation] = int(relation_id)
return relation2id
def init_embeddings(entity_file, relation_file):
| 64 | 64 | 106 | 9 | 54 | ansonb/RECON | GAT_sep_space/preprocess.py | Python | init_embeddings | init_embeddings | 28 | 39 | 28 | 28 | b041141add4c8a8b5d7ce6bbe813adb3c9b41fe8 | bigcode/the-stack | train |
d906a1fef354fff6f1debf40 | train | function | def read_relation_from_id(filename='./data/WN18RR/relation2id.txt'):
relation2id = {}
with open(filename, 'r') as f:
for line in f:
if len(line.strip().split()) > 1:
relation, relation_id = line.strip().split(
)[0].strip(), line.strip().split()[1].strip()
... | def read_relation_from_id(filename='./data/WN18RR/relation2id.txt'):
| relation2id = {}
with open(filename, 'r') as f:
for line in f:
if len(line.strip().split()) > 1:
relation, relation_id = line.strip().split(
)[0].strip(), line.strip().split()[1].strip()
relation2id[relation] = int(relation_id)
return relat... | 1:
entity, entity_id = line.strip().split(
)[0].strip(), line.strip().split()[1].strip()
entity2id[entity] = int(entity_id)
return entity2id
def read_relation_from_id(filename='./data/WN18RR/relation2id.txt'):
| 64 | 64 | 98 | 18 | 45 | ansonb/RECON | GAT_sep_space/preprocess.py | Python | read_relation_from_id | read_relation_from_id | 17 | 25 | 17 | 17 | 96604ba36ccdc9debaad71d135da7260ca34dcf3 | bigcode/the-stack | train |
f06df3ada86216862e9a55bb | train | function | def read_entity_from_id(filename='./data/WN18RR/entity2id.txt'):
entity2id = {}
with open(filename, 'r') as f:
for line in f:
if len(line.strip().split()) > 1:
entity, entity_id = line.strip().split(
)[0].strip(), line.strip().split()[1].strip()
... | def read_entity_from_id(filename='./data/WN18RR/entity2id.txt'):
| entity2id = {}
with open(filename, 'r') as f:
for line in f:
if len(line.strip().split()) > 1:
entity, entity_id = line.strip().split(
)[0].strip(), line.strip().split()[1].strip()
entity2id[entity] = int(entity_id)
return entity2id
| import torch
import os
import numpy as np
def read_entity_from_id(filename='./data/WN18RR/entity2id.txt'):
| 28 | 64 | 96 | 17 | 10 | ansonb/RECON | GAT_sep_space/preprocess.py | Python | read_entity_from_id | read_entity_from_id | 6 | 14 | 6 | 6 | b81b3e6141dcaeecd8c44b370a6347ffb7ef0b84 | bigcode/the-stack | train |
988f6b8c03f68d942801494e | train | function | def build_data(path='./data/WN18RR/', is_unweigted=False, directed=True):
entity2id = read_entity_from_id(os.path.join(path,'entity2id.txt'))
relation2id = read_relation_from_id(os.path.join(path,'relation2id.txt'))
# Adjacency matrix only required for training phase
# Currenlty creating as unweighted,... | def build_data(path='./data/WN18RR/', is_unweigted=False, directed=True):
| entity2id = read_entity_from_id(os.path.join(path,'entity2id.txt'))
relation2id = read_relation_from_id(os.path.join(path,'relation2id.txt'))
# Adjacency matrix only required for training phase
# Currenlty creating as unweighted, undirected
train_triples, train_adjacency_mat, unique_entities_train ... | rows, cols, data = [], [], []
unique_entities = set()
for line in lines:
if line.strip()=='':
continue
e1, relation, e2 = parse_line(line)
unique_entities.add(e1)
unique_entities.add(e2)
triples_data.append(
(entity2id[e1], relation2id[relation],... | 245 | 245 | 819 | 21 | 224 | ansonb/RECON | GAT_sep_space/preprocess.py | Python | build_data | build_data | 90 | 156 | 90 | 90 | ce200e9916137aa1e85f61fea40a94b82a67bfe0 | bigcode/the-stack | train |
0958e3acaffdbed7e7c300c5 | train | function | def load_data(filename, entity2id, relation2id, is_unweigted=False, directed=True):
with open(filename) as f:
lines = f.readlines()
# this is list for relation triples
triples_data = []
# for sparse tensor, rows list contains corresponding row of sparse tensor, cols list contains corresponding... | def load_data(filename, entity2id, relation2id, is_unweigted=False, directed=True):
| with open(filename) as f:
lines = f.readlines()
# this is list for relation triples
triples_data = []
# for sparse tensor, rows list contains corresponding row of sparse tensor, cols list contains corresponding
# columnn of sparse tensor, data contains the type of relation
# Adjacecny ... | line.strip().split()])
return np.array(entity_emb, dtype=np.float32), np.array(relation_emb, dtype=np.float32)
def parse_line(line):
line = line.strip().split()
e1, relation, e2 = line[0].strip(), line[1].strip(), line[2].strip()
return e1, relation, e2
def load_data(filename, entity2id, relation2id... | 102 | 102 | 343 | 23 | 78 | ansonb/RECON | GAT_sep_space/preprocess.py | Python | load_data | load_data | 48 | 87 | 48 | 48 | 3ef05fcca88b1804bc109f48ce2d35b98ef5f970 | bigcode/the-stack | train |
93e97bef647593b441dd8c63 | train | class | class APIExtension(object):
ATTRIBUTES = [
'name', 'namespace', 'enabled', 'exchange', 'routingKey', 'priority',
'isAuthorizationEnabled', 'href', 'id'
]
def __init__(self, client):
"""Constructor for APIExtension object.
:param pyvcloud.vcd.client.Client client: the client... | class APIExtension(object):
| ATTRIBUTES = [
'name', 'namespace', 'enabled', 'exchange', 'routingKey', 'priority',
'isAuthorizationEnabled', 'href', 'id'
]
def __init__(self, client):
"""Constructor for APIExtension object.
:param pyvcloud.vcd.client.Client client: the client that will be used
... | VMware vCloud Director Python SDK
# Copyright (c) 2018 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 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
#
... | 256 | 256 | 1,866 | 5 | 250 | zenddignite/pyvcloud | pyvcloud/vcd/api_extension.py | Python | APIExtension | APIExtension | 29 | 255 | 29 | 29 | f3ffd08976c8fea59affb3d9691fd77f276c3e0a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.