code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
measurements = collections.deque([], self._max_retries)
for attempt in range(1, self._max_retries + 1):
try:
result = yield self._execute(
action, parameters, attempt, measurements)
except (exceptions.InternalServerError,
... | def execute(self, action, parameters) | Execute a DynamoDB action with the given parameters. The method will
retry requests that failed due to OS level errors or when being
throttled by DynamoDB.
:param str action: DynamoDB action to invoke
:param dict parameters: parameters to send into the action
:rtype: tornado.con... | 3.142462 | 2.724439 | 1.153435 |
self.logger.debug('Setting error callback: %r', callback)
self._on_error = callback | def set_error_callback(self, callback) | Assign a method to invoke when a request has encountered an
unrecoverable error in an action execution.
:param method callback: The method to invoke | 5.698389 | 7.499643 | 0.759821 |
self.logger.debug('Setting instrumentation callback: %r', callback)
self._instrumentation_callback = callback | def set_instrumentation_callback(self, callback) | Assign a method to invoke when a request has completed gathering
measurements.
:param method callback: The method to invoke | 4.204801 | 5.547004 | 0.758031 |
future = concurrent.Future()
start = time.time()
def handle_response(request):
self._on_response(
action, parameters.get('TableName', 'Unknown'), attempt,
start, request, future, measurements)
ioloop.IOLoop.current().add... | def _execute(self, action, parameters, attempt, measurements) | Invoke a DynamoDB action
:param str action: DynamoDB action to invoke
:param dict parameters: parameters to send into the action
:param int attempt: Which attempt number this is
:param list measurements: A list for accumulating request measurements
:rtype: tornado.concurrent.Fut... | 3.701853 | 3.229825 | 1.146147 |
self.logger.debug('%s on %s request #%i = %r',
action, table, attempt, response)
now, exception = time.time(), None
try:
future.set_result(self._process_response(response))
except aws_exceptions.ConfigNotFound as error:
exception... | def _on_response(self, action, table, attempt, start, response, future,
measurements) | Invoked when the HTTP request to the DynamoDB has returned and
is responsible for setting the future result or exception based upon
the HTTP response provided.
:param str action: The action that was taken
:param str table: The table name the action was made against
:param int at... | 3.183669 | 3.146625 | 1.011773 |
error = response.exception()
if error:
if isinstance(error, aws_exceptions.AWSError):
if error.args[1]['type'] in exceptions.MAP:
raise exceptions.MAP[error.args[1]['type']](
error.args[1]['message'])
raise erro... | def _process_response(response) | Process the raw AWS response, returning either the mapped exception
or deserialized response.
:param tornado.concurrent.Future response: The request future
:rtype: dict or list
:raises: sprockets_dynamodb.exceptions.DynamoDBException | 3.210059 | 2.913547 | 1.10177 |
if resource_id is not None:
if self.read(resource_id):
raise ValueError("There are one object already with this id.")
obj['_id'] = resource_id
prepared_creation_tx = self.driver.instance.transactions.prepare(
operation='CREATE',
si... | def write(self, obj, resource_id=None) | Write and obj in bdb.
:param obj: value to be written in bdb.
:param resource_id: id to make possible read and search for an resource.
:return: id of the transaction | 3.795553 | 3.72761 | 1.018227 |
# tx_id=self._find_tx_id(resource_id)
value = [
{
'data': transaction['metadata'],
'id': transaction['id']
}
for transaction in self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_id))
][-1]
if v... | def _get(self, tx_id) | Read and obj in bdb using the tx_id.
:param resource_id: id of the transaction to be read.
:return: value with the data, transaction id and transaction. | 6.299503 | 5.811607 | 1.083952 |
try:
if not tx_id:
sent_tx = self.write(metadata, resource_id)
self.logger.debug('bdb::put::{}'.format(sent_tx['id']))
return sent_tx
else:
txs = self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_i... | def _update(self, metadata, tx_id, resource_id) | Update and obj in bdb using the tx_id.
:param metadata: new metadata for the transaction.
:param tx_id: id of the transaction to be updated.
:return: id of the transaction. | 4.143653 | 4.324111 | 0.958267 |
l = []
for i in self._list():
l.append(i['data']['data'])
return l[0:limit] | def list(self, search_from=None, search_to=None, limit=None) | List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions. | 6.92527 | 7.178761 | 0.964689 |
all = self.driver.instance.metadata.get(search=self.namespace)
list = []
for id in all:
try:
if not self._get(id['id']) in list:
list.append(self._get(id['id']))
except Exception:
pass
return list | def _list(self) | List all the objects saved in the namespace.
:param search_from: TBI
:param search_to: TBI
:param offset: TBI
:param limit: max number of values to be shows.
:return: list with transactions. | 6.196145 | 6.085456 | 1.018189 |
self.logger.debug('bdb::get::{}'.format(search_model.query))
assets = json.loads(requests.post("http://localhost:4000/query", data=search_model.query).content)['data']
self.logger.debug('bdb::result::len {}'.format(len(assets)))
assets_metadata = []
for i in assets:
... | def query(self, search_model: QueryModel) | Query to bdb namespace.
:param query_string: query in string format.
:return: list of transactions that match with the query. | 4.449166 | 4.044764 | 1.099982 |
txs = self.driver.instance.transactions.get(asset_id=self.get_asset_id(tx_id))
unspent = txs[-1]
output_index = 0
output = unspent['outputs'][output_index]
transfer_input = {
'fulfillment': output['condition']['details'],
'fulfills': {
... | def _delete(self, tx_id) | Delete a transaction. Read documentation about CRAB model in https://blog.bigchaindb.com/crab-create-retrieve-append-burn-b9f6d111f460.
:param tx_id: transaction id
:return: | 3.349323 | 3.014654 | 1.111014 |
tx = self.driver.instance.transactions.retrieve(txid=tx_id)
assert tx is not None
return tx['id'] if tx['operation'] == 'CREATE' else tx['asset']['id'] | def get_asset_id(self, tx_id) | Return the tx_id of the first transaction.
:param tx_id: Transaction id to start the recursive search.
:return Transaction id parent. | 6.412265 | 8.037128 | 0.79783 |
hdrobj = data if isinstance(data, HDRobject) else HDRobject(data)
hdrobj.write(filename) | def hdr(data, filename) | write ENVI header files
Parameters
----------
data: str or dict
the file or dictionary to get the info from
filename: str
the HDR file to write
Returns
------- | 5.081758 | 5.981819 | 0.849534 |
with open(self.filename, 'r') as infile:
lines = infile.readlines()
i = 0
out = dict()
while i < len(lines):
line = lines[i].strip('\r\n')
if '=' in line:
if '{' in line and '}' not in line:
while '}' not in... | def __hdr2dict(self) | read a HDR file into a dictionary
http://gis.stackexchange.com/questions/48618/how-to-read-write-envi-metadata-using-gdal
Returns
-------
dict
the hdr file metadata attributes | 2.572368 | 2.606167 | 0.987031 |
if filename == 'same':
filename = self.filename
if not filename.endswith('.hdr'):
filename += '.hdr'
with open(filename, 'w') as out:
out.write(self.__str__()) | def write(self, filename='same') | write object to an ENVI header file | 2.634399 | 2.318499 | 1.136252 |
' Setup of maximum speed '
spi.SPI_write_byte(self.CS, 0x07) # Max Speed setup
spi.SPI_write_byte(self.CS, 0x00)
spi.SPI_write_byte(self.CS, speed) | def MaxSpeed(self, speed) | Setup of maximum speed | 6.073345 | 5.698603 | 1.06576 |
' Go to Zero position '
self.ReleaseSW()
spi.SPI_write_byte(self.CS, 0x82 | (self.Dir & 1)) # Go to Zero
spi.SPI_write_byte(self.CS, 0x00)
spi.SPI_write_byte(self.CS, speed)
while self.IsBusy():
pass
time.sleep(0.3)
self.ReleaseSW() | def GoZero(self, speed) | Go to Zero position | 5.527884 | 6.0051 | 0.920532 |
' Move some distance units from current position '
steps = units * self.SPU # translate units to steps
if steps > 0: # look for direction
spi.SPI_write_byte(self.CS, 0x40 | (~self.Dir & 1))
else:
spi.SPI_write_byte... | def Move(self, units) | Move some distance units from current position | 3.910193 | 3.74385 | 1.044431 |
' Report given status bit '
spi.SPI_write_byte(self.CS, 0x39) # Read from address 0x19 (STATUS)
spi.SPI_write_byte(self.CS, 0x00)
data0 = spi.SPI_read_byte() # 1st byte
spi.SPI_write_byte(self.CS, 0x00)
data1 = spi.SPI_read_byte() # 2nd byte
... | def ReadStatusBit(self, bit) | Report given status bit | 3.853721 | 3.830041 | 1.006183 |
'Writes a data to a SPI device selected by chipselect bit. '
self.bus.write_byte_data(self.address, chip_select, data) | def SPI_write_byte(self, chip_select, data) | Writes a data to a SPI device selected by chipselect bit. | 7.945126 | 3.5933 | 2.211095 |
'Writes data to SPI device selected by chipselect bit. '
dat = list(data)
dat.insert(0, chip_select)
return self.bus.write_i2c_block(self.address, dat); | def SPI_write(self, chip_select, data) | Writes data to SPI device selected by chipselect bit. | 7.480264 | 4.860363 | 1.539034 |
'Configure SPI interface parameters.'
self.bus.write_byte_data(self.address, 0xF0, config)
return self.bus.read_byte_data(self.address, 0xF0) | def SPI_config(self,config) | Configure SPI interface parameters. | 3.153245 | 3.127375 | 1.008272 |
'Reads logic state on GPIO enabled slave-selects pins.'
self.bus.write_byte_data(self.address, 0xF5, 0x0f)
status = self.bus.read_byte(self.address)
bits_values = dict([('SS0',status & 0x01 == 0x01),('SS1',status & 0x02 == 0x02),('SS2',status & 0x04 == 0x04),('SS3',status & 0x08 == 0x08)... | def GPIO_read(self) | Reads logic state on GPIO enabled slave-selects pins. | 3.59391 | 2.400064 | 1.497423 |
'Enable or disable slave-select pins as gpio.'
self.bus.write_byte_data(self.address, 0xF6, gpio_enable)
self.bus.write_byte_data(self.address, 0xF7, gpio_config)
return | def GPIO_config(self, gpio_enable, gpio_config) | Enable or disable slave-select pins as gpio. | 3.910401 | 2.304478 | 1.696871 |
LOGGER.debug("Reading RPS01A sensor's address.",)
return self.bus.read_byte_data(self.address, self.address_reg) | def get_address(self) | Returns sensors I2C address. | 12.355105 | 9.481551 | 1.303068 |
LSB = self.bus.read_byte_data(self.address, self.zero_position_MSB)
MSB = self.bus.read_byte_data(self.address, self.zero_position_LSB)
DATA = (MSB << 6) + LSB
return DATA | def get_zero_position(self) | Returns programmed zero position in OTP memory. | 3.194005 | 2.759502 | 1.157457 |
LOGGER.debug("Reading RPS01A sensor's AGC settings",)
return self.bus.read_byte_data(self.address, self.AGC_reg) | def get_agc_value(self) | Returns sensor's Automatic Gain Control actual value.
0 - Represents high magtetic field
0xFF - Represents low magnetic field | 13.381358 | 10.666679 | 1.254501 |
status = self.bus.read_byte_data(self.address, self.diagnostics_reg)
bits_values = dict([('OCF',status & 0x01 == 0x01),
('COF',status & 0x02 == 0x02),
('Comp_Low',status & 0x04 == 0x04),
('Comp_High',status & 0... | def get_diagnostics(self) | Reads diagnostic data from the sensor.
OCF (Offset Compensation Finished) - logic high indicates the finished Offset Compensation Algorithm. After power up the flag remains always to logic high.
COF (Cordic Overflow) - logic high indicates an out of range error in the CORDIC part. When this bit is set,... | 3.247498 | 2.339208 | 1.38829 |
LSB = self.bus.read_byte_data(self.address, self.angle_LSB)
MSB = self.bus.read_byte_data(self.address, self.angle_MSB)
DATA = (MSB << 6) + LSB
if not verify:
return (360.0 / 2**14) * DATA
else:
status = self.get_diagnostics()
if not ... | def get_angle(self, verify = False) | Retuns measured angle in degrees in range 0-360. | 3.747 | 3.520848 | 1.064232 |
logger.init(is_debug_=is_debug)
if not genome:
raise click.BadParameter('Error: please, specify genome build name with -g (e.g. `-g hg19`)', param='genome')
if short:
if extended: raise click.BadParameter('--short and --extended can\'t be set both', param='extended')
if... | def main(input_bed, output_file, output_features=False, genome=None,
only_canonical=False, short=False, extended=False, high_confidence=False,
ambiguities_method=False, coding_only=False, collapse_exons=False, work_dir=False, is_debug=False) | Annotating BED file based on reference features annotations. | 2.732521 | 2.734273 | 0.999359 |
return (self.bus.read_byte_data(self.address, 0x02) + self.bus.read_byte_data(self.address, 0x03) * 256) | def StateOfCharge(self) | % of Full Charge | 2.700244 | 2.695167 | 1.001884 |
''' Get cells chemistry '''
length = self.bus.read_byte_data(self.address, 0x79)
chem = []
for n in range(length):
chem.append(self.bus.read_byte_data(self.address, 0x7A + n))
return chem | def Chemistry(self) | Get cells chemistry | 4.351388 | 3.703933 | 1.174802 |
if (x-4) > (y-4) and -(y-4) <= (x-4):
# right
return "#CDB95B"
elif (x-4) > (y-4) and -(y-4) > (x-4):
# top
return "#CD845B"
elif (x-4) <= (y-4) and -(y-4) <= (x-4):
# bottom
return "#57488E"
elif (x-4) <= (y-4) and -(y-4) > (x-4):
# left
... | def color(x, y) | triangles.
Colors:
- http://paletton.com/#uid=70l150klllletuehUpNoMgTsdcs shade 2 | 2.929855 | 3.084515 | 0.949859 |
'''
Reads data from desired register only once.
'''
comm_reg = (0b00010 << 3) + register
if register == self.AD7730_STATUS_REG:
bytes_num = 1
elif register == self.AD7730_DATA_REG:
bytes_num = 3
elif register == self.AD7730_MODE_... | def single_read(self, register) | Reads data from desired register only once. | 2.879474 | 2.613952 | 1.101579 |
status = self.single_read(self.AD7730_STATUS_REG)
bits_values = dict([('NOREF',status[0] & 0x10 == 0x10),
('STBY',status[0] & 0x20 == 0x20),
('STDY',status[0] & 0x40 == 0x40),
('RDY',status[0] & 0x80 == 0x80)]... | def getStatus(self) | RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet
STDY - Steady Bit. This bit is updated when the filter writes a result to the Data... | 3.473554 | 2.431177 | 1.428754 |
'''
def setMode(self
,mode = self.AD7730_IDLE_MODE
,polarity = self.AD7730_UNIPOLAR_MODE
,den = self.AD7730_IODISABLE_MODE
,iovalue = 0b00
,data_lenght = self.AD7730_24bitDATA_MODE
,r... | def setMode(self
,mode
,polarity
,den
,iovalue
,data_length
,reference
,input_range
,clock_enable
,burn_out
,c... | def setMode(self
,mode = self.AD7730_IDLE_MODE
,polarity = self.AD7730_UNIPOLAR_MODE
,den = self.AD7730_IODISABLE_MODE
,iovalue = 0b00
,data_lenght = self.AD7730_24bitDATA_MODE
,reference = self.AD77... | 3.011497 | 1.518547 | 1.983143 |
self.bus.write_byte(self.address, self.TRIG_RH_noHOLD); # start humidity measurement
time.sleep(0.1)
data = self.bus.read_i2c_block(self.address, 2)
value = data[0]<<8 | data[1]
value &= ~0b11 # trow out status bits
humidity = (-6.0 + 125.0*(value/65536.0))
... | def get_hum(self, raw = False) | The physical value RH given above corresponds to the
relative humidity above liquid water according to World
Meteorological Organization (WMO) | 7.086411 | 6.955054 | 1.018887 |
# CRC
polynomial = 0x131 # //P(x)=x^8+x^5+x^4+1 = 100110001
crc = 0xFF
# calculates 8-Bit checksum with given polynomial
for byteCtr in [ord(x) for x in struct.pack(">H", value)]:
crc ^= byteCtr
for bit in range(8, 0, -1):
if crc... | def _calculate_checksum(value) | 4.12 Checksum Calculation from an unsigned short input | 3.730671 | 3.476902 | 1.072987 |
inside = 0
for draws in range(1, self.data['samples']):
# generate points and check whether they are inside the unit circle
r1, r2 = (random(), random())
if r1 ** 2 + r2 ** 2 < 1.0:
inside += 1
if draws % 1000 != 0:
... | def run(self) | Run when button is pressed. | 4.713054 | 4.667126 | 1.009841 |
action = f.__name__
f.action = action
@wrapt.decorator
@tornado.gen.coroutine
def _execute(wrapped, instance, args, kwargs):
return wrapped(*args, **kwargs)
return _execute(f) | def on(f) | Decorator for action handlers.
The action name is inferred from the function name.
This also decorates the method with `tornado.gen.coroutine` so that
`~tornado.concurrent.Future` can be yielded. | 4.008828 | 4.166699 | 0.962111 |
@wrapt.decorator
@tornado.gen.coroutine
def _execute(wrapped, instance, args, kwargs):
return wrapped(*args, **kwargs)
_execute.action = action
return _execute | def on_action(action) | Decorator for action handlers.
:param str action: explicit action name
This also decorates the method with `tornado.gen.coroutine` so that
`~tornado.concurrent.Future` can be yielded. | 4.426798 | 4.030194 | 1.098408 |
self.data = Datastore(self.id_)
self.data.subscribe(lambda data: self.emit('data', data))
self.class_data = Datastore(type(self).__name__)
self.class_data.subscribe(lambda data: self.emit('class_data', data)) | def init_datastores(self) | Initialize datastores for this analysis instance.
This creates instances of :class:`.Datastore` at ``data`` and
``class_data`` with the datastore domains being the current id
and the class name of this analysis respectively.
Overwrite this method to use other datastore backends. | 3.581694 | 3.012222 | 1.189054 |
# call pre-emit hooks
if signal == 'log':
self.log_backend.info(message)
elif signal == 'warn':
self.log_backend.warn(message)
elif signal == 'error':
self.log_backend.error(message)
return self.emit_to_frontend(signal, message) | def emit(self, signal, message='__nomessagetoken__') | Emit a signal to the frontend.
:param str signal: name of the signal
:param message: message to send
:returns: return value from frontend emit function
:rtype: tornado.concurrent.Future | 3.434835 | 3.400339 | 1.010145 |
value_encoded = encode(value, self.get_change_trigger(i))
if i in self.data and self.data[i] == value_encoded:
return self
self.data[i] = value_encoded
return self.trigger_changed(i) | def set(self, i, value) | Set value at position i and return a Future.
:rtype: tornado.concurrent.Future | 5.147897 | 6.162349 | 0.835379 |
value_encoded = encode(value, self.get_change_trigger(key))
if key in self.data and self.data[key] == value_encoded:
return self
self.data[key] = value_encoded
return self.trigger_changed(key) | def set(self, key, value) | Set a value at key and return a Future.
:rtype: tornado.concurrent.Future | 4.727026 | 5.853696 | 0.807528 |
for k, v in new_data.items():
self[k] = v
return self | def update(self, new_data) | Update. | 4.054953 | 3.54855 | 1.142707 |
return [
ret
for key in DatastoreLegacy.store[self.domain].keys()
for ret in self.trigger_change_callbacks(key)
] | def trigger_all_change_callbacks(self) | Trigger all callbacks that were set with on_change(). | 12.631785 | 12.579635 | 1.004146 |
return DatastoreLegacy.store[self.domain].set(key, value) | def set(self, key, value) | Set value at key and return a Future
:rtype: tornado.concurrent.Future | 27.431213 | 41.321201 | 0.663853 |
for k, v in key_value_pairs.items():
if k not in DatastoreLegacy.store[self.domain]:
DatastoreLegacy.store[self.domain][k] = v | def init(self, key_value_pairs) | Initialize datastore.
Only sets values for keys that are not in the datastore already.
:param dict key_value_pairs:
A set of key value pairs to use to initialize the datastore. | 4.618185 | 4.838168 | 0.954532 |
# remove callbacks
DatastoreLegacy.datastores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and \
not DatastoreLegacy.datastores[self.domain]:
del DatastoreLegacy.store[self.domain]
del self | def close(self) | Close and delete instance. | 11.211892 | 9.921643 | 1.130044 |
if isinstance(node, list):
for i, item in enumerate(node):
AddIndex(item, index=i)
elif isinstance(node, dict):
if index is not None:
node['index'] = index
for key in node:
AddIndex(node[key]) | def AddIndex(node, index=None) | Recursively add the current index (with respect to a repeated section) in all
data dictionaries. | 2.037142 | 2.021252 | 1.007862 |
# Start with a clean build
sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG
handler = ShellCommandTrick(
shell_command='sphinx-build -b html docs docs/_build/html',
patterns=['*.rst', '*.py'],
ignore_patterns=['_build/*'],
ignore_directories=['.tox'],
... | def watch() | Renerate documentation when it changes. | 8.211439 | 7.719086 | 1.063784 |
docs_changelog = 'docs/changelog.rst'
check_git_unchanged(docs_changelog)
pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md')
if not skipdirhtml:
sphinx_build['-b', 'dirhtml', '-W', '-E', 'docs', 'docs/_build/dirhtml'] & FG
sphinx_build['-b', 'html', '-W'... | def gen(skipdirhtml=False) | Generate html and dirhtml output. | 3.263108 | 3.300584 | 0.988646 |
self.lhor.set_ydata(self.y_coord)
self.lver.set_xdata(self.x_coord) | def __reset_crosshair(self) | redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
------- | 5.016079 | 5.822164 | 0.861549 |
# clear the plot if lines have already been drawn on it
if len(self.ax2.lines) > 0:
self.ax2.cla()
# set up the vertical profile plot
self.ax2.set_ylabel(self.datalabel, fontsize=self.fontsize)
self.ax2.set_xlabel(self.spectrumlabel, fontsize=self.fontsize)
... | def __init_vertical_plot(self) | set up the vertical profile plot
Returns
------- | 3.62865 | 3.498466 | 1.037212 |
# only do something if the first plot has been clicked on
if event.inaxes == self.ax1:
# retrieve the click coordinates
self.x_coord = event.xdata
self.y_coord = event.ydata
# redraw the cross-hair
self.__rese... | def __onclick(self, event) | respond to mouse clicks in the plot.
This function responds to clicks on the first (horizontal slice) plot and updates the vertical profile and
slice plots
Parameters
----------
event: matplotlib.backend_bases.MouseEvent
the click event object containing image coordi... | 4.616687 | 4.450035 | 1.03745 |
def MoreFormatters(formatter_name):
for lookup_func in lookup_func_list:
formatter_func = lookup_func(formatter_name)
if formatter_func is not None:
return formatter_func
return MoreFormatters | def LookupChain(lookup_func_list) | Returns a *function* suitable for passing as the more_formatters argument
to Template.
NOTE: In Java, this would be implemented using the 'Composite' pattern. A
*list* of formatter lookup function behaves the same as a *single* formatter
lookup funcion.
Note the distinction between formatter *lookup* funct... | 3.332808 | 3.09363 | 1.077313 |
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None | def PythonPercentFormat(format_str) | Use Python % format strings as template format specifiers. | 5.254318 | 5.067223 | 1.036923 |
if format_str.startswith('plural?'):
i = len('plural?')
try:
splitchar = format_str[i] # Usually a space, but could be something else
_, plural_val, singular_val = format_str.split(splitchar)
except IndexError:
raise Error('plural? must have exactly 2 arguments')
def Formatter(... | def Plural(format_str) | Returns whether the value should be considered a plural value.
Integers greater than 1 are plural, and lists with length greater than one are
too. | 3.968748 | 3.774049 | 1.051589 |
bed = get_all_features(genome)
debug('Filtering BEDTool for high confidence CDS and stop codons')
return bed\
.filter(lambda r: r.fields[BedCols.FEATURE] in ['CDS', 'stop_codon'])\
.filter(high_confidence_filter)\
.merge() | def get_merged_cds(genome) | Returns all CDS merged, used:
- for TargQC general reports CDS coverage statistics for WGS
- for Seq2C CNV calling when no capture BED available | 9.386852 | 10.183663 | 0.921756 |
chrom = None
if genome:
if '-chr' in genome:
genome, chrom = genome.split('-')
check_genome(genome)
relative_path = relative_path.format(genome=genome)
path = abspath(join(dirname(__file__), relative_path))
if not isfile(path) and isfile(path + '.gz'):
p... | def _get(relative_path, genome=None) | :param relative_path: relative path of the file inside the repository
:param genome: genome name. Can contain chromosome name after comma, like hg19-chr20,
in case of BED, the returning BedTool will be with added filter.
:return: BedTools object if it's a BED file, or filepath | 2.994807 | 2.920733 | 1.025361 |
if output_fpath and reuse:
if verify_file(output_fpath, silent=True):
info(output_fpath + ' exists, reusing')
return output_fpath
if not output_fpath.endswith('.gz') and verify_file(output_fpath + '.gz', silent=True):
info(output_fpath + '.gz exists, reusing'... | def run(cmd, output_fpath=None, input_fpath=None, checks=None, stdout_to_outputfile=True,
stdout_tx=True, reuse=False, env_vars=None) | Run the provided command, logging details and checking for errors. | 2.080645 | 2.084521 | 0.99814 |
for s in samples:
if verify_file(s.qualimap_genome_results_fpath):
correction_is_needed = False
with open(s.qualimap_genome_results_fpath, 'r') as f:
content = f.readlines()
metrics_started = False
for line in content:
... | def _correct_qualimap_genome_results(samples) | fixing java.lang.Double.parseDouble error on entries like "6,082.49" | 2.302688 | 2.229791 | 1.032692 |
for s in samples:
qualimap1_dirname = dirname(s.qualimap_ins_size_hist_fpath).replace('raw_data_qualimapReport', 'raw_data')
qualimap2_dirname = dirname(s.qualimap_ins_size_hist_fpath)
if exists(qualimap1_dirname):
if not exists(qualimap2_dirname):
shutil.mov... | def _correct_qualimap_insert_size_histogram(work_dir, samples) | replacing Qualimap insert size histogram with Picard one. | 3.237432 | 3.122761 | 1.036721 |
assert len(vector) == 3
v = np.array(vector)
return v/np.sqrt(np.sum(v**2)) | def norm_vec(vector) | Normalize the length of a vector to one | 2.914351 | 2.81081 | 1.036837 |
axis = norm_vec(axis)
u, v, w = axis
points = np.array(points)
# Determine the rotational angle in the x-z plane
phi = np.arctan2(u, w)
# Determine the tilt angle w.r.t. the y-axis
theta = np.arccos(v)
# Negative rotation about y-axis
Rphi = np.array([
[np.cos(phi), 0, ... | def rotate_points_to_axis(points, axis) | Rotate all points of a list, such that `axis==[0,1,0]`
This is accomplished by rotating in the x-z-plane by phi into the
y-z-plane, then rotation in the y-z-plane by theta up to [0,1,0],
and finally rotating back in the x-z-plane by -phi.
Parameters
----------
points: list-like with elements o... | 1.835282 | 1.816902 | 1.010116 |
x, y, z = point
# azimuthal angle
phi = np.arctan2(x, z)
# angle in polar direction (negative)
theta = -np.arctan2(y, np.sqrt(x**2+z**2))
# Rotation in polar direction
Rtheta = np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0... | def rotation_matrix_from_point(point, ret_inv=False) | Compute rotation matrix to go from [0,0,1] to `point`.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for the correct 3D orientation
of the backpropagated projection... | 2.122168 | 2.152959 | 0.985698 |
# These matrices are correct if there is no tilt of the
# rotational axis within the detector plane (x-y).
D, Dinv = rotation_matrix_from_point(point, ret_inv=True)
# We need an additional rotation about the z-axis to correct
# for the tilt for all the the other cases.
angz = plane_angle
... | def rotation_matrix_from_point_planerot(point, plane_angle, ret_inv=False) | Compute rotation matrix to go from [0,0,1] to `point`,
while taking into account the tilted axis of rotation.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for the ... | 3.787329 | 3.866801 | 0.979448 |
'''
Given a set of file names, produce a list of names consisting of the
uniq parts of the names. This works from the end of the name. Chunks of
the name are split on '.' and '-'.
For example:
A.foo.bar.txt
B.foo.bar.txt
returns: ['A','B']
AA.BB.foo.txt
... | def filenames_to_uniq(names,new_delim='.') | Given a set of file names, produce a list of names consisting of the
uniq parts of the names. This works from the end of the name. Chunks of
the name are split on '.' and '-'.
For example:
A.foo.bar.txt
B.foo.bar.txt
returns: ['A','B']
AA.BB.foo.txt
CC.foo.... | 3.088448 | 1.850252 | 1.669204 |
if action_name == 'connect':
analysis.on_connect(self.executable, self.zmq_publish)
while not analysis.zmq_handshake:
yield tornado.gen.sleep(0.1)
log.debug('sending action {}'.format(action_name))
analysis.zmq_send({'signal': action_name, 'load': mess... | def run_process(self, analysis, action_name, message='__nomessagetoken__') | Executes an process in the analysis with the given message.
It also handles the start and stop signals in case a process_id
is given. | 6.285816 | 6.33702 | 0.99192 |
if check_staged(filename):
s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
return
else:
raise RuntimeError('There are staged changes in '
'{}, aborting.'.format(filename))... | def check_git_unchanged(filename, yes=False) | Check git to avoid overwriting user changes. | 2.145751 | 2.14105 | 1.002196 |
retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',
filename].run(retcode=None)
if retcode == 1:
return True
elif retcode == 0:
return False
else:
raise RuntimeError(stdout) | def check_staged(filename=None) | Check if there are 'changes to be committed' in the index. | 4.002914 | 3.819901 | 1.04791 |
if analysis is None:
return
# detect process_id
process_id = None
if isinstance(message, dict) and '__process_id' in message:
process_id = message['__process_id']
del message['__process_id']
if process_id:
yield analysis... | def run_process(analysis, action_name, message='__nomessagetoken__') | Executes an action in the analysis with the given message.
It also handles the start and stop signals in the case that message
is a `dict` with a key ``__process_id``.
:param str action_name: Name of the action to trigger.
:param message: Message.
:param callback:
A... | 2.817943 | 2.60458 | 1.081918 |
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
with dest.open('wb') as out:
while True:
data = r.read(chunk_size)
if data is None or len(data) == 0:
break
out.write(data)
r.release_conn(... | def dl_file(url, dest, chunk_size=6553) | Download `url` to `dest` | 1.911667 | 1.926583 | 0.992258 |
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpname = tempfile.mkstemp(prefix="odt_ex_", suffix=".tar")
with open(fd, "wb") as fo:
fo.write(data)
return tmpname | def extract_lzma(path) | Extract an lzma file and return the temporary file name | 4.214056 | 3.824746 | 1.101787 |
# download location
datapath = pathlib.Path(datapath)
datapath.mkdir(parents=True, exist_ok=True)
dlfile = datapath / fname
if not dlfile.exists():
print("Attempting to download file {} from {} to {}.".
format(fname, webloc, datapath))
try:
dl_file(url... | def get_file(fname, datapath=datapath) | Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository. | 3.52401 | 3.469384 | 1.015745 |
fname = get_file(fname)
if fname.suffix == ".lzma":
return load_tar_lzma_data(fname)
elif fname.suffix == ".zip":
return load_zip_data(fname, **kwargs) | def load_data(fname, **kwargs) | Load example data | 3.81051 | 3.701046 | 1.029576 |
tmpname = extract_lzma(tlfile)
# open tar file
fields_real = []
fields_imag = []
phantom = []
parms = {}
with tarfile.open(tmpname, "r") as t:
members = t.getmembers()
members.sort(key=lambda x: x.name)
for m in members:
n = m.name
f = ... | def load_tar_lzma_data(tlfile) | Load example sinogram data from a .tar.lzma file | 2.310694 | 2.234739 | 1.033988 |
ret = []
with zipfile.ZipFile(str(zipname)) as arc:
sino_real = np.loadtxt(arc.open(f_sino_real))
sino_imag = np.loadtxt(arc.open(f_sino_imag))
sino = sino_real + 1j * sino_imag
ret.append(sino)
if f_angles:
angles = np.loadtxt(arc.open(f_angles))
... | def load_zip_data(zipname, f_sino_real, f_sino_imag,
f_angles=None, f_phantom=None, f_info=None) | Load example sinogram data from a .zip file | 1.749365 | 1.76145 | 0.993139 |
def decor(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
out_file = kwargs.get("out_file", None)
if not out_file:
in_path = kwargs.get("in_file", args[0])
out_dir = kwargs.get("out_dir", os.path.dirname(in_path))
sa... | def transform_to(ext) | Decorator to create an output filename from an output filename with
the specified extension. Changes the extension, in_file is transformed
to a new type.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:... | 1.999738 | 1.939667 | 1.030969 |
def decor(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
out_file = kwargs.get("out_file", None)
if not out_file:
in_path = kwargs.get("in_file", args[0])
out_dir = kwargs.get("out_dir", os.path.dirname(in_path))
sa... | def filter_to(word) | Decorator to create an output filename from an input filename by
adding a word onto the stem. in_file is filtered by the function
and the results are written to out_file. You would want to use
this over transform_to if you don't know the extension of the file
going in. This also memoizes the output file... | 2.136138 | 1.974762 | 1.08172 |
cur_dir = os.getcwd()
safe_mkdir(new_dir)
os.chdir(new_dir)
try:
yield
finally:
os.chdir(cur_dir) | def chdir(new_dir) | Context manager to temporarily change to a new directory.
http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/ | 2.283473 | 2.390911 | 0.955064 |
try:
return (file_exists(fname) and file_exists(cmp_fname) and
getmtime(fname) >= getmtime(cmp_fname))
except OSError:
return False | def file_uptodate(fname, cmp_fname) | Check if a file exists, is non-empty and is more recent than cmp_fname. | 2.49649 | 2.467925 | 1.011575 |
if config["algorithm"].get("save_diskspace", False):
with open(fname, "w") as out_handle:
out_handle.write("File removed to save disk space: %s" % reason) | def save_diskspace(fname, reason, config) | Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message. | 4.645941 | 5.090936 | 0.912591 |
for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]:
if os.path.exists(orig + ext) and not os.path.lexists(new + ext):
with chdir(os.path.dirname(new)):
os.symlink(os.path.relpath(orig + ext), os.path.basename(new + ext))
orig_noext = splitext_plus(orig)[0]
new_noext = s... | def symlink_plus(orig, new) | Create relative symlinks and handle associated biological index files. | 2.003574 | 1.988358 | 1.007653 |
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = itertools.tee(iterable)
try:
return itertools.ifilterfalse(pred, t1), itertools.ifilter(pred, t2)
except:
return itertools.filterfalse(pre... | def partition(pred, iterable) | Use a predicate to partition entries into false entries and true entries | 2.227046 | 2.294039 | 0.970797 |
result = reduce(lambda d, t: d.get(t, {}), t, d)
if not result:
return default
else:
return result | def get_in(d, t, default=None) | look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {} | 3.552072 | 3.825726 | 0.92847 |
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, ... | def which(program) | returns the path to an executable or None if it can't be found | 1.351934 | 1.365007 | 0.990423 |
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif not 'HOMEPATH' in os.enviro... | def expanduser(path) | Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing. | 2.279815 | 2.238965 | 1.018245 |
base, ext = splitext(fname)
if ext in [".gz", ".bz2", ".zip"]:
base, ext2 = splitext(base)
ext = ext2 + ext
return base, ext | def splitext_plus(fname) | Split on file extensions, allowing for zipped extensions. | 1.933161 | 2.129116 | 0.907964 |
def proc_line(l, i):
while '\t\t' in l:
l = l.replace('\t\t', '\t.\t')
return l
return iterate_file(config, tsv_fpath, proc_line, suffix='dots') | def dots_to_empty_cells(config, tsv_fpath) | Put dots instead of empty cells in order to view TSV with column -t | 5.419193 | 5.296583 | 1.023149 |
exts = {".vcf": ".idx", ".bam": ".bai", "vcf.gz": ".tbi"}
safe_fpaths, orig_names = _flatten_plus_safe(work_dir, rollback_files)
__remove_files(safe_fpaths) # remove any half-finished transactions
try:
if len(safe_fpaths) == 1:
yield safe_fpaths[0]
else:
yie... | def file_transaction(work_dir, *rollback_files) | Wrap file generation in a transaction, moving to output if finishes. | 3.83841 | 3.728016 | 1.029612 |
# tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4()))
# unique_attempts = 0
# while os.path.exists(tmp_dir_base):
# if unique_attempts > 5:
# break
# tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4()))
# time.sleep(1)
# unique_attempts += 1
# if ba... | def tx_tmpdir(base_dir, rollback_dirpath) | Context manager to create and remove a transactional temporary directory. | 2.194949 | 2.212333 | 0.992142 |
tx_fpaths, orig_files = [], []
for fnames in rollback_files:
if isinstance(fnames, six.string_types):
fnames = [fnames]
for fname in fnames:
tx_file = fname + '.tx'
tx_fpath = join(tmp_dir, tx_file) if tmp_dir else tx_file
tx_fpaths.append(tx_... | def _flatten_plus_safe(tmp_dir, rollback_files) | Flatten names of files and create temporary file names. | 2.430621 | 2.387713 | 1.01797 |
output_fpath = intermediate_fname(work_dir, bed_fpath, 'merged')
if isfile(output_fpath) and verify_file(output_fpath, cmp_f=bed_fpath):
return output_fpath
with file_transaction(work_dir, output_fpath) as tx:
kwargs = dict(d=distance) if distance else dict()
BedTool(bed_fpath)... | def merge_overlaps(work_dir, bed_fpath, distance=None) | Merge bed file intervals to avoid overlapping regions.
Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes
that don't collapse BEDs prior to using them. | 3.104748 | 3.140819 | 0.988516 |
fd = open_gzipsafe(self.filename)
line = fd.readline()
while line.startswith('#'):
line = fd.readline()
fields = line.split('\t')
lc = 1
error = ''
# Checks that the two columns on the right contain integer values
try:
... | def checkformat(self) | ************************************************************************************************************************************************************
Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separated columns, the
two on... | 4.387856 | 3.396078 | 1.292036 |
return [ret
for key in self
for ret in self.trigger_callbacks(key, callbacks=None)] | def trigger_all_callbacks(self, callbacks=None) | Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future] | 13.841007 | 9.655328 | 1.43351 |
value_encoded = encode(value)
if key in self.data and self.data[key] == value_encoded:
return []
self.data[key] = value_encoded
return self.trigger_callbacks(key) | def set(self, key, value) | Set a value at key and return a Future.
:rtype: Iterable[tornado.concurrent.Future] | 4.016093 | 4.270757 | 0.94037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.