text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def run(self, args): """Runs the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance args (Namespace): arguments to parse Returns: ``None`` """ jlink = self.create_jlink(args) if args.downgrade: if not jlink.firmware_newer(): print('DLL firmware is not older than J-Link firmware.') else: jlink.invalidate_firmware() try: # Change to the firmware of the connected DLL. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Downgraded: %s' % jlink.firmware_version) elif args.upgrade: if not jlink.firmware_outdated(): print('DLL firmware is not newer than J-Link firmware.') else: try: # Upgrade the firmware. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Updated: %s' % jlink.firmware_version) return None
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "if", "args", ".", "downgrade", ":", "if", "not", "jlink", ".", "firmware_newer", "(", ")", ":", "print", "(", "'DLL firmware is not older than J-Link firmware.'", ")", "else", ":", "jlink", ".", "invalidate_firmware", "(", ")", "try", ":", "# Change to the firmware of the connected DLL.", "jlink", ".", "update_firmware", "(", ")", "except", "pylink", ".", "JLinkException", "as", "e", ":", "# On J-Link versions < 5.0.0, an exception will be thrown as", "# the connection will be lost, so we have to re-establish.", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "print", "(", "'Firmware Downgraded: %s'", "%", "jlink", ".", "firmware_version", ")", "elif", "args", ".", "upgrade", ":", "if", "not", "jlink", ".", "firmware_outdated", "(", ")", ":", "print", "(", "'DLL firmware is not newer than J-Link firmware.'", ")", "else", ":", "try", ":", "# Upgrade the firmware.", "jlink", ".", "update_firmware", "(", ")", "except", "pylink", ".", "JLinkException", "as", "e", ":", "# On J-Link versions < 5.0.0, an exception will be thrown as", "# the connection will be lost, so we have to re-establish.", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "print", "(", "'Firmware Updated: %s'", "%", "jlink", ".", "firmware_version", ")", "return", "None" ]
38.525
20.775
def runCPU(): """Poll CPU usage, make predictions, and plot the results. Runs forever.""" # Create the model for predicting CPU usage. model = ModelFactory.create(model_params.MODEL_PARAMS) model.enableInference({'predictedField': 'cpu'}) # The shifter will align prediction and actual values. shifter = InferenceShifter() # Keep the last WINDOW predicted and actual values for plotting. actHistory = deque([0.0] * WINDOW, maxlen=60) predHistory = deque([0.0] * WINDOW, maxlen=60) # Initialize the plot lines that we will update with each new record. actline, = plt.plot(range(WINDOW), actHistory) predline, = plt.plot(range(WINDOW), predHistory) # Set the y-axis range. actline.axes.set_ylim(0, 100) predline.axes.set_ylim(0, 100) while True: s = time.time() # Get the CPU usage. cpu = psutil.cpu_percent() # Run the input through the model and shift the resulting prediction. modelInput = {'cpu': cpu} result = shifter.shift(model.run(modelInput)) # Update the trailing predicted and actual value deques. inference = result.inferences['multiStepBestPredictions'][5] if inference is not None: actHistory.append(result.rawInput['cpu']) predHistory.append(inference) # Redraw the chart with the new data. actline.set_ydata(actHistory) # update the data predline.set_ydata(predHistory) # update the data plt.draw() plt.legend( ('actual','predicted') ) # Make sure we wait a total of 2 seconds per iteration. try: plt.pause(SECONDS_PER_STEP) except: pass
[ "def", "runCPU", "(", ")", ":", "# Create the model for predicting CPU usage.", "model", "=", "ModelFactory", ".", "create", "(", "model_params", ".", "MODEL_PARAMS", ")", "model", ".", "enableInference", "(", "{", "'predictedField'", ":", "'cpu'", "}", ")", "# The shifter will align prediction and actual values.", "shifter", "=", "InferenceShifter", "(", ")", "# Keep the last WINDOW predicted and actual values for plotting.", "actHistory", "=", "deque", "(", "[", "0.0", "]", "*", "WINDOW", ",", "maxlen", "=", "60", ")", "predHistory", "=", "deque", "(", "[", "0.0", "]", "*", "WINDOW", ",", "maxlen", "=", "60", ")", "# Initialize the plot lines that we will update with each new record.", "actline", ",", "=", "plt", ".", "plot", "(", "range", "(", "WINDOW", ")", ",", "actHistory", ")", "predline", ",", "=", "plt", ".", "plot", "(", "range", "(", "WINDOW", ")", ",", "predHistory", ")", "# Set the y-axis range.", "actline", ".", "axes", ".", "set_ylim", "(", "0", ",", "100", ")", "predline", ".", "axes", ".", "set_ylim", "(", "0", ",", "100", ")", "while", "True", ":", "s", "=", "time", ".", "time", "(", ")", "# Get the CPU usage.", "cpu", "=", "psutil", ".", "cpu_percent", "(", ")", "# Run the input through the model and shift the resulting prediction.", "modelInput", "=", "{", "'cpu'", ":", "cpu", "}", "result", "=", "shifter", ".", "shift", "(", "model", ".", "run", "(", "modelInput", ")", ")", "# Update the trailing predicted and actual value deques.", "inference", "=", "result", ".", "inferences", "[", "'multiStepBestPredictions'", "]", "[", "5", "]", "if", "inference", "is", "not", "None", ":", "actHistory", ".", "append", "(", "result", ".", "rawInput", "[", "'cpu'", "]", ")", "predHistory", ".", "append", "(", "inference", ")", "# Redraw the chart with the new data.", "actline", ".", "set_ydata", "(", "actHistory", ")", "# update the data", "predline", ".", "set_ydata", "(", "predHistory", ")", "# update the data", "plt", ".", "draw", "(", ")", "plt", ".", "legend", "(", "(", "'actual'", ",", "'predicted'", ")", ")", "# Make sure we wait a total of 2 seconds per iteration.", "try", ":", "plt", ".", "pause", "(", "SECONDS_PER_STEP", ")", "except", ":", "pass" ]
34.222222
18.911111
def _consume_queue(self): """ Continually blocks until data is on the internal queue, then calls the session's registered callback and sends a PublishMessageReceived if callback returned True. """ while True: session, block_id, raw_data = self._queue.get() data = json.loads(raw_data.decode('utf-8')) # decode as JSON try: result = session.callback(data) if result is None: self.log.warn("Callback %r returned None, expected boolean. Messages " "are not marked as received unless True is returned", session.callback) elif result: # Send a Successful PublishMessageReceived with the # block id sent in request if self._write_queue is not None: response_message = struct.pack('!HHH', PUBLISH_MESSAGE_RECEIVED, block_id, 200) self._write_queue.put((session.socket, response_message)) except Exception as exception: self.log.exception(exception) self._queue.task_done()
[ "def", "_consume_queue", "(", "self", ")", ":", "while", "True", ":", "session", ",", "block_id", ",", "raw_data", "=", "self", ".", "_queue", ".", "get", "(", ")", "data", "=", "json", ".", "loads", "(", "raw_data", ".", "decode", "(", "'utf-8'", ")", ")", "# decode as JSON", "try", ":", "result", "=", "session", ".", "callback", "(", "data", ")", "if", "result", "is", "None", ":", "self", ".", "log", ".", "warn", "(", "\"Callback %r returned None, expected boolean. Messages \"", "\"are not marked as received unless True is returned\"", ",", "session", ".", "callback", ")", "elif", "result", ":", "# Send a Successful PublishMessageReceived with the", "# block id sent in request", "if", "self", ".", "_write_queue", "is", "not", "None", ":", "response_message", "=", "struct", ".", "pack", "(", "'!HHH'", ",", "PUBLISH_MESSAGE_RECEIVED", ",", "block_id", ",", "200", ")", "self", ".", "_write_queue", ".", "put", "(", "(", "session", ".", "socket", ",", "response_message", ")", ")", "except", "Exception", "as", "exception", ":", "self", ".", "log", ".", "exception", "(", "exception", ")", "self", ".", "_queue", ".", "task_done", "(", ")" ]
49.5
21.653846
def line(self, value): """The line property. Args: value (int). the property value. """ if value == self._defaults['line'] and 'line' in self._values: del self._values['line'] else: self._values['line'] = value
[ "def", "line", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'line'", "]", "and", "'line'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'line'", "]", "else", ":", "self", ".", "_values", "[", "'line'", "]", "=", "value" ]
28.6
14.2
def get_all_completed_tasks(self, api_token, **kwargs): """Return a list of a user's completed tasks. .. warning:: Requires Todoist premium. :param api_token: The user's login api_token. :type api_token: str :param project_id: Filter the tasks by project. :type project_id: str :param limit: The maximum number of tasks to return (default ``30``, max ``50``). :type limit: int :param offset: Used for pagination if there are more tasks than limit. :type offset: int :param from_date: Return tasks with a completion date on or older than from_date. Formatted as ``2007-4-29T10:13``. :type from_date: str :param to: Return tasks with a completion date on or less than to_date. Formatted as ``2007-4-29T10:13``. :type from_date: str :return: The HTTP response to the request. :rtype: :class:`requests.Response` >>> from pytodoist.api import TodoistAPI >>> api = TodoistAPI() >>> response = api.login('john.doe@gmail.com', 'password') >>> user_info = response.json() >>> user_api_token = user_info['api_token'] >>> response = api.get_all_completed_tasks(user_api_token) >>> completed_tasks = response.json() """ params = { 'token': api_token } return self._get('get_all_completed_items', params, **kwargs)
[ "def", "get_all_completed_tasks", "(", "self", ",", "api_token", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'token'", ":", "api_token", "}", "return", "self", ".", "_get", "(", "'get_all_completed_items'", ",", "params", ",", "*", "*", "kwargs", ")" ]
40.971429
16.971429
def page_load_time(self): """ The average total load time for all runs (not weighted). """ load_times = self.get_load_times('page') return round(mean(load_times), self.decimal_precision)
[ "def", "page_load_time", "(", "self", ")", ":", "load_times", "=", "self", ".", "get_load_times", "(", "'page'", ")", "return", "round", "(", "mean", "(", "load_times", ")", ",", "self", ".", "decimal_precision", ")" ]
36.833333
11.5
def validate_business(form, field): """Valiates a PayPal business string. It can either be an email address or a paypal business account ID. """ if not is_valid_mail(field.data, multi=False) and not re.match(r'^[a-zA-Z0-9]{13}$', field.data): raise ValidationError(_('Invalid email address / paypal ID'))
[ "def", "validate_business", "(", "form", ",", "field", ")", ":", "if", "not", "is_valid_mail", "(", "field", ".", "data", ",", "multi", "=", "False", ")", "and", "not", "re", ".", "match", "(", "r'^[a-zA-Z0-9]{13}$'", ",", "field", ".", "data", ")", ":", "raise", "ValidationError", "(", "_", "(", "'Invalid email address / paypal ID'", ")", ")" ]
46.142857
23.571429
def from_url(cls, url): """ Given a resource uri, return an instance of that cache initialized with the given parameters. An example usage: >>> from aiocache import Cache >>> Cache.from_url('memory://') <aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00> a more advanced usage using queryparams to configure the cache: >>> from aiocache import Cache >>> cache = Cache.from_url('redis://localhost:10/1?pool_min_size=1') >>> cache RedisCache (localhost:10) >>> cache.db 1 >>> cache.pool_min_size 1 :param url: string identifying the resource uri of the cache to connect to """ parsed_url = urllib.parse.urlparse(url) kwargs = dict(urllib.parse.parse_qsl(parsed_url.query)) cache_class = Cache.get_scheme_class(parsed_url.scheme) if parsed_url.path: kwargs.update(cache_class.parse_uri_path(parsed_url.path)) if parsed_url.hostname: kwargs["endpoint"] = parsed_url.hostname if parsed_url.port: kwargs["port"] = parsed_url.port if parsed_url.password: kwargs["password"] = parsed_url.password return Cache(cache_class, **kwargs)
[ "def", "from_url", "(", "cls", ",", "url", ")", ":", "parsed_url", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "kwargs", "=", "dict", "(", "urllib", ".", "parse", ".", "parse_qsl", "(", "parsed_url", ".", "query", ")", ")", "cache_class", "=", "Cache", ".", "get_scheme_class", "(", "parsed_url", ".", "scheme", ")", "if", "parsed_url", ".", "path", ":", "kwargs", ".", "update", "(", "cache_class", ".", "parse_uri_path", "(", "parsed_url", ".", "path", ")", ")", "if", "parsed_url", ".", "hostname", ":", "kwargs", "[", "\"endpoint\"", "]", "=", "parsed_url", ".", "hostname", "if", "parsed_url", ".", "port", ":", "kwargs", "[", "\"port\"", "]", "=", "parsed_url", ".", "port", "if", "parsed_url", ".", "password", ":", "kwargs", "[", "\"password\"", "]", "=", "parsed_url", ".", "password", "return", "Cache", "(", "cache_class", ",", "*", "*", "kwargs", ")" ]
32.25641
21.948718
def to_bytes(self, request=None): '''Called to transform the collection of ``streams`` into the content string. This method can be overwritten by derived classes. :param streams: a collection (list or dictionary) containing ``strings/bytes`` used to build the final ``string/bytes``. :return: a string or bytes ''' data = bytearray() for chunk in self.stream(request): if isinstance(chunk, str): chunk = chunk.encode(self.charset) data.extend(chunk) return bytes(data)
[ "def", "to_bytes", "(", "self", ",", "request", "=", "None", ")", ":", "data", "=", "bytearray", "(", ")", "for", "chunk", "in", "self", ".", "stream", "(", "request", ")", ":", "if", "isinstance", "(", "chunk", ",", "str", ")", ":", "chunk", "=", "chunk", ".", "encode", "(", "self", ".", "charset", ")", "data", ".", "extend", "(", "chunk", ")", "return", "bytes", "(", "data", ")" ]
38.6
14.866667
def absolute_abundance(coverage, total_bases): """ absolute abundance = (number of bases mapped to genome / total number of bases in sample) * 100 """ absolute = {} for genome in coverage: absolute[genome] = [] index = 0 for calc in coverage[genome]: bases = calc[0] total = total_bases[index] absolute[genome].append((bases / total) * float(100)) index += 1 total_assembled = [0 for i in absolute[genome]] for genome in absolute: index = 0 for cov in absolute[genome]: total_assembled[index] += cov index += 1 absolute['Unassembled'] = [(100 - i) for i in total_assembled] return absolute
[ "def", "absolute_abundance", "(", "coverage", ",", "total_bases", ")", ":", "absolute", "=", "{", "}", "for", "genome", "in", "coverage", ":", "absolute", "[", "genome", "]", "=", "[", "]", "index", "=", "0", "for", "calc", "in", "coverage", "[", "genome", "]", ":", "bases", "=", "calc", "[", "0", "]", "total", "=", "total_bases", "[", "index", "]", "absolute", "[", "genome", "]", ".", "append", "(", "(", "bases", "/", "total", ")", "*", "float", "(", "100", ")", ")", "index", "+=", "1", "total_assembled", "=", "[", "0", "for", "i", "in", "absolute", "[", "genome", "]", "]", "for", "genome", "in", "absolute", ":", "index", "=", "0", "for", "cov", "in", "absolute", "[", "genome", "]", ":", "total_assembled", "[", "index", "]", "+=", "cov", "index", "+=", "1", "absolute", "[", "'Unassembled'", "]", "=", "[", "(", "100", "-", "i", ")", "for", "i", "in", "total_assembled", "]", "return", "absolute" ]
28.857143
18.095238
def application_path(path): """ Join application project_dir and path """ from uliweb import application return os.path.join(application.project_dir, path)
[ "def", "application_path", "(", "path", ")", ":", "from", "uliweb", "import", "application", "return", "os", ".", "path", ".", "join", "(", "application", ".", "project_dir", ",", "path", ")" ]
28.333333
5.666667
def set_raw(self,text): """ Sets the text of the raw element (or creates the layer if does not exist) @param text: text of the raw layer @type text: string """ node_raw = self.root.find('raw') if node_raw is None: node_raw = etree.Element('raw') self.root.insert(0,node_raw) node_raw.text = etree.CDATA(text)
[ "def", "set_raw", "(", "self", ",", "text", ")", ":", "node_raw", "=", "self", ".", "root", ".", "find", "(", "'raw'", ")", "if", "node_raw", "is", "None", ":", "node_raw", "=", "etree", ".", "Element", "(", "'raw'", ")", "self", ".", "root", ".", "insert", "(", "0", ",", "node_raw", ")", "node_raw", ".", "text", "=", "etree", ".", "CDATA", "(", "text", ")" ]
35.090909
8.181818
def registerItem(self, regItem): """ Adds a ClassRegItem object to the registry. """ super(RtiRegistry, self).registerItem(regItem) for ext in regItem.extensions: self._registerExtension(ext, regItem)
[ "def", "registerItem", "(", "self", ",", "regItem", ")", ":", "super", "(", "RtiRegistry", ",", "self", ")", ".", "registerItem", "(", "regItem", ")", "for", "ext", "in", "regItem", ".", "extensions", ":", "self", ".", "_registerExtension", "(", "ext", ",", "regItem", ")" ]
34.142857
10.428571
def _strOrDate(st): '''internal''' if isinstance(st, string_types): return st elif isinstance(st, datetime): return st.strftime('%Y%m%d') raise PyEXception('Not a date: %s', str(st))
[ "def", "_strOrDate", "(", "st", ")", ":", "if", "isinstance", "(", "st", ",", "string_types", ")", ":", "return", "st", "elif", "isinstance", "(", "st", ",", "datetime", ")", ":", "return", "st", ".", "strftime", "(", "'%Y%m%d'", ")", "raise", "PyEXception", "(", "'Not a date: %s'", ",", "str", "(", "st", ")", ")" ]
29.714286
12.571429
def _save_image(self, image_id, directory): """ Saves the image as a tar archive under specified name """ for x in [0, 1, 2]: self.log.info("Saving image %s to %s directory..." % (image_id, directory)) self.log.debug("Try #%s..." % (x + 1)) try: image = self.docker.get_image(image_id) if docker.version_info[0] < 3: # Docker library prior to 3.0.0 returned the requests # object directly which cold be used to read from self.log.debug("Extracting image using HTTPResponse object directly") self._extract_tar(image, directory) else: # Docker library >=3.0.0 returns iterator over raw data self.log.debug("Extracting image using iterator over raw data") fd_r, fd_w = os.pipe() r = os.fdopen(fd_r, 'rb') w = os.fdopen(fd_w, 'wb') extracter = threading.Thread(target=self._extract_tar, args=(r,directory)) extracter.start() for chunk in image: w.write(chunk) w.flush() w.close() extracter.join() r.close() self.log.info("Image saved!") return True except Exception as e: self.log.exception(e) self.log.warn( "An error occured while saving the %s image, retrying..." % image_id) raise SquashError("Couldn't save %s image!" % image_id)
[ "def", "_save_image", "(", "self", ",", "image_id", ",", "directory", ")", ":", "for", "x", "in", "[", "0", ",", "1", ",", "2", "]", ":", "self", ".", "log", ".", "info", "(", "\"Saving image %s to %s directory...\"", "%", "(", "image_id", ",", "directory", ")", ")", "self", ".", "log", ".", "debug", "(", "\"Try #%s...\"", "%", "(", "x", "+", "1", ")", ")", "try", ":", "image", "=", "self", ".", "docker", ".", "get_image", "(", "image_id", ")", "if", "docker", ".", "version_info", "[", "0", "]", "<", "3", ":", "# Docker library prior to 3.0.0 returned the requests", "# object directly which cold be used to read from", "self", ".", "log", ".", "debug", "(", "\"Extracting image using HTTPResponse object directly\"", ")", "self", ".", "_extract_tar", "(", "image", ",", "directory", ")", "else", ":", "# Docker library >=3.0.0 returns iterator over raw data", "self", ".", "log", ".", "debug", "(", "\"Extracting image using iterator over raw data\"", ")", "fd_r", ",", "fd_w", "=", "os", ".", "pipe", "(", ")", "r", "=", "os", ".", "fdopen", "(", "fd_r", ",", "'rb'", ")", "w", "=", "os", ".", "fdopen", "(", "fd_w", ",", "'wb'", ")", "extracter", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_extract_tar", ",", "args", "=", "(", "r", ",", "directory", ")", ")", "extracter", ".", "start", "(", ")", "for", "chunk", "in", "image", ":", "w", ".", "write", "(", "chunk", ")", "w", ".", "flush", "(", ")", "w", ".", "close", "(", ")", "extracter", ".", "join", "(", ")", "r", ".", "close", "(", ")", "self", ".", "log", ".", "info", "(", "\"Image saved!\"", ")", "return", "True", "except", "Exception", "as", "e", ":", "self", ".", "log", ".", "exception", "(", "e", ")", "self", ".", "log", ".", "warn", "(", "\"An error occured while saving the %s image, retrying...\"", "%", "image_id", ")", "raise", "SquashError", "(", "\"Couldn't save %s image!\"", "%", "image_id", ")" ]
37.977273
21.454545
def pre_social_login(self, request, sociallogin): """Update user based on token information.""" user = sociallogin.user # If the user hasn't been saved yet, it will be updated # later on in the sign-up flow. if not user.pk: return data = sociallogin.account.extra_data oidc = sociallogin.account.provider == 'helsinki_oidc' update_user(user, data, oidc)
[ "def", "pre_social_login", "(", "self", ",", "request", ",", "sociallogin", ")", ":", "user", "=", "sociallogin", ".", "user", "# If the user hasn't been saved yet, it will be updated", "# later on in the sign-up flow.", "if", "not", "user", ".", "pk", ":", "return", "data", "=", "sociallogin", ".", "account", ".", "extra_data", "oidc", "=", "sociallogin", ".", "account", ".", "provider", "==", "'helsinki_oidc'", "update_user", "(", "user", ",", "data", ",", "oidc", ")" ]
35
15.916667
def smoothed(self, angle=.4): """ Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed Returns --------- smoothed : trimesh.Trimesh Non watertight version of current mesh which will render nicely with smooth shading """ # smooth should be recomputed if visuals change self.visual._verify_crc() cached = self.visual._cache['smoothed'] if cached is not None: return cached smoothed = graph.smoothed(self, angle) self.visual._cache['smoothed'] = smoothed return smoothed
[ "def", "smoothed", "(", "self", ",", "angle", "=", ".4", ")", ":", "# smooth should be recomputed if visuals change", "self", ".", "visual", ".", "_verify_crc", "(", ")", "cached", "=", "self", ".", "visual", ".", "_cache", "[", "'smoothed'", "]", "if", "cached", "is", "not", "None", ":", "return", "cached", "smoothed", "=", "graph", ".", "smoothed", "(", "self", ",", "angle", ")", "self", ".", "visual", ".", "_cache", "[", "'smoothed'", "]", "=", "smoothed", "return", "smoothed" ]
29.555556
16.444444
def _add_pret_words(self, pret_embeddings): """Read pre-trained embedding file for extending vocabulary Parameters ---------- pret_embeddings : tuple (embedding_name, source), used for gluonnlp.embedding.create(embedding_name, source) """ words_in_train_data = set(self._id2word) pret_embeddings = gluonnlp.embedding.create(pret_embeddings[0], source=pret_embeddings[1]) for idx, token in enumerate(pret_embeddings.idx_to_token): if token not in words_in_train_data: self._id2word.append(token)
[ "def", "_add_pret_words", "(", "self", ",", "pret_embeddings", ")", ":", "words_in_train_data", "=", "set", "(", "self", ".", "_id2word", ")", "pret_embeddings", "=", "gluonnlp", ".", "embedding", ".", "create", "(", "pret_embeddings", "[", "0", "]", ",", "source", "=", "pret_embeddings", "[", "1", "]", ")", "for", "idx", ",", "token", "in", "enumerate", "(", "pret_embeddings", ".", "idx_to_token", ")", ":", "if", "token", "not", "in", "words_in_train_data", ":", "self", ".", "_id2word", ".", "append", "(", "token", ")" ]
41.928571
21.071429
def all(klass, account, tailored_audience_id, **kwargs): """Returns a Cursor instance for the given tailored audience permission resource.""" resource = klass.RESOURCE_COLLECTION.format( account_id=account.id, tailored_audience_id=tailored_audience_id) request = Request(account.client, 'get', resource, params=kwargs) return Cursor(klass, request, init_with=[account])
[ "def", "all", "(", "klass", ",", "account", ",", "tailored_audience_id", ",", "*", "*", "kwargs", ")", ":", "resource", "=", "klass", ".", "RESOURCE_COLLECTION", ".", "format", "(", "account_id", "=", "account", ".", "id", ",", "tailored_audience_id", "=", "tailored_audience_id", ")", "request", "=", "Request", "(", "account", ".", "client", ",", "'get'", ",", "resource", ",", "params", "=", "kwargs", ")", "return", "Cursor", "(", "klass", ",", "request", ",", "init_with", "=", "[", "account", "]", ")" ]
46.555556
19.888889
def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' changes = [] # Read current configuration and store default values current_network_settings = _parse_current_network_settings() # Build settings opts = _parse_network_settings(settings, current_network_settings) # Ubuntu has moved away from /etc/default/networking # beginning with the 12.04 release so we disable or enable # the networking related services on boot skip_etc_default_networking = ( __grains__['osfullname'] == 'Ubuntu' and int(__grains__['osrelease'].split('.')[0]) >= 12) if skip_etc_default_networking: if opts['networking'] == 'yes': service_cmd = 'service.enable' else: service_cmd = 'service.disable' if __salt__['service.available']('NetworkManager'): __salt__[service_cmd]('NetworkManager') if __salt__['service.available']('networking'): __salt__[service_cmd]('networking') else: try: template = JINJA.get_template('network.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template network.jinja') return '' network = template.render(opts) if 'test' in settings and settings['test']: return _read_temp(network) # Write settings _write_file_network(network, _DEB_NETWORKING_FILE, True) # Get hostname and domain from opts sline = opts['hostname'].split('.', 1) opts['hostname'] = sline[0] current_domainname = current_network_settings['domainname'] current_searchdomain = current_network_settings['searchdomain'] new_domain = False if len(sline) > 1: new_domainname = sline[1] if new_domainname != current_domainname: domainname = new_domainname opts['domainname'] = new_domainname new_domain = True else: domainname = current_domainname opts['domainname'] = domainname else: domainname = current_domainname opts['domainname'] = domainname new_search = False if 'search' in opts: new_searchdomain = opts['search'] if new_searchdomain != current_searchdomain: searchdomain = new_searchdomain opts['searchdomain'] = new_searchdomain new_search = True else: searchdomain = current_searchdomain opts['searchdomain'] = searchdomain else: searchdomain = current_searchdomain opts['searchdomain'] = searchdomain # If the domain changes, then we should write the resolv.conf file. if new_domain or new_search: # Look for existing domain line and update if necessary resolve = _parse_resolve() domain_prog = re.compile(r'domain\s+') search_prog = re.compile(r'search\s+') new_contents = [] for item in _read_file(_DEB_RESOLV_FILE): if domain_prog.match(item): item = 'domain {0}'.format(domainname) elif search_prog.match(item): item = 'search {0}'.format(searchdomain) new_contents.append(item) # A domain line didn't exist so we'll add one in # with the new domainname if 'domain' not in resolve: new_contents.insert(0, 'domain {0}' . format(domainname)) # A search line didn't exist so we'll add one in # with the new search domain if 'search' not in resolve: new_contents.insert('domain' in resolve, 'search {0}'.format(searchdomain)) new_resolv = '\n'.join(new_contents) # Write /etc/resolv.conf if not ('test' in settings and settings['test']): _write_file_network(new_resolv, _DEB_RESOLV_FILE) # used for returning the results back try: template = JINJA.get_template('display-network.jinja') except jinja2.exceptions.TemplateNotFound: log.error('Could not load template display-network.jinja') return '' network = template.render(opts) changes.extend(_read_temp(network)) return changes
[ "def", "build_network_settings", "(", "*", "*", "settings", ")", ":", "changes", "=", "[", "]", "# Read current configuration and store default values", "current_network_settings", "=", "_parse_current_network_settings", "(", ")", "# Build settings", "opts", "=", "_parse_network_settings", "(", "settings", ",", "current_network_settings", ")", "# Ubuntu has moved away from /etc/default/networking", "# beginning with the 12.04 release so we disable or enable", "# the networking related services on boot", "skip_etc_default_networking", "=", "(", "__grains__", "[", "'osfullname'", "]", "==", "'Ubuntu'", "and", "int", "(", "__grains__", "[", "'osrelease'", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", ">=", "12", ")", "if", "skip_etc_default_networking", ":", "if", "opts", "[", "'networking'", "]", "==", "'yes'", ":", "service_cmd", "=", "'service.enable'", "else", ":", "service_cmd", "=", "'service.disable'", "if", "__salt__", "[", "'service.available'", "]", "(", "'NetworkManager'", ")", ":", "__salt__", "[", "service_cmd", "]", "(", "'NetworkManager'", ")", "if", "__salt__", "[", "'service.available'", "]", "(", "'networking'", ")", ":", "__salt__", "[", "service_cmd", "]", "(", "'networking'", ")", "else", ":", "try", ":", "template", "=", "JINJA", ".", "get_template", "(", "'network.jinja'", ")", "except", "jinja2", ".", "exceptions", ".", "TemplateNotFound", ":", "log", ".", "error", "(", "'Could not load template network.jinja'", ")", "return", "''", "network", "=", "template", ".", "render", "(", "opts", ")", "if", "'test'", "in", "settings", "and", "settings", "[", "'test'", "]", ":", "return", "_read_temp", "(", "network", ")", "# Write settings", "_write_file_network", "(", "network", ",", "_DEB_NETWORKING_FILE", ",", "True", ")", "# Get hostname and domain from opts", "sline", "=", "opts", "[", "'hostname'", "]", ".", "split", "(", "'.'", ",", "1", ")", "opts", "[", "'hostname'", "]", "=", "sline", "[", "0", "]", "current_domainname", "=", "current_network_settings", "[", "'domainname'", "]", "current_searchdomain", "=", "current_network_settings", "[", "'searchdomain'", "]", "new_domain", "=", "False", "if", "len", "(", "sline", ")", ">", "1", ":", "new_domainname", "=", "sline", "[", "1", "]", "if", "new_domainname", "!=", "current_domainname", ":", "domainname", "=", "new_domainname", "opts", "[", "'domainname'", "]", "=", "new_domainname", "new_domain", "=", "True", "else", ":", "domainname", "=", "current_domainname", "opts", "[", "'domainname'", "]", "=", "domainname", "else", ":", "domainname", "=", "current_domainname", "opts", "[", "'domainname'", "]", "=", "domainname", "new_search", "=", "False", "if", "'search'", "in", "opts", ":", "new_searchdomain", "=", "opts", "[", "'search'", "]", "if", "new_searchdomain", "!=", "current_searchdomain", ":", "searchdomain", "=", "new_searchdomain", "opts", "[", "'searchdomain'", "]", "=", "new_searchdomain", "new_search", "=", "True", "else", ":", "searchdomain", "=", "current_searchdomain", "opts", "[", "'searchdomain'", "]", "=", "searchdomain", "else", ":", "searchdomain", "=", "current_searchdomain", "opts", "[", "'searchdomain'", "]", "=", "searchdomain", "# If the domain changes, then we should write the resolv.conf file.", "if", "new_domain", "or", "new_search", ":", "# Look for existing domain line and update if necessary", "resolve", "=", "_parse_resolve", "(", ")", "domain_prog", "=", "re", ".", "compile", "(", "r'domain\\s+'", ")", "search_prog", "=", "re", ".", "compile", "(", "r'search\\s+'", ")", "new_contents", "=", "[", "]", "for", "item", "in", "_read_file", "(", "_DEB_RESOLV_FILE", ")", ":", "if", "domain_prog", ".", "match", "(", "item", ")", ":", "item", "=", "'domain {0}'", ".", "format", "(", "domainname", ")", "elif", "search_prog", ".", "match", "(", "item", ")", ":", "item", "=", "'search {0}'", ".", "format", "(", "searchdomain", ")", "new_contents", ".", "append", "(", "item", ")", "# A domain line didn't exist so we'll add one in", "# with the new domainname", "if", "'domain'", "not", "in", "resolve", ":", "new_contents", ".", "insert", "(", "0", ",", "'domain {0}'", ".", "format", "(", "domainname", ")", ")", "# A search line didn't exist so we'll add one in", "# with the new search domain", "if", "'search'", "not", "in", "resolve", ":", "new_contents", ".", "insert", "(", "'domain'", "in", "resolve", ",", "'search {0}'", ".", "format", "(", "searchdomain", ")", ")", "new_resolv", "=", "'\\n'", ".", "join", "(", "new_contents", ")", "# Write /etc/resolv.conf", "if", "not", "(", "'test'", "in", "settings", "and", "settings", "[", "'test'", "]", ")", ":", "_write_file_network", "(", "new_resolv", ",", "_DEB_RESOLV_FILE", ")", "# used for returning the results back", "try", ":", "template", "=", "JINJA", ".", "get_template", "(", "'display-network.jinja'", ")", "except", "jinja2", ".", "exceptions", ".", "TemplateNotFound", ":", "log", ".", "error", "(", "'Could not load template display-network.jinja'", ")", "return", "''", "network", "=", "template", ".", "render", "(", "opts", ")", "changes", ".", "extend", "(", "_read_temp", "(", "network", ")", ")", "return", "changes" ]
34.00813
17.796748
def parse(query_string, info={}): """ :returns: a normalized query_dict as in the following examples: >>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}}) {'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False} >>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3}) {'kind': ['rlz-000', 'rlz-001', 'rlz-002'], 'k': [0, 1, 2], 'rlzs': True} >>> parse('kind=mean', {'stats': {'mean': 0, 'max': 1}}) {'kind': ['mean'], 'k': [0], 'rlzs': False} >>> parse('kind=rlz-3&imt=PGA&site_id=0', {'stats': {}}) {'kind': ['rlz-3'], 'imt': ['PGA'], 'site_id': [0], 'k': [3], 'rlzs': True} """ qdic = parse_qs(query_string) loss_types = info.get('loss_types', []) for key, val in qdic.items(): # for instance, convert site_id to an int if key == 'loss_type': qdic[key] = [loss_types[k] for k in val] else: qdic[key] = [lit_eval(v) for v in val] if info: qdic['k'], qdic['kind'], qdic['rlzs'] = _normalize(qdic['kind'], info) return qdic
[ "def", "parse", "(", "query_string", ",", "info", "=", "{", "}", ")", ":", "qdic", "=", "parse_qs", "(", "query_string", ")", "loss_types", "=", "info", ".", "get", "(", "'loss_types'", ",", "[", "]", ")", "for", "key", ",", "val", "in", "qdic", ".", "items", "(", ")", ":", "# for instance, convert site_id to an int", "if", "key", "==", "'loss_type'", ":", "qdic", "[", "key", "]", "=", "[", "loss_types", "[", "k", "]", "for", "k", "in", "val", "]", "else", ":", "qdic", "[", "key", "]", "=", "[", "lit_eval", "(", "v", ")", "for", "v", "in", "val", "]", "if", "info", ":", "qdic", "[", "'k'", "]", ",", "qdic", "[", "'kind'", "]", ",", "qdic", "[", "'rlzs'", "]", "=", "_normalize", "(", "qdic", "[", "'kind'", "]", ",", "info", ")", "return", "qdic" ]
44.043478
19.434783
def text_log_steps(self, request, project, pk=None): """ Gets a list of steps associated with this job """ try: job = Job.objects.get(repository__name=project, id=pk) except ObjectDoesNotExist: return Response("No job with id: {0}".format(pk), status=HTTP_404_NOT_FOUND) textlog_steps = TextLogStep.objects.filter(job=job).order_by( 'started_line_number').prefetch_related('errors') return Response(serializers.TextLogStepSerializer(textlog_steps, many=True, read_only=True).data)
[ "def", "text_log_steps", "(", "self", ",", "request", ",", "project", ",", "pk", "=", "None", ")", ":", "try", ":", "job", "=", "Job", ".", "objects", ".", "get", "(", "repository__name", "=", "project", ",", "id", "=", "pk", ")", "except", "ObjectDoesNotExist", ":", "return", "Response", "(", "\"No job with id: {0}\"", ".", "format", "(", "pk", ")", ",", "status", "=", "HTTP_404_NOT_FOUND", ")", "textlog_steps", "=", "TextLogStep", ".", "objects", ".", "filter", "(", "job", "=", "job", ")", ".", "order_by", "(", "'started_line_number'", ")", ".", "prefetch_related", "(", "'errors'", ")", "return", "Response", "(", "serializers", ".", "TextLogStepSerializer", "(", "textlog_steps", ",", "many", "=", "True", ",", "read_only", "=", "True", ")", ".", "data", ")" ]
47.266667
21
def terminating_sip_domains(self): """ Access the terminating_sip_domains :returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList """ if self._terminating_sip_domains is None: self._terminating_sip_domains = TerminatingSipDomainList( self._version, trunk_sid=self._solution['sid'], ) return self._terminating_sip_domains
[ "def", "terminating_sip_domains", "(", "self", ")", ":", "if", "self", ".", "_terminating_sip_domains", "is", "None", ":", "self", ".", "_terminating_sip_domains", "=", "TerminatingSipDomainList", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "return", "self", ".", "_terminating_sip_domains" ]
41.461538
18.692308
def dataset_document_iterator(self, file_path: str) -> Iterator[List[OntonotesSentence]]: """ An iterator over CONLL formatted files which yields documents, regardless of the number of document annotations in a particular file. This is useful for conll data which has been preprocessed, such as the preprocessing which takes place for the 2012 CONLL Coreference Resolution task. """ with codecs.open(file_path, 'r', encoding='utf8') as open_file: conll_rows = [] document: List[OntonotesSentence] = [] for line in open_file: line = line.strip() if line != '' and not line.startswith('#'): # Non-empty line. Collect the annotation. conll_rows.append(line) else: if conll_rows: document.append(self._conll_rows_to_sentence(conll_rows)) conll_rows = [] if line.startswith("#end document"): yield document document = [] if document: # Collect any stragglers or files which might not # have the '#end document' format for the end of the file. yield document
[ "def", "dataset_document_iterator", "(", "self", ",", "file_path", ":", "str", ")", "->", "Iterator", "[", "List", "[", "OntonotesSentence", "]", "]", ":", "with", "codecs", ".", "open", "(", "file_path", ",", "'r'", ",", "encoding", "=", "'utf8'", ")", "as", "open_file", ":", "conll_rows", "=", "[", "]", "document", ":", "List", "[", "OntonotesSentence", "]", "=", "[", "]", "for", "line", "in", "open_file", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", "!=", "''", "and", "not", "line", ".", "startswith", "(", "'#'", ")", ":", "# Non-empty line. Collect the annotation.", "conll_rows", ".", "append", "(", "line", ")", "else", ":", "if", "conll_rows", ":", "document", ".", "append", "(", "self", ".", "_conll_rows_to_sentence", "(", "conll_rows", ")", ")", "conll_rows", "=", "[", "]", "if", "line", ".", "startswith", "(", "\"#end document\"", ")", ":", "yield", "document", "document", "=", "[", "]", "if", "document", ":", "# Collect any stragglers or files which might not", "# have the '#end document' format for the end of the file.", "yield", "document" ]
49.653846
18.730769
def dispatch(self, context, consumed, handler, is_endpoint): """Called as dispatch descends into a tier. The base extension uses this to maintain the "current url". """ request = context.request if __debug__: log.debug("Handling dispatch event.", extra=dict( request = id(context), consumed = consumed, handler = safe_name(handler), endpoint = is_endpoint )) # The leading path element (leading slash) requires special treatment. if not consumed and context.request.path_info_peek() == '': consumed = [''] nConsumed = 0 if consumed: # Migrate path elements consumed from the `PATH_INFO` to `SCRIPT_NAME` WSGI environment variables. if not isinstance(consumed, (list, tuple)): consumed = consumed.split('/') for element in consumed: if element == context.request.path_info_peek(): context.request.path_info_pop() nConsumed += 1 else: break # Update the breadcrumb list. context.path.append(Crumb(handler, Path(request.script_name))) if consumed: # Lastly, update the remaining path element list. request.remainder = request.remainder[nConsumed:]
[ "def", "dispatch", "(", "self", ",", "context", ",", "consumed", ",", "handler", ",", "is_endpoint", ")", ":", "request", "=", "context", ".", "request", "if", "__debug__", ":", "log", ".", "debug", "(", "\"Handling dispatch event.\"", ",", "extra", "=", "dict", "(", "request", "=", "id", "(", "context", ")", ",", "consumed", "=", "consumed", ",", "handler", "=", "safe_name", "(", "handler", ")", ",", "endpoint", "=", "is_endpoint", ")", ")", "# The leading path element (leading slash) requires special treatment.", "if", "not", "consumed", "and", "context", ".", "request", ".", "path_info_peek", "(", ")", "==", "''", ":", "consumed", "=", "[", "''", "]", "nConsumed", "=", "0", "if", "consumed", ":", "# Migrate path elements consumed from the `PATH_INFO` to `SCRIPT_NAME` WSGI environment variables.", "if", "not", "isinstance", "(", "consumed", ",", "(", "list", ",", "tuple", ")", ")", ":", "consumed", "=", "consumed", ".", "split", "(", "'/'", ")", "for", "element", "in", "consumed", ":", "if", "element", "==", "context", ".", "request", ".", "path_info_peek", "(", ")", ":", "context", ".", "request", ".", "path_info_pop", "(", ")", "nConsumed", "+=", "1", "else", ":", "break", "# Update the breadcrumb list.", "context", ".", "path", ".", "append", "(", "Crumb", "(", "handler", ",", "Path", "(", "request", ".", "script_name", ")", ")", ")", "if", "consumed", ":", "# Lastly, update the remaining path element list.", "request", ".", "remainder", "=", "request", ".", "remainder", "[", "nConsumed", ":", "]" ]
29.631579
22.473684
def create_git_action_for_new_collection(self, new_collection_id=None): """Checks out master branch as a side effect""" ga = self.create_git_action() assert new_collection_id is not None # id should have been sorted out by the caller self.register_doc_id(ga, new_collection_id) return ga, new_collection_id
[ "def", "create_git_action_for_new_collection", "(", "self", ",", "new_collection_id", "=", "None", ")", ":", "ga", "=", "self", ".", "create_git_action", "(", ")", "assert", "new_collection_id", "is", "not", "None", "# id should have been sorted out by the caller", "self", ".", "register_doc_id", "(", "ga", ",", "new_collection_id", ")", "return", "ga", ",", "new_collection_id" ]
49.714286
9.571429
def rmfile(path): """Ensure file deleted also on *Windows* where read-only files need special treatment.""" if osp.isfile(path): if is_win: os.chmod(path, 0o777) os.remove(path)
[ "def", "rmfile", "(", "path", ")", ":", "if", "osp", ".", "isfile", "(", "path", ")", ":", "if", "is_win", ":", "os", ".", "chmod", "(", "path", ",", "0o777", ")", "os", ".", "remove", "(", "path", ")" ]
34.666667
14.166667
def _get_arch(): """ Determines the current processor architecture. @rtype: str @return: On error, returns: - L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg. On success, returns one of the following values: - L{ARCH_I386} (C{"i386"}) for Intel 32-bit x86 processor or compatible. - L{ARCH_AMD64} (C{"amd64"}) for Intel 64-bit x86_64 processor or compatible. May also return one of the following values if you get both Python and WinAppDbg to work in such machines... let me know if you do! :) - L{ARCH_MIPS} (C{"mips"}) for MIPS compatible processors. - L{ARCH_ALPHA} (C{"alpha"}) for Alpha processors. - L{ARCH_PPC} (C{"ppc"}) for PowerPC compatible processors. - L{ARCH_SHX} (C{"shx"}) for Hitachi SH processors. - L{ARCH_ARM} (C{"arm"}) for ARM compatible processors. - L{ARCH_IA64} (C{"ia64"}) for Intel Itanium processor or compatible. - L{ARCH_ALPHA64} (C{"alpha64"}) for Alpha64 processors. - L{ARCH_MSIL} (C{"msil"}) for the .NET virtual machine. - L{ARCH_SPARC} (C{"sparc"}) for Sun Sparc processors. Probably IronPython returns C{ARCH_MSIL} but I haven't tried it. Python on Windows CE and Windows Mobile should return C{ARCH_ARM}. Python on Solaris using Wine would return C{ARCH_SPARC}. Python in an Itanium machine should return C{ARCH_IA64} both on Wine and proper Windows. All other values should only be returned on Linux using Wine. """ try: si = GetNativeSystemInfo() except Exception: si = GetSystemInfo() try: return _arch_map[si.id.w.wProcessorArchitecture] except KeyError: return ARCH_UNKNOWN
[ "def", "_get_arch", "(", ")", ":", "try", ":", "si", "=", "GetNativeSystemInfo", "(", ")", "except", "Exception", ":", "si", "=", "GetSystemInfo", "(", ")", "try", ":", "return", "_arch_map", "[", "si", ".", "id", ".", "w", ".", "wProcessorArchitecture", "]", "except", "KeyError", ":", "return", "ARCH_UNKNOWN" ]
42.595238
28.214286
def remote_space_available(self, search_pattern=r"(\d+) \w+ free"): """Return space available on remote device.""" remote_cmd = "dir {}".format(self.file_system) remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd) match = re.search(search_pattern, remote_output) if "kbytes" in match.group(0) or "Kbytes" in match.group(0): return int(match.group(1)) * 1000 return int(match.group(1))
[ "def", "remote_space_available", "(", "self", ",", "search_pattern", "=", "r\"(\\d+) \\w+ free\"", ")", ":", "remote_cmd", "=", "\"dir {}\"", ".", "format", "(", "self", ".", "file_system", ")", "remote_output", "=", "self", ".", "ssh_ctl_chan", ".", "send_command_expect", "(", "remote_cmd", ")", "match", "=", "re", ".", "search", "(", "search_pattern", ",", "remote_output", ")", "if", "\"kbytes\"", "in", "match", ".", "group", "(", "0", ")", "or", "\"Kbytes\"", "in", "match", ".", "group", "(", "0", ")", ":", "return", "int", "(", "match", ".", "group", "(", "1", ")", ")", "*", "1000", "return", "int", "(", "match", ".", "group", "(", "1", ")", ")" ]
56.375
16.125
def iter_item_handles(self): """Return iterator over item handles.""" bucket = self.s3resource.Bucket(self.bucket) for obj in bucket.objects.filter(Prefix=self.data_key_prefix).all(): relpath = obj.get()['Metadata']['handle'] yield relpath
[ "def", "iter_item_handles", "(", "self", ")", ":", "bucket", "=", "self", ".", "s3resource", ".", "Bucket", "(", "self", ".", "bucket", ")", "for", "obj", "in", "bucket", ".", "objects", ".", "filter", "(", "Prefix", "=", "self", ".", "data_key_prefix", ")", ".", "all", "(", ")", ":", "relpath", "=", "obj", ".", "get", "(", ")", "[", "'Metadata'", "]", "[", "'handle'", "]", "yield", "relpath" ]
31.333333
23.111111
def _build_pipeline_request(self, task_view): """Returns a Pipeline objects for the job.""" job_metadata = task_view.job_metadata job_params = task_view.job_params job_resources = task_view.job_resources task_metadata = task_view.task_descriptors[0].task_metadata task_params = task_view.task_descriptors[0].task_params task_resources = task_view.task_descriptors[0].task_resources script = task_view.job_metadata['script'] reserved_labels = google_base.build_pipeline_labels( job_metadata, task_metadata, task_id_pattern='task-%d') # Build the ephemeralPipeline for this job. # The ephemeralPipeline definition changes for each job because file # parameters localCopy.path changes based on the remote_uri. pipeline = _Pipelines.build_pipeline( project=self._project, zones=job_resources.zones, min_cores=job_resources.min_cores, min_ram=job_resources.min_ram, disk_size=job_resources.disk_size, boot_disk_size=job_resources.boot_disk_size, preemptible=job_resources.preemptible, accelerator_type=job_resources.accelerator_type, accelerator_count=job_resources.accelerator_count, image=job_resources.image, script_name=script.name, envs=job_params['envs'] | task_params['envs'], inputs=job_params['inputs'] | task_params['inputs'], outputs=job_params['outputs'] | task_params['outputs'], pipeline_name=job_metadata['pipeline-name']) # Build the pipelineArgs for this job. logging_uri = task_resources.logging_path.uri scopes = job_resources.scopes or google_base.DEFAULT_SCOPES pipeline.update( _Pipelines.build_pipeline_args(self._project, script.value, job_params, task_params, reserved_labels, job_resources.preemptible, logging_uri, scopes, job_resources.keep_alive)) return pipeline
[ "def", "_build_pipeline_request", "(", "self", ",", "task_view", ")", ":", "job_metadata", "=", "task_view", ".", "job_metadata", "job_params", "=", "task_view", ".", "job_params", "job_resources", "=", "task_view", ".", "job_resources", "task_metadata", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_metadata", "task_params", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_params", "task_resources", "=", "task_view", ".", "task_descriptors", "[", "0", "]", ".", "task_resources", "script", "=", "task_view", ".", "job_metadata", "[", "'script'", "]", "reserved_labels", "=", "google_base", ".", "build_pipeline_labels", "(", "job_metadata", ",", "task_metadata", ",", "task_id_pattern", "=", "'task-%d'", ")", "# Build the ephemeralPipeline for this job.", "# The ephemeralPipeline definition changes for each job because file", "# parameters localCopy.path changes based on the remote_uri.", "pipeline", "=", "_Pipelines", ".", "build_pipeline", "(", "project", "=", "self", ".", "_project", ",", "zones", "=", "job_resources", ".", "zones", ",", "min_cores", "=", "job_resources", ".", "min_cores", ",", "min_ram", "=", "job_resources", ".", "min_ram", ",", "disk_size", "=", "job_resources", ".", "disk_size", ",", "boot_disk_size", "=", "job_resources", ".", "boot_disk_size", ",", "preemptible", "=", "job_resources", ".", "preemptible", ",", "accelerator_type", "=", "job_resources", ".", "accelerator_type", ",", "accelerator_count", "=", "job_resources", ".", "accelerator_count", ",", "image", "=", "job_resources", ".", "image", ",", "script_name", "=", "script", ".", "name", ",", "envs", "=", "job_params", "[", "'envs'", "]", "|", "task_params", "[", "'envs'", "]", ",", "inputs", "=", "job_params", "[", "'inputs'", "]", "|", "task_params", "[", "'inputs'", "]", ",", "outputs", "=", "job_params", "[", "'outputs'", "]", "|", "task_params", "[", "'outputs'", "]", ",", "pipeline_name", "=", "job_metadata", "[", "'pipeline-name'", "]", ")", "# Build the pipelineArgs for this job.", "logging_uri", "=", "task_resources", ".", "logging_path", ".", "uri", "scopes", "=", "job_resources", ".", "scopes", "or", "google_base", ".", "DEFAULT_SCOPES", "pipeline", ".", "update", "(", "_Pipelines", ".", "build_pipeline_args", "(", "self", ".", "_project", ",", "script", ".", "value", ",", "job_params", ",", "task_params", ",", "reserved_labels", ",", "job_resources", ".", "preemptible", ",", "logging_uri", ",", "scopes", ",", "job_resources", ".", "keep_alive", ")", ")", "return", "pipeline" ]
44.863636
17.204545
def list_backends(): """List color backends.""" return [b.name.replace(".py", "") for b in os.scandir(os.path.join(MODULE_DIR, "backends")) if "__" not in b.name]
[ "def", "list_backends", "(", ")", ":", "return", "[", "b", ".", "name", ".", "replace", "(", "\".py\"", ",", "\"\"", ")", "for", "b", "in", "os", ".", "scandir", "(", "os", ".", "path", ".", "join", "(", "MODULE_DIR", ",", "\"backends\"", ")", ")", "if", "\"__\"", "not", "in", "b", ".", "name", "]" ]
38
10.4
def shred(key_name: str, value: t.Any, field_names: t.Iterable[str] = SHRED_DATA_FIELD_NAMES) -> t.Union[t.Any, str]: """ Replaces sensitive data in ``value`` with ``*`` if ``key_name`` contains something that looks like a secret. :param field_names: a list of key names that can possibly contain sensitive data :param key_name: a key name to check :param value: a value to mask :return: an unchanged value if nothing to hide, ``'*' * len(str(value))`` otherwise """ key_name = key_name.lower() need_shred = False for data_field_name in field_names: if data_field_name in key_name: need_shred = True break if not need_shred: return value return '*' * len(str(value))
[ "def", "shred", "(", "key_name", ":", "str", ",", "value", ":", "t", ".", "Any", ",", "field_names", ":", "t", ".", "Iterable", "[", "str", "]", "=", "SHRED_DATA_FIELD_NAMES", ")", "->", "t", ".", "Union", "[", "t", ".", "Any", ",", "str", "]", ":", "key_name", "=", "key_name", ".", "lower", "(", ")", "need_shred", "=", "False", "for", "data_field_name", "in", "field_names", ":", "if", "data_field_name", "in", "key_name", ":", "need_shred", "=", "True", "break", "if", "not", "need_shred", ":", "return", "value", "return", "'*'", "*", "len", "(", "str", "(", "value", ")", ")" ]
34.363636
21.818182
def from_json(cls, json): """Create a Currency object from a JSON dump.""" obj = cls(name=json['name'], code=json['code'], numeric_code=json['numeric_code'], symbol=json['symbol'], exponent=json['exponent'], entities=json['entities'], withdrawal_date=json['withdrawal_date'], subunits=json['subunits']) return obj
[ "def", "from_json", "(", "cls", ",", "json", ")", ":", "obj", "=", "cls", "(", "name", "=", "json", "[", "'name'", "]", ",", "code", "=", "json", "[", "'code'", "]", ",", "numeric_code", "=", "json", "[", "'numeric_code'", "]", ",", "symbol", "=", "json", "[", "'symbol'", "]", ",", "exponent", "=", "json", "[", "'exponent'", "]", ",", "entities", "=", "json", "[", "'entities'", "]", ",", "withdrawal_date", "=", "json", "[", "'withdrawal_date'", "]", ",", "subunits", "=", "json", "[", "'subunits'", "]", ")", "return", "obj" ]
41.181818
7.909091
def roc_curve(self): """ Generate a ROC curve from the contingency table by calculating the probability of detection (TP/(TP+FN)) and the probability of false detection (FP/(FP+TN)). Returns: A pandas.DataFrame containing the POD, POFD, and the corresponding probability thresholds. """ pod = self.contingency_tables["TP"].astype(float) / (self.contingency_tables["TP"] + self.contingency_tables["FN"]) pofd = self.contingency_tables["FP"].astype(float) / (self.contingency_tables["FP"] + self.contingency_tables["TN"]) return pd.DataFrame({"POD": pod, "POFD": pofd, "Thresholds": self.thresholds}, columns=["POD", "POFD", "Thresholds"])
[ "def", "roc_curve", "(", "self", ")", ":", "pod", "=", "self", ".", "contingency_tables", "[", "\"TP\"", "]", ".", "astype", "(", "float", ")", "/", "(", "self", ".", "contingency_tables", "[", "\"TP\"", "]", "+", "self", ".", "contingency_tables", "[", "\"FN\"", "]", ")", "pofd", "=", "self", ".", "contingency_tables", "[", "\"FP\"", "]", ".", "astype", "(", "float", ")", "/", "(", "self", ".", "contingency_tables", "[", "\"FP\"", "]", "+", "self", ".", "contingency_tables", "[", "\"TN\"", "]", ")", "return", "pd", ".", "DataFrame", "(", "{", "\"POD\"", ":", "pod", ",", "\"POFD\"", ":", "pofd", ",", "\"Thresholds\"", ":", "self", ".", "thresholds", "}", ",", "columns", "=", "[", "\"POD\"", ",", "\"POFD\"", ",", "\"Thresholds\"", "]", ")" ]
60.857143
37
def publish(ctx, test=False): """Publish to the cheeseshop.""" clean(ctx) if test: run('python setup.py register -r test sdist bdist_wheel', echo=True) run('twine upload dist/* -r test', echo=True) else: run('python setup.py register sdist bdist_wheel', echo=True) run('twine upload dist/*', echo=True)
[ "def", "publish", "(", "ctx", ",", "test", "=", "False", ")", ":", "clean", "(", "ctx", ")", "if", "test", ":", "run", "(", "'python setup.py register -r test sdist bdist_wheel'", ",", "echo", "=", "True", ")", "run", "(", "'twine upload dist/* -r test'", ",", "echo", "=", "True", ")", "else", ":", "run", "(", "'python setup.py register sdist bdist_wheel'", ",", "echo", "=", "True", ")", "run", "(", "'twine upload dist/*'", ",", "echo", "=", "True", ")" ]
38
19.777778
def find_near_matches_no_deletions_ngrams(subsequence, sequence, search_params): """search for near-matches of subsequence in sequence This searches for near-matches, where the nearly-matching parts of the sequence must meet the following limitations (relative to the subsequence): * the maximum allowed number of character substitutions * the maximum allowed number of new characters inserted * no deletions are allowed * the total number of substitutions, insertions and deletions """ if not subsequence: raise ValueError('Given subsequence is empty!') max_substitutions, max_insertions, max_deletions, max_l_dist = search_params.unpacked max_substitutions = min(max_substitutions, max_l_dist) max_insertions = min(max_insertions, max_l_dist) subseq_len = len(subsequence) seq_len = len(sequence) ngram_len = subseq_len // (max_substitutions + max_insertions + 1) if ngram_len == 0: raise ValueError( "The subsequence's length must be greater than max_subs + max_ins!" ) matches = [] matched_indexes = set() for ngram_start in range(0, len(subsequence) - ngram_len + 1, ngram_len): ngram_end = ngram_start + ngram_len subseq_before = subsequence[:ngram_start] subseq_before_reversed = subseq_before[::-1] subseq_after = subsequence[ngram_end:] start_index = max(0, ngram_start - max_insertions) end_index = min(seq_len, seq_len - (subseq_len - ngram_end) + max_insertions) for index in search_exact( subsequence[ngram_start:ngram_end], sequence, start_index, end_index, ): if index - ngram_start in matched_indexes: continue seq_after = sequence[index + ngram_len:index + subseq_len - ngram_start + max_insertions] if seq_after.startswith(subseq_after): matches_after = [(0, 0)] else: matches_after = _expand(subseq_after, seq_after, max_substitutions, max_insertions, max_l_dist) if not matches_after: continue _max_substitutions = max_substitutions - min(m[0] for m in matches_after) _max_insertions = max_insertions - min(m[1] for m in matches_after) _max_l_dist = max_l_dist - min(m[0] + m[1] for m in matches_after) seq_before = sequence[index - ngram_start - _max_insertions:index] if seq_before.endswith(subseq_before): matches_before = [(0, 0)] else: matches_before = _expand( subseq_before_reversed, seq_before[::-1], _max_substitutions, _max_insertions, _max_l_dist, ) for (subs_before, ins_before) in matches_before: for (subs_after, ins_after) in matches_after: if ( subs_before + subs_after <= max_substitutions and ins_before + ins_after <= max_insertions and subs_before + subs_after + ins_before + ins_after <= max_l_dist ): matches.append(Match( start=index - ngram_start - ins_before, end=index - ngram_start + subseq_len + ins_after, dist=subs_before + subs_after + ins_before + ins_after, )) matched_indexes |= set(range( index - ngram_start - ins_before, index - ngram_start - ins_before + max_insertions + 1, )) return sorted(matches, key=lambda match: match.start)
[ "def", "find_near_matches_no_deletions_ngrams", "(", "subsequence", ",", "sequence", ",", "search_params", ")", ":", "if", "not", "subsequence", ":", "raise", "ValueError", "(", "'Given subsequence is empty!'", ")", "max_substitutions", ",", "max_insertions", ",", "max_deletions", ",", "max_l_dist", "=", "search_params", ".", "unpacked", "max_substitutions", "=", "min", "(", "max_substitutions", ",", "max_l_dist", ")", "max_insertions", "=", "min", "(", "max_insertions", ",", "max_l_dist", ")", "subseq_len", "=", "len", "(", "subsequence", ")", "seq_len", "=", "len", "(", "sequence", ")", "ngram_len", "=", "subseq_len", "//", "(", "max_substitutions", "+", "max_insertions", "+", "1", ")", "if", "ngram_len", "==", "0", ":", "raise", "ValueError", "(", "\"The subsequence's length must be greater than max_subs + max_ins!\"", ")", "matches", "=", "[", "]", "matched_indexes", "=", "set", "(", ")", "for", "ngram_start", "in", "range", "(", "0", ",", "len", "(", "subsequence", ")", "-", "ngram_len", "+", "1", ",", "ngram_len", ")", ":", "ngram_end", "=", "ngram_start", "+", "ngram_len", "subseq_before", "=", "subsequence", "[", ":", "ngram_start", "]", "subseq_before_reversed", "=", "subseq_before", "[", ":", ":", "-", "1", "]", "subseq_after", "=", "subsequence", "[", "ngram_end", ":", "]", "start_index", "=", "max", "(", "0", ",", "ngram_start", "-", "max_insertions", ")", "end_index", "=", "min", "(", "seq_len", ",", "seq_len", "-", "(", "subseq_len", "-", "ngram_end", ")", "+", "max_insertions", ")", "for", "index", "in", "search_exact", "(", "subsequence", "[", "ngram_start", ":", "ngram_end", "]", ",", "sequence", ",", "start_index", ",", "end_index", ",", ")", ":", "if", "index", "-", "ngram_start", "in", "matched_indexes", ":", "continue", "seq_after", "=", "sequence", "[", "index", "+", "ngram_len", ":", "index", "+", "subseq_len", "-", "ngram_start", "+", "max_insertions", "]", "if", "seq_after", ".", "startswith", "(", "subseq_after", ")", ":", "matches_after", "=", "[", "(", "0", ",", "0", ")", "]", "else", ":", "matches_after", "=", "_expand", "(", "subseq_after", ",", "seq_after", ",", "max_substitutions", ",", "max_insertions", ",", "max_l_dist", ")", "if", "not", "matches_after", ":", "continue", "_max_substitutions", "=", "max_substitutions", "-", "min", "(", "m", "[", "0", "]", "for", "m", "in", "matches_after", ")", "_max_insertions", "=", "max_insertions", "-", "min", "(", "m", "[", "1", "]", "for", "m", "in", "matches_after", ")", "_max_l_dist", "=", "max_l_dist", "-", "min", "(", "m", "[", "0", "]", "+", "m", "[", "1", "]", "for", "m", "in", "matches_after", ")", "seq_before", "=", "sequence", "[", "index", "-", "ngram_start", "-", "_max_insertions", ":", "index", "]", "if", "seq_before", ".", "endswith", "(", "subseq_before", ")", ":", "matches_before", "=", "[", "(", "0", ",", "0", ")", "]", "else", ":", "matches_before", "=", "_expand", "(", "subseq_before_reversed", ",", "seq_before", "[", ":", ":", "-", "1", "]", ",", "_max_substitutions", ",", "_max_insertions", ",", "_max_l_dist", ",", ")", "for", "(", "subs_before", ",", "ins_before", ")", "in", "matches_before", ":", "for", "(", "subs_after", ",", "ins_after", ")", "in", "matches_after", ":", "if", "(", "subs_before", "+", "subs_after", "<=", "max_substitutions", "and", "ins_before", "+", "ins_after", "<=", "max_insertions", "and", "subs_before", "+", "subs_after", "+", "ins_before", "+", "ins_after", "<=", "max_l_dist", ")", ":", "matches", ".", "append", "(", "Match", "(", "start", "=", "index", "-", "ngram_start", "-", "ins_before", ",", "end", "=", "index", "-", "ngram_start", "+", "subseq_len", "+", "ins_after", ",", "dist", "=", "subs_before", "+", "subs_after", "+", "ins_before", "+", "ins_after", ",", ")", ")", "matched_indexes", "|=", "set", "(", "range", "(", "index", "-", "ngram_start", "-", "ins_before", ",", "index", "-", "ngram_start", "-", "ins_before", "+", "max_insertions", "+", "1", ",", ")", ")", "return", "sorted", "(", "matches", ",", "key", "=", "lambda", "match", ":", "match", ".", "start", ")" ]
44.117647
24.705882
def load_profile(self, profile_name): """Load user profiles from file.""" data = self.storage.get_user_profiles(profile_name) for x in data.get_user_views(): self._graph.add_edge(int(x[0]), int(x[1]), {'weight': float(x[2])}) self.all_records[int(x[1])] += 1 return self._graph
[ "def", "load_profile", "(", "self", ",", "profile_name", ")", ":", "data", "=", "self", ".", "storage", ".", "get_user_profiles", "(", "profile_name", ")", "for", "x", "in", "data", ".", "get_user_views", "(", ")", ":", "self", ".", "_graph", ".", "add_edge", "(", "int", "(", "x", "[", "0", "]", ")", ",", "int", "(", "x", "[", "1", "]", ")", ",", "{", "'weight'", ":", "float", "(", "x", "[", "2", "]", ")", "}", ")", "self", ".", "all_records", "[", "int", "(", "x", "[", "1", "]", ")", "]", "+=", "1", "return", "self", ".", "_graph" ]
36.333333
17.777778
def set_welcome_message(self): """Create and insert welcome message.""" string = html_header() string += welcome_message().to_html() string += html_footer() self.welcome_message.setHtml(string)
[ "def", "set_welcome_message", "(", "self", ")", ":", "string", "=", "html_header", "(", ")", "string", "+=", "welcome_message", "(", ")", ".", "to_html", "(", ")", "string", "+=", "html_footer", "(", ")", "self", ".", "welcome_message", ".", "setHtml", "(", "string", ")" ]
38
6.333333
def cf_safe_name(name): """Converts a name to a safe string for a Cloudformation resource. Given a string, returns a name that is safe for use as a CloudFormation Resource. (ie: Only alphanumeric characters) """ alphanumeric = r"[a-zA-Z0-9]+" parts = re.findall(alphanumeric, name) return "".join([uppercase_first_letter(part) for part in parts])
[ "def", "cf_safe_name", "(", "name", ")", ":", "alphanumeric", "=", "r\"[a-zA-Z0-9]+\"", "parts", "=", "re", ".", "findall", "(", "alphanumeric", ",", "name", ")", "return", "\"\"", ".", "join", "(", "[", "uppercase_first_letter", "(", "part", ")", "for", "part", "in", "parts", "]", ")" ]
40.777778
15.111111
def build(self, **kwargs): """ Builds a new record subject to the restrictions in the query. Will build intermediate (join table) records as needed, and links them to the returned record so that they are saved when the returned record is. """ build_args = dict(self.where_query) build_args.update(kwargs) record = self.model(**record_args(build_args)) if self.join_args: # EXAMPLE: # Say we have a many-to-many relation like so: # Post -> Tagging -> Tag # If we are adding a tag to a post, we need to create the tagging # in addition to the tag. To do this, we add a "related record" to # the tag which is the tagging. By building the previous record, # if it exists, we can recursively build a long object tree. # That is, when we do post.tags(), we get a query that looks like: # Query(Tag).joins("taggings").where(taggings={"post_id":post.id}) # The call to "build" then creates a tag using kwargs and the where # constraint, and creates a tagging that looks like: # Tagging(post_id = post.id) and adds it to the tag's related # records. The tagging's tag_id is added once the tag is saved # which is the first time it gets an id # Join args will never have just one element next_to_build = getattr(self.record, self.join_args[-2]['table']).build() record._related_records.append(next_to_build) return record
[ "def", "build", "(", "self", ",", "*", "*", "kwargs", ")", ":", "build_args", "=", "dict", "(", "self", ".", "where_query", ")", "build_args", ".", "update", "(", "kwargs", ")", "record", "=", "self", ".", "model", "(", "*", "*", "record_args", "(", "build_args", ")", ")", "if", "self", ".", "join_args", ":", "# EXAMPLE:", "# Say we have a many-to-many relation like so:", "# Post -> Tagging -> Tag", "# If we are adding a tag to a post, we need to create the tagging", "# in addition to the tag. To do this, we add a \"related record\" to", "# the tag which is the tagging. By building the previous record,", "# if it exists, we can recursively build a long object tree.", "# That is, when we do post.tags(), we get a query that looks like:", "# Query(Tag).joins(\"taggings\").where(taggings={\"post_id\":post.id})", "# The call to \"build\" then creates a tag using kwargs and the where", "# constraint, and creates a tagging that looks like:", "# Tagging(post_id = post.id) and adds it to the tag's related", "# records. The tagging's tag_id is added once the tag is saved", "# which is the first time it gets an id", "# Join args will never have just one element", "next_to_build", "=", "getattr", "(", "self", ".", "record", ",", "self", ".", "join_args", "[", "-", "2", "]", "[", "'table'", "]", ")", ".", "build", "(", ")", "record", ".", "_related_records", ".", "append", "(", "next_to_build", ")", "return", "record" ]
54.37931
23.482759
def policy_set_definitions(self): """Instance depends on the API version: * 2017-06-01-preview: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicySetDefinitionsOperations>` * 2018-03-01: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2018_03_01.operations.PolicySetDefinitionsOperations>` * 2018-05-01: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2018_05_01.operations.PolicySetDefinitionsOperations>` """ api_version = self._get_api_version('policy_set_definitions') if api_version == '2017-06-01-preview': from .v2017_06_01_preview.operations import PolicySetDefinitionsOperations as OperationClass elif api_version == '2018-03-01': from .v2018_03_01.operations import PolicySetDefinitionsOperations as OperationClass elif api_version == '2018-05-01': from .v2018_05_01.operations import PolicySetDefinitionsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
[ "def", "policy_set_definitions", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'policy_set_definitions'", ")", "if", "api_version", "==", "'2017-06-01-preview'", ":", "from", ".", "v2017_06_01_preview", ".", "operations", "import", "PolicySetDefinitionsOperations", "as", "OperationClass", "elif", "api_version", "==", "'2018-03-01'", ":", "from", ".", "v2018_03_01", ".", "operations", "import", "PolicySetDefinitionsOperations", "as", "OperationClass", "elif", "api_version", "==", "'2018-05-01'", ":", "from", ".", "v2018_05_01", ".", "operations", "import", "PolicySetDefinitionsOperations", "as", "OperationClass", "else", ":", "raise", "NotImplementedError", "(", "\"APIVersion {} is not available\"", ".", "format", "(", "api_version", ")", ")", "return", "OperationClass", "(", "self", ".", "_client", ",", "self", ".", "config", ",", "Serializer", "(", "self", ".", "_models_dict", "(", "api_version", ")", ")", ",", "Deserializer", "(", "self", ".", "_models_dict", "(", "api_version", ")", ")", ")" ]
75.823529
45.823529
def update_resource(self, resource_form): """Updates an existing resource. arg: resource_form (osid.resource.ResourceForm): the form containing the elements to be updated raise: IllegalState - ``resource_form`` already used in an update transaction raise: InvalidArgument - the form contains an invalid value raise: NullArgument - ``resource_form`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure raise: Unsupported - ``resource_form`` did not originate from ``get_resource_form_for_update()`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceAdminSession.update_resource_template collection = JSONClientValidated('resource', collection='Resource', runtime=self._runtime) if not isinstance(resource_form, ABCResourceForm): raise errors.InvalidArgument('argument type is not an ResourceForm') if not resource_form.is_for_update(): raise errors.InvalidArgument('the ResourceForm is for update only, not create') try: if self._forms[resource_form.get_id().get_identifier()] == UPDATED: raise errors.IllegalState('resource_form already used in an update transaction') except KeyError: raise errors.Unsupported('resource_form did not originate from this session') if not resource_form.is_valid(): raise errors.InvalidArgument('one or more of the form elements is invalid') collection.save(resource_form._my_map) self._forms[resource_form.get_id().get_identifier()] = UPDATED # Note: this is out of spec. The OSIDs don't require an object to be returned: return objects.Resource( osid_object_map=resource_form._my_map, runtime=self._runtime, proxy=self._proxy)
[ "def", "update_resource", "(", "self", ",", "resource_form", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.update_resource_template", "collection", "=", "JSONClientValidated", "(", "'resource'", ",", "collection", "=", "'Resource'", ",", "runtime", "=", "self", ".", "_runtime", ")", "if", "not", "isinstance", "(", "resource_form", ",", "ABCResourceForm", ")", ":", "raise", "errors", ".", "InvalidArgument", "(", "'argument type is not an ResourceForm'", ")", "if", "not", "resource_form", ".", "is_for_update", "(", ")", ":", "raise", "errors", ".", "InvalidArgument", "(", "'the ResourceForm is for update only, not create'", ")", "try", ":", "if", "self", ".", "_forms", "[", "resource_form", ".", "get_id", "(", ")", ".", "get_identifier", "(", ")", "]", "==", "UPDATED", ":", "raise", "errors", ".", "IllegalState", "(", "'resource_form already used in an update transaction'", ")", "except", "KeyError", ":", "raise", "errors", ".", "Unsupported", "(", "'resource_form did not originate from this session'", ")", "if", "not", "resource_form", ".", "is_valid", "(", ")", ":", "raise", "errors", ".", "InvalidArgument", "(", "'one or more of the form elements is invalid'", ")", "collection", ".", "save", "(", "resource_form", ".", "_my_map", ")", "self", ".", "_forms", "[", "resource_form", ".", "get_id", "(", ")", ".", "get_identifier", "(", ")", "]", "=", "UPDATED", "# Note: this is out of spec. The OSIDs don't require an object to be returned:", "return", "objects", ".", "Resource", "(", "osid_object_map", "=", "resource_form", ".", "_my_map", ",", "runtime", "=", "self", ".", "_runtime", ",", "proxy", "=", "self", ".", "_proxy", ")" ]
50.731707
22.902439
def _get_tag(self, url, tag, print_warn=True): """Check if url is available and returns given tag type :param url: url to content relative to base url :param anchor: anchor type to return :param print_warn: if True print warn when url is unavailable """ # construct complete url complete_url = urljoin(self.base_url, url) # check if exists if requests.get('http:' + complete_url).ok: # construct tag if tag == 'script': return '<script src="{0}"></script>'.format(complete_url) elif tag == 'stylesheet': return '<link rel="stylesheet" href="{0}">'.format(complete_url) else: warnings.warn('Given tag is not valid') elif print_warn: warnings.warn('Url {0} not valid'.format(complete_url)) return None
[ "def", "_get_tag", "(", "self", ",", "url", ",", "tag", ",", "print_warn", "=", "True", ")", ":", "# construct complete url", "complete_url", "=", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", "# check if exists", "if", "requests", ".", "get", "(", "'http:'", "+", "complete_url", ")", ".", "ok", ":", "# construct tag", "if", "tag", "==", "'script'", ":", "return", "'<script src=\"{0}\"></script>'", ".", "format", "(", "complete_url", ")", "elif", "tag", "==", "'stylesheet'", ":", "return", "'<link rel=\"stylesheet\" href=\"{0}\">'", ".", "format", "(", "complete_url", ")", "else", ":", "warnings", ".", "warn", "(", "'Given tag is not valid'", ")", "elif", "print_warn", ":", "warnings", ".", "warn", "(", "'Url {0} not valid'", ".", "format", "(", "complete_url", ")", ")", "return", "None" ]
43.8
14.9
def get_param_arg(param, idx, klass, arg, attr='id'): """Return the correct value for a fabric from `arg`.""" if isinstance(arg, klass): return getattr(arg, attr) elif isinstance(arg, (int, str)): return arg else: raise TypeError( "%s[%d] must be int, str, or %s, not %s" % ( param, idx, klass.__name__, type(arg).__name__))
[ "def", "get_param_arg", "(", "param", ",", "idx", ",", "klass", ",", "arg", ",", "attr", "=", "'id'", ")", ":", "if", "isinstance", "(", "arg", ",", "klass", ")", ":", "return", "getattr", "(", "arg", ",", "attr", ")", "elif", "isinstance", "(", "arg", ",", "(", "int", ",", "str", ")", ")", ":", "return", "arg", "else", ":", "raise", "TypeError", "(", "\"%s[%d] must be int, str, or %s, not %s\"", "%", "(", "param", ",", "idx", ",", "klass", ".", "__name__", ",", "type", "(", "arg", ")", ".", "__name__", ")", ")" ]
38.3
14.2
def _reverse_transform_column(self, table, metadata, table_name): """Reverses the transformtion on a column from table using the given parameters. Args: table (pandas.DataFrame): Dataframe containing column to transform. metadata (dict): Metadata for given column. table_name (str): Name of table in original dataset. Returns: pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True, it will contain a second column containing 0 and 1 marking if that value was originally null or not. It will return None in the case the column is not in the table. """ column_name = metadata['name'] if column_name not in table: return null_name = '?' + column_name content = pd.DataFrame(columns=[column_name], index=table.index) transformer = self.transformers[(table_name, column_name)] content[column_name] = transformer.reverse_transform(table[column_name].to_frame()) if self.missing and null_name in table[column_name]: content[null_name] = table.pop(null_name) null_transformer = transformers.NullTransformer(metadata) content[column_name] = null_transformer.reverse_transform(content) return content
[ "def", "_reverse_transform_column", "(", "self", ",", "table", ",", "metadata", ",", "table_name", ")", ":", "column_name", "=", "metadata", "[", "'name'", "]", "if", "column_name", "not", "in", "table", ":", "return", "null_name", "=", "'?'", "+", "column_name", "content", "=", "pd", ".", "DataFrame", "(", "columns", "=", "[", "column_name", "]", ",", "index", "=", "table", ".", "index", ")", "transformer", "=", "self", ".", "transformers", "[", "(", "table_name", ",", "column_name", ")", "]", "content", "[", "column_name", "]", "=", "transformer", ".", "reverse_transform", "(", "table", "[", "column_name", "]", ".", "to_frame", "(", ")", ")", "if", "self", ".", "missing", "and", "null_name", "in", "table", "[", "column_name", "]", ":", "content", "[", "null_name", "]", "=", "table", ".", "pop", "(", "null_name", ")", "null_transformer", "=", "transformers", ".", "NullTransformer", "(", "metadata", ")", "content", "[", "column_name", "]", "=", "null_transformer", ".", "reverse_transform", "(", "content", ")", "return", "content" ]
44.483871
28.387097
def div(a,b): """``div(a,b)`` is like ``a // b`` if ``b`` devides ``a``, otherwise an `ValueError` is raised. >>> div(10,2) 5 >>> div(10,3) Traceback (most recent call last): ... ValueError: 3 does not divide 10 """ res, fail = divmod(a,b) if fail: raise ValueError("%r does not divide %r" % (b,a)) else: return res
[ "def", "div", "(", "a", ",", "b", ")", ":", "res", ",", "fail", "=", "divmod", "(", "a", ",", "b", ")", "if", "fail", ":", "raise", "ValueError", "(", "\"%r does not divide %r\"", "%", "(", "b", ",", "a", ")", ")", "else", ":", "return", "res" ]
22.8125
19.25
def get_range_start_line_number(self,rng): """ .. warning:: not implemented """ sys.stderr.write("error unimplemented get_range_start_line\n") sys.exit() for i in range(0,len(self._lines)): if rng.cmp(self._lines[i]['rng'])==0: return i+1 return None
[ "def", "get_range_start_line_number", "(", "self", ",", "rng", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"error unimplemented get_range_start_line\\n\"", ")", "sys", ".", "exit", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "self", ".", "_lines", ")", ")", ":", "if", "rng", ".", "cmp", "(", "self", ".", "_lines", "[", "i", "]", "[", "'rng'", "]", ")", "==", "0", ":", "return", "i", "+", "1", "return", "None" ]
30.666667
11.333333
def data_manipulation_sh(network): """ Adds missing components to run calculations with SH scenarios. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA """ from shapely.geometry import Point, LineString, MultiLineString from geoalchemy2.shape import from_shape, to_shape # add connection from Luebeck to Siems new_bus = str(network.buses.index.astype(np.int64).max() + 1) new_trafo = str(network.transformers.index.astype(np.int64).max() + 1) new_line = str(network.lines.index.astype(np.int64).max() + 1) network.add("Bus", new_bus, carrier='AC', v_nom=220, x=10.760835, y=53.909745) network.add("Transformer", new_trafo, bus0="25536", bus1=new_bus, x=1.29960, tap_ratio=1, s_nom=1600) network.add("Line", new_line, bus0="26387", bus1=new_bus, x=0.0001, s_nom=1600) network.lines.loc[new_line, 'cables'] = 3.0 # bus geom point_bus1 = Point(10.760835, 53.909745) network.buses.set_value(new_bus, 'geom', from_shape(point_bus1, 4326)) # line geom/topo network.lines.set_value(new_line, 'geom', from_shape(MultiLineString( [LineString([to_shape(network. buses.geom['26387']), point_bus1])]), 4326)) network.lines.set_value(new_line, 'topo', from_shape(LineString( [to_shape(network.buses.geom['26387']), point_bus1]), 4326)) # trafo geom/topo network.transformers.set_value(new_trafo, 'geom', from_shape(MultiLineString( [LineString( [to_shape(network .buses.geom['25536']), point_bus1])]), 4326)) network.transformers.set_value(new_trafo, 'topo', from_shape( LineString([to_shape(network.buses.geom['25536']), point_bus1]), 4326)) return
[ "def", "data_manipulation_sh", "(", "network", ")", ":", "from", "shapely", ".", "geometry", "import", "Point", ",", "LineString", ",", "MultiLineString", "from", "geoalchemy2", ".", "shape", "import", "from_shape", ",", "to_shape", "# add connection from Luebeck to Siems", "new_bus", "=", "str", "(", "network", ".", "buses", ".", "index", ".", "astype", "(", "np", ".", "int64", ")", ".", "max", "(", ")", "+", "1", ")", "new_trafo", "=", "str", "(", "network", ".", "transformers", ".", "index", ".", "astype", "(", "np", ".", "int64", ")", ".", "max", "(", ")", "+", "1", ")", "new_line", "=", "str", "(", "network", ".", "lines", ".", "index", ".", "astype", "(", "np", ".", "int64", ")", ".", "max", "(", ")", "+", "1", ")", "network", ".", "add", "(", "\"Bus\"", ",", "new_bus", ",", "carrier", "=", "'AC'", ",", "v_nom", "=", "220", ",", "x", "=", "10.760835", ",", "y", "=", "53.909745", ")", "network", ".", "add", "(", "\"Transformer\"", ",", "new_trafo", ",", "bus0", "=", "\"25536\"", ",", "bus1", "=", "new_bus", ",", "x", "=", "1.29960", ",", "tap_ratio", "=", "1", ",", "s_nom", "=", "1600", ")", "network", ".", "add", "(", "\"Line\"", ",", "new_line", ",", "bus0", "=", "\"26387\"", ",", "bus1", "=", "new_bus", ",", "x", "=", "0.0001", ",", "s_nom", "=", "1600", ")", "network", ".", "lines", ".", "loc", "[", "new_line", ",", "'cables'", "]", "=", "3.0", "# bus geom", "point_bus1", "=", "Point", "(", "10.760835", ",", "53.909745", ")", "network", ".", "buses", ".", "set_value", "(", "new_bus", ",", "'geom'", ",", "from_shape", "(", "point_bus1", ",", "4326", ")", ")", "# line geom/topo", "network", ".", "lines", ".", "set_value", "(", "new_line", ",", "'geom'", ",", "from_shape", "(", "MultiLineString", "(", "[", "LineString", "(", "[", "to_shape", "(", "network", ".", "buses", ".", "geom", "[", "'26387'", "]", ")", ",", "point_bus1", "]", ")", "]", ")", ",", "4326", ")", ")", "network", ".", "lines", ".", "set_value", "(", "new_line", ",", "'topo'", ",", "from_shape", "(", "LineString", "(", "[", "to_shape", "(", "network", ".", "buses", ".", "geom", "[", "'26387'", "]", ")", ",", "point_bus1", "]", ")", ",", "4326", ")", ")", "# trafo geom/topo", "network", ".", "transformers", ".", "set_value", "(", "new_trafo", ",", "'geom'", ",", "from_shape", "(", "MultiLineString", "(", "[", "LineString", "(", "[", "to_shape", "(", "network", ".", "buses", ".", "geom", "[", "'25536'", "]", ")", ",", "point_bus1", "]", ")", "]", ")", ",", "4326", ")", ")", "network", ".", "transformers", ".", "set_value", "(", "new_trafo", ",", "'topo'", ",", "from_shape", "(", "LineString", "(", "[", "to_shape", "(", "network", ".", "buses", ".", "geom", "[", "'25536'", "]", ")", ",", "point_bus1", "]", ")", ",", "4326", ")", ")", "return" ]
40.854167
22.5
def create_tag(self, tags): """Create tags for a Point in the language you specify. Tags can only contain alphanumeric (unicode) characters and the underscore. Tags will be stored lower-cased. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure tags (mandatory) (list) - the list of tags you want to add to your Point, e.g. ["garden", "soil"] """ if isinstance(tags, str): tags = [tags] evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=False) self._client._wait_and_except_if_failed(evt)
[ "def", "create_tag", "(", "self", ",", "tags", ")", ":", "if", "isinstance", "(", "tags", ",", "str", ")", ":", "tags", "=", "[", "tags", "]", "evt", "=", "self", ".", "_client", ".", "_request_point_tag_update", "(", "self", ".", "_type", ",", "self", ".", "__lid", ",", "self", ".", "__pid", ",", "tags", ",", "delete", "=", "False", ")", "self", ".", "_client", ".", "_wait_and_except_if_failed", "(", "evt", ")" ]
48.722222
29.166667
def obsoleteas(self, to='name_short'): """ Return obsolete countries in the specified classification Parameters ---------- to : str, optional Output classification (valid str for an index of country_data file), default: name_short Returns ------- Pandas DataFrame """ if isinstance(to, str): to = [to] return self.data[self.data.obsolete > 0][to]
[ "def", "obsoleteas", "(", "self", ",", "to", "=", "'name_short'", ")", ":", "if", "isinstance", "(", "to", ",", "str", ")", ":", "to", "=", "[", "to", "]", "return", "self", ".", "data", "[", "self", ".", "data", ".", "obsolete", ">", "0", "]", "[", "to", "]" ]
25.333333
19
def tell(self, solutions, function_values, check_points=None, copy=False): """pass objective function values to prepare for next iteration. This core procedure of the CMA-ES algorithm updates all state variables, in particular the two evolution paths, the distribution mean, the covariance matrix and a step-size. Arguments --------- `solutions` list or array of candidate solution points (of type `numpy.ndarray`), most presumably before delivered by method `ask()` or `ask_and_eval()`. `function_values` list or array of objective function values corresponding to the respective points. Beside for termination decisions, only the ranking of values in `function_values` is used. `check_points` If ``check_points is None``, only solutions that are not generated by `ask()` are possibly clipped (recommended). ``False`` does not clip any solution (not recommended). If ``True``, clips solutions that realize long steps (i.e. also those that are unlikely to be generated with `ask()`). `check_points` can be a list of indices to be checked in solutions. `copy` ``solutions`` can be modified in this routine, if ``copy is False`` Details ------- `tell()` updates the parameters of the multivariate normal search distribution, namely covariance matrix and step-size and updates also the attributes ``countiter`` and ``countevals``. To check the points for consistency is quadratic in the dimension (like sampling points). Bugs ---- The effect of changing the solutions delivered by `ask()` depends on whether boundary handling is applied. With boundary handling, modifications are disregarded. This is necessary to apply the default boundary handling that uses unrepaired solutions but might change in future. Example ------- :: import cma func = cma.fcts.elli # choose objective function es = cma.CMAEvolutionStrategy(cma.np.random.rand(10), 1) while not es.stop(): X = es.ask() es.tell(X, [func(x) for x in X]) es.result() # where the result can be found :See: class `CMAEvolutionStrategy`, `ask()`, `ask_and_eval()`, `fmin()` """ if self._flgtelldone: raise _Error('tell should only be called once per iteration') lam = len(solutions) if lam != array(function_values).shape[0]: raise _Error('for each candidate solution ' + 'a function value must be provided') if lam + self.sp.lam_mirr < 3: raise _Error('population size ' + str(lam) + ' is too small when option CMA_mirrors * popsize < 0.5') if not isscalar(function_values[0]): if isscalar(function_values[0][0]): if self.countiter <= 1: _print_warning('function values are not a list of scalars (further warnings are suppressed)') function_values = [val[0] for val in function_values] else: raise _Error('objective function values must be a list of scalars') # ## prepare N = self.N sp = self.sp if lam < sp.mu: # rather decrease cmean instead of having mu > lambda//2 raise _Error('not enough solutions passed to function tell (mu>lambda)') self.countiter += 1 # >= 1 now self.countevals += sp.popsize * self.evaluations_per_f_value self.best.update(solutions, self.sent_solutions, function_values, self.countevals) flg_diagonal = self.opts['CMA_diagonal'] is True \ or self.countiter <= self.opts['CMA_diagonal'] if not flg_diagonal and len(self.C.shape) == 1: # C was diagonal ie 1-D # enter non-separable phase (no easy return from here) self.C = np.diag(self.C) if 1 < 3: self.B = np.eye(N) # identity(N) idx = np.argsort(self.D) self.D = self.D[idx] self.B = self.B[:, idx] self._Yneg = np.zeros((N, N)) # ## manage fitness fit = self.fit # make short cut # CPU for N,lam=20,200: this takes 10s vs 7s fit.bndpen = self.boundary_handler.update(function_values, self)(solutions, self.sent_solutions, self.gp) # for testing: # fit.bndpen = self.boundary_handler.update(function_values, self)([s.unrepaired for s in solutions]) fit.idx = np.argsort(array(fit.bndpen) + array(function_values)) fit.fit = array(function_values, copy=False)[fit.idx] # update output data TODO: this is obsolete!? However: need communicate current best x-value? # old: out['recent_x'] = self.gp.pheno(pop[0]) # self.out['recent_x'] = array(solutions[fit.idx[0]]) # TODO: change in a data structure(?) and use current as identify # self.out['recent_f'] = fit.fit[0] # fitness histories fit.hist.insert(0, fit.fit[0]) # if len(self.fit.histbest) < 120+30*N/sp.popsize or # does not help, as tablet in the beginning is the critical counter-case if ((self.countiter % 5) == 0): # 20 percent of 1e5 gen. fit.histbest.insert(0, fit.fit[0]) fit.histmedian.insert(0, np.median(fit.fit) if len(fit.fit) < 21 else fit.fit[self.popsize // 2]) if len(fit.histbest) > 2e4: # 10 + 30*N/sp.popsize: fit.histbest.pop() fit.histmedian.pop() if len(fit.hist) > 10 + 30 * N / sp.popsize: fit.hist.pop() # TODO: clean up inconsistency when an unrepaired solution is available and used # now get the genotypes pop = self.pop_sorted = [] # create pop from input argument solutions for k, s in enumerate(solutions): # use phenotype before Solution.repair() if 1 < 3: pop += [self.gp.geno(s, from_bounds=self.boundary_handler.inverse, repair=(self.repair_genotype if check_points not in (False, 0, [], ()) else None), archive=self.sent_solutions)] # takes genotype from sent_solutions, if available try: self.archive.insert(s, value=self.sent_solutions.pop(s), fitness=function_values[k]) # self.sent_solutions.pop(s) except KeyError: pass # check that TPA mirrors are available, TODO: move to TPA class? if isinstance(self.adapt_sigma, CMAAdaptSigmaTPA) and self.countiter > 3 and not (self.countiter % 3): dm = self.mean[0] - self.mean_old[0] dx0 = pop[0][0] - self.mean_old[0] dx1 = pop[1][0] - self.mean_old[0] for i in np.random.randint(1, self.N, 1): try: if not Mh.equals_approximately( (self.mean[i] - self.mean_old[i]) / (pop[0][i] - self.mean_old[i]), dm / dx0, 1e-8) or \ not Mh.equals_approximately( (self.mean[i] - self.mean_old[i]) / (pop[1][i] - self.mean_old[i]), dm / dx1, 1e-8): _print_warning('TPA error with mirrored samples', 'tell', 'CMAEvolutionStrategy', self.countiter) except ZeroDivisionError: _print_warning('zero division encountered in TPA check\n which should be very rare and is likely a bug', 'tell', 'CMAEvolutionStrategy', self.countiter) try: moldold = self.mean_old except: pass self.mean_old = self.mean mold = self.mean_old # just an alias # check and normalize each x - m # check_points is a flag (None is default: check non-known solutions) or an index list # should also a number possible (first check_points points)? if check_points not in (None, False, 0, [], ()): # useful in case of injected solutions and/or adaptive encoding, however is automatic with use_sent_solutions try: if len(check_points): idx = check_points except: idx = xrange(sp.popsize) for k in idx: self.repair_genotype(pop[k]) # only arrays can be multiple indexed pop = array(pop, copy=False) # sort pop pop = pop[fit.idx] # prepend best-ever solution to population, in case if self.opts['CMA_elitist'] and self.best.f < fit.fit[0]: if self.best.x_geno is not None: xp = [self.best.x_geno] # xp = [self.best.xdict['geno']] # xp = [self.gp.geno(self.best.x[:])] # TODO: remove # print self.mahalanobis_norm(xp[0]-self.mean) else: xp = [self.gp.geno(array(self.best.x, copy=True), self.boundary_handler.inverse, copy_if_changed=False)] print('genotype for elitist not found') self.clip_or_fit_solutions(xp, [0]) pop = array([xp[0]] + list(pop)) elif self.opts['CMA_elitist'] == 'initial': # current solution was better self.opts['CMA_elitist'] = False self.pop_sorted = pop # compute new mean self.mean = mold + self.sp.cmean * \ (sum(sp.weights * pop[0:sp.mu].T, 1) - mold) # check Delta m (this is not default, but could become at some point) # CAVE: upper_length=sqrt(2)+2 is too restrictive, test upper_length = sqrt(2*N) thoroughly. # replaced by repair_geno? # simple test case injecting self.mean: # self.mean = 1e-4 * self.sigma * np.random.randn(N) if 1 < 3: cmean = self.sp.cmean # zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz # get learning rate constants cc, c1, cmu = sp.cc, sp.c1, sp.cmu if flg_diagonal: cc, c1, cmu = sp.cc_sep, sp.c1_sep, sp.cmu_sep # now the real work can start hsig = self.adapt_sigma.hsig(self) # ps update must be done here in separable case # hsig = sum(self.ps**2) / self.N < 2 + 4./(N+1) # adjust missing variance due to hsig, in 4-D with damps=1e99 and sig0 small # hsig leads to premature convergence of C otherwise # hsiga = (1-hsig**2) * c1 * cc * (2-cc) # to be removed in future c1a = c1 - (1 - hsig**2) * c1 * cc * (2 - cc) # adjust for variance loss self.pc = (1 - cc) * self.pc + \ hsig * (sqrt(cc * (2 - cc) * sp.mueff) / self.sigma / cmean) * \ (self.mean - mold) / self.sigma_vec # covariance matrix adaptation/udpate if sp.CMA_on: # assert sp.c1 + sp.cmu < sp.mueff / N # ?? assert c1 + cmu <= 1 # default full matrix case if not flg_diagonal: Y = (pop[0:sp.mu] - mold) / (self.sigma * self.sigma_vec) Y = dot((cmu * sp.weights) * Y.T, Y) # learning rate integrated if self.sp.neg.cmuexp: tmp = (pop[-sp.neg.mu:] - mold) / (self.sigma * self.sigma_vec) # normalize to constant length (seems preferable in several aspects) for i in xrange(tmp.shape[0]): tmp[i, :] *= N**0.5 / self.mahalanobis_norm( self.sigma_vec * tmp[i, :]) / self.sigma self._Yneg *= 1 - self.sp.neg.cmuexp # for some reason necessary? self._Yneg += dot(sp.neg.weights * tmp.T, tmp) - self.C # self.update_exponential(dot(sp.neg.weights * tmp.T, tmp) - 1 * self.C, -1*self.sp.neg.cmuexp) self.C *= 1 - c1a - cmu self.C += np.outer(c1 * self.pc, self.pc) + Y self.dC[:] = np.diag(self.C) # for output and termination checking else: # separable/diagonal linear case assert(c1 + cmu <= 1) Z = np.zeros(N) for k in xrange(sp.mu): z = (pop[k] - mold) / (self.sigma * self.sigma_vec) # TODO see above Z += sp.weights[k] * z * z # is 1-D self.C = (1 - c1a - cmu) * self.C + c1 * self.pc * self.pc + cmu * Z # TODO: self.C *= exp(cmuneg * (N - dot(sp.neg.weights, **2) self.dC = self.C self.D = sqrt(self.C) # C is a 1-D array, this is why adapt_sigma needs to prepare before self.itereigenupdated = self.countiter # idx = self._mirror_idx_cov() # take half of mirrored vectors for negative update # step-size adaptation, adapt sigma # in case of TPA, function_values[0] and [1] must reflect samples colinear to xmean - xmean_old self.adapt_sigma.update(self, function_values=function_values) if self.sigma * min(self.sigma_vec * self.dC**0.5) < self.opts['minstd']: self.sigma = self.opts['minstd'] / min(self.sigma_vec * self.dC**0.5) if self.sigma * max(self.sigma_vec * self.dC**0.5) > self.opts['maxstd']: self.sigma = self.opts['maxstd'] / max(self.sigma_vec * self.dC**0.5) # g = self.countiter # N = self.N # mindx = eval(self.opts['mindx']) # if isinstance(self.opts['mindx'], basestring) else self.opts['mindx'] if self.sigma * min(self.D) < self.opts['mindx']: # TODO: sigma_vec is missing here self.sigma = self.opts['mindx'] / min(self.D) if self.sigma > 1e9 * self.sigma0: alpha = self.sigma / max(self.D) self.multiplyC(alpha) self.sigma /= alpha**0.5 self.opts['tolupsigma'] /= alpha**0.5 # to be compared with sigma # TODO increase sigma in case of a plateau? # Uncertainty noise measurement is done on an upper level # move mean into "feasible preimage", leads to weird behavior on # 40-D tablet with bound 0.1, not quite explained (constant # dragging is problematic, but why doesn't it settle), still a bug? if new_injections: self.pop_injection_directions = self.prepare_injection_directions() self.pop_sorted = [] # remove this in case pop is still needed self._flgtelldone = True
[ "def", "tell", "(", "self", ",", "solutions", ",", "function_values", ",", "check_points", "=", "None", ",", "copy", "=", "False", ")", ":", "if", "self", ".", "_flgtelldone", ":", "raise", "_Error", "(", "'tell should only be called once per iteration'", ")", "lam", "=", "len", "(", "solutions", ")", "if", "lam", "!=", "array", "(", "function_values", ")", ".", "shape", "[", "0", "]", ":", "raise", "_Error", "(", "'for each candidate solution '", "+", "'a function value must be provided'", ")", "if", "lam", "+", "self", ".", "sp", ".", "lam_mirr", "<", "3", ":", "raise", "_Error", "(", "'population size '", "+", "str", "(", "lam", ")", "+", "' is too small when option CMA_mirrors * popsize < 0.5'", ")", "if", "not", "isscalar", "(", "function_values", "[", "0", "]", ")", ":", "if", "isscalar", "(", "function_values", "[", "0", "]", "[", "0", "]", ")", ":", "if", "self", ".", "countiter", "<=", "1", ":", "_print_warning", "(", "'function values are not a list of scalars (further warnings are suppressed)'", ")", "function_values", "=", "[", "val", "[", "0", "]", "for", "val", "in", "function_values", "]", "else", ":", "raise", "_Error", "(", "'objective function values must be a list of scalars'", ")", "# ## prepare", "N", "=", "self", ".", "N", "sp", "=", "self", ".", "sp", "if", "lam", "<", "sp", ".", "mu", ":", "# rather decrease cmean instead of having mu > lambda//2", "raise", "_Error", "(", "'not enough solutions passed to function tell (mu>lambda)'", ")", "self", ".", "countiter", "+=", "1", "# >= 1 now", "self", ".", "countevals", "+=", "sp", ".", "popsize", "*", "self", ".", "evaluations_per_f_value", "self", ".", "best", ".", "update", "(", "solutions", ",", "self", ".", "sent_solutions", ",", "function_values", ",", "self", ".", "countevals", ")", "flg_diagonal", "=", "self", ".", "opts", "[", "'CMA_diagonal'", "]", "is", "True", "or", "self", ".", "countiter", "<=", "self", ".", "opts", "[", "'CMA_diagonal'", "]", "if", "not", "flg_diagonal", "and", "len", "(", "self", ".", "C", ".", "shape", ")", "==", "1", ":", "# C was diagonal ie 1-D", "# enter non-separable phase (no easy return from here)", "self", ".", "C", "=", "np", ".", "diag", "(", "self", ".", "C", ")", "if", "1", "<", "3", ":", "self", ".", "B", "=", "np", ".", "eye", "(", "N", ")", "# identity(N)", "idx", "=", "np", ".", "argsort", "(", "self", ".", "D", ")", "self", ".", "D", "=", "self", ".", "D", "[", "idx", "]", "self", ".", "B", "=", "self", ".", "B", "[", ":", ",", "idx", "]", "self", ".", "_Yneg", "=", "np", ".", "zeros", "(", "(", "N", ",", "N", ")", ")", "# ## manage fitness", "fit", "=", "self", ".", "fit", "# make short cut", "# CPU for N,lam=20,200: this takes 10s vs 7s", "fit", ".", "bndpen", "=", "self", ".", "boundary_handler", ".", "update", "(", "function_values", ",", "self", ")", "(", "solutions", ",", "self", ".", "sent_solutions", ",", "self", ".", "gp", ")", "# for testing:", "# fit.bndpen = self.boundary_handler.update(function_values, self)([s.unrepaired for s in solutions])", "fit", ".", "idx", "=", "np", ".", "argsort", "(", "array", "(", "fit", ".", "bndpen", ")", "+", "array", "(", "function_values", ")", ")", "fit", ".", "fit", "=", "array", "(", "function_values", ",", "copy", "=", "False", ")", "[", "fit", ".", "idx", "]", "# update output data TODO: this is obsolete!? However: need communicate current best x-value?", "# old: out['recent_x'] = self.gp.pheno(pop[0])", "# self.out['recent_x'] = array(solutions[fit.idx[0]]) # TODO: change in a data structure(?) and use current as identify", "# self.out['recent_f'] = fit.fit[0]", "# fitness histories", "fit", ".", "hist", ".", "insert", "(", "0", ",", "fit", ".", "fit", "[", "0", "]", ")", "# if len(self.fit.histbest) < 120+30*N/sp.popsize or # does not help, as tablet in the beginning is the critical counter-case", "if", "(", "(", "self", ".", "countiter", "%", "5", ")", "==", "0", ")", ":", "# 20 percent of 1e5 gen.", "fit", ".", "histbest", ".", "insert", "(", "0", ",", "fit", ".", "fit", "[", "0", "]", ")", "fit", ".", "histmedian", ".", "insert", "(", "0", ",", "np", ".", "median", "(", "fit", ".", "fit", ")", "if", "len", "(", "fit", ".", "fit", ")", "<", "21", "else", "fit", ".", "fit", "[", "self", ".", "popsize", "//", "2", "]", ")", "if", "len", "(", "fit", ".", "histbest", ")", ">", "2e4", ":", "# 10 + 30*N/sp.popsize:", "fit", ".", "histbest", ".", "pop", "(", ")", "fit", ".", "histmedian", ".", "pop", "(", ")", "if", "len", "(", "fit", ".", "hist", ")", ">", "10", "+", "30", "*", "N", "/", "sp", ".", "popsize", ":", "fit", ".", "hist", ".", "pop", "(", ")", "# TODO: clean up inconsistency when an unrepaired solution is available and used", "# now get the genotypes", "pop", "=", "self", ".", "pop_sorted", "=", "[", "]", "# create pop from input argument solutions", "for", "k", ",", "s", "in", "enumerate", "(", "solutions", ")", ":", "# use phenotype before Solution.repair()", "if", "1", "<", "3", ":", "pop", "+=", "[", "self", ".", "gp", ".", "geno", "(", "s", ",", "from_bounds", "=", "self", ".", "boundary_handler", ".", "inverse", ",", "repair", "=", "(", "self", ".", "repair_genotype", "if", "check_points", "not", "in", "(", "False", ",", "0", ",", "[", "]", ",", "(", ")", ")", "else", "None", ")", ",", "archive", "=", "self", ".", "sent_solutions", ")", "]", "# takes genotype from sent_solutions, if available", "try", ":", "self", ".", "archive", ".", "insert", "(", "s", ",", "value", "=", "self", ".", "sent_solutions", ".", "pop", "(", "s", ")", ",", "fitness", "=", "function_values", "[", "k", "]", ")", "# self.sent_solutions.pop(s)", "except", "KeyError", ":", "pass", "# check that TPA mirrors are available, TODO: move to TPA class?", "if", "isinstance", "(", "self", ".", "adapt_sigma", ",", "CMAAdaptSigmaTPA", ")", "and", "self", ".", "countiter", ">", "3", "and", "not", "(", "self", ".", "countiter", "%", "3", ")", ":", "dm", "=", "self", ".", "mean", "[", "0", "]", "-", "self", ".", "mean_old", "[", "0", "]", "dx0", "=", "pop", "[", "0", "]", "[", "0", "]", "-", "self", ".", "mean_old", "[", "0", "]", "dx1", "=", "pop", "[", "1", "]", "[", "0", "]", "-", "self", ".", "mean_old", "[", "0", "]", "for", "i", "in", "np", ".", "random", ".", "randint", "(", "1", ",", "self", ".", "N", ",", "1", ")", ":", "try", ":", "if", "not", "Mh", ".", "equals_approximately", "(", "(", "self", ".", "mean", "[", "i", "]", "-", "self", ".", "mean_old", "[", "i", "]", ")", "/", "(", "pop", "[", "0", "]", "[", "i", "]", "-", "self", ".", "mean_old", "[", "i", "]", ")", ",", "dm", "/", "dx0", ",", "1e-8", ")", "or", "not", "Mh", ".", "equals_approximately", "(", "(", "self", ".", "mean", "[", "i", "]", "-", "self", ".", "mean_old", "[", "i", "]", ")", "/", "(", "pop", "[", "1", "]", "[", "i", "]", "-", "self", ".", "mean_old", "[", "i", "]", ")", ",", "dm", "/", "dx1", ",", "1e-8", ")", ":", "_print_warning", "(", "'TPA error with mirrored samples'", ",", "'tell'", ",", "'CMAEvolutionStrategy'", ",", "self", ".", "countiter", ")", "except", "ZeroDivisionError", ":", "_print_warning", "(", "'zero division encountered in TPA check\\n which should be very rare and is likely a bug'", ",", "'tell'", ",", "'CMAEvolutionStrategy'", ",", "self", ".", "countiter", ")", "try", ":", "moldold", "=", "self", ".", "mean_old", "except", ":", "pass", "self", ".", "mean_old", "=", "self", ".", "mean", "mold", "=", "self", ".", "mean_old", "# just an alias", "# check and normalize each x - m", "# check_points is a flag (None is default: check non-known solutions) or an index list", "# should also a number possible (first check_points points)?", "if", "check_points", "not", "in", "(", "None", ",", "False", ",", "0", ",", "[", "]", ",", "(", ")", ")", ":", "# useful in case of injected solutions and/or adaptive encoding, however is automatic with use_sent_solutions", "try", ":", "if", "len", "(", "check_points", ")", ":", "idx", "=", "check_points", "except", ":", "idx", "=", "xrange", "(", "sp", ".", "popsize", ")", "for", "k", "in", "idx", ":", "self", ".", "repair_genotype", "(", "pop", "[", "k", "]", ")", "# only arrays can be multiple indexed", "pop", "=", "array", "(", "pop", ",", "copy", "=", "False", ")", "# sort pop", "pop", "=", "pop", "[", "fit", ".", "idx", "]", "# prepend best-ever solution to population, in case", "if", "self", ".", "opts", "[", "'CMA_elitist'", "]", "and", "self", ".", "best", ".", "f", "<", "fit", ".", "fit", "[", "0", "]", ":", "if", "self", ".", "best", ".", "x_geno", "is", "not", "None", ":", "xp", "=", "[", "self", ".", "best", ".", "x_geno", "]", "# xp = [self.best.xdict['geno']]", "# xp = [self.gp.geno(self.best.x[:])] # TODO: remove", "# print self.mahalanobis_norm(xp[0]-self.mean)", "else", ":", "xp", "=", "[", "self", ".", "gp", ".", "geno", "(", "array", "(", "self", ".", "best", ".", "x", ",", "copy", "=", "True", ")", ",", "self", ".", "boundary_handler", ".", "inverse", ",", "copy_if_changed", "=", "False", ")", "]", "print", "(", "'genotype for elitist not found'", ")", "self", ".", "clip_or_fit_solutions", "(", "xp", ",", "[", "0", "]", ")", "pop", "=", "array", "(", "[", "xp", "[", "0", "]", "]", "+", "list", "(", "pop", ")", ")", "elif", "self", ".", "opts", "[", "'CMA_elitist'", "]", "==", "'initial'", ":", "# current solution was better", "self", ".", "opts", "[", "'CMA_elitist'", "]", "=", "False", "self", ".", "pop_sorted", "=", "pop", "# compute new mean", "self", ".", "mean", "=", "mold", "+", "self", ".", "sp", ".", "cmean", "*", "(", "sum", "(", "sp", ".", "weights", "*", "pop", "[", "0", ":", "sp", ".", "mu", "]", ".", "T", ",", "1", ")", "-", "mold", ")", "# check Delta m (this is not default, but could become at some point)", "# CAVE: upper_length=sqrt(2)+2 is too restrictive, test upper_length = sqrt(2*N) thoroughly.", "# replaced by repair_geno?", "# simple test case injecting self.mean:", "# self.mean = 1e-4 * self.sigma * np.random.randn(N)", "if", "1", "<", "3", ":", "cmean", "=", "self", ".", "sp", ".", "cmean", "# zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", "# get learning rate constants", "cc", ",", "c1", ",", "cmu", "=", "sp", ".", "cc", ",", "sp", ".", "c1", ",", "sp", ".", "cmu", "if", "flg_diagonal", ":", "cc", ",", "c1", ",", "cmu", "=", "sp", ".", "cc_sep", ",", "sp", ".", "c1_sep", ",", "sp", ".", "cmu_sep", "# now the real work can start", "hsig", "=", "self", ".", "adapt_sigma", ".", "hsig", "(", "self", ")", "# ps update must be done here in separable case", "# hsig = sum(self.ps**2) / self.N < 2 + 4./(N+1)", "# adjust missing variance due to hsig, in 4-D with damps=1e99 and sig0 small", "# hsig leads to premature convergence of C otherwise", "# hsiga = (1-hsig**2) * c1 * cc * (2-cc) # to be removed in future", "c1a", "=", "c1", "-", "(", "1", "-", "hsig", "**", "2", ")", "*", "c1", "*", "cc", "*", "(", "2", "-", "cc", ")", "# adjust for variance loss", "self", ".", "pc", "=", "(", "1", "-", "cc", ")", "*", "self", ".", "pc", "+", "hsig", "*", "(", "sqrt", "(", "cc", "*", "(", "2", "-", "cc", ")", "*", "sp", ".", "mueff", ")", "/", "self", ".", "sigma", "/", "cmean", ")", "*", "(", "self", ".", "mean", "-", "mold", ")", "/", "self", ".", "sigma_vec", "# covariance matrix adaptation/udpate", "if", "sp", ".", "CMA_on", ":", "# assert sp.c1 + sp.cmu < sp.mueff / N # ??", "assert", "c1", "+", "cmu", "<=", "1", "# default full matrix case", "if", "not", "flg_diagonal", ":", "Y", "=", "(", "pop", "[", "0", ":", "sp", ".", "mu", "]", "-", "mold", ")", "/", "(", "self", ".", "sigma", "*", "self", ".", "sigma_vec", ")", "Y", "=", "dot", "(", "(", "cmu", "*", "sp", ".", "weights", ")", "*", "Y", ".", "T", ",", "Y", ")", "# learning rate integrated", "if", "self", ".", "sp", ".", "neg", ".", "cmuexp", ":", "tmp", "=", "(", "pop", "[", "-", "sp", ".", "neg", ".", "mu", ":", "]", "-", "mold", ")", "/", "(", "self", ".", "sigma", "*", "self", ".", "sigma_vec", ")", "# normalize to constant length (seems preferable in several aspects)", "for", "i", "in", "xrange", "(", "tmp", ".", "shape", "[", "0", "]", ")", ":", "tmp", "[", "i", ",", ":", "]", "*=", "N", "**", "0.5", "/", "self", ".", "mahalanobis_norm", "(", "self", ".", "sigma_vec", "*", "tmp", "[", "i", ",", ":", "]", ")", "/", "self", ".", "sigma", "self", ".", "_Yneg", "*=", "1", "-", "self", ".", "sp", ".", "neg", ".", "cmuexp", "# for some reason necessary?", "self", ".", "_Yneg", "+=", "dot", "(", "sp", ".", "neg", ".", "weights", "*", "tmp", ".", "T", ",", "tmp", ")", "-", "self", ".", "C", "# self.update_exponential(dot(sp.neg.weights * tmp.T, tmp) - 1 * self.C, -1*self.sp.neg.cmuexp)", "self", ".", "C", "*=", "1", "-", "c1a", "-", "cmu", "self", ".", "C", "+=", "np", ".", "outer", "(", "c1", "*", "self", ".", "pc", ",", "self", ".", "pc", ")", "+", "Y", "self", ".", "dC", "[", ":", "]", "=", "np", ".", "diag", "(", "self", ".", "C", ")", "# for output and termination checking", "else", ":", "# separable/diagonal linear case", "assert", "(", "c1", "+", "cmu", "<=", "1", ")", "Z", "=", "np", ".", "zeros", "(", "N", ")", "for", "k", "in", "xrange", "(", "sp", ".", "mu", ")", ":", "z", "=", "(", "pop", "[", "k", "]", "-", "mold", ")", "/", "(", "self", ".", "sigma", "*", "self", ".", "sigma_vec", ")", "# TODO see above", "Z", "+=", "sp", ".", "weights", "[", "k", "]", "*", "z", "*", "z", "# is 1-D", "self", ".", "C", "=", "(", "1", "-", "c1a", "-", "cmu", ")", "*", "self", ".", "C", "+", "c1", "*", "self", ".", "pc", "*", "self", ".", "pc", "+", "cmu", "*", "Z", "# TODO: self.C *= exp(cmuneg * (N - dot(sp.neg.weights, **2)", "self", ".", "dC", "=", "self", ".", "C", "self", ".", "D", "=", "sqrt", "(", "self", ".", "C", ")", "# C is a 1-D array, this is why adapt_sigma needs to prepare before", "self", ".", "itereigenupdated", "=", "self", ".", "countiter", "# idx = self._mirror_idx_cov() # take half of mirrored vectors for negative update", "# step-size adaptation, adapt sigma", "# in case of TPA, function_values[0] and [1] must reflect samples colinear to xmean - xmean_old", "self", ".", "adapt_sigma", ".", "update", "(", "self", ",", "function_values", "=", "function_values", ")", "if", "self", ".", "sigma", "*", "min", "(", "self", ".", "sigma_vec", "*", "self", ".", "dC", "**", "0.5", ")", "<", "self", ".", "opts", "[", "'minstd'", "]", ":", "self", ".", "sigma", "=", "self", ".", "opts", "[", "'minstd'", "]", "/", "min", "(", "self", ".", "sigma_vec", "*", "self", ".", "dC", "**", "0.5", ")", "if", "self", ".", "sigma", "*", "max", "(", "self", ".", "sigma_vec", "*", "self", ".", "dC", "**", "0.5", ")", ">", "self", ".", "opts", "[", "'maxstd'", "]", ":", "self", ".", "sigma", "=", "self", ".", "opts", "[", "'maxstd'", "]", "/", "max", "(", "self", ".", "sigma_vec", "*", "self", ".", "dC", "**", "0.5", ")", "# g = self.countiter", "# N = self.N", "# mindx = eval(self.opts['mindx'])", "# if isinstance(self.opts['mindx'], basestring) else self.opts['mindx']", "if", "self", ".", "sigma", "*", "min", "(", "self", ".", "D", ")", "<", "self", ".", "opts", "[", "'mindx'", "]", ":", "# TODO: sigma_vec is missing here", "self", ".", "sigma", "=", "self", ".", "opts", "[", "'mindx'", "]", "/", "min", "(", "self", ".", "D", ")", "if", "self", ".", "sigma", ">", "1e9", "*", "self", ".", "sigma0", ":", "alpha", "=", "self", ".", "sigma", "/", "max", "(", "self", ".", "D", ")", "self", ".", "multiplyC", "(", "alpha", ")", "self", ".", "sigma", "/=", "alpha", "**", "0.5", "self", ".", "opts", "[", "'tolupsigma'", "]", "/=", "alpha", "**", "0.5", "# to be compared with sigma", "# TODO increase sigma in case of a plateau?", "# Uncertainty noise measurement is done on an upper level", "# move mean into \"feasible preimage\", leads to weird behavior on", "# 40-D tablet with bound 0.1, not quite explained (constant", "# dragging is problematic, but why doesn't it settle), still a bug?", "if", "new_injections", ":", "self", ".", "pop_injection_directions", "=", "self", ".", "prepare_injection_directions", "(", ")", "self", ".", "pop_sorted", "=", "[", "]", "# remove this in case pop is still needed", "self", ".", "_flgtelldone", "=", "True" ]
47.660194
25.964401
def checkBim(fileName, minNumber, chromosome): """Checks the BIM file for chrN markers. :param fileName: :param minNumber: :param chromosome: :type fileName: str :type minNumber: int :type chromosome: str :returns: ``True`` if there are at least ``minNumber`` markers on chromosome ``chromosome``, ``False`` otherwise. """ nbMarkers = 0 with open(fileName, 'r') as inputFile: for line in inputFile: row = line.rstrip("\r\n").split("\t") if row[0] == chromosome: nbMarkers += 1 if nbMarkers < minNumber: return False return True
[ "def", "checkBim", "(", "fileName", ",", "minNumber", ",", "chromosome", ")", ":", "nbMarkers", "=", "0", "with", "open", "(", "fileName", ",", "'r'", ")", "as", "inputFile", ":", "for", "line", "in", "inputFile", ":", "row", "=", "line", ".", "rstrip", "(", "\"\\r\\n\"", ")", ".", "split", "(", "\"\\t\"", ")", "if", "row", "[", "0", "]", "==", "chromosome", ":", "nbMarkers", "+=", "1", "if", "nbMarkers", "<", "minNumber", ":", "return", "False", "return", "True" ]
26.25
18.125
def check_get_revoked(self): """ Create a CRL object with 100 Revoked objects, then call the get_revoked method repeatedly. """ crl = CRL() for i in xrange(100): crl.add_revoked(Revoked()) for i in xrange(self.iterations): crl.get_revoked()
[ "def", "check_get_revoked", "(", "self", ")", ":", "crl", "=", "CRL", "(", ")", "for", "i", "in", "xrange", "(", "100", ")", ":", "crl", ".", "add_revoked", "(", "Revoked", "(", ")", ")", "for", "i", "in", "xrange", "(", "self", ".", "iterations", ")", ":", "crl", ".", "get_revoked", "(", ")" ]
31.1
8.7
def _set_lang_settings(self, lang_settings): """ Checks and sets the per language WPM, singular and plural values. """ is_int = isinstance(lang_settings, int) is_dict = isinstance(lang_settings, dict) if not is_int and not is_dict: raise TypeError(("Settings 'READTIME_WPM' must be either an int," "or a dict with settings per language.")) # For backwards compatability reasons we'll allow the # READTIME_WPM setting to be set as an to override just the default # set WPM. if is_int: self.lang_settings['default']['wpm'] = lang_settings elif is_dict: for lang, conf in lang_settings.items(): if 'wpm' not in conf: raise KeyError(('Missing wpm value for the' 'language: {}'.format(lang))) if not isinstance(conf['wpm'], int): raise TypeError(('WPM is not an integer for' ' the language: {}'.format(lang))) if "min_singular" not in conf: raise KeyError(('Missing singular form for "minute" for' ' the language: {}'.format(lang))) if "min_plural" not in conf: raise KeyError(('Missing plural form for "minutes" for' ' the language: {}'.format(lang))) if "sec_singular" not in conf: raise KeyError(('Missing singular form for "second" for' ' the language: {}'.format(lang))) if "sec_plural" not in conf: raise KeyError(('Missing plural form for "seconds" for' ' the language: {}'.format(lang))) self.lang_settings = lang_settings
[ "def", "_set_lang_settings", "(", "self", ",", "lang_settings", ")", ":", "is_int", "=", "isinstance", "(", "lang_settings", ",", "int", ")", "is_dict", "=", "isinstance", "(", "lang_settings", ",", "dict", ")", "if", "not", "is_int", "and", "not", "is_dict", ":", "raise", "TypeError", "(", "(", "\"Settings 'READTIME_WPM' must be either an int,\"", "\"or a dict with settings per language.\"", ")", ")", "# For backwards compatability reasons we'll allow the", "# READTIME_WPM setting to be set as an to override just the default", "# set WPM.", "if", "is_int", ":", "self", ".", "lang_settings", "[", "'default'", "]", "[", "'wpm'", "]", "=", "lang_settings", "elif", "is_dict", ":", "for", "lang", ",", "conf", "in", "lang_settings", ".", "items", "(", ")", ":", "if", "'wpm'", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing wpm value for the'", "'language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "not", "isinstance", "(", "conf", "[", "'wpm'", "]", ",", "int", ")", ":", "raise", "TypeError", "(", "(", "'WPM is not an integer for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"min_singular\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing singular form for \"minute\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"min_plural\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing plural form for \"minutes\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"sec_singular\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing singular form for \"second\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "if", "\"sec_plural\"", "not", "in", "conf", ":", "raise", "KeyError", "(", "(", "'Missing plural form for \"seconds\" for'", "' the language: {}'", ".", "format", "(", "lang", ")", ")", ")", "self", ".", "lang_settings", "=", "lang_settings" ]
45.902439
22.682927
def conv3x3(in_channels, out_channels, stride=1): """ 3x3 convolution with padding. Original code has had bias turned off, because Batch Norm would remove the bias either way """ return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
[ "def", "conv3x3", "(", "in_channels", ",", "out_channels", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_channels", ",", "out_channels", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "bias", "=", "False", ")" ]
48.333333
21.666667
def import_class(classpath): """Import the class referred to by the fully qualified class path. Args: classpath: A full "foo.bar.MyClass" path to a class definition. Returns: The class referred to by the classpath. Raises: ImportError: If an error occurs while importing the module. AttributeError: IF the class does not exist in the imported module. """ modname, classname = classpath.rsplit(".", 1) module = importlib.import_module(modname) klass = getattr(module, classname) return klass
[ "def", "import_class", "(", "classpath", ")", ":", "modname", ",", "classname", "=", "classpath", ".", "rsplit", "(", "\".\"", ",", "1", ")", "module", "=", "importlib", ".", "import_module", "(", "modname", ")", "klass", "=", "getattr", "(", "module", ",", "classname", ")", "return", "klass" ]
32.117647
21.117647
def initialize(self): '''List all datasets for a given ...''' fmt = guess_format(self.source.url) # if format can't be guessed from the url # we fallback on the declared Content-Type if not fmt: response = requests.head(self.source.url) mime_type = response.headers.get('Content-Type', '').split(';', 1)[0] if not mime_type: msg = 'Unable to detect format from extension or mime type' raise ValueError(msg) fmt = guess_format(mime_type) if not fmt: msg = 'Unsupported mime type "{0}"'.format(mime_type) raise ValueError(msg) graph = self.parse_graph(self.source.url, fmt) self.job.data = {'graph': graph.serialize(format='json-ld', indent=None)}
[ "def", "initialize", "(", "self", ")", ":", "fmt", "=", "guess_format", "(", "self", ".", "source", ".", "url", ")", "# if format can't be guessed from the url", "# we fallback on the declared Content-Type", "if", "not", "fmt", ":", "response", "=", "requests", ".", "head", "(", "self", ".", "source", ".", "url", ")", "mime_type", "=", "response", ".", "headers", ".", "get", "(", "'Content-Type'", ",", "''", ")", ".", "split", "(", "';'", ",", "1", ")", "[", "0", "]", "if", "not", "mime_type", ":", "msg", "=", "'Unable to detect format from extension or mime type'", "raise", "ValueError", "(", "msg", ")", "fmt", "=", "guess_format", "(", "mime_type", ")", "if", "not", "fmt", ":", "msg", "=", "'Unsupported mime type \"{0}\"'", ".", "format", "(", "mime_type", ")", "raise", "ValueError", "(", "msg", ")", "graph", "=", "self", ".", "parse_graph", "(", "self", ".", "source", ".", "url", ",", "fmt", ")", "self", ".", "job", ".", "data", "=", "{", "'graph'", ":", "graph", ".", "serialize", "(", "format", "=", "'json-ld'", ",", "indent", "=", "None", ")", "}" ]
47.588235
16.294118
def mkron(a, *args): """Kronecker product of all the arguments""" if not isinstance(a, list): a = [a] a = list(a) # copy list for i in args: if isinstance(i, list): a.extend(i) else: a.append(i) c = _vector.vector() c.d = 0 c.n = _np.array([], dtype=_np.int32) c.r = _np.array([], dtype=_np.int32) c.core = [] for t in a: thetensor = t.tt if isinstance(t, _matrix.matrix) else t c.d += thetensor.d c.n = _np.concatenate((c.n, thetensor.n)) c.r = _np.concatenate((c.r[:-1], thetensor.r)) c.core = _np.concatenate((c.core, thetensor.core)) c.get_ps() return c
[ "def", "mkron", "(", "a", ",", "*", "args", ")", ":", "if", "not", "isinstance", "(", "a", ",", "list", ")", ":", "a", "=", "[", "a", "]", "a", "=", "list", "(", "a", ")", "# copy list", "for", "i", "in", "args", ":", "if", "isinstance", "(", "i", ",", "list", ")", ":", "a", ".", "extend", "(", "i", ")", "else", ":", "a", ".", "append", "(", "i", ")", "c", "=", "_vector", ".", "vector", "(", ")", "c", ".", "d", "=", "0", "c", ".", "n", "=", "_np", ".", "array", "(", "[", "]", ",", "dtype", "=", "_np", ".", "int32", ")", "c", ".", "r", "=", "_np", ".", "array", "(", "[", "]", ",", "dtype", "=", "_np", ".", "int32", ")", "c", ".", "core", "=", "[", "]", "for", "t", "in", "a", ":", "thetensor", "=", "t", ".", "tt", "if", "isinstance", "(", "t", ",", "_matrix", ".", "matrix", ")", "else", "t", "c", ".", "d", "+=", "thetensor", ".", "d", "c", ".", "n", "=", "_np", ".", "concatenate", "(", "(", "c", ".", "n", ",", "thetensor", ".", "n", ")", ")", "c", ".", "r", "=", "_np", ".", "concatenate", "(", "(", "c", ".", "r", "[", ":", "-", "1", "]", ",", "thetensor", ".", "r", ")", ")", "c", ".", "core", "=", "_np", ".", "concatenate", "(", "(", "c", ".", "core", ",", "thetensor", ".", "core", ")", ")", "c", ".", "get_ps", "(", ")", "return", "c" ]
25.846154
19.461538
def datetime(self): """ Returns a datetime object of the month, day, year, and time the game was played. """ date_string = '%s %s' % (self._date, self._year) date_string = re.sub(r' \(\d+\)', '', date_string) return datetime.strptime(date_string, '%A, %b %d %Y')
[ "def", "datetime", "(", "self", ")", ":", "date_string", "=", "'%s %s'", "%", "(", "self", ".", "_date", ",", "self", ".", "_year", ")", "date_string", "=", "re", ".", "sub", "(", "r' \\(\\d+\\)'", ",", "''", ",", "date_string", ")", "return", "datetime", ".", "strptime", "(", "date_string", ",", "'%A, %b %d %Y'", ")" ]
38.875
16.625
def status(name=None, user=None, conf_file=None, bin_env=None): ''' List programs and its state user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status ''' all_process = {} for line in status_raw(name, user, conf_file, bin_env).splitlines(): if len(line.split()) > 2: process, state, reason = line.split(None, 2) else: process, state, reason = line.split() + [''] all_process[process] = {'state': state, 'reason': reason} return all_process
[ "def", "status", "(", "name", "=", "None", ",", "user", "=", "None", ",", "conf_file", "=", "None", ",", "bin_env", "=", "None", ")", ":", "all_process", "=", "{", "}", "for", "line", "in", "status_raw", "(", "name", ",", "user", ",", "conf_file", ",", "bin_env", ")", ".", "splitlines", "(", ")", ":", "if", "len", "(", "line", ".", "split", "(", ")", ")", ">", "2", ":", "process", ",", "state", ",", "reason", "=", "line", ".", "split", "(", "None", ",", "2", ")", "else", ":", "process", ",", "state", ",", "reason", "=", "line", ".", "split", "(", ")", "+", "[", "''", "]", "all_process", "[", "process", "]", "=", "{", "'state'", ":", "state", ",", "'reason'", ":", "reason", "}", "return", "all_process" ]
27.5
23.5
def generate(self, project): """ Package name construction is based on provider, not on prefix. Prefix does not have to equal provider_prefix. """ for assignment in self.s2n_mapping: if assignment["ipprefix"] == project: self._name = assignment["package"] return self # # github.com -> github # code.google.com/p/ -> googlecode # golang.org/x/ -> golangorg # gopkg.in/check.v1 -> gopkg-check # camlistore.org # name = project if name.startswith("github.com"): name = re.sub(r"^github\.com", "github", name) if name.startswith("gopkg.in"): name = re.sub(r"gopkg\.in", "gopkg", name) # any version marks? name = re.sub(r"\.v\d", "", name) name = re.sub(r"/v\d/", "/", name) if name.startswith("code.google.com/p"): name = re.sub(r"^code\.google\.com/p", "googlecode", name) if name.startswith("golang.org/x"): name = re.sub(r"^golang\.org/x", "golangorg", name) if name.startswith("google.golang.org"): name = re.sub(r"^google\.golang\.org", "googlegolangorg", name) if name.startswith("bitbucket.org"): name = re.sub(r"^bitbucket\.org", "bitbucket", name) if name.startswith("k8s.io"): name = re.sub(r"^k8s\.io", "k8s", name) if name.endswith(".org"): name = re.sub(r"\.org$", "", name) name = name.replace("/", "-") self._name = "golang-%s" % name return self
[ "def", "generate", "(", "self", ",", "project", ")", ":", "for", "assignment", "in", "self", ".", "s2n_mapping", ":", "if", "assignment", "[", "\"ipprefix\"", "]", "==", "project", ":", "self", ".", "_name", "=", "assignment", "[", "\"package\"", "]", "return", "self", "#", "# github.com -> github", "# code.google.com/p/ -> googlecode", "# golang.org/x/ -> golangorg", "# gopkg.in/check.v1 -> gopkg-check", "# camlistore.org", "#", "name", "=", "project", "if", "name", ".", "startswith", "(", "\"github.com\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"^github\\.com\"", ",", "\"github\"", ",", "name", ")", "if", "name", ".", "startswith", "(", "\"gopkg.in\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"gopkg\\.in\"", ",", "\"gopkg\"", ",", "name", ")", "# any version marks?", "name", "=", "re", ".", "sub", "(", "r\"\\.v\\d\"", ",", "\"\"", ",", "name", ")", "name", "=", "re", ".", "sub", "(", "r\"/v\\d/\"", ",", "\"/\"", ",", "name", ")", "if", "name", ".", "startswith", "(", "\"code.google.com/p\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"^code\\.google\\.com/p\"", ",", "\"googlecode\"", ",", "name", ")", "if", "name", ".", "startswith", "(", "\"golang.org/x\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"^golang\\.org/x\"", ",", "\"golangorg\"", ",", "name", ")", "if", "name", ".", "startswith", "(", "\"google.golang.org\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"^google\\.golang\\.org\"", ",", "\"googlegolangorg\"", ",", "name", ")", "if", "name", ".", "startswith", "(", "\"bitbucket.org\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"^bitbucket\\.org\"", ",", "\"bitbucket\"", ",", "name", ")", "if", "name", ".", "startswith", "(", "\"k8s.io\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"^k8s\\.io\"", ",", "\"k8s\"", ",", "name", ")", "if", "name", ".", "endswith", "(", "\".org\"", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"\\.org$\"", ",", "\"\"", ",", "name", ")", "name", "=", "name", ".", "replace", "(", "\"/\"", ",", "\"-\"", ")", "self", ".", "_name", "=", "\"golang-%s\"", "%", "name", "return", "self" ]
25.745098
17.901961
def load_hpo_terms(adapter, hpo_lines=None, hpo_gene_lines=None, alias_genes=None): """Load the hpo terms into the database Parse the hpo lines, build the objects and add them to the database Args: adapter(MongoAdapter) hpo_lines(iterable(str)) hpo_gene_lines(iterable(str)) """ # Store the hpo terms hpo_terms = {} # Fetch the hpo terms if no file if not hpo_lines: hpo_lines = fetch_hpo_terms() # Fetch the hpo gene information if no file if not hpo_gene_lines: hpo_gene_lines = fetch_hpo_to_genes() # Parse the terms # This will yield dictionaries with information about the terms LOG.info("Parsing hpo terms") for term in parse_hpo_obo(hpo_lines): hpo_terms[term['hpo_id']] = term # Get a map with hgnc symbols to hgnc ids from scout if not alias_genes: alias_genes = adapter.genes_by_alias() LOG.info("Adding gene information to hpo terms ...") for hpo_to_symbol in parse_hpo_to_genes(hpo_gene_lines): hgnc_symbol = hpo_to_symbol['hgnc_symbol'] hpo_id = hpo_to_symbol['hpo_id'] # Fetch gene info to get correct hgnc id gene_info = alias_genes.get(hgnc_symbol) if not gene_info: continue hgnc_id = gene_info['true'] if hpo_id not in hpo_terms: continue hpo_term = hpo_terms[hpo_id] if not 'genes' in hpo_term: hpo_term['genes'] = set() hpo_term['genes'].add(hgnc_id) start_time = datetime.now() LOG.info("Loading the hpo terms...") nr_terms = len(hpo_terms) hpo_bulk = [] with progressbar(hpo_terms.values(), label="Loading hpo terms", length=nr_terms) as bar: for hpo_info in bar: hpo_bulk.append(build_hpo_term(hpo_info)) if len(hpo_bulk) > 10000: adapter.load_hpo_bulk(hpo_bulk) hpo_bulk = [] if hpo_bulk: adapter.load_hpo_bulk(hpo_bulk) LOG.info("Loading done. Nr of terms loaded {0}".format(nr_terms)) LOG.info("Time to load terms: {0}".format(datetime.now() - start_time))
[ "def", "load_hpo_terms", "(", "adapter", ",", "hpo_lines", "=", "None", ",", "hpo_gene_lines", "=", "None", ",", "alias_genes", "=", "None", ")", ":", "# Store the hpo terms", "hpo_terms", "=", "{", "}", "# Fetch the hpo terms if no file", "if", "not", "hpo_lines", ":", "hpo_lines", "=", "fetch_hpo_terms", "(", ")", "# Fetch the hpo gene information if no file", "if", "not", "hpo_gene_lines", ":", "hpo_gene_lines", "=", "fetch_hpo_to_genes", "(", ")", "# Parse the terms", "# This will yield dictionaries with information about the terms", "LOG", ".", "info", "(", "\"Parsing hpo terms\"", ")", "for", "term", "in", "parse_hpo_obo", "(", "hpo_lines", ")", ":", "hpo_terms", "[", "term", "[", "'hpo_id'", "]", "]", "=", "term", "# Get a map with hgnc symbols to hgnc ids from scout", "if", "not", "alias_genes", ":", "alias_genes", "=", "adapter", ".", "genes_by_alias", "(", ")", "LOG", ".", "info", "(", "\"Adding gene information to hpo terms ...\"", ")", "for", "hpo_to_symbol", "in", "parse_hpo_to_genes", "(", "hpo_gene_lines", ")", ":", "hgnc_symbol", "=", "hpo_to_symbol", "[", "'hgnc_symbol'", "]", "hpo_id", "=", "hpo_to_symbol", "[", "'hpo_id'", "]", "# Fetch gene info to get correct hgnc id", "gene_info", "=", "alias_genes", ".", "get", "(", "hgnc_symbol", ")", "if", "not", "gene_info", ":", "continue", "hgnc_id", "=", "gene_info", "[", "'true'", "]", "if", "hpo_id", "not", "in", "hpo_terms", ":", "continue", "hpo_term", "=", "hpo_terms", "[", "hpo_id", "]", "if", "not", "'genes'", "in", "hpo_term", ":", "hpo_term", "[", "'genes'", "]", "=", "set", "(", ")", "hpo_term", "[", "'genes'", "]", ".", "add", "(", "hgnc_id", ")", "start_time", "=", "datetime", ".", "now", "(", ")", "LOG", ".", "info", "(", "\"Loading the hpo terms...\"", ")", "nr_terms", "=", "len", "(", "hpo_terms", ")", "hpo_bulk", "=", "[", "]", "with", "progressbar", "(", "hpo_terms", ".", "values", "(", ")", ",", "label", "=", "\"Loading hpo terms\"", ",", "length", "=", "nr_terms", ")", "as", "bar", ":", "for", "hpo_info", "in", "bar", ":", "hpo_bulk", ".", "append", "(", "build_hpo_term", "(", "hpo_info", ")", ")", "if", "len", "(", "hpo_bulk", ")", ">", "10000", ":", "adapter", ".", "load_hpo_bulk", "(", "hpo_bulk", ")", "hpo_bulk", "=", "[", "]", "if", "hpo_bulk", ":", "adapter", ".", "load_hpo_bulk", "(", "hpo_bulk", ")", "LOG", ".", "info", "(", "\"Loading done. Nr of terms loaded {0}\"", ".", "format", "(", "nr_terms", ")", ")", "LOG", ".", "info", "(", "\"Time to load terms: {0}\"", ".", "format", "(", "datetime", ".", "now", "(", ")", "-", "start_time", ")", ")" ]
29.068493
19.561644
def _get_mixed_actions(labeling_bits, equation_tup, trans_recips): """ From a labeling for player 0, a tuple of hyperplane equations of the polar polytopes, and a tuple of the reciprocals of the translations, return a tuple of the corresponding, normalized mixed actions. Parameters ---------- labeling_bits : scalar(np.uint64) Integer with set bits representing a labeling of a mixed action of player 0. equation_tup : tuple(ndarray(float, ndim=1)) Tuple of hyperplane equations of the polar polytopes. trans_recips : tuple(scalar(float)) Tuple of the reciprocals of the translations. Returns ------- tuple(ndarray(float, ndim=1)) Tuple of mixed actions. """ m, n = equation_tup[0].shape[0] - 1, equation_tup[1].shape[0] - 1 out = np.empty(m+n) for pl, (start, stop, skip) in enumerate([(0, m, np.uint64(1)), (m, m+n, np.uint64(0))]): sum_ = 0. for i in range(start, stop): if (labeling_bits & np.uint64(1)) == skip: out[i] = 0 else: out[i] = equation_tup[pl][i-start] * trans_recips[pl] - \ equation_tup[pl][-1] sum_ += out[i] labeling_bits = labeling_bits >> np.uint64(1) if sum_ != 0: out[start:stop] /= sum_ return out[:m], out[m:]
[ "def", "_get_mixed_actions", "(", "labeling_bits", ",", "equation_tup", ",", "trans_recips", ")", ":", "m", ",", "n", "=", "equation_tup", "[", "0", "]", ".", "shape", "[", "0", "]", "-", "1", ",", "equation_tup", "[", "1", "]", ".", "shape", "[", "0", "]", "-", "1", "out", "=", "np", ".", "empty", "(", "m", "+", "n", ")", "for", "pl", ",", "(", "start", ",", "stop", ",", "skip", ")", "in", "enumerate", "(", "[", "(", "0", ",", "m", ",", "np", ".", "uint64", "(", "1", ")", ")", ",", "(", "m", ",", "m", "+", "n", ",", "np", ".", "uint64", "(", "0", ")", ")", "]", ")", ":", "sum_", "=", "0.", "for", "i", "in", "range", "(", "start", ",", "stop", ")", ":", "if", "(", "labeling_bits", "&", "np", ".", "uint64", "(", "1", ")", ")", "==", "skip", ":", "out", "[", "i", "]", "=", "0", "else", ":", "out", "[", "i", "]", "=", "equation_tup", "[", "pl", "]", "[", "i", "-", "start", "]", "*", "trans_recips", "[", "pl", "]", "-", "equation_tup", "[", "pl", "]", "[", "-", "1", "]", "sum_", "+=", "out", "[", "i", "]", "labeling_bits", "=", "labeling_bits", ">>", "np", ".", "uint64", "(", "1", ")", "if", "sum_", "!=", "0", ":", "out", "[", "start", ":", "stop", "]", "/=", "sum_", "return", "out", "[", ":", "m", "]", ",", "out", "[", "m", ":", "]" ]
33.238095
21.380952
def cumulative_max(self): """ Return the cumulative maximum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the maximum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float). Returns ------- out : SArray[int, float] Notes ----- - Missing values are ignored while performing the cumulative aggregate operation. Examples -------- >>> sa = SArray([1, 0, 3, 4, 2]) >>> sa.cumulative_max() dtype: int rows: 3 [1, 1, 3, 4, 4] """ from .. import extensions agg_op = "__builtin__cum_max__" return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op))
[ "def", "cumulative_max", "(", "self", ")", ":", "from", ".", ".", "import", "extensions", "agg_op", "=", "\"__builtin__cum_max__\"", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_cumulative_aggregate", "(", "agg_op", ")", ")" ]
29.821429
22.25
def get_zone_variable(self, zone_id, variable): """ Retrieve the current value of a zone variable. If the variable is not found in the local cache then the value is requested from the controller. """ try: return self._retrieve_cached_zone_variable(zone_id, variable) except UncachedVariable: return (yield from self._send_cmd("GET %s.%s" % ( zone_id.device_str(), variable)))
[ "def", "get_zone_variable", "(", "self", ",", "zone_id", ",", "variable", ")", ":", "try", ":", "return", "self", ".", "_retrieve_cached_zone_variable", "(", "zone_id", ",", "variable", ")", "except", "UncachedVariable", ":", "return", "(", "yield", "from", "self", ".", "_send_cmd", "(", "\"GET %s.%s\"", "%", "(", "zone_id", ".", "device_str", "(", ")", ",", "variable", ")", ")", ")" ]
44.9
17.9
def add_property(self, *args, **kwargs): # type: (*Any, **Any) -> Property """Add a new property to this model. See :class:`pykechain.Client.create_property` for available parameters. :return: :class:`Property` :raises APIError: in case an Error occurs """ if self.category != Category.MODEL: raise APIError("Part should be of category MODEL") return self._client.create_property(self, *args, **kwargs)
[ "def", "add_property", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# type: (*Any, **Any) -> Property", "if", "self", ".", "category", "!=", "Category", ".", "MODEL", ":", "raise", "APIError", "(", "\"Part should be of category MODEL\"", ")", "return", "self", ".", "_client", ".", "create_property", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
36.076923
17.384615
def logged(level=logging.DEBUG): """ Useful logging decorator. If a method is logged, the beginning and end of the method call will be logged at a pre-specified level. Args: level: Level to log method at. Defaults to DEBUG. """ def wrap(f): _logger = logging.getLogger("{}.{}".format(f.__module__, f.__name__)) def wrapped_f(*args, **kwargs): _logger.log(level, "Called at {} with args = {} and kwargs = {}" .format(datetime.datetime.now(), args, kwargs)) data = f(*args, **kwargs) _logger.log(level, "Done at {} with args = {} and kwargs = {}" .format(datetime.datetime.now(), args, kwargs)) return data return wrapped_f return wrap
[ "def", "logged", "(", "level", "=", "logging", ".", "DEBUG", ")", ":", "def", "wrap", "(", "f", ")", ":", "_logger", "=", "logging", ".", "getLogger", "(", "\"{}.{}\"", ".", "format", "(", "f", ".", "__module__", ",", "f", ".", "__name__", ")", ")", "def", "wrapped_f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_logger", ".", "log", "(", "level", ",", "\"Called at {} with args = {} and kwargs = {}\"", ".", "format", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "args", ",", "kwargs", ")", ")", "data", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "_logger", ".", "log", "(", "level", ",", "\"Done at {} with args = {} and kwargs = {}\"", ".", "format", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "args", ",", "kwargs", ")", ")", "return", "data", "return", "wrapped_f", "return", "wrap" ]
36.761905
23.238095
def _uniqualize(d): ''' d = {1:'a',2:'b',3:'c',4:'b'} _uniqualize(d) ''' pt = copy.deepcopy(d) seqs_for_del =[] vset = set({}) for k in pt: vset.add(pt[k]) tslen = vset.__len__() freq = {} for k in pt: v = pt[k] if(v in freq): freq[v] = freq[v] + 1 seqs_for_del.append(k) else: freq[v] = 0 npt = {} for k in pt: if(k in seqs_for_del): pass else: npt[k] = pt[k] pt = npt return(npt)
[ "def", "_uniqualize", "(", "d", ")", ":", "pt", "=", "copy", ".", "deepcopy", "(", "d", ")", "seqs_for_del", "=", "[", "]", "vset", "=", "set", "(", "{", "}", ")", "for", "k", "in", "pt", ":", "vset", ".", "add", "(", "pt", "[", "k", "]", ")", "tslen", "=", "vset", ".", "__len__", "(", ")", "freq", "=", "{", "}", "for", "k", "in", "pt", ":", "v", "=", "pt", "[", "k", "]", "if", "(", "v", "in", "freq", ")", ":", "freq", "[", "v", "]", "=", "freq", "[", "v", "]", "+", "1", "seqs_for_del", ".", "append", "(", "k", ")", "else", ":", "freq", "[", "v", "]", "=", "0", "npt", "=", "{", "}", "for", "k", "in", "pt", ":", "if", "(", "k", "in", "seqs_for_del", ")", ":", "pass", "else", ":", "npt", "[", "k", "]", "=", "pt", "[", "k", "]", "pt", "=", "npt", "return", "(", "npt", ")" ]
19.666667
20.333333
def plot_figures(): """Plot figures for tutorial.""" numpy.random.seed(1000) def foo(coord, param): return param[0] * numpy.e ** (-param[1] * coord) coord = numpy.linspace(0, 10, 200) distribution = cp.J(cp.Uniform(1, 2), cp.Uniform(0.1, 0.2)) samples = distribution.sample(50) evals = numpy.array([foo(coord, sample) for sample in samples.T]) plt.plot(coord, evals.T, "k-", lw=3, alpha=0.2) plt.xlabel(r"\verb;coord;") plt.ylabel(r"function evaluations \verb;foo;") plt.savefig("demonstration.png") plt.clf() samples = distribution.sample(1000, "H") evals = [foo(coord, sample) for sample in samples.T] expected = numpy.mean(evals, 0) deviation = numpy.std(evals, 0) plt.fill_between( coord, expected-deviation, expected+deviation, color="k", alpha=0.3 ) plt.plot(coord, expected, "k--", lw=3) plt.xlabel(r"\verb;coord;") plt.ylabel(r"function evaluations \verb;foo;") plt.title("Results using Monte Carlo simulation") plt.savefig("results_montecarlo.png") plt.clf() polynomial_expansion = cp.orth_ttr(8, distribution) foo_approx = cp.fit_regression(polynomial_expansion, samples, evals) expected = cp.E(foo_approx, distribution) deviation = cp.Std(foo_approx, distribution) plt.fill_between( coord, expected-deviation, expected+deviation, color="k", alpha=0.3 ) plt.plot(coord, expected, "k--", lw=3) plt.xlabel(r"\verb;coord;") plt.ylabel(r"function evaluations \verb;foo;") plt.title("Results using point collocation method") plt.savefig("results_collocation.png") plt.clf() absissas, weights = cp.generate_quadrature(8, distribution, "C") evals = [foo(coord, val) for val in absissas.T] foo_approx = cp.fit_quadrature(polynomial_expansion, absissas, weights, evals) expected = cp.E(foo_approx, distribution) deviation = cp.Std(foo_approx, distribution) plt.fill_between( coord, expected-deviation, expected+deviation, color="k", alpha=0.3 ) plt.plot(coord, expected, "k--", lw=3) plt.xlabel(r"\verb;coord;") plt.ylabel(r"function evaluations \verb;foo;") plt.title("Results using psuedo-spectral projection method") plt.savefig("results_spectral.png") plt.clf()
[ "def", "plot_figures", "(", ")", ":", "numpy", ".", "random", ".", "seed", "(", "1000", ")", "def", "foo", "(", "coord", ",", "param", ")", ":", "return", "param", "[", "0", "]", "*", "numpy", ".", "e", "**", "(", "-", "param", "[", "1", "]", "*", "coord", ")", "coord", "=", "numpy", ".", "linspace", "(", "0", ",", "10", ",", "200", ")", "distribution", "=", "cp", ".", "J", "(", "cp", ".", "Uniform", "(", "1", ",", "2", ")", ",", "cp", ".", "Uniform", "(", "0.1", ",", "0.2", ")", ")", "samples", "=", "distribution", ".", "sample", "(", "50", ")", "evals", "=", "numpy", ".", "array", "(", "[", "foo", "(", "coord", ",", "sample", ")", "for", "sample", "in", "samples", ".", "T", "]", ")", "plt", ".", "plot", "(", "coord", ",", "evals", ".", "T", ",", "\"k-\"", ",", "lw", "=", "3", ",", "alpha", "=", "0.2", ")", "plt", ".", "xlabel", "(", "r\"\\verb;coord;\"", ")", "plt", ".", "ylabel", "(", "r\"function evaluations \\verb;foo;\"", ")", "plt", ".", "savefig", "(", "\"demonstration.png\"", ")", "plt", ".", "clf", "(", ")", "samples", "=", "distribution", ".", "sample", "(", "1000", ",", "\"H\"", ")", "evals", "=", "[", "foo", "(", "coord", ",", "sample", ")", "for", "sample", "in", "samples", ".", "T", "]", "expected", "=", "numpy", ".", "mean", "(", "evals", ",", "0", ")", "deviation", "=", "numpy", ".", "std", "(", "evals", ",", "0", ")", "plt", ".", "fill_between", "(", "coord", ",", "expected", "-", "deviation", ",", "expected", "+", "deviation", ",", "color", "=", "\"k\"", ",", "alpha", "=", "0.3", ")", "plt", ".", "plot", "(", "coord", ",", "expected", ",", "\"k--\"", ",", "lw", "=", "3", ")", "plt", ".", "xlabel", "(", "r\"\\verb;coord;\"", ")", "plt", ".", "ylabel", "(", "r\"function evaluations \\verb;foo;\"", ")", "plt", ".", "title", "(", "\"Results using Monte Carlo simulation\"", ")", "plt", ".", "savefig", "(", "\"results_montecarlo.png\"", ")", "plt", ".", "clf", "(", ")", "polynomial_expansion", "=", "cp", ".", "orth_ttr", "(", "8", ",", "distribution", ")", "foo_approx", "=", "cp", ".", "fit_regression", "(", "polynomial_expansion", ",", "samples", ",", "evals", ")", "expected", "=", "cp", ".", "E", "(", "foo_approx", ",", "distribution", ")", "deviation", "=", "cp", ".", "Std", "(", "foo_approx", ",", "distribution", ")", "plt", ".", "fill_between", "(", "coord", ",", "expected", "-", "deviation", ",", "expected", "+", "deviation", ",", "color", "=", "\"k\"", ",", "alpha", "=", "0.3", ")", "plt", ".", "plot", "(", "coord", ",", "expected", ",", "\"k--\"", ",", "lw", "=", "3", ")", "plt", ".", "xlabel", "(", "r\"\\verb;coord;\"", ")", "plt", ".", "ylabel", "(", "r\"function evaluations \\verb;foo;\"", ")", "plt", ".", "title", "(", "\"Results using point collocation method\"", ")", "plt", ".", "savefig", "(", "\"results_collocation.png\"", ")", "plt", ".", "clf", "(", ")", "absissas", ",", "weights", "=", "cp", ".", "generate_quadrature", "(", "8", ",", "distribution", ",", "\"C\"", ")", "evals", "=", "[", "foo", "(", "coord", ",", "val", ")", "for", "val", "in", "absissas", ".", "T", "]", "foo_approx", "=", "cp", ".", "fit_quadrature", "(", "polynomial_expansion", ",", "absissas", ",", "weights", ",", "evals", ")", "expected", "=", "cp", ".", "E", "(", "foo_approx", ",", "distribution", ")", "deviation", "=", "cp", ".", "Std", "(", "foo_approx", ",", "distribution", ")", "plt", ".", "fill_between", "(", "coord", ",", "expected", "-", "deviation", ",", "expected", "+", "deviation", ",", "color", "=", "\"k\"", ",", "alpha", "=", "0.3", ")", "plt", ".", "plot", "(", "coord", ",", "expected", ",", "\"k--\"", ",", "lw", "=", "3", ")", "plt", ".", "xlabel", "(", "r\"\\verb;coord;\"", ")", "plt", ".", "ylabel", "(", "r\"function evaluations \\verb;foo;\"", ")", "plt", ".", "title", "(", "\"Results using psuedo-spectral projection method\"", ")", "plt", ".", "savefig", "(", "\"results_spectral.png\"", ")", "plt", ".", "clf", "(", ")" ]
31.859155
19.239437
def sortable_title(portal, title): """Convert title to sortable title """ if not title: return '' def_charset = portal.plone_utils.getSiteEncoding() sortabletitle = str(title.lower().strip()) # Replace numbers with zero filled numbers sortabletitle = num_sort_regex.sub(zero_fill, sortabletitle) # Truncate to prevent bloat for charset in [def_charset, 'latin-1', 'utf-8']: try: sortabletitle = safe_unicode(sortabletitle, charset)[:30] sortabletitle = sortabletitle.encode(def_charset or 'utf-8') break except UnicodeError: pass except TypeError: # If we get a TypeError if we already have a unicode string sortabletitle = sortabletitle[:30] break return sortabletitle
[ "def", "sortable_title", "(", "portal", ",", "title", ")", ":", "if", "not", "title", ":", "return", "''", "def_charset", "=", "portal", ".", "plone_utils", ".", "getSiteEncoding", "(", ")", "sortabletitle", "=", "str", "(", "title", ".", "lower", "(", ")", ".", "strip", "(", ")", ")", "# Replace numbers with zero filled numbers", "sortabletitle", "=", "num_sort_regex", ".", "sub", "(", "zero_fill", ",", "sortabletitle", ")", "# Truncate to prevent bloat", "for", "charset", "in", "[", "def_charset", ",", "'latin-1'", ",", "'utf-8'", "]", ":", "try", ":", "sortabletitle", "=", "safe_unicode", "(", "sortabletitle", ",", "charset", ")", "[", ":", "30", "]", "sortabletitle", "=", "sortabletitle", ".", "encode", "(", "def_charset", "or", "'utf-8'", ")", "break", "except", "UnicodeError", ":", "pass", "except", "TypeError", ":", "# If we get a TypeError if we already have a unicode string", "sortabletitle", "=", "sortabletitle", "[", ":", "30", "]", "break", "return", "sortabletitle" ]
34.956522
17.521739
def _waitAny(*children): """Waits on any child Future created by the calling Future. :param children: A tuple of children Future objects spawned by the calling Future. :return: A generator function that iterates on futures that are done. The generator produces results of the children in a non deterministic order that depends on the particular parallel execution of the Futures. The generator returns a tuple as soon as one becomes available.""" n = len(children) # check for available results and index those unavailable for index, future in enumerate(children): if future.exceptionValue: raise future.exceptionValue if future._ended(): future._delete() yield future n -= 1 else: future.index = index future = control.current while n > 0: # wait for remaining results; switch to controller future.stopWatch.halt() childFuture = _controller.switch(future) future.stopWatch.resume() if childFuture.exceptionValue: raise childFuture.exceptionValue # Only yield if executed future was in children, otherwise loop if childFuture in children: childFuture._delete() yield childFuture n -= 1
[ "def", "_waitAny", "(", "*", "children", ")", ":", "n", "=", "len", "(", "children", ")", "# check for available results and index those unavailable", "for", "index", ",", "future", "in", "enumerate", "(", "children", ")", ":", "if", "future", ".", "exceptionValue", ":", "raise", "future", ".", "exceptionValue", "if", "future", ".", "_ended", "(", ")", ":", "future", ".", "_delete", "(", ")", "yield", "future", "n", "-=", "1", "else", ":", "future", ".", "index", "=", "index", "future", "=", "control", ".", "current", "while", "n", ">", "0", ":", "# wait for remaining results; switch to controller", "future", ".", "stopWatch", ".", "halt", "(", ")", "childFuture", "=", "_controller", ".", "switch", "(", "future", ")", "future", ".", "stopWatch", ".", "resume", "(", ")", "if", "childFuture", ".", "exceptionValue", ":", "raise", "childFuture", ".", "exceptionValue", "# Only yield if executed future was in children, otherwise loop", "if", "childFuture", "in", "children", ":", "childFuture", ".", "_delete", "(", ")", "yield", "childFuture", "n", "-=", "1" ]
36.971429
17.571429
def mission_clear_all_send(self, target_system, target_component, force_mavlink1=False): ''' Delete all mission items at once. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.mission_clear_all_encode(target_system, target_component), force_mavlink1=force_mavlink1)
[ "def", "mission_clear_all_send", "(", "self", ",", "target_system", ",", "target_component", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "mission_clear_all_encode", "(", "target_system", ",", "target_component", ")", ",", "force_mavlink1", "=", "force_mavlink1", ")" ]
47.888889
35
def brightness(self, value=1.0): """Increases or decreases the brightness in the layer. The given value is a percentage to increase or decrease the image brightness, for example 0.8 means brightness at 80%. """ b = ImageEnhance.Brightness(self.img) self.img = b.enhance(value)
[ "def", "brightness", "(", "self", ",", "value", "=", "1.0", ")", ":", "b", "=", "ImageEnhance", ".", "Brightness", "(", "self", ".", "img", ")", "self", ".", "img", "=", "b", ".", "enhance", "(", "value", ")" ]
28.25
15.5
async def webhooks(self): """|coro| Gets the list of webhooks from this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. Raises ------- Forbidden You don't have permissions to get the webhooks. Returns -------- List[:class:`Webhook`] The webhooks for this channel. """ data = await self._state.http.channel_webhooks(self.id) return [Webhook.from_state(d, state=self._state) for d in data]
[ "async", "def", "webhooks", "(", "self", ")", ":", "data", "=", "await", "self", ".", "_state", ".", "http", ".", "channel_webhooks", "(", "self", ".", "id", ")", "return", "[", "Webhook", ".", "from_state", "(", "d", ",", "state", "=", "self", ".", "_state", ")", "for", "d", "in", "data", "]" ]
25.7
23.1
def get_bounding_box( self, resource, resolution, _id, bb_type, url_prefix, auth, session, send_opts): """Get bounding box containing object specified by id. Currently only supports 'loose' bounding boxes. The bounding box returned is cuboid aligned. Args: resource (intern.resource.Resource): Resource compatible with annotation operations. resolution (int): 0 indicates native resolution. _id (int): Id of object of interest. bb_type (string): Defaults to 'loose'. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (dict): {'x_range': [0, 10], 'y_range': [0, 10], 'z_range': [0, 10], 't_range': [0, 10]} Raises: requests.HTTPError TypeError: if resource is not an annotation channel. """ if not isinstance(resource, ChannelResource): raise TypeError('resource must be ChannelResource') if resource.type != 'annotation': raise TypeError('Channel is not an annotation channel') req = self.get_bounding_box_request( resource, 'GET', 'application/json', url_prefix, auth, resolution, _id, bb_type) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code == 200: json_data = resp.json() return json_data msg = ('Get bounding box failed on {}, got HTTP response: ({}) - {}'.format( resource.name, resp.status_code, resp.text)) raise HTTPError(msg, request=req, response=resp)
[ "def", "get_bounding_box", "(", "self", ",", "resource", ",", "resolution", ",", "_id", ",", "bb_type", ",", "url_prefix", ",", "auth", ",", "session", ",", "send_opts", ")", ":", "if", "not", "isinstance", "(", "resource", ",", "ChannelResource", ")", ":", "raise", "TypeError", "(", "'resource must be ChannelResource'", ")", "if", "resource", ".", "type", "!=", "'annotation'", ":", "raise", "TypeError", "(", "'Channel is not an annotation channel'", ")", "req", "=", "self", ".", "get_bounding_box_request", "(", "resource", ",", "'GET'", ",", "'application/json'", ",", "url_prefix", ",", "auth", ",", "resolution", ",", "_id", ",", "bb_type", ")", "prep", "=", "session", ".", "prepare_request", "(", "req", ")", "resp", "=", "session", ".", "send", "(", "prep", ",", "*", "*", "send_opts", ")", "if", "resp", ".", "status_code", "==", "200", ":", "json_data", "=", "resp", ".", "json", "(", ")", "return", "json_data", "msg", "=", "(", "'Get bounding box failed on {}, got HTTP response: ({}) - {}'", ".", "format", "(", "resource", ".", "name", ",", "resp", ".", "status_code", ",", "resp", ".", "text", ")", ")", "raise", "HTTPError", "(", "msg", ",", "request", "=", "req", ",", "response", "=", "resp", ")" ]
42
23.386364
def requires_authentication(fn): """ Requires that the calling Subject be authenticated before allowing access. """ @functools.wraps(fn) def wrap(*args, **kwargs): subject = WebYosai.get_current_subject() if not subject.authenticated: msg = "The current Subject is not authenticated. ACCESS DENIED." raise WebYosai.get_current_webregistry().raise_unauthorized(msg) return fn(*args, **kwargs) return wrap
[ "def", "requires_authentication", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "subject", "=", "WebYosai", ".", "get_current_subject", "(", ")", "if", "not", "subject", ".", "authenticated", ":", "msg", "=", "\"The current Subject is not authenticated. ACCESS DENIED.\"", "raise", "WebYosai", ".", "get_current_webregistry", "(", ")", ".", "raise_unauthorized", "(", "msg", ")", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrap" ]
33.933333
20.333333
def get_compound_ids(self): """Extract the current compound ids in the database. Updates the self.compound_ids list """ cursor = self.conn.cursor() cursor.execute('SELECT inchikey_id FROM metab_compound') self.conn.commit() for row in cursor: if not row[0] in self.compound_ids: self.compound_ids.append(row[0])
[ "def", "get_compound_ids", "(", "self", ")", ":", "cursor", "=", "self", ".", "conn", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "'SELECT inchikey_id FROM metab_compound'", ")", "self", ".", "conn", ".", "commit", "(", ")", "for", "row", "in", "cursor", ":", "if", "not", "row", "[", "0", "]", "in", "self", ".", "compound_ids", ":", "self", ".", "compound_ids", ".", "append", "(", "row", "[", "0", "]", ")" ]
42.111111
9.444444
def determine_file_type(self, z): """Determine file type.""" content = z.read('[Content_Types].xml') with io.BytesIO(content) as b: encoding = self._analyze_file(b) if encoding is None: encoding = 'utf-8' b.seek(0) text = b.read().decode(encoding) soup = bs4.BeautifulSoup(text, 'xml') for o in soup.find_all('Override'): name = o.attrs.get('PartName') for k, v in MIMEMAP.items(): if name.startswith('/{}/'.format(k)): self.type = v break if self.type: break self.filepattern = DOC_PARAMS[self.type]['filepattern'] self.namespaces = DOC_PARAMS[self.type]['namespaces'] self.captures = sv.compile(DOC_PARAMS[self.type]['captures'], DOC_PARAMS[self.type]['namespaces'])
[ "def", "determine_file_type", "(", "self", ",", "z", ")", ":", "content", "=", "z", ".", "read", "(", "'[Content_Types].xml'", ")", "with", "io", ".", "BytesIO", "(", "content", ")", "as", "b", ":", "encoding", "=", "self", ".", "_analyze_file", "(", "b", ")", "if", "encoding", "is", "None", ":", "encoding", "=", "'utf-8'", "b", ".", "seek", "(", "0", ")", "text", "=", "b", ".", "read", "(", ")", ".", "decode", "(", "encoding", ")", "soup", "=", "bs4", ".", "BeautifulSoup", "(", "text", ",", "'xml'", ")", "for", "o", "in", "soup", ".", "find_all", "(", "'Override'", ")", ":", "name", "=", "o", ".", "attrs", ".", "get", "(", "'PartName'", ")", "for", "k", ",", "v", "in", "MIMEMAP", ".", "items", "(", ")", ":", "if", "name", ".", "startswith", "(", "'/{}/'", ".", "format", "(", "k", ")", ")", ":", "self", ".", "type", "=", "v", "break", "if", "self", ".", "type", ":", "break", "self", ".", "filepattern", "=", "DOC_PARAMS", "[", "self", ".", "type", "]", "[", "'filepattern'", "]", "self", ".", "namespaces", "=", "DOC_PARAMS", "[", "self", ".", "type", "]", "[", "'namespaces'", "]", "self", ".", "captures", "=", "sv", ".", "compile", "(", "DOC_PARAMS", "[", "self", ".", "type", "]", "[", "'captures'", "]", ",", "DOC_PARAMS", "[", "self", ".", "type", "]", "[", "'namespaces'", "]", ")" ]
41.818182
13.181818
def _create_executor(self, handler, args, cpus_per_worker=1): """Return a new :class:`.Executor` instance.""" if self._args.parallel > 0: workers = self._args.parallel else: try: workers = mp.cpu_count() // cpus_per_worker except NotImplementedError: workers = 1 if workers != 1: logger.info('Using {} parallel worker processes...'.format( workers)) executor = ProcessPoolExecutor( processes=workers, handler_init=handler, handler_args=args) else: logger.info('Using single worker...') executor = SequentialExecutor( handler_init=handler, handler_args=args) return executor
[ "def", "_create_executor", "(", "self", ",", "handler", ",", "args", ",", "cpus_per_worker", "=", "1", ")", ":", "if", "self", ".", "_args", ".", "parallel", ">", "0", ":", "workers", "=", "self", ".", "_args", ".", "parallel", "else", ":", "try", ":", "workers", "=", "mp", ".", "cpu_count", "(", ")", "//", "cpus_per_worker", "except", "NotImplementedError", ":", "workers", "=", "1", "if", "workers", "!=", "1", ":", "logger", ".", "info", "(", "'Using {} parallel worker processes...'", ".", "format", "(", "workers", ")", ")", "executor", "=", "ProcessPoolExecutor", "(", "processes", "=", "workers", ",", "handler_init", "=", "handler", ",", "handler_args", "=", "args", ")", "else", ":", "logger", ".", "info", "(", "'Using single worker...'", ")", "executor", "=", "SequentialExecutor", "(", "handler_init", "=", "handler", ",", "handler_args", "=", "args", ")", "return", "executor" ]
36.52381
17.238095
def execute(self, sources, sink, interval, alignment_stream=None): """ Execute the tool over the given time interval. If an alignment stream is given, the output instances will be aligned to this stream :param sources: The source streams (possibly None) :param sink: The sink stream :param alignment_stream: The alignment stream :param interval: The time interval :type sources: list[Stream] | tuple[Stream] | None :type sink: Stream :type alignment_stream: Stream | None :type interval: TimeInterval :return: None """ if not isinstance(interval, TimeInterval): raise TypeError('Expected TimeInterval, got {}'.format(type(interval))) # logging.info(self.message(interval)) if interval.end > sink.channel.up_to_timestamp: raise StreamNotAvailableError(sink.channel.up_to_timestamp) required_intervals = TimeIntervals([interval]) - sink.calculated_intervals if not required_intervals.is_empty: document_count = 0 for interval in required_intervals: for stream_instance in self._execute( sources=sources, alignment_stream=alignment_stream, interval=interval): sink.writer(stream_instance) document_count += 1 sink.calculated_intervals += interval required_intervals = TimeIntervals([interval]) - sink.calculated_intervals if not required_intervals.is_empty: # raise ToolExecutionError(required_intervals) logging.error("{} execution error for time interval {} on stream {}".format( self.name, interval, sink)) if not document_count: logging.debug("{} did not produce any data for time interval {} on stream {}".format( self.name, interval, sink)) self.write_to_history( interval=interval, tool=self.name, document_count=document_count )
[ "def", "execute", "(", "self", ",", "sources", ",", "sink", ",", "interval", ",", "alignment_stream", "=", "None", ")", ":", "if", "not", "isinstance", "(", "interval", ",", "TimeInterval", ")", ":", "raise", "TypeError", "(", "'Expected TimeInterval, got {}'", ".", "format", "(", "type", "(", "interval", ")", ")", ")", "# logging.info(self.message(interval))", "if", "interval", ".", "end", ">", "sink", ".", "channel", ".", "up_to_timestamp", ":", "raise", "StreamNotAvailableError", "(", "sink", ".", "channel", ".", "up_to_timestamp", ")", "required_intervals", "=", "TimeIntervals", "(", "[", "interval", "]", ")", "-", "sink", ".", "calculated_intervals", "if", "not", "required_intervals", ".", "is_empty", ":", "document_count", "=", "0", "for", "interval", "in", "required_intervals", ":", "for", "stream_instance", "in", "self", ".", "_execute", "(", "sources", "=", "sources", ",", "alignment_stream", "=", "alignment_stream", ",", "interval", "=", "interval", ")", ":", "sink", ".", "writer", "(", "stream_instance", ")", "document_count", "+=", "1", "sink", ".", "calculated_intervals", "+=", "interval", "required_intervals", "=", "TimeIntervals", "(", "[", "interval", "]", ")", "-", "sink", ".", "calculated_intervals", "if", "not", "required_intervals", ".", "is_empty", ":", "# raise ToolExecutionError(required_intervals)", "logging", ".", "error", "(", "\"{} execution error for time interval {} on stream {}\"", ".", "format", "(", "self", ".", "name", ",", "interval", ",", "sink", ")", ")", "if", "not", "document_count", ":", "logging", ".", "debug", "(", "\"{} did not produce any data for time interval {} on stream {}\"", ".", "format", "(", "self", ".", "name", ",", "interval", ",", "sink", ")", ")", "self", ".", "write_to_history", "(", "interval", "=", "interval", ",", "tool", "=", "self", ".", "name", ",", "document_count", "=", "document_count", ")" ]
42.387755
20.959184
def _get_attribute_tensors(onnx_model_proto): # type: (ModelProto) -> Iterable[TensorProto] """Create an iterator of tensors from node attributes of an ONNX model.""" for node in onnx_model_proto.graph.node: for attribute in node.attribute: if attribute.HasField("t"): yield attribute.t for tensor in attribute.tensors: yield tensor
[ "def", "_get_attribute_tensors", "(", "onnx_model_proto", ")", ":", "# type: (ModelProto) -> Iterable[TensorProto]", "for", "node", "in", "onnx_model_proto", ".", "graph", ".", "node", ":", "for", "attribute", "in", "node", ".", "attribute", ":", "if", "attribute", ".", "HasField", "(", "\"t\"", ")", ":", "yield", "attribute", ".", "t", "for", "tensor", "in", "attribute", ".", "tensors", ":", "yield", "tensor" ]
49.75
10
def convert_video(fieldfile, force=False): """ Converts a given video file into all defined formats. """ instance = fieldfile.instance field = fieldfile.field filename = os.path.basename(fieldfile.path) source_path = fieldfile.path encoding_backend = get_backend() for options in settings.VIDEO_ENCODING_FORMATS[encoding_backend.name]: video_format, created = Format.objects.get_or_create( object_id=instance.pk, content_type=ContentType.objects.get_for_model(instance), field_name=field.name, format=options['name']) # do not reencode if not requested if video_format.file and not force: continue else: # set progress to 0 video_format.reset_progress() # TODO do not upscale videos _, target_path = tempfile.mkstemp( suffix='_{name}.{extension}'.format(**options)) try: encoding = encoding_backend.encode( source_path, target_path, options['params']) while encoding: try: progress = next(encoding) except StopIteration: break video_format.update_progress(progress) except VideoEncodingError: # TODO handle with more care video_format.delete() os.remove(target_path) continue # save encoded file video_format.file.save( '{filename}_{name}.{extension}'.format(filename=filename, **options), File(open(target_path, mode='rb'))) video_format.update_progress(100) # now we are ready # remove temporary file os.remove(target_path)
[ "def", "convert_video", "(", "fieldfile", ",", "force", "=", "False", ")", ":", "instance", "=", "fieldfile", ".", "instance", "field", "=", "fieldfile", ".", "field", "filename", "=", "os", ".", "path", ".", "basename", "(", "fieldfile", ".", "path", ")", "source_path", "=", "fieldfile", ".", "path", "encoding_backend", "=", "get_backend", "(", ")", "for", "options", "in", "settings", ".", "VIDEO_ENCODING_FORMATS", "[", "encoding_backend", ".", "name", "]", ":", "video_format", ",", "created", "=", "Format", ".", "objects", ".", "get_or_create", "(", "object_id", "=", "instance", ".", "pk", ",", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "instance", ")", ",", "field_name", "=", "field", ".", "name", ",", "format", "=", "options", "[", "'name'", "]", ")", "# do not reencode if not requested", "if", "video_format", ".", "file", "and", "not", "force", ":", "continue", "else", ":", "# set progress to 0", "video_format", ".", "reset_progress", "(", ")", "# TODO do not upscale videos", "_", ",", "target_path", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'_{name}.{extension}'", ".", "format", "(", "*", "*", "options", ")", ")", "try", ":", "encoding", "=", "encoding_backend", ".", "encode", "(", "source_path", ",", "target_path", ",", "options", "[", "'params'", "]", ")", "while", "encoding", ":", "try", ":", "progress", "=", "next", "(", "encoding", ")", "except", "StopIteration", ":", "break", "video_format", ".", "update_progress", "(", "progress", ")", "except", "VideoEncodingError", ":", "# TODO handle with more care", "video_format", ".", "delete", "(", ")", "os", ".", "remove", "(", "target_path", ")", "continue", "# save encoded file", "video_format", ".", "file", ".", "save", "(", "'{filename}_{name}.{extension}'", ".", "format", "(", "filename", "=", "filename", ",", "*", "*", "options", ")", ",", "File", "(", "open", "(", "target_path", ",", "mode", "=", "'rb'", ")", ")", ")", "video_format", ".", "update_progress", "(", "100", ")", "# now we are ready", "# remove temporary file", "os", ".", "remove", "(", "target_path", ")" ]
31.945455
17.036364
def merge(cls, components): """Merges components into a single component, applying their actions appropriately. This operation is associative: M(M(a, b), c) == M(a, M(b, c)) == M(a, b, c). :param list components: an iterable of instances of DictValueComponent. :return: An instance representing the result of merging the components. :rtype: `DictValueComponent` """ # Note that action of the merged component is EXTEND until the first REPLACE is encountered. # This guarantees associativity. action = cls.EXTEND val = {} for component in components: if component.action is cls.REPLACE: val = component.val action = cls.REPLACE elif component.action is cls.EXTEND: val.update(component.val) else: raise ParseError('Unknown action for dict value: {}'.format(component.action)) return cls(action, val)
[ "def", "merge", "(", "cls", ",", "components", ")", ":", "# Note that action of the merged component is EXTEND until the first REPLACE is encountered.", "# This guarantees associativity.", "action", "=", "cls", ".", "EXTEND", "val", "=", "{", "}", "for", "component", "in", "components", ":", "if", "component", ".", "action", "is", "cls", ".", "REPLACE", ":", "val", "=", "component", ".", "val", "action", "=", "cls", ".", "REPLACE", "elif", "component", ".", "action", "is", "cls", ".", "EXTEND", ":", "val", ".", "update", "(", "component", ".", "val", ")", "else", ":", "raise", "ParseError", "(", "'Unknown action for dict value: {}'", ".", "format", "(", "component", ".", "action", ")", ")", "return", "cls", "(", "action", ",", "val", ")" ]
39.909091
20.363636
def dump_to_stream(self, cnf, stream, **opts): """ :param cnf: Configuration data to dump :param stream: Config file or file like object write to :param opts: optional keyword parameters """ tree = container_to_etree(cnf, **opts) etree_write(tree, stream)
[ "def", "dump_to_stream", "(", "self", ",", "cnf", ",", "stream", ",", "*", "*", "opts", ")", ":", "tree", "=", "container_to_etree", "(", "cnf", ",", "*", "*", "opts", ")", "etree_write", "(", "tree", ",", "stream", ")" ]
38
7
def _get_relationship_cell_val(self, obj, column): """ Return the value to insert in a relationship cell Handle the case of complex related datas we want to handle """ val = SqlaExporter._get_relationship_cell_val(self, obj, column) if val == "": related_key = column.get('related_key', None) if column['__col__'].uselist and related_key is None and \ self.is_root: # on récupère les objets liés key = column['key'] related_objects = getattr(obj, key, None) if not related_objects: return "" else: exporter = self._get_related_exporter( related_objects[0], column, ) for rel_obj in related_objects: exporter.add_row(rel_obj) return val
[ "def", "_get_relationship_cell_val", "(", "self", ",", "obj", ",", "column", ")", ":", "val", "=", "SqlaExporter", ".", "_get_relationship_cell_val", "(", "self", ",", "obj", ",", "column", ")", "if", "val", "==", "\"\"", ":", "related_key", "=", "column", ".", "get", "(", "'related_key'", ",", "None", ")", "if", "column", "[", "'__col__'", "]", ".", "uselist", "and", "related_key", "is", "None", "and", "self", ".", "is_root", ":", "# on récupère les objets liés", "key", "=", "column", "[", "'key'", "]", "related_objects", "=", "getattr", "(", "obj", ",", "key", ",", "None", ")", "if", "not", "related_objects", ":", "return", "\"\"", "else", ":", "exporter", "=", "self", ".", "_get_related_exporter", "(", "related_objects", "[", "0", "]", ",", "column", ",", ")", "for", "rel_obj", "in", "related_objects", ":", "exporter", ".", "add_row", "(", "rel_obj", ")", "return", "val" ]
36.346154
16.423077
def _load_version1(self, filename): """load a version 1 pest control file information Parameters ---------- filename : str pst filename Raises ------ lots of exceptions for incorrect format """ f = open(filename, 'r') f.readline() #control section line = f.readline() assert "* control data" in line,\ "Pst.load() error: looking for control" +\ " data section, found:" + line iskeyword = False if "keyword" in line.lower(): iskeyword = True control_lines = [] while True: line = f.readline() if line == '': raise Exception("Pst.load() EOF while " +\ "reading control data section") if line.startswith('*'): break control_lines.append(line) self.control_data.parse_values_from_lines(control_lines,iskeyword) #anything between control data and SVD while True: if line == '': raise Exception("EOF before parameter groups section found") if "* singular value decomposition" in line.lower() or\ "* parameter groups" in line.lower(): break self.other_lines.append(line) line = f.readline() if "* singular value decomposition" in line.lower(): svd_lines = [] for _ in range(3): line = f.readline() if line == '': raise Exception("EOF while reading SVD section") svd_lines.append(line) self.svd_data.parse_values_from_lines(svd_lines) line = f.readline() while True: if line == '': raise Exception("EOF before parameter groups section found") if "* parameter groups" in line.lower(): break self.other_lines.append(line) line = f.readline() #parameter data assert "* parameter groups" in line.lower(),\ "Pst.load() error: looking for parameter" +\ " group section, found:" + line #try: self.parameter_groups = self._read_df(f,self.control_data.npargp, self.pargp_fieldnames, self.pargp_converters, self.pargp_defaults) self.parameter_groups.index = self.parameter_groups.pargpnme #except Exception as e: # raise Exception("Pst.load() error reading parameter groups: {0}".format(str(e))) #parameter data line = f.readline() assert "* parameter data" in line.lower(),\ "Pst.load() error: looking for parameter" +\ " data section, found:" + line try: self.parameter_data = self._read_df(f,self.control_data.npar, self.par_fieldnames, self.par_converters, self.par_defaults) self.parameter_data.index = self.parameter_data.parnme except Exception as e: raise Exception("Pst.load() error reading parameter data: {0}".format(str(e))) # oh the tied parameter bullshit, how do I hate thee counts = self.parameter_data.partrans.value_counts() if "tied" in counts.index: # tied_lines = [f.readline().lower().strip().split() for _ in range(counts["tied"])] # self.tied = pd.DataFrame(tied_lines,columns=["parnme","partied"]) # self.tied.index = self.tied.pop("parnme") tied = self._read_df(f,counts["tied"],self.tied_fieldnames, self.tied_converters) tied.index = tied.parnme self.parameter_data.loc[:,"partied"] = np.NaN self.parameter_data.loc[tied.index,"partied"] = tied.partied # obs groups - just read past for now line = f.readline() # assert "* observation groups" in line.lower(),\ # "Pst.load() error: looking for obs" +\ # " group section, found:" + line # [f.readline() for _ in range(self.control_data.nobsgp)] if "* observation groups" in line: while True: seekpoint = f.tell() line = f.readline() if line == "": raise Exception("Pst.load() error: EOF when searching for '* observation data'") if line.startswith("*"): f.seek(seekpoint) break line = f.readline() assert "* observation data" in line.lower(), \ "Pst.load() error: looking for observation" + \ " data section, found:" + line else: assert "* observation data" in line.lower(),\ "Pst.load() error: looking for observation" +\ " data section, found:" + line try: self.observation_data = self._read_df(f,self.control_data.nobs, self.obs_fieldnames, self.obs_converters) self.observation_data.index = self.observation_data.obsnme except Exception as e: raise Exception("Pst.load() error reading observation data: {0}".format(str(e))) #model command line line = f.readline() assert "* model command line" in line.lower(),\ "Pst.load() error: looking for model " +\ "command section, found:" + line for i in range(self.control_data.numcom): self.model_command.append(f.readline().strip()) #model io line = f.readline() assert "* model input/output" in line.lower(), \ "Pst.load() error; looking for model " +\ " i/o section, found:" + line for i in range(self.control_data.ntplfle): raw = f.readline().strip().split() self.template_files.append(raw[0]) self.input_files.append(raw[1]) for i in range(self.control_data.ninsfle): raw = f.readline().strip().split() self.instruction_files.append(raw[0]) self.output_files.append(raw[1]) #prior information - sort of hackish if self.control_data.nprior == 0: self.prior_information = self.null_prior else: pilbl, obgnme, weight, equation = [], [], [], [] line = f.readline() assert "* prior information" in line.lower(), \ "Pst.load() error; looking for prior " +\ " info section, found:" + line for iprior in range(self.control_data.nprior): line = f.readline() if line == '': raise Exception("EOF during prior information " + "section") raw = line.strip().split() pilbl.append(raw[0].lower()) obgnme.append(raw[-1].lower()) weight.append(float(raw[-2])) eq = ' '.join(raw[1:-2]) equation.append(eq) self.prior_information = pd.DataFrame({"pilbl": pilbl, "equation": equation, "weight": weight, "obgnme": obgnme}) self.prior_information.index = self.prior_information.pilbl if "regul" in self.control_data.pestmode: line = f.readline() assert "* regul" in line.lower(), \ "Pst.load() error; looking for regul " +\ " section, found:" + line #[self.regul_lines.append(f.readline()) for _ in range(3)] regul_lines = [f.readline() for _ in range(3)] raw = regul_lines[0].strip().split() self.reg_data.phimlim = float(raw[0]) self.reg_data.phimaccept = float(raw[1]) raw = regul_lines[1].strip().split() self.wfinit = float(raw[0]) for line in f: if line.strip().startswith("++") and '#' not in line: self._parse_pestpp_line(line) f.close() for df in [self.parameter_groups,self.parameter_data, self.observation_data,self.prior_information]: if "extra" in df.columns and df.extra.dropna().shape[0] > 0: self.with_comments = False break return
[ "def", "_load_version1", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "'r'", ")", "f", ".", "readline", "(", ")", "#control section", "line", "=", "f", ".", "readline", "(", ")", "assert", "\"* control data\"", "in", "line", ",", "\"Pst.load() error: looking for control\"", "+", "\" data section, found:\"", "+", "line", "iskeyword", "=", "False", "if", "\"keyword\"", "in", "line", ".", "lower", "(", ")", ":", "iskeyword", "=", "True", "control_lines", "=", "[", "]", "while", "True", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "raise", "Exception", "(", "\"Pst.load() EOF while \"", "+", "\"reading control data section\"", ")", "if", "line", ".", "startswith", "(", "'*'", ")", ":", "break", "control_lines", ".", "append", "(", "line", ")", "self", ".", "control_data", ".", "parse_values_from_lines", "(", "control_lines", ",", "iskeyword", ")", "#anything between control data and SVD", "while", "True", ":", "if", "line", "==", "''", ":", "raise", "Exception", "(", "\"EOF before parameter groups section found\"", ")", "if", "\"* singular value decomposition\"", "in", "line", ".", "lower", "(", ")", "or", "\"* parameter groups\"", "in", "line", ".", "lower", "(", ")", ":", "break", "self", ".", "other_lines", ".", "append", "(", "line", ")", "line", "=", "f", ".", "readline", "(", ")", "if", "\"* singular value decomposition\"", "in", "line", ".", "lower", "(", ")", ":", "svd_lines", "=", "[", "]", "for", "_", "in", "range", "(", "3", ")", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "raise", "Exception", "(", "\"EOF while reading SVD section\"", ")", "svd_lines", ".", "append", "(", "line", ")", "self", ".", "svd_data", ".", "parse_values_from_lines", "(", "svd_lines", ")", "line", "=", "f", ".", "readline", "(", ")", "while", "True", ":", "if", "line", "==", "''", ":", "raise", "Exception", "(", "\"EOF before parameter groups section found\"", ")", "if", "\"* parameter groups\"", "in", "line", ".", "lower", "(", ")", ":", "break", "self", ".", "other_lines", ".", "append", "(", "line", ")", "line", "=", "f", ".", "readline", "(", ")", "#parameter data", "assert", "\"* parameter groups\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error: looking for parameter\"", "+", "\" group section, found:\"", "+", "line", "#try:", "self", ".", "parameter_groups", "=", "self", ".", "_read_df", "(", "f", ",", "self", ".", "control_data", ".", "npargp", ",", "self", ".", "pargp_fieldnames", ",", "self", ".", "pargp_converters", ",", "self", ".", "pargp_defaults", ")", "self", ".", "parameter_groups", ".", "index", "=", "self", ".", "parameter_groups", ".", "pargpnme", "#except Exception as e:", "# raise Exception(\"Pst.load() error reading parameter groups: {0}\".format(str(e)))", "#parameter data", "line", "=", "f", ".", "readline", "(", ")", "assert", "\"* parameter data\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error: looking for parameter\"", "+", "\" data section, found:\"", "+", "line", "try", ":", "self", ".", "parameter_data", "=", "self", ".", "_read_df", "(", "f", ",", "self", ".", "control_data", ".", "npar", ",", "self", ".", "par_fieldnames", ",", "self", ".", "par_converters", ",", "self", ".", "par_defaults", ")", "self", ".", "parameter_data", ".", "index", "=", "self", ".", "parameter_data", ".", "parnme", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"Pst.load() error reading parameter data: {0}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "# oh the tied parameter bullshit, how do I hate thee", "counts", "=", "self", ".", "parameter_data", ".", "partrans", ".", "value_counts", "(", ")", "if", "\"tied\"", "in", "counts", ".", "index", ":", "# tied_lines = [f.readline().lower().strip().split() for _ in range(counts[\"tied\"])]", "# self.tied = pd.DataFrame(tied_lines,columns=[\"parnme\",\"partied\"])", "# self.tied.index = self.tied.pop(\"parnme\")", "tied", "=", "self", ".", "_read_df", "(", "f", ",", "counts", "[", "\"tied\"", "]", ",", "self", ".", "tied_fieldnames", ",", "self", ".", "tied_converters", ")", "tied", ".", "index", "=", "tied", ".", "parnme", "self", ".", "parameter_data", ".", "loc", "[", ":", ",", "\"partied\"", "]", "=", "np", ".", "NaN", "self", ".", "parameter_data", ".", "loc", "[", "tied", ".", "index", ",", "\"partied\"", "]", "=", "tied", ".", "partied", "# obs groups - just read past for now", "line", "=", "f", ".", "readline", "(", ")", "# assert \"* observation groups\" in line.lower(),\\", "# \"Pst.load() error: looking for obs\" +\\", "# \" group section, found:\" + line", "# [f.readline() for _ in range(self.control_data.nobsgp)]", "if", "\"* observation groups\"", "in", "line", ":", "while", "True", ":", "seekpoint", "=", "f", ".", "tell", "(", ")", "line", "=", "f", ".", "readline", "(", ")", "if", "line", "==", "\"\"", ":", "raise", "Exception", "(", "\"Pst.load() error: EOF when searching for '* observation data'\"", ")", "if", "line", ".", "startswith", "(", "\"*\"", ")", ":", "f", ".", "seek", "(", "seekpoint", ")", "break", "line", "=", "f", ".", "readline", "(", ")", "assert", "\"* observation data\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error: looking for observation\"", "+", "\" data section, found:\"", "+", "line", "else", ":", "assert", "\"* observation data\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error: looking for observation\"", "+", "\" data section, found:\"", "+", "line", "try", ":", "self", ".", "observation_data", "=", "self", ".", "_read_df", "(", "f", ",", "self", ".", "control_data", ".", "nobs", ",", "self", ".", "obs_fieldnames", ",", "self", ".", "obs_converters", ")", "self", ".", "observation_data", ".", "index", "=", "self", ".", "observation_data", ".", "obsnme", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "\"Pst.load() error reading observation data: {0}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "#model command line", "line", "=", "f", ".", "readline", "(", ")", "assert", "\"* model command line\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error: looking for model \"", "+", "\"command section, found:\"", "+", "line", "for", "i", "in", "range", "(", "self", ".", "control_data", ".", "numcom", ")", ":", "self", ".", "model_command", ".", "append", "(", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", ")", "#model io", "line", "=", "f", ".", "readline", "(", ")", "assert", "\"* model input/output\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error; looking for model \"", "+", "\" i/o section, found:\"", "+", "line", "for", "i", "in", "range", "(", "self", ".", "control_data", ".", "ntplfle", ")", ":", "raw", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "self", ".", "template_files", ".", "append", "(", "raw", "[", "0", "]", ")", "self", ".", "input_files", ".", "append", "(", "raw", "[", "1", "]", ")", "for", "i", "in", "range", "(", "self", ".", "control_data", ".", "ninsfle", ")", ":", "raw", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "self", ".", "instruction_files", ".", "append", "(", "raw", "[", "0", "]", ")", "self", ".", "output_files", ".", "append", "(", "raw", "[", "1", "]", ")", "#prior information - sort of hackish", "if", "self", ".", "control_data", ".", "nprior", "==", "0", ":", "self", ".", "prior_information", "=", "self", ".", "null_prior", "else", ":", "pilbl", ",", "obgnme", ",", "weight", ",", "equation", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "line", "=", "f", ".", "readline", "(", ")", "assert", "\"* prior information\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error; looking for prior \"", "+", "\" info section, found:\"", "+", "line", "for", "iprior", "in", "range", "(", "self", ".", "control_data", ".", "nprior", ")", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "raise", "Exception", "(", "\"EOF during prior information \"", "+", "\"section\"", ")", "raw", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "pilbl", ".", "append", "(", "raw", "[", "0", "]", ".", "lower", "(", ")", ")", "obgnme", ".", "append", "(", "raw", "[", "-", "1", "]", ".", "lower", "(", ")", ")", "weight", ".", "append", "(", "float", "(", "raw", "[", "-", "2", "]", ")", ")", "eq", "=", "' '", ".", "join", "(", "raw", "[", "1", ":", "-", "2", "]", ")", "equation", ".", "append", "(", "eq", ")", "self", ".", "prior_information", "=", "pd", ".", "DataFrame", "(", "{", "\"pilbl\"", ":", "pilbl", ",", "\"equation\"", ":", "equation", ",", "\"weight\"", ":", "weight", ",", "\"obgnme\"", ":", "obgnme", "}", ")", "self", ".", "prior_information", ".", "index", "=", "self", ".", "prior_information", ".", "pilbl", "if", "\"regul\"", "in", "self", ".", "control_data", ".", "pestmode", ":", "line", "=", "f", ".", "readline", "(", ")", "assert", "\"* regul\"", "in", "line", ".", "lower", "(", ")", ",", "\"Pst.load() error; looking for regul \"", "+", "\" section, found:\"", "+", "line", "#[self.regul_lines.append(f.readline()) for _ in range(3)]", "regul_lines", "=", "[", "f", ".", "readline", "(", ")", "for", "_", "in", "range", "(", "3", ")", "]", "raw", "=", "regul_lines", "[", "0", "]", ".", "strip", "(", ")", ".", "split", "(", ")", "self", ".", "reg_data", ".", "phimlim", "=", "float", "(", "raw", "[", "0", "]", ")", "self", ".", "reg_data", ".", "phimaccept", "=", "float", "(", "raw", "[", "1", "]", ")", "raw", "=", "regul_lines", "[", "1", "]", ".", "strip", "(", ")", ".", "split", "(", ")", "self", ".", "wfinit", "=", "float", "(", "raw", "[", "0", "]", ")", "for", "line", "in", "f", ":", "if", "line", ".", "strip", "(", ")", ".", "startswith", "(", "\"++\"", ")", "and", "'#'", "not", "in", "line", ":", "self", ".", "_parse_pestpp_line", "(", "line", ")", "f", ".", "close", "(", ")", "for", "df", "in", "[", "self", ".", "parameter_groups", ",", "self", ".", "parameter_data", ",", "self", ".", "observation_data", ",", "self", ".", "prior_information", "]", ":", "if", "\"extra\"", "in", "df", ".", "columns", "and", "df", ".", "extra", ".", "dropna", "(", ")", ".", "shape", "[", "0", "]", ">", "0", ":", "self", ".", "with_comments", "=", "False", "break", "return" ]
40.829384
18.781991
def _in_deferred_types(self, cls): """ Check if the given class is specified in the deferred type registry. Returns the printer from the registry if it exists, and None if the class is not in the registry. Successful matches will be moved to the regular type registry for future use. """ mod = getattr(cls, '__module__', None) name = getattr(cls, '__name__', None) key = (mod, name) printer = None if key in self.deferred_printers: # Move the printer over to the regular registry. printer = self.deferred_printers.pop(key) self.type_printers[cls] = printer return printer
[ "def", "_in_deferred_types", "(", "self", ",", "cls", ")", ":", "mod", "=", "getattr", "(", "cls", ",", "'__module__'", ",", "None", ")", "name", "=", "getattr", "(", "cls", ",", "'__name__'", ",", "None", ")", "key", "=", "(", "mod", ",", "name", ")", "printer", "=", "None", "if", "key", "in", "self", ".", "deferred_printers", ":", "# Move the printer over to the regular registry.", "printer", "=", "self", ".", "deferred_printers", ".", "pop", "(", "key", ")", "self", ".", "type_printers", "[", "cls", "]", "=", "printer", "return", "printer" ]
40.470588
15.294118
def format(args): """ %prog format gffile > formatted.gff Read in the gff and print it out, changing seqid, etc. """ from jcvi.formats.obo import load_GODag, validate_term valid_multiparent_ops = ["split", "merge"] p = OptionParser(format.__doc__) g1 = OptionGroup(p, "Parameter(s) used to modify GFF attributes (9th column)") g1.add_option("--name", help="Add Name attribute from two-column file [default: %default]") g1.add_option("--note", help="Add Note attribute from two-column file [default: %default]") g1.add_option("--add_attribute", dest="attrib_files", help="Add new attribute(s) " + \ "from two-column file(s); attribute name comes from filename; " + \ "accepts comma-separated list of files [default: %default]") g1.add_option("--add_dbxref", dest="dbxref_files", help="Add new Dbxref value(s) (DBTAG:ID) " + \ "from two-column file(s). DBTAG comes from filename, ID comes from 2nd column; " + \ "accepts comma-separated list of files [default: %default]") g1.add_option("--nostrict", default=False, action="store_true", help="Disable strict parsing of GFF file and/or mapping file [default: %default]") g1.add_option("--remove_attr", dest="remove_attrs", help="Specify attributes to remove; " + \ "accepts comma-separated list of attribute names [default: %default]") g1.add_option("--copy_id_attr_to_name", default=False, action="store_true", help="Copy `ID` attribute value to `Name`, when `Name` is not defined") g1.add_option("--invent_name_attr", default=False, action="store_true", help="Invent `Name` attribute for 2nd level child features; " + \ "Formatted like PARENT:FEAT_TYPE:FEAT_INDEX") g1.add_option("--no_keep_attr_order", default=False, action="store_true", help="Do not maintain attribute order [default: %default]") p.add_option_group(g1) g2 = OptionGroup(p, "Parameter(s) used to modify content within columns 1-8") g2.add_option("--seqid", help="Switch seqid from two-column file. If not" + \ " a file, value will globally replace GFF seqid [default: %default]") g2.add_option("--source", help="Switch GFF source from two-column file. If not" + \ " a file, value will globally replace GFF source [default: %default]") g2.add_option("--type", help="Switch GFF feature type from two-column file. If not" + \ " a file, value will globally replace GFF type [default: %default]") g2.add_option("--fixphase", default=False, action="store_true", help="Change phase 1<->2, 2<->1 [default: %default]") p.add_option_group(g2) g3 = OptionGroup(p, "Other parameter(s) to perform manipulations to the GFF " + \ "file content") g3.add_option("--unique", default=False, action="store_true", help="Make IDs unique [default: %default]") g3.add_option("--chaindup", default=None, dest="duptype", help="Chain duplicate features of a particular GFF3 `type`," + \ " sharing the same ID attribute [default: %default]") g3.add_option("--multiparents", default=None, choices=valid_multiparent_ops, help="Split/merge identical features (same `seqid`, `source`, `type` " + \ "`coord-range`, `strand`, `phase`) mapping to multiple parents " + \ "[default: %default]") g3.add_option("--remove_feats", help="Comma separated list of features to remove by type" + \ " [default: %default]") g3.add_option("--remove_feats_by_ID", help="List of features to remove by ID;" + \ " accepts comma-separated list or list file [default: %default]") g3.add_option("--gsac", default=False, action="store_true", help="Fix GSAC GFF3 file attributes [default: %default]") g3.add_option("--invent_protein_feat", default=False, action="store_true", help="Invent a protein feature span (chain CDS feats)") g3.add_option("--process_ftype", default=None, type="str", help="Specify feature types to process; " "accepts comma-separated list of feature types [default: %default]") g3.add_option("--gff3", default=False, action="store_true", help="Print output in GFF3 format [default: %default]") g3.add_option("--make_gff_store", default=False, action="store_true", help="Store entire GFF file in memory during first iteration [default: %default]") p.add_option_group(g3) p.set_outfile() p.set_SO_opts() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gffile, = args mapfile = opts.seqid names = opts.name note = opts.note source = opts.source ftype = opts.type attrib_files = opts.attrib_files.split(",") if opts.attrib_files else None dbxref_files = opts.dbxref_files.split(",") if opts.dbxref_files else None remove_attrs = opts.remove_attrs.split(",") if opts.remove_attrs else None process_ftype = opts.process_ftype.split(",") if opts.process_ftype else None gsac = opts.gsac assert not (opts.unique and opts.duptype), \ "Cannot use `--unique` and `--chaindup` together" assert not(opts.type and opts.duptype), \ "Cannot use `--type` and `--chaindup` together" unique = opts.unique duptype = opts.duptype fixphase = opts.fixphase phaseT = {"1":"2", "2":"1"} remove_feats = opts.remove_feats.split(",") if opts.remove_feats else None remove_feats_by_ID = None if opts.remove_feats_by_ID: remove_feats_by_ID = LineFile(opts.remove_feats_by_ID, load=True).lines \ if op.isfile(opts.remove_feats_by_ID) else \ opts.remove_feats_by_ID.split(",") strict = False if opts.nostrict else True make_gff_store = True if gffile in ("-", "stdin") else opts.make_gff_store assert not (opts.copy_id_attr_to_name and opts.invent_name_attr), \ "Cannot use `--copy_id_attr_to_name` and `--invent_name_attr` together" copy_id_attr_to_name = opts.copy_id_attr_to_name invent_name_attr = opts.invent_name_attr invent_protein_feat = opts.invent_protein_feat compute_signature = False outfile = opts.outfile mapping = None mod_attrs = set() if mapfile and op.isfile(mapfile): mapping = DictFile(mapfile, delimiter="\t", strict=strict) mod_attrs.add("ID") if note: note = DictFile(note, delimiter="\t", strict=strict) mod_attrs.add("Note") if source and op.isfile(source): source = DictFile(source, delimiter="\t", strict=strict) if ftype and op.isfile(ftype): ftype = DictFile(ftype, delimiter="\t", strict=strict) if names: names = DictFile(names, delimiter="\t", strict=strict) mod_attrs.add("Name") if attrib_files: attr_values = {} for fn in attrib_files: attr_name = op.basename(fn).rsplit(".", 1)[0] if attr_name not in reserved_gff_attributes: attr_name = attr_name.lower() attr_values[attr_name] = DictFile(fn, delimiter="\t", strict=strict) mod_attrs.add(attr_name) if dbxref_files: dbxref_values = {} for fn in dbxref_files: dbtag = op.basename(fn).rsplit(".", 1)[0] dbxref_values[dbtag] = DictFile(fn, delimiter="\t", strict=strict) mod_attrs.add("Dbxref") if remove_attrs: mod_remove_attrs = [] for remove_attr in remove_attrs: if remove_attr in mod_attrs: mod_remove_attrs.append(remove_attr) if mod_remove_attrs: logging.error("Attributes `{0}` cannot be removed and modified".format( \ ",".join(mod_remove_attrs))) sys.exit() if gsac: # setting gsac will force IDs to be unique unique = True notes = {} remove = set() if unique or duptype or remove_feats or remove_feats_by_ID \ or opts.multiparents == "merge" or invent_name_attr or make_gff_store \ or invent_protein_feat: if unique: dupcounts = defaultdict(int) seen = defaultdict(int) newparentid = {} elif duptype: dupranges = AutoVivification() skip = defaultdict(int) if opts.multiparents == "merge": merge_feats = AutoVivification() if invent_name_attr: ft = GffFeatureTracker() elif copy_id_attr_to_name: pass if invent_protein_feat: cds_track = {} if opts.multiparents == "merge" or invent_name_attr: make_gff_store = compute_signature = True gff = Gff(gffile, keep_attr_order=(not opts.no_keep_attr_order), \ make_gff_store=make_gff_store, compute_signature=compute_signature, \ strict=strict) for g in gff: if process_ftype and g.type not in process_ftype: continue id = g.accn if remove_feats and g.type in remove_feats: remove.add(id) if remove_feats_by_ID and id in remove_feats_by_ID: remove.add(id) if unique: dupcounts[id] += 1 elif duptype and g.type == duptype: dupranges[g.seqid][id][g.idx] = (g.start, g.end) if opts.multiparents == "merge" and g.type != "CDS": #don't merge CDS pp = g.get_attr("Parent", first=False) if pp and len(pp) > 0: for parent in pp: if parent not in remove: sig = g.sign if sig not in merge_feats: merge_feats[sig]['parents'] = [] if parent not in merge_feats[sig]['parents']: merge_feats[sig]['parents'].append(parent) if invent_name_attr: parent, iso = atg_name(g.get_attr("Parent"), retval="locus,iso") if not parent: parent = g.get_attr("Parent") ft.track(parent, g) if invent_protein_feat: if g.type == 'CDS': cds_parent = g.get_attr("Parent") if cds_parent not in cds_track: cds_track[cds_parent] = [] cds_track[cds_parent].append((g.start, g.end)) if opts.verifySO: so = load_GODag() valid_soterm = {} fw = must_open(outfile, "w") if not make_gff_store: gff = Gff(gffile, keep_attr_order=(not opts.no_keep_attr_order), \ strict=strict) for g in gff: if process_ftype and g.type not in process_ftype: print(g, file=fw) continue id = g.accn if opts.multiparents == "merge" and g.type != "CDS": #don't merge CDS sig = g.sign if len(merge_feats[sig]['parents']) > 1: if 'candidate' not in merge_feats[sig]: merge_feats[sig]['candidate'] = id g.set_attr("Parent", merge_feats[sig]['parents']) else: continue if remove_feats or remove_feats_by_ID: if id in remove: continue else: if "Parent" in g.attributes: keep, parent = [], g.get_attr("Parent", first=False) for i, pid in enumerate(parent): if pid not in remove: keep.append(parent[i]) else: remove.add(id) if len(keep) == 0: continue parent = g.set_attr("Parent", keep) if remove_attrs: for remove_attr in remove_attrs: if remove_attr in g.attributes: g.set_attr(remove_attr, None) if opts.verifySO: if g.type not in valid_soterm: valid_soterm[g.type] = validate_term(g.type, so=so, method=opts.verifySO) ntype = valid_soterm[g.type] if ntype and g.type != ntype: g.type = ntype origid = g.seqid if fixphase: phase = g.phase g.phase = phaseT.get(phase, phase) if mapfile: if isinstance(mapping, dict): if origid in mapping: g.seqid = mapping[origid] else: logging.error("{0} not found in `{1}`. ID unchanged.".\ format(origid, mapfile)) else: g.seqid = mapfile if source: if isinstance(source, dict) and g.source in source: g.source = source[g.source] else: g.source = source if names: if id in names: g.set_attr("Name", names[id]) if note: name = g.get_attr("Name") tag = None if id in note: tag = note[id] elif name and name in note: tag = note[name] if tag: g.set_attr("Note", tag, update=False) if attrib_files: for attr_name in attr_values: name = g.get_attr("Name") if id in attr_values[attr_name]: g.set_attr(attr_name, attr_values[attr_name][id]) elif name and name in attr_values[attr_name]: g.set_attr(attr_name, attr_values[attr_name][name]) if dbxref_files: for dbtag in dbxref_values: if id in dbxref_values[dbtag]: g.set_attr("Dbxref", dbxref_values[dbtag][id], dbtag=dbtag, append=True) if unique: if dupcounts[id] > 1: seen[id] += 1 old_id = id id = "{0}-{1}".format(old_id, seen[old_id]) newparentid[old_id] = id g.set_attr("ID", id) if "Parent" in g.attributes: parent = g.attributes["Parent"][0] if dupcounts[parent] > 1: g.set_attr("Parent", newparentid[parent]) if duptype: if duptype == g.type and len(dupranges[g.seqid][id]) > 1: p = sorted(dupranges[g.seqid][id]) s, e = dupranges[g.seqid][id][p[0]][0:2] # get coords of first encountered feature if g.start == s and g.end == e and p[0] == g.idx: r = [dupranges[g.seqid][id][x] for x in dupranges[g.seqid][id]] g.start, g.end = range_minmax(r) else: skip[(g.seqid, g.idx, id, g.start, g.end)] = 1 if gsac and g.type == "gene": notes[id] = g.attributes["Name"] if ftype: if isinstance(ftype, dict) and g.type in ftype: g.type = ftype[g.type] else: g.type = ftype if invent_name_attr: ft.store_symbol(g) if re.search(ft.ftype, g.type): parent, iso = atg_name(g.get_attr("Parent"), retval="locus,iso") if not parent: parent = g.get_attr("Parent") if parent in ft.tracker: fidx = ft.feat_index(parent, g.type, g.strand, (g.start, g.end, g.sign)) symbol = ft.get_symbol(parent) attr = "ID" if symbol == parent else "Name" g.set_attr(attr, "{0}:{1}:{2}".format(symbol, g.type, fidx + 1)) if opts.multiparents == "merge" and attr == "Name": g.set_attr("ID", "{0}:{1}:{2}".format(parent, g.type, fidx + 1)) elif copy_id_attr_to_name: if "Name" not in g.attributes.keys(): g.set_attr("Name", g.get_attr("ID")) protein_feat = None if invent_protein_feat: if g.type == 'mRNA': if id in cds_track: pstart, pstop = range_minmax(cds_track[id]) protein_feat = GffLine("\t".join(str(x) for x in [g.seqid, g.source, "protein", pstart, pstop, \ ".", g.strand, ".", "ID={0}-Protein;Name={0};Derives_from={0}".format(id)])) elif g.type == 'CDS': parent = g.get_attr("Parent") if parent in cds_track: _parent = [parent, "{0}-Protein".format(parent)] g.set_attr("Parent", _parent) pp = g.get_attr("Parent", first=False) if opts.multiparents == "split" and (pp and len(pp) > 1) and g.type != "CDS": # separate features with multiple parents id = g.get_attr("ID") for i, parent in enumerate(pp): if id: g.set_attr("ID", "{0}-{1}".format(id, i + 1)) g.set_attr("Parent", parent, update=True, urlquote=True) if gsac: fix_gsac(g, notes) print(g, file=fw) else: if g.gff3 and not opts.gff3: opts.gff3 = True g.update_attributes(gff3=opts.gff3) if gsac: fix_gsac(g, notes) if duptype == g.type and skip[(g.seqid, g.idx, id, g.start, g.end)] == 1: continue print(g, file=fw) if g.type == 'mRNA' and invent_protein_feat: print(protein_feat, file=fw) fw.close()
[ "def", "format", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "obo", "import", "load_GODag", ",", "validate_term", "valid_multiparent_ops", "=", "[", "\"split\"", ",", "\"merge\"", "]", "p", "=", "OptionParser", "(", "format", ".", "__doc__", ")", "g1", "=", "OptionGroup", "(", "p", ",", "\"Parameter(s) used to modify GFF attributes (9th column)\"", ")", "g1", ".", "add_option", "(", "\"--name\"", ",", "help", "=", "\"Add Name attribute from two-column file [default: %default]\"", ")", "g1", ".", "add_option", "(", "\"--note\"", ",", "help", "=", "\"Add Note attribute from two-column file [default: %default]\"", ")", "g1", ".", "add_option", "(", "\"--add_attribute\"", ",", "dest", "=", "\"attrib_files\"", ",", "help", "=", "\"Add new attribute(s) \"", "+", "\"from two-column file(s); attribute name comes from filename; \"", "+", "\"accepts comma-separated list of files [default: %default]\"", ")", "g1", ".", "add_option", "(", "\"--add_dbxref\"", ",", "dest", "=", "\"dbxref_files\"", ",", "help", "=", "\"Add new Dbxref value(s) (DBTAG:ID) \"", "+", "\"from two-column file(s). DBTAG comes from filename, ID comes from 2nd column; \"", "+", "\"accepts comma-separated list of files [default: %default]\"", ")", "g1", ".", "add_option", "(", "\"--nostrict\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Disable strict parsing of GFF file and/or mapping file [default: %default]\"", ")", "g1", ".", "add_option", "(", "\"--remove_attr\"", ",", "dest", "=", "\"remove_attrs\"", ",", "help", "=", "\"Specify attributes to remove; \"", "+", "\"accepts comma-separated list of attribute names [default: %default]\"", ")", "g1", ".", "add_option", "(", "\"--copy_id_attr_to_name\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Copy `ID` attribute value to `Name`, when `Name` is not defined\"", ")", "g1", ".", "add_option", "(", "\"--invent_name_attr\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Invent `Name` attribute for 2nd level child features; \"", "+", "\"Formatted like PARENT:FEAT_TYPE:FEAT_INDEX\"", ")", "g1", ".", "add_option", "(", "\"--no_keep_attr_order\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Do not maintain attribute order [default: %default]\"", ")", "p", ".", "add_option_group", "(", "g1", ")", "g2", "=", "OptionGroup", "(", "p", ",", "\"Parameter(s) used to modify content within columns 1-8\"", ")", "g2", ".", "add_option", "(", "\"--seqid\"", ",", "help", "=", "\"Switch seqid from two-column file. If not\"", "+", "\" a file, value will globally replace GFF seqid [default: %default]\"", ")", "g2", ".", "add_option", "(", "\"--source\"", ",", "help", "=", "\"Switch GFF source from two-column file. If not\"", "+", "\" a file, value will globally replace GFF source [default: %default]\"", ")", "g2", ".", "add_option", "(", "\"--type\"", ",", "help", "=", "\"Switch GFF feature type from two-column file. If not\"", "+", "\" a file, value will globally replace GFF type [default: %default]\"", ")", "g2", ".", "add_option", "(", "\"--fixphase\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Change phase 1<->2, 2<->1 [default: %default]\"", ")", "p", ".", "add_option_group", "(", "g2", ")", "g3", "=", "OptionGroup", "(", "p", ",", "\"Other parameter(s) to perform manipulations to the GFF \"", "+", "\"file content\"", ")", "g3", ".", "add_option", "(", "\"--unique\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Make IDs unique [default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--chaindup\"", ",", "default", "=", "None", ",", "dest", "=", "\"duptype\"", ",", "help", "=", "\"Chain duplicate features of a particular GFF3 `type`,\"", "+", "\" sharing the same ID attribute [default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--multiparents\"", ",", "default", "=", "None", ",", "choices", "=", "valid_multiparent_ops", ",", "help", "=", "\"Split/merge identical features (same `seqid`, `source`, `type` \"", "+", "\"`coord-range`, `strand`, `phase`) mapping to multiple parents \"", "+", "\"[default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--remove_feats\"", ",", "help", "=", "\"Comma separated list of features to remove by type\"", "+", "\" [default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--remove_feats_by_ID\"", ",", "help", "=", "\"List of features to remove by ID;\"", "+", "\" accepts comma-separated list or list file [default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--gsac\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Fix GSAC GFF3 file attributes [default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--invent_protein_feat\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Invent a protein feature span (chain CDS feats)\"", ")", "g3", ".", "add_option", "(", "\"--process_ftype\"", ",", "default", "=", "None", ",", "type", "=", "\"str\"", ",", "help", "=", "\"Specify feature types to process; \"", "\"accepts comma-separated list of feature types [default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--gff3\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Print output in GFF3 format [default: %default]\"", ")", "g3", ".", "add_option", "(", "\"--make_gff_store\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Store entire GFF file in memory during first iteration [default: %default]\"", ")", "p", ".", "add_option_group", "(", "g3", ")", "p", ".", "set_outfile", "(", ")", "p", ".", "set_SO_opts", "(", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "not", "p", ".", "print_help", "(", ")", ")", "gffile", ",", "=", "args", "mapfile", "=", "opts", ".", "seqid", "names", "=", "opts", ".", "name", "note", "=", "opts", ".", "note", "source", "=", "opts", ".", "source", "ftype", "=", "opts", ".", "type", "attrib_files", "=", "opts", ".", "attrib_files", ".", "split", "(", "\",\"", ")", "if", "opts", ".", "attrib_files", "else", "None", "dbxref_files", "=", "opts", ".", "dbxref_files", ".", "split", "(", "\",\"", ")", "if", "opts", ".", "dbxref_files", "else", "None", "remove_attrs", "=", "opts", ".", "remove_attrs", ".", "split", "(", "\",\"", ")", "if", "opts", ".", "remove_attrs", "else", "None", "process_ftype", "=", "opts", ".", "process_ftype", ".", "split", "(", "\",\"", ")", "if", "opts", ".", "process_ftype", "else", "None", "gsac", "=", "opts", ".", "gsac", "assert", "not", "(", "opts", ".", "unique", "and", "opts", ".", "duptype", ")", ",", "\"Cannot use `--unique` and `--chaindup` together\"", "assert", "not", "(", "opts", ".", "type", "and", "opts", ".", "duptype", ")", ",", "\"Cannot use `--type` and `--chaindup` together\"", "unique", "=", "opts", ".", "unique", "duptype", "=", "opts", ".", "duptype", "fixphase", "=", "opts", ".", "fixphase", "phaseT", "=", "{", "\"1\"", ":", "\"2\"", ",", "\"2\"", ":", "\"1\"", "}", "remove_feats", "=", "opts", ".", "remove_feats", ".", "split", "(", "\",\"", ")", "if", "opts", ".", "remove_feats", "else", "None", "remove_feats_by_ID", "=", "None", "if", "opts", ".", "remove_feats_by_ID", ":", "remove_feats_by_ID", "=", "LineFile", "(", "opts", ".", "remove_feats_by_ID", ",", "load", "=", "True", ")", ".", "lines", "if", "op", ".", "isfile", "(", "opts", ".", "remove_feats_by_ID", ")", "else", "opts", ".", "remove_feats_by_ID", ".", "split", "(", "\",\"", ")", "strict", "=", "False", "if", "opts", ".", "nostrict", "else", "True", "make_gff_store", "=", "True", "if", "gffile", "in", "(", "\"-\"", ",", "\"stdin\"", ")", "else", "opts", ".", "make_gff_store", "assert", "not", "(", "opts", ".", "copy_id_attr_to_name", "and", "opts", ".", "invent_name_attr", ")", ",", "\"Cannot use `--copy_id_attr_to_name` and `--invent_name_attr` together\"", "copy_id_attr_to_name", "=", "opts", ".", "copy_id_attr_to_name", "invent_name_attr", "=", "opts", ".", "invent_name_attr", "invent_protein_feat", "=", "opts", ".", "invent_protein_feat", "compute_signature", "=", "False", "outfile", "=", "opts", ".", "outfile", "mapping", "=", "None", "mod_attrs", "=", "set", "(", ")", "if", "mapfile", "and", "op", ".", "isfile", "(", "mapfile", ")", ":", "mapping", "=", "DictFile", "(", "mapfile", ",", "delimiter", "=", "\"\\t\"", ",", "strict", "=", "strict", ")", "mod_attrs", ".", "add", "(", "\"ID\"", ")", "if", "note", ":", "note", "=", "DictFile", "(", "note", ",", "delimiter", "=", "\"\\t\"", ",", "strict", "=", "strict", ")", "mod_attrs", ".", "add", "(", "\"Note\"", ")", "if", "source", "and", "op", ".", "isfile", "(", "source", ")", ":", "source", "=", "DictFile", "(", "source", ",", "delimiter", "=", "\"\\t\"", ",", "strict", "=", "strict", ")", "if", "ftype", "and", "op", ".", "isfile", "(", "ftype", ")", ":", "ftype", "=", "DictFile", "(", "ftype", ",", "delimiter", "=", "\"\\t\"", ",", "strict", "=", "strict", ")", "if", "names", ":", "names", "=", "DictFile", "(", "names", ",", "delimiter", "=", "\"\\t\"", ",", "strict", "=", "strict", ")", "mod_attrs", ".", "add", "(", "\"Name\"", ")", "if", "attrib_files", ":", "attr_values", "=", "{", "}", "for", "fn", "in", "attrib_files", ":", "attr_name", "=", "op", ".", "basename", "(", "fn", ")", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", "if", "attr_name", "not", "in", "reserved_gff_attributes", ":", "attr_name", "=", "attr_name", ".", "lower", "(", ")", "attr_values", "[", "attr_name", "]", "=", "DictFile", "(", "fn", ",", "delimiter", "=", "\"\\t\"", ",", "strict", "=", "strict", ")", "mod_attrs", ".", "add", "(", "attr_name", ")", "if", "dbxref_files", ":", "dbxref_values", "=", "{", "}", "for", "fn", "in", "dbxref_files", ":", "dbtag", "=", "op", ".", "basename", "(", "fn", ")", ".", "rsplit", "(", "\".\"", ",", "1", ")", "[", "0", "]", "dbxref_values", "[", "dbtag", "]", "=", "DictFile", "(", "fn", ",", "delimiter", "=", "\"\\t\"", ",", "strict", "=", "strict", ")", "mod_attrs", ".", "add", "(", "\"Dbxref\"", ")", "if", "remove_attrs", ":", "mod_remove_attrs", "=", "[", "]", "for", "remove_attr", "in", "remove_attrs", ":", "if", "remove_attr", "in", "mod_attrs", ":", "mod_remove_attrs", ".", "append", "(", "remove_attr", ")", "if", "mod_remove_attrs", ":", "logging", ".", "error", "(", "\"Attributes `{0}` cannot be removed and modified\"", ".", "format", "(", "\",\"", ".", "join", "(", "mod_remove_attrs", ")", ")", ")", "sys", ".", "exit", "(", ")", "if", "gsac", ":", "# setting gsac will force IDs to be unique", "unique", "=", "True", "notes", "=", "{", "}", "remove", "=", "set", "(", ")", "if", "unique", "or", "duptype", "or", "remove_feats", "or", "remove_feats_by_ID", "or", "opts", ".", "multiparents", "==", "\"merge\"", "or", "invent_name_attr", "or", "make_gff_store", "or", "invent_protein_feat", ":", "if", "unique", ":", "dupcounts", "=", "defaultdict", "(", "int", ")", "seen", "=", "defaultdict", "(", "int", ")", "newparentid", "=", "{", "}", "elif", "duptype", ":", "dupranges", "=", "AutoVivification", "(", ")", "skip", "=", "defaultdict", "(", "int", ")", "if", "opts", ".", "multiparents", "==", "\"merge\"", ":", "merge_feats", "=", "AutoVivification", "(", ")", "if", "invent_name_attr", ":", "ft", "=", "GffFeatureTracker", "(", ")", "elif", "copy_id_attr_to_name", ":", "pass", "if", "invent_protein_feat", ":", "cds_track", "=", "{", "}", "if", "opts", ".", "multiparents", "==", "\"merge\"", "or", "invent_name_attr", ":", "make_gff_store", "=", "compute_signature", "=", "True", "gff", "=", "Gff", "(", "gffile", ",", "keep_attr_order", "=", "(", "not", "opts", ".", "no_keep_attr_order", ")", ",", "make_gff_store", "=", "make_gff_store", ",", "compute_signature", "=", "compute_signature", ",", "strict", "=", "strict", ")", "for", "g", "in", "gff", ":", "if", "process_ftype", "and", "g", ".", "type", "not", "in", "process_ftype", ":", "continue", "id", "=", "g", ".", "accn", "if", "remove_feats", "and", "g", ".", "type", "in", "remove_feats", ":", "remove", ".", "add", "(", "id", ")", "if", "remove_feats_by_ID", "and", "id", "in", "remove_feats_by_ID", ":", "remove", ".", "add", "(", "id", ")", "if", "unique", ":", "dupcounts", "[", "id", "]", "+=", "1", "elif", "duptype", "and", "g", ".", "type", "==", "duptype", ":", "dupranges", "[", "g", ".", "seqid", "]", "[", "id", "]", "[", "g", ".", "idx", "]", "=", "(", "g", ".", "start", ",", "g", ".", "end", ")", "if", "opts", ".", "multiparents", "==", "\"merge\"", "and", "g", ".", "type", "!=", "\"CDS\"", ":", "#don't merge CDS", "pp", "=", "g", ".", "get_attr", "(", "\"Parent\"", ",", "first", "=", "False", ")", "if", "pp", "and", "len", "(", "pp", ")", ">", "0", ":", "for", "parent", "in", "pp", ":", "if", "parent", "not", "in", "remove", ":", "sig", "=", "g", ".", "sign", "if", "sig", "not", "in", "merge_feats", ":", "merge_feats", "[", "sig", "]", "[", "'parents'", "]", "=", "[", "]", "if", "parent", "not", "in", "merge_feats", "[", "sig", "]", "[", "'parents'", "]", ":", "merge_feats", "[", "sig", "]", "[", "'parents'", "]", ".", "append", "(", "parent", ")", "if", "invent_name_attr", ":", "parent", ",", "iso", "=", "atg_name", "(", "g", ".", "get_attr", "(", "\"Parent\"", ")", ",", "retval", "=", "\"locus,iso\"", ")", "if", "not", "parent", ":", "parent", "=", "g", ".", "get_attr", "(", "\"Parent\"", ")", "ft", ".", "track", "(", "parent", ",", "g", ")", "if", "invent_protein_feat", ":", "if", "g", ".", "type", "==", "'CDS'", ":", "cds_parent", "=", "g", ".", "get_attr", "(", "\"Parent\"", ")", "if", "cds_parent", "not", "in", "cds_track", ":", "cds_track", "[", "cds_parent", "]", "=", "[", "]", "cds_track", "[", "cds_parent", "]", ".", "append", "(", "(", "g", ".", "start", ",", "g", ".", "end", ")", ")", "if", "opts", ".", "verifySO", ":", "so", "=", "load_GODag", "(", ")", "valid_soterm", "=", "{", "}", "fw", "=", "must_open", "(", "outfile", ",", "\"w\"", ")", "if", "not", "make_gff_store", ":", "gff", "=", "Gff", "(", "gffile", ",", "keep_attr_order", "=", "(", "not", "opts", ".", "no_keep_attr_order", ")", ",", "strict", "=", "strict", ")", "for", "g", "in", "gff", ":", "if", "process_ftype", "and", "g", ".", "type", "not", "in", "process_ftype", ":", "print", "(", "g", ",", "file", "=", "fw", ")", "continue", "id", "=", "g", ".", "accn", "if", "opts", ".", "multiparents", "==", "\"merge\"", "and", "g", ".", "type", "!=", "\"CDS\"", ":", "#don't merge CDS", "sig", "=", "g", ".", "sign", "if", "len", "(", "merge_feats", "[", "sig", "]", "[", "'parents'", "]", ")", ">", "1", ":", "if", "'candidate'", "not", "in", "merge_feats", "[", "sig", "]", ":", "merge_feats", "[", "sig", "]", "[", "'candidate'", "]", "=", "id", "g", ".", "set_attr", "(", "\"Parent\"", ",", "merge_feats", "[", "sig", "]", "[", "'parents'", "]", ")", "else", ":", "continue", "if", "remove_feats", "or", "remove_feats_by_ID", ":", "if", "id", "in", "remove", ":", "continue", "else", ":", "if", "\"Parent\"", "in", "g", ".", "attributes", ":", "keep", ",", "parent", "=", "[", "]", ",", "g", ".", "get_attr", "(", "\"Parent\"", ",", "first", "=", "False", ")", "for", "i", ",", "pid", "in", "enumerate", "(", "parent", ")", ":", "if", "pid", "not", "in", "remove", ":", "keep", ".", "append", "(", "parent", "[", "i", "]", ")", "else", ":", "remove", ".", "add", "(", "id", ")", "if", "len", "(", "keep", ")", "==", "0", ":", "continue", "parent", "=", "g", ".", "set_attr", "(", "\"Parent\"", ",", "keep", ")", "if", "remove_attrs", ":", "for", "remove_attr", "in", "remove_attrs", ":", "if", "remove_attr", "in", "g", ".", "attributes", ":", "g", ".", "set_attr", "(", "remove_attr", ",", "None", ")", "if", "opts", ".", "verifySO", ":", "if", "g", ".", "type", "not", "in", "valid_soterm", ":", "valid_soterm", "[", "g", ".", "type", "]", "=", "validate_term", "(", "g", ".", "type", ",", "so", "=", "so", ",", "method", "=", "opts", ".", "verifySO", ")", "ntype", "=", "valid_soterm", "[", "g", ".", "type", "]", "if", "ntype", "and", "g", ".", "type", "!=", "ntype", ":", "g", ".", "type", "=", "ntype", "origid", "=", "g", ".", "seqid", "if", "fixphase", ":", "phase", "=", "g", ".", "phase", "g", ".", "phase", "=", "phaseT", ".", "get", "(", "phase", ",", "phase", ")", "if", "mapfile", ":", "if", "isinstance", "(", "mapping", ",", "dict", ")", ":", "if", "origid", "in", "mapping", ":", "g", ".", "seqid", "=", "mapping", "[", "origid", "]", "else", ":", "logging", ".", "error", "(", "\"{0} not found in `{1}`. ID unchanged.\"", ".", "format", "(", "origid", ",", "mapfile", ")", ")", "else", ":", "g", ".", "seqid", "=", "mapfile", "if", "source", ":", "if", "isinstance", "(", "source", ",", "dict", ")", "and", "g", ".", "source", "in", "source", ":", "g", ".", "source", "=", "source", "[", "g", ".", "source", "]", "else", ":", "g", ".", "source", "=", "source", "if", "names", ":", "if", "id", "in", "names", ":", "g", ".", "set_attr", "(", "\"Name\"", ",", "names", "[", "id", "]", ")", "if", "note", ":", "name", "=", "g", ".", "get_attr", "(", "\"Name\"", ")", "tag", "=", "None", "if", "id", "in", "note", ":", "tag", "=", "note", "[", "id", "]", "elif", "name", "and", "name", "in", "note", ":", "tag", "=", "note", "[", "name", "]", "if", "tag", ":", "g", ".", "set_attr", "(", "\"Note\"", ",", "tag", ",", "update", "=", "False", ")", "if", "attrib_files", ":", "for", "attr_name", "in", "attr_values", ":", "name", "=", "g", ".", "get_attr", "(", "\"Name\"", ")", "if", "id", "in", "attr_values", "[", "attr_name", "]", ":", "g", ".", "set_attr", "(", "attr_name", ",", "attr_values", "[", "attr_name", "]", "[", "id", "]", ")", "elif", "name", "and", "name", "in", "attr_values", "[", "attr_name", "]", ":", "g", ".", "set_attr", "(", "attr_name", ",", "attr_values", "[", "attr_name", "]", "[", "name", "]", ")", "if", "dbxref_files", ":", "for", "dbtag", "in", "dbxref_values", ":", "if", "id", "in", "dbxref_values", "[", "dbtag", "]", ":", "g", ".", "set_attr", "(", "\"Dbxref\"", ",", "dbxref_values", "[", "dbtag", "]", "[", "id", "]", ",", "dbtag", "=", "dbtag", ",", "append", "=", "True", ")", "if", "unique", ":", "if", "dupcounts", "[", "id", "]", ">", "1", ":", "seen", "[", "id", "]", "+=", "1", "old_id", "=", "id", "id", "=", "\"{0}-{1}\"", ".", "format", "(", "old_id", ",", "seen", "[", "old_id", "]", ")", "newparentid", "[", "old_id", "]", "=", "id", "g", ".", "set_attr", "(", "\"ID\"", ",", "id", ")", "if", "\"Parent\"", "in", "g", ".", "attributes", ":", "parent", "=", "g", ".", "attributes", "[", "\"Parent\"", "]", "[", "0", "]", "if", "dupcounts", "[", "parent", "]", ">", "1", ":", "g", ".", "set_attr", "(", "\"Parent\"", ",", "newparentid", "[", "parent", "]", ")", "if", "duptype", ":", "if", "duptype", "==", "g", ".", "type", "and", "len", "(", "dupranges", "[", "g", ".", "seqid", "]", "[", "id", "]", ")", ">", "1", ":", "p", "=", "sorted", "(", "dupranges", "[", "g", ".", "seqid", "]", "[", "id", "]", ")", "s", ",", "e", "=", "dupranges", "[", "g", ".", "seqid", "]", "[", "id", "]", "[", "p", "[", "0", "]", "]", "[", "0", ":", "2", "]", "# get coords of first encountered feature", "if", "g", ".", "start", "==", "s", "and", "g", ".", "end", "==", "e", "and", "p", "[", "0", "]", "==", "g", ".", "idx", ":", "r", "=", "[", "dupranges", "[", "g", ".", "seqid", "]", "[", "id", "]", "[", "x", "]", "for", "x", "in", "dupranges", "[", "g", ".", "seqid", "]", "[", "id", "]", "]", "g", ".", "start", ",", "g", ".", "end", "=", "range_minmax", "(", "r", ")", "else", ":", "skip", "[", "(", "g", ".", "seqid", ",", "g", ".", "idx", ",", "id", ",", "g", ".", "start", ",", "g", ".", "end", ")", "]", "=", "1", "if", "gsac", "and", "g", ".", "type", "==", "\"gene\"", ":", "notes", "[", "id", "]", "=", "g", ".", "attributes", "[", "\"Name\"", "]", "if", "ftype", ":", "if", "isinstance", "(", "ftype", ",", "dict", ")", "and", "g", ".", "type", "in", "ftype", ":", "g", ".", "type", "=", "ftype", "[", "g", ".", "type", "]", "else", ":", "g", ".", "type", "=", "ftype", "if", "invent_name_attr", ":", "ft", ".", "store_symbol", "(", "g", ")", "if", "re", ".", "search", "(", "ft", ".", "ftype", ",", "g", ".", "type", ")", ":", "parent", ",", "iso", "=", "atg_name", "(", "g", ".", "get_attr", "(", "\"Parent\"", ")", ",", "retval", "=", "\"locus,iso\"", ")", "if", "not", "parent", ":", "parent", "=", "g", ".", "get_attr", "(", "\"Parent\"", ")", "if", "parent", "in", "ft", ".", "tracker", ":", "fidx", "=", "ft", ".", "feat_index", "(", "parent", ",", "g", ".", "type", ",", "g", ".", "strand", ",", "(", "g", ".", "start", ",", "g", ".", "end", ",", "g", ".", "sign", ")", ")", "symbol", "=", "ft", ".", "get_symbol", "(", "parent", ")", "attr", "=", "\"ID\"", "if", "symbol", "==", "parent", "else", "\"Name\"", "g", ".", "set_attr", "(", "attr", ",", "\"{0}:{1}:{2}\"", ".", "format", "(", "symbol", ",", "g", ".", "type", ",", "fidx", "+", "1", ")", ")", "if", "opts", ".", "multiparents", "==", "\"merge\"", "and", "attr", "==", "\"Name\"", ":", "g", ".", "set_attr", "(", "\"ID\"", ",", "\"{0}:{1}:{2}\"", ".", "format", "(", "parent", ",", "g", ".", "type", ",", "fidx", "+", "1", ")", ")", "elif", "copy_id_attr_to_name", ":", "if", "\"Name\"", "not", "in", "g", ".", "attributes", ".", "keys", "(", ")", ":", "g", ".", "set_attr", "(", "\"Name\"", ",", "g", ".", "get_attr", "(", "\"ID\"", ")", ")", "protein_feat", "=", "None", "if", "invent_protein_feat", ":", "if", "g", ".", "type", "==", "'mRNA'", ":", "if", "id", "in", "cds_track", ":", "pstart", ",", "pstop", "=", "range_minmax", "(", "cds_track", "[", "id", "]", ")", "protein_feat", "=", "GffLine", "(", "\"\\t\"", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "[", "g", ".", "seqid", ",", "g", ".", "source", ",", "\"protein\"", ",", "pstart", ",", "pstop", ",", "\".\"", ",", "g", ".", "strand", ",", "\".\"", ",", "\"ID={0}-Protein;Name={0};Derives_from={0}\"", ".", "format", "(", "id", ")", "]", ")", ")", "elif", "g", ".", "type", "==", "'CDS'", ":", "parent", "=", "g", ".", "get_attr", "(", "\"Parent\"", ")", "if", "parent", "in", "cds_track", ":", "_parent", "=", "[", "parent", ",", "\"{0}-Protein\"", ".", "format", "(", "parent", ")", "]", "g", ".", "set_attr", "(", "\"Parent\"", ",", "_parent", ")", "pp", "=", "g", ".", "get_attr", "(", "\"Parent\"", ",", "first", "=", "False", ")", "if", "opts", ".", "multiparents", "==", "\"split\"", "and", "(", "pp", "and", "len", "(", "pp", ")", ">", "1", ")", "and", "g", ".", "type", "!=", "\"CDS\"", ":", "# separate features with multiple parents", "id", "=", "g", ".", "get_attr", "(", "\"ID\"", ")", "for", "i", ",", "parent", "in", "enumerate", "(", "pp", ")", ":", "if", "id", ":", "g", ".", "set_attr", "(", "\"ID\"", ",", "\"{0}-{1}\"", ".", "format", "(", "id", ",", "i", "+", "1", ")", ")", "g", ".", "set_attr", "(", "\"Parent\"", ",", "parent", ",", "update", "=", "True", ",", "urlquote", "=", "True", ")", "if", "gsac", ":", "fix_gsac", "(", "g", ",", "notes", ")", "print", "(", "g", ",", "file", "=", "fw", ")", "else", ":", "if", "g", ".", "gff3", "and", "not", "opts", ".", "gff3", ":", "opts", ".", "gff3", "=", "True", "g", ".", "update_attributes", "(", "gff3", "=", "opts", ".", "gff3", ")", "if", "gsac", ":", "fix_gsac", "(", "g", ",", "notes", ")", "if", "duptype", "==", "g", ".", "type", "and", "skip", "[", "(", "g", ".", "seqid", ",", "g", ".", "idx", ",", "id", ",", "g", ".", "start", ",", "g", ".", "end", ")", "]", "==", "1", ":", "continue", "print", "(", "g", ",", "file", "=", "fw", ")", "if", "g", ".", "type", "==", "'mRNA'", "and", "invent_protein_feat", ":", "print", "(", "protein_feat", ",", "file", "=", "fw", ")", "fw", ".", "close", "(", ")" ]
43.049383
21.528395
def add_peak_demand(self): """Summarizes peak loads of underlying load_areas in kVA. (peak load sum and peak load of satellites) """ peak_load = peak_load_satellites = 0 for lv_load_area in self.lv_load_areas(): peak_load += lv_load_area.peak_load if lv_load_area.is_satellite: peak_load_satellites += lv_load_area.peak_load self.peak_load = peak_load self.peak_load_satellites = peak_load_satellites
[ "def", "add_peak_demand", "(", "self", ")", ":", "peak_load", "=", "peak_load_satellites", "=", "0", "for", "lv_load_area", "in", "self", ".", "lv_load_areas", "(", ")", ":", "peak_load", "+=", "lv_load_area", ".", "peak_load", "if", "lv_load_area", ".", "is_satellite", ":", "peak_load_satellites", "+=", "lv_load_area", ".", "peak_load", "self", ".", "peak_load", "=", "peak_load", "self", ".", "peak_load_satellites", "=", "peak_load_satellites" ]
41.166667
10.166667
def compile_excludes(self): """Compile a set of regexps for files to be exlcuded from scans.""" self.compiled_exclude_files = [] for pattern in self.exclude_files: try: self.compiled_exclude_files.append(re.compile(pattern)) except re.error as e: raise ValueError( "Bad python regex in exclude '%s': %s" % (pattern, str(e)))
[ "def", "compile_excludes", "(", "self", ")", ":", "self", ".", "compiled_exclude_files", "=", "[", "]", "for", "pattern", "in", "self", ".", "exclude_files", ":", "try", ":", "self", ".", "compiled_exclude_files", ".", "append", "(", "re", ".", "compile", "(", "pattern", ")", ")", "except", "re", ".", "error", "as", "e", ":", "raise", "ValueError", "(", "\"Bad python regex in exclude '%s': %s\"", "%", "(", "pattern", ",", "str", "(", "e", ")", ")", ")" ]
46.222222
13.666667
def generate(self): """ Generates a new token for this column based on its bit length. This method will not ensure uniqueness in the model itself, that should be checked against the model records in the database first. :return: <str> """ try: model = self.schema().model() except AttributeError: return os.urandom(self.__bits).encode('hex') else: while True: token = os.urandom(self.__bits).encode('hex') if model.select(where=orb.Query(self) == token).count() == 0: return token
[ "def", "generate", "(", "self", ")", ":", "try", ":", "model", "=", "self", ".", "schema", "(", ")", ".", "model", "(", ")", "except", "AttributeError", ":", "return", "os", ".", "urandom", "(", "self", ".", "__bits", ")", ".", "encode", "(", "'hex'", ")", "else", ":", "while", "True", ":", "token", "=", "os", ".", "urandom", "(", "self", ".", "__bits", ")", ".", "encode", "(", "'hex'", ")", "if", "model", ".", "select", "(", "where", "=", "orb", ".", "Query", "(", "self", ")", "==", "token", ")", ".", "count", "(", ")", "==", "0", ":", "return", "token" ]
36.941176
19.882353
def get_languages(self, target_language=None): """Get list of supported languages for translation. Response See https://cloud.google.com/translate/docs/discovering-supported-languages :type target_language: str :param target_language: (Optional) The language used to localize returned language names. Defaults to the target language on the current client. :rtype: list :returns: List of dictionaries. Each dictionary contains a supported ISO 639-1 language code (using the dictionary key ``language``). If ``target_language`` is passed, each dictionary will also contain the name of each supported language (localized to the target language). """ query_params = {} if target_language is None: target_language = self.target_language if target_language is not None: query_params["target"] = target_language response = self._connection.api_request( method="GET", path="/languages", query_params=query_params ) return response.get("data", {}).get("languages", ())
[ "def", "get_languages", "(", "self", ",", "target_language", "=", "None", ")", ":", "query_params", "=", "{", "}", "if", "target_language", "is", "None", ":", "target_language", "=", "self", ".", "target_language", "if", "target_language", "is", "not", "None", ":", "query_params", "[", "\"target\"", "]", "=", "target_language", "response", "=", "self", ".", "_connection", ".", "api_request", "(", "method", "=", "\"GET\"", ",", "path", "=", "\"/languages\"", ",", "query_params", "=", "query_params", ")", "return", "response", ".", "get", "(", "\"data\"", ",", "{", "}", ")", ".", "get", "(", "\"languages\"", ",", "(", ")", ")" ]
42.310345
22.724138
def Parse(self, stat, file_object, knowledge_base): """Parse the netgroup file and return User objects. Lines are of the form: group1 (-,user1,) (-,user2,) (-,user3,) Groups are ignored, we return users in lines that match the filter regexes, or all users in the file if no filters are specified. We assume usernames are in the default regex format specified in the adduser man page. Notably no non-ASCII characters. Args: stat: unused statentry file_object: netgroup VFSFile knowledge_base: unused Returns: rdf_client.User """ _, _ = stat, knowledge_base lines = [ l.strip() for l in utils.ReadFileBytesAsUnicode(file_object).splitlines() ] return self.ParseLines(lines)
[ "def", "Parse", "(", "self", ",", "stat", ",", "file_object", ",", "knowledge_base", ")", ":", "_", ",", "_", "=", "stat", ",", "knowledge_base", "lines", "=", "[", "l", ".", "strip", "(", ")", "for", "l", "in", "utils", ".", "ReadFileBytesAsUnicode", "(", "file_object", ")", ".", "splitlines", "(", ")", "]", "return", "self", ".", "ParseLines", "(", "lines", ")" ]
28.846154
22
def _create_new_thread_loop(self): """ Create a daemonized thread that will run Tornado IOLoop. :return: the IOLoop backed by the new thread. """ self._thread_loop = ThreadLoop() if not self._thread_loop.is_ready(): self._thread_loop.start() return self._thread_loop._io_loop
[ "def", "_create_new_thread_loop", "(", "self", ")", ":", "self", ".", "_thread_loop", "=", "ThreadLoop", "(", ")", "if", "not", "self", ".", "_thread_loop", ".", "is_ready", "(", ")", ":", "self", ".", "_thread_loop", ".", "start", "(", ")", "return", "self", ".", "_thread_loop", ".", "_io_loop" ]
37.222222
5.666667
def convert_options(settings, defaults=None): """ Convert a settings object (or dictionary) to parameters which may be passed to a new ``Client()`` instance. """ if defaults is None: defaults = {} if isinstance(settings, dict): def getopt(key, default=None): return settings.get( 'SENTRY_%s' % key.upper(), defaults.get(key, default) ) options = copy.copy( settings.get('SENTRY_CONFIG') or settings.get('RAVEN_CONFIG') or {} ) else: def getopt(key, default=None): return getattr(settings, 'SENTRY_%s' % key.upper(), defaults.get(key, default)) options = copy.copy( getattr(settings, 'SENTRY_CONFIG', None) or getattr(settings, 'RAVEN_CONFIG', None) or {} ) options.setdefault('include_paths', getopt('include_paths', [])) options.setdefault('exclude_paths', getopt('exclude_paths', [])) options.setdefault('timeout', getopt('timeout')) options.setdefault('name', getopt('name')) options.setdefault('auto_log_stacks', getopt('auto_log_stacks')) options.setdefault('string_max_length', getopt('string_max_length')) options.setdefault('list_max_length', getopt('list_max_length')) options.setdefault('site', getopt('site')) options.setdefault('processors', getopt('processors')) options.setdefault('sanitize_keys', getopt('sanitize_keys')) options.setdefault('dsn', getopt('dsn', os.environ.get('SENTRY_DSN'))) options.setdefault('context', getopt('context')) options.setdefault('tags', getopt('tags')) options.setdefault('release', getopt('release')) options.setdefault('repos', getopt('repos')) options.setdefault('environment', getopt('environment')) options.setdefault('ignore_exceptions', getopt('ignore_exceptions')) options.setdefault('sample_rate', getopt('sample_rate')) transport = getopt('transport') or options.get('transport') if isinstance(transport, string_types): transport = import_string(transport) options['transport'] = transport return options
[ "def", "convert_options", "(", "settings", ",", "defaults", "=", "None", ")", ":", "if", "defaults", "is", "None", ":", "defaults", "=", "{", "}", "if", "isinstance", "(", "settings", ",", "dict", ")", ":", "def", "getopt", "(", "key", ",", "default", "=", "None", ")", ":", "return", "settings", ".", "get", "(", "'SENTRY_%s'", "%", "key", ".", "upper", "(", ")", ",", "defaults", ".", "get", "(", "key", ",", "default", ")", ")", "options", "=", "copy", ".", "copy", "(", "settings", ".", "get", "(", "'SENTRY_CONFIG'", ")", "or", "settings", ".", "get", "(", "'RAVEN_CONFIG'", ")", "or", "{", "}", ")", "else", ":", "def", "getopt", "(", "key", ",", "default", "=", "None", ")", ":", "return", "getattr", "(", "settings", ",", "'SENTRY_%s'", "%", "key", ".", "upper", "(", ")", ",", "defaults", ".", "get", "(", "key", ",", "default", ")", ")", "options", "=", "copy", ".", "copy", "(", "getattr", "(", "settings", ",", "'SENTRY_CONFIG'", ",", "None", ")", "or", "getattr", "(", "settings", ",", "'RAVEN_CONFIG'", ",", "None", ")", "or", "{", "}", ")", "options", ".", "setdefault", "(", "'include_paths'", ",", "getopt", "(", "'include_paths'", ",", "[", "]", ")", ")", "options", ".", "setdefault", "(", "'exclude_paths'", ",", "getopt", "(", "'exclude_paths'", ",", "[", "]", ")", ")", "options", ".", "setdefault", "(", "'timeout'", ",", "getopt", "(", "'timeout'", ")", ")", "options", ".", "setdefault", "(", "'name'", ",", "getopt", "(", "'name'", ")", ")", "options", ".", "setdefault", "(", "'auto_log_stacks'", ",", "getopt", "(", "'auto_log_stacks'", ")", ")", "options", ".", "setdefault", "(", "'string_max_length'", ",", "getopt", "(", "'string_max_length'", ")", ")", "options", ".", "setdefault", "(", "'list_max_length'", ",", "getopt", "(", "'list_max_length'", ")", ")", "options", ".", "setdefault", "(", "'site'", ",", "getopt", "(", "'site'", ")", ")", "options", ".", "setdefault", "(", "'processors'", ",", "getopt", "(", "'processors'", ")", ")", "options", ".", "setdefault", "(", "'sanitize_keys'", ",", "getopt", "(", "'sanitize_keys'", ")", ")", "options", ".", "setdefault", "(", "'dsn'", ",", "getopt", "(", "'dsn'", ",", "os", ".", "environ", ".", "get", "(", "'SENTRY_DSN'", ")", ")", ")", "options", ".", "setdefault", "(", "'context'", ",", "getopt", "(", "'context'", ")", ")", "options", ".", "setdefault", "(", "'tags'", ",", "getopt", "(", "'tags'", ")", ")", "options", ".", "setdefault", "(", "'release'", ",", "getopt", "(", "'release'", ")", ")", "options", ".", "setdefault", "(", "'repos'", ",", "getopt", "(", "'repos'", ")", ")", "options", ".", "setdefault", "(", "'environment'", ",", "getopt", "(", "'environment'", ")", ")", "options", ".", "setdefault", "(", "'ignore_exceptions'", ",", "getopt", "(", "'ignore_exceptions'", ")", ")", "options", ".", "setdefault", "(", "'sample_rate'", ",", "getopt", "(", "'sample_rate'", ")", ")", "transport", "=", "getopt", "(", "'transport'", ")", "or", "options", ".", "get", "(", "'transport'", ")", "if", "isinstance", "(", "transport", ",", "string_types", ")", ":", "transport", "=", "import_string", "(", "transport", ")", "options", "[", "'transport'", "]", "=", "transport", "return", "options" ]
38.781818
18.672727
def localize_datetime(datetime_obj, tz=pytz.utc): """Converts a naive or UTC-localized date into the provided timezone. :param datetime_obj: The datetime object. :type datetime_obj: datetime :param tz: The timezone. If blank or None, UTC is used. :type tz: datetime.tzinfo :return: The localized datetime object. :rtype: datetime """ if not datetime_obj.tzinfo: return tz.localize(datetime_obj) else: try: return datetime_obj.astimezone(tz) except OverflowError: if datetime_obj < datetime(2, 1, 1, tzinfo=pytz.utc): return MIN_DATE.astimezone(tz) return MAX_DATE.astimezone(tz)
[ "def", "localize_datetime", "(", "datetime_obj", ",", "tz", "=", "pytz", ".", "utc", ")", ":", "if", "not", "datetime_obj", ".", "tzinfo", ":", "return", "tz", ".", "localize", "(", "datetime_obj", ")", "else", ":", "try", ":", "return", "datetime_obj", ".", "astimezone", "(", "tz", ")", "except", "OverflowError", ":", "if", "datetime_obj", "<", "datetime", "(", "2", ",", "1", ",", "1", ",", "tzinfo", "=", "pytz", ".", "utc", ")", ":", "return", "MIN_DATE", ".", "astimezone", "(", "tz", ")", "return", "MAX_DATE", ".", "astimezone", "(", "tz", ")" ]
35.631579
12.263158
def htmlize_paragraphs(text): """ Convert paragraphs delimited by blank lines into HTML text enclosed in <p> tags. """ paragraphs = re.split('(\r?\n)\s*(\r?\n)', text) return '\n'.join('<p>%s</p>' % paragraph for paragraph in paragraphs)
[ "def", "htmlize_paragraphs", "(", "text", ")", ":", "paragraphs", "=", "re", ".", "split", "(", "'(\\r?\\n)\\s*(\\r?\\n)'", ",", "text", ")", "return", "'\\n'", ".", "join", "(", "'<p>%s</p>'", "%", "paragraph", "for", "paragraph", "in", "paragraphs", ")" ]
36.428571
15.857143
def init_strate(self, global_setting, quant_frame, event_engine): """TinyQuantFrame 初始化策略的接口""" if type(self._quant_frame) is not int: return True self._quant_frame = quant_frame self._event_engine = event_engine init_ret = self.__loadSetting(global_setting) # 注册事件 self._event_engine.register(EVENT_BEFORE_TRADING, self.__event_before_trading) self._event_engine.register(EVENT_AFTER_TRADING, self.__event_after_trading) self._event_engine.register(EVENT_QUOTE_CHANGE, self.__event_quote_change) self._event_engine.register(EVENT_CUR_KLINE_BAR, self.__event_cur_kline_bar) self.log("init_strate '%s' ret = %s" % (self.name, init_ret)) # 对外通知初始化事件 self.on_init_strate() return init_ret
[ "def", "init_strate", "(", "self", ",", "global_setting", ",", "quant_frame", ",", "event_engine", ")", ":", "if", "type", "(", "self", ".", "_quant_frame", ")", "is", "not", "int", ":", "return", "True", "self", ".", "_quant_frame", "=", "quant_frame", "self", ".", "_event_engine", "=", "event_engine", "init_ret", "=", "self", ".", "__loadSetting", "(", "global_setting", ")", "# 注册事件", "self", ".", "_event_engine", ".", "register", "(", "EVENT_BEFORE_TRADING", ",", "self", ".", "__event_before_trading", ")", "self", ".", "_event_engine", ".", "register", "(", "EVENT_AFTER_TRADING", ",", "self", ".", "__event_after_trading", ")", "self", ".", "_event_engine", ".", "register", "(", "EVENT_QUOTE_CHANGE", ",", "self", ".", "__event_quote_change", ")", "self", ".", "_event_engine", ".", "register", "(", "EVENT_CUR_KLINE_BAR", ",", "self", ".", "__event_cur_kline_bar", ")", "self", ".", "log", "(", "\"init_strate '%s' ret = %s\"", "%", "(", "self", ".", "name", ",", "init_ret", ")", ")", "# 对外通知初始化事件", "self", ".", "on_init_strate", "(", ")", "return", "init_ret" ]
36.090909
26.5
def create(input_shape): """ Vel factory function """ if isinstance(input_shape, numbers.Number): input_shape = (input_shape,) elif not isinstance(input_shape, tuple): input_shape = tuple(input_shape) def instantiate(**_): return NormalizeObservations(input_shape) return ModelFactory.generic(instantiate)
[ "def", "create", "(", "input_shape", ")", ":", "if", "isinstance", "(", "input_shape", ",", "numbers", ".", "Number", ")", ":", "input_shape", "=", "(", "input_shape", ",", ")", "elif", "not", "isinstance", "(", "input_shape", ",", "tuple", ")", ":", "input_shape", "=", "tuple", "(", "input_shape", ")", "def", "instantiate", "(", "*", "*", "_", ")", ":", "return", "NormalizeObservations", "(", "input_shape", ")", "return", "ModelFactory", ".", "generic", "(", "instantiate", ")" ]
31
12.636364