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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36be0971ec8204256bcc6b6c | train | function | def _detection_layer(inputs, num_classes, anchors, img_size, data_format):
num_anchors = len(anchors)
predictions = slim.conv2d(inputs, num_anchors * (5 + num_classes), 1,
stride=1, normalizer_fn=None,
activation_fn=None,
... | def _detection_layer(inputs, num_classes, anchors, img_size, data_format):
| num_anchors = len(anchors)
predictions = slim.conv2d(inputs, num_anchors * (5 + num_classes), 1,
stride=1, normalizer_fn=None,
activation_fn=None,
biases_initializer=tf.zeros_initializer())
shape = predictions.get_sha... | _conv2d_fixed_padding(up_route_54,128,kernel_size=1)
net = tf.concat([route,net], axis=1 if data_format == 'NCHW' else 3)
net = _yolo_conv_block(net,256,2,1)
#features of 136 layer
route_1 = net
return route_1, route_2, route_3
def _get_size(shape, data_format):
if len(shape) == 4:
sh... | 156 | 156 | 523 | 18 | 138 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _detection_layer | _detection_layer | 182 | 232 | 182 | 182 | ebc801a47d4736fbcd06df509da133c209b10198 | bigcode/the-stack | train |
676b0547191847b2b1575710 | train | function | def _yolo_res_Block(inputs,in_channels,res_num,data_format,double_ch=False):
out_channels = in_channels
if double_ch:
out_channels = in_channels * 2
net = _conv2d_fixed_padding(inputs,in_channels*2,kernel_size=3,strides=2)#cov后分支
route = _conv2d_fixed_padding(net,out_channels,kernel_size=1)#右
... | def _yolo_res_Block(inputs,in_channels,res_num,data_format,double_ch=False):
| out_channels = in_channels
if double_ch:
out_channels = in_channels * 2
net = _conv2d_fixed_padding(inputs,in_channels*2,kernel_size=3,strides=2)#cov后分支
route = _conv2d_fixed_padding(net,out_channels,kernel_size=1)#右
net = _conv2d_fixed_padding(net,out_channels,kernel_size=1)#左
for _ in... | if strides > 1:
inputs = _fixed_padding(inputs, kernel_size)
inputs = slim.conv2d(inputs, filters, kernel_size, stride=strides,
padding=('SAME' if strides == 1 else 'VALID'))
return inputs
def _yolo_res_Block(inputs,in_channels,res_num,data_format,double_ch=False):
| 71 | 71 | 237 | 17 | 53 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _yolo_res_Block | _yolo_res_Block | 55 | 75 | 55 | 55 | 49340500273df451a17a5d942f638bbab274096d | bigcode/the-stack | train |
1299de091aabfc0dc2d2adde | train | function | def _upsample(inputs, out_shape, data_format='NCHW'):
# tf.image.resize_nearest_neighbor accepts input in format NHWC
if data_format == 'NCHW':
inputs = tf.transpose(inputs, [0, 2, 3, 1])
if data_format == 'NCHW':
new_height = out_shape[2]
new_width = out_shape[3]
else:
... | def _upsample(inputs, out_shape, data_format='NCHW'):
# tf.image.resize_nearest_neighbor accepts input in format NHWC
| if data_format == 'NCHW':
inputs = tf.transpose(inputs, [0, 2, 3, 1])
if data_format == 'NCHW':
new_height = out_shape[2]
new_width = out_shape[3]
else:
new_height = out_shape[1]
new_width = out_shape[2]
inputs = tf.image.resize_nearest_neighbor(inputs, (new_hei... | d(inputs, 5, 1, 'SAME'),
inputs],
axis=1 if data_format == 'NCHW' else 3)
def _upsample(inputs, out_shape, data_format='NCHW'):
# tf.image.resize_nearest_neighbor accepts input in format NHWC
| 64 | 64 | 182 | 31 | 33 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _upsample | _upsample | 99 | 118 | 99 | 100 | a001519f50cfa93790eb1f13912220d2f78ff82f | bigcode/the-stack | train |
6ed87a807678d1ced29b4c0d | train | function | def yolo_v4(inputs, num_classes, is_training=False, data_format='NCHW', reuse=False):
"""
Creates YOLO v4 model.
:param inputs: a 4-D tensor of size [batch_size, height, width, channels].
Dimension batch_size may be undefined. The channel order is RGB.
:param num_classes: number of predicted cl... | def yolo_v4(inputs, num_classes, is_training=False, data_format='NCHW', reuse=False):
| """
Creates YOLO v4 model.
:param inputs: a 4-D tensor of size [batch_size, height, width, channels].
Dimension batch_size may be undefined. The channel order is RGB.
:param num_classes: number of predicted classes.
:param is_training: whether is training or not.
:param data_format: dat... | (confidence)
grid_x = tf.range(grid_size[0], dtype=tf.float32)
grid_y = tf.range(grid_size[1], dtype=tf.float32)
a, b = tf.meshgrid(grid_x, grid_y)
x_offset = tf.reshape(a, (-1, 1))
y_offset = tf.reshape(b, (-1, 1))
x_y_offset = tf.concat([x_offset, y_offset], axis=-1)
x_y_offset = tf.res... | 255 | 255 | 852 | 24 | 230 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | yolo_v4 | yolo_v4 | 237 | 307 | 237 | 237 | 8039c4b1e89c1b3c4f7c83ad724c9d743cf84c32 | bigcode/the-stack | train |
528f94fe55c413d71cc5e66d | train | function | def _get_size(shape, data_format):
if len(shape) == 4:
shape = shape[1:]
return shape[1:3] if data_format == 'NCHW' else shape[0:2]
| def _get_size(shape, data_format):
| if len(shape) == 4:
shape = shape[1:]
return shape[1:3] if data_format == 'NCHW' else shape[0:2]
| == 'NCHW' else 3)
net = _yolo_conv_block(net,256,2,1)
#features of 136 layer
route_1 = net
return route_1, route_2, route_3
def _get_size(shape, data_format):
| 64 | 64 | 49 | 9 | 54 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _get_size | _get_size | 176 | 179 | 176 | 176 | 2f786b0e8f2b785fd2c3a09cf6864fde2c70e7af | bigcode/the-stack | train |
d8b8baf3cd69a0fd3e1db450 | train | function | def _conv2d_fixed_padding(inputs, filters, kernel_size, strides=1):
if strides > 1:
inputs = _fixed_padding(inputs, kernel_size)
inputs = slim.conv2d(inputs, filters, kernel_size, stride=strides,
padding=('SAME' if strides == 1 else 'VALID'))
return inputs
| def _conv2d_fixed_padding(inputs, filters, kernel_size, strides=1):
| if strides > 1:
inputs = _fixed_padding(inputs, kernel_size)
inputs = slim.conv2d(inputs, filters, kernel_size, stride=strides,
padding=('SAME' if strides == 1 else 'VALID'))
return inputs
| padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end],
[pad_beg, pad_end], [0, 0]], mode=mode)
return padded_inputs
def _conv2d_fixed_padding(inputs, filters, kernel_size, strides=1):
| 64 | 64 | 73 | 18 | 45 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _conv2d_fixed_padding | _conv2d_fixed_padding | 47 | 52 | 47 | 47 | a76a1feae00b6388b18d1da3991faa52a2fddf75 | bigcode/the-stack | train |
6150300d4a2fdde31a6039ee | train | function | def csp_darknet53(inputs,data_format):
"""
Builds CSPDarknet-53 model.
"""
net = _conv2d_fixed_padding(inputs,32,kernel_size=3)
#downsample
#res1
net=_yolo_res_Block(net,32,1,data_format,double_ch=True)
#res2
net = _yolo_res_Block(net,64,2,data_format)
#res8
net = _yolo_res_B... | def csp_darknet53(inputs,data_format):
| """
Builds CSPDarknet-53 model.
"""
net = _conv2d_fixed_padding(inputs,32,kernel_size=3)
#downsample
#res1
net=_yolo_res_Block(net,32,1,data_format,double_ch=True)
#res2
net = _yolo_res_Block(net,64,2,data_format)
#res8
net = _yolo_res_Block(net,128,8,data_format)
#featu... | in format NHWC
if data_format == 'NCHW':
inputs = tf.transpose(inputs, [0, 2, 3, 1])
if data_format == 'NCHW':
new_height = out_shape[2]
new_width = out_shape[3]
else:
new_height = out_shape[1]
new_width = out_shape[2]
inputs = tf.image.resize_nearest_neighbor(... | 166 | 166 | 555 | 10 | 155 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | csp_darknet53 | csp_darknet53 | 121 | 174 | 121 | 121 | 67fc53a368d3003451182f46fbc67b9a5bd9f95e | bigcode/the-stack | train |
86ed311d9e991d47ae6c1942 | train | function | @tf.contrib.framework.add_arg_scope
def _fixed_padding(inputs, kernel_size, *args, mode='CONSTANT', **kwargs):
"""
Pads the input along the spatial dimensions independently of input size.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, cha... | @tf.contrib.framework.add_arg_scope
def _fixed_padding(inputs, kernel_size, *args, mode='CONSTANT', **kwargs):
| """
Pads the input along the spatial dimensions independently of input size.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, channels] depending on data_format.
kernel_size: The kernel to be used in the conv2d or max_pool2d operation... | = 0.1
_ANCHORS = [(12, 16), (19, 36), (40, 28),
(36, 75), (76, 55), (72, 146),
(142, 110), (192, 243), (459, 401)]
@tf.contrib.framework.add_arg_scope
def _fixed_padding(inputs, kernel_size, *args, mode='CONSTANT', **kwargs):
| 94 | 94 | 314 | 28 | 66 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _fixed_padding | _fixed_padding | 14 | 43 | 14 | 15 | ab9a82e5b2d414447ed668193f93e6fa425be701 | bigcode/the-stack | train |
288fb02ebc566742b9d8cdff | train | function | def _yolo_conv_block(net,in_channels,a,b):
for _ in range(a):
out_channels=in_channels/2
net = _conv2d_fixed_padding(net,out_channels,kernel_size=1)
net = _conv2d_fixed_padding(net,in_channels,kernel_size=3)
out_channels=in_channels
for _ in range(b):
out_channels=out_channe... | def _yolo_conv_block(net,in_channels,a,b):
| for _ in range(a):
out_channels=in_channels/2
net = _conv2d_fixed_padding(net,out_channels,kernel_size=1)
net = _conv2d_fixed_padding(net,in_channels,kernel_size=3)
out_channels=in_channels
for _ in range(b):
out_channels=out_channels/2
net = _conv2d_fixed_padding(ne... | #concat
net=tf.concat([net,route],axis=1 if data_format == 'NCHW' else 3)
net=_conv2d_fixed_padding(net,in_channels*2,kernel_size=1)
return net
def _yolo_conv_block(net,in_channels,a,b):
| 64 | 64 | 107 | 12 | 51 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _yolo_conv_block | _yolo_conv_block | 77 | 88 | 77 | 77 | 5e9b3a8b4965cac446671035fa5848928cf3b284 | bigcode/the-stack | train |
24b33303c72d3bf56f2aa14b | train | function | def _spp_block(inputs, data_format='NCHW'):
return tf.concat([slim.max_pool2d(inputs, 13, 1, 'SAME'),
slim.max_pool2d(inputs, 9, 1, 'SAME'),
slim.max_pool2d(inputs, 5, 1, 'SAME'),
inputs],
axis=1 if data_format == 'NCHW' else 3)
| def _spp_block(inputs, data_format='NCHW'):
| return tf.concat([slim.max_pool2d(inputs, 13, 1, 'SAME'),
slim.max_pool2d(inputs, 9, 1, 'SAME'),
slim.max_pool2d(inputs, 5, 1, 'SAME'),
inputs],
axis=1 if data_format == 'NCHW' else 3)
| ,kernel_size=3)
out_channels=in_channels
for _ in range(b):
out_channels=out_channels/2
net = _conv2d_fixed_padding(net,out_channels,kernel_size=1)
return net
def _spp_block(inputs, data_format='NCHW'):
| 64 | 64 | 93 | 14 | 49 | Clark1216/OpenVINO-YOLOV4 | yolov4-relu/yolo_v4.py | Python | _spp_block | _spp_block | 91 | 96 | 91 | 91 | a29648fa07de1b0d4035a56f6750d46dfcb78452 | bigcode/the-stack | train |
e20a961ee5926cca572515ab | train | class | class Migration(migrations.Migration):
dependencies = [
('complaints', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='complaints',
name='ticket_id',
field=models.CharField(default=complaints.models.generate_key, max_length=25),
... | class Migration(migrations.Migration):
| dependencies = [
('complaints', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='complaints',
name='ticket_id',
field=models.CharField(default=complaints.models.generate_key, max_length=25),
),
migrations.AlterField(
... | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-21 13:09
from __future__ import unicode_literals
import complaints.models
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
| 61 | 64 | 144 | 7 | 53 | shashank-sharma/smart-odisha-hackathon | complaints/migrations/0002_auto_20180321_1309.py | Python | Migration | Migration | 10 | 27 | 10 | 11 | 4c1b94bed69aa6ee149a23195275a9eeb7c4f139 | bigcode/the-stack | train |
3a14e6e820c6e5a615dd4a13 | train | class | class Bets:
def __init__(self, principal, o1, o2):
self.principal = principal
self.o1 = o1
self.o2 = o2
def solution(self, option1 = None, option2=None):
if option1 == True and option2 == None:
x = Symbol('x')
solution = solve(x*self.o1 - (self.principa... | class Bets:
| def __init__(self, principal, o1, o2):
self.principal = principal
self.o1 = o1
self.o2 = o2
def solution(self, option1 = None, option2=None):
if option1 == True and option2 == None:
x = Symbol('x')
solution = solve(x*self.o1 - (self.principal - x), x)
... | = Symbol('x')
a = solve(x*2.20 - 120, x)
type(a) is a list with the answer of the equation
Links:
https://pythonforundergradengineers.com/sympy-two-equations-for-two-unknows-and-statics-problem.html
https://www.google.com/search?channel=fs&client=ubuntu&q=sympy
"""
from sympy.solvers import solve
from sympy impo... | 104 | 104 | 349 | 4 | 99 | arcelioeperez/Finance-Projects | Betting/odds.py | Python | Bets | Bets | 47 | 82 | 47 | 47 | 26673ed84a736a4f10248f7ff465c3a6f14304a3 | bigcode/the-stack | train |
5cf76725f79baf91907b7656 | train | class | class FusionUtils:
def __init__(self, model: OnnxModel):
self.model: OnnxModel = model
def cast_graph_input_to_int32(self, input_name: str) -> Tuple[bool, str]:
graph_input = self.model.find_graph_input(input_name)
if graph_input is not None and graph_input.type.tensor_type.elem_type !=... | class FusionUtils:
| def __init__(self, model: OnnxModel):
self.model: OnnxModel = model
def cast_graph_input_to_int32(self, input_name: str) -> Tuple[bool, str]:
graph_input = self.model.find_graph_input(input_name)
if graph_input is not None and graph_input.type.tensor_type.elem_type != TensorProto.INT32:... | #-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
from logging import getLogger
from OnnxModel import OnnxModel
from typing ... | 64 | 130 | 436 | 4 | 60 | linnealovespie/onnxruntime | onnxruntime/python/tools/transformers/fusion_utils.py | Python | FusionUtils | FusionUtils | 13 | 57 | 13 | 13 | 3aae4e946903d2681db3dbdc919f0c607ad82fac | bigcode/the-stack | train |
acf39990065e894d0d33b8c3 | train | function | def downgrade():
# Delete any rows referencing the enum state
op.execute("DELETE FROM settings WHERE key = 'ArchiveChannel'")
# Rename the old type
op.execute("ALTER TYPE settingskey RENAME TO settingskey_old")
# Create a new type with all fields except TicketCategory
op.execute(
"CREA... | def downgrade():
# Delete any rows referencing the enum state
| op.execute("DELETE FROM settings WHERE key = 'ArchiveChannel'")
# Rename the old type
op.execute("ALTER TYPE settingskey RENAME TO settingskey_old")
# Create a new type with all fields except TicketCategory
op.execute(
"CREATE TYPE settingskey AS ENUM('ManagementRole', 'PanelAccessRole', '... | .
revision = "f90d606fedf5"
down_revision = "dcbd19c929ed"
branch_labels = None
depends_on = None
def upgrade():
op.execute("ALTER TYPE settingskey ADD VALUE 'ArchiveChannel'")
def downgrade():
# Delete any rows referencing the enum state
| 63 | 64 | 144 | 13 | 51 | WaffleHacks/wafflebot | alembic/versions/f90d606fedf5_add_archive_channel_setting_key.py | Python | downgrade | downgrade | 23 | 41 | 23 | 24 | 25adc23f4145980a76f04209aa7fd4697bf104f6 | bigcode/the-stack | train |
ec3a814405081ada6801a56d | train | function | def upgrade():
op.execute("ALTER TYPE settingskey ADD VALUE 'ArchiveChannel'")
| def upgrade():
| op.execute("ALTER TYPE settingskey ADD VALUE 'ArchiveChannel'")
| 410+00:00
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "f90d606fedf5"
down_revision = "dcbd19c929ed"
branch_labels = None
depends_on = None
def upgrade():
| 64 | 64 | 17 | 3 | 60 | WaffleHacks/wafflebot | alembic/versions/f90d606fedf5_add_archive_channel_setting_key.py | Python | upgrade | upgrade | 19 | 20 | 19 | 19 | 8ced28cac87fd0f42915ea52189bb5971999858b | bigcode/the-stack | train |
4db727b6eac1c27e4f159fad | train | class | class ListCmd(object):
def __init__(self):
self.cmd = ListCommand()
self.options, self.args = self.cmd.parser.parse_args(['-o'])
@property
def outdated_packages(self):
for package_data in self.cmd.find_packages_latests_versions(
self.options):
di... | class ListCmd(object):
| def __init__(self):
self.cmd = ListCommand()
self.options, self.args = self.cmd.parser.parse_args(['-o'])
@property
def outdated_packages(self):
for package_data in self.cmd.find_packages_latests_versions(
self.options):
dist, remote = package_dat... | from pip.commands import ListCommand
class ListCmd(object):
| 12 | 64 | 141 | 5 | 6 | Largo/Lurnby | manipulate/venv/lib/python3.6/site-packages/pip_upgrade/commands/list.py | Python | ListCmd | ListCmd | 4 | 19 | 4 | 4 | 95afe5f825ca131808fbfabf5040135aa3042f00 | bigcode/the-stack | train |
a660bc51567889d9680532d8 | train | function | def train_nn(model, x_train, y_train):
# optimizer = torch.optim.SGD(model.parameters(), lr = 0.001)
optimizer = torch.optim.Adam(model.parameters(), lr = 0.005)
model.train()
epoch = 250
for epoch in range(epoch):
optimizer.zero_grad()
# Forward pass
y_pred = model... | def train_nn(model, x_train, y_train):
# optimizer = torch.optim.SGD(model.parameters(), lr = 0.001)
| optimizer = torch.optim.Adam(model.parameters(), lr = 0.005)
model.train()
epoch = 250
for epoch in range(epoch):
optimizer.zero_grad()
# Forward pass
y_pred = model(x_train)
# Compute Loss
diff = y_train - y_pred
# loss = torch.matmul(torch.transpose... | self.relu(output)
output = self.fc3(output)
return output
def predict(self, x, debug=False):
return self.forward(x)
def train_nn(model, x_train, y_train):
# optimizer = torch.optim.SGD(model.parameters(), lr = 0.001)
| 62 | 64 | 202 | 30 | 32 | franciscovargas/GP_Sinkhorn | gp_sinkhorn/NN.py | Python | train_nn | train_nn | 30 | 53 | 30 | 32 | c426de5f2273b10491490146629d413603da6770 | bigcode/the-stack | train |
2454646d0699eb90de4583c2 | train | class | class Feedforward(torch.nn.Module):
def __init__(self, input_size=2, hidden_size=500):
super(Feedforward, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)
self.relu = torch.nn.ReLU... | class Feedforward(torch.nn.Module):
| def __init__(self, input_size=2, hidden_size=500):
super(Feedforward, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.fc1 = torch.nn.Linear(self.input_size, self.hidden_size)
self.relu = torch.nn.ReLU()
self.bn = torch.nn.BatchNorm1d... | import torch
class Feedforward(torch.nn.Module):
| 11 | 64 | 195 | 8 | 2 | franciscovargas/GP_Sinkhorn | gp_sinkhorn/NN.py | Python | Feedforward | Feedforward | 5 | 27 | 5 | 6 | 52cf7869a1865c5ca3109a715094156e7729594e | bigcode/the-stack | train |
e979fb87e09be796519735e7 | train | function | def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('config.py')
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
db.init_app(app)
moment.init_app(app)
from .main import main... | def create_app(config_name):
| app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('config.py')
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
db.init_app(app)
moment.init_app(app)
from .main import main as main_blueprint
app.re... | /env python
# -*- coding: utf-8 -*-
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_moment import Moment
from flask import Flask
from instance.config import config
bootstrap = Bootstrap()
db = SQLAlchemy()
moment = Moment()
def create_app(config_name):
| 64 | 64 | 90 | 6 | 58 | atwh0405/moviee | app/__init__.py | Python | create_app | create_app | 15 | 25 | 15 | 15 | d83cb7a51e991e6c59dd974bcf370ebe46556520 | bigcode/the-stack | train |
a2737ea0ff72f1db41fbad26 | train | function | def _check_array_from_pandas_roundtrip(np_array, type=None):
arr = pa.array(np_array, from_pandas=True, type=type)
result = arr.to_pandas()
npt.assert_array_equal(result, np_array)
| def _check_array_from_pandas_roundtrip(np_array, type=None):
| arr = pa.array(np_array, from_pandas=True, type=type)
result = arr.to_pandas()
npt.assert_array_equal(result, np_array)
| None:
if mask is None:
expected = pd.Series(values)
else:
expected = pd.Series(np.ma.masked_array(values, mask=mask))
tm.assert_series_equal(pd.Series(result), expected, check_names=False)
def _check_array_from_pandas_roundtrip(np_array, type=None):
| 64 | 64 | 51 | 15 | 49 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _check_array_from_pandas_roundtrip | _check_array_from_pandas_roundtrip | 135 | 138 | 135 | 135 | ea2449e8bf66b24bf130475cce1948f261785c7c | bigcode/the-stack | train |
602538f09d5df1cdc7ff2c4b | train | class | class TestConvertStructTypes(object):
"""
Conversion tests for struct types.
"""
def test_pandas_roundtrip(self):
df = pd.DataFrame({'dicts': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]})
expected_schema = pa.schema([
('dicts', pa.struct([('a', pa.int64()), ('b', pa.int64())])),
... | class TestConvertStructTypes(object):
| """
Conversion tests for struct types.
"""
def test_pandas_roundtrip(self):
df = pd.DataFrame({'dicts': [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]})
expected_schema = pa.schema([
('dicts', pa.struct([('a', pa.int64()), ('b', pa.int64())])),
])
_check_pandas_round... | [None, [None], None]
)
])
def test_array_from_pandas_typed_array_with_mask(self, t, data, expected):
m = np.array([True, False, True])
s = pd.Series(data)
result = pa.Array.from_pandas(s, mask=m, type=pa.list_(t()))
assert pa.Array.from_pandas(expected,
... | 256 | 256 | 1,624 | 7 | 249 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertStructTypes | TestConvertStructTypes | 1,965 | 2,141 | 1,965 | 1,965 | 53fa6f64b306b42e1f1efec0b061688a9375d57a | bigcode/the-stack | train |
7f2d2b3d5fa895404131925d | train | function | @pytest.mark.parametrize('dtype',
['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])
def test_table_integer_object_nulls_option(dtype):
num_values = 100
null_mask = np.random.randint(0, 10, size=num_values) < 3
values = np.random.randint(0, 100, size=num_values, dtype=dtype)
ar... | @pytest.mark.parametrize('dtype',
['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])
def test_table_integer_object_nulls_option(dtype):
| num_values = 100
null_mask = np.random.randint(0, 10, size=num_values) < 3
values = np.random.randint(0, 100, size=num_values, dtype=dtype)
array = pa.array(values, mask=null_mask)
if null_mask.any():
expected = values.astype('O')
expected[null_mask] = None
else:
expec... | (integer_object_nulls=True)
np.testing.assert_equal(result, expected)
@pytest.mark.parametrize('dtype',
['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])
def test_table_integer_object_nulls_option(dtype):
| 64 | 64 | 185 | 49 | 15 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_integer_object_nulls_option | test_table_integer_object_nulls_option | 883 | 904 | 883 | 885 | 154fa012610a138a5eed53912a20f84a39dc8bca | bigcode/the-stack | train |
ecc1b3cc5c115baafdb6700b | train | function | def test_recordbatch_table_pass_name_to_pandas():
rb = pa.record_batch([pa.array([1, 2, 3, 4])], names=['a0'])
t = pa.table([pa.array([1, 2, 3, 4])], names=['a0'])
assert rb[0].to_pandas().name == 'a0'
assert t[0].to_pandas().name == 'a0'
| def test_recordbatch_table_pass_name_to_pandas():
| rb = pa.record_batch([pa.array([1, 2, 3, 4])], names=['a0'])
t = pa.table([pa.array([1, 2, 3, 4])], names=['a0'])
assert rb[0].to_pandas().name == 'a0'
assert t[0].to_pandas().name == 'a0'
| _pandas(data2)
table = pa.Table.from_batches([batch1, batch2])
result = table.to_pandas()
data = pd.concat([data1, data2]).reset_index(drop=True)
tm.assert_frame_equal(data, result)
def test_recordbatch_table_pass_name_to_pandas():
| 64 | 64 | 96 | 11 | 53 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_recordbatch_table_pass_name_to_pandas | test_recordbatch_table_pass_name_to_pandas | 2,894 | 2,898 | 2,894 | 2,894 | 8b169eaebdd8d7344bd3a8b92851ffe5023cf5ba | bigcode/the-stack | train |
ee1956f6df05d08f2e30638b | train | function | def _threaded_conversion():
df = _alltypes_example()
_check_pandas_roundtrip(df, use_threads=True)
_check_pandas_roundtrip(df, use_threads=True, as_batch=True)
| def _threaded_conversion():
| df = _alltypes_example()
_check_pandas_roundtrip(df, use_threads=True)
_check_pandas_roundtrip(df, use_threads=True, as_batch=True)
| at the top-level for Python 2.7's multiprocessing
def _non_threaded_conversion():
df = _alltypes_example()
_check_pandas_roundtrip(df, use_threads=False)
_check_pandas_roundtrip(df, use_threads=False, as_batch=True)
def _threaded_conversion():
| 64 | 64 | 44 | 6 | 58 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _threaded_conversion | _threaded_conversion | 2,196 | 2,199 | 2,196 | 2,196 | 6d284d6dcddcd052575e6cdad424416c108f2472 | bigcode/the-stack | train |
c7795d4e547f8bd7dcc2e852 | train | function | def test_metadata_compat_missing_field_name():
# Combination of missing field name but with index column as metadata.
# This combo occurs in the latest versions of fastparquet (0.3.2), but not
# in pyarrow itself (since field_name was added in 0.8, index as metadata
# only added later)
a_values = [... | def test_metadata_compat_missing_field_name():
# Combination of missing field name but with index column as metadata.
# This combo occurs in the latest versions of fastparquet (0.3.2), but not
# in pyarrow itself (since field_name was added in 0.8, index as metadata
# only added later)
| a_values = [1, 2, 3, 4]
b_values = [u'a', u'b', u'c', u'd']
a_arrow = pa.array(a_values, type='int64')
b_arrow = pa.array(b_values, type='utf8')
expected = pd.DataFrame({
'a': a_values,
'b': b_values,
}, index=pd.RangeIndex(0, 8, step=2, name='qux'))
table = pa.table({'a': a... | 'pandas_type': 'unicode',
'numpy_type': 'object',
'metadata': None}],
'pandas_version': '0.23.4'}
)})
r5 = t5.to_pandas()
tm.assert_frame_equal(r5, e5)
def test_metadata_compat_missing_field_name():
# Combination of missing field name... | 133 | 133 | 445 | 74 | 59 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_metadata_compat_missing_field_name | test_metadata_compat_missing_field_name | 3,374 | 3,423 | 3,374 | 3,379 | c4d756ba36cd69bcaf7bb79574cdbc1db1392c94 | bigcode/the-stack | train |
436e8f002563dc8253529b5a | train | class | class TestConvertMetadata(object):
"""
Conversion tests for Pandas metadata & indices.
"""
def test_non_string_columns(self):
df = pd.DataFrame({0: [1, 2, 3]})
table = pa.Table.from_pandas(df)
assert table.field(0).name == '0'
def test_from_pandas_with_columns(self):
... | class TestConvertMetadata(object):
| """
Conversion tests for Pandas metadata & indices.
"""
def test_non_string_columns(self):
df = pd.DataFrame({0: [1, 2, 3]})
table = pa.Table.from_pandas(df)
assert table.field(0).name == '0'
def test_from_pandas_with_columns(self):
df = pd.DataFrame({0: [1, 2, 3], ... | and expected_pa_type is None:
expected_pa_type = type_
if expected_pa_type is not None:
assert arr.type == expected_pa_type
result = pd.Series(arr.to_pandas(), name=s.name)
tm.assert_series_equal(s, result)
def _check_array_roundtrip(values, expected=None, mask=None,
... | 256 | 256 | 4,111 | 6 | 250 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertMetadata | TestConvertMetadata | 141 | 566 | 141 | 141 | 509d241a10c37734ada9428cd10aad74d0dc3507 | bigcode/the-stack | train |
ed6ce0ed0d4fc77a8caf4f4d | train | function | def test_to_pandas_deduplicate_strings_array_types():
nunique = 100
repeats = 10
values = _generate_dedup_example(nunique, repeats)
for arr in [pa.array(values, type=pa.binary()),
pa.array(values, type=pa.utf8()),
pa.chunked_array([values, values])]:
_assert_nuni... | def test_to_pandas_deduplicate_strings_array_types():
| nunique = 100
repeats = 10
values = _generate_dedup_example(nunique, repeats)
for arr in [pa.array(values, type=pa.binary()),
pa.array(values, type=pa.utf8()),
pa.chunked_array([values, values])]:
_assert_nunique(arr.to_pandas(), nunique)
_assert_nunique(... | , repeats):
unique_values = [tm.rands(10) for i in range(nunique)]
return unique_values * repeats
def _assert_nunique(obj, expected):
assert len({id(x) for x in obj}) == expected
def test_to_pandas_deduplicate_strings_array_types():
| 64 | 64 | 107 | 12 | 51 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_to_pandas_deduplicate_strings_array_types | test_to_pandas_deduplicate_strings_array_types | 2,572 | 2,581 | 2,572 | 2,572 | 7324f43c470f0a99d3fa7926aa65c7d22154c4d1 | bigcode/the-stack | train |
95124a4c2ad6f6ce95c10662 | train | function | def _generate_dedup_example(nunique, repeats):
unique_values = [tm.rands(10) for i in range(nunique)]
return unique_values * repeats
| def _generate_dedup_example(nunique, repeats):
| unique_values = [tm.rands(10) for i in range(nunique)]
return unique_values * repeats
| expected_msg = 'Conversion failed for column diff with type timedelta64'
with pytest.raises(pa.ArrowNotImplementedError, match=expected_msg):
pa.Table.from_pandas(df)
# ----------------------------------------------------------------------
# Test object deduplication in to_pandas
def _generate_dedup_exam... | 64 | 64 | 37 | 12 | 51 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _generate_dedup_example | _generate_dedup_example | 2,563 | 2,565 | 2,563 | 2,563 | 664d9ea4353c81824fba509bcbce528ecc69e112 | bigcode/the-stack | train |
509cf87d2de7066d460fecb7 | train | function | def _check_serialize_components_roundtrip(df):
ctx = pa.default_serialization_context()
components = ctx.serialize(df).to_components()
deserialized = ctx.deserialize_components(components)
tm.assert_frame_equal(df, deserialized)
| def _check_serialize_components_roundtrip(df):
| ctx = pa.default_serialization_context()
components = ctx.serialize(df).to_components()
deserialized = ctx.deserialize_components(components)
tm.assert_frame_equal(df, deserialized)
| 1 = pa.Table.from_pandas(df)
table2 = pa.Table.from_pandas(table1.to_pandas())
assert table1.equals(table2)
assert table1.schema.equals(table2.schema)
assert table1.schema.metadata == table2.schema.metadata
def _check_serialize_components_roundtrip(df):
| 64 | 64 | 49 | 10 | 53 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _check_serialize_components_roundtrip | _check_serialize_components_roundtrip | 2,508 | 2,514 | 2,508 | 2,508 | 8e700e5bdeec5ad50852089bbb231770dc639d9b | bigcode/the-stack | train |
3cc2e93b2e3c9269e7feb1c4 | train | function | def test_table_from_pandas_keeps_column_order_of_dataframe():
df1 = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
df2 = df1[['floats', 'partition', 'arrays']]
schema1 = pa.schema([
... | def test_table_from_pandas_keeps_column_order_of_dataframe():
| df1 = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
df2 = df1[['floats', 'partition', 'arrays']]
schema1 = pa.schema([
('partition', pa.int64()),
('arrays', pa.list_(pa.... | string', 'foo']})
schema = pa.schema([pa.field('a', pa.float64(), nullable=False),
pa.field('b', pa.utf8(), nullable=False)])
with pytest.raises(ValueError):
pa.Table.from_pandas(df, schema=schema)
def test_table_from_pandas_keeps_column_order_of_dataframe():
| 70 | 70 | 235 | 13 | 57 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_from_pandas_keeps_column_order_of_dataframe | test_table_from_pandas_keeps_column_order_of_dataframe | 2,654 | 2,677 | 2,654 | 2,654 | e0d104b09174ebb4e3ecb03975a27ef135483e14 | bigcode/the-stack | train |
2cd4d1a1d53557acb009ab74 | train | function | @pytest.mark.parametrize(
('type', 'expected'),
[
(pa.null(), 'empty'),
(pa.bool_(), 'bool'),
(pa.int8(), 'int8'),
(pa.int16(), 'int16'),
(pa.int32(), 'int32'),
(pa.int64(), 'int64'),
(pa.uint8(), 'uint8'),
(pa.uint16(), 'uint16'),
(pa.uint... | @pytest.mark.parametrize(
('type', 'expected'),
[
(pa.null(), 'empty'),
(pa.bool_(), 'bool'),
(pa.int8(), 'int8'),
(pa.int16(), 'int16'),
(pa.int32(), 'int32'),
(pa.int64(), 'int64'),
(pa.uint8(), 'uint8'),
(pa.uint16(), 'uint16'),
(pa.uint... | assert get_logical_type(type) == expected
| @pytest.mark.parametrize(
('type', 'expected'),
[
(pa.null(), 'empty'),
(pa.bool_(), 'bool'),
(pa.int8(), 'int8'),
(pa.int16(), 'int16'),
(pa.int32(), 'int32'),
(pa.int64(), 'int64'),
(pa.uint8(), 'uint8'),
(pa.uint16(), 'uint16'),
(pa.uint... | 280 | 87 | 291 | 280 | 0 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_logical_type | test_logical_type | 2,905 | 2,935 | 2,905 | 2,934 | d58ab8af5c7e1d3f61203ac6aaf3aeb44ce09486 | bigcode/the-stack | train |
83b6e3c2bdb28a857cf81ebd | train | function | def test_recordbatch_from_to_pandas():
data = pd.DataFrame({
'c1': np.array([1, 2, 3, 4, 5], dtype='int64'),
'c2': np.array([1, 2, 3, 4, 5], dtype='uint32'),
'c3': np.random.randn(5),
'c4': ['foo', 'bar', None, 'baz', 'qux'],
'c5': [False, True, False, True, False]
})
... | def test_recordbatch_from_to_pandas():
| data = pd.DataFrame({
'c1': np.array([1, 2, 3, 4, 5], dtype='int64'),
'c2': np.array([1, 2, 3, 4, 5], dtype='uint32'),
'c3': np.random.randn(5),
'c4': ['foo', 'bar', None, 'baz', 'qux'],
'c5': [False, True, False, True, False]
})
batch = pa.RecordBatch.from_pandas(da... | , schema=schema, preserve_index=True,
expected_schema=schema, expected=expected)
_check_pandas_roundtrip(df, schema=schema, preserve_index=None,
expected_schema=schema, expected=expected)
# --------------------------------------------------------------------... | 64 | 64 | 147 | 9 | 54 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_recordbatch_from_to_pandas | test_recordbatch_from_to_pandas | 2,856 | 2,867 | 2,856 | 2,856 | 03bdd0c155aadbb7882d0aa203d1263b153b8709 | bigcode/the-stack | train |
52e419e64e415c01b7736b33 | train | function | def test_convert_unsupported_type_error_message():
# ARROW-1454
df = pd.DataFrame({
't1': pd.date_range('2000-01-01', periods=20),
't2': pd.date_range('2000-05-01', periods=20)
})
# timedelta64 as yet unsupported
df['diff'] = df.t2 - df.t1
expected_msg = 'Conversion failed for... | def test_convert_unsupported_type_error_message():
# ARROW-1454
| df = pd.DataFrame({
't1': pd.date_range('2000-01-01', periods=20),
't2': pd.date_range('2000-05-01', periods=20)
})
# timedelta64 as yet unsupported
df['diff'] = df.t2 - df.t1
expected_msg = 'Conversion failed for column diff with type timedelta64'
with pytest.raises(pa.ArrowNo... | time_to_micros(pytime):
return (pytime.hour * 3600000000 +
pytime.minute * 60000000 +
pytime.second * 1000000 +
pytime.microsecond)
def test_convert_unsupported_type_error_message():
# ARROW-1454
| 64 | 64 | 127 | 17 | 47 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_convert_unsupported_type_error_message | test_convert_unsupported_type_error_message | 2,543 | 2,556 | 2,543 | 2,545 | 205d8116620548af6b10c18d4085ce1162dd69e7 | bigcode/the-stack | train |
3a1edd74631106ef8bef9adb | train | function | @pytest.mark.parametrize('dtype',
['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])
def test_array_integer_object_nulls_option(dtype):
num_values = 100
null_mask = np.random.randint(0, 10, size=num_values) < 3
values = np.random.randint(0, 100, size=num_values, dtype=dtype)
ar... | @pytest.mark.parametrize('dtype',
['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])
def test_array_integer_object_nulls_option(dtype):
| num_values = 100
null_mask = np.random.randint(0, 10, size=num_values) < 3
values = np.random.randint(0, 100, size=num_values, dtype=dtype)
array = pa.array(values, mask=null_mask)
if null_mask.any():
expected = values.astype('O')
expected[null_mask] = None
else:
expec... | assert x == 1.5
assert y is None
@pytest.mark.parametrize('dtype',
['i1', 'i2', 'i4', 'i8', 'u1', 'u2', 'u4', 'u8'])
def test_array_integer_object_nulls_option(dtype):
| 64 | 64 | 161 | 49 | 14 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_array_integer_object_nulls_option | test_array_integer_object_nulls_option | 862 | 880 | 862 | 864 | 756781d90d1303cd48d95eb6c6f0ae91b70483d3 | bigcode/the-stack | train |
621aed375263d86db95ac277 | train | function | def test_recordbatchlist_to_pandas():
data1 = pd.DataFrame({
'c1': np.array([1, 1, 2], dtype='uint32'),
'c2': np.array([1.0, 2.0, 3.0], dtype='float64'),
'c3': [True, None, False],
'c4': ['foo', 'bar', None]
})
data2 = pd.DataFrame({
'c1': np.array([3, 5], dtype='uin... | def test_recordbatchlist_to_pandas():
| data1 = pd.DataFrame({
'c1': np.array([1, 1, 2], dtype='uint32'),
'c2': np.array([1.0, 2.0, 3.0], dtype='float64'),
'c3': [True, None, False],
'c4': ['foo', 'bar', None]
})
data2 = pd.DataFrame({
'c1': np.array([3, 5], dtype='uint32'),
'c2': np.array([4.0, 5.... | ': ['foo', 'bar', None, 'baz', 'qux'],
'c5': [False, True, False, True, False]
})
batch = pa.RecordBatch.from_pandas(data)
result = batch.to_pandas()
tm.assert_frame_equal(data, result)
def test_recordbatchlist_to_pandas():
| 71 | 71 | 238 | 9 | 62 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_recordbatchlist_to_pandas | test_recordbatchlist_to_pandas | 2,870 | 2,891 | 2,870 | 2,870 | fb87fe1c8ffe8f78bed37acac13c31ec4da557bc | bigcode/the-stack | train |
9ecded70d31a4dc2cc3f03b1 | train | function | @pytest.mark.skipif(LooseVersion(np.__version__) >= '0.16',
reason='Until numpy/numpy#12745 is resolved')
def test_serialize_deserialize_pandas():
# ARROW-1784, serialize and deserialize DataFrame by decomposing
# BlockManager
df = _fully_loaded_dataframe_example()
_check_serialize_c... | @pytest.mark.skipif(LooseVersion(np.__version__) >= '0.16',
reason='Until numpy/numpy#12745 is resolved')
def test_serialize_deserialize_pandas():
# ARROW-1784, serialize and deserialize DataFrame by decomposing
# BlockManager
| df = _fully_loaded_dataframe_example()
_check_serialize_components_roundtrip(df)
| deserialized)
@pytest.mark.skipif(LooseVersion(np.__version__) >= '0.16',
reason='Until numpy/numpy#12745 is resolved')
def test_serialize_deserialize_pandas():
# ARROW-1784, serialize and deserialize DataFrame by decomposing
# BlockManager
| 64 | 64 | 80 | 61 | 3 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_serialize_deserialize_pandas | test_serialize_deserialize_pandas | 2,517 | 2,523 | 2,517 | 2,521 | 4222ef33dc0cb9646b950878dd5a14d0ac7d8b68 | bigcode/the-stack | train |
7e086ecc8869cc336f4c8adf | train | function | def _check_array_roundtrip(values, expected=None, mask=None,
type=None):
arr = pa.array(values, from_pandas=True, mask=mask, type=type)
result = arr.to_pandas()
values_nulls = pd.isnull(values)
if mask is None:
assert arr.null_count == values_nulls.sum()
else:
... | def _check_array_roundtrip(values, expected=None, mask=None,
type=None):
| arr = pa.array(values, from_pandas=True, mask=mask, type=type)
result = arr.to_pandas()
values_nulls = pd.isnull(values)
if mask is None:
assert arr.null_count == values_nulls.sum()
else:
assert arr.null_count == (mask | values_nulls).sum()
if expected is None:
if mask ... | _pa_type = type_
if expected_pa_type is not None:
assert arr.type == expected_pa_type
result = pd.Series(arr.to_pandas(), name=s.name)
tm.assert_series_equal(s, result)
def _check_array_roundtrip(values, expected=None, mask=None,
type=None):
| 64 | 64 | 144 | 18 | 46 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _check_array_roundtrip | _check_array_roundtrip | 115 | 132 | 115 | 116 | 11187f7c5117beb9a98a3fcf5f9bb83b6bb8facf | bigcode/the-stack | train |
147478b583c71c1559e24062 | train | class | class TestZeroCopyConversion(object):
"""
Tests that zero-copy conversion works with some types.
"""
def test_zero_copy_success(self):
result = pa.array([0, 1, 2]).to_pandas(zero_copy_only=True)
npt.assert_array_equal(result, [0, 1, 2])
def test_zero_copy_dictionaries(self):
... | class TestZeroCopyConversion(object):
| """
Tests that zero-copy conversion works with some types.
"""
def test_zero_copy_success(self):
result = pa.array([0, 1, 2]).to_pandas(zero_copy_only=True)
npt.assert_array_equal(result, [0, 1, 2])
def test_zero_copy_dictionaries(self):
arr = pa.DictionaryArray.from_arrays... | from tuples works when specifying expected struct type
struct_type = pa.struct([('a', pa.int64()), ('b', pa.int64())])
arr = np.asarray(df['tuples'])
_check_array_roundtrip(
arr, expected=expected_df['tuples'], type=struct_type)
expected_schema = pa.schema([('tuples', stru... | 113 | 113 | 377 | 7 | 106 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestZeroCopyConversion | TestZeroCopyConversion | 2,144 | 2,186 | 2,144 | 2,144 | 75b3d773e1dd793f0b70cf177f1a4f5a0e0f5f6d | bigcode/the-stack | train |
9613523bd57e3794f831bd58 | train | function | def _assert_nunique(obj, expected):
assert len({id(x) for x in obj}) == expected
| def _assert_nunique(obj, expected):
| assert len({id(x) for x in obj}) == expected
| _pandas(df)
# ----------------------------------------------------------------------
# Test object deduplication in to_pandas
def _generate_dedup_example(nunique, repeats):
unique_values = [tm.rands(10) for i in range(nunique)]
return unique_values * repeats
def _assert_nunique(obj, expected):
| 64 | 64 | 24 | 9 | 54 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _assert_nunique | _assert_nunique | 2,568 | 2,569 | 2,568 | 2,568 | 616a491fcbc44095d312515a6a2159127fa8e97f | bigcode/the-stack | train |
73c08fc7e65e9b5653b3b7d0 | train | function | def test_object_leak_in_dataframe():
# ARROW-6876
arr = pa.array([{'a': 1}])
table = pa.table([arr], ['f0'])
col = table.to_pandas()['f0']
assert col.dtype == np.dtype('object')
obj = col[0]
refcount = sys.getrefcount(obj)
assert sys.getrefcount(obj) == refcount
del col
assert sy... | def test_object_leak_in_dataframe():
# ARROW-6876
| arr = pa.array([{'a': 1}])
table = pa.table([arr], ['f0'])
col = table.to_pandas()['f0']
assert col.dtype == np.dtype('object')
obj = col[0]
refcount = sys.getrefcount(obj)
assert sys.getrefcount(obj) == refcount
del col
assert sys.getrefcount(obj) == refcount - 1
| = np_arr[0]
refcount = sys.getrefcount(obj)
assert sys.getrefcount(obj) == refcount
del np_arr
assert sys.getrefcount(obj) == refcount - 1
def test_object_leak_in_dataframe():
# ARROW-6876
| 64 | 64 | 110 | 16 | 47 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_object_leak_in_dataframe | test_object_leak_in_dataframe | 2,995 | 3,005 | 2,995 | 2,996 | 7a1900c1f672b144a81e23f8bb64dbdac8ac6d5b | bigcode/the-stack | train |
0a6666a0d48dfb1515f4855f | train | function | def test_table_from_pandas_schema_index_columns():
# ARROW-5220
df = pd.DataFrame({'a': [1, 2, 3], 'b': [0.1, 0.2, 0.3]})
schema = pa.schema([
('a', pa.int64()),
('b', pa.float64()),
('index', pa.int32()),
])
# schema includes index with name not in dataframe
with pytes... | def test_table_from_pandas_schema_index_columns():
# ARROW-5220
| df = pd.DataFrame({'a': [1, 2, 3], 'b': [0.1, 0.2, 0.3]})
schema = pa.schema([
('a', pa.int64()),
('b', pa.float64()),
('index', pa.int32()),
])
# schema includes index with name not in dataframe
with pytest.raises(KeyError, match="name 'index' present in the"):
pa.... | 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
schema = pa.schema([
('partition', pa.int32()),
('arrays', pa.list_(pa.int32())),
('floats', pa.float64()),
])
columns = ['arrays', 'floats']
with pytest.raises(ValueErro... | 246 | 246 | 821 | 18 | 227 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_from_pandas_schema_index_columns | test_table_from_pandas_schema_index_columns | 2,762 | 2,849 | 2,762 | 2,763 | ed4b0d18542611454982395972fb50870f4d87c0 | bigcode/the-stack | train |
ef8243bf5990ddd47ecd9d36 | train | class | class TestConvertMisc(object):
"""
Miscellaneous conversion tests.
"""
type_pairs = [
(np.int8, pa.int8()),
(np.int16, pa.int16()),
(np.int32, pa.int32()),
(np.int64, pa.int64()),
(np.uint8, pa.uint8()),
(np.uint16, pa.uint16()),
(np.uint32, pa.ui... | class TestConvertMisc(object):
| """
Miscellaneous conversion tests.
"""
type_pairs = [
(np.int8, pa.int8()),
(np.int16, pa.int16()),
(np.int32, pa.int32()),
(np.int64, pa.int64()),
(np.uint8, pa.uint8()),
(np.uint16, pa.uint16()),
(np.uint32, pa.uint32()),
(np.uint64, pa... | def test_zero_copy_failure_with_float_when_nulls(self):
self.check_zero_copy_failure(pa.array([0.0, 1.0, None]))
def test_zero_copy_failure_on_bool_types(self):
self.check_zero_copy_failure(pa.array([True, False]))
def test_zero_copy_failure_on_list_types(self):
arr = pa.array([[1,... | 256 | 256 | 2,333 | 6 | 250 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertMisc | TestConvertMisc | 2,202 | 2,459 | 2,202 | 2,202 | 9f21bed103463434191b3f49f7455586854ccbf3 | bigcode/the-stack | train |
95989a0bad16490113c8d810 | train | class | class TestConvertStringLikeTypes(object):
def test_pandas_unicode(self):
repeats = 1000
values = [u'foo', None, u'bar', u'mañana', np.nan]
df = pd.DataFrame({'strings': values * repeats})
field = pa.field('strings', pa.string())
schema = pa.schema([field])
_check_pa... | class TestConvertStringLikeTypes(object):
| def test_pandas_unicode(self):
repeats = 1000
values = [u'foo', None, u'bar', u'mañana', np.nan]
df = pd.DataFrame({'strings': values * repeats})
field = pa.field('strings', pa.string())
schema = pa.schema([field])
_check_pandas_roundtrip(df, expected_schema=schema)
... | '2007-07-13',
None,
'2006-01-15',
'2010-08-19'],
dtype='datetime64[D]')
_check_array_from_pandas_roundtrip(datetime64_d, type=dtype)
def test_array_from_pandas_date_with_mask(self):
m = np.array([True, False, True])
data = pd.... | 256 | 256 | 2,011 | 8 | 248 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertStringLikeTypes | TestConvertStringLikeTypes | 1,391 | 1,585 | 1,391 | 1,392 | 91ac684566907ca7435a98730103ed1d9a8a0992 | bigcode/the-stack | train |
39f8f2804b156a0ba4068674 | train | function | def test_array_from_py_float32():
data = [[1.2, 3.4], [9.0, 42.0]]
t = pa.float32()
arr1 = pa.array(data[0], type=t)
arr2 = pa.array(data, type=pa.list_(t))
expected1 = np.array(data[0], dtype=np.float32)
expected2 = pd.Series([np.array(data[0], dtype=np.float32),
n... | def test_array_from_py_float32():
| data = [[1.2, 3.4], [9.0, 42.0]]
t = pa.float32()
arr1 = pa.array(data[0], type=t)
arr2 = pa.array(data, type=pa.list_(t))
expected1 = np.array(data[0], dtype=np.float32)
expected2 = pd.Series([np.array(data[0], dtype=np.float32),
np.array(data[1], dtype=np.float32)... | col[0]
refcount = sys.getrefcount(obj)
assert sys.getrefcount(obj) == refcount
del col
assert sys.getrefcount(obj) == refcount - 1
# ----------------------------------------------------------------------
# Some nested array tests array tests
def test_array_from_py_float32():
| 64 | 64 | 139 | 8 | 55 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_array_from_py_float32 | test_array_from_py_float32 | 3,012 | 3,026 | 3,012 | 3,012 | 34402e3cefc8b52c0f82d03566172b5eaef531c9 | bigcode/the-stack | train |
aa8f2954b81e57d6af9a931c | train | function | def test_variable_dictionary_to_pandas():
np.random.seed(12345)
d1 = pa.array(random_strings(100, 32), type='string')
d2 = pa.array(random_strings(100, 16), type='string')
d3 = pa.array(random_strings(10000, 10), type='string')
a1 = pa.DictionaryArray.from_arrays(
np.random.randint(0, len(... | def test_variable_dictionary_to_pandas():
| np.random.seed(12345)
d1 = pa.array(random_strings(100, 32), type='string')
d2 = pa.array(random_strings(100, 16), type='string')
d3 = pa.array(random_strings(10000, 10), type='string')
a1 = pa.DictionaryArray.from_arrays(
np.random.randint(0, len(d1), size=1000, dtype='i4'),
d1
... | tm.assert_series_equal(pd.Series(pandas2), pd.Series(ex_pandas2))
def random_strings(n, item_size, pct_null=0, dictionary=None):
if dictionary is not None:
result = dictionary[np.random.randint(0, len(dictionary), size=n)]
else:
result = np.array([random_ascii(item_size) for i in range(n)],
... | 115 | 115 | 384 | 8 | 106 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_variable_dictionary_to_pandas | test_variable_dictionary_to_pandas | 3,116 | 3,157 | 3,116 | 3,116 | 900b18b2cee736924f01a5b1c9b8d318aac3609e | bigcode/the-stack | train |
4dd3e109e11c2b2a7a07bc39 | train | function | def random_strings(n, item_size, pct_null=0, dictionary=None):
if dictionary is not None:
result = dictionary[np.random.randint(0, len(dictionary), size=n)]
else:
result = np.array([random_ascii(item_size) for i in range(n)],
dtype=object)
if pct_null > 0:
... | def random_strings(n, item_size, pct_null=0, dictionary=None):
| if dictionary is not None:
result = dictionary[np.random.randint(0, len(dictionary), size=n)]
else:
result = np.array([random_ascii(item_size) for i in range(n)],
dtype=object)
if pct_null > 0:
result[np.random.rand(n) < pct_null] = None
return result
| 2.to_pandas()
ex_pandas2 = pd.Categorical.from_codes(np.where(mask, -1, indices),
categories=dictionary)
tm.assert_series_equal(pd.Series(pandas2), pd.Series(ex_pandas2))
def random_strings(n, item_size, pct_null=0, dictionary=None):
| 64 | 64 | 90 | 16 | 48 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | random_strings | random_strings | 3,103 | 3,113 | 3,103 | 3,103 | 29ab14c4eddce252ae5dbe551dcb00cf0a3305c3 | bigcode/the-stack | train |
2f3b76c7067ecb6459acd07a | train | function | def _check_pandas_roundtrip(df, expected=None, use_threads=True,
expected_schema=None,
check_dtype=True, schema=None,
preserve_index=False,
as_batch=False):
klass = pa.RecordBatch if as_batch else pa.Tabl... | def _check_pandas_roundtrip(df, expected=None, use_threads=True,
expected_schema=None,
check_dtype=True, schema=None,
preserve_index=False,
as_batch=False):
| klass = pa.RecordBatch if as_batch else pa.Table
table = klass.from_pandas(df, schema=schema,
preserve_index=preserve_index,
nthreads=2 if use_threads else 1)
result = table.to_pandas(use_threads=use_threads)
if expected_schema:
# all ... | for x in range(size - 2)] + [None],
'empty_str': [''] * size
})
def _check_pandas_roundtrip(df, expected=None, use_threads=True,
expected_schema=None,
check_dtype=True, schema=None,
preserve_index=False,
... | 64 | 64 | 183 | 39 | 25 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _check_pandas_roundtrip | _check_pandas_roundtrip | 78 | 99 | 78 | 82 | 736b9014f7a3c78bbf9c9c4c6e20cc73ab6a05ae | bigcode/the-stack | train |
2e1a1dedb1f21e3b4ba54ec3 | train | function | def test_array_protocol():
if LooseVersion(pd.__version__) < '0.24.0':
pytest.skip('IntegerArray only introduced in 0.24')
df = pd.DataFrame({'a': pd.Series([1, 2, None], dtype='Int64')})
if LooseVersion(pd.__version__) < '0.26.0.dev':
# with pandas<=0.25, trying to convert nullable intege... | def test_array_protocol():
| if LooseVersion(pd.__version__) < '0.24.0':
pytest.skip('IntegerArray only introduced in 0.24')
df = pd.DataFrame({'a': pd.Series([1, 2, None], dtype='Int64')})
if LooseVersion(pd.__version__) < '0.26.0.dev':
# with pandas<=0.25, trying to convert nullable integer errors
with pytes... | ('string'),
a3.cast('string'),
a4.cast('string')])
result = a.to_pandas()
result_dense = a_dense.to_pandas()
assert (result.cat.categories == expected_dict.to_pandas()).all()
expected_dense = result.astype('str')
expected_dense[resul... | 98 | 98 | 329 | 5 | 92 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_array_protocol | test_array_protocol | 3,164 | 3,198 | 3,164 | 3,164 | 2f6ee0ed6b8f2fc5c883c711c035183fbd1e9367 | bigcode/the-stack | train |
2e47b43e594ca1805f4f7064 | train | function | def test_object_leak_in_numpy_array():
# ARROW-6876
arr = pa.array([{'a': 1}])
np_arr = arr.to_pandas()
assert np_arr.dtype == np.dtype('object')
obj = np_arr[0]
refcount = sys.getrefcount(obj)
assert sys.getrefcount(obj) == refcount
del np_arr
assert sys.getrefcount(obj) == refcount... | def test_object_leak_in_numpy_array():
# ARROW-6876
| arr = pa.array([{'a': 1}])
np_arr = arr.to_pandas()
assert np_arr.dtype == np.dtype('object')
obj = np_arr[0]
refcount = sys.getrefcount(obj)
assert sys.getrefcount(obj) == refcount
del np_arr
assert sys.getrefcount(obj) == refcount - 1
| _allocated_bytes() == (prior_allocation + N * 8)
# Check successful garbage collection
x = None # noqa
gc.collect()
assert pa.total_allocated_bytes() == prior_allocation
def test_object_leak_in_numpy_array():
# ARROW-6876
| 64 | 64 | 100 | 17 | 46 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_object_leak_in_numpy_array | test_object_leak_in_numpy_array | 2,983 | 2,992 | 2,983 | 2,984 | 705eb54d2bc968ef076910c605bf030efef9d671 | bigcode/the-stack | train |
87c4e797554e016c91e3f403 | train | class | class TestConvertListTypes(object):
"""
Conversion tests for list<> types.
"""
def test_column_of_arrays(self):
df, schema = dataframe_with_arrays()
_check_pandas_roundtrip(df, schema=schema, expected_schema=schema)
table = pa.Table.from_pandas(df, schema=schema, preserve_index=... | class TestConvertListTypes(object):
| """
Conversion tests for list<> types.
"""
def test_column_of_arrays(self):
df, schema = dataframe_with_arrays()
_check_pandas_roundtrip(df, schema=schema, expected_schema=schema)
table = pa.Table.from_pandas(df, schema=schema, preserve_index=False)
# schema's metadata ... | 5))
expected = [decimal.Decimal('0.01000'), decimal.Decimal('0.00100')]
assert array.to_pylist() == expected
def test_decimal_with_None_explicit_type(self):
series = pd.Series([decimal.Decimal('3.14'), None])
_check_series_roundtrip(series, type_=pa.decimal128(12, 5))
# Te... | 256 | 256 | 2,409 | 7 | 249 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertListTypes | TestConvertListTypes | 1,679 | 1,962 | 1,679 | 1,679 | 12a5c8b14c49b0dd53a00e45e73f8d4c477b30a5 | bigcode/the-stack | train |
a50680f484f9adbc3bfb28cd | train | function | def test_array_uses_memory_pool():
# ARROW-6570
N = 10000
arr = pa.array(np.arange(N, dtype=np.int64),
mask=np.random.randint(0, 2, size=N).astype(np.bool_))
# In the case the gc is caught loafing
gc.collect()
prior_allocation = pa.total_allocated_bytes()
x = arr.to_pan... | def test_array_uses_memory_pool():
# ARROW-6570
| N = 10000
arr = pa.array(np.arange(N, dtype=np.int64),
mask=np.random.randint(0, 2, size=N).astype(np.bool_))
# In the case the gc is caught loafing
gc.collect()
prior_allocation = pa.total_allocated_bytes()
x = arr.to_pandas()
assert pa.total_allocated_bytes() == (prio... | 'time'),
(pa.time64('us'), 'time')
]
)
def test_logical_type(type, expected):
assert get_logical_type(type) == expected
# ----------------------------------------------------------------------
# to_pandas uses MemoryPool
def test_array_uses_memory_pool():
# ARROW-6570
| 64 | 64 | 194 | 16 | 47 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_array_uses_memory_pool | test_array_uses_memory_pool | 2,941 | 2,964 | 2,941 | 2,942 | 978553ba85456be15b9a7fccc1eeaa5a99038f18 | bigcode/the-stack | train |
4f4e2c1e4680d4f97f4ffd4a | train | class | class TestConvertDecimalTypes(object):
"""
Conversion test for decimal types.
"""
decimal32 = [
decimal.Decimal('-1234.123'),
decimal.Decimal('1234.439')
]
decimal64 = [
decimal.Decimal('-129934.123331'),
decimal.Decimal('129534.123731')
]
decimal128 = [
... | class TestConvertDecimalTypes(object):
| """
Conversion test for decimal types.
"""
decimal32 = [
decimal.Decimal('-1234.123'),
decimal.Decimal('1234.439')
]
decimal64 = [
decimal.Decimal('-129934.123331'),
decimal.Decimal('129534.123731')
]
decimal128 = [
decimal.Decimal('394092382910493... | ', b'baz'], dtype='|S3')
converted = pa.array(arr, type=pa.binary(3))
expected = pa.array(list(arr), type=pa.binary(3))
assert converted.equals(expected)
mask = np.array([True, False, True])
converted = pa.array(arr, type=pa.binary(3), mask=mask)
expected = pa.array([b'... | 242 | 242 | 809 | 7 | 235 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertDecimalTypes | TestConvertDecimalTypes | 1,588 | 1,676 | 1,588 | 1,588 | 5a9e84e57a5a753a257152b3fb8bcd24c5fd26ee | bigcode/the-stack | train |
f1120c0fb479b1f13270af24 | train | function | def test_table_from_pandas_keeps_column_order_of_schema():
# ARROW-3766
df = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
schema = pa.schema([
('floats', pa.float64()),
... | def test_table_from_pandas_keeps_column_order_of_schema():
# ARROW-3766
| df = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
schema = pa.schema([
('floats', pa.float64()),
('arrays', pa.list_(pa.int32())),
('partition', pa.int32())
])
... | , preserve_index=False)
table2 = pa.Table.from_pandas(df2, preserve_index=False)
assert table1.schema.equals(schema1, check_metadata=False)
assert table2.schema.equals(schema2, check_metadata=False)
def test_table_from_pandas_keeps_column_order_of_schema():
# ARROW-3766
| 68 | 68 | 228 | 21 | 47 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_from_pandas_keeps_column_order_of_schema | test_table_from_pandas_keeps_column_order_of_schema | 2,680 | 2,701 | 2,680 | 2,681 | 5073ba8bf9f52514b28fe8e13c397575b4538366 | bigcode/the-stack | train |
6837776cbe677094a9b6ff06 | train | function | def test_metadata_compat_range_index_pre_0_12():
# Forward compatibility for metadata created from pandas.RangeIndex
# prior to pyarrow 0.13.0
a_values = [u'foo', u'bar', None, u'baz']
b_values = [u'a', u'a', u'b', u'b']
a_arrow = pa.array(a_values, type='utf8')
b_arrow = pa.array(b_values, type... | def test_metadata_compat_range_index_pre_0_12():
# Forward compatibility for metadata created from pandas.RangeIndex
# prior to pyarrow 0.13.0
| a_values = [u'foo', u'bar', None, u'baz']
b_values = [u'a', u'a', u'b', u'b']
a_arrow = pa.array(a_values, type='utf8')
b_arrow = pa.array(b_values, type='utf8')
rng_index_arrow = pa.array([0, 2, 4, 6], type='int64')
gen_name_0 = '__index_level_0__'
gen_name_1 = '__index_level_1__'
# ... | 0.26.0.dev
# default conversion
result = pa.table(df)
expected = pa.array([1, 2, None], pa.int64())
assert result[0].chunk(0).equals(expected)
# with specifying schema
schema = pa.schema([('a', pa.float64())])
result = pa.table(df, schema=schema)
expect... | 256 | 256 | 1,608 | 38 | 217 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_metadata_compat_range_index_pre_0_12 | test_metadata_compat_range_index_pre_0_12 | 3,205 | 3,371 | 3,205 | 3,207 | 226b89b573580f6b295b10faa06c19f0f32b3eb9 | bigcode/the-stack | train |
4252ebaa4fa53a996ebe2f13 | train | function | def test_dictionary_with_pandas():
indices = np.repeat([0, 1, 2], 2)
dictionary = np.array(['foo', 'bar', 'baz'], dtype=object)
mask = np.array([False, False, True, False, False, False])
d1 = pa.DictionaryArray.from_arrays(indices, dictionary)
d2 = pa.DictionaryArray.from_arrays(indices, dictionary... | def test_dictionary_with_pandas():
| indices = np.repeat([0, 1, 2], 2)
dictionary = np.array(['foo', 'bar', 'baz'], dtype=object)
mask = np.array([False, False, True, False, False, False])
d1 = pa.DictionaryArray.from_arrays(indices, dictionary)
d2 = pa.DictionaryArray.from_arrays(indices, dictionary, mask=mask)
pandas1 = d1.to_p... | result = pa.Array.from_pandas(series, type=pa.timestamp('us'), safe=False)
assert result.equals(expected)
result = pa.array(series, type=pa.timestamp('us'), safe=False)
assert result.equals(expected)
# ----------------------------------------------------------------------
# DictionaryArray tests
def ... | 64 | 64 | 188 | 7 | 56 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_dictionary_with_pandas | test_dictionary_with_pandas | 3,083 | 3,100 | 3,083 | 3,083 | ea2f828031bc979ccbc621ab46000b639fb75d11 | bigcode/the-stack | train |
fd429c64c7151be5f9c68435 | train | function | def _non_threaded_conversion():
df = _alltypes_example()
_check_pandas_roundtrip(df, use_threads=False)
_check_pandas_roundtrip(df, use_threads=False, as_batch=True)
| def _non_threaded_conversion():
| df = _alltypes_example()
_check_pandas_roundtrip(df, use_threads=False)
_check_pandas_roundtrip(df, use_threads=False, as_batch=True)
| test_zero_copy_failure_on_timestamp_types(self):
arr = np.array(['2007-07-13'], dtype='datetime64[ns]')
self.check_zero_copy_failure(pa.array(arr))
# This function must be at the top-level for Python 2.7's multiprocessing
def _non_threaded_conversion():
| 64 | 64 | 45 | 7 | 56 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _non_threaded_conversion | _non_threaded_conversion | 2,190 | 2,193 | 2,190 | 2,190 | 596fafcf2a3403bc04d39e654acdbdbe90b93158 | bigcode/the-stack | train |
a5317f1ed47ca7415808f23f | train | function | def test_table_from_pandas_checks_field_nullability():
# ARROW-2136
df = pd.DataFrame({'a': [1.2, 2.1, 3.1],
'b': [np.nan, 'string', 'foo']})
schema = pa.schema([pa.field('a', pa.float64(), nullable=False),
pa.field('b', pa.utf8(), nullable=False)])
with p... | def test_table_from_pandas_checks_field_nullability():
# ARROW-2136
| df = pd.DataFrame({'a': [1.2, 2.1, 3.1],
'b': [np.nan, 'string', 'foo']})
schema = pa.schema([pa.field('a', pa.float64(), nullable=False),
pa.field('b', pa.utf8(), nullable=False)])
with pytest.raises(ValueError):
pa.Table.from_pandas(df, schema=schema... | _arr.to_pandas(**pandas_options),
nunique)
_assert_nunique(casted_arr.to_pandas(deduplicate_objects=False,
**pandas_options),
len(casted_arr))
# ---------------------------------------------------------------------
de... | 64 | 64 | 109 | 19 | 45 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_from_pandas_checks_field_nullability | test_table_from_pandas_checks_field_nullability | 2,643 | 2,651 | 2,643 | 2,644 | 5968e14f720b7fe41f61ebbcbd44d68e6df29fea | bigcode/the-stack | train |
d86da5eeb528dbdcd4e12631 | train | function | @pytest.mark.parametrize('columns', ([b'foo'], ['foo']))
def test_roundtrip_with_bytes_unicode(columns):
df = pd.DataFrame(columns=columns)
table1 = pa.Table.from_pandas(df)
table2 = pa.Table.from_pandas(table1.to_pandas())
assert table1.equals(table2)
assert table1.schema.equals(table2.schema)
... | @pytest.mark.parametrize('columns', ([b'foo'], ['foo']))
def test_roundtrip_with_bytes_unicode(columns):
| df = pd.DataFrame(columns=columns)
table1 = pa.Table.from_pandas(df)
table2 = pa.Table.from_pandas(table1.to_pandas())
assert table1.equals(table2)
assert table1.schema.equals(table2.schema)
assert table1.schema.metadata == table2.schema.metadata
| IntervalIndex in pandas 0.20.x
data[10] = pd.interval_range(start=1, freq=1, periods=10)
return pd.DataFrame(data, index=index)
@pytest.mark.parametrize('columns', ([b'foo'], ['foo']))
def test_roundtrip_with_bytes_unicode(columns):
| 64 | 64 | 89 | 23 | 41 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_roundtrip_with_bytes_unicode | test_roundtrip_with_bytes_unicode | 2,498 | 2,505 | 2,498 | 2,499 | ba8ae8cf161e37fc56c6474ca6355b08dca6fa5f | bigcode/the-stack | train |
fc118118d050a4a85954aa89 | train | function | def test_table_from_pandas_columns_and_schema_are_mutually_exclusive():
df = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
schema = pa.schema([
('partition', pa.int32()),
('a... | def test_table_from_pandas_columns_and_schema_are_mutually_exclusive():
| df = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
schema = pa.schema([
('partition', pa.int32()),
('arrays', pa.list_(pa.int32())),
('floats', pa.float64()),
])
... | _index=False)
table2 = pa.Table.from_pandas(df, columns=columns2, preserve_index=False)
assert table1.schema.equals(schema1, check_metadata=False)
assert table2.schema.equals(schema2, check_metadata=False)
def test_table_from_pandas_columns_and_schema_are_mutually_exclusive():
| 64 | 64 | 156 | 15 | 49 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_from_pandas_columns_and_schema_are_mutually_exclusive | test_table_from_pandas_columns_and_schema_are_mutually_exclusive | 2,731 | 2,745 | 2,731 | 2,731 | 0e5e85e4b41f55713b6a750f42c079cb7e9f835f | bigcode/the-stack | train |
2c775cb1256880c0e58f64a6 | train | function | def _check_series_roundtrip(s, type_=None, expected_pa_type=None):
arr = pa.array(s, from_pandas=True, type=type_)
if type_ is not None and expected_pa_type is None:
expected_pa_type = type_
if expected_pa_type is not None:
assert arr.type == expected_pa_type
result = pd.Series(arr.to... | def _check_series_roundtrip(s, type_=None, expected_pa_type=None):
| arr = pa.array(s, from_pandas=True, type=type_)
if type_ is not None and expected_pa_type is None:
expected_pa_type = type_
if expected_pa_type is not None:
assert arr.type == expected_pa_type
result = pd.Series(arr.to_pandas(), name=s.name)
tm.assert_series_equal(s, result)
| , check_metadata=False)
if expected is None:
expected = df
tm.assert_frame_equal(result, expected, check_dtype=check_dtype,
check_index_type=('equiv' if preserve_index
else False))
def _check_series_roundtrip(s, type_=None, expected... | 64 | 64 | 96 | 17 | 47 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _check_series_roundtrip | _check_series_roundtrip | 102 | 112 | 102 | 102 | bfca717f1aa5b7f0551b8b77489f2537b02844a5 | bigcode/the-stack | train |
ad495b8f0185a54a935d2bb3 | train | function | def test_to_pandas_deduplicate_date_time():
nunique = 100
repeats = 10
unique_values = list(range(nunique))
cases = [
# raw type, array type, to_pandas options
('int32', 'date32', {'date_as_object': True}),
('int64', 'date64', {'date_as_object': True}),
('int32', 'time3... | def test_to_pandas_deduplicate_date_time():
| nunique = 100
repeats = 10
unique_values = list(range(nunique))
cases = [
# raw type, array type, to_pandas options
('int32', 'date32', {'date_as_object': True}),
('int64', 'date64', {'date_as_object': True}),
('int32', 'time32[ms]', {}),
('int64', 'time64[us]',... | .to_pandas(integer_object_nulls=True), nunique)
_assert_nunique(arr.to_pandas(integer_object_nulls=True,
deduplicate_objects=False),
# Account for None
(nunique - 1) * repeats + 1)
def test_to_pandas_deduplicate_date_time():
| 64 | 64 | 197 | 11 | 53 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_to_pandas_deduplicate_date_time | test_to_pandas_deduplicate_date_time | 2,616 | 2,638 | 2,616 | 2,616 | 033c3d1e715932ff725f015a29e86d080956470e | bigcode/the-stack | train |
f64dc367abae402a3041c87d | train | function | def test_table_from_pandas_keeps_schema_nullability():
# ARROW-5169
df = pd.DataFrame({'a': [1, 2, 3, 4]})
schema = pa.schema([
pa.field('a', pa.int64(), nullable=False),
])
table = pa.Table.from_pandas(df)
assert table.schema.field('a').nullable is True
table = pa.Table.from_panda... | def test_table_from_pandas_keeps_schema_nullability():
# ARROW-5169
| df = pd.DataFrame({'a': [1, 2, 3, 4]})
schema = pa.schema([
pa.field('a', pa.int64(), nullable=False),
])
table = pa.Table.from_pandas(df)
assert table.schema.field('a').nullable is True
table = pa.Table.from_pandas(df, schema=schema)
assert table.schema.field('a').nullable is Fals... | ('floats', pa.float64()),
])
columns = ['arrays', 'floats']
with pytest.raises(ValueError):
pa.Table.from_pandas(df, schema=schema, columns=columns)
def test_table_from_pandas_keeps_schema_nullability():
# ARROW-5169
| 64 | 64 | 111 | 20 | 44 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_from_pandas_keeps_schema_nullability | test_table_from_pandas_keeps_schema_nullability | 2,748 | 2,759 | 2,748 | 2,749 | 45975c5735e09085a157394d5770d160288eca49 | bigcode/the-stack | train |
c1bdad8524b3aab45def9d09 | train | class | class TestConvertDateTimeLikeTypes(object):
"""
Conversion tests for datetime- and timestamp-like types (date64, etc.).
"""
def test_timestamps_notimezone_no_nulls(self):
df = pd.DataFrame({
'datetime64': np.array([
'2007-07-13T01:23:34.123456789',
'2... | class TestConvertDateTimeLikeTypes(object):
| """
Conversion tests for datetime- and timestamp-like types (date64, etc.).
"""
def test_timestamps_notimezone_no_nulls(self):
df = pd.DataFrame({
'datetime64': np.array([
'2007-07-13T01:23:34.123456789',
'2006-01-13T12:34:56.432539784',
... | = pa.array(values, mask=null_mask)
if null_mask.any():
expected = values.astype('O')
expected[null_mask] = None
else:
expected = values
result = array.to_pandas(integer_object_nulls=True)
np.testing.assert_equal(result, expected)
@pytest.mark.parametrize('dtype',
... | 256 | 256 | 4,540 | 9 | 247 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertDateTimeLikeTypes | TestConvertDateTimeLikeTypes | 907 | 1,385 | 907 | 907 | 946fd1997b1c89f25ecd239b9691a01c25070546 | bigcode/the-stack | train |
75dfd6e23675d7fb9a57fc0e | train | function | def _pytime_from_micros(val):
microseconds = val % 1000000
val //= 1000000
seconds = val % 60
val //= 60
minutes = val % 60
hours = val // 60
return time(hours, minutes, seconds, microseconds)
| def _pytime_from_micros(val):
| microseconds = val % 1000000
val //= 1000000
seconds = val % 60
val //= 60
minutes = val % 60
hours = val // 60
return time(hours, minutes, seconds, microseconds)
| 45 is resolved')
def test_serialize_deserialize_pandas():
# ARROW-1784, serialize and deserialize DataFrame by decomposing
# BlockManager
df = _fully_loaded_dataframe_example()
_check_serialize_components_roundtrip(df)
def _pytime_from_micros(val):
| 64 | 64 | 73 | 10 | 54 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _pytime_from_micros | _pytime_from_micros | 2,526 | 2,533 | 2,526 | 2,526 | 47425dfab8fc91691f226e1428bbfcf0b7fd567b | bigcode/the-stack | train |
dbac999b6e85c91c96d9ba44 | train | class | class TestConvertPrimitiveTypes(object):
"""
Conversion tests for primitive (e.g. numeric) types.
"""
def test_float_no_nulls(self):
data = {}
fields = []
dtypes = [('f2', pa.float16()),
('f4', pa.float32()),
('f8', pa.float64())]
num_... | class TestConvertPrimitiveTypes(object):
| """
Conversion tests for primitive (e.g. numeric) types.
"""
def test_float_no_nulls(self):
data = {}
fields = []
dtypes = [('f2', pa.float16()),
('f4', pa.float32()),
('f8', pa.float64())]
num_values = 100
for numpy_dtype, ar... | df = tbl.to_pandas()
tbl2 = pa.Table.from_pandas(df)
md2 = tbl2.schema.pandas_metadata
# Second roundtrip
df2 = tbl2.to_pandas()
expected = pd.DataFrame(OrderedDict([('c1', c1), ('c2', c2)]))
tm.assert_frame_equal(df2, expected)
assert md2['columns'] == [
... | 256 | 256 | 2,712 | 7 | 248 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | TestConvertPrimitiveTypes | TestConvertPrimitiveTypes | 569 | 859 | 569 | 569 | 3711a20eb9eef06bbb555a747bc390a49ead7c58 | bigcode/the-stack | train |
53f9997dea88591a13adf191 | train | function | def test_cast_timestamp_unit():
# ARROW-1680
val = datetime.now()
s = pd.Series([val])
s_nyc = s.dt.tz_localize('tzlocal()').dt.tz_convert('America/New_York')
us_with_tz = pa.timestamp('us', tz='America/New_York')
arr = pa.Array.from_pandas(s_nyc, type=us_with_tz)
# ARROW-1906
assert ... | def test_cast_timestamp_unit():
# ARROW-1680
| val = datetime.now()
s = pd.Series([val])
s_nyc = s.dt.tz_localize('tzlocal()').dt.tz_convert('America/New_York')
us_with_tz = pa.timestamp('us', tz='America/New_York')
arr = pa.Array.from_pandas(s_nyc, type=us_with_tz)
# ARROW-1906
assert arr.type == us_with_tz
arr2 = pa.Array.from_... | .array(data[0], type=t)
arr2 = pa.array(data, type=pa.list_(t))
expected1 = np.array(data[0], dtype=np.float32)
expected2 = pd.Series([np.array(data[0], dtype=np.float32),
np.array(data[1], dtype=np.float32)])
assert arr1.type == t
assert arr1.equals(pa.array(expected1))... | 117 | 117 | 391 | 14 | 102 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_cast_timestamp_unit | test_cast_timestamp_unit | 3,033 | 3,076 | 3,033 | 3,034 | 59db28a4bbc3c3c3e1498e667fe10586c27a99ca | bigcode/the-stack | train |
78c520f1bdc5ba7a5f800ad5 | train | function | def _pytime_to_micros(pytime):
return (pytime.hour * 3600000000 +
pytime.minute * 60000000 +
pytime.second * 1000000 +
pytime.microsecond)
| def _pytime_to_micros(pytime):
| return (pytime.hour * 3600000000 +
pytime.minute * 60000000 +
pytime.second * 1000000 +
pytime.microsecond)
|
val //= 1000000
seconds = val % 60
val //= 60
minutes = val % 60
hours = val // 60
return time(hours, minutes, seconds, microseconds)
def _pytime_to_micros(pytime):
| 64 | 64 | 50 | 11 | 53 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _pytime_to_micros | _pytime_to_micros | 2,536 | 2,540 | 2,536 | 2,536 | 397570d1a9cd6b091cdf38002ec0fe699fe9a5ab | bigcode/the-stack | train |
2e366341e537832b5056f7d2 | train | function | def test_table_uses_memory_pool():
N = 10000
arr = pa.array(np.arange(N, dtype=np.int64))
t = pa.table([arr], ['f0'])
prior_allocation = pa.total_allocated_bytes()
x = t.to_pandas()
assert pa.total_allocated_bytes() == (prior_allocation + N * 8)
# Check successful garbage collection
x... | def test_table_uses_memory_pool():
| N = 10000
arr = pa.array(np.arange(N, dtype=np.int64))
t = pa.table([arr], ['f0'])
prior_allocation = pa.total_allocated_bytes()
x = t.to_pandas()
assert pa.total_allocated_bytes() == (prior_allocation + N * 8)
# Check successful garbage collection
x = None # noqa
gc.collect()
... | copy does not allocate memory
arr = pa.array(np.arange(N, dtype=np.int64))
prior_allocation = pa.total_allocated_bytes()
x = arr.to_pandas() # noqa
assert pa.total_allocated_bytes() == prior_allocation
def test_table_uses_memory_pool():
| 64 | 64 | 111 | 8 | 55 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_uses_memory_pool | test_table_uses_memory_pool | 2,967 | 2,980 | 2,967 | 2,967 | 706d3f1d107ecb31e1d36ddb7d19f316a6e0b6ef | bigcode/the-stack | train |
8c5784c62698fa60599954f9 | train | function | def test_safe_cast_from_float_with_nans_to_int():
# TODO(kszucs): write tests for creating Date32 and Date64 arrays, see
# ARROW-4258 and https://github.com/apache/arrow/pull/3395
values = pd.Series([1, 2, None, 4])
arr = pa.Array.from_pandas(values, type=pa.int32(), safe=True)
expecte... | def test_safe_cast_from_float_with_nans_to_int():
# TODO(kszucs): write tests for creating Date32 and Date64 arrays, see
# ARROW-4258 and https://github.com/apache/arrow/pull/3395
| values = pd.Series([1, 2, None, 4])
arr = pa.Array.from_pandas(values, type=pa.int32(), safe=True)
expected = pa.array([1, 2, None, 4], type=pa.int32())
assert arr.equals(expected)
| "):
pa.Table.from_pandas(df)
def test_safe_cast_from_float_with_nans_to_int():
# TODO(kszucs): write tests for creating Date32 and Date64 arrays, see
# ARROW-4258 and https://github.com/apache/arrow/pull/3395
| 64 | 64 | 118 | 55 | 9 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_safe_cast_from_float_with_nans_to_int | test_safe_cast_from_float_with_nans_to_int | 2,462 | 2,468 | 2,462 | 2,464 | 9c6ea7150d1c5e79e550f893b5d1bc4f2628ae87 | bigcode/the-stack | train |
8f7664f7b124cdbcc441334c | train | function | def test_table_from_pandas_columns_argument_only_does_filtering():
df = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
columns1 = ['arrays', 'floats', 'partition']
schema1 = pa.schema([
... | def test_table_from_pandas_columns_argument_only_does_filtering():
| df = pd.DataFrame(OrderedDict([
('partition', [0, 0, 1, 1]),
('arrays', [[0, 1, 2], [3, 4], None, None]),
('floats', [None, None, 1.1, 3.3])
]))
columns1 = ['arrays', 'floats', 'partition']
schema1 = pa.schema([
('arrays', pa.list_(pa.int64())),
('floats', pa.flo... | andas(df1, schema=schema, preserve_index=False)
table2 = pa.Table.from_pandas(df2, schema=schema, preserve_index=False)
assert table1.schema.equals(schema, check_metadata=False)
assert table1.schema.equals(table2.schema, check_metadata=False)
def test_table_from_pandas_columns_argument_only_does_filtering(... | 72 | 72 | 240 | 14 | 58 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_table_from_pandas_columns_argument_only_does_filtering | test_table_from_pandas_columns_argument_only_does_filtering | 2,704 | 2,728 | 2,704 | 2,704 | 45b51868e809efb6aa29da0f8dcd4c6e01f6f858 | bigcode/the-stack | train |
7f10c564701a3163c8be30a4 | train | function | def test_to_pandas_deduplicate_strings_table_types():
nunique = 100
repeats = 10
values = _generate_dedup_example(nunique, repeats)
arr = pa.array(values)
rb = pa.RecordBatch.from_arrays([arr], ['foo'])
tbl = pa.Table.from_batches([rb])
for obj in [rb, tbl]:
_assert_nunique(obj.to_... | def test_to_pandas_deduplicate_strings_table_types():
| nunique = 100
repeats = 10
values = _generate_dedup_example(nunique, repeats)
arr = pa.array(values)
rb = pa.RecordBatch.from_arrays([arr], ['foo'])
tbl = pa.Table.from_batches([rb])
for obj in [rb, tbl]:
_assert_nunique(obj.to_pandas()['foo'], nunique)
_assert_nunique(obj.... | .array(values, type=pa.utf8()),
pa.chunked_array([values, values])]:
_assert_nunique(arr.to_pandas(), nunique)
_assert_nunique(arr.to_pandas(deduplicate_objects=False), len(arr))
def test_to_pandas_deduplicate_strings_table_types():
| 64 | 64 | 115 | 12 | 52 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_to_pandas_deduplicate_strings_table_types | test_to_pandas_deduplicate_strings_table_types | 2,584 | 2,596 | 2,584 | 2,584 | 66ef51b2670accc110bfe15a151b86e4c502fb42 | bigcode/the-stack | train |
e0c9c50ae4517e445addb42d | train | function | def _alltypes_example(size=100):
return pd.DataFrame({
'uint8': np.arange(size, dtype=np.uint8),
'uint16': np.arange(size, dtype=np.uint16),
'uint32': np.arange(size, dtype=np.uint32),
'uint64': np.arange(size, dtype=np.uint64),
'int8': np.arange(size, dtype=np.int16),
... | def _alltypes_example(size=100):
| return pd.DataFrame({
'uint8': np.arange(size, dtype=np.uint8),
'uint16': np.arange(size, dtype=np.uint16),
'uint32': np.arange(size, dtype=np.uint32),
'uint64': np.arange(size, dtype=np.uint64),
'int8': np.arange(size, dtype=np.int16),
'int16': np.arange(size, dtype=... | pandas_api
from pyarrow.tests.util import random_ascii
import pyarrow as pa
try:
import pandas as pd
import pandas.util.testing as tm
from .pandas_examples import dataframe_with_arrays, dataframe_with_lists
except ImportError:
pass
# Marks all of the tests in this module
pytestmark = pytest.mark.pan... | 84 | 84 | 280 | 9 | 74 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _alltypes_example | _alltypes_example | 55 | 75 | 55 | 55 | 0cfaf5a39049ba5460c22ae993e49987c049b98e | bigcode/the-stack | train |
93b62a23c749ac102b0b913f | train | function | def _fully_loaded_dataframe_example():
index = pd.MultiIndex.from_arrays([
pd.date_range('2000-01-01', periods=5).repeat(2),
np.tile(np.array(['foo', 'bar'], dtype=object), 5)
])
c1 = pd.date_range('2000-01-01', periods=10)
data = {
0: c1,
1: c1.tz_localize('utc'),
... | def _fully_loaded_dataframe_example():
| index = pd.MultiIndex.from_arrays([
pd.date_range('2000-01-01', periods=5).repeat(2),
np.tile(np.array(['foo', 'bar'], dtype=object), 5)
])
c1 = pd.date_range('2000-01-01', periods=10)
data = {
0: c1,
1: c1.tz_localize('utc'),
2: c1.tz_localize('US/Eastern'),
... | ARROW-4258 and https://github.com/apache/arrow/pull/3395
values = pd.Series([1, 2, None, 4])
arr = pa.Array.from_pandas(values, type=pa.int32(), safe=True)
expected = pa.array([1, 2, None, 4], type=pa.int32())
assert arr.equals(expected)
def _fully_loaded_dataframe_example():
| 89 | 89 | 299 | 7 | 82 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | _fully_loaded_dataframe_example | _fully_loaded_dataframe_example | 2,471 | 2,495 | 2,471 | 2,471 | ebb6a4111b8cbaaa1c603befface84fb32fb1c7c | bigcode/the-stack | train |
f155bcc366397bd7718ff313 | train | function | def test_to_pandas_deduplicate_integers_as_objects():
nunique = 100
repeats = 10
# Python automatically interns smaller integers
unique_values = list(np.random.randint(10000000, 1000000000, size=nunique))
unique_values[nunique // 2] = None
arr = pa.array(unique_values * repeats)
_assert_n... | def test_to_pandas_deduplicate_integers_as_objects():
| nunique = 100
repeats = 10
# Python automatically interns smaller integers
unique_values = list(np.random.randint(10000000, 1000000000, size=nunique))
unique_values[nunique // 2] = None
arr = pa.array(unique_values * repeats)
_assert_nunique(arr.to_pandas(integer_object_nulls=True), nuniq... | .from_batches([rb])
for obj in [rb, tbl]:
_assert_nunique(obj.to_pandas()['foo'], nunique)
_assert_nunique(obj.to_pandas(deduplicate_objects=False)['foo'],
len(obj))
def test_to_pandas_deduplicate_integers_as_objects():
| 64 | 64 | 139 | 14 | 50 | csjasonchan357/calotrack-1050-final | calotrack_venv/lib/python3.7/site-packages/pyarrow/tests/test_pandas.py | Python | test_to_pandas_deduplicate_integers_as_objects | test_to_pandas_deduplicate_integers_as_objects | 2,599 | 2,613 | 2,599 | 2,599 | 63194a9f5bb9f357fabfe2692103b0a41f706cd2 | bigcode/the-stack | train |
ea2bf9d92936d806b79decf4 | train | class | class BaseResult(HasTraits):
analysis = Instance("pychron.processing.analyses.analysis.Analysis")
isotope = Str
@property
def record_id(self):
r = ""
if self.analysis:
r = self.analysis.record_id
return r
@property
def identifier(self):
r = ""
... | class BaseResult(HasTraits):
| analysis = Instance("pychron.processing.analyses.analysis.Analysis")
isotope = Str
@property
def record_id(self):
r = ""
if self.analysis:
r = self.analysis.record_id
return r
@property
def identifier(self):
r = ""
if self.analysis:
... | License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
from traits.api... | 64 | 64 | 118 | 7 | 56 | ASUPychron/pychron | pychron/pipeline/results/base.py | Python | BaseResult | BaseResult | 19 | 42 | 19 | 19 | af6cfdc9a99b075ef735d0a0e9bd8f95b1529d32 | bigcode/the-stack | train |
df775835093f1f6cabaf66dc | train | function | def init_dist_slurm(tcp_port, local_rank, backend='nccl'):
"""
modified from https://github.com/open-mmlab/mmdetection
Args:
tcp_port:
backend:
Returns:
"""
proc_id = int(os.environ['SLURM_PROCID'])
ntasks = int(os.environ['SLURM_NTASKS'])
node_list = os.environ['SLURM_... | def init_dist_slurm(tcp_port, local_rank, backend='nccl'):
| """
modified from https://github.com/open-mmlab/mmdetection
Args:
tcp_port:
backend:
Returns:
"""
proc_id = int(os.environ['SLURM_PROCID'])
ntasks = int(os.environ['SLURM_NTASKS'])
node_list = os.environ['SLURM_NODELIST']
num_gpus = torch.cuda.device_count()
tor... | def keep_arrays_by_name(gt_names, used_classes):
inds = [i for i, x in enumerate(gt_names) if x in used_classes]
inds = np.array(inds, dtype=np.int64)
return inds
def init_dist_slurm(tcp_port, local_rank, backend='nccl'):
| 65 | 65 | 217 | 17 | 47 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | init_dist_slurm | init_dist_slurm | 144 | 168 | 144 | 144 | 8ffbc3eac479851fb413d748e902df861a78106a | bigcode/the-stack | train |
f262017ed78204ccb5b4f143 | train | function | def get_dist_info(return_gpu_per_machine=False):
if torch.__version__ < '1.0':
initialized = dist._initialized
else:
if dist.is_available():
initialized = dist.is_initialized()
else:
initialized = False
if initialized:
rank = dist.get_rank()
wo... | def get_dist_info(return_gpu_per_machine=False):
| if torch.__version__ < '1.0':
initialized = dist._initialized
else:
if dist.is_available():
initialized = dist.is_initialized()
else:
initialized = False
if initialized:
rank = dist.get_rank()
world_size = dist.get_world_size()
else:
... | ,
# init_method='tcp://127.0.0.1:%d' % tcp_port,
# rank=local_rank,
# world_size=num_gpus
)
rank = dist.get_rank()
return num_gpus, rank
def get_dist_info(return_gpu_per_machine=False):
| 64 | 64 | 124 | 10 | 53 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | get_dist_info | get_dist_info | 189 | 208 | 189 | 189 | 534797d40fc19fee5881346ccd3488563b636cf5 | bigcode/the-stack | train |
4e4f603c5594d1fc0818ebaf | train | function | def rotate_points_along_z(points, angle):
"""
Args:
points: (B, N, 3 + C)
angle: (B), angle along z-axis, angle increases x ==> y
Returns:
"""
points, is_numpy = check_numpy_to_torch(points)
angle, _ = check_numpy_to_torch(angle)
cosa = torch.cos(angle)
sina = torch.sin... | def rotate_points_along_z(points, angle):
| """
Args:
points: (B, N, 3 + C)
angle: (B), angle along z-axis, angle increases x ==> y
Returns:
"""
points, is_numpy = check_numpy_to_torch(points)
angle, _ = check_numpy_to_torch(angle)
cosa = torch.cos(angle)
sina = torch.sin(angle)
zeros = angle.new_zeros(points... | (info, name):
ret_info = {}
keep_indices = [i for i, x in enumerate(info['name']) if x != name]
for key in info.keys():
ret_info[key] = info[key][keep_indices]
return ret_info
def rotate_points_along_z(points, angle):
| 64 | 64 | 214 | 10 | 53 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | rotate_points_along_z | rotate_points_along_z | 35 | 57 | 35 | 35 | 2bb3c7687cdd1e67ea9051fc3e221db3c72738ad | bigcode/the-stack | train |
c91ab086e8e4489d5ab67377 | train | class | class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val... | class AverageMeter(object):
| """Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n... | (indices, point_indices, output_shape)
return v2pinds_tensor
def sa_create(name, var):
x = SharedArray.create(name, var.shape, dtype=var.dtype)
x[...] = var[...]
x.flags.writeable = False
return x
class AverageMeter(object):
| 64 | 64 | 102 | 5 | 58 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | AverageMeter | AverageMeter | 262 | 277 | 262 | 262 | 35586e94f817c7ee18a9f17acc856531f257ac51 | bigcode/the-stack | train |
4124ed11eed37526b7adf139 | train | function | def drop_info_with_name(info, name):
ret_info = {}
keep_indices = [i for i, x in enumerate(info['name']) if x != name]
for key in info.keys():
ret_info[key] = info[key][keep_indices]
return ret_info
| def drop_info_with_name(info, name):
| ret_info = {}
keep_indices = [i for i, x in enumerate(info['name']) if x != name]
for key in info.keys():
ret_info[key] = info[key][keep_indices]
return ret_info
| def limit_period(val, offset=0.5, period=np.pi):
val, is_numpy = check_numpy_to_torch(val)
ans = val - torch.floor(val / period + offset) * period
return ans.numpy() if is_numpy else ans
def drop_info_with_name(info, name):
| 64 | 64 | 59 | 9 | 54 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | drop_info_with_name | drop_info_with_name | 27 | 32 | 27 | 27 | 325e5526a0e7f6c261a1b86380ca3942a05b0578 | bigcode/the-stack | train |
20932205a23af1a6ed5850a9 | train | function | def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
| def set_random_seed(seed):
| random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
| not None:
file_handler = logging.FileHandler(filename=log_file)
file_handler.setLevel(log_level if rank == 0 else 'ERROR')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.propagate = False
return logger
def set_random_seed(seed):
| 64 | 64 | 53 | 6 | 57 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | set_random_seed | set_random_seed | 102 | 108 | 102 | 102 | 5dde91fba6943500999c0a6f926dd16766287aff | bigcode/the-stack | train |
e06eb897dd382ee499a587fc | train | function | def keep_arrays_by_name(gt_names, used_classes):
inds = [i for i, x in enumerate(gt_names) if x in used_classes]
inds = np.array(inds, dtype=np.int64)
return inds
| def keep_arrays_by_name(gt_names, used_classes):
| inds = [i for i, x in enumerate(gt_names) if x in used_classes]
inds = np.array(inds, dtype=np.int64)
return inds
| ), Number of values padded to the edges (before, after)
"""
assert desired_size >= cur_size
# Calculate amount to pad
diff = desired_size - cur_size
pad_params = (0, diff)
return pad_params
def keep_arrays_by_name(gt_names, used_classes):
| 64 | 64 | 48 | 11 | 52 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | keep_arrays_by_name | keep_arrays_by_name | 138 | 141 | 138 | 138 | a62b986ebcd3b912331ac92304d6f8e70cf9af09 | bigcode/the-stack | train |
4a90e993b5839bb7bc908b3b | train | function | def check_numpy_to_torch(x):
if isinstance(x, np.ndarray):
return torch.from_numpy(x).float(), True
return x, False
| def check_numpy_to_torch(x):
| if isinstance(x, np.ndarray):
return torch.from_numpy(x).float(), True
return x, False
| import logging
import os
import pickle
import random
import shutil
import subprocess
import SharedArray
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
def check_numpy_to_torch(x):
| 53 | 64 | 33 | 8 | 44 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | check_numpy_to_torch | check_numpy_to_torch | 15 | 18 | 15 | 15 | 891b21dbbdeeb9aac8b5cf26dcf7a95d07e92110 | bigcode/the-stack | train |
5fcb43cfd5330a1d07caa9ad | train | function | def worker_init_fn(worker_id, seed=666):
if seed is not None:
random.seed(seed + worker_id)
np.random.seed(seed + worker_id)
torch.manual_seed(seed + worker_id)
torch.cuda.manual_seed(seed + worker_id)
torch.cuda.manual_seed_all(seed + worker_id)
| def worker_init_fn(worker_id, seed=666):
| if seed is not None:
random.seed(seed + worker_id)
np.random.seed(seed + worker_id)
torch.manual_seed(seed + worker_id)
torch.cuda.manual_seed(seed + worker_id)
torch.cuda.manual_seed_all(seed + worker_id)
| def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def worker_init_fn(worker_id, seed=666):
| 64 | 64 | 65 | 11 | 52 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | worker_init_fn | worker_init_fn | 111 | 117 | 111 | 111 | 51b4d4ed7927bd297c78b842930ece6415832346 | bigcode/the-stack | train |
76dfd90ac727b3cd565d8960 | train | function | def merge_results_dist(result_part, size, tmpdir):
rank, world_size = get_dist_info()
os.makedirs(tmpdir, exist_ok=True)
dist.barrier()
pickle.dump(result_part, open(os.path.join(tmpdir, 'result_part_{}.pkl'.format(rank)), 'wb'))
dist.barrier()
if rank != 0:
return None
part_list ... | def merge_results_dist(result_part, size, tmpdir):
| rank, world_size = get_dist_info()
os.makedirs(tmpdir, exist_ok=True)
dist.barrier()
pickle.dump(result_part, open(os.path.join(tmpdir, 'result_part_{}.pkl'.format(rank)), 'wb'))
dist.barrier()
if rank != 0:
return None
part_list = []
for i in range(world_size):
part_f... | ()
else:
rank = 0
world_size = 1
if return_gpu_per_machine:
gpu_per_machine = torch.cuda.device_count()
return rank, world_size, gpu_per_machine
return rank, world_size
def merge_results_dist(result_part, size, tmpdir):
| 64 | 64 | 171 | 12 | 51 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | merge_results_dist | merge_results_dist | 211 | 232 | 211 | 211 | 1585106df7402c220564de88760f74447af9c020 | bigcode/the-stack | train |
81f7c03433ab8a79fec7ad30 | train | function | def mask_points_by_range(points, limit_range):
mask = (points[:, 0] >= limit_range[0]) & (points[:, 0] <= limit_range[3]) \
& (points[:, 1] >= limit_range[1]) & (points[:, 1] <= limit_range[4])
return mask
| def mask_points_by_range(points, limit_range):
| mask = (points[:, 0] >= limit_range[0]) & (points[:, 0] <= limit_range[3]) \
& (points[:, 1] >= limit_range[1]) & (points[:, 1] <= limit_range[4])
return mask
| ).float()
points_rot = torch.matmul(points[:, :, 0:3], rot_matrix)
points_rot = torch.cat((points_rot, points[:, :, 3:]), dim=-1)
return points_rot.numpy() if is_numpy else points_rot
def mask_points_by_range(points, limit_range):
| 64 | 64 | 70 | 10 | 53 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | mask_points_by_range | mask_points_by_range | 60 | 63 | 60 | 60 | 0e5c5d77d4e77c40eae2196b6ad5def69ac4c37b | bigcode/the-stack | train |
ef2fd4c4c1eb586e0713ff59 | train | function | def create_logger(log_file=None, rank=0, log_level=logging.INFO):
logger = logging.getLogger(__name__)
logger.setLevel(log_level if rank == 0 else 'ERROR')
formatter = logging.Formatter('%(asctime)s %(levelname)5s %(message)s')
console = logging.StreamHandler()
console.setLevel(log_level if rank =... | def create_logger(log_file=None, rank=0, log_level=logging.INFO):
| logger = logging.getLogger(__name__)
logger.setLevel(log_level if rank == 0 else 'ERROR')
formatter = logging.Formatter('%(asctime)s %(levelname)5s %(message)s')
console = logging.StreamHandler()
console.setLevel(log_level if rank == 0 else 'ERROR')
console.setFormatter(formatter)
logger.a... | .tensor(point_cloud_range[0:3], device=voxel_centers.device).float()
voxel_centers = (voxel_centers + 0.5) * voxel_size + pc_range
return voxel_centers
def create_logger(log_file=None, rank=0, log_level=logging.INFO):
| 64 | 64 | 161 | 16 | 47 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | create_logger | create_logger | 85 | 99 | 85 | 85 | a37f934f588834dc9a9a622b116ad3d7c6a08013 | bigcode/the-stack | train |
cbe0b122ecb9eb21a5982b05 | train | function | def scatter_point_inds(indices, point_inds, shape):
ret = -1 * torch.ones(*shape, dtype=point_inds.dtype, device=point_inds.device)
ndim = indices.shape[-1]
flattened_indices = indices.view(-1, ndim)
slices = [flattened_indices[:, i] for i in range(ndim)]
ret[slices] = point_inds
return ret
| def scatter_point_inds(indices, point_inds, shape):
| ret = -1 * torch.ones(*shape, dtype=point_inds.dtype, device=point_inds.device)
ndim = indices.shape[-1]
flattened_indices = indices.view(-1, ndim)
slices = [flattened_indices[:, i] for i in range(ndim)]
ret[slices] = point_inds
return ret
| (pickle.load(open(part_file, 'rb')))
ordered_results = []
for res in zip(*part_list):
ordered_results.extend(list(res))
ordered_results = ordered_results[:size]
shutil.rmtree(tmpdir)
return ordered_results
def scatter_point_inds(indices, point_inds, shape):
| 64 | 64 | 83 | 11 | 52 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | scatter_point_inds | scatter_point_inds | 235 | 241 | 235 | 235 | 782d81dc07a73c27fae4e5e07204b8f5ce3b0581 | bigcode/the-stack | train |
88a9a0237da71d44c970ca80 | train | function | def sa_create(name, var):
x = SharedArray.create(name, var.shape, dtype=var.dtype)
x[...] = var[...]
x.flags.writeable = False
return x
| def sa_create(name, var):
| x = SharedArray.create(name, var.shape, dtype=var.dtype)
x[...] = var[...]
x.flags.writeable = False
return x
| _indices = torch.arange(indices.shape[0], device=device, dtype=torch.int32)
output_shape = [batch_size] + list(spatial_shape)
v2pinds_tensor = scatter_point_inds(indices, point_indices, output_shape)
return v2pinds_tensor
def sa_create(name, var):
| 64 | 64 | 43 | 7 | 56 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | sa_create | sa_create | 255 | 259 | 255 | 255 | 4ecd7ccc68374a580f3dfab28905e9fc11d70322 | bigcode/the-stack | train |
48ba662261a5d68e8ccd5c5b | train | function | def generate_voxel2pinds(sparse_tensor):
device = sparse_tensor.indices.device
batch_size = sparse_tensor.batch_size
spatial_shape = sparse_tensor.spatial_shape
indices = sparse_tensor.indices.long()
point_indices = torch.arange(indices.shape[0], device=device, dtype=torch.int32)
output_shape = ... | def generate_voxel2pinds(sparse_tensor):
| device = sparse_tensor.indices.device
batch_size = sparse_tensor.batch_size
spatial_shape = sparse_tensor.spatial_shape
indices = sparse_tensor.indices.long()
point_indices = torch.arange(indices.shape[0], device=device, dtype=torch.int32)
output_shape = [batch_size] + list(spatial_shape)
v2... | point_inds.device)
ndim = indices.shape[-1]
flattened_indices = indices.view(-1, ndim)
slices = [flattened_indices[:, i] for i in range(ndim)]
ret[slices] = point_inds
return ret
def generate_voxel2pinds(sparse_tensor):
| 64 | 64 | 105 | 11 | 52 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | generate_voxel2pinds | generate_voxel2pinds | 244 | 252 | 244 | 244 | c7e5a39b596e9fffd71539768f05c5684fafa69b | bigcode/the-stack | train |
ed2fc4309d71c10a76f44247 | train | function | def init_dist_pytorch(tcp_port, local_rank, backend='nccl'):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
# os.environ['MASTER_PORT'] = str(tcp_port)
# os.environ['MASTER_ADDR'] = 'localhost'
num_gpus = torch.cuda.device_count()
torch.cuda.set_device(local_ra... | def init_dist_pytorch(tcp_port, local_rank, backend='nccl'):
| if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
# os.environ['MASTER_PORT'] = str(tcp_port)
# os.environ['MASTER_ADDR'] = 'localhost'
num_gpus = torch.cuda.device_count()
torch.cuda.set_device(local_rank % num_gpus)
dist.init_process_group(
backend=... | os.environ['RANK'] = str(proc_id)
dist.init_process_group(backend=backend)
total_gpus = dist.get_world_size()
rank = dist.get_rank()
return total_gpus, rank
def init_dist_pytorch(tcp_port, local_rank, backend='nccl'):
| 64 | 64 | 151 | 17 | 46 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | init_dist_pytorch | init_dist_pytorch | 171 | 186 | 171 | 171 | 1f3f16e7301d3639dfc9d54a48829f163007e94e | bigcode/the-stack | train |
ab242bc6bc922e3833cd5d82 | train | function | def limit_period(val, offset=0.5, period=np.pi):
val, is_numpy = check_numpy_to_torch(val)
ans = val - torch.floor(val / period + offset) * period
return ans.numpy() if is_numpy else ans
| def limit_period(val, offset=0.5, period=np.pi):
| val, is_numpy = check_numpy_to_torch(val)
ans = val - torch.floor(val / period + offset) * period
return ans.numpy() if is_numpy else ans
|
import torch.distributed as dist
import torch.multiprocessing as mp
def check_numpy_to_torch(x):
if isinstance(x, np.ndarray):
return torch.from_numpy(x).float(), True
return x, False
def limit_period(val, offset=0.5, period=np.pi):
| 64 | 64 | 55 | 15 | 48 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | limit_period | limit_period | 21 | 24 | 21 | 21 | 4801525239e3d7396835d1389b4fadf84e10463b | bigcode/the-stack | train |
6773e9ff37e2a35b2417c3b8 | train | function | def get_pad_params(desired_size, cur_size):
"""
Get padding parameters for np.pad function
Args:
desired_size: int, Desired padded output size
cur_size: int, Current size. Should always be less than or equal to cur_size
Returns:
pad_params: tuple(int), Number of values padded to ... | def get_pad_params(desired_size, cur_size):
| """
Get padding parameters for np.pad function
Args:
desired_size: int, Desired padded output size
cur_size: int, Current size. Should always be less than or equal to cur_size
Returns:
pad_params: tuple(int), Number of values padded to the edges (before, after)
"""
assert... | if seed is not None:
random.seed(seed + worker_id)
np.random.seed(seed + worker_id)
torch.manual_seed(seed + worker_id)
torch.cuda.manual_seed(seed + worker_id)
torch.cuda.manual_seed_all(seed + worker_id)
def get_pad_params(desired_size, cur_size):
| 64 | 64 | 118 | 11 | 53 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | get_pad_params | get_pad_params | 120 | 135 | 120 | 120 | f1217ee645d1f1e3f28f64daeb67692d6947b5eb | bigcode/the-stack | train |
f8a3b06caa36ae0ad78f6a0e | train | function | def get_voxel_centers(voxel_coords, downsample_times, voxel_size, point_cloud_range):
"""
Args:
voxel_coords: (N, 3)
downsample_times:
voxel_size:
point_cloud_range:
Returns:
"""
assert voxel_coords.shape[1] == 3
voxel_centers = voxel_coords[:, [2, 1, 0]].float(... | def get_voxel_centers(voxel_coords, downsample_times, voxel_size, point_cloud_range):
| """
Args:
voxel_coords: (N, 3)
downsample_times:
voxel_size:
point_cloud_range:
Returns:
"""
assert voxel_coords.shape[1] == 3
voxel_centers = voxel_coords[:, [2, 1, 0]].float() # (xyz)
voxel_size = torch.tensor(voxel_size, device=voxel_centers.device).floa... | points[:, 0] <= limit_range[3]) \
& (points[:, 1] >= limit_range[1]) & (points[:, 1] <= limit_range[4])
return mask
def get_voxel_centers(voxel_coords, downsample_times, voxel_size, point_cloud_range):
| 64 | 64 | 169 | 21 | 42 | maxpark/OpenPCDet | pcdet/utils/common_utils.py | Python | get_voxel_centers | get_voxel_centers | 66 | 82 | 66 | 66 | 13b8dc8749e11b04e39c2637709c37e703599b20 | bigcode/the-stack | train |
0fb6d7663d49c60c109cf92f | train | function | def create_diagram(dot):
# Generates a diagram based on a graphviz DOT diagram description.
if not dot:
raise Exception("syntax: no graphviz definition provided")
dot_args = [ # These args add a watermark to the dot graphic.
"-Glabel=Made on Cloud Run",
"-Gfontsize=10",
"-G... | def create_diagram(dot):
# Generates a diagram based on a graphviz DOT diagram description.
| if not dot:
raise Exception("syntax: no graphviz definition provided")
dot_args = [ # These args add a watermark to the dot graphic.
"-Glabel=Made on Cloud Run",
"-Gfontsize=10",
"-Glabeljust=right",
"-Glabelloc=bottom",
"-Gfontcolor=gray",
"-Tpng",
... | return "Internal Server Error", 500
# [END run_system_package_handler]
# [END cloudrun_system_package_handler]
# [START cloudrun_system_package_exec]
# [START run_system_package_exec]
def create_diagram(dot):
# Generates a diagram based on a graphviz DOT diagram description.
| 64 | 64 | 177 | 20 | 44 | glasnt/python-docs-samples | run/system-package/main.py | Python | create_diagram | create_diagram | 52 | 74 | 52 | 53 | 8e3a85d3a9fc9c659f0d2d927415e37804236c01 | bigcode/the-stack | train |
cab6ea75ee203e5a190c3898 | train | function | @app.route("/diagram.png", methods=["GET"])
def index():
# Takes an HTTP GET request with query param dot and
# returns a png with the rendered DOT diagram in a HTTP response.
try:
image = create_diagram(request.args.get("dot"))
response = make_response(image)
response.headers.set("C... | @app.route("/diagram.png", methods=["GET"])
def index():
# Takes an HTTP GET request with query param dot and
# returns a png with the rendered DOT diagram in a HTTP response.
| try:
image = create_diagram(request.args.get("dot"))
response = make_response(image)
response.headers.set("Content-Type", "image/png")
return response
except Exception as e:
print("error: {}".format(e))
# If no graphviz definition or bad graphviz def, return 400... | app = Flask(__name__)
# [START cloudrun_system_package_handler]
# [START run_system_package_handler]
@app.route("/diagram.png", methods=["GET"])
def index():
# Takes an HTTP GET request with query param dot and
# returns a png with the rendered DOT diagram in a HTTP response.
| 64 | 64 | 143 | 41 | 23 | glasnt/python-docs-samples | run/system-package/main.py | Python | index | index | 26 | 43 | 26 | 29 | 836c587b0fcd6c1342fa0ac8710d41ab597b8ab0 | bigcode/the-stack | train |
55ee42823f304fec66f4ed8f | train | function | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
controls = QuantumRegister(n, "ofc")
oracle = QuantumCircuit(controls, name="Zf")
for i in range(2 ** n):
rep... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
| controls = QuantumRegister(n, "ofc")
oracle = QuantumCircuit(controls, name="Zf")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.h(controls[... | import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_control_Z_gate (issue #127)
| 64 | 64 | 197 | 58 | 5 | UCLA-SEAL/QDiff | benchmark/startQiskit_QC1640.py | Python | build_oracle | build_oracle | 16 | 40 | 16 | 20 | 65ce9f82635737bf77eda8c5c06726774c01313a | bigcode/the-stack | train |
40c330dfd8f17c81cb1f6985 | train | function | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[0]) # number=3
prog.x(input_qubit[4]) # number=53
prog.cx(input_qubit[2],input_qubit[0]) ... | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
| input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[0]) # number=3
prog.x(input_qubit[4]) # number=53
prog.cx(input_qubit[2],input_qubit[0]) # number=45
prog.z(input_qubit[2]) # number=46
prog.cx(in... | transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as nx
def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f^\pm
# NOTE: use U1 gate (P gate) with \lambda = 180 ==> CZ gate
# or multi_cont... | 256 | 256 | 925 | 17 | 238 | UCLA-SEAL/QDiff | benchmark/startQiskit_QC1640.py | Python | make_circuit | make_circuit | 43 | 117 | 43 | 44 | eec0f7149a578154b44b650e0c61f97eac1f076a | bigcode/the-stack | train |
77e38aa93d00f76b009e1f9b | train | class | class ExportDicomTest(sparktk_test.SparkTKTestCase):
def setUp(self):
"""import dicom data for testing"""
super(ExportDicomTest, self).setUp()
self.dataset = self.get_file("dicom_uncompressed")
self.dicom = self.context.dicom.import_dcm(self.dataset)
self.xml_directory = sel... | class ExportDicomTest(sparktk_test.SparkTKTestCase):
| def setUp(self):
"""import dicom data for testing"""
super(ExportDicomTest, self).setUp()
self.dataset = self.get_file("dicom_uncompressed")
self.dicom = self.context.dicom.import_dcm(self.dataset)
self.xml_directory = self.get_local_dataset("dicom_xml/")
self.image_d... | You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See t... | 205 | 205 | 685 | 16 | 188 | lewisc/spark-tk | regression-tests/sparktkregtests/testcases/dicom/dicom_export_dcm_test.py | Python | ExportDicomTest | ExportDicomTest | 26 | 84 | 26 | 27 | 4b90d5d53b96895a7378ecea40c66cbe786ce00a | bigcode/the-stack | train |
a5b4e2725afe7900162a4cca | train | class | class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(201, 137)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(10, 100, 181, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
... | class Ui_Dialog(object):
| def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(201, 137)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(10, 100, 181, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStand... | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'replacedumpeditorform.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impor... | 101 | 210 | 700 | 6 | 94 | student-proger/rfid | replacedumpeditorform.py | Python | Ui_Dialog | Ui_Dialog | 14 | 64 | 14 | 14 | 4fc68848c41dc07b63bff15b29cf6055922424fc | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.