_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q254600 | Record.get_object | validation | def get_object(cls, api_token, domain, record_id):
"""
Class method that will return a Record object by ID and the domain.
"""
| python | {
"resource": ""
} |
q254601 | Record.create | validation | def create(self):
"""
Creates a new record for a domain.
Args:
type (str): The type of the DNS record (e.g. A, CNAME, TXT).
name (str): The host name, alias, or service being defined by the
record.
data (int): Variable data depending on record type.
priority (int): The priority for SRV and MX records.
port (int): The port for SRV records.
ttl (int): The time to live for the record, in seconds.
weight (int): The weight for SRV records.
flags (int): An unsigned integer between 0-255 used for CAA records.
tags (string): The parameter tag for CAA records. Valid values are
"issue", "wildissue", or "iodef"
"""
input_params = {
"type": self.type,
"data": self.data,
"name": self.name,
"priority": | python | {
"resource": ""
} |
q254602 | Record.destroy | validation | def destroy(self):
"""
Destroy the record
"""
| python | {
"resource": ""
} |
q254603 | Record.save | validation | def save(self):
"""
Save existing record
"""
data = {
"type": self.type,
"data": self.data,
"name": self.name,
"priority": self.priority,
| python | {
"resource": ""
} |
q254604 | BaseAPI.get_timeout | validation | def get_timeout(self):
"""
Checks if any timeout for the requests to DigitalOcean is required.
To set a timeout, use the REQUEST_TIMEOUT_ENV_VAR environment
variable.
"""
timeout_str = os.environ.get(REQUEST_TIMEOUT_ENV_VAR)
| python | {
"resource": ""
} |
q254605 | Volume.get_object | validation | def get_object(cls, api_token, volume_id):
"""
Class method that will return an Volume object by ID.
"""
| python | {
"resource": ""
} |
q254606 | Volume.create_from_snapshot | validation | def create_from_snapshot(self, *args, **kwargs):
"""
Creates a Block Storage volume
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
name: string - a name for the volume
snapshot_id: string - unique identifier for the volume snapshot
size_gigabytes: int - size of the Block Storage volume in GiB
filesystem_type: string, optional - name of the filesystem type the
volume will be formated with ('ext4' or 'xfs')
filesystem_label: string, optional - the label to be applied to the
filesystem, only used in conjunction with filesystem_type
Optional Args:
description: string - text field to describe a volume
"""
data = self.get_data('volumes/',
type=POST,
params={'name': self.name,
| python | {
"resource": ""
} |
q254607 | Volume.attach | validation | def attach(self, droplet_id, region):
"""
Attach a Volume to a Droplet.
Args:
droplet_id: int - droplet id
region: string - slug identifier for the region
"""
return self.get_data(
"volumes/%s/actions/" % | python | {
"resource": ""
} |
q254608 | Volume.resize | validation | def resize(self, size_gigabytes, region):
"""
Detach a Volume to a Droplet.
Args:
size_gigabytes: int - size of the Block Storage volume in GiB
region: string - slug identifier for the region
"""
return self.get_data(
| python | {
"resource": ""
} |
q254609 | Volume.snapshot | validation | def snapshot(self, name):
"""
Create a snapshot of the volume.
Args:
name: string - a human-readable name for | python | {
"resource": ""
} |
q254610 | Volume.get_snapshots | validation | def get_snapshots(self):
"""
Retrieve the list of snapshots that have been created from a volume.
Args:
"""
data = self.get_data("volumes/%s/snapshots/" % self.id)
snapshots = list()
for jsond in data[u'snapshots']:
| python | {
"resource": ""
} |
q254611 | Certificate.get_object | validation | def get_object(cls, api_token, cert_id):
"""
Class method that will return a Certificate object by its ID.
"""
| python | {
"resource": ""
} |
q254612 | Certificate.load | validation | def load(self):
"""
Load the Certificate object from DigitalOcean.
Requires self.id to be set.
"""
data = self.get_data("certificates/%s" % self.id)
| python | {
"resource": ""
} |
q254613 | Certificate.create | validation | def create(self):
"""
Create the Certificate
"""
params = {
"name": self.name,
"type": self.type,
"dns_names": self.dns_names,
"private_key": self.private_key,
"leaf_certificate": self.leaf_certificate,
"certificate_chain": self.certificate_chain
}
data = self.get_data("certificates/", type=POST, params=params)
if data:
self.id = data['certificate']['id']
self.not_after = data['certificate']['not_after']
| python | {
"resource": ""
} |
q254614 | Image.get_object | validation | def get_object(cls, api_token, image_id_or_slug):
"""
Class method that will return an Image object by ID or slug.
This method is used to validate the type of the image. If it is a
number, it will be considered as an Image ID, instead if it is a
string, it will considered as slug.
""" | python | {
"resource": ""
} |
q254615 | Image.create | validation | def create(self):
"""
Creates a new custom DigitalOcean Image from the Linux virtual machine
image located at the provided `url`.
"""
params = {'name': self.name,
'region': self.region,
'url': self.url,
'distribution': self.distribution,
'description': self.description,
'tags': self.tags} | python | {
"resource": ""
} |
q254616 | Image.load | validation | def load(self, use_slug=False):
"""
Load slug.
Loads by id, or by slug if id is not present or use slug is True.
"""
identifier = None
if use_slug or not self.id:
identifier = self.slug
| python | {
"resource": ""
} |
q254617 | Image.transfer | validation | def transfer(self, new_region_slug):
"""
Transfer the image
"""
return self.get_data(
"images/%s/actions/" % self.id,
| python | {
"resource": ""
} |
q254618 | Image.rename | validation | def rename(self, new_name):
"""
Rename an image
"""
return self.get_data(
"images/%s" % | python | {
"resource": ""
} |
q254619 | convert_convtranspose | validation | def convert_convtranspose(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert transposed convolution layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting transposed convolution ...')
if names == 'short':
tf_name = 'C' + random_string(7)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
bias_name = '{0}.bias'.format(w_name)
weights_name = '{0}.weight'.format(w_name)
if len(weights[weights_name].numpy().shape) == 4:
W = weights[weights_name].numpy().transpose(2, 3, 1, 0)
height, width, n_filters, channels = W.shape
n_groups = params['group']
if n_groups > 1:
raise AssertionError('Cannot convert conv1d with groups != 1')
if params['dilations'][0] > 1:
raise AssertionError('Cannot convert conv1d with dilation_rate != 1')
if bias_name in weights:
biases = weights[bias_name].numpy()
has_bias = True
else:
biases = None
has_bias = False
input_name = inputs[0]
if has_bias:
weights = [W, biases]
else:
weights = [W]
conv = keras.layers.Conv2DTranspose(
filters=n_filters,
kernel_size=(height, width),
strides=(params['strides'][0], params['strides'][1]),
padding='valid',
output_padding=0,
weights=weights,
use_bias=has_bias,
| python | {
"resource": ""
} |
q254620 | convert_sum | validation | def convert_sum(
params, w_name, scope_name, inputs, layers, weights, names
):
"""
Convert sum.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: | python | {
"resource": ""
} |
q254621 | convert_reduce_sum | validation | def convert_reduce_sum(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert reduce_sum layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
| python | {
"resource": ""
} |
q254622 | convert_concat | validation | def convert_concat(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert concatenation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting concat ...')
concat_nodes = [layers[i] for i in inputs]
if len(concat_nodes) == 1:
# no-op
layers[scope_name] = concat_nodes[0]
| python | {
"resource": ""
} |
q254623 | convert_slice | validation | def convert_slice(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert slice operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting slice ...')
if len(params['axes']) > 1:
raise AssertionError('Cannot convert slice by multiple dimensions')
if params['axes'][0] not in [0, 1, 2, 3]:
| python | {
"resource": ""
} |
q254624 | convert_clip | validation | def convert_clip(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert clip operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
| python | {
"resource": ""
} |
q254625 | convert_elementwise_add | validation | def convert_elementwise_add(
params, w_name, scope_name, inputs, layers, weights, names
):
"""
Convert elementwise addition.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting elementwise_add ...')
if 'broadcast' in params:
model0 = layers[inputs[0]]
model1 = layers[inputs[1]]
if names == 'short':
tf_name = 'A' + random_string(7)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
def target_layer(x):
layer = tf.add(x[0], x[1])
return layer
lambda_layer = keras.layers.Lambda(target_layer, name=tf_name)
| python | {
"resource": ""
} |
q254626 | convert_elementwise_sub | validation | def convert_elementwise_sub(
params, w_name, scope_name, inputs, layers, weights, names
):
"""
Convert elementwise subtraction.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors | python | {
"resource": ""
} |
q254627 | convert_gemm | validation | def convert_gemm(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Linear.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting Linear ...')
if names == 'short':
tf_name = 'FC' + random_string(6)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
bias_name = '{0}.bias'.format(w_name)
weights_name = '{0}.weight'.format(w_name)
W = weights[weights_name].numpy().transpose()
input_channels, output_channels = W.shape
| python | {
"resource": ""
} |
q254628 | convert_matmul | validation | def convert_matmul(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert matmul layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting matmul ...')
if names == 'short':
tf_name = 'MMUL' + random_string(4)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
if len(inputs) == 1:
| python | {
"resource": ""
} |
q254629 | convert_constant | validation | def convert_constant(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert constant layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
| python | {
"resource": ""
} |
q254630 | convert_transpose | validation | def convert_transpose(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert transpose layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting transpose ...')
if params['perm'][0] != 0:
if inputs[0] in layers:
print('!!! Cannot permute batch dimension. Result may be wrong !!!')
layers[scope_name] = layers[inputs[0]]
| python | {
"resource": ""
} |
q254631 | convert_reshape | validation | def convert_reshape(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert reshape layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting reshape ...')
if names == 'short':
tf_name = 'RESH' + random_string(4)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
if len(inputs) > 1:
if layers[inputs[1]][0] == -1:
| python | {
"resource": ""
} |
q254632 | convert_squeeze | validation | def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
| python | {
"resource": ""
} |
q254633 | convert_unsqueeze | validation | def convert_unsqueeze(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert unsqueeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting unsqueeze ...')
if names == 'short':
tf_name = 'UNSQ' + random_string(4)
elif names == 'keep':
tf_name | python | {
"resource": ""
} |
q254634 | convert_shape | validation | def convert_shape(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert shape operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
| python | {
"resource": ""
} |
q254635 | convert_avgpool | validation | def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Average pooling.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting pooling ...')
if names == 'short':
tf_name = 'P' + random_string(7)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
if 'kernel_shape' in params:
height, width = params['kernel_shape']
else:
height, width = params['kernel_size']
if 'strides' in params:
stride_height, stride_width = params['strides']
else:
stride_height, stride_width = params['stride']
if 'pads' in params:
padding_h, padding_w, _, _ = params['pads']
else:
padding_h, padding_w = params['padding']
input_name = inputs[0]
pad = 'valid'
if height % 2 == 1 and width % 2 == 1 and \
height // 2 == padding_h and width // 2 == padding_w and \
stride_height == 1 and | python | {
"resource": ""
} |
q254636 | convert_maxpool3 | validation | def convert_maxpool3(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert 3d Max pooling.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting pooling ...')
if names == 'short':
tf_name = 'P' + random_string(7)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
if 'kernel_shape' in params:
height, width, depth = params['kernel_shape']
else:
| python | {
"resource": ""
} |
q254637 | convert_adaptive_max_pool2d | validation | def convert_adaptive_max_pool2d(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert convert_adaptive_max_pool2d layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting adaptive_avg_pool2d...')
if names == 'short':
tf_name = 'APOL' + random_string(4)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
| python | {
"resource": ""
} |
q254638 | convert_padding | validation | def convert_padding(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert padding layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting padding...')
if params['mode'] == 'constant':
# raise AssertionError('Cannot convert non-constant padding')
if params['value'] != 0.0:
raise AssertionError('Cannot convert non-zero padding')
| python | {
"resource": ""
} |
q254639 | convert_batchnorm | validation | def convert_batchnorm(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert batch normalization layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting batchnorm ...')
if names == 'short':
tf_name = 'BN' + random_string(6)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
bias_name = '{0}.bias'.format(w_name)
weights_name = '{0}.weight'.format(w_name)
mean_name = '{0}.running_mean'.format(w_name)
var_name = '{0}.running_var'.format(w_name)
if bias_name in weights:
beta = weights[bias_name].numpy()
if weights_name in weights:
gamma = weights[weights_name].numpy()
| python | {
"resource": ""
} |
q254640 | convert_instancenorm | validation | def convert_instancenorm(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert instance normalization layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting instancenorm ...')
if names == 'short':
tf_name = 'IN' + random_string(6)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
assert(len(inputs) == 3)
bias_name = '{0}.bias'.format(w_name)
weights_name = '{0}.weight'.format(w_name)
# Use previously taken constants
if inputs[-2] + '_np' in layers:
gamma = layers[inputs[-2] + '_np']
else:
| python | {
"resource": ""
} |
q254641 | convert_dropout | validation | def convert_dropout(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert dropout.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
| python | {
"resource": ""
} |
q254642 | convert_relu | validation | def convert_relu(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert relu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors | python | {
"resource": ""
} |
q254643 | convert_lrelu | validation | def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert leaky relu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
| python | {
"resource": ""
} |
q254644 | convert_sigmoid | validation | def convert_sigmoid(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert sigmoid layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors | python | {
"resource": ""
} |
q254645 | convert_softmax | validation | def convert_softmax(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert softmax layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting softmax ...')
if names == 'short':
tf_name = 'SMAX' + random_string(4)
elif names == 'keep':
tf_name = w_name
| python | {
"resource": ""
} |
q254646 | convert_tanh | validation | def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert tanh layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors | python | {
"resource": ""
} |
q254647 | convert_hardtanh | validation | def convert_hardtanh(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert hardtanh layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras | python | {
"resource": ""
} |
q254648 | convert_selu | validation | def convert_selu(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert selu layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors | python | {
"resource": ""
} |
q254649 | convert_upsample_bilinear | validation | def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert upsample_bilinear2d layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting upsample...')
if names == 'short':
tf_name = 'UPSL' + random_string(4)
elif names == 'keep':
tf_name = w_name
else:
tf_name = w_name + str(random.random())
output_size = params['output_size']
align_corners | python | {
"resource": ""
} |
q254650 | convert_upsample | validation | def convert_upsample(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert nearest upsampling layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers
"""
print('Converting upsample...')
if params['mode'] != 'nearest':
raise AssertionError('Cannot convert non-nearest upsampling')
if names == 'short':
tf_name = 'UPSL' + random_string(4)
elif names == 'keep':
tf_name = | python | {
"resource": ""
} |
q254651 | set_training | validation | def set_training(model, mode):
"""
A context manager to temporarily set the training mode of 'model'
to 'mode', resetting it when we exit the with-block. A no-op if
mode is None.
"""
if mode is None:
yield
| python | {
"resource": ""
} |
q254652 | get_platform_pwm | validation | def get_platform_pwm(**keywords):
"""Attempt to return a PWM instance for the platform which the code is being
executed on. Currently supports only the Raspberry Pi using the RPi.GPIO
library and Beaglebone Black using the Adafruit_BBIO library. Will throw an
exception if a PWM instance can't be created for the current platform. The
returned PWM object has the same interface as the RPi_PWM_Adapter and
BBIO_PWM_Adapter classes.
"""
plat = Platform.platform_detect()
| python | {
"resource": ""
} |
q254653 | RPi_PWM_Adapter.stop | validation | def stop(self, pin):
"""Stop PWM output on specified pin."""
if pin not in self.pwm:
| python | {
"resource": ""
} |
q254654 | platform_detect | validation | def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
# the platform.
plat = platform.platform()
if plat.lower().find('armv7l-with-debian') | python | {
"resource": ""
} |
q254655 | BitBang.write | validation | def write(self, data, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI write. If assert_ss is True, the SS line will be
asserted low, the specified bytes will be clocked out the MOSI line, and
if deassert_ss is True the SS line be put back high.
"""
# Fail MOSI is not specified.
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
for byte in data:
for i in range(8):
# Write bit to MOSI.
if self._write_shift(byte, i) & self._mask:
self._gpio.set_high(self._mosi)
else:
| python | {
"resource": ""
} |
q254656 | BitBang.read | validation | def read(self, length, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI read. If assert_ss is true, the SS line will be
asserted low, the specified length of bytes will be clocked in the MISO
line, and if deassert_ss is true the SS line will be put back high.
Bytes which are read will be returned as a bytearray object.
"""
if self._miso is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(length)
for i in range(length):
for j in range(8):
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else: | python | {
"resource": ""
} |
q254657 | BitBang.transfer | validation | def transfer(self, data, assert_ss=True, deassert_ss=True):
"""Full-duplex SPI read and write. If assert_ss is true, the SS line
will be asserted low, the specified bytes will be clocked out the MOSI
line while bytes will also be read from the MISO line, and if
deassert_ss is true the SS line will be put back high. Bytes which are
read will be returned as a bytearray object.
"""
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if self._miso is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(len(data))
for i in range(len(data)):
for j in range(8):
# Write bit to MOSI.
if self._write_shift(data[i], j) & self._mask:
self._gpio.set_high(self._mosi)
else:
self._gpio.set_low(self._mosi)
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
| python | {
"resource": ""
} |
q254658 | MCP230xxBase.setup | validation | def setup(self, pin, value):
"""Set the input or output mode for a specified pin. Mode should be
either GPIO.OUT or GPIO.IN.
"""
self._validate_pin(pin)
# Set bit to 1 for input or 0 for output.
if value == GPIO.IN:
self.iodir[int(pin/8)] |= 1 << (int(pin%8))
| python | {
"resource": ""
} |
q254659 | MCP230xxBase.pullup | validation | def pullup(self, pin, enabled):
"""Turn on the pull-up resistor for the specified pin if enabled is True,
otherwise turn off the pull-up resistor.
"""
self._validate_pin(pin)
if enabled:
| python | {
"resource": ""
} |
q254660 | MCP230xxBase.write_gpio | validation | def write_gpio(self, gpio=None):
"""Write the specified byte value to the GPIO registor. If no value
specified the current buffered value will be written.
"""
| python | {
"resource": ""
} |
q254661 | MCP230xxBase.write_iodir | validation | def write_iodir(self, iodir=None):
"""Write the specified byte value to the IODIR registor. If no value
specified the current buffered value will be written.
"""
| python | {
"resource": ""
} |
q254662 | MCP230xxBase.write_gppu | validation | def write_gppu(self, gppu=None):
"""Write the specified byte value to the GPPU registor. If no value
specified the current buffered value will be written.
"""
| python | {
"resource": ""
} |
q254663 | disable_FTDI_driver | validation | def disable_FTDI_driver():
"""Disable the FTDI drivers for the current platform. This is necessary
because they will conflict with libftdi and accessing the FT232H. Note you
can enable the FTDI drivers again by calling enable_FTDI_driver.
"""
logger.debug('Disabling FTDI driver.')
if sys.platform == 'darwin':
logger.debug('Detected Mac OSX')
# Mac OS commands to disable FTDI driver.
_check_running_as_root()
subprocess.call('kextunload -b com.apple.driver.AppleUSBFTDI', | python | {
"resource": ""
} |
q254664 | enable_FTDI_driver | validation | def enable_FTDI_driver():
"""Re-enable the FTDI drivers for the current platform."""
logger.debug('Enabling FTDI driver.')
if sys.platform == 'darwin':
logger.debug('Detected Mac OSX')
# Mac OS commands to enable FTDI driver.
_check_running_as_root()
subprocess.check_call('kextload -b com.apple.driver.AppleUSBFTDI', shell=True)
subprocess.check_call('kextload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)
| python | {
"resource": ""
} |
q254665 | enumerate_device_serials | validation | def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID):
"""Return a list of all FT232H device serial numbers connected to the
machine. You can use these serial numbers to open a specific FT232H device
by passing it to the FT232H initializer's serial parameter.
"""
try:
# Create a libftdi context.
ctx = None
ctx = ftdi.new()
# Enumerate FTDI devices.
device_list = None
count, device_list = ftdi.usb_find_all(ctx, vid, pid)
if count < 0:
raise RuntimeError('ftdi_usb_find_all returned error {0}: {1}'.format(count, ftdi.get_error_string(self._ctx)))
# Walk through list of devices and assemble list of serial numbers.
devices = []
while device_list is not None:
| python | {
"resource": ""
} |
q254666 | FT232H.close | validation | def close(self):
"""Close the FTDI device. Will be automatically called when | python | {
"resource": ""
} |
q254667 | FT232H._write | validation | def _write(self, string):
"""Helper function to call write_data on the provided FTDI device and
verify it succeeds.
"""
# Get modem status. Useful to enable for debugging.
#ret, status = ftdi.poll_modem_status(self._ctx)
#if ret == 0:
# logger.debug('Modem status {0:02X}'.format(status))
#else:
# logger.debug('Modem status error {0}'.format(ret))
length = len(string)
try:
ret = ftdi.write_data(self._ctx, string, length)
except TypeError:
ret = ftdi.write_data(self._ctx, string); #compatible with libFtdi 1.3
# Log the string that was written in a python hex string format using a very
| python | {
"resource": ""
} |
q254668 | FT232H._check | validation | def _check(self, command, *args):
"""Helper function to call the provided command on the FTDI device and
verify the response matches the expected value.
"""
ret = command(self._ctx, *args)
logger.debug('Called ftdi_{0} and got | python | {
"resource": ""
} |
q254669 | FT232H._poll_read | validation | def _poll_read(self, expected, timeout_s=5.0):
"""Helper function to continuously poll reads on the FTDI device until an
expected number of bytes are returned. Will throw a timeout error if no
data is received within the specified number of timeout seconds. Returns
the read data as a string if successful, otherwise raises an execption.
"""
start = time.time()
# Start with an empty response buffer.
response = bytearray(expected)
index = 0
# Loop calling read until the response buffer is full or a timeout occurs.
while time.time() - start <= timeout_s:
ret, data = ftdi.read_data(self._ctx, expected - index)
# Fail | python | {
"resource": ""
} |
q254670 | FT232H._mpsse_enable | validation | def _mpsse_enable(self):
"""Enable MPSSE mode on the FTDI device."""
# Reset MPSSE by sending mask = 0 and mode = 0
self._check(ftdi.set_bitmode, 0, 0)
| python | {
"resource": ""
} |
q254671 | FT232H._mpsse_sync | validation | def _mpsse_sync(self, max_retries=10):
"""Synchronize buffers with MPSSE by sending bad opcode and reading expected
error response. Should be called once after enabling MPSSE."""
# Send a bad/unknown command (0xAB), then read buffer until bad command
# response is found.
self._write('\xAB')
# Keep reading until bad command response (0xFA 0xAB) is returned.
# Fail if too many read attempts are made to prevent sticking in a loop.
tries = 0
sync = False
while | python | {
"resource": ""
} |
q254672 | FT232H.mpsse_set_clock | validation | def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):
"""Set the clock speed of the MPSSE engine. Can be any value from 450hz
to 30mhz and will pick that speed or the closest speed below it.
"""
# Disable clock divisor by 5 to enable faster speeds on FT232H.
self._write('\x8A')
# Turn on/off adaptive clocking.
if adaptive:
self._write('\x96')
else:
self._write('\x97')
# Turn on/off three phase clock (needed for I2C).
# Also adjust the frequency for three-phase clocking as specified in section 2.2.4
# of this document:
# http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
if three_phase:
self._write('\x8C')
else:
self._write('\x8D')
# Compute divisor for requested | python | {
"resource": ""
} |
q254673 | FT232H.mpsse_read_gpio | validation | def mpsse_read_gpio(self):
"""Read both GPIO bus states and return a 16 bit value with their state.
D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
"""
# Send command to read low byte and high byte.
self._write('\x81\x83')
# Wait for 2 byte response.
data = self._poll_read(2)
| python | {
"resource": ""
} |
q254674 | FT232H.mpsse_gpio | validation | def mpsse_gpio(self):
"""Return command to update the MPSSE GPIO state to the current direction
and level.
"""
level_low = chr(self._level & 0xFF)
level_high = chr((self._level >> 8) & 0xFF)
dir_low = chr(self._direction & 0xFF)
| python | {
"resource": ""
} |
q254675 | FT232H.setup | validation | def setup(self, pin, mode):
"""Set the input or output mode for a specified pin. Mode should be
either OUT or IN."""
| python | {
"resource": ""
} |
q254676 | SPI.write | validation | def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
#check for hardware limit of FT232H and similar MPSSE chips
if (len(data) > 65536):
print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')
print('use for loops for larger reads')
exit(1)
# Build command to write SPI data.
command = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve
logger.debug('SPI write with command {0:2X}.'.format(command))
# Compute length low and high bytes.
# NOTE: Must actually send length minus one because the MPSSE engine
# considers 0 a length of 1 and FFFF a length of 65536
# splitting into two lists for two commands to prevent buffer errors
data1 = data[:len(data)/2]
data2 = data[len(data)/2:]
| python | {
"resource": ""
} |
q254677 | SPI.read | validation | def read(self, length):
"""Half-duplex SPI read. The specified length of bytes will be clocked
in the MISO line and returned as a bytearray object.
"""
#check for hardware limit of FT232H and similar MPSSE chips
if (1 > length > 65536):
print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')
print('use for loops for larger reads')
exit(1)
# Build command to read SPI data.
command = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)
logger.debug('SPI read with command {0:2X}.'.format(command))
# Compute length low and high bytes.
| python | {
"resource": ""
} |
q254678 | SPI.bulkread | validation | def bulkread(self, data = [], lengthR = 'None', readmode = 1):
"""Half-duplex SPI write then read. Send command and payload to slave as bytearray
then consequently read out response from the slave for length in bytes.
Designed for use with NOR or NAND flash chips, and possibly SD cards...etc...
Read command is cut in half and performed twice in series to prevent single byte errors.
Hardware limits per command are enforced before doing anything.
Read length is an optional argument, so that it can function similar to transfer
but still half-duplex.
For reading without writing, one can send a blank array or skip that argument.
"""
#check for hardware limit of FT232H and similar MPSSE chips
if (1 > lengthR > 65536)|(len(data) > 65536):
print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')
print('use for loops for larger reads')
exit(1)
#default mode is to act like `transfer` but half-duplex
if (lengthR == 'None')&(readmode == 1):
lengthR = len(data)
#command parameters definition and math
#MPSSE engine sees length 0 as 1 byte, so - 1 lengths
commandW = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve
lengthW = len(data) - 1
len_lowW = (lengthW) & 0xFF
len_highW = ((lengthW) >> 8) & 0xFF
commandR = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)
#force odd numbers to round up instead of | python | {
"resource": ""
} |
q254679 | SPI.transfer | validation | def transfer(self, data):
"""Full-duplex SPI read and write. The specified array of bytes will be
clocked out the MOSI line, while simultaneously bytes will be read from
the MISO line. Read bytes will be returned as a bytearray object.
"""
#check for hardware limit of FT232H and similar MPSSE chips
if (len(data) > 65536):
print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')
print('use for loops for larger reads')
exit(1)
# Build command to read and write SPI data.
command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve << 2) | self.write_clock_ve
logger.debug('SPI transfer with command {0:2X}.'.format(command))
# Compute length low and high bytes.
# NOTE: Must actually send length minus one because the MPSSE engine
# considers 0 a length of 1 and FFFF a length of 65536
data1 = data[:len(data)/2]
data2 = data[len(data)/2:]
len_low1 = (len(data1) - 1) & 0xFF
len_high1 = ((len(data1) - 1) >> 8) & 0xFF
len_low2 = (len(data2) - 1) & 0xFF
len_high2 = ((len(data2) - 1) >> 8) & 0xFF
payload1 = ''
payload2 = ''
#start command set
self._assert_cs()
# Perform twice to | python | {
"resource": ""
} |
q254680 | I2CDevice._idle | validation | def _idle(self):
"""Put I2C lines into idle state."""
# Put the I2C lines into an idle state with | python | {
"resource": ""
} |
q254681 | I2CDevice._transaction_end | validation | def _transaction_end(self):
"""End I2C transaction and get response bytes, including ACKs."""
# Ask to return response bytes immediately.
self._command.append('\x87')
# Send the entire command to the MPSSE.
| python | {
"resource": ""
} |
q254682 | I2CDevice._i2c_write_bytes | validation | def _i2c_write_bytes(self, data):
"""Write the specified number of bytes to the chip."""
for byte in data:
# Write byte.
self._command.append(str(bytearray((0x11, 0x00, 0x00, byte))))
# Make sure pins are back in idle state with clock low and data high.
self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
| python | {
"resource": ""
} |
q254683 | I2CDevice.ping | validation | def ping(self):
"""Attempt to detect if a device at this address is present on the I2C
bus. Will send out the device's address for writing and verify an ACK
is received. Returns true if the ACK is received, and false if not.
"""
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(False)]) | python | {
"resource": ""
} |
q254684 | I2CDevice.readS8 | validation | def readS8(self, register):
"""Read a signed byte from the specified register."""
result = self.readU8(register)
| python | {
"resource": ""
} |
q254685 | get_i2c_device | validation | def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs):
"""Return an I2C device for the specified address and on the specified bus.
| python | {
"resource": ""
} |
q254686 | Device.write8 | validation | def write8(self, register, value):
"""Write an 8-bit value to the specified register."""
value = value & 0xFF
self._bus.write_byte_data(self._address, register, value)
| python | {
"resource": ""
} |
q254687 | Device.readU8 | validation | def readU8(self, register):
"""Read an unsigned byte from the specified register."""
result = self._bus.read_byte_data(self._address, register) & 0xFF
| python | {
"resource": ""
} |
q254688 | get_platform_gpio | validation | def get_platform_gpio(**keywords):
"""Attempt to return a GPIO instance for the platform which the code is being
executed on. Currently supports only the Raspberry Pi using the RPi.GPIO
library and Beaglebone Black using the Adafruit_BBIO library. Will throw an
exception if a GPIO instance can't be created for the current platform. The
returned GPIO object is an instance of BaseGPIO.
"""
| python | {
"resource": ""
} |
q254689 | RPiGPIOAdapter.setup | validation | def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
| python | {
"resource": ""
} |
q254690 | AdafruitMinnowAdapter.setup | validation | def setup(self,pin,mode):
"""Set the input or output mode for a specified pin. Mode should be | python | {
"resource": ""
} |
q254691 | AdafruitMinnowAdapter.remove_event_detect | validation | def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
| python | {
"resource": ""
} |
q254692 | TrashDirectory.all_info_files | validation | def all_info_files(self) :
'Returns a generator of "Path"s'
try :
for info_file in list_files_in_dir(self.info_dir):
if not os.path.basename(info_file).endswith('.trashinfo') :
self.on_non_trashinfo_found()
| python | {
"resource": ""
} |
q254693 | TrashPutCmd.trash | validation | def trash(self, file) :
"""
Trash a file in the appropriate trash directory.
If the file belong to the same volume of the trash home directory it
will be trashed in the home trash directory.
Otherwise it will be trashed in one of the relevant volume trash
directories.
Each volume can have two trash directories, they are
- $volume/.Trash/$uid
- $volume/.Trash-$uid
Firstly the software attempt to trash the file in the first directory
then try to trash in the second trash directory.
"""
if self._should_skipped_by_specs(file):
self.reporter.unable_to_trash_dot_entries(file)
| python | {
"resource": ""
} |
q254694 | BpmnParser.get_process_parser | validation | def get_process_parser(self, process_id_or_name):
"""
Returns the ProcessParser for the given process ID or name. It matches
by name first.
| python | {
"resource": ""
} |
q254695 | BpmnParser.add_bpmn_files | validation | def add_bpmn_files(self, filenames):
"""
Add all filenames in the given list to the parser's set.
"""
for filename in filenames:
f = open(filename, 'r')
try: | python | {
"resource": ""
} |
q254696 | BpmnParser.add_bpmn_xml | validation | def add_bpmn_xml(self, bpmn, svg=None, filename=None):
"""
Add the given lxml representation of the BPMN file to the parser's set.
:param svg: Optionally, provide the text data for the SVG of the BPMN
file
:param filename: Optionally, provide the source filename.
"""
xpath = xpath_eval(bpmn)
processes = xpath('.//bpmn:process')
for process in processes:
process_parser = self.PROCESS_PARSER_CLASS(
self, process, svg, filename=filename, doc_xpath=xpath)
if process_parser.get_id() in self.process_parsers:
raise ValidationException(
| python | {
"resource": ""
} |
q254697 | one | validation | def one(nodes, or_none=False):
"""
Assert that there is exactly one node in the give list, and return it.
"""
if not nodes and or_none:
return None
assert len(
| python | {
"resource": ""
} |
q254698 | XmlSerializer.serialize_value | validation | def serialize_value(self, parent_elem, value):
"""
Serializes str, Attrib, or PathAttrib objects.
Example::
<attribute>foobar</attribute>
"""
if isinstance(value, (str, int)) or type(value).__name__ == 'str':
| python | {
"resource": ""
} |
q254699 | XmlSerializer.serialize_value_list | validation | def serialize_value_list(self, list_elem, thelist):
"""
Serializes a list, where the values are objects of type
str, Attrib, or PathAttrib.
Example::
<value>text</value>
<value><attribute>foobar</attribute></value>
<value><path>foobar</path></value>
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.