code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
key = self.get_upload_key()
metadata = key.metadata.copy()
# Some http header properties which are stored on the key need to be
# copied to the metadata when updating
headers = {
# http header name, key attribute name
'Cache-Control': 'cache_cont... | def get_upload_key_metadata(self) | Generate metadata dictionary from a bucket key. | 3.466664 | 3.410754 | 1.016392 |
location = self.get_storage().location
return self.cleaned_data['key_name'][len(location):] | def get_upload_path(self) | Returns the uploaded file path from the storage backend.
:returns: File path from the storage backend.
:rtype: :py:class:`unicode` | 9.401159 | 11.245252 | 0.836011 |
"Return the answer"
answer = raw_input(question)
if escape:
answer.replace('"', '\\"')
return answer.decode('utf') | def ask(question, escape=True) | Return the answer | 6.398364 | 6.390926 | 1.001164 |
self.use_cached_state = cache
endpoint = API_SESAME_ENDPOINT.format(self._device_id)
response = self.account.request('GET', endpoint)
if response is None or response.status_code != 200:
return
state = json.loads(response.text)
self._nickname = state... | def update_state(self, cache=True) | Update the internal state of the Sesame. | 4.241177 | 3.762033 | 1.127363 |
endpoint = API_SESAME_CONTROL_ENDPOINT.format(self.device_id)
payload = {'type': 'lock'}
response = self.account.request('POST', endpoint, payload=payload)
if response is None:
return False
if response.status_code == 200 or response.status_code == 204:
... | def lock(self) | Lock the Sesame. Return True on success, else False. | 3.91355 | 3.212659 | 1.218166 |
for server, conf in self.servers.iteritems():
self._add_index_server()
for conf_k, conf_v in conf.iteritems():
if not self.conf.has_section(server):
self.conf.add_section(server)
self.conf.set(server, conf_k, conf_v)
w... | def save(self) | Saves pypirc file with new configuration information. | 2.88752 | 2.676049 | 1.079024 |
idx_srvs = []
if 'index-servers' in self.conf.options('distutils'):
idx = self.conf.get('distutils', 'index-servers')
idx_srvs = [srv.strip() for srv in idx.split('\n') if srv.strip()]
return idx_srvs | def _get_index_servers(self) | Gets index-servers current configured in pypirc. | 3.456998 | 2.807603 | 1.231299 |
index_servers = '\n\t'.join(self.servers.keys())
self.conf.set('distutils', 'index-servers', index_servers) | def _add_index_server(self) | Adds index-server to 'distutil's 'index-servers' param. | 7.078042 | 4.579818 | 1.545485 |
if isinstance(data, list):
for item in data:
self.outputmap(item)
elif isinstance(data, dict):
for map_target in self.output_map:
if map_target in data:
data[map_target] = getattr(self, self.output_map[map_target])(data... | def outputmap(self, data) | Internal function used to traverse a data structure and map the contents onto python-friendly objects inplace.
This uses recursion, so try not to pass in anything that's over 255 objects deep.
:param data: data structure
:type data: any
:param prefix: endpoint family, e... | 2.249099 | 2.394012 | 0.939469 |
def TCA_select(bus, addr, channel):
if addr < 0x70 or addr > 0x77:
print("The TCA address(" + str(addr) + ") is invalid. Aborting")
return False
if channel == "off":
bus.write_byte(addr, 0)
elif channel < 0 or channel > 3:
print("The requested channel does not ex... | This function will write to the control register of the
TCA module to select the channel that will be
exposed on the TCA module.
After doing this, the desired module can be used as it would be normally.
(The caller should use the address of the I2C sensor modu... | null | null | null | |
def get_ADC_value(bus, addr, channel):
if channel == 1:
INIT = 0b10000000
elif channel == 2:
INIT = 0b10100000
elif channel == 3:
INIT = 0b11000000
elif channel == 4:
INIT = 0b11100000
bus.write_byte(addr, INIT)
data = bus.read_i2c_block_data(addr,... | This method selects a channel and initiates conversion
The ADC operates at 240 SPS (12 bits) with 1x gain
One shot conversions are used, meaning a wait period is needed
in order to acquire new data. This is done via a constant poll
of the ready bit.
Upon completion, a voltage value ... | null | null | null | |
def IO_expander_output(bus, addr, bank, mask):
IODIR_map = [0x00, 0x01]
output_map = [0x14, 0x15]
if (bank != 0) and (bank != 1):
print()
raise InvalidIOUsage("An invalid IO bank has been selected")
IO_direction = IODIR_map[bank]
output_reg = output_map[bank]
... | Method for controlling the GPIO expander via I2C
which accepts a bank - A(0) or B(1) and a mask
to push to the pins of the expander.
The method also assumes the the expander is operating
in sequential mode. If this mode is not used,
the register addresses will need to be chang... | null | null | null | |
def get_IO_reg(bus, addr, bank):
output_map = [0x14, 0x15]
if (bank != 0) and (bank != 1):
print()
raise InvalidIOUsage("An invalid IO bank has been selected")
output_reg = output_map[bank]
current_status = bus.read_byte_data(addr, output_reg)
return current_status | Method retrieves the register corresponding to respective bank (0 or 1) | null | null | null | |
def import_i2c_addr(bus, opt="sensors"):
i2c_list = []
for device in range(128):
try:
bus.read_byte(device)
i2c_list.append((device))
except IOError:
pass
if opt == "sensors":
sensor_list = []
for module in range(112,120... | import_i2c_addresses will return a list of the
currently connected I2C devices.
This can be used a means to automatically detect
the number of connected sensor modules.
Modules are between int(112) and int(119)
By default, the method will return a list
... | null | null | null | |
temp_dir = "/tmp/"
filename = "gtts.mp3"
file_path = "{}/{}".format(temp_dir, filename)
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
def delete_file():
try:
os.remove(file_path)
if not os.listdir(temp_di... | def speak(self, sentence) | Speak a sentence using Google TTS.
:param sentence: the sentence to speak. | 2.442757 | 2.459357 | 0.99325 |
def get_lux_count(lux_byte):
LUX_VALID_MASK = 0b10000000
LUX_CHORD_MASK = 0b01110000
LUX_STEP_MASK = 0b00001111
valid = lux_byte & LUX_VALID_MASK
if valid != 0:
step_num = (lux_byte & LUX_STEP_MASK)
# Shift to normalize value
chord_num = (lux_byte & LUX_CHORD_MA... | Method to convert data from the TSL2550D lux sensor
into more easily usable ADC count values. | null | null | null | |
def update_lux(self, extend=0):
DEVICE_REG_OUT = 0x1d
LUX_PWR_ON = 0x03
if extend == 1:
LUX_MODE = 0x1d
delay = .08
scale = 5
else:
LUX_MODE = 0x18
delay = .4
scale = 1
LUX_READ_CH0 = 0x4... | Communicates with the TSL2550D light sensor and returns a
lux value.
Note that this method contains approximately 1 second of total delay.
This delay is necessary in order to obtain full resolution
compensated lux values.
Alternatively, the device could be ... | null | null | null | |
def update_humidity_temp(self):
# Create mask for STATUS (first two bits of 64 bit wide result)
STATUS = 0b11 << 6
TCA_select(SensorCluster.bus, self.mux_addr, SensorCluster.humidity_chan)
SensorCluster.bus.write_quick(SensorCluster.humidity_addr) # Begin conversion
... | This method utilizes the HIH7xxx sensor to read
humidity and temperature in one call. | null | null | null | |
def update_soil_moisture(self):
SensorCluster.analog_sensor_power(SensorCluster.bus, "on") # turn on sensor
sleep(.2)
TCA_select(SensorCluster.bus, self.mux_addr, SensorCluster.adc_chan)
moisture = get_ADC_value(
SensorCluster.bus, SensorCluster.adc_addr, Sens... | Method will select the ADC module,
turn on the analog sensor, wait for voltage settle,
and then digitize the sensor voltage.
Voltage division/signal loss is accounted for by
scaling up the sensor output.
This may need to be adjusted if ... | null | null | null | |
def update_instance_sensors(self, opt=None):
self.update_count += 1
self.update_lux()
self.update_humidity_temp()
if opt == "all":
try:
self.update_soil_moisture()
except SensorError:
# This could be handled with... | Method runs through all sensor modules and updates
to the latest sensor values.
After running through each sensor module,
The sensor head (the I2C multiplexer), is disabled
in order to avoid address conflicts.
Usage:
plant_sensor_object.updateAllSensors(bus... | null | null | null | |
def sensor_values(self):
self.update_instance_sensors(opt="all")
return {
"light": self.lux,
"water": self.soil_moisture,
"humidity": self.humidity,
"temperature": self.temp
} | Returns the values of all sensors for this cluster | null | null | null | |
def analog_sensor_power(cls, bus, operation):
# Set appropriate analog sensor power bit in GPIO mask
# using the ControlCluster bank_mask to avoid overwriting any data
reg_data = get_IO_reg(bus, 0x20, cls.power_bank)
if operation == "on":
reg_data = reg_data ... | Method that turns on all of the analog sensor modules
Includes all attached soil moisture sensors
Note that all of the SensorCluster object should be attached
in parallel and only 1 GPIO pin is available
to toggle analog sensor power.
The sensor p... | null | null | null | |
def get_water_level(cls):
# ----------
# These values should be updated based on the real system parameters
vref = 4.95
tank_height = 17.5 # in centimeters (height of container)
rref = 2668 # Reference resistor
# ----------
val = 0
for i... | This method uses the ADC on the control module to measure
the current water tank level and returns the water volume
remaining in the tank.
For this method, it is assumed that a simple voltage divider
is used to interface the sensor to the ADC module.
... | null | null | null | |
module_name, symbol_name = import_path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, symbol_name) | def _imported_symbol(import_path) | Resolve a dotted path into a symbol, and return that.
For example...
>>> _imported_symbol('django.db.models.Model')
<class 'django.db.models.base.Model'>
Raise ImportError if there's no such module, AttributeError if no
such symbol. | 2.163607 | 2.302886 | 0.939519 |
# We use locals() to allow concise looping over the arguments.
atts = locals()
atts.pop('ac')
temp_dict = {}
temp_dict.update(atts)
for k in temp_dict.keys():
if atts[k] is None:
del atts[k]
if (ac
and value is not None
and (not isinstance(value, stri... | def Param(name, value=None, unit=None, ucd=None, dataType=None, utype=None,
ac=True) | 'Parameter', used as a general purpose key-value entry in the 'What' section.
May be assembled into a :class:`Group`.
NB ``name`` is not mandated by schema, but *is* mandated in full spec.
Args:
value(str): String representing parameter value.
Or, if ``ac`` is true, then 'autoconversi... | 4.642856 | 4.030658 | 1.151885 |
atts = {}
if name:
atts['name'] = name
if type:
atts['type'] = type
g = objectify.Element('Group', attrib=atts)
for p in params:
g.append(p)
return g | def Group(params, name=None, type=None) | Groups together Params for adding under the 'What' section.
Args:
params(list of :func:`Param`): Parameter elements to go in this group.
name(str): Group name. NB ``None`` is valid, since the group may be
best identified by its type.
type(str): Type of group, e.g. 'complex' (for... | 2.575879 | 3.426387 | 0.751777 |
attrib = {'uri': uri}
if meaning is not None:
attrib['meaning'] = meaning
return objectify.Element('Reference', attrib) | def Reference(uri, meaning=None) | Represents external information, typically original obs data and metadata.
Args:
uri(str): Uniform resource identifier for external data, e.g. FITS file.
meaning(str): The nature of the document referenced, e.g. what
instrument and filter was used to create the data? | 3.682629 | 5.636075 | 0.653403 |
atts = {}
if probability is not None:
atts['probability'] = str(probability)
if relation is not None:
atts['relation'] = relation
inf = objectify.Element('Inference', attrib=atts)
if name is not None:
inf.Name = name
if concept is not None:
inf.Concept = conc... | def Inference(probability=None, relation=None, name=None, concept=None) | Represents a probable cause / relation between this event and some prior.
Args:
probability(float): Value 0.0 to 1.0.
relation(str): e.g. 'associated' or 'identified' (see Voevent spec)
name(str): e.g. name of identified progenitor.
concept(str): One of a 'formal UCD-like vocabulary... | 2.351959 | 2.83955 | 0.828286 |
# This is an ugly hack around the limitations of the lxml.objectify API:
c = objectify.StringElement(cite=cite_type)
c._setText(ivorn)
c.tag = "EventIVORN"
return c | def EventIvorn(ivorn, cite_type) | Used to cite earlier VOEvents.
Use in conjunction with :func:`.add_citations`
Args:
ivorn(str): It is assumed this will be copied verbatim from elsewhere,
and so these should have any prefix (e.g. 'ivo://','http://')
already in place - the function will not alter the value.
... | 12.629461 | 14.779102 | 0.854549 |
import warnings
warnings.warn(
,
FutureWarning)
return EventIvorn(ivorn, cite_type) | def Citation(ivorn, cite_type) | Deprecated alias of :func:`.EventIvorn` | 15.440608 | 5.31753 | 2.903718 |
if type(data) is not list or type(data[0]) is not dict:
raise BadRequest("Ingestion data must be a list of dicts")
data = "\r\n".join(map(json.dumps, data))
return self.request.post(source_id, data, {'Accept-Encoding': 'application/text'}) | def batch(self, source_id, data) | Upload data to the given soruce
:param source_id: The ID of the source to upload to
:type source_id: str
:param data: The data to upload to the source
:type data: list
:return: dict of REST API output with headers attached
:rtype: :class:`~datasif... | 4.435187 | 4.336704 | 1.022709 |
try:
PackageVersion(requirement=requirement).save()
logger.info("Package '%s' added.", requirement.name) # noqa
except IntegrityError:
logger.info("Package '%s' already exists.", requirement.name) | def create_package_version(requirement) | Create a new PackageVersion from a requirement. Handles errors. | 3.448628 | 3.149157 | 1.095096 |
logger.info("Loading requirements from local file.")
with open(REQUIREMENTS_FILE, 'r') as f:
requirements = parse(f)
for r in requirements:
logger.debug("Creating new package: %r", r)
create_package_version(r) | def local() | Load local requirements file. | 5.4092 | 4.596227 | 1.176878 |
logger.info("Fetching latest data from PyPI.")
results = defaultdict(list)
packages = PackageVersion.objects.exclude(is_editable=True)
for pv in packages:
pv.update_from_pypi()
results[pv.diff_status].append(pv)
logger.debug("Updated package from PyPI: %r", pv)
results['... | def remote() | Update package info from PyPI. | 6.951547 | 5.834413 | 1.191473 |
if options['clean']:
clean()
if options['local']:
local()
if options['remote']:
results = remote()
render = lambda t: render_to_string(t, results)
if options['notify']:
send_mail(
options['... | def handle(self, *args, **options) | Run the managemement command. | 3.594761 | 3.476853 | 1.033912 |
if len(sources) == 0:
raise HistoricSourcesRequired()
if isinstance(sources, six.string_types):
sources = [sources]
params = {'hash': stream, 'start': start, 'sources': ','.join(sources), 'parameters': ','.join(parameters)}
if end:
params['end... | def create(self, stream, start, parameters, sources, end=None) | Create a hitorics preview job.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/previewcreate
:param stream: hash of the CSDL filter to create the job for
:type stream: str
:param start: Unix timestamp for the start of the period
:t... | 3.642062 | 2.555511 | 1.42518 |
return self.request.get('get', params=dict(id=preview_id)) | def get(self, preview_id) | Retrieve a Historics preview job.
Warning: previews expire after 24 hours.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/previewget
:param preview_id: historics preview job hash of the job to retrieve
:type preview_id: str
:retu... | 9.385729 | 13.840691 | 0.678126 |
if len(sources) == 0:
raise HistoricSourcesRequired()
if not isinstance(sources, list):
sources = [sources]
params = {'hash': hash, 'start': start, 'end': end, 'name': name, 'sources': ','.join(sources)}
if sample:
params['sample'] = sample
... | def prepare(self, hash, start, end, name, sources, sample=None) | Prepare a historics query which can later be started.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsprepare
:param hash: The hash of a CSDL create the query for
:type hash: str
:param start: when to start querying data from - unix t... | 2.951638 | 2.316285 | 1.274298 |
return self.request.post('start', data=dict(id=historics_id)) | def start(self, historics_id) | Start the historics job with the given ID.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstart
:param historics_id: hash of the job to start
:type historics_id: str
:return: dict of REST API output with headers attached
... | 5.350845 | 9.922952 | 0.539239 |
return self.request.post('update', data=dict(id=historics_id, name=name)) | def update(self, historics_id, name) | Update the name of the given Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsupdate
:param historics_id: playback id of the job to start
:type historics_id: str
:param name: new name of the stream
:type na... | 4.249359 | 7.229086 | 0.587814 |
return self.request.post('stop', data=dict(id=historics_id, reason=reason)) | def stop(self, historics_id, reason='') | Stop an existing Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstop
:param historics_id: playback id of the job to stop
:type historics_id: str
:param reason: optional reason for stopping the job
:type r... | 4.205396 | 7.029219 | 0.598274 |
params = {'start': start, 'end': end}
if sources:
params['sources'] = ','.join(sources)
return self.request.get('status', params=params) | def status(self, start, end, sources=None) | Check the data coverage in the Historics archive for a given interval.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstatus
:param start: Unix timestamp for the start time
:type start: int
:param end: Unix timestamp for the start ti... | 2.529153 | 2.727988 | 0.927113 |
return self.request.post('delete', data=dict(id=historics_id)) | def delete(self, historics_id) | Delete one specified playback query. If the query is currently running, stop it.
status_code is set to 204 on success
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsdelete
:param historics_id: playback id of the query to delete
:typ... | 5.516772 | 10.170985 | 0.542403 |
return self.get(historics_id, maximum=None, page=None, with_estimate=with_estimate) | def get_for(self, historics_id, with_estimate=None) | Get the historic query for the given ID
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: playback id of the query
:type historics_id: str
:return: dict of REST API output with headers attached
:rtyp... | 5.688232 | 8.560269 | 0.664492 |
params = {'id': historics_id}
if maximum:
params['max'] = maximum
if page:
params['page'] = page
params['with_estimate'] = 1 if with_estimate else 0
return self.request.get('get', params=params) | def get(self, historics_id=None, maximum=None, page=None, with_estimate=None) | Get the historics query with the given ID, if no ID is provided then get a list of historics queries.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: (optional) ID of the query to retrieve
:type historics_id: str
... | 2.696711 | 3.207363 | 0.840788 |
params = {"id": historics_id}
if reason != "":
params["reason"] = reason
return self.request.post('pause', data=params) | def pause(self, historics_id, reason="") | Pause an existing Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicspause
:param historics_id: id of the job to pause
:type historics_id: str
:param reason: optional reason for pausing it
:type reason: str
... | 3.314003 | 4.282784 | 0.773796 |
return self.request.post('resume', data=dict(id=historics_id)) | def resume(self, historics_id) | Resume a paused Historics query.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsresume
:param historics_id: id of the job to resume
:type historics_id: str
:return: dict of REST API output with headers attached
:rtype: :c... | 5.220184 | 9.743755 | 0.535747 |
params = {'id': source_id, 'resource_ids': resource_ids}
return self.request.post('remove', params) | def remove(self, source_id, resource_ids) | Remove one or more resources from a Managed Source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceresourceremove
:param source_id: target Source ID
:type source_id: str
:param resources: An array of the resource IDs that you would like ... | 4.33533 | 5.484514 | 0.790468 |
params = {'id': source_id, 'auth': auth, 'validate': validate}
return self.request.post('add', params) | def add(self, source_id, auth, validate=True) | Add one or more sets of authorization credentials to a Managed Source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceauthadd
:param source_id: target Source ID
:type source_id: str
:param auth: An array of the source-specific authorizat... | 3.892887 | 5.341056 | 0.728861 |
params = {'id': source_id, 'auth_ids': auth_ids}
return self.request.post('remove', params) | def remove(self, source_id, auth_ids) | Remove one or more sets of authorization credentials from a Managed Source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceauthremove
:param source_id: target Source ID
:type source_id: str
:param resources: An array of the authorization... | 4.124299 | 6.147794 | 0.670858 |
assert resources, "Need at least one resource"
params = {
'source_type': source_type,
'name': name,
'resources': resources,
'validate': validate
}
if auth:
params['auth'] = auth
if parameters:
para... | def create(self, source_type, name, resources, auth=None, parameters=None, validate=True) | Create a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourcecreate
:param source_type: data source name e.g. facebook_page, googleplus, instagram, yammer
:type source_type: str
:param name: name to use to identify the managed... | 2.501861 | 2.639259 | 0.947941 |
assert resources, "Need at least one resource"
assert auth, "Need at least one authentication token"
params = {'id': source_id, 'source_type': source_type, 'name': name, 'resources': resources, 'auth': auth, 'validate': validate}
if parameters:
params['parameters'] =... | def update(self, source_id, source_type, name, resources, auth, parameters=None, validate=True) | Update a managed source
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceupdate
:param source_type: data source name e.g. facebook_page, googleplus, instagram, yammer
:type source_type: str
:param name: name to use to identify the managed... | 2.923738 | 3.096849 | 0.944101 |
params = {'id': source_id}
if page:
params['page'] = page
if per_page:
params['per_page'] = per_page
return self.request.get('log', params=params) | def log(self, source_id, page=None, per_page=None) | Get the log for a specific Managed Source.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourcelog
:param source_id: target Source ID
:type source_id: str
:param page: (optional) page number for pagination
:type page: int
... | 2.262742 | 2.531361 | 0.893883 |
params = {}
if source_type:
params['source_type'] = source_type
if source_id:
params['id'] = source_id
if page:
params['page'] = page
if per_page:
params['per_page'] = per_page
return self.request.get('get', params... | def get(self, source_id=None, source_type=None, page=None, per_page=None) | Get a specific managed source or a list of them.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/sourceget
:param source_id: (optional) target Source ID
:type source_id: str
:param source_type: (optional) data source name e.g. facebook_page, g... | 1.815611 | 1.996904 | 0.909213 |
# input dist array
inp = gdaZeros(localArray.shape, localArray.dtype, numGhosts=1)
# output array
out = numpy.zeros(localArray.shape, localArray.dtype)
# no displacement term
weight = self.stencil[self.zeros]
out[...] += weight * localArray
for... | def apply(self, localArray) | Apply Laplacian stencil to data
@param localArray local array
@return new array on local proc | 6.724842 | 6.47136 | 1.03917 |
self.user_id = user_id
self.password = password
if self.user_id == None or self.password == None:
print "[*] Error __init__: user_id and password is needed"
return False
try:
cookie = naver_login(user_id, password)
except:
... | def login(self, user_id, password, svctype = "Android NDrive App ver", auth = 0) | Log in Naver and get cookie
Agrs:
user_id: Naver account's login id
password: Naver account's login password
Returns:
True: Login success
False: Login failed
Remarks:
self.cookie is a dictionary with 5 keys: path, domain, NID_AUT, ni... | 3.438607 | 3.063054 | 1.122608 |
data = {'userid': self.user_id, 'svctype': svctype, 'auth': auth}
r = self.session.get(nurls['getRegisterUserInfo'], params = data)
j = json.loads(r.text)
if j['message'] != 'success':
print "[*] Error getRegisterUserInfo: " + j['message']
return False
... | def getRegisterUserInfo(self, svctype = "Android NDrive App ver", auth = 0) | Get registerUserInfo
Args:
svctype: Platform information
auth: ???
Returns:
True: Success
False: Failed | 4.105784 | 4.555512 | 0.901278 |
checkAccount()
data = {'userid': self.user_id,
'useridx': self.useridx
}
r = self.session.post(nurls['checkStatus'], data = data)
p = re.compile(r'\<message\>(?P<message>.+)\</message\>')
message = p.search(r.text).group('message')
... | def checkStatus(self) | Check status
Args:
Returns:
True: Sucess
False: Failed | 4.44083 | 4.716929 | 0.941466 |
s = self.checkStatus()
s = self.getDiskSpace()
s = self.checkUpload(file_path, upload_path, overwrite)
if s is True:
self.put(file_path, upload_path) | def uploadFile(self, file_path, upload_path = '', overwrite = False) | uploadFile
Remarks:
How Ndrive uploads a file to its server:
1. POST /CheckStatus.ndrive
2. POST /GetDiskSpace.ndrive
3. POST /CheckUpload.ndrive
4. PUT /FILE_PATH
5. POST /GetList.ndrive
6. POST /GetWas... | 4.811848 | 3.351126 | 1.43589 |
self.checkAccount()
url = nurls['checkUpload']
file_size = os.stat(file_path).st_size
file_name = os.path.basename(file_path)
now = datetime.datetime.now().isoformat()
data = {'userid': self.user_id,
'useridx': self.useridx,
'... | def getDiskSpace(self, file_path, upload_path = '', overwrite = False) | getDiskSpace
Args:
file_path: Full path for a file you want to checkUpload
upload_path: Ndrive path where you want to upload file
ex) /Picture/
Returns:
True: Possible to upload a file with a given file_size
False: Impossible to upload a ... | 4.583259 | 4.569966 | 1.002909 |
f = open(file_path, "r")
c = f.read()
file_name = os.path.basename(file_path)
now = datetime.datetime.now().isoformat()
url = nurls['put'] + upload_path + file_name
headers = {'userid': self.user_id,
'useridx': self.useridx,
... | def put(self, file_path, upload_path = '') | PUT
Args:
file_path: Full path for a file you want to upload
upload_path: Ndrive path where you want to upload file
ex) /Picture/
Returns:
True: Upload success
False: Upload failed | 4.377855 | 4.194883 | 1.043618 |
now = datetime.datetime.now().isoformat()
url = nurls['put'] + upload_path + file_name
headers = {'userid': self.user_id,
'useridx': self.useridx,
'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
'charset': 'UT... | def delete(self, file_path) | DELETE
Args:
file_path: Full path for a file you want to delete
upload_path: Ndrive path where you want to delete file
ex) /Picture/
Returns:
True: Delete success
False: Delete failed | 5.955524 | 5.337799 | 1.115727 |
url = nurls['getList']
data = {'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
'orgresource': orgresource,
'type': type,
'dept': dept,
'sort': sort,
'order'... | def getList(self, dummy = 56184, orgresource = '/', type = 1, dept = 0, sort = 'name', order = 'asc', startnum = 0, pagingrow = 1000) | GetList
Args:
dummy: ???
orgresource: Directory path to get the file list
ex) /Picture/
type: 1 => only directories with idxfolder property
2 => only files
3 => directories and files with thumbnail info
... | 3.088771 | 2.875021 | 1.074347 |
url = nurls['doMove']
data = {'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
'orgresource': orgresource,
'dstresource': dstresource,
'overwrite': overwrite,
'bShareFireCop... | def doMove(self, orgresource, dstresource, dummy = 56184, stresource = 'F', bShareFireCopy = 'false') | DoMove
Args:
dummy: ???
orgresource: Path for a file which you want to move
dstresource: Destination path
bShareFireCopy: ???
Returns:
True: Move success
False: Move failed | 5.384171 | 5.140364 | 1.04743 |
url = nurls['getProperty']
data = {'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
'orgresource': orgresource,
}
r = self.session.post(url = url, data = data)
j = json.loads(r.text)
if s... | def getProperty(self, orgresource, dummy = 56184) | GetProperty
Args:
dummy: ???
orgresource: File path
Returns:
FileInfo object:
False: Failed to get property | 5.035054 | 4.291474 | 1.173269 |
url = nurls['getVersionListCount']
data = {'userid': self.user_id,
'useridx': self.useridx,
'orgresource': orgresource,
}
r = self.session.post(url = url, data = data)
j = json.loads(r.text)
if j['message'] != 'success'... | def getVersionListCount(self, orgresource) | GetVersionListCount
Args:
orgresource: File path
Returns:
Integer number: # of version list
False: Failed to get property | 4.07798 | 4.044256 | 1.008339 |
url = nurls['setProperty']
data = {'userid': self.user_id,
'useridx': self.useridx,
'orgresource': orgresource,
'protect': protect,
'dummy': dummy,
}
r = self.session.post(url = url, data = data)
... | def setProperty(self, orgresource, protect, dummy = 7046) | SetProperty
Args:
orgresource: File path
protect: 'Y' or 'N', 중요 표시
Returns:
Integer number: # of version list
False: Failed to get property | 4.977774 | 4.47219 | 1.11305 |
url = nurls['setProperty']
data = {'userid': self.user_id,
'useridx': self.useridx,
'tagtype': tagtype,
'startnum': startnum,
'pagingrow': pagingrow,
}
r = self.session.post(url = url, data = data)
... | def getMusicAlbumList(self, tagtype = 0, startnum = 0, pagingrow = 100) | GetMusicAlbumList
Args:
tagtype = ???
startnum
pagingrow
Returns:
???
False: Failed to get property | 4.563292 | 4.470162 | 1.020834 |
j = json.loads(text)
if j['message'] != 'success':
print "[*] Error : " + j['message']
return False
else:
return True | def resultManager(self, text) | resultcode & message:
0 = success => if "resultvalue" = null: no result to show
11 = Not Exist Path
36 = File Infomation Not Found
2002 = Invalidation Cookie | 4.974178 | 5.559145 | 0.894774 |
manager.database.update(
connection=connection,
force_download=force_download
) | def update(connection, force_download) | Update the database | 6.043935 | 5.487413 | 1.101418 |
manager.database.set_mysql_connection(
host=host,
user=user,
password=password,
db=db,
charset=charset
) | def set_mysql(host, user, password, db, charset) | Set the SQLAlchemy connection string with MySQL settings | 2.935764 | 2.91445 | 1.007313 |
"Main program"
generators = check_dependencies()
args = docopt(__doc__, version='md2ebook 0.0.1-dev')
commander = Commander(args, generators)
commander.handle() | def main() | Main program | 9.98318 | 9.029641 | 1.105601 |
from scipy.stats import norm, rankdata
x = asarray(x, float).copy()
ok = isfinite(x)
x[ok] *= -1
y = empty_like(x)
y[ok] = rankdata(x[ok])
y[ok] = norm.isf(y[ok] / (sum(ok) + 1))
y[~ok] = x[~ok]
return y | def quantile_gaussianize(x) | Normalize a sequence of values via rank and Normal c.d.f.
Args:
x (array_like): sequence of values.
Returns:
Gaussian-normalized values.
Example:
.. doctest::
>>> from scipy_sugar.stats import quantile_gaussianize
>>> print(quantile_gaussianize([-1, 0, 2]))
[... | 3.427001 | 4.080091 | 0.839933 |
noise = noise_generator.generate(self.labels, split_idx)
for dim, noise_value in zip(self, noise):
dim.chemshift = round(dim.chemshift + noise_value, ndigits) | def apply_noise(self, noise_generator, split_idx, ndigits=6) | Apply noise to dimensions within a peak.
:param noise_generator: Noise generator object.
:param int split_idx: Index specifying which peak list split parameters to use.
:return: None
:rtype: :py:obj:`None` | 5.921822 | 6.576897 | 0.900397 |
sparky_str = "Assignment\t\t{}\n\n".format("\t\t".join(["w" + str(i + 1) for i in range(len(self.labels))]))
for peak in self:
assignment_str = "-".join(peak.assignments_list)
dimensions_str = "\t\t".join([str(chemshift) for chemshift in peak.chemshifts_list])
... | def _to_sparky(self) | Save :class:`~nmrstarlib.plsimulator.PeakList` into Sparky-formatted string.
:return: Peak list representation in Sparky format.
:rtype: :py:class:`str` | 4.442085 | 3.986256 | 1.11435 |
autoassign_str = "#Index\t\t{}\t\tIntensity\t\tWorkbook\n".format(
"\t\t".join([str(i + 1) + "Dim" for i in range(len(self.labels))]))
for peak_idx, peak in enumerate(self):
dimensions_str = "\t\t".join([str(chemshift) for chemshift in peak.chemshifts_list])
... | def _to_autoassign(self) | Save :class:`~nmrstarlib.plsimulator.PeakList` into AutoAssign-formatted string.
:return: Peak list representation in AutoAssign format.
:rtype: :py:class:`str` | 4.783239 | 4.530504 | 1.055785 |
json_list = [{"Assignment": peak.assignments_list, "Dimensions": peak.chemshifts_list} for peak in self]
return json.dumps(json_list, sort_keys=True, indent=4) | def _to_json(self) | Save :class:`~nmrstarlib.plsimulator.PeakList` into JSON string.
:return: Peak list representation in JSON format.
:rtype: :py:class:`str` | 10.042071 | 8.849958 | 1.134703 |
try:
if fileformat == "sparky":
sparky_str = self._to_sparky()
filehandle.write(sparky_str)
elif fileformat == "autoassign":
autoassign_str = self._to_sparky()
filehandle.write(autoassign_str)
elif filef... | def write(self, filehandle, fileformat) | Write :class:`~nmrstarlib.plsimulator.PeakList` data into file.
:param filehandle: file-like object.
:type filehandle: :py:class:`io.TextIOWrapper`
:param str fileformat: Format to use to write data: `sparky`, `autoassign`, or `json`.
:return: None
:rtype: :py:obj:`None` | 2.842957 | 2.10812 | 1.348575 |
seq_ids = tuple(int(residue["Seq_ID"]) for residue in self)
return seq_ids == tuple(range(int(seq_ids[0]), int(seq_ids[-1])+1)) | def is_sequential(self) | Check if residues that sequence site is composed of are in sequential order.
:return: If sequence site is in valid sequential order (True) or not (False).
:rtype: :py:obj:`True` or :py:obj:`False` | 5.465207 | 5.009171 | 1.09104 |
dimension_groups = []
for dim_group_label, position in dimension_positions:
dim_group = DimensionGroup(dim_group_label, position)
for dim_label in nmrstarlib.RESONANCE_CLASSES[dim_group_label]:
dim_group.dimensions.append(Dimension(dim_label, position))
... | def create_dimension_groups(dimension_positions) | Create list of dimension groups.
:param zip dimension_positions: List of tuples describing dimension and its position within sequence site.
:return: List of dimension groups.
:rtype: :py:class:`list` | 3.48332 | 3.781143 | 0.921234 |
peak_templates = []
for peak_descr in self:
expanded_dims = [dim_group.dimensions for dim_group in peak_descr]
templates = product(*expanded_dims)
for template in templates:
peak_templates.append(PeakTemplate(template))
return peak_tem... | def peak_templates(self) | Create a list of concrete peak templates from a list of general peak descriptions.
:return: List of peak templates.
:rtype: :py:class:`list` | 4.806699 | 5.06474 | 0.949051 |
relative_positions_set = set()
for peak_descr in self:
relative_positions_set.update(peak_descr.relative_positions)
return len(relative_positions_set) | def seq_site_length(self) | Calculate length of a single sequence site based upon relative positions specified in peak descriptions.
:return: Length of sequence site.
:rtype: :py:class:`int` | 5.22638 | 3.823253 | 1.366998 |
try:
spectrum_description = nmrstarlib.SPECTRUM_DESCRIPTIONS[spectrum_name]
except KeyError:
raise NotImplementedError("Experiment type is not defined.")
spectrum = plsimulator.Spectrum(spectrum_name, spectrum_description["Labels"],
... | def create_spectrum(spectrum_name) | Initialize spectrum and peak descriptions.
:param str spectrum_name: Name of the spectrum from which peak list will be simulated.
:return: Spectrum object.
:rtype: :class:`~nmrstarlib.plsimulator.Spectrum` | 7.015697 | 5.308296 | 1.321648 |
seq_ids = sorted(list(chain.keys()), key=int) # make sure that sequence is sorted by sequence id
slices = [itertools.islice(seq_ids, i, None) for i in range(seq_site_length)]
seq_site_ids = list(zip(*slices))
sequence_sites = []
for seq_site_id in seq_site_ids:
... | def create_sequence_sites(chain, seq_site_length) | Create sequence sites using sequence ids.
:param dict chain: Chain object that contains chemical shift values and assignment information.
:param int seq_site_length: Length of a single sequence site.
:return: List of sequence sites.
:rtype: :py:class:`list` | 3.453702 | 3.5636 | 0.969161 |
start_indexes = [sum(chunk_sizes[:i]) for i in range(0, len(chunk_sizes))]
end_indexes = [sum(chunk_sizes[:i+1]) for i in range(0, len(chunk_sizes))]
return tuple(zip(start_indexes, end_indexes)) | def calculate_intervals(chunk_sizes) | Calculate intervals for a given chunk sizes.
:param list chunk_sizes: List of chunk sizes.
:return: Tuple of intervals.
:rtype: :py:class:`tuple` | 1.952814 | 2.17809 | 0.896572 |
chunk_sizes = [int((i*len(spin_systems_list))/100) for i in self.plsplit]
if sum(chunk_sizes) < len(spin_systems_list):
difference = len(spin_systems_list) - sum(chunk_sizes)
chunk_sizes[chunk_sizes.index(min(chunk_sizes))] += difference
assert sum(chunk_sizes) ... | def split_by_percent(self, spin_systems_list) | Split list of spin systems by specified percentages.
:param list spin_systems_list: List of spin systems.
:return: List of spin systems divided into sub-lists corresponding to specified split percentages.
:rtype: :py:class:`list` | 2.879036 | 2.962611 | 0.97179 |
sequence_sites = self.create_sequence_sites(chain, spectrum.seq_site_length)
spin_systems = []
peaklist = plsimulator.PeakList(spectrum.name, spectrum.labels, source, chain_idx)
for seq_site in sequence_sites:
spin_system = plsimulator.SpinSystem()
for t... | def create_peaklist(self, spectrum, chain, chain_idx, source) | Create peak list file.
:param spectrum: Spectrum object instance.
:type spectrum: :class:`~nmrstarlib.plsimulator.Spectrum`
:param dict chain: Chain object that contains chemical shift values and assignment information.
:param int chain_idx: Protein chain index.
:param str sourc... | 4.143816 | 3.903184 | 1.06165 |
a = numpy.array(arry, dtype)
res = DistArray(a.shape, a.dtype)
res[:] = a
return res | def daArray(arry, dtype=numpy.float) | Array constructor for numpy distributed array
@param arry numpy-like array | 4.234703 | 6.491867 | 0.652309 |
res = DistArray(shap, dtype)
res[:] = 0
return res | def daZeros(shap, dtype=numpy.float) | Zero constructor for numpy distributed array
@param shap the shape of the array
@param dtype the numpy data type | 6.294253 | 7.891046 | 0.797645 |
res = DistArray(shap, dtype)
res[:] = 1
return res | def daOnes(shap, dtype=numpy.float) | One constructor for numpy distributed array
@param shap the shape of the array
@param dtype the numpy data type | 7.093429 | 9.030418 | 0.785504 |
a = numpy.array(arry, dtype)
res = MaskedDistArray(a.shape, a.dtype)
res[:] = a
res.mask = mask
return res | def mdaArray(arry, dtype=numpy.float, mask=None) | Array constructor for masked distributed array
@param arry numpy-like array
@param mask mask array (or None if all data elements are valid) | 4.42558 | 5.341266 | 0.828564 |
res = MaskedDistArray(shap, dtype)
res[:] = 0
res.mask = mask
return res | def mdaZeros(shap, dtype=numpy.float, mask=None) | Zero constructor for masked distributed array
@param shap the shape of the array
@param dtype the numpy data type
@param mask mask array (or None if all data elements are valid) | 5.948483 | 5.560826 | 1.069712 |
res = MaskedDistArray(shap, dtype)
res[:] = 1
res.mask = mask
return res | def mdaOnes(shap, dtype=numpy.float, mask=None) | One constructor for masked distributed array
@param shap the shape of the array
@param dtype the numpy data type
@param mask mask array (or None if all data elements are valid) | 6.237893 | 6.050814 | 1.030918 |
return super(MapArgumentParser,self).format_help().replace(MapConstants.placeholderCounterHelpVersion,MapConstants.placeholderCounter).replace('COUNT_FROM','VALUE').replace('NUMBER_LENGTH','LENGTH').replace('EXTENSIONS','EXT') | def format_help(self) | The help statement is slightly changed in that:
1) MapConstants.placeholderCounterHelpVersion is replaced MapConstants.placeholderCounter
2) 'COUNT_FROM', 'NUMBER_LENGTH', and 'EXTENSIONS' are shortened to 'VALUE', 'LENGTH', and 'EXT', respectively. | 30.178171 | 2.693002 | 11.206146 |
result = {}
if self.is_valid():
upload = self.cleaned_data['upload']
name = storage.save(upload.name, upload)
result['filename'] = os.path.basename(name)
try:
result['url'] = storage.url(name)
except NotImplementedError... | def stash(self, storage, url) | Stores the uploaded file in a temporary storage location. | 3.465048 | 3.359528 | 1.031409 |
if email is not None:
self.email = email
if password is not None:
self.password = password
url = self.api_url + API_LOGIN_ENDPOINT
data = json.dumps({'email': self.email, 'password': self.password})
headers = {'Content-Type': 'application/json'}
... | def login(self, email=None, password=None, timeout=5) | Log in to CANDY HOUSE account. Return True on success. | 1.844172 | 1.831627 | 1.006849 |
url = self.api_url + endpoint
data = None
headers = {}
if payload is not None:
data = json.dumps(payload)
headers['Content-Type'] = 'application/json'
try:
if self.auth_token is not None:
headers[API_AUTH_HEADER] = se... | def request(self, method, endpoint, payload=None, timeout=5) | Send request to API. | 2.196093 | 2.170485 | 1.011798 |
response = self.request('GET', API_SESAME_LIST_ENDPOINT)
if response is not None and response.status_code == 200:
return json.loads(response.text)['sesames']
_LOGGER.warning("Unable to list Sesames")
return [] | def sesames(self) | Return list of Sesames. | 4.625753 | 3.921156 | 1.179691 |
'''
Iterates through required values, checking to_populate for required values
If a key in prompts is missing in to_populate and ``helper==True``,
prompts the user using the values in to_populate. Otherwise, raises an
error.
Parameters
----------
to_populate : dict
Data dictio... | def check_requirements(to_populate, prompts, helper=False) | Iterates through required values, checking to_populate for required values
If a key in prompts is missing in to_populate and ``helper==True``,
prompts the user using the values in to_populate. Otherwise, raises an
error.
Parameters
----------
to_populate : dict
Data dictionary to fill... | 5.13308 | 2.137868 | 2.401027 |
self._set_cursor_x(0)
self._set_cursor_y(0)
self.DC.on()
self._write(data) | def write_all(self, data) | :param list[int] data: | 7.430611 | 6.187074 | 1.200989 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.