code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for _ in range(steps(self.temperature, 0.0,
self.command_set.temperature_steps)):
self._warmer() | def _warmest(self) | Group temperature as warm as possible. | 18.884184 | 14.385948 | 1.312683 |
for _ in range(steps(self.temperature, 1.0,
self.command_set.temperature_steps)):
self._cooler() | def _coolest(self) | Group temperature as cool as possible. | 17.062733 | 13.482628 | 1.265535 |
res = []
for i in ipaddress.split("."):
res.append(int(i))
assert len(res) == 4
return res | def ip_to_array(ipaddress) | Convert a string representing an IPv4 address to 4 bytes. | 2.8881 | 2.742105 | 1.053242 |
res = []
for dummy in range(0, length):
res.append(i & 0xff)
i = i >> 8
return reversed(res) | def int_to_array(i, length=2) | Convert an length byte integer to an array of bytes. | 3.220222 | 3.29553 | 0.977148 |
b1 = Blink1(gamma=gamma, white_point=white_point)
yield b1
if switch_off:
b1.off()
b1.close() | def blink1(switch_off=True, gamma=None, white_point=None) | Context manager which automatically shuts down the Blink(1)
after use.
:param switch_off: turn blink(1) off when existing context
:param gamma: set gamma curve (as tuple)
:param white_point: set white point (as tuple) | 2.784975 | 3.044471 | 0.914765 |
try:
hidraw = hid.device(VENDOR_ID,PRODUCT_ID,serial_number)
hidraw.open(VENDOR_ID,PRODUCT_ID,serial_number)
# hidraw = hid.device(VENDOR_ID,PRODUCT_ID,unicode(serial_number))
# hidraw.open(VENDOR_ID,PRODUCT_ID,unicode(serial_number))
except IOErr... | def find(serial_number=None) | Find a praticular blink(1) device, or the first one
:param serial_number: serial number of blink(1) device (from Blink1.list()) | 2.813864 | 2.69025 | 1.045949 |
try:
devs = hid.enumerate(VENDOR_ID,PRODUCT_ID)
serials = list(map(lambda d:d.get('serial_number'), devs))
return serials
except IOError as e:
return [] | def list() | List blink(1) devices connected, by serial number
:return: List of blink(1) device serial numbers | 4.567353 | 3.981576 | 1.147122 |
log.debug("blink1write:" + ",".join('0x%02x' % v for v in buf))
self.dev.send_feature_report(buf) | def write(self,buf) | Write command to blink(1), low-level internal use
Send USB Feature Report 0x01 to blink(1) with 8-byte payload
Note: arg 'buf' must be 8 bytes or bad things happen | 7.989431 | 5.692351 | 1.403538 |
buf = self.dev.get_feature_report(REPORT_ID,9)
log.debug("blink1read: " + ",".join('0x%02x' % v for v in buf))
return buf | def read(self) | Read command result from blink(1), low-level internal use
Receive USB Feature Report 0x01 from blink(1) with 8-byte payload
Note: buf must be 8 bytes or bad things happen | 9.031343 | 5.881524 | 1.535545 |
action = ord('c')
fade_time = int(fade_milliseconds / 10)
th = (fade_time & 0xff00) >> 8
tl = fade_time & 0x00ff
buf = [REPORT_ID, action, int(red), int(green), int(blue), th, tl, led_number, 0]
self.write( buf ) | def fade_to_rgb_uncorrected(self, fade_milliseconds, red, green, blue, led_number=0) | Command blink(1) to fade to RGB color, no color correction applied. | 4.182456 | 4.041612 | 1.034849 |
if isinstance(color, tuple):
return color
if color.startswith('#'):
try:
return webcolors.hex_to_rgb(color)
except ValueError:
raise InvalidColor(color)
try:
return webcolors.name_to_rgb(color)
exce... | def color_to_rgb(color) | Convert color name or hexcode to (r,g,b) tuple | 2.212534 | 2.08913 | 1.059069 |
red, green, blue = self.color_to_rgb(color)
return self.fade_to_rgb(fade_milliseconds, red, green, blue) | def fade_to_color(self, fade_milliseconds, color) | Fade the light to a known colour in a
:param fade_milliseconds: Duration of the fade in milliseconds
:param color: Named color to fade to
:return: None | 3.067774 | 3.517436 | 0.872162 |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('v'), 0, 0, 0, 0, 0, 0, 0]
self.write(buf)
time.sleep(.05)
version_raw = self.read()
version = (version_raw[3] - ord('0')) * 100 + (version_raw[4] - ord('0'))
return str(version) | def get_version(self) | Get blink(1) firmware version | 4.274958 | 3.38477 | 1.262998 |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('p'), 1, int(start_pos), int(end_pos), int(count), 0, 0, 0]
return self.write(buf); | def play(self, start_pos=0, end_pos=0, count=0) | Play internal color pattern
:param start_pos: pattern line to start from
:param end_pos: pattern line to end at
:param count: number of times to play, 0=play forever | 6.950799 | 7.212067 | 0.963773 |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('p'), 0, 0, 0, 0, 0, 0, 0]
return self.write(buf); | def stop(self) | Stop internal color pattern playing | 7.574872 | 6.570327 | 1.152891 |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('W'), 0xBE, 0xEF, 0xCA, 0xFE, 0, 0, 0]
return self.write(buf); | def savePattern(self) | Save internal RAM pattern to flash | 10.066787 | 7.751587 | 1.298674 |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('l'), led_number, 0,0,0,0,0,0]
self.write(buf) | def setLedN(self, led_number=0) | Set the 'current LED' value for writePatternLine
:param led_number: LED to adjust, 0=all, 1=LEDA, 2=LEDB | 7.376025 | 8.505005 | 0.867257 |
if ( self.dev == None ): return ''
self.setLedN(led_number)
red, green, blue = self.color_to_rgb(color)
r, g, b = self.cc(red, green, blue)
step_time = int(step_milliseconds / 10)
th = (step_time & 0xff00) >> 8
tl = step_time & 0x00ff
buf = [REPOR... | def writePatternLine(self, step_milliseconds, color, pos, led_number=0) | Write a color & step time color pattern line to RAM
:param step_milliseconds: how long for this pattern line to take
:param color: LED color
:param pos: color pattern line number (0-15)
:param led_number: LED to adjust, 0=all, 1=LEDA, 2=LEDB | 4.246496 | 4.358195 | 0.97437 |
if ( self.dev == None ): return ''
buf = [REPORT_ID, ord('R'), 0, 0, 0, 0, 0, int(pos), 0]
self.write(buf)
buf = self.read()
(r,g,b) = (buf[2],buf[3],buf[4])
step_millis = ((buf[5] << 8) | buf[6]) * 10
return (r,g,b,step_millis) | def readPatternLine(self, pos) | Read a color pattern line at position
:param pos: pattern line to read
:return pattern line data as tuple (r,g,b, step_millis) | 4.808146 | 3.496085 | 1.375294 |
if ( self.dev == None ): return ''
pattern=[]
for i in range(0,16): # FIXME: adjustable for diff blink(1) models
pattern.append( self.readPatternLine(i) )
return pattern | def readPattern(self) | Read the entire color pattern
:return List of pattern line tuples | 14.938188 | 15.047042 | 0.992766 |
if ( self.dev == None ): return ''
en = int(enable == True)
timeout_time = int(timeout_millis/10)
th = (timeout_time & 0xff00) >>8
tl = timeout_time & 0x00ff
st = int(stay_lit == True)
buf = [REPORT_ID, ord('D'), en, th, tl, st, start_pos, end_pos, 0]
... | def serverTickle(self, enable, timeout_millis=0, stay_lit=False, start_pos=0, end_pos=16) | Enable/disable servertickle / serverdown watchdog
:param: enable: Set True to enable serverTickle
:param: timeout_millis: millisecs until servertickle is triggered
:param: stay_lit: Set True to keep current color of blink(1), False to turn off
:param: start_pos: Sub-pattern start positio... | 4.314225 | 4.227559 | 1.0205 |
data = {'display_name': repo_name,
'notes': {
'_repo-type': 'rpm-repo',
}
}
juicer.utils.Log.log_debug("Create Repo: %s", repo_name)
for env in envs:
if juicer.utils.repo_exists_p(repo_name, self.conne... | def create_repo(self, repo_name=None, feed=None, envs=[], checksum_type="sha256", query='/repositories/') | `repo_name` - Name of repository to create
`feed` - Repo URL to feed from
`checksum_type` - Used for generating meta-data
Create repository in specified environments, associate the
yum_distributor with it and publish the repo | 2.731933 | 2.680317 | 1.019257 |
try:
repo_defs = juicer.utils.ValidateRepoDef.validate_document(from_file)
except JuicerRepoDefError, e:
juicer.utils.Log.log_error("Could not load repo defs from %s:" % from_file)
raise e
else:
juicer.utils.Log.log_debug("Loaded and valid... | def import_repo(self, from_file, noop=False, query='/repositories/') | `from_file` - JSON file of repo definitions
`noop` - Boolean, if true don't actually create/update repos, just show what would have happened | 4.466215 | 4.416975 | 1.011148 |
repo_id = "%s-%s" % (juicer_repo['name'], env)
distributor_id = "yum_distributor"
importer_id = "yum_importer"
distributor_diff = repo_diff.diff()['distributor']
importer_diff = repo_diff.diff()['importer']
distributor_query = query + "%s/distributors/%s/" % (re... | def _update_repo(self, juicer_repo, pulp_repo, env, repo_diff, query='/repositories/') | `from_file` - JSON file of repo definitions
`noop` - Boolean, if true don't actually create/update repos, just show what would have happened
https://pulp-dev-guide.readthedocs.org/en/pulp-2.3/integration/rest-api/repo/cud.html#update-a-distributor-associated-with-a-repository
https://pulp-dev-g... | 2.035084 | 1.995326 | 1.019925 |
all_envs = envs
juicer.utils.Log.log_notice("Only exporting repos in environment(s): %s", ", ".join(all_envs))
all_pulp_repo_names = self.list_repos(envs=all_envs)
all_pulp_repo_names_uniqued = set()
num_repos = 0
# Track name of all processed repos. Update when... | def export_repos(self, envs=[]) | Dump JuicerRepo() objects for all repos in all environments.
Note that this has undefined results should a repo exist with
different configurations in different environments. | 4.344566 | 4.351886 | 0.998318 |
login = login.lower()
data = {'login': login,
'password': password[0],
'name': user_name}
juicer.utils.Log.log_debug("Create User: %s ('%s')", login, user_name)
for env in envs:
if envs.index(env) != 0 and juicer.utils.env_same_host... | def create_user(self, login=None, password=None, user_name=None, envs=[], query='/users/') | `login` - Login or username for user
`password` - Plain text password for user
`user_name` - Full name of user
Create user in specified environments | 3.438941 | 3.519998 | 0.976973 |
orphan_query = '/content/orphans/rpm/'
juicer.utils.Log.log_debug("Delete Repo: %s", repo_name)
for env in self.args.envs:
if not juicer.utils.repo_exists_p(repo_name, self.connectors[env], env):
juicer.utils.Log.log_info("repo `%s` doesn't exist in %s... sk... | def delete_repo(self, repo_name=None, envs=[], query='/repositories/') | `repo_name` - Name of repository to delete
Delete repo in specified environments | 3.248153 | 3.268382 | 0.993811 |
juicer.utils.Log.log_debug("Delete User: %s", login)
for env in envs:
if envs.index(env) != 0 and juicer.utils.env_same_host(env, envs[envs.index(env) - 1]):
juicer.utils.Log.log_info("environment `%s` shares a host with environment `%s`... skipping!",
... | def delete_user(self, login=None, envs=[], query='/users/') | `login` - Login or username of user to delete
Delete user in specified environments | 3.395135 | 3.432068 | 0.989239 |
juicer.utils.Log.log_debug(
"Sync Repo %s In: %s" % (repo_name, ",".join(envs)))
data = {
'override_config': {
'verify_checksum': 'true',
'verify_size': 'true'
},
}
for env in envs:
url = "... | def sync_repo(self, repo_name=None, envs=[], query='/repositories/') | Sync repository in specified environments | 5.083643 | 5.011184 | 1.014459 |
juicer.utils.Log.log_debug(
"List Repos In: %s", ", ".join(envs))
repo_lists = {}
for env in envs:
repo_lists[env] = []
for env in envs:
_r = self.connectors[env].get(query)
if _r.status_code == Constants.PULP_GET_OK:
... | def list_repos(self, envs=[], query='/repositories/') | List repositories in specified environments | 4.531475 | 4.564312 | 0.992806 |
juicer.utils.Log.log_debug(
"List Users In: %s", ", ".join(envs))
for env in envs:
juicer.utils.Log.log_info("%s:" % (env))
_r = self.connectors[env].get(query)
if _r.status_code == Constants.PULP_GET_OK:
for user in juicer.uti... | def list_users(self, envs=[], query="/users/") | List users in specified environments | 3.98418 | 3.916564 | 1.017264 |
data = {'login': self.args.login}
juicer.utils.Log.log_debug(
"Add Role '%s' to '%s'", role, login)
for env in self.args.envs:
if not juicer.utils.role_exists_p(role, self.connectors[env]):
juicer.utils.Log.log_info("role `%s` doesn't exist i... | def role_add(self, role=None, login=None, envs=[], query='/roles/') | `login` - Login or username of user to add to `role`
`role` - Role to add user to
Add user to role | 3.486727 | 3.466693 | 1.005779 |
juicer.utils.Log.log_debug("Show Repo(s): %s", str(repo_names))
repo_objects = {}
for env in envs:
repo_objects[env] = []
for env in envs:
juicer.utils.Log.log_debug("scanning environment: %s", env)
for repo_name in repo_names:
... | def show_repo(self, repo_names=[], envs=[], query='/repositories/') | `repo_names` - Name of repository(s) to show
Show repositories in specified environments | 2.596401 | 2.659191 | 0.976388 |
juicer.utils.Log.log_debug("Show User: %s", login)
# keep track of which iteration of environment we're in
count = 0
for env in self.args.envs:
count += 1
juicer.utils.Log.log_info("%s:", env)
if not juicer.utils.user_exists_p(login, self.c... | def show_user(self, login=None, envs=[], query='/users/') | `login` - Login or username of user
Show user in specified environments | 3.880202 | 3.898581 | 0.995286 |
juicer.utils.Log.log_debug("List Roles %s", ", ".join(envs))
count = 0
for env in envs:
count += 1
rcount = 0
juicer.utils.Log.log_info("%s:", env)
_r = self.connectors[env].get(query)
if _r.status_code == Constants.PULP_GET... | def list_roles(self, envs=[], query='/roles/') | List roles in specified environments | 2.804193 | 2.809317 | 0.998176 |
juicer.utils.Log.log_debug("Update user information %s" % login)
login = login.lower()
data = {'delta': {}}
if not user_name and not password:
raise JuicerError("Error: --name or --password must be present")
if user_name:
data['delta']['name']... | def update_user(self, login=None, user_name=None, password=None, envs=[], query='/users/') | `login` - Login or username of user to update
`user_name` - Updated full name of user
`password` - Updated plain text password for user
Update user information | 4.343118 | 4.351949 | 0.997971 |
repo_def = {}
defaults = juicer.common.Constants.REPO_DEF_DEFAULTS
repo_def['name'] = self['name']
for key in juicer.common.Constants.REPO_DEF_OPT_KEYS:
repo_def[key] = self.spec.get(key, defaults[key])
juicer.utils.Log.log_debug("Defined %s as %s" % (key... | def to_juicer_repo(self) | Returns a JuicerRepo() object representing this pulp repo | 4.511187 | 4.214257 | 1.070458 |
j_cs = self.j['checksum_type']
j_feed = self.j['feed']
p_cs = self.p['checksum_type']
p_feed = self.p['feed']
# checksum is a distributor property
# Is the pulp checksum wrong?
if not p_cs == j_cs:
juicer.utils.Log.log_debug("Pulp checksum_t... | def _diff(self) | Calculates what you need to do to make a pulp repo match a juicer repo def | 4.161442 | 3.4987 | 1.189425 |
if conf.get('legacy_namespace', 'y') in self.TRUE_VALUES:
self.count_prefix = 'stats_counts'
self.count_suffix = ''
self.gauge_prefix = 'stats.gauges'
self.timer_prefix = 'stats.timers'
self.rate_prefix = 'stats'
self.rate_suffix =... | def _set_prefixes(self, conf) | Set the graphite key prefixes
:param dict conf: The configuration data | 2.314673 | 2.362049 | 0.979943 |
for i in xrange(0, len(items), self.max_batch_size):
yield items[i:i + self.max_batch_size] | def _get_batches(self, items) | given a list yield list at most self.max_batch_size in size | 2.480545 | 1.755301 | 1.413174 |
if self.debug:
if self.pickle_proto:
print "reporting pickled stats"
else:
print "reporting stats -> {\n%s}" % payload
try:
graphite = socket.socket()
with eventlet.Timeout(self.graphite_timeout, True):
... | def report_stats(self, payload, is_retry=False) | Send data to graphite host
:param payload: Data to send to graphite | 3.103229 | 3.075982 | 1.008858 |
while True:
try:
eventlet.sleep(self.flush_interval)
if self.debug:
print "seen %d stats so far." % self.stats_seen
print "current counters: %s" % self.counters
if self.pickle_proto:
... | def stats_flush(self) | Periodically flush stats to graphite | 5.274825 | 5.076069 | 1.039156 |
tstamp = int(time.time())
payload = []
for item in self.counters:
payload.append(("%s.%s%s" % (self.rate_prefix, item,
self.rate_suffix),
(tstamp,
self.counters[item] / self.fl... | def pickle_payload(self) | obtain stats payload in batches of pickle format | 2.497668 | 2.368968 | 1.054327 |
tstamp = int(time.time())
payload = []
for item in self.counters:
payload.append('%s.%s%s %s %s\n' % (self.rate_prefix,
item,
self.rate_suffix,
... | def plain_payload(self) | obtain stats payload in plaintext format | 2.445123 | 2.316719 | 1.055425 |
try:
self.gauges[key] = float(fields[0])
if self.stats_seen >= maxint:
self.logger.info("hit maxint, reset seen counter")
self.stats_seen = 0
self.stats_seen += 1
except Exception as err:
self.logger.info("error dec... | def process_gauge(self, key, fields) | Process a received gauge event
:param key: Key of timer
:param fields: Received fields | 3.786748 | 3.860023 | 0.981017 |
try:
if key not in self.timers:
self.timers[key] = []
self.timers[key].append(float(fields[0]))
if self.stats_seen >= maxint:
self.logger.info("hit maxint, reset seen counter")
self.stats_seen = 0
self.stats... | def process_timer(self, key, fields) | Process a received timer event
:param key: Key of timer
:param fields: Received fields | 3.438724 | 3.599534 | 0.955325 |
sample_rate = 1.0
try:
if len(fields) is 3:
if self.ratecheck.match(fields[2]):
sample_rate = float(fields[2].lstrip("@"))
else:
raise Exception("bad sample rate.")
counter_value = float(fields[0] or... | def process_counter(self, key, fields) | Process a received counter event
:param key: Key of counter
:param fields: Received fields | 3.585038 | 3.729608 | 0.961237 |
self.timers[key].sort()
values = {'count': len(self.timers[key]),
'low': min(self.timers[key]),
'high': max(self.timers[key]),
'total': sum(self.timers[key])}
values['mean'] = values['low']
nth_percentile = 'upper_%i' % self.... | def process_timer_key(self, key, tstamp, stack, pickled=False) | Append the plain text graphite
:param str key: The timer key to process
:param int tstamp: The timestamp for the data point
:param list stack: The stack of metrics to append the output to | 3.033401 | 3.055736 | 0.992691 |
bits = data.split(':')
if len(bits) == 2:
key = self.keycheck.sub('_', bits[0])
fields = bits[1].split("|")
field_count = len(fields)
if field_count >= 2:
processor = self.processors.get(fields[1])
if processor:
... | def decode_recvd(self, data) | Decode and process the data from a received event.
:param data: Data to decode and process. | 4.650867 | 4.814578 | 0.965997 |
parser = argparse.ArgumentParser()
parser.prog = 'juju-resources {}'.format(self.object_name)
for set_name, set_args in getattr(self.object, '_subcommand_argsets', {}).items():
for ap_args, ap_kwargs in set_args:
parser.add_argument(*ap_args, **ap_kwargs)
... | def _get_usage(self) | Build usage string from argparser args. | 3.104355 | 2.908764 | 1.067242 |
if addr is None:
raise KNXException("No address given")
res = None
if re.match('[0-9]+$', addr):
res = int(addr)
match = re.match("([0-9]+)/([0-9]+)$", addr)
if match:
main = match.group(1)
sub = match.group(2)
res = int(main) * 2048 + int(sub)
m... | def parse_group_address(addr) | Parse KNX group addresses and return the address as an integer.
This allows to convert x/x/x and x/x address syntax to a numeric
KNX group address | 2.187659 | 2.096045 | 1.043708 |
old_val = self.values.get(name)
if old_val != value:
self.values[name] = value
return True
else:
return False | def set(self, name, value) | Set the cached value for the given name | 2.725836 | 2.896291 | 0.941147 |
self.repeat = self.repeat % 2
self.priority = self.priority % 4
self.src_addr = self.src_addr % 0x10000
self.dst_addr = self.dst_addr % 0x10000
self.multicast = self.multicast % 2
self.routing = self.routing % 8
self.length = self.length % 16
for ... | def sanitize(self) | Sanitize all fields of the KNX message. | 2.607417 | 2.350124 | 1.109481 |
self.sanitize()
res = []
res.append((1 << 7) + (1 << 4) + (self.repeat << 5) +
(self.priority << 2))
res.append(self.src_addr >> 8)
res.append(self.src_addr % 0x100)
res.append(self.dst_addr >> 8)
res.append(self.dst_addr % 0x100)
... | def to_frame(self) | Convert the object to its frame format. | 2.613456 | 2.534458 | 1.031169 |
message = cls()
# Check checksum first
checksum = 0
for i in range(0, len(frame) - 1):
checksum += frame[i]
if (checksum % 0x100) != frame[len(frame) - 1]:
raise KNXException('Checksum error in frame {}, '
'expecte... | def from_frame(cls, frame) | Create a KNXMessage object from the frame format. | 2.264935 | 2.144246 | 1.056285 |
resource_type = classify_resource_type(resource)
if resource_type is None:
juicer.utils.Log.log_debug("Could not classify or find the input resource.")
return []
elif resource_type == REMOTE_PKG_TYPE:
return [resource]
elif resource_type == REMOTE_INDEX_TYPE:
return... | def assemble_remotes(resource) | Using the specified input resource, assemble a list of rpm URLS.
This function will, when given a remote package url, directory
index, or a combination of the two in a local input file, do all
the work required to turn that input into a list of only remote
package URLs. | 6.870109 | 5.388386 | 1.274985 |
if is_remote_package(resource):
juicer.utils.Log.log_debug("Classified %s as a remote package" % resource)
return REMOTE_PKG_TYPE
elif is_directory_index(resource):
juicer.utils.Log.log_debug("Classified %s as a directory index" % resource)
return REMOTE_INDEX_TYPE
elif ... | def classify_resource_type(resource) | Determine if the specified resource is remote or local.
We can handle three remote resource types from the command line,
remote RPMs, directory indexes, and input files. They're
classified by matching the following patterns:
- Remote RPMS start with http[s] and end with .RPM
- Directory indexes st... | 3.00853 | 2.437244 | 1.234398 |
remote_regexp = re.compile(r"^https?://(.+).rpm$", re.I)
result = remote_regexp.match(resource)
if result is not None:
juicer.utils.Log.log_debug("%s matches remote package regexp" % resource)
return True
else:
juicer.utils.Log.log_debug("%s doesn't match remote package reg... | def is_remote_package(resource) | Classify the input resource as a remote RPM or not. | 3.932579 | 3.545212 | 1.109265 |
remote_regexp = re.compile(r"^https?://(.+)/?$", re.I)
result = remote_regexp.match(resource)
if result is not None:
juicer.utils.Log.log_debug("%s matches directory index regexp" % resource)
return True
else:
juicer.utils.Log.log_debug("%s doesn't match directory index reg... | def is_directory_index(resource) | Classify the input resource as a directory index or not. | 4.160129 | 3.892908 | 1.068643 |
input_resource = open(resource, 'r').read()
remotes_list = [url for url in input_resource.split()]
juicer.utils.Log.log_debug("Input file parsed into: %s\n" % str(remotes_list))
remote_packages = [pkg for pkg in remotes_list if is_remote_package(pkg) is True]
juicer.utils.Log.log_debug("remot... | def parse_input_file(resource) | Parse input file into remote packages and excluded data.
In addition to garbage, excluded data includes directory indexes
for the time being. This will be revisited after basic
functionality has been fully implemented. | 3.555661 | 3.005378 | 1.183099 |
# Normalize our URL style
if not directory_index.endswith('/'):
directory_index = directory_index + '/'
site_index = urllib2.urlopen(directory_index)
parsed_site_index = bs(site_index)
rpm_link_tags = parsed_site_index.findAll('a', href=re.compile(r'.*rpm$'))
# Only save the HREF ... | def parse_directory_index(directory_index) | Retrieve a directory index and make a list of the RPMs listed. | 5.342616 | 5.043526 | 1.059302 |
if luminosity < 0:
val = 0
elif luminosity > 255:
val = 255
else:
val = luminosity
return round(val) | def correct_output(luminosity) | :param luminosity: Input luminosity
:return: Luminosity limited to the 0 <= l <= 255 range. | 2.322752 | 2.226623 | 1.043173 |
temp = kelvin / 100.0
# Calculate Red:
if temp <= 66:
red = 255
else:
red = 329.698727446 * ((temp - 60) ** -0.1332047592)
# Calculate Green:
if temp <= 66:
green = 99.4708025861 * math.log(temp) - 161.1195681661
else:
green = 288.1221695283 * ((temp -... | def kelvin_to_rgb(kelvin) | Convert a color temperature given in kelvin to an approximate RGB value.
:param kelvin: Color temp in K
:return: Tuple of (r, g, b), equivalent color for the temperature | 1.561551 | 1.635999 | 0.954494 |
if saturation_of_color(color) == 0:
self.white()
return
self._color = color
self.hue = hue_of_color(color) | def color(self, color) | Set group color.
Color is set on a best-effort basis.
:param color: RGB color tuple. | 6.21959 | 9.105175 | 0.683083 |
self._color = RGB_WHITE
cmd = self.command_set.white()
self.send(cmd) | def white(self) | Set color to white. | 11.996133 | 9.410885 | 1.274708 |
if brightness < 0 or brightness > 1:
raise ValueError("Brightness must be a percentage "
"represented as decimal 0-1.0")
self._brightness = brightness
cmd = self.command_set.brightness(brightness)
self.send(cmd) | def brightness(self, brightness) | Set the group brightness.
:param brightness: Brightness in decimal percent (0.0-1.0). | 4.540402 | 5.201474 | 0.872907 |
if hue < 0 or hue > 1:
raise ValueError("Hue must be a percentage "
"represented as decimal 0-1.0")
self._hue = hue
cmd = self.command_set.hue(hue)
self.send(cmd) | def hue(self, hue) | Set the group hue.
:param hue: Hue in decimal percent (0.0-1.0). | 4.796912 | 5.38444 | 0.890884 |
# Transition to white immediately.
if color == RGB_WHITE:
self.white()
color = None
# Transition away from white immediately.
elif self.color == RGB_WHITE and color is not None:
self.color = color
color = None
# Transition ... | def transition(self, duration, color=None, brightness=None) | Transition wrapper.
Short-circuit transition as necessary.
:param duration: Time to transition.
:param color: Transition to this color.
:param brightness: Transition to this brightness. | 3.455543 | 3.470018 | 0.995829 |
# Calculate brightness steps.
b_steps = 0
if brightness is not None:
b_steps = steps(self.brightness,
brightness, self.command_set.brightness_steps)
b_start = self.brightness
# Calculate hue steps.
h_steps = 0
i... | def _transition(self, duration, hue=None, brightness=None) | Transition.
:param duration: Time to transition.
:param hue: Transition to this hue.
:param brightness: Transition to this brightness. | 2.464484 | 2.487866 | 0.990602 |
d = datetime.now()
if self.timeaddr:
self.tunnel.group_write(self.timeaddr,
time_to_knx(d))
if self.dateaddr:
self.tunnel.group_write(self.dateaddr,
date_to_knx(d))
if self.datetime... | def send_updates(self) | Send updated to the KNX bus. | 2.680557 | 2.280424 | 1.175464 |
self.updater_running = True
while (self.updater_running):
self.send_updates()
sleep(self.updateinterval) | def updater_loop(self) | Main loop that should run in the background. | 5.055419 | 4.406378 | 1.147296 |
thread = threading.Thread(target=self.updater_loop())
thread.daemon = True
thread.start() | def run_updater_in_background(self) | Starts a thread that runs the updater in the background. | 3.451992 | 2.958048 | 1.166983 |
'''Return the parent of a directory.'''
return os.path.abspath(os.path.join(path, os.pardir, os.pardir, '_build')) | def parent_dir(path) | Return the parent of a directory. | 4.365369 | 3.966591 | 1.100534 |
self._reset()
self.path = path
self._refresh_synced()
if self.is_synced:
self._refresh_path()
self._refresh_signed()
self._refresh_nvr() | def update(self, path) | Update the attributes of this CartItem. | 7.31908 | 6.996406 | 1.04612 |
rpm = RPM(self.path)
rpm.sync(destination)
if rpm.modified:
juicer.utils.Log.log_debug("Source RPM modified. New 'path': %s" % rpm)
self.update(rpm.path)
return True
return False | def sync_to(self, destination) | Sync an RPM from a REMOTE to a LOCAL path.
Returns True if the item required a sync, False if it already
existed locally.
TODO: Remove dupe code in Cart.py:sync_remotes() | 11.029692 | 9.551214 | 1.154795 |
if self.path.startswith('http'):
juicer.utils.Log.log_debug("%s is not synced" % self.path)
self.is_synced = False
else:
juicer.utils.Log.log_debug("%s is synced" % self.path)
self.is_synced = True | def _refresh_synced(self) | Update our is_synced attribute accordingly. | 3.817267 | 3.305073 | 1.154972 |
# Unsynced items are remote so we can't check some of their
# properties yet
if os.path.exists(self.path):
try:
i = open(self.path, 'r')
i.close()
juicer.utils.Log.log_debug("Successfully read item at: %s" % self.path)
... | def _refresh_path(self) | Does it exist? Can we read it? Is it an RPM? | 5.376694 | 4.896119 | 1.098154 |
rpm_info = juicer.utils.rpm_info(self.path)
self.name = rpm_info['name']
self.version = rpm_info['version']
self.release = rpm_info['release'] | def _refresh_nvr(self) | Refresh our name-version-release attributes. | 4.031734 | 3.286121 | 1.226898 |
self.path = ''
self.version = ''
self.release = ''
self.is_signed = False
self.is_synced = False
self.rpm = False | def _reset(self) | Used during update operations and when initialized. | 6.658323 | 5.961982 | 1.116797 |
for group in bridge.groups:
self._groups[group.name] = group | def add_bridge(self, bridge) | Add bridge groups.
:param bridge: Add groups from this bridge. | 5.667258 | 5.806794 | 0.97597 |
out_bytes = []
idx = 0
search_start_idx = 0
for in_char in in_bytes:
if idx - search_start_idx == 0xFE:
out_bytes.append('\xFF')
out_bytes.append(in_bytes[search_start_idx:idx])
search_start_idx = idx
if in_char == '\x00':
out_bytes.ap... | def encode(in_bytes) | Encode a string using Consistent Overhead Byte Stuffing/Reduced (COBS/R).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string may be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01 | 2.820282 | 2.63156 | 1.071715 |
if not bridge.is_ready:
raise Exception('The bridge has to be ready to construct command.')
wb1 = bridge.wb1
wb2 = bridge.wb2
sn = bridge.sn
preamble = [0x80, 0x00, 0x00, 0x00, 0x11, wb1, wb2, 0x00, sn, 0x00]
cmd = [0x31, self.PASSWORD_BYTE1, self.P... | def get_bytes(self, bridge) | Gets the full command as bytes.
:param bridge: The bridge, to which the command should be sent. | 4.09569 | 4.087796 | 1.001931 |
saturation_inverted = 1 - saturation
return math.ceil(saturation_inverted * self.MAX_SATURATION) | def convert_saturation(self, saturation) | Convert the saturation from decimal percent (0.0-1.0)
to byte representation for use in commands.
:param saturation: The saturation from in decimal percent (0.0-1.0).
1.0 is the maximum saturation where no white leds will be on. 0.0 is no
saturation.
:return: The saturation in by... | 6.376887 | 6.543191 | 0.974584 |
hue = math.ceil(hue * self.MAX_HUE)
if legacy_color_wheel:
hue = (176 - hue) % (self.MAX_HUE + 1)
hue = (self.MAX_HUE - hue - 0x37) % (self.MAX_HUE + 1)
else:
hue += 10 # The color wheel for RGBWW bulbs seems to be shifted
return hue % (self... | def convert_hue(self, hue, legacy_color_wheel=False) | Converts the hue from HSV color circle to the LimitlessLED color wheel.
:param hue: The hue in decimal percent (0.0-1.0).
:param legacy_color_wheel: Whether or not use the old color wheel.
:return: The hue regarding the LimitlessLED color wheel. | 4.548749 | 4.771117 | 0.953393 |
return CommandV6(cmd_1, cmd_2, self._remote_style, self._group_number,
select, select_command) | def _build_command(self, cmd_1, cmd_2,
select=False, select_command=None) | Constructs the complete command.
:param cmd_1: Light command 1.
:param cmd_2: Light command 2.
:return: The complete command. | 10.017735 | 11.544344 | 0.867761 |
if json_string is not None:
return self.__init__(loads(json_string))
dump = self
if isinstance(self, HAR.log):
dump = {"log": dump}
return dumps(dump, default=lambda x: dict(x)) | def json(self, json_string=None) | Convenience method allowing easy dumping to and loading from json. | 7.386305 | 6.470453 | 1.141544 |
self._asyncio_loop = asyncio.get_event_loop()
# Creating Broadcast Receiver
coroutine_listen = self._asyncio_loop.create_datagram_endpoint(
lambda: self.KNXSearchBroadcastReceiverProtocol(
self._process_response,
self._timeout_handling,
... | def start_search(self) | Start the Gateway Search Request and return the address information
:rtype: (string,int)
:return: a tuple(string(IP),int(Port) when found or None when
timeout occurs | 3.132408 | 3.00986 | 1.040716 |
resp = bytearray(received_data)
self._resolved_gateway_ip_address = str.format(
"{}.{}.{}.{}", resp[8], resp[9], resp[10], resp[11])
self._resolved_gateway_ip_port = struct.unpack(
'!h', bytes(resp[12:14]))[0] | def _process_response(self, received_data) | Processing the incoming UDP Datagram from the Broadcast Socket
:param received_data: UDP Datagram Package to Process
:type received_data: Byte | 4.028165 | 3.926568 | 1.025874 |
query = '%s/%s/%s/' % (query, self.uid, offset)
_r = self.connector.put(query, fdata, log_data=False, auto_create_json_str=False)
juicer.utils.Log.log_notice("Appending to: %s" % query)
juicer.utils.Log.log_debug("Continuing upload with append. POST returned with data: %s" % st... | def append(self, fdata, offset, query='/content/uploads') | append binary data to an upload
`fdata` - binary data to send to pulp
`offset` - the amount of previously-uploaded data | 7.508206 | 8.178499 | 0.918042 |
query = '/repositories/%s/actions/import_upload/' % self.repoid
data = {'upload_id': self.uid,
'unit_type_id': ftype,
'unit_key': {
'name': rpm_name,
'version': nvrea[1],
'release': nvrea[2],
... | def import_upload(self, nvrea, ftype='rpm', rpm_name='', desc=None, htype='md5', lic=None, group=None, vendor=None, req=None) | import the completed upload into pulp
`ftype` - the type of the upload
`rpm_name` - the name of the uploaded rpm
`desc` - description of the rpm
`htype` - checksum type
`lic` - license used in the packaged software
`group` - package group
`vendor` - software vendo... | 4.572566 | 4.483438 | 1.019879 |
query = query + self.uid + '/'
_r = self.connector.delete(query)
if _r.status_code == Constants.PULP_DELETE_OK:
juicer.utils.Log.log_info("Cleaned up after upload request.")
else:
_r.raise_for_status() | def clean_upload(self, query='/content/uploads/') | pulp leaves droppings if you don't specifically tell it
to clean up after itself. use this to do so. | 9.283672 | 7.116906 | 1.304453 |
config_file = Constants.USER_CONFIG
if os.path.exists(config_file) and os.access(config_file, os.R_OK):
return config_file
elif os.path.exists(config_file) and not os.access(config_file, os.R_OK):
raise IOError("Can not read %s" % config_file)
else:
shutil.copy(Constants.EXA... | def _user_config_file() | Check that the config file is present and readable. If not,
copy a template in place. | 3.860845 | 3.629294 | 1.063801 |
config = ConfigParser.SafeConfigParser()
configs = []
try:
configs.append(_user_config_file())
except Exception, e:
juicer.utils.Log.log_debug(e)
config.read(configs)
return config | def _config_file() | combine the user config file with the system config file (if present) | 6.534928 | 5.218997 | 1.252143 |
config = _config_file()
_config_test(config)
juicer.utils.Log.log_debug("Establishing cart connection:")
cart_con = MongoClient(dict(config.items(config.sections()[0]))['cart_host'])
cart_db = cart_con.carts
return cart_db | def cart_db() | return a pymongo db connection for interacting with cart objects | 9.481009 | 8.334373 | 1.137579 |
cart_cols = cart_db()
cart_json = read_json_document(cart.cart_file())
try:
cart_id = cart_cols[collection].save(cart_json)
except MongoErrors.AutoReconnect:
raise JuicerConfigError("Error saving cart to `cart_host`. Ensure that this node is the master.")
return cart_id | def upload_cart(cart, collection) | Connect to mongo and store your cart in the specified collection. | 12.315684 | 11.993028 | 1.026904 |
connections = {}
_defaults = {}
_defaults['start_in'] = ''
_defaults['rpm_sign_plugin'] = ''
config = _config_file()
_config_test(config)
juicer.utils.Log.log_debug("Loading connection information:")
for section in config.sections():
cfg = dict(config.items(section))
... | def get_login_info() | Give back an array of dicts with the connection
information for all the environments. | 4.133709 | 4.080054 | 1.01315 |
config = ConfigParser.SafeConfigParser()
config = _config_file()
juicer.utils.Log.log_debug("Reading environment sections:")
environments = config.sections()
juicer.utils.Log.log_debug("Read environment sections: %s", ', '.join(environments))
return environments | def get_environments() | Return defined environments from config file for default
environment values. | 7.767995 | 7.3977 | 1.050055 |
config = _config_file()
h1 = dict(config.items(env1))['base_url']
h2 = dict(config.items(env2))['base_url']
return h1 == h2 | def env_same_host(env1, env2) | determine if two environments are on the same host. returns
true or false | 4.177032 | 4.3687 | 0.956127 |
config = _config_file()
juicer.utils.Log.log_debug("Finding next environment...")
if env not in config.sections():
raise JuicerConfigError("%s is not a server configured in juicer.conf", env)
section = dict(config.items(env))
if 'promotes_to' not in section.keys():
err = "En... | def get_next_environment(env) | Given an environment, return the next environment in the
promotion hierarchy | 6.735546 | 6.774248 | 0.994287 |
dl_base = connection.base_url.replace('/pulp/api/v2', '/pulp/repos')
_m = re.match('(.*)-(.*)', repoid)
repo = _m.group(1)
env = _m.group(2)
return "%s/%s/%s" % (dl_base, env, repo) | def pulp_repo_path(connection, repoid) | Given a connection and a repoid, return the url of the repository | 4.020761 | 3.752414 | 1.071513 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.