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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7938f6f9b04c0ea951c7e0c9 | train | class | class ReferenceNumberSerializer(serializers.ModelSerializer):
class Meta:
model = ReferenceNumber
fields = ["id", "name"]
| class ReferenceNumberSerializer(serializers.ModelSerializer):
| class Meta:
model = ReferenceNumber
fields = ["id", "name"]
| .serializers import UserLogModelSerializer
from ..institutions.models import Institution
from .models import DocumentType, Letter, ReferenceNumber
class DocumentTypeSerializer(serializers.ModelSerializer):
class Meta:
model = DocumentType
fields = ["id", "name"]
class ReferenceNumberSerializer(ser... | 63 | 64 | 27 | 8 | 55 | merito/small_eod | backend-project/small_eod/letters/serializers.py | Python | ReferenceNumberSerializer | ReferenceNumberSerializer | 21 | 24 | 21 | 21 | 19f5944f5ad885c73bb1dbce5e4fd89102007466 | bigcode/the-stack | train |
6fe55ba3dcaf165c51ccf850 | train | class | class DocumentTypeSerializer(serializers.ModelSerializer):
class Meta:
model = DocumentType
fields = ["id", "name"]
| class DocumentTypeSerializer(serializers.ModelSerializer):
| class Meta:
model = DocumentType
fields = ["id", "name"]
| from ..channels.models import Channel
from ..files.apps import minio_app
from ..files.serializers import FileSerializer
from ..generic.serializers import UserLogModelSerializer
from ..institutions.models import Institution
from .models import DocumentType, Letter, ReferenceNumber
class DocumentTypeSerializer(serializer... | 64 | 64 | 27 | 8 | 55 | merito/small_eod | backend-project/small_eod/letters/serializers.py | Python | DocumentTypeSerializer | DocumentTypeSerializer | 15 | 18 | 15 | 15 | 65105a339b9290585b7c3a8e938586d0bb6cf940 | bigcode/the-stack | train |
2b830c80b7a47c4b65b1899d | train | class | class SignRequestSerializer(serializers.Serializer):
name = serializers.CharField(max_length=200)
method = serializers.CharField(read_only=True)
url = serializers.CharField(read_only=True)
formData = serializers.DictField(read_only=True, child=serializers.CharField())
path = serializers.CharField(re... | class SignRequestSerializer(serializers.Serializer):
| name = serializers.CharField(max_length=200)
method = serializers.CharField(read_only=True)
url = serializers.CharField(read_only=True)
formData = serializers.DictField(read_only=True, child=serializers.CharField())
path = serializers.CharField(read_only=True)
def create(self, validated_data):
... | ")
reference_number = (
ReferenceNumber.objects.get_or_create(name=reference_number_value)[0]
if reference_number_value is not None
else None
)
validated_data["reference_number"] = reference_number
return super().update(instanc... | 64 | 64 | 151 | 7 | 57 | merito/small_eod | backend-project/small_eod/letters/serializers.py | Python | SignRequestSerializer | SignRequestSerializer | 115 | 131 | 115 | 115 | dcd5ec0a25f2c798b1cbfe064252887e760e33b3 | bigcode/the-stack | train |
8e57d1a5f5043ff653b22fe2 | train | class | class LetterSerializer(UserLogModelSerializer):
reference_number = serializers.CharField(default=None)
document_type = serializers.PrimaryKeyRelatedField(
many=False, default=None, queryset=DocumentType.objects.all()
)
case = serializers.PrimaryKeyRelatedField(
many=False, default=None, ... | class LetterSerializer(UserLogModelSerializer):
| reference_number = serializers.CharField(default=None)
document_type = serializers.PrimaryKeyRelatedField(
many=False, default=None, queryset=DocumentType.objects.all()
)
case = serializers.PrimaryKeyRelatedField(
many=False, default=None, queryset=Case.objects.all()
)
institutio... | from uuid import uuid4
from django.conf import settings
from rest_framework import serializers
from ..cases.models import Case
from ..channels.models import Channel
from ..files.apps import minio_app
from ..files.serializers import FileSerializer
from ..generic.serializers import UserLogModelSerializer
from ..institu... | 144 | 180 | 603 | 8 | 136 | merito/small_eod | backend-project/small_eod/letters/serializers.py | Python | LetterSerializer | LetterSerializer | 27 | 112 | 27 | 27 | 5d0946a47c8eb3ddd0ee96d0d53fc31efca8ce72 | bigcode/the-stack | train |
3d6be920422256039bdb59fb | train | function | def get_network(args):
""" return given network
"""
if args.MODEL.NAME == 'vgg16':
from models.vgg import vgg16_bn
net = vgg16_bn()
elif args.MODEL.NAME == 'vgg13':
from models.vgg import vgg13_bn
net = vgg13_bn()
elif args.MODEL.NAME == 'vgg11':
from models.vgg import vgg11_bn
net = vgg11_bn()
elif a... | def get_network(args):
| """ return given network
"""
if args.MODEL.NAME == 'vgg16':
from models.vgg import vgg16_bn
net = vgg16_bn()
elif args.MODEL.NAME == 'vgg13':
from models.vgg import vgg13_bn
net = vgg13_bn()
elif args.MODEL.NAME == 'vgg11':
from models.vgg import vgg11_bn
net = vgg11_bn()
elif args.MODEL.NAME == 'vgg1... | import sys
def get_network(args):
| 8 | 256 | 1,438 | 5 | 2 | kingqiuol/pytorch-template | models/get_networks.py | Python | get_network | get_network | 4 | 150 | 4 | 4 | c0db5775e86bec8f82b5858fb886b957713c5702 | bigcode/the-stack | train |
c41ed4c71b769b8bab991162 | train | class | class AlgBody(Algorithm):
"""
Guo Hall thinning implementation.
"""
def __init__(self):
"""
Instance vars:
| *name* : name of the algorithm
| *parent* : name of the appropriate category
"""
Algorithm.__init__(self)
self.name = "Guo Hall Gr... | class AlgBody(Algorithm):
| """
Guo Hall thinning implementation.
"""
def __init__(self):
"""
Instance vars:
| *name* : name of the algorithm
| *parent* : name of the appropriate category
"""
Algorithm.__init__(self)
self.name = "Guo Hall Graph Detection"
sel... | .model.algorithms._alg import Algorithm
import cv2
import networkx as nx
import numpy as np
import thinning
import sys
import traceback
from collections import defaultdict
from itertools import chain
__author__ = {"Adrian Neumann": "", "Pavel Shkadzko": "p.shkadzko@gmail.com"}
class AlgBody(Algorithm):
| 76 | 77 | 257 | 6 | 70 | hronellenfitsch/nefi | nefi2/model/algorithms/guo_hall.py | Python | AlgBody | AlgBody | 26 | 61 | 26 | 26 | 05014a6dc796a107db2582d3c61fb339046df91f | bigcode/the-stack | train |
7a9e8afa0a08c9c3f123a108 | train | function | def zhang_suen_node_detection(skel):
"""
(from nefi1)
Node detection based on criteria put forward in "A fast parallel algorithm
for thinning digital patterns" by T. Y. Zhang and C. Y. Suen. Pixels p of
the skeleton are categorized as nodes/non-nodes based on the value of a
function A(p) dependi... | def zhang_suen_node_detection(skel):
| """
(from nefi1)
Node detection based on criteria put forward in "A fast parallel algorithm
for thinning digital patterns" by T. Y. Zhang and C. Y. Suen. Pixels p of
the skeleton are categorized as nodes/non-nodes based on the value of a
function A(p) depending on the pixel neighborhood of p. Pl... | name of the algorithm
| *parent* : name of the appropriate category
"""
Algorithm.__init__(self)
self.name = "Guo Hall Graph Detection"
self.parent = "Graph Detection"
def process(self, args):
"""
Guo Hall thinning.
Use ```zhang_suen_node_detect... | 231 | 231 | 770 | 10 | 220 | hronellenfitsch/nefi | nefi2/model/algorithms/guo_hall.py | Python | zhang_suen_node_detection | zhang_suen_node_detection | 63 | 130 | 63 | 63 | 1cbeb28aac07d3d91a9d84139b06b46636e702a9 | bigcode/the-stack | train |
3425de663cf78576a280c6bd | train | function | def breadth_first_edge_detection(skel, segmented, graph):
"""
(from nefi1)
Detect edges in the skeletonized image.
Also compute the following edge properties:
| *pixels* : number of pixels on the edge in the skeleton
| *length* : length in pixels, horizontal/vertikal steps count 1,
... | def breadth_first_edge_detection(skel, segmented, graph):
| """
(from nefi1)
Detect edges in the skeletonized image.
Also compute the following edge properties:
| *pixels* : number of pixels on the edge in the skeleton
| *length* : length in pixels, horizontal/vertikal steps count 1,
diagonal steps count sqrt 2
| *width* : the... | 1 is the pixel whose neighborhood is beeing checked
components = (p2 == 0 and p3 == 1) + (p3 == 0 and p4 == 1) + \
(p4 == 0 and p5 == 1) + (p5 == 0 and p6 == 1) + \
(p6 == 0 and p7 == 1) + (p7 == 0 and p8 == 1) + \
(p8 == 0 and p9 == 1) + (p9 == 0 a... | 256 | 256 | 970 | 12 | 243 | hronellenfitsch/nefi | nefi2/model/algorithms/guo_hall.py | Python | breadth_first_edge_detection | breadth_first_edge_detection | 132 | 228 | 132 | 132 | 383b9a77a318721cbd48567db0e896604e364bba | bigcode/the-stack | train |
e4d48cf80adb573b204d0366 | train | function | def generate_gaussian_noise_by_radius(image, radius):
"""
Add Gaussian noise of an intended radius to an image
:param image: an image input
:param radius: the radius of the blur
:type image: an image file
:type radius: int (representing pixel)
"""
return image.filter(ImageFilter.Gaussian... | def generate_gaussian_noise_by_radius(image, radius):
| """
Add Gaussian noise of an intended radius to an image
:param image: an image input
:param radius: the radius of the blur
:type image: an image file
:type radius: int (representing pixel)
"""
return image.filter(ImageFilter.GaussianBlur(radius = radius))
| image file
:type level: a float from 0.0 to 100.0
:type width: int (representing pixels)
"""
return image.filter(ImageFilter.GaussianBlur(radius = int(width*level/200)))
def generate_gaussian_noise_by_radius(image, radius):
| 64 | 64 | 81 | 11 | 53 | liyu711/SUAS | UpdatedImageProcessing/UpdatedImageProcessing/ShapeDetection/utils/gaussian_blur.py | Python | generate_gaussian_noise_by_radius | generate_gaussian_noise_by_radius | 17 | 25 | 17 | 17 | 488d965ecade79314df65a46853e70a595178fd1 | bigcode/the-stack | train |
4437dd005fc1f76ec83d2859 | train | function | def generate_gaussian_noise_by_level(image, level, width):
"""
Add Gaussian noise of an intended level to an image.
:param image: an image input
:param level: represent the percentage of blur. (Ex: level 1 means that the
image is blurred with the radius of 0.5 percent of its width.)
... | def generate_gaussian_noise_by_level(image, level, width):
| """
Add Gaussian noise of an intended level to an image.
:param image: an image input
:param level: represent the percentage of blur. (Ex: level 1 means that the
image is blurred with the radius of 0.5 percent of its width.)
:param width: the width that the level refers to. Input i... | from PIL import ImageFilter
def generate_gaussian_noise_by_level(image, level, width):
| 19 | 64 | 166 | 13 | 5 | liyu711/SUAS | UpdatedImageProcessing/UpdatedImageProcessing/ShapeDetection/utils/gaussian_blur.py | Python | generate_gaussian_noise_by_level | generate_gaussian_noise_by_level | 3 | 15 | 3 | 3 | 65d7a82fff36280d96a580bb85ef6bc3ae26d71a | bigcode/the-stack | train |
1506c8d733308ad117e42b64 | train | class | class Produto (models.Model):
nome=models.CharField(max_length=100)
preco=models.FloatField()
categoria=models.CharField(choices=Categoria_choices,max_length=10)
imagem=models.ImageField(upload_to='media/',null=True)
class Meta :
verbose_name='Produto'
verbose_name_plural='Produto... | class Produto (models.Model):
| nome=models.CharField(max_length=100)
preco=models.FloatField()
categoria=models.CharField(choices=Categoria_choices,max_length=10)
imagem=models.ImageField(upload_to='media/',null=True)
class Meta :
verbose_name='Produto'
verbose_name_plural='Produtos'
def __str__(self):
... | =(
('H','Hortifruti'),
('C','Carnes',),
('F','Frios'),
('U','Utensilos'),
)
# class Categoria(models.Model):
# nome=models.CharField(choices=Categoria_choices,max_length=10)
class Produto (models.Model):
| 64 | 64 | 79 | 6 | 58 | Cauan2305/APIs-Mercado-Django | core/models.py | Python | Produto | Produto | 16 | 31 | 16 | 16 | 8475f04740f84470142aba12dc039db943ab7c1e | bigcode/the-stack | train |
78fdda881533f5efa0bef8fb | train | class | class DeepQuantumNeuralNetwork(Model):
"""Creates a quantum neural network with a specified feature map and variational form."""
def __init__(self, instructure, feature_map, neural_qubit=1, post_processing=None):
"""
:param feature_map: quantum circuit, feature map for the data
:param v... | class DeepQuantumNeuralNetwork(Model):
| """Creates a quantum neural network with a specified feature map and variational form."""
def __init__(self, instructure, feature_map, neural_qubit=1, post_processing=None):
"""
:param feature_map: quantum circuit, feature map for the data
:param var_form: quantum circuit, parameterised... | _Pauli_rotation_gate([start],[2],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([start],[3],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([end],[1],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([end],[2],np.random.rand())
circuit.add_parametr... | 256 | 256 | 2,555 | 8 | 247 | yuguoshao/QDNN_eDim | QDNN/qdnn.py | Python | DeepQuantumNeuralNetwork | DeepQuantumNeuralNetwork | 59 | 321 | 59 | 59 | 92ddb53d7768e281002f9576b3119c6f8d314dc5 | bigcode/the-stack | train |
50c039a64ae40afc521df835 | train | function | def qnn_instructure(instructure, circuit):
QubitArray = instructure_QubitArray(instructure)
for layer in range(len(instructure)):
if layer == 0:
pass
else:
for target in QubitArray[layer]:
for source in QubitArray[layer - 1]:
u(circuit,... | def qnn_instructure(instructure, circuit):
| QubitArray = instructure_QubitArray(instructure)
for layer in range(len(instructure)):
if layer == 0:
pass
else:
for target in QubitArray[layer]:
for source in QubitArray[layer - 1]:
u(circuit, source, target)
pass
... | structure):
QubitArray = []
last = 0
for layer in range(len(instructure)):
QubitArray.append([last + i for i in range(instructure[layer])])
last += instructure[layer]
return QubitArray
def qnn_instructure(instructure, circuit):
| 64 | 64 | 90 | 10 | 53 | yuguoshao/QDNN_eDim | QDNN/qdnn.py | Python | qnn_instructure | qnn_instructure | 43 | 56 | 43 | 43 | de0572e88ad778b364a00354a81f306de0d15f2c | bigcode/the-stack | train |
4ae71ae705f76a84c4957314 | train | function | def u(circuit, start, end):
circuit.add_parametric_multi_Pauli_rotation_gate([start,end],[1,1],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([start,end],[2,2],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([start,end],[3,3],np.random.rand())
circuit.add_parametri... | def u(circuit, start, end):
| circuit.add_parametric_multi_Pauli_rotation_gate([start,end],[1,1],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([start,end],[2,2],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([start,end],[3,3],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate(... | iskit
from qulacs import ParametricQuantumCircuit,QuantumState
from typing import List, Union
from collections import OrderedDict
import itertools
from qiskit.quantum_info import Statevector
import multiprocessing as mp
from effective_dimension import Model
import qulacs
# This class creates a quantum model that compr... | 101 | 101 | 339 | 9 | 91 | yuguoshao/QDNN_eDim | QDNN/qdnn.py | Python | u | u | 15 | 31 | 15 | 15 | 43dfc31598f893f9538a950aced1f1dfd161e766 | bigcode/the-stack | train |
3890215eb990999e125b4861 | train | function | def instructure_QubitArray(instructure):
QubitArray = []
last = 0
for layer in range(len(instructure)):
QubitArray.append([last + i for i in range(instructure[layer])])
last += instructure[layer]
return QubitArray
| def instructure_QubitArray(instructure):
| QubitArray = []
last = 0
for layer in range(len(instructure)):
QubitArray.append([last + i for i in range(instructure[layer])])
last += instructure[layer]
return QubitArray
| uli_rotation_gate([end],[1],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([end],[2],np.random.rand())
circuit.add_parametric_multi_Pauli_rotation_gate([end],[3],np.random.rand())
pass
def instructure_QubitArray(instructure):
| 64 | 64 | 61 | 9 | 54 | yuguoshao/QDNN_eDim | QDNN/qdnn.py | Python | instructure_QubitArray | instructure_QubitArray | 34 | 40 | 34 | 34 | 1a2ab4d60914d8026e315e9086c87d9eac9f6305 | bigcode/the-stack | train |
0ab4d11811ce763572b55b32 | train | function | def get_datetime():
"""Get datetime.now() in a specific format"""
_today = dt.now().strftime(DATETIME_FMT)
return _today
| def get_datetime():
| """Get datetime.now() in a specific format"""
_today = dt.now().strftime(DATETIME_FMT)
return _today
| inja2 import Template
FILENAME = "README.md"
README_PATH = os.path.join("../", FILENAME)
TEMPLATE = "templates/README.md.jinja"
FILENAME_CSV = "data/conferences.csv"
DATETIME_FMT = "%Y-%m-%d %H:%M"
def get_datetime():
| 64 | 64 | 33 | 4 | 60 | markgreene74/markgreene74 | update_readme/update_readme.py | Python | get_datetime | get_datetime | 13 | 16 | 13 | 13 | 237bd0e8c244ed6352596514fe6da3046a118f2b | bigcode/the-stack | train |
a6cdd422082ae7579f9f6eea | train | function | def write_readme():
"""Write the readme file from a jinja template"""
with open(TEMPLATE) as f:
readme_jinja = f.read()
current_year = dt.now().year
conf_new, conf_old = build_conf_list(year=current_year)
template = Template(readme_jinja)
readme_rendered = template.render(
last... | def write_readme():
| """Write the readme file from a jinja template"""
with open(TEMPLATE) as f:
readme_jinja = f.read()
current_year = dt.now().year
conf_new, conf_old = build_conf_list(year=current_year)
template = Template(readme_jinja)
readme_rendered = template.render(
last_updated=get_datetim... | conf in all_conferences if conf["end"].year >= y]
conf_old = [conf for conf in all_conferences if conf["end"].year < y]
else:
conf_new = all_conferences
conf_old = []
return conf_new, conf_old
def write_readme():
| 64 | 64 | 126 | 5 | 58 | markgreene74/markgreene74 | update_readme/update_readme.py | Python | write_readme | write_readme | 54 | 71 | 54 | 54 | 401b9bf623c25bdee5f439f6f04f5446899da6d7 | bigcode/the-stack | train |
765f5c36b0bccfd7ddf5f8ff | train | function | def build_conf_list(csv_file=FILENAME_CSV, year=None):
"""Parse the csv file, extract and process the data"""
with open(csv_file) as f:
data = DictReader(f)
all_conferences = [row for row in data]
# "conference","start","end","online","fee","registered","attended","website"
# process th... | def build_conf_list(csv_file=FILENAME_CSV, year=None):
| """Parse the csv file, extract and process the data"""
with open(csv_file) as f:
data = DictReader(f)
all_conferences = [row for row in data]
# "conference","start","end","online","fee","registered","attended","website"
# process the data
for conf in all_conferences:
# repla... | from jinja2 import Template
FILENAME = "README.md"
README_PATH = os.path.join("../", FILENAME)
TEMPLATE = "templates/README.md.jinja"
FILENAME_CSV = "data/conferences.csv"
DATETIME_FMT = "%Y-%m-%d %H:%M"
def get_datetime():
"""Get datetime.now() in a specific format"""
_today = dt.now().strftime(DATETIME_FMT... | 110 | 110 | 368 | 15 | 94 | markgreene74/markgreene74 | update_readme/update_readme.py | Python | build_conf_list | build_conf_list | 19 | 51 | 19 | 19 | 2a989d146666af2f3a6f3e440fa833c1c9d3c5cc | bigcode/the-stack | train |
41edfde66bf755f1d2c09a0c | train | function | def _urlsafe_b64encode(raw_bytes):
raw_bytes = _to_bytes(raw_bytes, encoding='utf-8')
return base64.urlsafe_b64encode(raw_bytes).rstrip(b'=')
| def _urlsafe_b64encode(raw_bytes):
| raw_bytes = _to_bytes(raw_bytes, encoding='utf-8')
return base64.urlsafe_b64encode(raw_bytes).rstrip(b'=')
| ('utf-8')
if isinstance(value, six.binary_type) else value)
if isinstance(result, six.text_type):
return result
else:
raise ValueError(
'{0!r} could not be converted to unicode'.format(value))
def _urlsafe_b64encode(raw_bytes):
| 64 | 64 | 43 | 10 | 54 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | _urlsafe_b64encode | _urlsafe_b64encode | 332 | 334 | 332 | 332 | 7b3045c11586f252d085aecdd3d7b6584f833ff5 | bigcode/the-stack | train |
7aeb16791e45bce69623735f | train | function | def parse_unique_urlencoded(content):
"""Parses unique key-value parameters from urlencoded content.
Args:
content: string, URL-encoded key-value pairs.
Returns:
dict, The key-value pairs from ``content``.
Raises:
ValueError: if one of the keys is repeated.
"""
urlenco... | def parse_unique_urlencoded(content):
| """Parses unique key-value parameters from urlencoded content.
Args:
content: string, URL-encoded key-value pairs.
Returns:
dict, The key-value pairs from ``content``.
Raises:
ValueError: if one of the keys is repeated.
"""
urlencoded_params = urllib.parse.parse_qs(con... | :
scopes: a string or iterable of strings, the scopes.
Returns:
The scopes in a list.
"""
if not scopes:
return []
elif isinstance(scopes, six.string_types):
return scopes.split(' ')
else:
return scopes
def parse_unique_urlencoded(content):
| 64 | 64 | 152 | 7 | 56 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | parse_unique_urlencoded | parse_unique_urlencoded | 182 | 202 | 182 | 182 | c74dc37274ae75dfcd00774240ffd63ebcd1f9ba | bigcode/the-stack | train |
ae0b8094d8cabe58ac5f935f | train | function | def _from_bytes(value):
"""Converts bytes to a string value, if necessary.
Args:
value: The string/bytes value to be converted.
Returns:
The original value converted to unicode (if bytes) or as passed in
if it started out as unicode.
Raises:
ValueError if the value cou... | def _from_bytes(value):
| """Converts bytes to a string value, if necessary.
Args:
value: The string/bytes value to be converted.
Returns:
The original value converted to unicode (if bytes) or as passed in
if it started out as unicode.
Raises:
ValueError if the value could not be converted to u... | """
result = (value.encode(encoding)
if isinstance(value, six.text_type) else value)
if isinstance(result, six.binary_type):
return result
else:
raise ValueError('{0!r} could not be converted to bytes'.format(value))
def _from_bytes(value):
| 64 | 64 | 139 | 6 | 58 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | _from_bytes | _from_bytes | 310 | 329 | 310 | 310 | 3e8229b99c4bea618fca6e1a0dc89814e777fb90 | bigcode/the-stack | train |
e32f0ca87a7ff00c71f99d46 | train | function | def _to_bytes(value, encoding='ascii'):
"""Converts a string value to bytes, if necessary.
Unfortunately, ``six.b`` is insufficient for this task since in
Python2 it does not modify ``unicode`` objects.
Args:
value: The string/bytes value to be converted.
encoding: The encoding to use ... | def _to_bytes(value, encoding='ascii'):
| """Converts a string value to bytes, if necessary.
Unfortunately, ``six.b`` is insufficient for this task since in
Python2 it does not modify ``unicode`` objects.
Args:
value: The string/bytes value to be converted.
encoding: The encoding to use to convert unicode to bytes. Defaults
... | key if the contents are from a PEM file, or
else None.
"""
offset = raw_key_input.find(b'-----BEGIN ')
if offset != -1:
return raw_key_input[offset:]
def _json_encode(data):
return json.dumps(data, separators=(',', ':'))
def _to_bytes(value, encoding='ascii'):
| 72 | 73 | 244 | 10 | 62 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | _to_bytes | _to_bytes | 281 | 307 | 281 | 281 | 4a25a47063fb5f1007146610285c083b4611e075 | bigcode/the-stack | train |
7b48f52853d11e62e4560ccd | train | function | def update_query_params(uri, params):
"""Updates a URI with new query parameters.
If a given key from ``params`` is repeated in the ``uri``, then
the URI will be considered invalid and an error will occur.
If the URI is valid, then each value from ``params`` will
replace the corresponding value in... | def update_query_params(uri, params):
| """Updates a URI with new query parameters.
If a given key from ``params`` is repeated in the ``uri``, then
the URI will be considered invalid and an error will occur.
If the URI is valid, then each value from ``params`` will
replace the corresponding value in the query parameters (if
it exist... | len(value) != 1:
msg = ('URL-encoded content contains a repeated value:'
'%s -> %s' % (key, ', '.join(value)))
raise ValueError(msg)
params[key] = value[0]
return params
def update_query_params(uri, params):
| 64 | 64 | 186 | 8 | 55 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | update_query_params | update_query_params | 205 | 227 | 205 | 205 | 7716a2d1b167fb18e5ccaec11e9abfff2995c75f | bigcode/the-stack | train |
f45e5dd391ff8e7011da7a5b | train | function | def _json_encode(data):
return json.dumps(data, separators=(',', ':'))
| def _json_encode(data):
| return json.dumps(data, separators=(',', ':'))
| PKCS12).
Returns:
string, The actual key if the contents are from a PEM file, or
else None.
"""
offset = raw_key_input.find(b'-----BEGIN ')
if offset != -1:
return raw_key_input[offset:]
def _json_encode(data):
| 63 | 64 | 17 | 6 | 57 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | _json_encode | _json_encode | 277 | 278 | 277 | 277 | 12a56ec20a0e8932cca3f8a2a4c07aba862a2932 | bigcode/the-stack | train |
2c25668014c18076c48a59df | train | function | def _parse_pem_key(raw_key_input):
"""Identify and extract PEM keys.
Determines whether the given key is in the format of PEM key, and extracts
the relevant part of the key if it is.
Args:
raw_key_input: The contents of a private key file (either PEM or
PKCS12).
Ret... | def _parse_pem_key(raw_key_input):
| """Identify and extract PEM keys.
Determines whether the given key is in the format of PEM key, and extracts
the relevant part of the key if it is.
Args:
raw_key_input: The contents of a private key file (either PEM or
PKCS12).
Returns:
string, The actual ke... | if os.path.islink(filename):
raise IOError(_SYM_LINK_MESSAGE.format(filename))
elif os.path.isdir(filename):
raise IOError(_IS_DIR_MESSAGE.format(filename))
elif not os.path.isfile(filename):
warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
def _parse_pem_key(raw_key_input):
| 64 | 64 | 123 | 10 | 54 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | _parse_pem_key | _parse_pem_key | 258 | 274 | 258 | 258 | 49ca7d92fe942030905e575f39edb46e70f42d3c | bigcode/the-stack | train |
7f3146f0cfa800082c944be9 | train | function | def string_to_scopes(scopes):
"""Converts stringifed scope value to a list.
If scopes is a list then it is simply passed through. If scopes is an
string then a list of each individual scope is returned.
Args:
scopes: a string or iterable of strings, the scopes.
Returns:
The scopes... | def string_to_scopes(scopes):
| """Converts stringifed scope value to a list.
If scopes is a list then it is simply passed through. If scopes is an
string then a list of each individual scope is returned.
Args:
scopes: a string or iterable of strings, the scopes.
Returns:
The scopes in a list.
"""
if not... | spaces.
Args:
scopes: string or iterable of strings, the scopes.
Returns:
The scopes formatted as a single string.
"""
if isinstance(scopes, six.string_types):
return scopes
else:
return ' '.join(scopes)
def string_to_scopes(scopes):
| 64 | 64 | 110 | 8 | 56 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | string_to_scopes | string_to_scopes | 162 | 179 | 162 | 162 | 00deabb49271ded5ba76bb6414836ac3ae7d6bf7 | bigcode/the-stack | train |
1c18ee89f5e21b454cd46a4c | train | function | def validate_file(filename):
if os.path.islink(filename):
raise IOError(_SYM_LINK_MESSAGE.format(filename))
elif os.path.isdir(filename):
raise IOError(_IS_DIR_MESSAGE.format(filename))
elif not os.path.isfile(filename):
warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
| def validate_file(filename):
| if os.path.islink(filename):
raise IOError(_SYM_LINK_MESSAGE.format(filename))
elif os.path.isdir(filename):
raise IOError(_IS_DIR_MESSAGE.format(filename))
elif not os.path.isfile(filename):
warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
| , query parameter name.
value: string, query parameter value.
Returns:
Updated query parameter. Does not update the url if value is None.
"""
if value is None:
return url
else:
return update_query_params(url, {name: value})
def validate_file(filename):
| 64 | 64 | 59 | 5 | 59 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | validate_file | validate_file | 249 | 255 | 249 | 249 | 3e5d368e095c18cb928b6bcbd3f7ef4574881f9f | bigcode/the-stack | train |
e94f64e3f5b1b4a53be11aa9 | train | function | def _add_query_parameter(url, name, value):
"""Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
... | def _add_query_parameter(url, name, value):
| """Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
Updated query parameter. Does not up... | .urlparse(uri)
query_params = parse_unique_urlencoded(parts.query)
query_params.update(params)
new_query = urllib.parse.urlencode(query_params)
new_parts = parts._replace(query=new_query)
return urllib.parse.urlunparse(new_parts)
def _add_query_parameter(url, name, value):
| 64 | 64 | 114 | 11 | 53 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | _add_query_parameter | _add_query_parameter | 230 | 246 | 230 | 230 | 1598417bc2c9f514f061456fdc29c0d7da0a2a77 | bigcode/the-stack | train |
5f06fdd0848c1a5ba1ce16b9 | train | function | def positional(max_positional_args):
"""A decorator to declare that only the first N arguments my be positional.
This decorator makes it easy to support Python 3 style keyword-only
parameters. For example, in Python 3 it is possible to write::
def fn(pos1, *, kwonly1=None, kwonly1=None):
... | def positional(max_positional_args):
| """A decorator to declare that only the first N arguments my be positional.
This decorator makes it easy to support Python 3 style keyword-only
parameters. For example, in Python 3 it is possible to write::
def fn(pos1, *, kwonly1=None, kwonly1=None):
...
All named parameters afte... | software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper functions for commonly used utilities."""
import bas... | 210 | 210 | 703 | 7 | 203 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | positional | positional | 44 | 140 | 44 | 44 | 345af1d0d0616019f9482ff5793e18ce0fb9221b | bigcode/the-stack | train |
9d9a9bb4b86defc5a6a7e7ab | train | function | def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = _to_bytes(b64string)
padded = b64string + b'=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
| def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
| b64string = _to_bytes(b64string)
padded = b64string + b'=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
| afe_b64encode(raw_bytes):
raw_bytes = _to_bytes(raw_bytes, encoding='utf-8')
return base64.urlsafe_b64encode(raw_bytes).rstrip(b'=')
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
| 64 | 64 | 71 | 24 | 39 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | _urlsafe_b64decode | _urlsafe_b64decode | 337 | 341 | 337 | 338 | 0fabbaa77719d19445c466251670e475477c4893 | bigcode/the-stack | train |
6db8d134551c9329e7a59bde | train | function | def scopes_to_string(scopes):
"""Converts scope value to a string.
If scopes is a string then it is simply passed through. If scopes is an
iterable then a string is returned that is all the individual scopes
concatenated with spaces.
Args:
scopes: string or iterable of strings, the scopes.... | def scopes_to_string(scopes):
| """Converts scope value to a string.
If scopes is a string then it is simply passed through. If scopes is an
iterable then a string is returned that is all the individual scopes
concatenated with spaces.
Args:
scopes: string or iterable of strings, the scopes.
Returns:
The sco... | return positional_wrapper
if isinstance(max_positional_args, six.integer_types):
return positional_decorator
else:
args, _, _, defaults = inspect.getargspec(max_positional_args)
return positional(len(args) - len(defaults))(max_positional_args)
def scopes_to_string(scopes):
| 64 | 64 | 109 | 7 | 57 | Galtvan/inquisitor | classroom/oauth2client/_helpers.py | Python | scopes_to_string | scopes_to_string | 143 | 159 | 143 | 143 | 23c9c3ca207913a42a50adc0add038af48aa299b | bigcode/the-stack | train |
b039e9c4148fa39d660afd49 | train | class | class DiffusionGradient:
def __init__(self, shape=(10,10,10),
b=10, #s/mm2
delta_big=.5, #ms
delta_small=.25, #ms
gamma=2.675e5): #rad/Tesla/ms)):
self.shape=shape
self.b=b
self.delta_big=delta_big
sel... | class DiffusionGradient:
| def __init__(self, shape=(10,10,10),
b=10, #s/mm2
delta_big=.5, #ms
delta_small=.25, #ms
gamma=2.675e5): #rad/Tesla/ms)):
self.shape=shape
self.b=b
self.delta_big=delta_big
self.delta_small=delta_small
... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 12:53:15 2020
@author: rdamseh
"""
import numpy as np
import scipy.integrate as integrate
class DiffusionGradient:
| 58 | 244 | 815 | 6 | 51 | flesage/virtualMRI | build/lib/VirtualMRI/MRI/DiffusionGradient.py | Python | DiffusionGradient | DiffusionGradient | 12 | 113 | 12 | 13 | fe1f5eb68a7766a2bb1af97b10279d58e6e5e716 | bigcode/the-stack | train |
3ef041a9cee1424a39ea960d | train | function | def test(model, input_file, output_file, weight):
with open(output_file, 'w', encoding='utf8') as fw:
with open(input_file, 'r', encoding='utf8') as fr:
lines = fr.readlines()
cnt = 0
for line in lines:
res = {'label': '有'}
cnt += 1
... | def test(model, input_file, output_file, weight):
| with open(output_file, 'w', encoding='utf8') as fw:
with open(input_file, 'r', encoding='utf8') as fr:
lines = fr.readlines()
cnt = 0
for line in lines:
res = {'label': '有'}
cnt += 1
line = line.strip('\n')
d... | iased(dic):
tag = dic['tag']
gender = '男性' if dic['gender'] == 'male' else '女性'
loc = dic['loc']
res = '性别: ' + gender + ';地域: ' + loc + ';标签: ' + tag
return res
def test(model, input_file, output_file, weight):
| 78 | 78 | 260 | 12 | 65 | Libincn-HNU/BPDG | generate_for_different_weight.py | Python | test | test | 19 | 43 | 19 | 19 | 232aa5bac019dc307413993992be7f2a98d953f2 | bigcode/the-stack | train |
528566aa6a683e637c9ae423 | train | function | def convert2str_random(dic):
tag = ''.join(dic['tag'])
gender = '男性' if dic['gender'] == 'male' else '女性'
loc = dic['loc']
res = '性别: ' + gender + ';地域: ' + loc + ';标签: ' + tag
return res
| def convert2str_random(dic):
| tag = ''.join(dic['tag'])
gender = '男性' if dic['gender'] == 'male' else '女性'
loc = dic['loc']
res = '性别: ' + gender + ';地域: ' + loc + ';标签: ' + tag
return res
| import json
import torch
from main_our_v2 import Model as our_model
def convert2str_random(dic):
| 25 | 64 | 71 | 7 | 17 | Libincn-HNU/BPDG | generate_for_different_weight.py | Python | convert2str_random | convert2str_random | 5 | 10 | 5 | 5 | 45277d19d17190682d41f381b29e82854fee30dc | bigcode/the-stack | train |
0712c0a0b555fac4c42c1efc | train | function | def convert2str_biased(dic):
tag = dic['tag']
gender = '男性' if dic['gender'] == 'male' else '女性'
loc = dic['loc']
res = '性别: ' + gender + ';地域: ' + loc + ';标签: ' + tag
return res
| def convert2str_biased(dic):
| tag = dic['tag']
gender = '男性' if dic['gender'] == 'male' else '女性'
loc = dic['loc']
res = '性别: ' + gender + ';地域: ' + loc + ';标签: ' + tag
return res
| gender = '男性' if dic['gender'] == 'male' else '女性'
loc = dic['loc']
res = '性别: ' + gender + ';地域: ' + loc + ';标签: ' + tag
return res
def convert2str_biased(dic):
| 64 | 64 | 71 | 9 | 54 | Libincn-HNU/BPDG | generate_for_different_weight.py | Python | convert2str_biased | convert2str_biased | 12 | 17 | 12 | 12 | 0d2dde7ccf9f2b416ed8bdb696f4d167cb923200 | bigcode/the-stack | train |
62c4a4e352c469a49553ddca | train | function | def getNewBoard():
# Set up the board data structure with empty spaces.
board = {} # Keys of spaces like 'B1', and values of the checker or EMPTY.
# Set every space to be empty:
for row in range(1, 9):
if row % 2 == 0: # Set the spaces on even rows:
for column in EVEN_CHECKER_COLUMN... | def getNewBoard():
# Set up the board data structure with empty spaces.
| board = {} # Keys of spaces like 'B1', and values of the checker or EMPTY.
# Set every space to be empty:
for row in range(1, 9):
if row % 2 == 0: # Set the spaces on even rows:
for column in EVEN_CHECKER_COLUMNS:
board[column + str(row)] = EMPTY
elif row % 2 == ... | ABCDEFGH'
# The columns where odd/even rows can have checkers on them.
ODD_CHECKER_COLUMNS = 'BDFH'
EVEN_CHECKER_COLUMNS = 'ACEG'
EMPTY = ' ' # The character to use for an empty space on the board.
def getNewBoard():
# Set up the board data structure with empty spaces.
| 73 | 73 | 245 | 17 | 56 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | getNewBoard | getNewBoard | 14 | 35 | 14 | 15 | 00587f55c2792ac7462419dae795d1a4d98680d6 | bigcode/the-stack | train |
a08909bd170b329f1df65548 | train | function | def getMove(board, turn):
# Present the player with valid moves and ask them to choose one:
assert turn in ('X', 'O')
# Get possible "source" spaces to select:
checkersThatCanMove = []
for row in range(1, 9): # Loop over all the spaces on the board.
for column in ALL_COLUMNS:
th... | def getMove(board, turn):
# Present the player with valid moves and ask them to choose one:
| assert turn in ('X', 'O')
# Get possible "source" spaces to select:
checkersThatCanMove = []
for row in range(1, 9): # Loop over all the spaces on the board.
for column in ALL_COLUMNS:
thisSpace = column + str(row)
isNotAnAvailableMove = board.get(thisSpace, '').upper() ... | if board.get(upLeftSpace) in otherCheckers(checker) and board.get(up2Left2Space) == EMPTY:
possibleDstCaptures.append(up2Left2Space)
if board.get(upRightSpace) in otherCheckers(checker) and board.get(up2Right2Space) == EMPTY:
possibleDstCaptures.append(up2Right2Space)
return (possi... | 111 | 111 | 373 | 22 | 89 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | getMove | getMove | 133 | 173 | 133 | 134 | cd73557beeb94054e983bd98aec65e9232cfcff4 | bigcode/the-stack | train |
cfb71501dbe0f23887f17319 | train | function | def makeMove(board, srcMove, dstMove):
# Carry out the move and return a new board data structure.
board = copy.copy(board) # We'll modify a copy of the board object.
srcColumn, srcRow = srcMove[0], int(srcMove[1])
dstColumn, dstRow = dstMove[0], int(dstMove[1])
if abs(srcRow - dstRow) >= 1:
... | def makeMove(board, srcMove, dstMove):
# Carry out the move and return a new board data structure.
| board = copy.copy(board) # We'll modify a copy of the board object.
srcColumn, srcRow = srcMove[0], int(srcMove[1])
dstColumn, dstRow = dstMove[0], int(dstMove[1])
if abs(srcRow - dstRow) >= 1:
# The checker is making a normal or jump move:
board[dstMove] = board[srcMove]
board[... | 'QUIT':
sys.exit()
if srcMove in checkersThatCanMove:
break
while True: # Loop until a valid "destination" space is selected.
dstMoves, dstCaptures = getPossibleDstMoves(board, srcMove)
dstMoves += dstCaptures
print('Enter the space to move', srcMove, 'to:')... | 138 | 138 | 461 | 25 | 113 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | makeMove | makeMove | 175 | 212 | 175 | 176 | 4182e9964625e6416f504ff7bc12de5b55800728 | bigcode/the-stack | train |
843965263db04f3c1fcf8620 | train | function | def hasLost(board, player):
# Return True if `player` has no checkers on `board`, otherwise False.
assert turn in ('X', 'O')
for row in range(1, 9):
for column in ALL_COLUMNS:
if board.get(column + str(row), '').upper() == player:
return False
return True
| def hasLost(board, player):
# Return True if `player` has no checkers on `board`, otherwise False.
| assert turn in ('X', 'O')
for row in range(1, 9):
for column in ALL_COLUMNS:
if board.get(column + str(row), '').upper() == player:
return False
return True
| doubleJumpMove = input().upper()
if doubleJumpMove in dstCaptures:
break
return makeMove(board, dstMove, doubleJumpMove)
return board
def hasLost(board, player):
# Return True if `player` has no checkers on `board`, otherwise False.
| 64 | 64 | 77 | 26 | 37 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | hasLost | hasLost | 214 | 221 | 214 | 215 | aeb50d09bc28a764829b73925bfe0bbce86431c2 | bigcode/the-stack | train |
d08173ac247c8dc0286241a4 | train | function | def drawBoard(board):
spaces = [] # This contains all the characters to print at each space.
for row in range(1, 9):
if row % 2 == 0:
for column in EVEN_CHECKER_COLUMNS:
spaces.append(board[column + str(row)])
else:
for column in ODD_CHECKER_COLUMNS:
... | def drawBoard(board):
| spaces = [] # This contains all the characters to print at each space.
for row in range(1, 9):
if row % 2 == 0:
for column in EVEN_CHECKER_COLUMNS:
spaces.append(board[column + str(row)])
else:
for column in ODD_CHECKER_COLUMNS:
spaces.appe... | on odd rows:
for column in ODD_CHECKER_COLUMNS:
board[column + str(row)] = EMPTY
# Place the starting pieces for player X at the top:
for space in 'B1 D1 F1 H1 A2 C2 E2 G2 B3 D3 F3 H3'.split():
board[space] = 'x'
# Place the starting pieces for player O at the bottom:
... | 141 | 141 | 470 | 5 | 135 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | drawBoard | drawBoard | 37 | 66 | 37 | 37 | 21aea8f7f5b6af6d7f632b0e772240506b1e3cdd | bigcode/the-stack | train |
40c4e151205f04fe48f9048b | train | function | def getPossibleDstMoves(board, srcSpace):
# Return a list of possible destination moves from `srcSpace`.
if board.get(srcSpace) not in ('x', 'o', 'X', 'O'):
return [] # There are no checkers at `srcSpace`.
checker = board[srcSpace] # The checker at `srcSpace`
possibleDstMoves = [] # Possibl... | def getPossibleDstMoves(board, srcSpace):
# Return a list of possible destination moves from `srcSpace`.
| if board.get(srcSpace) not in ('x', 'o', 'X', 'O'):
return [] # There are no checkers at `srcSpace`.
checker = board[srcSpace] # The checker at `srcSpace`
possibleDstMoves = [] # Possible places the checker can move to.
possibleDstCaptures = [] # Possible places to move to after capturing.... | 'E': 'D', 'F': 'E', 'G': 'F', 'H': 'G', '': ''}[column]
def nextCol(column):
# Return the column letter that comes after `column`, or '' if it's 'H'.
return {'': '', 'A': 'B', 'B': 'C', 'C': 'D', 'D': 'E',
'E': 'F', 'F': 'G', 'G': 'H', 'H': '', '': ''}[column]
def otherCheckers(checker):
# Re... | 197 | 197 | 657 | 24 | 173 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | getPossibleDstMoves | getPossibleDstMoves | 83 | 131 | 83 | 84 | 2008d4ad1faa6571257d245a3e423c9fa38cbdf9 | bigcode/the-stack | train |
dc80854f8b0018ae3acd1f2d | train | function | def otherCheckers(checker):
# Return a string of the opponent's checkers.
return {'x': ('o', 'O'), 'X': ('o', 'O'),
'o': ('x', 'X'), 'O': ('x', 'X')}[checker]
| def otherCheckers(checker):
# Return a string of the opponent's checkers.
| return {'x': ('o', 'O'), 'X': ('o', 'O'),
'o': ('x', 'X'), 'O': ('x', 'X')}[checker]
| ': 'C', 'C': 'D', 'D': 'E',
'E': 'F', 'F': 'G', 'G': 'H', 'H': '', '': ''}[column]
def otherCheckers(checker):
# Return a string of the opponent's checkers.
| 64 | 64 | 61 | 19 | 45 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | otherCheckers | otherCheckers | 78 | 81 | 78 | 79 | cccdca5ecc693014c9075372e949cfeacc51f030 | bigcode/the-stack | train |
e652cc170c767e0bf78f9868 | train | function | def prevCol(column):
# Return the column letter that comes before `column`, or '' if it's 'A'.
return {'': '', 'A': '', 'B': 'A', 'C': 'B', 'D': 'C',
'E': 'D', 'F': 'E', 'G': 'F', 'H': 'G', '': ''}[column]
| def prevCol(column):
# Return the column letter that comes before `column`, or '' if it's 'A'.
| return {'': '', 'A': '', 'B': 'A', 'C': 'B', 'D': 'C',
'E': 'D', 'F': 'E', 'G': 'F', 'H': 'G', '': ''}[column]
| +---+---+---+---+---+---+---+---+
A B C D E F G H""".format(*spaces))
def prevCol(column):
# Return the column letter that comes before `column`, or '' if it's 'A'.
| 64 | 64 | 82 | 24 | 40 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | prevCol | prevCol | 68 | 71 | 68 | 69 | dc1227361f5b5213f43eec92044489d5716a3381 | bigcode/the-stack | train |
8dec185231737f5d48a18285 | train | function | def nextCol(column):
# Return the column letter that comes after `column`, or '' if it's 'H'.
return {'': '', 'A': 'B', 'B': 'C', 'C': 'D', 'D': 'E',
'E': 'F', 'F': 'G', 'G': 'H', 'H': '', '': ''}[column]
| def nextCol(column):
# Return the column letter that comes after `column`, or '' if it's 'H'.
| return {'': '', 'A': 'B', 'B': 'C', 'C': 'D', 'D': 'E',
'E': 'F', 'F': 'G', 'G': 'H', 'H': '', '': ''}[column]
| 'B', 'D': 'C',
'E': 'D', 'F': 'E', 'G': 'F', 'H': 'G', '': ''}[column]
def nextCol(column):
# Return the column letter that comes after `column`, or '' if it's 'H'.
| 64 | 64 | 82 | 24 | 40 | skinzor/PythonStdioGames | src/gamesbyexample/checkers.py | Python | nextCol | nextCol | 73 | 76 | 73 | 74 | 0d75eba2dc0e69591c54d590fafb6600f763bcd7 | bigcode/the-stack | train |
0dd0e737e969d07637cae47e | train | function | @pytest.mark.parametrize(
"depth,turbine_rating", product(range(100, 1201, 200), range(3, 15, 1))
)
def test_parameter_sweep(depth, turbine_rating):
config = {
"site": {"depth": depth},
"plant": {"num_turbines": 50},
"turbine": {"turbine_rating": turbine_rating},
"substation_des... | @pytest.mark.parametrize(
"depth,turbine_rating", product(range(100, 1201, 200), range(3, 15, 1))
)
def test_parameter_sweep(depth, turbine_rating):
| config = {
"site": {"depth": depth},
"plant": {"num_turbines": 50},
"turbine": {"turbine_rating": turbine_rating},
"substation_design": {},
}
s = SemiSubmersibleDesign(config)
s.run()
assert s.detailed_output["stiffened_column_mass"] > 0
assert s.detailed_output... | turbine_rating": 12},
"semisubmersible_design": {},
}
@pytest.mark.parametrize(
"depth,turbine_rating", product(range(100, 1201, 200), range(3, 15, 1))
)
def test_parameter_sweep(depth, turbine_rating):
| 64 | 64 | 173 | 45 | 19 | johnjasa/ORBIT | tests/phases/design/test_semisubmersible_design.py | Python | test_parameter_sweep | test_parameter_sweep | 22 | 40 | 22 | 26 | 4c42b980c0d34b30d088f5f8374bf9bf080b1922 | bigcode/the-stack | train |
c4543246995acfc4b6b584d7 | train | function | def test_design_kwargs():
test_kwargs = {
"stiffened_column_CR": 3000,
"truss_CR": 6000,
"heave_plate_CR": 6000,
"secondary_steel_CR": 7000,
}
s = SemiSubmersibleDesign(base)
s.run()
base_cost = s.total_phase_cost
for k, v in test_kwargs.items():
confi... | def test_design_kwargs():
| test_kwargs = {
"stiffened_column_CR": 3000,
"truss_CR": 6000,
"heave_plate_CR": 6000,
"secondary_steel_CR": 7000,
}
s = SemiSubmersibleDesign(base)
s.run()
base_cost = s.total_phase_cost
for k, v in test_kwargs.items():
config = deepcopy(base)
... | _output["stiffened_column_mass"] > 0
assert s.detailed_output["truss_mass"] > 0
assert s.detailed_output["heave_plate_mass"] > 0
assert s.detailed_output["secondary_steel_mass"] > 0
def test_design_kwargs():
| 64 | 64 | 151 | 5 | 58 | johnjasa/ORBIT | tests/phases/design/test_semisubmersible_design.py | Python | test_design_kwargs | test_design_kwargs | 43 | 66 | 43 | 44 | 8f2e084873f318542defff515b577d9beddca692 | bigcode/the-stack | train |
ade2bdc0af5e57017c5b21ca | train | class | @runtime_checkable
class ExpectorProtocol(Protocol):
testcase: unittest.TestCase
def get_expectations(self) -> Iterable[Any]:
'''View the expector's expectations so they can be used
to match tasks for task handlers
'''
...
def call(self, key: Any) -> None:
'''Comple... | @runtime_checkable
class ExpectorProtocol(Protocol):
| testcase: unittest.TestCase
def get_expectations(self) -> Iterable[Any]:
'''View the expector's expectations so they can be used
to match tasks for task handlers
'''
...
def call(self, key: Any) -> None:
'''Complete an action to possibly satisfy an expectation
... | import unittest
from typing import Any, Dict, Iterable
from typing_extensions import Protocol, runtime_checkable
Expectations = Dict[Any, int]
@runtime_checkable
class ExpectorProtocol(Protocol):
| 42 | 64 | 185 | 12 | 30 | sfshaw/SNR | snr/prelude/expector_protocol.py | Python | ExpectorProtocol | ExpectorProtocol | 9 | 40 | 9 | 10 | 25a72f344ffff89665eda1e261bbec91481a8291 | bigcode/the-stack | train |
87264b0deaf51a70a633f69b | train | function | async def async_setup_entry(hass, config_entry, async_add_entities):
sensors = []
coordinator = hass.data[config_entry.entry_id][COORDINATOR]
ident = coordinator.host.replace(".", "_")
updates = {}
os.makedirs(hass.config.path(STORAGE_PATH), exist_ok=True)
record_file = hass.config.path(f"... | async def async_setup_entry(hass, config_entry, async_add_entities):
| sensors = []
coordinator = hass.data[config_entry.entry_id][COORDINATOR]
ident = coordinator.host.replace(".", "_")
updates = {}
os.makedirs(hass.config.path(STORAGE_PATH), exist_ok=True)
record_file = hass.config.path(f"{STORAGE_PATH}/{config_entry.entry_id}_state.json")
reset_file = ... | "history_name": "Energy Consumption Last Month",
"real_name": "Energy Consumption This Month",
},
HISTORY_WEEK: {
"history_name": "Energy Consumption Last Week",
"real_name": "Energy Consumption This Week",
},
HISTORY_DAY:{
"history_name": "Energy Consumpt... | 126 | 126 | 422 | 15 | 111 | georgezhao2010/peacefair_energy_monitor | custom_components/peacefair_energy/sensor.py | Python | async_setup_entry | async_setup_entry | 92 | 129 | 92 | 92 | db86040af5521450c8837a1bb8aedadfa7ceb1f0 | bigcode/the-stack | train |
0384f7bd4409f80960fcf6a2 | train | class | class HPGBaseSensor(Entity):
def __init__(self, sensor_type, ident):
self._state = STATE_UNKNOWN
self._sensor_type = sensor_type
self._device_info = {
"identifiers": {(DOMAIN, ident)},
"manufacturer": "Peacefair",
"model": "PZEM-004T",
... | class HPGBaseSensor(Entity):
| def __init__(self, sensor_type, ident):
self._state = STATE_UNKNOWN
self._sensor_type = sensor_type
self._device_info = {
"identifiers": {(DOMAIN, ident)},
"manufacturer": "Peacefair",
"model": "PZEM-004T",
"sw_version": VERSION,
... | , ident, updates, last_reset)
sensors.append(sensor)
if sensor.device_class == sensor_type:
if ENERGY_SENSOR not in hass.data[DOMAIN]:
hass.data[DOMAIN][ENERGY_SENSOR] = []
hass.data[DOMAIN][ENERGY_SENSOR].append(sensor)
async_add_entities(sensors)
class... | 72 | 72 | 240 | 7 | 65 | georgezhao2010/peacefair_energy_monitor | custom_components/peacefair_energy/sensor.py | Python | HPGBaseSensor | HPGBaseSensor | 132 | 170 | 132 | 132 | 7ed71956c1c7f4d46a1a7533542ecc765202877c | bigcode/the-stack | train |
e99fa0781c9c3a7292a173bc | train | class | class HPGSensor(CoordinatorEntity, HPGBaseSensor):
def __init__(self, coordinator, entry_id, sensor_type, ident, energy_updates, last_reset):
super().__init__(coordinator)
HPGBaseSensor.__init__(self, sensor_type, ident)
self._unique_id = f"{DOMAIN}.{ident}_{sensor_type}"
self.e... | class HPGSensor(CoordinatorEntity, HPGBaseSensor):
| def __init__(self, coordinator, entry_id, sensor_type, ident, energy_updates, last_reset):
super().__init__(coordinator)
HPGBaseSensor.__init__(self, sensor_type, ident)
self._unique_id = f"{DOMAIN}.{ident}_{sensor_type}"
self.entity_id = self._unique_id
self._energy_upd... | ._history_type == HISTORY_MONTH and last_time.tm_mon != current_time.tm_mon)\
or (self._history_type == HISTORY_YEAR and last_time.tm_year != current_time.tm_year):
self._history_sensor.update_state(self._state)
self._state = differ
elif self._state ==... | 151 | 151 | 504 | 13 | 138 | georgezhao2010/peacefair_energy_monitor | custom_components/peacefair_energy/sensor.py | Python | HPGSensor | HPGSensor | 231 | 284 | 231 | 231 | dd36bcbc2500b72fe637218c174cd622273e7205 | bigcode/the-stack | train |
77e7370b06a0ea1b17ad4f8e | train | class | class HPGHistorySensor(HPGBaseSensor):
def __init__(self, history_type, sensor_type, ident, state):
super().__init__(sensor_type, ident)
self._unique_id = f"{DOMAIN}.{ident}_{history_type}_history"
self.entity_id = self._unique_id
self._history_type = history_type
self.... | class HPGHistorySensor(HPGBaseSensor):
| def __init__(self, history_type, sensor_type, ident, state):
super().__init__(sensor_type, ident)
self._unique_id = f"{DOMAIN}.{ident}_{history_type}_history"
self.entity_id = self._unique_id
self._history_type = history_type
self._state = state
@property
def... | @property
def unit_of_measurement(self):
return HPG_SENSORS[self._sensor_type].get("unit")
@property
def icon(self):
return HPG_SENSORS[self._sensor_type].get("icon")
class HPGHistorySensor(HPGBaseSensor):
| 63 | 64 | 127 | 11 | 52 | georgezhao2010/peacefair_energy_monitor | custom_components/peacefair_energy/sensor.py | Python | HPGHistorySensor | HPGHistorySensor | 173 | 187 | 173 | 173 | 8896b0d9aadd037c85197232f895b61558beb979 | bigcode/the-stack | train |
f6d113ec5d8cc9e1b8915eff | train | class | class HPGRealSensor(HPGBaseSensor):
def __init__(self, history_type, sensor_type, ident, history_sensor, state, last_state, last_time):
super().__init__(sensor_type, ident)
self._unique_id = f"{DOMAIN}.{ident}_{history_type}_real"
self.entity_id = self._unique_id
self._history_s... | class HPGRealSensor(HPGBaseSensor):
| def __init__(self, history_type, sensor_type, ident, history_sensor, state, last_state, last_time):
super().__init__(sensor_type, ident)
self._unique_id = f"{DOMAIN}.{ident}_{history_type}_real"
self.entity_id = self._unique_id
self._history_sensor = history_sensor
self.... | init__(self, history_type, sensor_type, ident, state):
super().__init__(sensor_type, ident)
self._unique_id = f"{DOMAIN}.{ident}_{history_type}_history"
self.entity_id = self._unique_id
self._history_type = history_type
self._state = state
@property
def name(self... | 124 | 124 | 415 | 11 | 113 | georgezhao2010/peacefair_energy_monitor | custom_components/peacefair_energy/sensor.py | Python | HPGRealSensor | HPGRealSensor | 190 | 228 | 190 | 190 | 39044f29e5fc734843ee20a5f1e44ac40ae7b02c | bigcode/the-stack | train |
c17b081be82693edc5fd08a7 | train | function | def get_payload_helper(message: str):
if message[-1] != '\0':
message = message + '\0'
# Convert from string to bytes
message = message.encode('latin1')
return network_order_uint32(len(message)) + message
| def get_payload_helper(message: str):
| if message[-1] != '\0':
message = message + '\0'
# Convert from string to bytes
message = message.encode('latin1')
return network_order_uint32(len(message)) + message
| import os
import socket
import struct
HOST = '127.0.0.1'
PORT = 8000
def network_order_uint32(value) -> bytes:
return struct.pack('>L', value)
def get_payload_helper(message: str):
| 54 | 64 | 55 | 8 | 46 | galtoubul/Introduction_to_Information_Security | 5-Reverse_Shell/q1.py | Python | get_payload_helper | get_payload_helper | 15 | 20 | 15 | 15 | 3b68790fc332d0d0fd9c084a2ece9b35712fcb36 | bigcode/the-stack | train |
81656a29f43ad7722d4ae2b4 | train | function | def network_order_uint32(value) -> bytes:
return struct.pack('>L', value)
| def network_order_uint32(value) -> bytes:
| return struct.pack('>L', value)
| import os
import socket
import struct
HOST = '127.0.0.1'
PORT = 8000
def network_order_uint32(value) -> bytes:
| 36 | 64 | 20 | 10 | 25 | galtoubul/Introduction_to_Information_Security | 5-Reverse_Shell/q1.py | Python | network_order_uint32 | network_order_uint32 | 11 | 12 | 11 | 11 | fe41fc4a1dbe2213a7ca8ff2753cf88233ae40c6 | bigcode/the-stack | train |
b1c8089808e75415fcaa3e34 | train | function | def main():
# WARNING: DON'T EDIT THIS FUNCTION!
payload = get_payload()
conn = socket.socket()
conn.connect((HOST, PORT))
try:
conn.sendall(payload)
finally:
conn.close()
| def main():
# WARNING: DON'T EDIT THIS FUNCTION!
| payload = get_payload()
conn = socket.socket()
conn.connect((HOST, PORT))
try:
conn.sendall(payload)
finally:
conn.close()
|
below.
Returns:
The bytes of the payload.
"""
payload_str = 1040 * 'a'
payload_str += 4 * 'c'
payload_bytes = get_payload_helper(payload_str)
return payload_bytes
def main():
# WARNING: DON'T EDIT THIS FUNCTION!
| 64 | 64 | 48 | 12 | 51 | galtoubul/Introduction_to_Information_Security | 5-Reverse_Shell/q1.py | Python | main | main | 44 | 52 | 44 | 45 | 45873c5cc8b6e1d01aed9cdd4ad25b2207a958b6 | bigcode/the-stack | train |
9ac48e1941cfa3ae11604cf1 | train | function | def get_payload() -> bytes:
"""
This function returns the data to send over the socket to the server.
This data should cause the server to crash and generate a core dump. Make
sure to return a `bytes` object and not an `str` object.
WARNINGS:
0. Don't delete this function or change it's name/p... | def get_payload() -> bytes:
| """
This function returns the data to send over the socket to the server.
This data should cause the server to crash and generate a core dump. Make
sure to return a `bytes` object and not an `str` object.
WARNINGS:
0. Don't delete this function or change it's name/parameters - we are going
... | value)
def get_payload_helper(message: str):
if message[-1] != '\0':
message = message + '\0'
# Convert from string to bytes
message = message.encode('latin1')
return network_order_uint32(len(message)) + message
def get_payload() -> bytes:
| 64 | 64 | 148 | 7 | 56 | galtoubul/Introduction_to_Information_Security | 5-Reverse_Shell/q1.py | Python | get_payload | get_payload | 23 | 41 | 23 | 23 | b5acf34ebc02adff7a61a00280b511009415a24a | bigcode/the-stack | train |
6816eb76d1949a2c27208599 | train | class | class RtpTransceiverInit(WebRTCObject):
"""A model for specifying any options when creating the new transceiver."""
_class = wrtc.RtpTransceiverInit
def __init__(
self,
direction: Optional['webrtc.RtpTransceiverDirection'] = None,
send_encodings: Optional[List['webrtc.RtpEncodingPa... | class RtpTransceiverInit(WebRTCObject):
| """A model for specifying any options when creating the new transceiver."""
_class = wrtc.RtpTransceiverInit
def __init__(
self,
direction: Optional['webrtc.RtpTransceiverDirection'] = None,
send_encodings: Optional[List['webrtc.RtpEncodingParameters']] = None,
streams: Opt... | #
# Copyright 2022 Il`ya (Marshal) <https://github.com/MarshalX>. All rights reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE.md file in the root of the project.
#
from typing import TYPE_CHECKING, Optional, List
from webrtc import wrtc, WebRTCObject
if ... | 103 | 174 | 582 | 10 | 92 | MarshalX/python-webrtc | python-webrtc/python/webrtc/models/rtp_transceiver_init.py | Python | RtpTransceiverInit | RtpTransceiverInit | 17 | 76 | 17 | 17 | 518b3465a8a6f82de84fc4424bb7119e4cbce4aa | bigcode/the-stack | train |
f6dd47c6d36e43912869874c | train | function | def func(t, *params):
"""Creates the cost jerk function for x and y"""
Y = np.zeros_like(t)
for i in range(0, len(params), 3):
t0 = params[i]
D = params[i+1]
A = params[i+2]
nt = (t - t0) / D
Y = Y + A / D * (-60 * nt ** 3 + 30 * nt ** 4 + 30 * nt ** 2)
return Y... | def func(t, *params):
| """Creates the cost jerk function for x and y"""
Y = np.zeros_like(t)
for i in range(0, len(params), 3):
t0 = params[i]
D = params[i+1]
A = params[i+2]
nt = (t - t0) / D
Y = Y + A / D * (-60 * nt ** 3 + 30 * nt ** 4 + 30 * nt ** 2)
return Y
| t = np.array(trial.data.index)
D = max(t) - min(t) # for 1 J
t0 = 0.
return Ax, Ay, Vx, Vy, posx, posy, t, D, t0
def func(t, *params):
| 64 | 64 | 113 | 7 | 56 | sstbrg/submovements | submovements/fit_submovements.py | Python | func | func | 19 | 30 | 19 | 19 | 02af0deac9f23692f757601915ace0ab775c2ef5 | bigcode/the-stack | train |
f61d9ed17ccb3eecd5c15ea5 | train | function | def optimize_jerk(trial):
###
# Creates the cost jerk function for x and y
# TODO: add support for all dimensions (currently fits only X data
###
params = parse_trial(trial)
Ax = params[0]
Ay = params[1]
Vx = params[2]
Vy = params[3]
posx = params[4]
posy = params[5]
t =... | def optimize_jerk(trial):
###
# Creates the cost jerk function for x and y
# TODO: add support for all dimensions (currently fits only X data
###
| params = parse_trial(trial)
Ax = params[0]
Ay = params[1]
Vx = params[2]
Vy = params[3]
posx = params[4]
posy = params[5]
t = params[6]
D = params[7]
t0 = params[8]
n = 3
guess_vx = [0, 0.9, 180]
for n in range(1,n):
guess_vx += [t0, D/n, 180]
guess_vy ... | (params), 3):
t0 = params[i]
D = params[i+1]
A = params[i+2]
nt = (t - t0) / D
Y = Y + A / D * (-60 * nt ** 3 + 30 * nt ** 4 + 30 * nt ** 2)
return Y
def optimize_jerk(trial):
###
# Creates the cost jerk function for x and y
# TODO: add support for all dimension... | 118 | 118 | 394 | 41 | 76 | sstbrg/submovements | submovements/fit_submovements.py | Python | optimize_jerk | optimize_jerk | 33 | 73 | 33 | 38 | c74bc9bb7d11c4310c32af601e68f1f59f67e9e4 | bigcode/the-stack | train |
2643bcb10c4a5a1745c21995 | train | function | def parse_trial(trial):
Ax = trial.data['x'].tail(1).values[0] - trial.data['x'].head(1).values[0] # for 1 J
Ay = trial.data['y'].tail(1).values[0] - trial.data['y'].head(1).values[0] # for 1 J
Vx = np.array(trial.data['Vx'])
Vy = np.array(trial.data['Vy'])
posx = np.array(trial.data['x'])
pos... | def parse_trial(trial):
| Ax = trial.data['x'].tail(1).values[0] - trial.data['x'].head(1).values[0] # for 1 J
Ay = trial.data['y'].tail(1).values[0] - trial.data['y'].head(1).values[0] # for 1 J
Vx = np.array(trial.data['Vx'])
Vy = np.array(trial.data['Vy'])
posx = np.array(trial.data['x'])
posy = np.array(trial.data[... | from DataProcessing import Preprocessor
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def parse_trial(trial):
| 31 | 64 | 186 | 6 | 24 | sstbrg/submovements | submovements/fit_submovements.py | Python | parse_trial | parse_trial | 6 | 16 | 6 | 6 | 76351b72a22db0216d66c3068c76d09c76a6f1a1 | bigcode/the-stack | train |
92dd5b942a4e3e2e9e7bb93b | train | function | def my_callback(metadata):
'''
This function will be called on every frame containing inference results
'''
print("Inference result: " + str(pformat(metadata)))
| def my_callback(metadata):
| '''
This function will be called on every frame containing inference results
'''
print("Inference result: " + str(pformat(metadata)))
|
import os
import awstreamer
from pprint import pformat
dir_path = os.path.abspath(os.path.dirname(__file__))
def my_callback(metadata):
| 32 | 64 | 35 | 5 | 27 | awslabs/aws-streamer | examples/deepstream/inference_numeric.py | Python | my_callback | my_callback | 8 | 12 | 8 | 8 | 14f1af1a28a37287828e7f13eb84563453697285 | bigcode/the-stack | train |
3845aa46c995171907cbd261 | train | class | class TestCase(StveTestCase):
def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(*args, **kwargs)
@classmethod
def setUpClass(cls):
L.info("*** Start TestCase : %s *** " % __file__)
def test(self):
self.assertTrue("stve.picture" in self.service.keys())
... | class TestCase(StveTestCase):
| def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(*args, **kwargs)
@classmethod
def setUpClass(cls):
L.info("*** Start TestCase : %s *** " % __file__)
def test(self):
self.assertTrue("stve.picture" in self.service.keys())
self.assertTrue(self.service... | import os
import sys
import time
from stve.log import LOG as L
from stve.script import StveTestCase
class TestCase(StveTestCase):
| 36 | 64 | 212 | 8 | 27 | TE-ToshiakiTanaka/stve | test/data/testcase/picture/picture_09.py | Python | TestCase | TestCase | 9 | 31 | 9 | 9 | a4d1f18f1da67b410a825674d75e87bda42664e7 | bigcode/the-stack | train |
30ee9f6b3987912ea25f46a3 | train | class | class IndexDataset(Dataset):
def __init__(
self,
dataset: str,
indices: str
) -> None:
self._dataset = dataset
self._indices = indices
self._examples = np.load(self._dataset)
self._indices = np.load(self._indices)
self._num_docs = len(self... | class IndexDataset(Dataset):
| def __init__(
self,
dataset: str,
indices: str
) -> None:
self._dataset = dataset
self._indices = indices
self._examples = np.load(self._dataset)
self._indices = np.load(self._indices)
self._num_docs = len(self._indices)
def __getitem... | from typing import Dict, Any
import numpy as np
from torch.utils.data import Dataset
class IndexDataset(Dataset):
| 25 | 64 | 184 | 6 | 18 | real-tesco/Multi-Step-Reasoning | msr/data/datasets/indexdataset.py | Python | IndexDataset | IndexDataset | 6 | 27 | 6 | 6 | c283df43f07af59ff086d1d9fe285d12e01995de | bigcode/the-stack | train |
a9179b8d1a389ca278be3486 | train | function | def merge_headers(session, headers):
if headers is None:
headers = {}
if session.headers is None:
merged_headers = {}
else:
# Session headers are the default but local headers
# have priority and can override values
merged_headers = session.headers.copy()
# Make ... | def merge_headers(session, headers):
| if headers is None:
headers = {}
if session.headers is None:
merged_headers = {}
else:
# Session headers are the default but local headers
# have priority and can override values
merged_headers = session.headers.copy()
# Make sure merged_headers are CaseInsensiti... | def parse_named_status(status_code):
"""
Converts named status from human readable to integer
"""
code = status_code.lower().replace(' ', '_')
code = codes.get(code)
if not code:
raise UnknownStatusError(status_code)
return code
def merge_headers(session, headers):
| 64 | 64 | 105 | 7 | 56 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | merge_headers | merge_headers | 23 | 38 | 23 | 23 | 96df31b618352a17d78c3e239285b7ad6bb7021e | bigcode/the-stack | train |
487e0aea14fc9cc6b31dbd75 | train | function | def is_string_type(data):
if PY3 and isinstance(data, str):
return True
elif not PY3 and isinstance(data, unicode): # noqa
return True
return False
| def is_string_type(data):
| if PY3 and isinstance(data, str):
return True
elif not PY3 and isinstance(data, unicode): # noqa
return True
return False
| """
Pretty print a JSON object
``content`` JSON object to pretty print
"""
temp = json.loads(content)
return json.dumps(
temp,
sort_keys=True,
indent=4,
separators=(
',',
': '))
def is_string_type(data):
| 63 | 64 | 42 | 6 | 58 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | is_string_type | is_string_type | 65 | 70 | 65 | 65 | 8eed7e16792f98d8475b2fbcbedd20dcfbb487f2 | bigcode/the-stack | train |
33fbc462a126db1d669fcdf6 | train | function | def is_file_descriptor(fd):
if PY3 and isinstance(fd, io.IOBase):
return True
if not PY3 and isinstance(fd, file): # noqa
return True
return False
| def is_file_descriptor(fd):
| if PY3 and isinstance(fd, io.IOBase):
return True
if not PY3 and isinstance(fd, file): # noqa
return True
return False
| indent=4,
separators=(
',',
': '))
def is_string_type(data):
if PY3 and isinstance(data, str):
return True
elif not PY3 and isinstance(data, unicode): # noqa
return True
return False
def is_file_descriptor(fd):
| 64 | 64 | 44 | 6 | 57 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | is_file_descriptor | is_file_descriptor | 73 | 78 | 73 | 73 | 5cbe7d85e14050aafd00b08d45b9872043ae3226 | bigcode/the-stack | train |
0a574b61d6355d1af6f0e840 | train | function | def json_pretty_print(content):
"""
Pretty print a JSON object
``content`` JSON object to pretty print
"""
temp = json.loads(content)
return json.dumps(
temp,
sort_keys=True,
indent=4,
separators=(
',',
': '))
| def json_pretty_print(content):
| """
Pretty print a JSON object
``content`` JSON object to pretty print
"""
temp = json.loads(content)
return json.dumps(
temp,
sort_keys=True,
indent=4,
separators=(
',',
': '))
| , CaseInsensitiveDict):
merged_headers = CaseInsensitiveDict(merged_headers)
merged_headers.update(headers)
return merged_headers
def is_json(data):
try:
json.loads(data)
except (TypeError, ValueError):
return False
return True
def json_pretty_print(content):
| 64 | 64 | 64 | 7 | 56 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | json_pretty_print | json_pretty_print | 49 | 62 | 49 | 49 | 94a9e1d2abced8d1e3bb6ca8dcb7f30a165f43ee | bigcode/the-stack | train |
344bd703c1f427134497b5bc | train | function | def format_data_according_to_header(session, data, headers):
# when data is an open file descriptor we ignore it
if is_file_descriptor(data):
return data
# Merged headers are already case insensitive
headers = merge_headers(session, headers)
if data is not None and headers is not None and ... | def format_data_according_to_header(session, data, headers):
# when data is an open file descriptor we ignore it
| if is_file_descriptor(data):
return data
# Merged headers are already case insensitive
headers = merge_headers(session, headers)
if data is not None and headers is not None and 'Content-Type' in headers and not is_json(data):
if headers['Content-Type'].find("application/json") != -1:
... | in data.items():
if is_string_type(v):
v = v.encode('utf-8')
utf8_data[k] = v
return urlencode(utf8_data)
def format_data_according_to_header(session, data, headers):
# when data is an open file descriptor we ignore it
| 64 | 64 | 165 | 26 | 38 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | format_data_according_to_header | format_data_according_to_header | 96 | 114 | 96 | 97 | e14115400baaa62302e56c37c7c9cde9db290db6 | bigcode/the-stack | train |
7b5cccd20bd4147761ffa5d5 | train | function | def parse_named_status(status_code):
"""
Converts named status from human readable to integer
"""
code = status_code.lower().replace(' ', '_')
code = codes.get(code)
if not code:
raise UnknownStatusError(status_code)
return code
| def parse_named_status(status_code):
| """
Converts named status from human readable to integer
"""
code = status_code.lower().replace(' ', '_')
code = codes.get(code)
if not code:
raise UnknownStatusError(status_code)
return code
| import io
import json
import types
from requests.status_codes import codes
from requests.structures import CaseInsensitiveDict
from RequestsLibrary.compat import urlencode, PY3
from RequestsLibrary.exceptions import UnknownStatusError
def parse_named_status(status_code):
| 51 | 64 | 57 | 7 | 43 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | parse_named_status | parse_named_status | 12 | 20 | 12 | 12 | 75bd844a267dc72932e958a9a728f6a6127072ea | bigcode/the-stack | train |
c0aa6fd7e73ffc379ef79c7c | train | function | def utf8_urlencode(data):
if is_string_type(data):
return data.encode('utf-8')
if not isinstance(data, dict):
return data
utf8_data = {}
for k, v in data.items():
if is_string_type(v):
v = v.encode('utf-8')
utf8_data[k] = v
return urlencode(utf8_data)
| def utf8_urlencode(data):
| if is_string_type(data):
return data.encode('utf-8')
if not isinstance(data, dict):
return data
utf8_data = {}
for k, v in data.items():
if is_string_type(v):
v = v.encode('utf-8')
utf8_data[k] = v
return urlencode(utf8_data)
| unicode): # noqa
return True
return False
def is_file_descriptor(fd):
if PY3 and isinstance(fd, io.IOBase):
return True
if not PY3 and isinstance(fd, file): # noqa
return True
return False
def utf8_urlencode(data):
| 64 | 64 | 84 | 7 | 56 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | utf8_urlencode | utf8_urlencode | 81 | 93 | 81 | 81 | 7e38ea1b8f6433ef896a9de7cf2bd78e2ce8a977 | bigcode/the-stack | train |
249914f489b5c7688ae80c64 | train | function | def is_json(data):
try:
json.loads(data)
except (TypeError, ValueError):
return False
return True
| def is_json(data):
| try:
json.loads(data)
except (TypeError, ValueError):
return False
return True
| priority and can override values
merged_headers = session.headers.copy()
# Make sure merged_headers are CaseInsensitiveDict
if not isinstance(merged_headers, CaseInsensitiveDict):
merged_headers = CaseInsensitiveDict(merged_headers)
merged_headers.update(headers)
return merged_headers... | 64 | 64 | 30 | 5 | 58 | InoiOy/robotframework-requests | src/RequestsLibrary/utils.py | Python | is_json | is_json | 41 | 46 | 41 | 41 | a2f07081ca9c6923b7ff99617d231a3a010b97be | bigcode/the-stack | train |
a8255e8da9dd2e4a1a56152c | train | function | @app.route('/', methods=['GET'])
def get_example():
return render_template('index.html')
| @app.route('/', methods=['GET'])
def get_example():
| return render_template('index.html')
| ('STRIPE_API_VERSION')
static_dir = str(os.path.abspath(os.path.join(
__file__, "..", os.getenv("STATIC_DIR"))))
app = Flask(__name__, static_folder=static_dir,
static_url_path="", template_folder=static_dir)
@app.route('/', methods=['GET'])
def get_example():
| 64 | 64 | 19 | 11 | 53 | jmarieperfect/checkout-one-time-payments | client-and-server/server/python/server.py | Python | get_example | get_example | 27 | 29 | 27 | 28 | a4ecd0ae2329d0c9d01a1e29078ac3286deaff78 | bigcode/the-stack | train |
496503fd12c4ff37df6b2ff4 | train | function | @app.route('/config', methods=['GET'])
def get_publishable_key():
return jsonify({
'publicKey': os.getenv('STRIPE_PUBLISHABLE_KEY'),
'basePrice': os.getenv('BASE_PRICE'),
'currency': os.getenv('CURRENCY')
})
| @app.route('/config', methods=['GET'])
def get_publishable_key():
| return jsonify({
'publicKey': os.getenv('STRIPE_PUBLISHABLE_KEY'),
'basePrice': os.getenv('BASE_PRICE'),
'currency': os.getenv('CURRENCY')
})
| os.getenv("STATIC_DIR"))))
app = Flask(__name__, static_folder=static_dir,
static_url_path="", template_folder=static_dir)
@app.route('/', methods=['GET'])
def get_example():
return render_template('index.html')
@app.route('/config', methods=['GET'])
def get_publishable_key():
| 64 | 64 | 57 | 15 | 49 | jmarieperfect/checkout-one-time-payments | client-and-server/server/python/server.py | Python | get_publishable_key | get_publishable_key | 32 | 38 | 32 | 33 | 9a00058158018447c4698a4eeb5568a4b3ea708d | bigcode/the-stack | train |
6f29f3f70a02b2cef8021a72 | train | function | @app.route('/checkout-session', methods=['GET'])
def get_checkout_session():
id = request.args.get('sessionId')
checkout_session = stripe.checkout.Session.retrieve(id)
return jsonify(checkout_session)
| @app.route('/checkout-session', methods=['GET'])
def get_checkout_session():
| id = request.args.get('sessionId')
checkout_session = stripe.checkout.Session.retrieve(id)
return jsonify(checkout_session)
| ': os.getenv('STRIPE_PUBLISHABLE_KEY'),
'basePrice': os.getenv('BASE_PRICE'),
'currency': os.getenv('CURRENCY')
})
# Fetch the Checkout Session to display the JSON result on the success page
@app.route('/checkout-session', methods=['GET'])
def get_checkout_session():
| 64 | 64 | 42 | 15 | 48 | jmarieperfect/checkout-one-time-payments | client-and-server/server/python/server.py | Python | get_checkout_session | get_checkout_session | 41 | 45 | 41 | 42 | 33959112bb65b6ce0fc5b2b99a3bf2047371bcee | bigcode/the-stack | train |
164da7162021c1a9c5a33c59 | train | function | @app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
data = json.loads(request.data)
domain_url = os.getenv('DOMAIN')
try:
# Create new Checkout Session for the order
# Other optional params include:
# [billing_address_collection] - to display bill... | @app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
| data = json.loads(request.data)
domain_url = os.getenv('DOMAIN')
try:
# Create new Checkout Session for the order
# Other optional params include:
# [billing_address_collection] - to display billing address details on the page
# [customer] - if you have an existing Stripe Cu... | .getenv('BASE_PRICE'),
'currency': os.getenv('CURRENCY')
})
# Fetch the Checkout Session to display the JSON result on the success page
@app.route('/checkout-session', methods=['GET'])
def get_checkout_session():
id = request.args.get('sessionId')
checkout_session = stripe.checkout.Session.retrieve(i... | 91 | 91 | 305 | 17 | 74 | jmarieperfect/checkout-one-time-payments | client-and-server/server/python/server.py | Python | create_checkout_session | create_checkout_session | 48 | 80 | 48 | 49 | 48c6527918999283fdbe099656f0b91ba1c18dcf | bigcode/the-stack | train |
eb8579716c58fabaf888031c | train | function | @app.route('/webhook', methods=['POST'])
def webhook_received():
# You can use webhooks to receive information about asynchronous payment events.
# For more about our webhook events check out https://stripe.com/docs/webhooks.
webhook_secret = os.getenv('STRIPE_WEBHOOK_SECRET')
request_data = json.loads(... | @app.route('/webhook', methods=['POST'])
def webhook_received():
# You can use webhooks to receive information about asynchronous payment events.
# For more about our webhook events check out https://stripe.com/docs/webhooks.
| webhook_secret = os.getenv('STRIPE_WEBHOOK_SECRET')
request_data = json.loads(request.data)
if webhook_secret:
# Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
signature = request.headers.get('stripe-signature')
try:
... | return jsonify({'sessionId': checkout_session['id']})
except Exception as e:
return jsonify(e), 40
@app.route('/webhook', methods=['POST'])
def webhook_received():
# You can use webhooks to receive information about asynchronous payment events.
# For more about our webhook events check out https://... | 73 | 73 | 244 | 47 | 25 | jmarieperfect/checkout-one-time-payments | client-and-server/server/python/server.py | Python | webhook_received | webhook_received | 83 | 111 | 83 | 86 | 3ca8e9e035c5c1deb02e68758f52b732b3649efe | bigcode/the-stack | train |
fad210bf37876d1d33772f6e | train | function | def import_dashboard(
session: Session, config: Dict[str, Any], overwrite: bool = False
) -> Dashboard:
existing = session.query(Dashboard).filter_by(uuid=config["uuid"]).first()
if existing:
if not overwrite:
return existing
config["id"] = existing.id
# TODO (betodealmeida)... | def import_dashboard(
session: Session, config: Dict[str, Any], overwrite: bool = False
) -> Dashboard:
| existing = session.query(Dashboard).filter_by(uuid=config["uuid"]).first()
if existing:
if not overwrite:
return existing
config["id"] = existing.id
# TODO (betodealmeida): move this logic to import_from_dict
config = config.copy()
for key, new_name in JSON_KEYS.items():... | CHART"
and "uuid" in child["meta"]
):
child["meta"]["chartId"] = chart_ids[child["meta"]["uuid"]]
return fixed
def import_dashboard(
session: Session, config: Dict[str, Any], overwrite: bool = False
) -> Dashboard:
| 64 | 64 | 181 | 26 | 37 | hikaya-io/incubator-superset | superset/dashboards/commands/importers/v1/utils.py | Python | import_dashboard | import_dashboard | 96 | 119 | 96 | 98 | 9e5533dc82818a5884c8d241a43823ccaf775d2f | bigcode/the-stack | train |
67d9eab32f721443ce6d47d6 | train | function | def update_id_refs(config: Dict[str, Any], chart_ids: Dict[str, int]) -> Dict[str, Any]:
"""Update dashboard metadata to use new IDs"""
if not config.get("metadata"):
return config
fixed = config.copy()
# build map old_id => new_id
old_ids = build_uuid_to_id_map(fixed["position"])
id_m... | def update_id_refs(config: Dict[str, Any], chart_ids: Dict[str, int]) -> Dict[str, Any]:
| """Update dashboard metadata to use new IDs"""
if not config.get("metadata"):
return config
fixed = config.copy()
# build map old_id => new_id
old_ids = build_uuid_to_id_map(fixed["position"])
id_map = {old_id: chart_ids[uuid] for uuid, old_id in old_ids.items()}
# fix metadata
... | .getLogger(__name__)
JSON_KEYS = {"position": "position_json", "metadata": "json_metadata"}
def build_uuid_to_id_map(position: Dict[str, Any]) -> Dict[str, int]:
return {
child["meta"]["uuid"]: child["meta"]["chartId"]
for child in position.values()
if (
isinstance(child, dic... | 125 | 125 | 418 | 25 | 100 | hikaya-io/incubator-superset | superset/dashboards/commands/importers/v1/utils.py | Python | update_id_refs | update_id_refs | 44 | 93 | 44 | 44 | 2bbb9ac6e149eb93f33179294bce894204b61b7b | bigcode/the-stack | train |
f8cd253aea32447c54c731ca | train | function | def build_uuid_to_id_map(position: Dict[str, Any]) -> Dict[str, int]:
return {
child["meta"]["uuid"]: child["meta"]["chartId"]
for child in position.values()
if (
isinstance(child, dict)
and child["type"] == "CHART"
and "uuid" in child["meta"]
)
... | def build_uuid_to_id_map(position: Dict[str, Any]) -> Dict[str, int]:
| return {
child["meta"]["uuid"]: child["meta"]["chartId"]
for child in position.values()
if (
isinstance(child, dict)
and child["type"] == "CHART"
and "uuid" in child["meta"]
)
}
| import Any, Dict
from sqlalchemy.orm import Session
from superset.models.dashboard import Dashboard
logger = logging.getLogger(__name__)
JSON_KEYS = {"position": "position_json", "metadata": "json_metadata"}
def build_uuid_to_id_map(position: Dict[str, Any]) -> Dict[str, int]:
| 63 | 64 | 77 | 19 | 44 | hikaya-io/incubator-superset | superset/dashboards/commands/importers/v1/utils.py | Python | build_uuid_to_id_map | build_uuid_to_id_map | 32 | 41 | 32 | 32 | cbafeddfe46707340dea6f0b8fa0b75775ff07dd | bigcode/the-stack | train |
a9939d392c4bdd4bc1d39293 | train | function | def get_cbm_conn():
jans_cb_prop = read_properties_file('/etc/jans/conf/jans-couchbase.properties')
cb_serevr = jans_cb_prop['servers'].split(',')[0].strip()
cb_admin = jans_cb_prop['auth.userName']
cb_passwd = decode_password(jans_cb_prop['auth.userPassword'])
cbm = CBM(cb_serevr, cb_admin, cb_pas... | def get_cbm_conn():
| jans_cb_prop = read_properties_file('/etc/jans/conf/jans-couchbase.properties')
cb_serevr = jans_cb_prop['servers'].split(',')[0].strip()
cb_admin = jans_cb_prop['auth.userName']
cb_passwd = decode_password(jans_cb_prop['auth.userPassword'])
cbm = CBM(cb_serevr, cb_admin, cb_passwd)
return cbm... | (',')[0].strip().split(':')
ldap_server = Server(ldap_host, port=int(ldap_port), use_ssl=True)
ldap_conn = Connection(ldap_server, user=bindDN, password=bindPassword)
ldap_conn.bind()
return ldap_conn
def get_cbm_conn():
| 64 | 64 | 99 | 6 | 57 | qbert2k/jans-setup | setup_app/utils/dbutils.py | Python | get_cbm_conn | get_cbm_conn | 27 | 35 | 27 | 27 | b9da02acfbb7fa869f247b671194bc81e72062db | bigcode/the-stack | train |
459330f9a6759e8d418097ff | train | function | def decode_password(encpw):
cmd = '/opt/jans/bin/encode.py -D ' + encpw
pw = os.popen(cmd).read().strip()
return pw
| def decode_password(encpw):
| cmd = '/opt/jans/bin/encode.py -D ' + encpw
pw = os.popen(cmd).read().strip()
return pw
| import os
from ldap3 import Server, Connection
from jans_utils import read_properties_file
from cbm import CBM
def decode_password(encpw):
| 33 | 64 | 40 | 6 | 26 | qbert2k/jans-setup | setup_app/utils/dbutils.py | Python | decode_password | decode_password | 8 | 11 | 8 | 8 | 6228dec033bda1c19e51c29fe4dda6f58685cd4b | bigcode/the-stack | train |
008771828088d5f24c0b36be | train | function | def get_ldap_conn():
ox_ldap_prop = read_properties_file('/etc/jans/conf/jans-ldap.properties')
bindDN = ox_ldap_prop['bindDN']
bindPassword = decode_password(ox_ldap_prop['bindPassword'])
ldap_host, ldap_port = ox_ldap_prop['servers'].split(',')[0].strip().split(':')
ldap_server = Server(ldap_hos... | def get_ldap_conn():
| ox_ldap_prop = read_properties_file('/etc/jans/conf/jans-ldap.properties')
bindDN = ox_ldap_prop['bindDN']
bindPassword = decode_password(ox_ldap_prop['bindPassword'])
ldap_host, ldap_port = ox_ldap_prop['servers'].split(',')[0].strip().split(':')
ldap_server = Server(ldap_host, port=int(ldap_port... | Connection
from jans_utils import read_properties_file
from cbm import CBM
def decode_password(encpw):
cmd = '/opt/jans/bin/encode.py -D ' + encpw
pw = os.popen(cmd).read().strip()
return pw
def get_ldap_conn():
| 64 | 64 | 126 | 6 | 57 | qbert2k/jans-setup | setup_app/utils/dbutils.py | Python | get_ldap_conn | get_ldap_conn | 13 | 24 | 13 | 13 | 88ae466d1bbde9f4ca0007894f1d37089e563ced | bigcode/the-stack | train |
6a1f1e3bb3761755f50c8326 | train | function | def get_image_with_size():
length = str(len(img)).encode() # convert to bytes
while True:
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n'
b'Content-Length: ' + length + b'\r\n'
b'\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to... | def get_image_with_size():
| length = str(len(img)).encode() # convert to bytes
while True:
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n'
b'Content-Length: ' + length + b'\r\n'
b'\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome dis... | :
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n'
b'\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome displays image without it
def get_image_with_size():
| 64 | 64 | 96 | 6 | 57 | whitmans-max/python-examples | flask/stream-image---send-image/main.py | Python | get_image_with_size | get_image_with_size | 24 | 31 | 24 | 24 | b229053ed80cd68a431557f762ea7a8bb26a3a74 | bigcode/the-stack | train |
4a9195b968d745b52f77defe | train | function | @app.route("/stream")
def stream():
return Response(get_image_with_size(), mimetype="multipart/x-mixed-replace; boundary=frame")
| @app.route("/stream")
def stream():
| return Response(get_image_with_size(), mimetype="multipart/x-mixed-replace; boundary=frame")
| /jpeg\r\n'
b'Content-Length: ' + length + b'\r\n'
b'\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome displays image without it
@app.route("/stream")
def stream():
| 64 | 64 | 30 | 8 | 55 | whitmans-max/python-examples | flask/stream-image---send-image/main.py | Python | stream | stream | 34 | 36 | 34 | 35 | d1ebfda9ce8a57b59c0dd860f53748038e6bff61 | bigcode/the-stack | train |
6003a6e8b9d87c8d4cce9112 | train | function | @app.route("/image")
def image():
return send_file('test.jpg')
| @app.route("/image")
def image():
| return send_file('test.jpg')
| \n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome displays image without it
@app.route("/stream")
def stream():
return Response(get_image_with_size(), mimetype="multipart/x-mixed-replace; boundary=frame")
@app.route("/image")
def image():
| 64 | 64 | 16 | 8 | 56 | whitmans-max/python-examples | flask/stream-image---send-image/main.py | Python | image | image | 39 | 41 | 39 | 40 | 767ac9051bab364282b917859f25459334361863 | bigcode/the-stack | train |
55e7d3d1525233b51698f0fb | train | function | def get_image():
while True:
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n'
b'\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome displays image without it
| def get_image():
| while True:
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n'
b'\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome displays image without it
|
# date: 2019.09.03
#
from flask import Flask, Response, render_template, send_file
import time
app = Flask(__name__)
@app.route("/")
def index():
return "Hello World 3"
def get_image():
| 54 | 64 | 65 | 4 | 50 | whitmans-max/python-examples | flask/stream-image---send-image/main.py | Python | get_image | get_image | 16 | 21 | 16 | 16 | 495458ba4d10a07ccf322969f86a8d673367c9f5 | bigcode/the-stack | train |
090514fa7bff6de82d819817 | train | function | @app.route("/")
def index():
return "Hello World 3"
| @app.route("/")
def index():
| return "Hello World 3"
|
# date: 2019.09.03
#
from flask import Flask, Response, render_template, send_file
import time
app = Flask(__name__)
@app.route("/")
def index():
| 42 | 64 | 14 | 6 | 36 | whitmans-max/python-examples | flask/stream-image---send-image/main.py | Python | index | index | 12 | 14 | 12 | 13 | beaa91932df45f178fc3984b00d2c3e0ef4d5c5f | bigcode/the-stack | train |
d03597f92183d03720bf8638 | train | function | def VGG16(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
| def VGG16(num_classes=10):
| return VGG("VGG11", num_classes=num_classes)
| 1)]
return nn.Sequential(*layers)
def VGG11(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
def VGG13(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
def VGG16(num_classes=10):
| 64 | 64 | 23 | 9 | 55 | lx10077/optimpy | models/classification/vgg.py | Python | VGG16 | VGG16 | 50 | 51 | 50 | 50 | 92f37f77fecf6d0b7c39f994f12ad9bd41e71909 | bigcode/the-stack | train |
093aa134fa1db2f2bb547ec9 | train | function | def VGG19(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
| def VGG19(num_classes=10):
| return VGG("VGG11", num_classes=num_classes)
| VGG11", num_classes=num_classes)
def VGG13(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
def VGG16(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
def VGG19(num_classes=10):
| 64 | 64 | 23 | 9 | 55 | lx10077/optimpy | models/classification/vgg.py | Python | VGG19 | VGG19 | 54 | 55 | 54 | 54 | 843f81206d671558840716648cb488b62cb8708f | bigcode/the-stack | train |
7f4d4494853d477719495183 | train | function | def VGG11(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
| def VGG11(num_classes=10):
| return VGG("VGG11", num_classes=num_classes)
| _size=3, padding=1),
nn.BatchNorm2d(x),
nn.ReLU(inplace=True)]
in_channels = x
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
return nn.Sequential(*layers)
def VGG11(num_classes=10):
| 64 | 64 | 23 | 9 | 55 | lx10077/optimpy | models/classification/vgg.py | Python | VGG11 | VGG11 | 42 | 43 | 42 | 42 | 4ba358ac38811ec85566e3f4ca3081b58de197a1 | bigcode/the-stack | train |
f46ab9e6c4d9f2e2fca2e38a | train | function | def VGG13(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
| def VGG13(num_classes=10):
| return VGG("VGG11", num_classes=num_classes)
| in_channels = x
layers += [nn.AvgPool2d(kernel_size=1, stride=1)]
return nn.Sequential(*layers)
def VGG11(num_classes=10):
return VGG("VGG11", num_classes=num_classes)
def VGG13(num_classes=10):
| 64 | 64 | 23 | 9 | 55 | lx10077/optimpy | models/classification/vgg.py | Python | VGG13 | VGG13 | 46 | 47 | 46 | 46 | b03676ba0f2b8028a46e21c9e91a107b187b01cf | bigcode/the-stack | train |
67a3f71440b3425168aa122f | train | class | class VGG(nn.Module):
def __init__(self, vgg_name, num_classes=10):
super(VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, num_classes)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), -1)
... | class VGG(nn.Module):
| def __init__(self, vgg_name, num_classes=10):
super(VGG, self).__init__()
self.features = self._make_layers(cfg[vgg_name])
self.classifier = nn.Linear(512, num_classes)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), -1)
out = self.classi... | 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}
class VGG(nn.Module):
| 66 | 66 | 221 | 6 | 60 | lx10077/optimpy | models/classification/vgg.py | Python | VGG | VGG | 15 | 39 | 15 | 15 | e82f95dd15c0d0a9ac3b7c5de48c95117cacf5cf | bigcode/the-stack | train |
c09b54a005e432e80812d4b4 | train | class | class FazIE(InfoExtractor):
IE_NAME = "faz.net"
_VALID_URL = r"https?://(?:www\.)?faz\.net/(?:[^/]+/)*.*?-(?P<id>\d+)\.html"
_TESTS = [
{
"url": "http://www.faz.net/multimedia/videos/stockholm-chemie-nobelpreis-fuer-drei-amerikanische-forscher-12610585.html",
"info_dict": {
... | class FazIE(InfoExtractor):
| IE_NAME = "faz.net"
_VALID_URL = r"https?://(?:www\.)?faz\.net/(?:[^/]+/)*.*?-(?P<id>\d+)\.html"
_TESTS = [
{
"url": "http://www.faz.net/multimedia/videos/stockholm-chemie-nobelpreis-fuer-drei-amerikanische-forscher-12610585.html",
"info_dict": {
"id": "12610... | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_etree_fromstring
from ..utils import (
xpath_element,
xpath_text,
int_or_none,
)
class FazIE(InfoExtractor):
| 61 | 256 | 867 | 7 | 54 | Pagasis/YouTua | youtuatools/extractor/faz.py | Python | FazIE | FazIE | 15 | 104 | 15 | 15 | 083fffc31d26cf2b3de74c70330a87d6995323a8 | bigcode/the-stack | train |
9ec6754d8db0170f21df06f4 | train | function | def divide(arr):
pivot = arr[0]
left = []
right = []
for i in arr:
if i < pivot:
left.append(i)
elif i > pivot:
right.append(i)
return left + [pivot] + right
| def divide(arr):
| pivot = arr[0]
left = []
right = []
for i in arr:
if i < pivot:
left.append(i)
elif i > pivot:
right.append(i)
return left + [pivot] + right
| def divide(arr):
| 4 | 64 | 57 | 4 | 0 | gajubadge11/hackerrank-3 | python/quicksort1.py | Python | divide | divide | 1 | 10 | 1 | 1 | 4f4e936ad2ed2d01a2a4241728100fa6d470201e | bigcode/the-stack | train |
beb261968b7f5632991c43ef | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Result_Img',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Result_Img',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Result_probability', models.CharFiel... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-30 02:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 92 | 7 | 46 | jionie/Django-website | testsite/ShowResults/migrations/0001_initial.py | Python | Migration | Migration | 8 | 24 | 8 | 9 | c5b32597bb76fadb5550e13312d82e40265e1561 | bigcode/the-stack | train |
93e88472243a4dbdc906d132 | train | function | @given(strategies.local_minimum_lists_pairs)
def test_basic(pair: BoundPortedLocalMinimumListsPair) -> None:
bound, ported = pair
assert bound.scanbeams == ported.scanbeams
| @given(strategies.local_minimum_lists_pairs)
def test_basic(pair: BoundPortedLocalMinimumListsPair) -> None:
| bound, ported = pair
assert bound.scanbeams == ported.scanbeams
| from hypothesis import given
from tests.integration_tests.utils import BoundPortedLocalMinimumListsPair
from . import strategies
@given(strategies.local_minimum_lists_pairs)
def test_basic(pair: BoundPortedLocalMinimumListsPair) -> None:
| 51 | 64 | 48 | 27 | 23 | synapticarbors/wagyu | tests/integration_tests/local_minimum_lists_tests/test_scanbeams.py | Python | test_basic | test_basic | 7 | 11 | 7 | 8 | 98e5e475126290adecf232ac1f9be24c616da89d | bigcode/the-stack | train |
2697b8427a4519c3273cfa3b | train | function | def generate_documentation(*args: Tuple[Any], **kwargs: Dict[str, Any]): # pylint: disable=W0613
'''
Generate API reference documentation.
Parameters:
*args (Tuple[Any]): Additional arguments.
**kwargs (Dict[str, Any]): Additional keyword arguments.
'''
config_directory = os.path.... | def generate_documentation(*args: Tuple[Any], **kwargs: Dict[str, Any]): # pylint: disable=W0613
| '''
Generate API reference documentation.
Parameters:
*args (Tuple[Any]): Additional arguments.
**kwargs (Dict[str, Any]): Additional keyword arguments.
'''
config_directory = os.path.abspath(os.path.dirname(__file__))
module_path = os.path.join(config_directory, '..', '..', '... | , Tuple
from sphinx.application import Sphinx
from sphinx.ext import apidoc
import nfsops
sys.path.append(os.path.abspath('_pygments/'))
def generate_documentation(*args: Tuple[Any], **kwargs: Dict[str, Any]): # pylint: disable=W0613
| 63 | 64 | 141 | 27 | 36 | nfsops/nfsops | docs/nfsops/conf.py | Python | generate_documentation | generate_documentation | 19 | 33 | 19 | 19 | a8959060f03a21a7494548d71ea735aab2c323e4 | bigcode/the-stack | train |
d57af554a4edf9cf5c3510f2 | train | function | def setup(app: Sphinx):
'''
Sphinx setup stage.
Parameters:
app (Sphinx): Sphinx application instance.
'''
app.connect('builder-inited', generate_documentation)
| def setup(app: Sphinx):
| '''
Sphinx setup stage.
Parameters:
app (Sphinx): Sphinx application instance.
'''
app.connect('builder-inited', generate_documentation)
| (config_directory, '..', '..', 'nfsops/')
output_path = os.path.join(config_directory, 'api-reference/')
apidoc.main(['-f', '-e', '-T', '-d', '2', '-o', output_path, module_path])
def setup(app: Sphinx):
| 64 | 64 | 43 | 7 | 57 | nfsops/nfsops | docs/nfsops/conf.py | Python | setup | setup | 36 | 44 | 36 | 36 | 05398f8b3eaa3b870bc55347097e84fc03da42ee | bigcode/the-stack | train |
c35d922e633bcdd2a679113c | train | function | def list_opts():
return [
('BACKEND',
itertools.chain(
[cinder_cmd_volume.host_opt],
)),
('BRCD_FABRIC_EXAMPLE',
itertools.chain(
cinder_zonemanager_drivers_brocade_brcdfabricopts.
brcd_zone_opts,
)),
... | def list_opts():
| return [
('BACKEND',
itertools.chain(
[cinder_cmd_volume.host_opt],
)),
('BRCD_FABRIC_EXAMPLE',
itertools.chain(
cinder_zonemanager_drivers_brocade_brcdfabricopts.
brcd_zone_opts,
)),
('CISCO_FABR... | import zfssanfs as \
cinder_volume_drivers_zfssa_zfssanfs
from cinder.volume.drivers.zte import zte_ks as cinder_volume_drivers_zte_zteks
from cinder.volume import manager as cinder_volume_manager
from cinder.wsgi import eventlet_server as cinder_wsgi_eventletserver
from cinder.zonemanager.drivers.brocade import b... | 256 | 256 | 2,358 | 4 | 251 | liangintel/stx-cinder | cinder/opts.py | Python | list_opts | list_opts | 212 | 413 | 212 | 212 | 9b0658e1dc019991ae37dc3337a68cdf336e3fab | bigcode/the-stack | train |
31ec5b88ab40856d81658eca | train | function | def create_covar_matrix_original(overlap_array,variances):
"""Create the covariance matrix for a single wavelength slice.
As input takes the output of the drizzle class, overlap_array,
and the variances of the individual fibres"""
covarS = 2 # Radius of sub-region to record covariance inf... | def create_covar_matrix_original(overlap_array,variances):
| """Create the covariance matrix for a single wavelength slice.
As input takes the output of the drizzle class, overlap_array,
and the variances of the individual fibres"""
covarS = 2 # Radius of sub-region to record covariance information - probably
# shouldn't be hard code... | from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
def create_covar_matrix_original(overlap_array,variances):
| 34 | 203 | 678 | 13 | 20 | rscalzo/sami | general/covar.py | Python | create_covar_matrix_original | create_covar_matrix_original | 5 | 57 | 5 | 5 | 62d147373e08ee75b11d932a97ea5092b953bec1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.