code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
url = '/users/' + login + '/' _r = connector.get(url) return (_r.status_code == Constants.PULP_GET_OK)
def user_exists_p(login, connector)
Determine if user exists in specified environment.
9.895234
8.982159
1.101654
# Lifted from: http://stackoverflow.com/a/406822/263969 result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result
def flatten(x)
Flatten an arbitrary depth nested list.
2.618809
2.40096
1.090734
if not title.endswith('.json'): title += '.json' json_body = create_json_str(body) if os.path.exists(title): juicer.utils.Log.log_warn("Cart file '%s' already exists, overwriting with new data." % title) f = open(title, 'w') f.write(json_body) f.flush() f.close()
def write_json_document(title, body)
`title` - Name of the file to write. `body` - Python datastructure representing the document. This method handles transforming the body into a proper json string, and then writing the file to disk.
4.019765
4.236165
0.948916
if not title.endswith('.json'): juicer.utils.Log.log_warn("File name (%s) does not end with '.json', appending it automatically." % title) title += '.json' if not os.path.exists(title): raise IOError("Could not find file: '%s'" % title) f = open(title, 'r') doc = f.read() ...
def read_json_document(title)
Reads in a json document and returns a native python datastructure.
4.088491
4.162032
0.982331
# Stolen from http://rosettacode.org/wiki/Walk_a_directory/Recursively#Python if (not os.path.isdir(search_base)) and os.path.exists(search_base): # Adapt the algorithm to gracefully handle non-directory search paths yield search_base else: for root, dirs, files in os.walk(searc...
def find_pattern(search_base, pattern='*.rpm')
`search_base` - The directory to begin walking down. `pattern` - File pattern to match for. This is a generator which yields the full path to files (one at a time) which match the given glob (`pattern`).
3.308207
3.354673
0.986149
remote_pkgs = [] local_pkgs = [] possible_remotes = filter(lambda i: not os.path.exists(i), package_list) juicer.utils.Log.log_debug("Considering %s possible remotes" % len(possible_remotes)) for item in possible_remotes: remote_pkgs.extend(juicer.utils.Remotes.assemble_remotes(item))...
def filter_package_list(package_list)
Filter a list of packages into local and remotes.
2.862601
2.757032
1.038291
def decorator(func): @wraps(func) def wrapper(*args, **kwargs): saved_stdout = sys.stdout sys.stdout = cStringIO.StringIO() try: out = func(*args, **kwargs) if returns_output: out = sys.stdout.getvalue().str...
def mute(returns_output=False)
`returns_output` - Returns all print output in a list. Capture or ignore all print output generated by a function. Usage: output = mute(returns_output=True)(module.my_func)(args)
2.130021
2.371541
0.898159
import magic m = magic.open(magic.MAGIC_MIME) m.load() mime = m.file(path) # rpms or directories are cool if 'rpm' in mime or 'directory' in mime: return True else: juicer.utils.Log.log_info("error: File `%s` is not an rpm" % path) return False
def is_rpm(path)
Attempt to validate the path as an actual (S)RPM. If an exception is raised then this is not an RPM.
7.047618
6.575677
1.071771
remote = requests.get(url, verify=False) if not remote.status_code == Constants.PULP_GET_OK: raise JuicerPulpError("A %s error occurred trying to get %s" % (remote.status_code, url)) with open(save_as, 'wb') as data: data.write(remote.content)
def save_url_as(url, save_as)
Download the file `url` and save it to the local disk as `save_as`.
5.766963
5.585515
1.032485
dl_base = connector.base_url.replace('/pulp/api/v2', '/pulp/repos') repoid = '%s-%s' % (repo, env) _r = connector.get('/repositories/%s/' % repoid) if not _r.status_code == Constants.PULP_GET_OK: # maybe the repo name is the repoid _r = connector.get('/repositories/%s/' % repo) ...
def remote_url(connector, env, repo, filename)
return a str containing a link to the rpm in the pulp repository
4.515272
4.150418
1.087908
try: fdno = os.open(package, os.O_RDONLY) except OSError: hdr = None return hdr ts.setVSFlags(~(rpm.RPMVSF_NOMD5 | rpm.RPMVSF_NEEDPAYLOAD)) try: hdr = ts.hdrFromFdno(fdno) except rpm.error: hdr = None raise rpm.error if type(hdr) != rpm.hdr: ...
def return_hdr(ts, package)
Hand back the hdr - duh - if the pkg is foobar handback None Shamelessly stolen from Seth Vidal http://yum.baseurl.org/download/misc/checksig.py
3.805065
3.74906
1.014938
string = '%|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|' siginfo = hdr.sprintf(string) if siginfo != '(none)': error = 0 sigtype, sigdate, sigid = siginfo.split(',') else: error ...
def get_sig_info(hdr)
hand back signature information and an error code Shamelessly stolen from Seth Vidal http://yum.baseurl.org/download/misc/checksig.py
5.32036
5.093862
1.044465
rpmroot = '/' ts = rpm.TransactionSet(rpmroot) sigerror = 0 ts.setVSFlags(0) hdr = return_hdr(ts, package) sigerror, (sigtype, sigdate, sigid) = get_sig_info(hdr) if sigid == 'None': keyid = 'None' else: keyid = sigid[-8:] if keyid != 'None': return Tru...
def check_sig(package)
check if rpm has a signature, we don't care if it's valid or not at the moment Shamelessly stolen from Seth Vidal http://yum.baseurl.org/download/misc/checksig.py
7.045407
6.897354
1.021465
regex = re.compile('(.*)-(.*)') manifest = os.path.expanduser(manifest) if not os.path.exists(manifest): raise JuicerManifestError('File not found: %s' % manifest) rpm_list = [] fd = open(manifest) data = yaml.load(fd) if data is None: raise JuicerManifestError('%s co...
def parse_manifest(manifest)
return a list of dicts containing an rpm name, version and release eg: [{'name': 'httpd', 'version': 1.3.39, 'release': 1}]
2.712124
2.587618
1.048116
ts = rpm.TransactionSet() ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) rpm_info = {} rpm_fd = open(rpm_path, 'rb') pkg = ts.hdrFromFdno(rpm_fd) rpm_info['name'] = pkg['name'] rpm_info['version'] = pkg['version'] rpm_info['release'] = pkg['release'] rpm_info['epoch'] = 0 rpm_info...
def rpm_info(rpm_path)
Query information about the RPM at `rpm_path`.
2.406947
2.440992
0.986053
ts = rpm.TransactionSet() ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) info = rpm_info(rpm_path) pkg_name = info['name'] nvrea = info['nvrea'] cksum = info['cksum'] size = info['size'] package_basename = info['package_basename'] juicer.utils.Log.log_notice("Expected amount to seek:...
def upload_rpm(rpm_path, repoid, connector, callback=None)
upload an rpm into pulp rpm_path: path to an rpm connector: the connector to use for interacting with pulp callback: Optional callback to call after an RPM is uploaded. Callback should accept one argument, the name of the RPM which was uploaded
4.251968
4.279573
0.99355
cart_con = cart_db() carts = cart_con[env] return carts.find_one({'_id': cart_name})
def download_cart(cart_name, env)
accesses mongodb and return a cart spec stored there
6.600718
5.276178
1.251042
base_url = base_url.replace('/pulp/api/', '/pulp/repos') url = '%s/%s/carts/%s.json' % (base_url, env, cart_name) rsock = urllib2.urlopen(url) data = rsock.read() rsock.close() return load_json_str(data)
def get_cart(base_url, env, cart_name)
returns a dict object representing a cart stored in pulp base_url: a str for the base_url (eg: http://sweet.pulp.repo/pulp/api/) env: a str with the the name of the environement (eg: prod) cart_name: a str with the name of the cart to get
3.514869
3.635103
0.966924
db = cart_db() carts = db[env] for repo in repos: field = 'repos_items.%s' % repo value = '.*%s.*' % pkg_name found_carts = [] for cart in carts.find({field: {'$regex': value}}): found_carts.append(cart) return found_carts
def search_carts(env, pkg_name, repos)
returns a list of carts containing a package with the specified name env: the name of an environment from the juicer config pkg_name: the name of the package for which to search repos: a list of repos in which to search for the package
4.156676
4.58094
0.907385
# Accounting for '| ' and ' |' width = len(msg) + 4 s = [] s.append('-' * width) s.append("| %s |" % msg) s.append('-' * width) return '\n'.join(s)
def header(msg)
Wrap `msg` in bars to create a header effect
3.858651
3.795968
1.016513
remaining_envs = set(repo['env']) - set(all_envs) if set(repo['env']) - set(all_envs): raise JuicerRepoInUndefinedEnvs("Repo def %s references undefined environments: %s" % (repo['name'], ", ".join(list(remaining_envs)))) else: return True
def repo_in_defined_envs(repo, all_envs)
Raises exception if the repo references undefined environments
5.127058
4.524766
1.13311
return juicer.common.Repo.RepoDiff(juicer_repo=juicer_def, pulp_repo=pulp_def)
def repo_def_matches_reality(juicer_def, pulp_def)
Compare a juicer repo def with a given pulp definition. Compute and return the update necessary to make `pulp_def` match `juicer_def`. `juicer_def` - A JuicerRepo() object representing a juicer repository `pulp_def` - A PulpRepo() object representing a pulp repository
7.362189
6.625461
1.111197
return [l[i:i + n] for i in range(0, len(l), n)]
def chunk_list(l, n)
Return `n` size lists from a given list `l`
2.058727
1.974653
1.042576
ds_str = juicer.utils.create_json_str(repo, indent=4, cls=juicer.common.Repo.RepoEncoder) juicer.utils.Log.log_debug(ds_str)
def debug_log_repo(repo)
Log to DEBUG level a Repo (or subclass) pretty-printed
12.179346
11.714597
1.039673
if defaults is None: defaults = {} if raw: c = RawConfigParser(defaults) else: c = ConfigParser(defaults) if hasattr(conffile, 'readline'): c.readfp(conffile) else: if not c.read(conffile): print ("Unable to read config file %s") % conffile ...
def readconf(conffile, section_name=None, log_name=None, defaults=None, raw=False)
Read config file and return config items as a dict :param conffile: path to config file, or a file-like object (hasattr readline) :param section_name: config section to read (will return all sections if not defined) :param log_name: name to be used with logging (wi...
1.8555
1.875474
0.98935
# Check for a pidfile to see if the daemon already runs try: pidfile = file(self.pidfile, 'r') pid = int(pidfile.read().strip()) pidfile.close() except IOError: pid = None if pid: message = "pidfile %s already exist. D...
def start(self, *args, **kw)
Start the daemon
1.63367
1.601206
1.020275
if led_type in [RGBW, BRIDGE_LED]: return RgbwGroup(bridge, number, name, led_type) elif led_type == RGBWW: return RgbwwGroup(bridge, number, name) elif led_type == WHITE: return WhiteGroup(bridge, number, name) elif led_type == DIMMER: return DimmerGroup(bridge, num...
def group_factory(bridge, number, name, led_type)
Make a group. :param bridge: Member of this bridge. :param number: Group number (1-4). :param name: Name of group. :param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`. :returns: New group.
2.147593
1.703724
1.260529
group = group_factory(self, number, name, led_type) self.groups.append(group) return group
def add_group(self, number, name, led_type)
Add a group. :param number: Group number (1-4). :param name: Group name. :param led_type: Either `RGBW`, `WRGB`, `RGBWW`, `WHITE`, `DIMMER` or `BRIDGE_LED`. :returns: Added group.
2.991956
5.2032
0.575022
# Enqueue the command. self._command_queue.put((command, reps, wait)) # Wait before accepting another command. # This keeps individual groups relatively synchronized. sleep = reps * wait * self.active if command.select and self._selected_number != command.group_n...
def send(self, command, reps=REPS, wait=MIN_WAIT)
Send a command to the physical bridge. :param command: A Command instance. :param reps: Number of repetitions. :param wait: Wait time in seconds.
9.883577
11.027938
0.896231
while not self.is_closed: # Get command from queue. msg = self._command_queue.get() # Closed if msg is None: return # Use the lock so we are sure is_ready is not changed during execution # and the socket is not in...
def _consume(self)
Consume commands from the queue. The command is repeated according to the configured value. Wait after each command is sent. The bridge socket is a shared resource. It must only be used by one thread at a time. Note that this can and will delay commands if multiple groups are a...
5.58473
5.143891
1.085701
try: self._socket.send(bytearray(command)) self._sn = (self._sn + 1) % 256 return True except (socket.error, socket.timeout): # We can get a socket.error or timeout exception if the bridge is disconnected, # but we are still sending da...
def _send_raw(self, command)
Sends an raw command directly to the physical bridge. :param command: A bytearray.
4.669667
4.331026
1.07819
try: # We are changing self.is_ready: lock it up! self._lock.acquire() response = bytearray(22) self._send_raw(BRIDGE_INITIALIZATION_COMMAND) self._socket.recv_into(response) self._wb1 = response[19] self._wb2 = respon...
def _init_connection(self)
Requests the session ids of the bridge. :returns: True, if initialization was successful. False, otherwise.
5.650865
5.22541
1.08142
send_next_keep_alive_at = 0 while not self.is_closed: if not self.is_ready: self._reconnect() continue if time.monotonic() > send_next_keep_alive_at: command = KEEP_ALIVE_COMMAND_PREAMBLE + [self.wb1, self.wb2] ...
def _keep_alive(self)
Send keep alive messages continuously to bridge.
3.285967
3.181801
1.032738
self.is_closed = True self.is_ready = False self._command_queue.put(None)
def close(self)
Closes the connection to the bridge.
6.343687
5.581772
1.136501
# TODO: Check length ipframe = cls(frame[2] * 256 + frame[3]) ipframe.body = frame[6:] return ipframe
def from_frame(cls, frame)
Initilize the frame object based on a KNX/IP data frame.
7.777632
5.160995
1.507003
total_length = self.total_length() res = [0x06, 0x10, 0, 0, 0, 0] res[2] = (self.service_type_id >> 8) & 0xff res[3] = (self.service_type_id >> 0) & 0xff res[4] = (total_length >> 8) & 0xff res[5] = (total_length >> 0) & 0xff return res
def header(self)
Return the frame header (as an array of bytes).
2.172771
2.04766
1.061099
# TODO: Check length request = cls() request.channel = body[1] request.seq = body[2] request.cemi = body[4:] return request
def from_body(cls, body)
Create a tunnelling request from a given body of a KNX/IP frame.
7.643393
5.198959
1.470178
# TODO: check that length matches message = cls() message.code = cemi[0] offset = cemi[1] message.ctl1 = cemi[2 + offset] message.ctl2 = cemi[3 + offset] message.src_addr = cemi[4 + offset] * 256 + cemi[5 + offset] message.dst_addr = cemi[6 + of...
def from_body(cls, cemi)
Create a new CEMIMessage initialized from the given CEMI data.
2.943516
2.882244
1.021258
self.code = 0x11 # frametype 1, repeat 1, system broadcast 1, priority 3, ack-req 0, # confirm-flag 0 self.ctl1 = 0xbc self.ctl2 = 0xe0 # dst addr type 1, hop count 6, extended frame format self.src_addr = 0 self.dst_addr = dst_addr
def init_group(self, dst_addr=1)
Initilize the CEMI frame with the given destination address.
9.789644
9.004467
1.087199
self.init_group(dst_addr) # unnumbered data packet, group write self.tpci_apci = 0x00 * 256 + 0x80 self.dptsize = dptsize if data is None: self.data = [0] else: self.data = data
def init_group_write(self, dst_addr=1, data=None, dptsize=0)
Initialize the CEMI frame for a group write operation.
5.355646
5.341738
1.002604
self.init_group(dst_addr) self.tpci_apci = 0x00 # unnumbered data packet, group read self.data = [0]
def init_group_read(self, dst_addr=1)
Initialize the CEMI frame for a group read operation.
11.357266
10.543085
1.077224
body = [self.code, 0x00, self.ctl1, self.ctl2, (self.src_addr >> 8) & 0xff, (self.src_addr >> 0) & 0xff, (self.dst_addr >> 8) & 0xff, (self.dst_addr >> 0) & 0xff] if self.dptsize == 0 and (len(self.data) == 1) and ((self.data[0] & 0xC0) == 0): # less ...
def to_body(self)
Convert the CEMI frame object to its byte representation.
2.955702
2.790126
1.059343
if self.connected: logging.info("KNXIPTunnel connect request ignored, " "already connected") return True if self.remote_ip == "0.0.0.0": scanner = GatewayScanner() try: ipaddr, port = scanner.start_search...
def connect(self, timeout=2)
Connect to the KNX/IP tunnelling interface. If the remote address is "0.0.0.0", it will use the Gateway scanner to automatically detect a KNX gateway and it will connect to it if one has been found. Returns true if a connection could be established, false otherwise
2.831654
2.735643
1.035096
if self.connected and self.channel: logging.debug("Disconnecting KNX/IP tunnel...") frame = KNXIPFrame(KNXIPFrame.DISCONNECT_REQUEST) frame.body = self.hpai_body() # TODO: Glaube Sequence erhoehen ist nicht notwendig im Control # Tunnel beim...
def disconnect(self)
Disconnect an open tunnel connection
8.995348
8.834998
1.018149
if not self.connected: self.connection_state = -1 return False frame = KNXIPFrame(KNXIPFrame.CONNECTIONSTATE_REQUEST) frame.body = self.hpai_body() # Send maximum 3 connection state requests with a 10 second timeout res = False self.conn...
def check_connection_state(self)
Check the state of the connection using connection state request. This sends a CONNECTION_STATE_REQUEST. This method will only return True, if the connection is established and no error code is returned from the KNX/IP gateway
3.998358
3.912996
1.021815
body = [] # ============ IP Body ========== body.extend([self.channel]) # Communication Channel Id body.extend([0x00]) # Reserverd # =========== Client HPAI =========== body.extend([0x08]) # HPAI Length body.extend([0x01]) # Host Protocol # Tu...
def hpai_body(self)
Create a body with HPAI information. This is used for disconnect and connection state requests.
5.449282
5.362217
1.016237
if not self.connected: if auto_connect: if not self.connect(): raise KNXException("KNX tunnel not reconnected") else: raise KNXException("KNX tunnel not connected") frame = KNXIPFrame(KNXIPFrame.TUNNELING_REQUEST) ...
def send_tunnelling_request(self, cemi, auto_connect=True)
Sends a tunneling request based on the given CEMI data. This method does not wait for an acknowledge or result frame.
4.016884
4.032509
0.996125
if use_cache: res = self.value_cache.get(addr) if res: logging.debug( "Got value of group address %s from cache: %s", addr, res) return res cemi = CEMIMessage() cemi.init_group_read(addr) with self._lo...
def group_read(self, addr, use_cache=True, timeout=1)
Send a group read to the KNX bus and return the result.
4.027521
3.607322
1.116485
cemi = CEMIMessage() cemi.init_group_write(addr, data, dptsize) with self._lock: self.send_tunnelling_request(cemi) # Workaround for lost KNX packets if self._write_delay: time.sleep(self._write_delay)
def group_write(self, addr, data, dptsize=0)
Send a group write to the given address. The method does not check if the address exists and the write request is valid.
6.917815
7.257786
0.953158
data = self.group_read(addr, use_cache) if len(data) != 1: problem = "Can't toggle a {}-octet group address {}".format( len(data), addr) logging.error(problem) raise KNXException(problem) if data[0] == 0: self.group_write(...
def group_toggle(self, addr, use_cache=True)
Toggle the value of an 1-bit group address. If the object has a value != 0, it will be set to 0, otherwise to 1
2.413303
2.397114
1.006754
try: listeners = self.address_listeners[address] except KeyError: listeners = [] self.address_listeners[address] = listeners if not func in listeners: listeners.append(func) return True
def register_listener(self, address, func)
Adds a listener to messages received on a specific address If some KNX messages will be received from the KNX bus, this listener will be called func(address, data). There can be multiple listeners for a given address
2.538848
2.673491
0.949638
listeners = self.address_listeners[address] if listeners is None: return False if func in listeners: listeners.remove(func) return True return False
def unregister_listener(self, address, func)
Removes a listener function for a given address Remove the listener for the given address. Returns true if the listener was found and removed, false otherwise
3.384359
3.215365
1.052558
self.value_cache.set(address, data) if self.notify: self.notify(address, data) try: listeners = self.address_listeners[address] except KeyError: listeners = [] for listener in listeners: listener(address, data)
def received_message(self, address, data)
Process a message received from the KNX bus.
3.528939
3.543178
0.995981
data = self.request[0] sock = self.request[1] frame = KNXIPFrame.from_frame(data) if frame.service_type_id == KNXIPFrame.TUNNELING_REQUEST: req = KNXTunnelingRequest.from_body(frame.body) msg = CEMIMessage.from_body(req.cemi) send_ack = Fals...
def handle(self)
Process an incoming package.
3.643343
3.589204
1.015084
if floatval < -671088.64 or floatval > 670760.96: raise KNXException("float {} out of valid range".format(floatval)) floatval = floatval * 100 i = 0 for i in range(0, 15): exp = pow(2, i) if ((floatval / exp) >= -2048) and ((floatval / exp) < 2047): break ...
def float_to_knx2(floatval)
Convert a float to a 2 byte KNX float value
3.070082
2.923047
1.050302
if len(knxdata) != 2: raise KNXException("Can only convert a 2 Byte object to float") data = knxdata[0] * 256 + knxdata[1] sign = data >> 15 exponent = (data >> 11) & 0x0f mantisse = float(data & 0x7ff) if sign == 1: mantisse = -2048 + mantisse return mantisse * pow(2,...
def knx2_to_float(knxdata)
Convert a KNX 2 byte float object to a float
2.70209
2.520277
1.07214
knxdata = [0, 0, 0] knxdata[0] = ((dow & 0x07) << 5) + timeval.hour knxdata[1] = timeval.minute knxdata[2] = timeval.second return knxdata
def time_to_knx(timeval, dow=0)
Converts a time and day-of-week to a KNX time object
2.654968
2.469166
1.075249
if len(knxdata) != 3: raise KNXException("Can only convert a 3 Byte object to time") dow = knxdata[0] >> 5 res = time(knxdata[0] & 0x1f, knxdata[1], knxdata[2]) return [res, dow]
def knx_to_time(knxdata)
Converts a KNX time to a tuple of a time object and the day of week
4.031991
3.488481
1.155801
if (dateval.year < 1990) or (dateval.year > 2089): raise KNXException("Year has to be between 1990 and 2089") if dateval.year < 2000: year = dateval.year - 1900 else: year = dateval.year - 2000 return([dateval.day, dateval.month, year])
def date_to_knx(dateval)
Convert a date to a 3 byte KNX data array
2.348427
2.227262
1.054401
if len(knxdata) != 3: raise KNXException("Can only convert a 3 Byte object to date") year = knxdata[2] if year >= 90: year += 1900 else: year += 2000 return date(year, knxdata[1], knxdata[0])
def knx_to_date(knxdata)
Convert a 3 byte KNX data object to a date
2.844534
2.465995
1.153504
res = [0, 0, 0, 0, 0, 0, 0, 0] year = datetimeval.year if (year < 1900) or (year > 2155): raise KNXException("Only years between 1900 and 2155 supported") res[0] = year - 1900 res[1] = datetimeval.month res[2] = datetimeval.day res[3] = (datetimeval.isoweekday() << 5) + datetim...
def datetime_to_knx(datetimeval, clock_synced_external=1)
Convert a Python timestamp to an 8 byte KNX time and date object
2.122806
2.091938
1.014756
if len(knxdata) != 8: raise KNXException("Can only convert an 8 Byte object to datetime") year = knxdata[0] + 1900 month = knxdata[1] day = knxdata[2] hour = knxdata[3] & 0x1f minute = knxdata[4] second = knxdata[5] return datetime(year, month, day, hour, minute, second)
def knx_to_datetime(knxdata)
Convert a an 8 byte KNX time and date object to its components
2.156394
1.93043
1.117053
self._color = color self.saturation = saturation_of_color(color) if self.saturation != 0: 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.
3.775826
4.32545
0.872932
if saturation < 0 or saturation > 1: raise ValueError("Saturation must be a percentage " "represented as decimal 0-1.0") self._saturation = saturation self._update_color() if saturation == 0: self.white() else: ...
def saturation(self, saturation)
Set the group saturation. :param saturation: Saturation in decimal percent (0.0-1.0).
4.100198
4.461332
0.919052
if temperature < 0 or temperature > 1: raise ValueError("Temperature must be a percentage " "represented as decimal 0-1.0") self._temperature = temperature cmd = self.command_set.temperature(temperature) self.send(cmd)
def temperature(self, temperature)
Set the temperature. :param temperature: Value to set (0.0-1.0).
4.88045
5.492544
0.888559
if color and temperature is not None: raise ValueError("Cannot transition to color and temperature " "simultaneously.") # Transition to white immediately. if color == RGB_WHITE: self.white() # Transition away from white immed...
def transition(self, duration, color=None, brightness=None, temperature=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. :param temperature: Transition to this temperature.
2.857639
2.962141
0.964721
# 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, brightness, hue=None, saturation=None, temperature=None)
Transition. :param duration: Time to transition. :param brightness: Transition to this brightness. :param hue: Transition to this hue. :param saturation: Transition to this saturation. :param temperature: Transition to this temperature.
1.716016
1.728239
0.992928
normalized = '' cwd = os.getcwd() if not outputdir: outputdir_drivers = os.path.join(cwd, 'drivers') if os.path.isdir(outputdir_drivers): normalized = outputdir_drivers else: normalized = cwd else: normalized = os.path.join(cwd, os.path.normpa...
def normalize_outputdir(outputdir=None)
if output dir is None try using the ./drivers directory if it already exists, otherwise use the current working directory
2.361904
2.079002
1.136076
platform_data = { 'os_name': None, 'os_bits': None } os_name = platform.system() normalize_os = { 'Windows': 'windows', 'Linux': 'linux', 'Darwin': 'mac' } if os_name in normalize_os.keys(): platform_data['os_name'] = normalize_os[os_name] ...
def get_platform()
Get the current platform data. Returns a dictionary with keys: `os_name`, `os_bits`
2.43539
2.278493
1.06886
request = requests.get(url, stream=True) if request.status_code == 404: msg = ('there was a 404 error trying to reach {} \nThis probably ' 'means the requested version does not exist.'.format(url)) logger.error(msg) sys.exit() total_size = int(request.headers["Con...
def download_file_with_progress_bar(url)
Downloads a file from the given url, displays a progress bar. Returns a io.BytesIO object
2.706123
2.795157
0.968147
zipf = zipfile.ZipFile(bytes_io) return zipf.read(expected_file)
def extract_file_from_zip(bytes_io, expected_file)
Extracts a file from a bytes_io zip. Returns bytes
3.318433
3.32761
0.997242
with open('temp', 'wb+') as f: bytes_io.seek(0) shutil.copyfileobj(bytes_io, f, length=131072) tar = tarfile.open('temp', mode='r:gz') os.remove('temp') return tar.extractfile(expected_file).read()
def extract_file_from_tar(bytes_io, expected_file)
extract a file from a bytes_io tar. Returns bytes
2.413576
2.416584
0.998755
if color == RGB_WHITE: 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.
8.217483
11.38616
0.721708
platform = helpers.get_platform() driver_name = helpers.normalize_driver_name(driver_name) driver_class = helpers.get_driver_class(driver_name) driver = driver_class(outputdir, platform['os_name'], platform['os_bits']) if version: driver.download_driver_executable(version=version) e...
def update(driver_name, outputdir, version=None)
Update local driver executable to the latest version or a specific version. driver : a driver name. Options: - chrome, chromedriver - firefox, gecko, geckodriver
2.980626
3.266376
0.912517
if drivers: # Generate a list of tuples: [(driver_name, requested_version)] # If driver string does not contain a version, the second element # of the tuple is None. # Example: # [('driver_a', '2.2'), ('driver_b', None)] drivers_split = [helpers.split_driver_name...
def clean(outputdir, drivers=None)
Remove driver executables from the specified outputdir. drivers can be a list of drivers to filter which executables to remove. Specify a version using an equal sign i.e.: 'chrome=2.2'
2.962162
3.010554
0.983926
for repo in cart.repos(): if not juicer.utils.repo_exists_p(repo, self.connectors[env], env): juicer.utils.Log.log_info("repo '%s' doesn't exist in %s environment... skipping!", (repo, env)) continue repo...
def upload(self, env, cart, callback=None)
Nothing special happens here. This method recieves a destination repo, and a payload of `cart` which will be uploaded into the target repo. Preparation: To use this method you must pre-process your cart: Remotes must be fetched and saved locally. Directories must be recursed and...
3.198208
3.078512
1.038881
juicer.utils.Log.log_debug("Initializing push of cart '%s'" % cart.cart_name) if not env: env = self._defaults['start_in'] cart.current_env = env self.sign_cart_for_env_maybe(cart, env) self.upload(env, cart, callback) return True
def push(self, cart, env=None, callback=None)
`cart` - Release cart to push items from `callback` - Optional callback to call if juicer.utils.upload_rpm succeeds Pushes the items in a release cart to the pre-release environment.
10.134277
8.870713
1.142442
juicer.utils.Log.log_debug("Initializing publish of cart '%s'" % cart.cart_name) if not env: env = self._defaults['start_in'] cart_id = juicer.utils.upload_cart(cart, env) juicer.utils.Log.log_debug('%s uploaded with an id of %s' % ...
def publish(self, cart, env=None)
`cart` - Release cart to publish in json format Publish a release cart in JSON format to the pre-release environment.
6.361142
6.272354
1.014155
cart = juicer.common.Cart.Cart(cart_name) # repo_items is a list that starts with the REPO name, # followed by the ITEMS going into the repo. for repo_items in cart_description: (repo, items) = (repo_items[0], repo_items[1:]) juicer.utils.Log.log_debug("...
def create(self, cart_name, cart_description)
`cart_name` - Name of this release cart `cart_description` - list of ['reponame', item1, ..., itemN] lists
7.207453
6.62417
1.088054
if cart_description is None: juicer.utils.Log.log_debug("No cart_description provided.") cart_description = [] if manifests is None: juicer.utils.Log.log_debug("No manifests provided.") manifests = [] juicer.utils.Log.log_debug("Loading ...
def update(self, cart_name, cart_description, manifests)
`cart_name` - Name of this release cart `cart_description` - list of ['reponame', item1, ..., itemN] lists `manifests` - a list of manifest files
3.267503
3.239905
1.008518
cart = juicer.common.Cart.Cart(cart_name) for manifest in manifests: cart.add_from_manifest(manifest, self.connectors) cart.save() return cart
def create_manifest(self, cart_name, manifests)
`cart_name` - Name of this release cart `manifests` - a list of manifest files
8.542051
9.365515
0.912075
carts = [] for glob in cart_glob: # Translate cart names into cart file names if not glob.endswith('.json'): search_glob = glob + ".json" else: search_glob = glob for cart in juicer.utils.find_pattern(Constants.CAR...
def list(self, cart_glob=['*.json'])
List all carts
4.119812
4.10853
1.002746
# this data block is... yeah. searching in pulp v2 is painful # # https://pulp-dev-guide.readthedocs.org/en/latest/rest-api/content/retrieval.html#search-for-units # https://pulp-dev-guide.readthedocs.org/en/latest/rest-api/conventions/criteria.html#search-criteria # ...
def search(self, pkg_name=None, search_carts=False, query='/content/units/rpm/search/')
search for a package stored in a pulp repo `pkg_name` - substring in the name of the package `search_carts` - whether or not to return carts that include the listed package
3.757478
3.699753
1.015603
for env in self.args.environment: juicer.utils.Log.log_info("Trying to open a connection to %s, %s ...", env, self.connectors[env].base_url) try: _r = self.connectors[env].get() juicer.utils.Log.log_info("OK")...
def hello(self)
Test pulp server connections defined in ~/.config/juicer/config.
3.843545
3.357269
1.144843
if new_cart_name is not None: cart_name = new_cart_name else: cart_name = carts[0] result_cart = juicer.common.Cart.Cart(cart_name) items_hash = {} for cart in carts: # 1. Grab items from each cart and shit them into result_cart ...
def merge(self, carts=None, new_cart_name=None)
`carts` - A list of cart names `new_cart_name` - Resultant cart name Merge the contents of N carts into a new cart TODO: Sanity check that each cart in `carts` exists. Try 'juicer pull'ing carts that can't be located locally. Then cry like a baby and error out.
3.550482
3.325493
1.067656
if not env: env = self._defaults['start_in'] juicer.utils.Log.log_debug("Initializing pulling cart: %s ...", cartname) cart_file = os.path.join(juicer.common.Cart.CART_LOCATION, cartname) cart_file += '.json' cart_check = juicer.utils.download_cart(cartname...
def pull(self, cartname=None, env=None)
`cartname` - Name of cart Pull remote cart from the pre release (base) environment
5.545918
5.743028
0.965678
cart = juicer.common.Cart.Cart(cart_name=cart_name, autoload=True, autosync=True) old_env = cart.current_env cart.current_env = juicer.utils.get_next_environment(cart.current_env) # figure out what needs to be done to promote packages. If # packages are going between en...
def promote(self, cart_name)
`name` - name of cart Promote a cart from its current environment to the next in the chain.
4.920717
4.949458
0.994193
for rpm in rpms: data = { 'criteria': { 'type_ids': ['rpm'], 'filters': { 'unit': { 'filename': { "$regex": rpm } ...
def delete_rpms(self, repo_name, rpms, env)
`repo_name` - Name of the repository rpms live in (includes -env) `rpms` - A list of rpm filenames to delete `env` - Environment we're currently deleting in Delete rpms from a repository in specified environments
5.125907
5.188552
0.987926
if self.connectors[env].requires_signature: cart.sync_remotes(force=True) juicer.utils.Log.log_notice("%s requires RPM signatures", env) juicer.utils.Log.log_notice("Checking for rpm_sign_plugin definition ...") module_name = self._defaults['rpm_sign_plug...
def sign_cart_for_env_maybe(self, cart, env=None)
Sign the items to upload, if the env requires a signature. `cart` - Cart to sign `envs` - The cart is signed if env has the property: requires_signature = True Will attempt to load the rpm_sign_plugin defined in ~/.config/juicer/config, which must be a plugin inheriting from ...
4.195353
3.500072
1.198648
_r = self.connectors[env].post('/repositories/%s-%s/actions/publish/' % (repo, env), {'id': 'yum_distributor'}) if _r.status_code != Constants.PULP_POST_ACCEPTED: _r.raise_for_status() else: juicer.utils.Log.log_info("`%s` published in `%s`" % (repo, env))
def publish_repo(self, repo, env)
`repo` - Repo name. `env` - Environment. Publish a repository. This action regenerates metadata.
10.227246
10.706135
0.95527
orphan_query = '/content/orphans/rpm/' t = datetime.datetime.now() - datetime.timedelta(days = daycount) juicer.utils.Log.log_debug("Prune Repo: %s", repo_name) juicer.utils.Log.log_debug("Pruning packages created before %s" % t) for env in self.args.envs: i...
def prune_repo(self, repo_name=None, daycount=None, envs=[], query='/repositories/')
`repo_name` - name of the repository to prune
3.469628
3.493608
0.993136
cart = juicer.common.Cart.Cart(cart_name=cartname) cart.implode(self._defaults['start_in'])
def delete(self, cartname)
`cartname` - name of the cart to delete Delete a cart both from your local filesystem and the mongo database
30.281717
36.532272
0.828903
final_zero = True out_bytes = [] idx = 0 search_start_idx = 0 for in_char in in_bytes: if in_char == '\x00': final_zero = True out_bytes.append(chr(idx - search_start_idx + 1)) out_bytes.append(in_bytes[search_start_idx:idx]) search_start_...
def encode(in_bytes)
Encode a string using Consistent Overhead Byte Stuffing (COBS). Input is any byte string. Output is also a byte string. Encoding guarantees no zero bytes in the output. The output string will be expanded slightly, by a predictable amount. An empty string is encoded to '\\x01
2.053538
2.116294
0.970346
out_bytes = [] idx = 0 if len(in_bytes) > 0: while True: length = ord(in_bytes[idx]) if length == 0: raise DecodeError("zero byte found in input") idx += 1 end = idx + length - 1 copy_bytes = in_bytes[idx:end] ...
def decode(in_bytes)
Decode a string using Consistent Overhead Byte Stuffing (COBS). Input should be a byte string that has been COBS encoded. Output is also a byte string. A cobs.DecodeError exception will be raised if the encoded data is invalid.
2.623514
2.703444
0.970434
if not isinstance(iterable, str): return iterable.__len__() try: return len(unicode(iterable, 'utf')) except: return iterable.__len__()
def len(iterable)
Redefining len here so it will be able to work with non-ASCII characters
4.325304
4.194459
1.031195
self._hline_string = None self._row_size = None self._header = [] self._rows = []
def reset(self)
Reset the instance - reset rows and header
12.960724
8.268374
1.567506
self._check_row_size(array) self._header = map(str, array)
def header(self, array)
Specify the header of the table
11.068477
10.2554
1.079283
self._check_row_size(array) self._rows.append(map(str, array))
def add_row(self, array)
Add a row in the rows stack - cells can contain newlines and tabs
8.212022
7.975509
1.029655
self._check_row_size(array) try: array = map(int, array) if reduce(min, array) <= 0: raise ValueError except ValueError: sys.stderr.write("Wrong argument in column width specification\n") raise self._width = array
def set_cols_width(self, array)
Set the desired columns width - the elements of the array should be integers, specifying the width of each column. For example: [10, 20, 5]
5.464933
5.437261
1.005089
if not self._row_size: self._row_size = len(array) elif self._row_size != len(array): raise ArraySizeError, "array should contain %d elements" \ % self._row_size
def _check_row_size(self, array)
Check that the specified array fits the previous rows size
3.27442
3.095834
1.057686