Mir-2002/python-google-style-docstrings
Overview This dataset contains Python code-docstring pairs, whereas the docstrings are in Google style. A Google style docstring is structured as follows: <Description of the code> Args: <var1> (<data-type>) : <description of var1> <var2> (<data_type>) : <description of var2> Returns: <var3> (<data-type>) : <description of var3> Raises: <var4> (<data-type>) : <description of var4> The format varies widely (like additional sections such as Examples, Notes, etc) but generally… See the full description on the dataset page: https://huggingface.co/datasets/Mir-2002/python-google-style-docstrings.
07
1{"code": "def in_flight_request_count(self, node_id=None):\n \n if node_id is not None:\n conn = self._conns.get(node_id)\n if conn is None:\n return 0\n return len(conn.in_flight_requests)\n else:\n return sum([len(conn.in_flight_requests)\n for conn in list(self._conns.values())])", "docstring": "Get the number of in-flight requests for a node or all nodes.\n\nArguments:\nnode_id (int, optional): a specific node to check. If unspecified,\nreturn the total for all nodes\n\nReturns:\nint: pending in-flight requests for the node, or all nodes if None", "source": "juraj-google-style"}
2{"code": "def set_size(self, w, h):\n self.attributes['width'] = str(w)\n self.attributes['height'] = str(h)", "docstring": "Sets the rectangle size.\n\nArgs:\nw (int): width of the rectangle\nh (int): height of the rectangle", "source": "codesearchnet"}
3{"code": "def validate_stats(stats_path, schema_path, anomalies_path):\n print('Validating schema against the computed statistics.')\n schema = taxi.read_schema(schema_path)\n stats = tfdv.load_statistics(stats_path)\n anomalies = tfdv.validate_statistics(stats, schema)\n print('Detected following anomalies:')\n print(text_format.MessageToString(anomalies))\n print('Writing anomalies to anomalies path.')\n file_io.write_string_to_file(anomalies_path, text_format.MessageToString(anomalies))", "docstring": "Validates the statistics against the schema and materializes anomalies.\n\nArgs:\nstats_path: Location of the stats used to infer the schema.\nschema_path: Location of the schema to be used for validation.\nanomalies_path: Location where the detected anomalies are materialized.", "source": "github-repos"}
4{"code": "def failed_rows_with_errors(self) -> PCollection[Tuple[str, dict, list]]:\n self.validate([WriteToBigQuery.Method.STREAMING_INSERTS, WriteToBigQuery.Method.STORAGE_WRITE_API], 'FAILED_ROWS_WITH_ERRORS')\n return self._failed_rows_with_errors", "docstring": "A ``[STREAMING_INSERTS, STORAGE_WRITE_API]`` method attribute\n\nReturns:\nA PCollection of rows that failed when inserting to BigQuery,\nalong with their errors.\n\nRaises:\nAttributeError: if accessed with a write method\nbesides ``[STREAMING_INSERTS, STORAGE_WRITE_API]``.", "source": "github-repos"}
5{"code": "def run(self, dag):\n \n \n for node in dag.op_nodes():\n basic_insts = ['measure', 'reset', 'barrier', 'snapshot']\n if node.name in basic_insts:\n \n \n \n continue\n if node.name in self.basis: \n continue\n\n \n rule = node.op.definition\n if not rule:\n raise QiskitError(\"Cannot unroll the circuit to the given basis, %s. \"\n \"No rule to expand instruction %s.\" %\n (str(self.basis), node.op.name))\n\n \n \n decomposition = DAGCircuit()\n decomposition.add_qreg(rule[0][1][0][0])\n for inst in rule:\n decomposition.apply_operation_back(*inst)\n\n unrolled_dag = self.run(decomposition) \n dag.substitute_node_with_dag(node, unrolled_dag)\n return dag", "docstring": "Expand all op nodes to the given basis.\n\nArgs:\ndag(DAGCircuit): input dag\n\nRaises:\nQiskitError: if unable to unroll given the basis due to undefined\ndecomposition rules (such as a bad basis) or excessive recursion.\n\nReturns:\nDAGCircuit: output unrolled dag", "source": "juraj-google-style"}
6{"code": "def _make_static_axis_non_negative_list(axis, ndims):\n axis = distribution_util.make_non_negative_axis(axis, ndims)\n axis_const = tf.get_static_value(axis)\n if (axis_const is None):\n raise ValueError(('Expected argument `axis` to be statically available. Found: %s' % axis))\n axis = (axis_const + np.zeros([1], dtype=axis_const.dtype))\n return list((int(dim) for dim in axis))", "docstring": "Convert possibly negatively indexed axis to non-negative list of ints.\n\nArgs:\naxis: Integer Tensor.\nndims: Number of dimensions into which axis indexes.\n\nReturns:\nA list of non-negative Python integers.\n\nRaises:\nValueError: If `axis` is not statically defined.", "source": "codesearchnet"}
7{"code": "def _dump(self):\n return {'topic': self.topic, 'headers': self._headers, 'id': self.id, 'body': self.body, 'queue': self.queue}", "docstring": "Dump message attributes.\n\nReturns:\ndict: A dictionary of message attributes.", "source": "codesearchnet"}
8{"code": "def quad_genz_keister_18(order):\n order = sorted(GENZ_KEISTER_18.keys())[order]\n (abscissas, weights) = GENZ_KEISTER_18[order]\n abscissas = numpy.array(abscissas)\n weights = numpy.array(weights)\n weights /= numpy.sum(weights)\n abscissas *= numpy.sqrt(2)\n return (abscissas, weights)", "docstring": "Hermite Genz-Keister 18 rule.\n\nArgs:\norder (int):\nThe quadrature order. Must be in the interval (0, 8).\n\nReturns:\n(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):\nAbscissas and weights\n\nExamples:\n>>> abscissas, weights = quad_genz_keister_18(1)\n>>> print(numpy.around(abscissas, 4))\n[-1.7321 0. 1.7321]\n>>> print(numpy.around(weights, 4))\n[0.1667 0.6667 0.1667]", "source": "codesearchnet"}
9{"code": "def _buckets_nearly_equal(a_dist, b_dist):\n \n a_type, a_buckets = _detect_bucket_option(a_dist)\n b_type, b_buckets = _detect_bucket_option(b_dist)\n if a_type != b_type:\n return False\n elif a_type == u'linearBuckets':\n return _linear_buckets_nearly_equal(a_buckets, b_buckets)\n elif a_type == u'exponentialBuckets':\n return _exponential_buckets_nearly_equal(a_buckets, b_buckets)\n elif a_type == u'explicitBuckets':\n return _explicit_buckets_nearly_equal(a_buckets, b_buckets)\n else:\n return False", "docstring": "Determines whether two `Distributions` are nearly equal.\n\nArgs:\na_dist (:class:`Distribution`): an instance\nb_dist (:class:`Distribution`): another instance\n\nReturn:\nboolean: `True` if the two instances are approximately equal, otherwise\nFalse", "source": "juraj-google-style"}
10{"code": "def __init__(self, dist_cls_a, dist_cls_b):\n self._key = (dist_cls_a, dist_cls_b)", "docstring": "Initialize the KL registrar.\n\nArgs:\ndist_cls_a: the class of the first argument of the KL divergence.\ndist_cls_b: the class of the second argument of the KL divergence.", "source": "github-repos"}
11{"code": "def add_values_to_bundle_safe(connection, bundle, values):\n \n for value in values:\n try:\n connection.addValueToBundle(bundle, value)\n except YouTrackException as e:\n if e.response.status == 409:\n print(\"Value with name [ %s ] already exists in bundle [ %s ]\" %\n (utf8encode(value.name), utf8encode(bundle.name)))\n else:\n raise e", "docstring": "Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added.\n\nArgs:\nconnection: An opened Connection instance.\nbundle: Bundle instance to add values in.\nvalues: Values, that should be added in bundle.\n\nRaises:\nYouTrackException: if something is wrong with queries.", "source": "juraj-google-style"}
12{"code": "def plot_script(self, script):\n \n\n script.plot([self.matplotlibwidget_1.figure, self.matplotlibwidget_2.figure])\n self.matplotlibwidget_1.draw()\n self.matplotlibwidget_2.draw()", "docstring": "Calls the plot function of the script, and redraws both plots\nArgs:\nscript: script to be plotted", "source": "juraj-google-style"}
13{"code": "def set_servo_position(self, goalposition, goaltime, led):\n \n goalposition_msb = int(goalposition) >> 8\n goalposition_lsb = int(goalposition) & 0xff\n\n data = []\n data.append(0x0C)\n data.append(self.servoid)\n data.append(I_JOG_REQ)\n data.append(goalposition_lsb)\n data.append(goalposition_msb)\n data.append(led)\n data.append(self.servoid)\n data.append(goaltime)\n send_data(data)", "docstring": "Set the position of Herkulex\n\nEnable torque using torque_on function before calling this\n\nArgs:\n\ngoalposition (int): The desired position, min-0 & max-1023\ngoaltime (int): the time taken to move from present\nposition to goalposition\nled (int): the LED color\n0x00 LED off\n0x04 GREEN\n0x08 BLUE\n0x10 RED", "source": "juraj-google-style"}
14{"code": "def __init__(self, counter_name, delta=1):\n \n self.counter_name = counter_name\n self.delta = delta", "docstring": "Constructor.\n\nArgs:\ncounter_name: name of the counter as string\ndelta: increment delta as int.", "source": "juraj-google-style"}
15{"code": "def tent_transform(value: types.FloatTensor) -> types.FloatTensor:\n return tf.where(value < 0.5, 2 * value, 2 * (1 - value))", "docstring": "Returns the tent transform of a given `Tensor`.\n\n#### Examples\n\n```python\nimport tensorflow as tf\nimport tf_quant_finance as tff\n\n# Example: Commputing the tent transform of a given vector.\n\ntff.math.qmc.utils.tent_transform(tf.constant([0, .2, .4, .6, .8, 1]))\n# ==> tf.Tensor([0, .4, .8, .8, .4, 0.], shape=(4,), dtype=float32)\n```\n\nArgs:\nvalue: Scalar `Tensor` of real values in the `[0, 1)` range.\n\nReturns:\n`Tensor` with the same `shape` as `value` equal to `2 ** value` if `value`\nis less than `0.5` or `2 * (1 - value)` otherwise.", "source": "github-repos"}
16{"code": "def list_media_services(access_token, subscription_id):\n \n endpoint = ''.join([get_rm_endpoint(),\n '/subscriptions/', subscription_id,\n '/providers/microsoft.media/mediaservices?api-version=', MEDIA_API])\n return do_get(endpoint, access_token)", "docstring": "List the media services in a subscription.\n\nArgs:\naccess_token (str): A valid Azure authentication token.\nsubscription_id (str): Azure subscription id.\n\nReturns:\nHTTP response. JSON body.", "source": "juraj-google-style"}
17{"code": "def icon_description(self, **kwargs):\n params = {'language': util.language_code(kwargs.get('lang'))}\n result = self.make_request('icon_description', {}, **params)\n if (not util.check_result(result)):\n return (False, result.get('message', 'UNKNOWN ERROR'))\n values = util.response_list(result, 'Data')\n return (True, [emtype.IconDescription(**a) for a in values])", "docstring": "Obtain a list of elements that have an associated icon.\n\nArgs:\nlang (str): Language code (*es* or *en*).\n\nReturns:\nStatus boolean and parsed response (list[IconDescription]), or\nmessage string in case of error.", "source": "codesearchnet"}
18{"code": "def has_succeed(self):\n status_code = self._response.status_code\n if (status_code in [HTTP_CODE_ZERO, HTTP_CODE_SUCCESS, HTTP_CODE_CREATED, HTTP_CODE_EMPTY, HTTP_CODE_MULTIPLE_CHOICES]):\n return True\n if (status_code in [HTTP_CODE_BAD_REQUEST, HTTP_CODE_UNAUTHORIZED, HTTP_CODE_PERMISSION_DENIED, HTTP_CODE_NOT_FOUND, HTTP_CODE_METHOD_NOT_ALLOWED, HTTP_CODE_CONNECTION_TIMEOUT, HTTP_CODE_CONFLICT, HTTP_CODE_PRECONDITION_FAILED, HTTP_CODE_INTERNAL_SERVER_ERROR, HTTP_CODE_SERVICE_UNAVAILABLE]):\n return False\n raise Exception('Unknown status code %s.', status_code)", "docstring": "Check if the connection has succeed\n\nReturns:\nReturns True if connection has succeed.\nFalse otherwise.", "source": "codesearchnet"}
19{"code": "def train_on_batch(model, inputs, targets, sample_weights=None, output_loss_metrics=None):\n inputs = training_utils_v1.cast_to_model_input_dtypes(inputs, model)\n outs, total_loss, output_losses, masks = _process_single_batch(model, inputs, targets, sample_weights=sample_weights, training=True, output_loss_metrics=output_loss_metrics)\n if not isinstance(outs, list):\n outs = [outs]\n metrics_results = _eager_metrics_fn(model, outs, targets, sample_weights=sample_weights, masks=masks)\n total_loss = nest.flatten(total_loss)\n return {'total_loss': total_loss, 'output_losses': output_losses, 'metrics': metrics_results}", "docstring": "Calculates the loss and gradient updates for one input batch.\n\nArgs:\nmodel: Model whose loss has to be calculated.\ninputs: Input batch data.\ntargets: Target batch data.\nsample_weights: Sample weight batch data.\noutput_loss_metrics: List of metrics that are used to aggregated output\nloss values.\n\nReturns:\nDict with three items:\n'total_loss': list with a single tensor for overall loss,\n'output_losses': list of tensors for loss corresponding to each of the\nmodel output. Could be a empty list when model has only one output.\n'metrics': list of tensors for metric specified.", "source": "github-repos"}
20{"code": "def loads(s, single=False):\n corpus = etree.fromstring(s)\n if single:\n ds = _deserialize_dmrs(next(iter(corpus)))\n else:\n ds = (_deserialize_dmrs(dmrs_elem) for dmrs_elem in corpus)\n return ds", "docstring": "Deserialize DMRX string representations\n\nArgs:\ns (str): a DMRX string\nsingle (bool): if `True`, only return the first Xmrs object\nReturns:\na generator of Xmrs objects (unless *single* is `True`)", "source": "codesearchnet"}
21{"code": "def verify_reset_restored_iterator(self, ds_fn, num_outputs, break_point=None, sparse_tensors=False, verify_exhausted=True, assert_items_equal=False):\n if context.executing_eagerly():\n self.skipTest('Eager mode iteration do not support re-initialization.')\n break_point = num_outputs \n expected = self.gen_outputs(ds_fn, [], num_outputs, sparse_tensors=sparse_tensors, verify_exhausted=verify_exhausted)\n self.gen_outputs(ds_fn, [], break_point, sparse_tensors=sparse_tensors, verify_exhausted=False)\n actual = []\n with ops.Graph().as_default() as g:\n saver = self._import_meta_graph()\n init_op, get_next_op = self._get_iterator_ops_from_collection(ds_fn, sparse_tensors=sparse_tensors)\n get_next_op = remove_variants(get_next_op)\n with self.session(graph=g) as sess:\n self._initialize(init_op, sess)\n self._restore(saver, sess)\n self._initialize(init_op, sess)\n for _ in range(num_outputs):\n actual.append(sess.run(get_next_op))\n if verify_exhausted:\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next_op)\n self.match(expected, actual, assert_items_equal=assert_items_equal)", "docstring": "Attempts to re-initialize a restored iterator.\n\nThis is useful when restoring a training checkpoint during validation.\n\nArgs:\nds_fn: 0-argument function that returns a Dataset.\nnum_outputs: Total number of outputs expected from this Dataset.\nbreak_point: Break point. Optional. Defaults to num_outputs/2.\nsparse_tensors: Whether dataset is built from SparseTensor(s).\nverify_exhausted: Whether to verify that the iterator has been exhausted\nafter producing `num_outputs` elements.\nassert_items_equal: Tests the output has the expected elements regardless\nof order.\n\nRaises:\nAssertionError if any test fails.", "source": "github-repos"}
22{"code": "class RandomInvert(BaseImagePreprocessingLayer):\n _USE_BASE_FACTOR = False\n _FACTOR_BOUNDS = (0, 1)\n\n def __init__(self, factor=1.0, value_range=(0, 255), seed=None, data_format=None, **kwargs):\n super().__init__(data_format=data_format, **kwargs)\n self._set_factor(factor)\n self.value_range = value_range\n self.seed = seed\n self.generator = self.backend.random.SeedGenerator(seed)\n\n def get_random_transformation(self, data, training=True, seed=None):\n if not training:\n return None\n if isinstance(data, dict):\n images = data['images']\n else:\n images = data\n seed = seed or self._get_seed_generator(self.backend._backend)\n images_shape = self.backend.shape(images)\n rank = len(images_shape)\n if rank == 3:\n batch_size = 1\n elif rank == 4:\n batch_size = images_shape[0]\n else:\n raise ValueError(f'Expected the input image to be rank 3 or 4. Received inputs.shape={images_shape}')\n invert_probability = self.backend.random.uniform(shape=(batch_size,), minval=self.factor[0], maxval=self.factor[1], seed=seed)\n random_threshold = self.backend.random.uniform(shape=(batch_size,), minval=0, maxval=1, seed=seed)\n apply_inversion = random_threshold < invert_probability\n return {'apply_inversion': apply_inversion}\n\n def transform_images(self, images, transformation, training=True):\n if training:\n images = self.backend.cast(images, self.compute_dtype)\n apply_inversion = transformation['apply_inversion']\n return self.backend.numpy.where(apply_inversion[:, None, None, None], self.value_range[1] - images, images)\n return images\n\n def transform_labels(self, labels, transformation, training=True):\n return labels\n\n def transform_bounding_boxes(self, bounding_boxes, transformation, training=True):\n return bounding_boxes\n\n def transform_segmentation_masks(self, segmentation_masks, transformation, training=True):\n return segmentation_masks\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def get_config(self):\n config = {'factor': self.factor, 'value_range': self.value_range, 'seed': self.seed}\n base_config = super().get_config()\n return {**base_config, **config}", "docstring": "Preprocessing layer for random inversion of image colors.\n\nThis layer randomly inverts the colors of input images with a specified\nprobability range. When applied, each image has a chance of having its\ncolors inverted, where the pixel values are transformed to their\ncomplementary values. Images that are not selected for inversion\nremain unchanged.\n\nArgs:\nfactor: A single float or a tuple of two floats.\n`factor` controls the probability of inverting the image colors.\nIf a tuple is provided, the value is sampled between the two values\nfor each image, where `factor[0]` is the minimum and `factor[1]` is\nthe maximum probability. If a single float is provided, a value\nbetween `0.0` and the provided float is sampled.\nDefaults to `(0, 1)`.\nvalue_range: a tuple or a list of two elements. The first value\nrepresents the lower bound for values in passed images, the second\nrepresents the upper bound. Images passed to the layer should have\nvalues within `value_range`. Defaults to `(0, 255)`.\nseed: Integer. Used to create a random seed.", "source": "github-repos"}
23{"code": "def scroll(self, x, y):\n assert isinstance(x, _INTTYPES), ('x must be an integer, got %s' % repr(x))\n assert isinstance(y, _INTTYPES), ('y must be an integer, got %s' % repr(x))\n\n def getSlide(x, length):\n 'get the parameters needed to scroll the console in the given\\n direction with x\\n returns (x, length, srcx)\\n '\n if (x > 0):\n srcx = 0\n length -= x\n elif (x < 0):\n srcx = abs(x)\n x = 0\n length -= srcx\n else:\n srcx = 0\n return (x, length, srcx)\n\n def getCover(x, length):\n 'return the (x, width) ranges of what is covered and uncovered'\n cover = (0, length)\n uncover = None\n if (x > 0):\n cover = (x, (length - x))\n uncover = (0, x)\n elif (x < 0):\n x = abs(x)\n cover = (0, (length - x))\n uncover = ((length - x), x)\n return (cover, uncover)\n (width, height) = self.get_size()\n if ((abs(x) >= width) or (abs(y) >= height)):\n return self.clear()\n (coverX, uncoverX) = getCover(x, width)\n (coverY, uncoverY) = getCover(y, height)\n (x, width, srcx) = getSlide(x, width)\n (y, height, srcy) = getSlide(y, height)\n self.blit(self, x, y, width, height, srcx, srcy)\n if uncoverX:\n self.draw_rect(uncoverX[0], coverY[0], uncoverX[1], coverY[1], 32, self._fg, self._bg)\n if uncoverY:\n self.draw_rect(coverX[0], uncoverY[0], coverX[1], uncoverY[1], 32, self._fg, self._bg)\n if (uncoverX and uncoverY):\n self.draw_rect(uncoverX[0], uncoverY[0], uncoverX[1], uncoverY[1], 32, self._fg, self._bg)", "docstring": "Scroll the contents of the console in the direction of x,y.\n\nUncovered areas will be cleared to the default background color.\nDoes not move the virutal cursor.\n\nArgs:\nx (int): Distance to scroll along the x-axis.\ny (int): Distance to scroll along the y-axis.\n\nReturns:\nIterator[Tuple[int, int]]: An iterator over the (x, y) coordinates\nof any tile uncovered after scrolling.\n\n.. seealso:: :any:`set_colors`", "source": "codesearchnet"}
24{"code": "def clean_decodes(ids, vocab_size, eos_id=1):\n ret = []\n for i in ids:\n if (i == eos_id):\n break\n if (i >= vocab_size):\n break\n ret.append(int(i))\n return ret", "docstring": "Stop at EOS or padding or OOV.\n\nArgs:\nids: a list of integers\nvocab_size: an integer\neos_id: EOS id\n\nReturns:\na list of integers", "source": "codesearchnet"}
25{"code": "def pivot_and_annotate(self, values, gpl, annotation_column, gpl_on='ID', gsm_on='ID_REF'):\n if isinstance(gpl, GPL):\n annotation_table = gpl.table\n elif isinstance(gpl, DataFrame):\n annotation_table = gpl\n else:\n raise TypeError('gpl should be a GPL object or a pandas.DataFrame')\n pivoted_samples = self.pivot_samples(values=values, index=gsm_on)\n ndf = pivoted_samples.reset_index().merge(annotation_table[[gpl_on, annotation_column]], left_on=gsm_on, right_on=gpl_on).set_index(gsm_on)\n del ndf[gpl_on]\n ndf.columns.name = 'name'\n return ndf", "docstring": "Annotate GSM with provided GPL.\n\nArgs:\nvalues (:obj:`str`): Column to use as values eg. \"VALUES\"\ngpl (:obj:`pandas.DataFrame` or :obj:`GEOparse.GPL`): A Platform or\nDataFrame to annotate with.\nannotation_column (:obj:`str`): Column in table for annotation.\ngpl_on (:obj:`str`, optional): Use this column in GPL to merge.\nDefaults to \"ID\".\ngsm_on (:obj:`str`, optional): Use this column in GSM to merge.\nDefaults to \"ID_REF\".\n\nReturns:\npandas.DataFrame: Pivoted and annotated table of results", "source": "codesearchnet"}
26{"code": "def __init__(self, num_packs=1):\n if num_packs < 0:\n raise ValueError('NCCL all-reduce requires num_packs >= 0, but {} is specified'.format(num_packs))\n super(NcclAllReduce, self).__init__(all_reduce_alg='nccl', num_packs=num_packs)", "docstring": "Initializes the object.\n\nArgs:\nnum_packs: a non-negative integer. The number of packs to split values\ninto. If zero, no packing will be done.\n\nRaises:\nValueError: if `num_packs` is negative.", "source": "github-repos"}
27{"code": "def _create_initial_state(self, initial_ids, initial_cache):\n \n \n cur_index = tf.constant(0)\n\n \n alive_seq = _expand_to_beam_size(initial_ids, self.beam_size)\n alive_seq = tf.expand_dims(alive_seq, axis=2)\n\n \n \n initial_log_probs = tf.constant(\n [[0.] + [-float(\"inf\")] * (self.beam_size - 1)])\n alive_log_probs = tf.tile(initial_log_probs, [self.batch_size, 1])\n\n \n \n alive_cache = nest.map_structure(\n lambda t: _expand_to_beam_size(t, self.beam_size), initial_cache)\n\n \n finished_seq = tf.zeros(tf.shape(alive_seq), tf.int32)\n\n \n finished_scores = tf.ones([self.batch_size, self.beam_size]) * -INF\n\n \n finished_flags = tf.zeros([self.batch_size, self.beam_size], tf.bool)\n\n \n state = {\n _StateKeys.CUR_INDEX: cur_index,\n _StateKeys.ALIVE_SEQ: alive_seq,\n _StateKeys.ALIVE_LOG_PROBS: alive_log_probs,\n _StateKeys.ALIVE_CACHE: alive_cache,\n _StateKeys.FINISHED_SEQ: finished_seq,\n _StateKeys.FINISHED_SCORES: finished_scores,\n _StateKeys.FINISHED_FLAGS: finished_flags\n }\n\n \n \n \n \n \n state_shape_invariants = {\n _StateKeys.CUR_INDEX: tf.TensorShape([]),\n _StateKeys.ALIVE_SEQ: tf.TensorShape([None, self.beam_size, None]),\n _StateKeys.ALIVE_LOG_PROBS: tf.TensorShape([None, self.beam_size]),\n _StateKeys.ALIVE_CACHE: nest.map_structure(\n _get_shape_keep_last_dim, alive_cache),\n _StateKeys.FINISHED_SEQ: tf.TensorShape([None, self.beam_size, None]),\n _StateKeys.FINISHED_SCORES: tf.TensorShape([None, self.beam_size]),\n _StateKeys.FINISHED_FLAGS: tf.TensorShape([None, self.beam_size])\n }\n\n return state, state_shape_invariants", "docstring": "Return initial state dictionary and its shape invariants.\n\nArgs:\ninitial_ids: initial ids to pass into the symbols_to_logits_fn.\nint tensor with shape [batch_size, 1]\ninitial_cache: dictionary storing values to be passed into the\nsymbols_to_logits_fn.\n\nReturns:\nstate and shape invariant dictionaries with keys from _StateKeys", "source": "juraj-google-style"}
28{"code": "def variables(self):\n current_graph = ops.get_default_graph()\n\n def _from_current_graph(variable):\n if variable._in_graph_mode:\n return variable.op.graph is current_graph\n else:\n return variable._graph_key == current_graph._graph_key\n optimizer_variables = [v for v in self._non_slot_variables() if _from_current_graph(v)]\n for _, variable_dict in self._slots.items():\n for _, slot_for_variable in variable_dict.items():\n if _from_current_graph(slot_for_variable):\n optimizer_variables.append(slot_for_variable)\n return sorted(optimizer_variables, key=lambda v: v.name)", "docstring": "A list of variables which encode the current state of `Optimizer`.\n\nIncludes slot variables and additional global variables created by the\noptimizer in the current default graph.\n\nReturns:\nA list of variables.", "source": "github-repos"}
29{"code": "def _get_bond_data(line):\n line = line.split()\n length = float(line[2])\n sites = line[0].replace('/', '-').split('-')\n site_indices = tuple(((int(ind) - 1) for ind in sites[1:4:2]))\n species = tuple((re.split('\\\\d+', spec)[0] for spec in sites[0:3:2]))\n label = ('%s%d-%s%d' % (species[0], (site_indices[0] + 1), species[1], (site_indices[1] + 1)))\n return (label, length, site_indices)", "docstring": "Subroutine to extract bond label, site indices, and length from\na COPL header line. The site indices are zero-based, so they\ncan be easily used with a Structure object.\n\nExample header line: Fe-1/Fe-1-tr(-1,-1,-1) : 2.482 Ang.\n\nArgs:\nline: line in the COHPCAR header describing the bond.\n\nReturns:\nThe bond label, the bond length and a tuple of the site\nindices.", "source": "codesearchnet"}
30{"code": "def get_dns_zone_ids(env='dev', facing='internal'):\n client = boto3.Session(profile_name=env).client('route53')\n zones = client.list_hosted_zones_by_name(DNSName='.'.join([env, DOMAIN]))\n zone_ids = []\n for zone in zones['HostedZones']:\n LOG.debug('Found Hosted Zone: %s', zone)\n if ((facing == 'external') or zone['Config']['PrivateZone']):\n LOG.info('Using %(Id)s for \"%(Name)s\", %(Config)s', zone)\n zone_ids.append(zone['Id'])\n LOG.debug('Zone IDs: %s', zone_ids)\n return zone_ids", "docstring": "Get Route 53 Hosted Zone IDs for _env_.\n\nArgs:\nenv (str): Deployment environment.\nfacing (str): Type of ELB, external or internal.\n\nReturns:\nlist: Hosted Zone IDs for _env_. Only *PrivateZone* when _facing_ is\ninternal.", "source": "codesearchnet"}
31{"code": "def _mutation(candidate, rate=0.1):\n sample_index = np.random.choice(len(candidate))\n sample = candidate[sample_index]\n idx_list = []\n for i in range(int(max((len(sample) * rate), 1))):\n idx = np.random.choice(len(sample))\n idx_list.append(idx)\n field = sample[idx]\n field[np.argmax(field)] = 0\n bit = np.random.choice(field.shape[0])\n field[bit] = 1\n logger.info((LOGGING_PREFIX + 'Perform mutation on %sth at index=%s'), sample_index, str(idx_list))\n return sample", "docstring": "Perform mutation action to candidates.\n\nFor example, randomly change 10% of original sample\n\nArgs:\ncandidate: List of candidate genes (encodings).\nrate: Percentage of mutation bits\n\nExamples:\n>>> # Genes that represent 3 parameters\n>>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0]])\n>>> new_gene = _mutation([gene1])\n>>> # new_gene could be the gene1 with the 3rd parameter changed\n>>> # new_gene[0] = gene1[0]\n>>> # new_gene[1] = gene1[1]\n>>> # new_gene[2] = [0, 1] != gene1[2]\n\nReturns:\nNew gene (encoding)", "source": "codesearchnet"}
32{"code": "def build_listen(self, listen_node):\n \n proxy_name = listen_node.listen_header.proxy_name.text\n service_address_node = listen_node.listen_header.service_address\n\n \n config_block_lines = self.__build_config_block(\n listen_node.config_block)\n\n \n host, port = '', ''\n if isinstance(service_address_node, pegnode.ServiceAddress):\n host = service_address_node.host.text\n port = service_address_node.port.text\n else:\n \n \n for line in config_block_lines:\n if isinstance(line, config.Bind):\n host, port = line.host, line.port\n break\n else:\n raise Exception(\n 'Not specify host and port in `listen` definition')\n return config.Listen(\n name=proxy_name, host=host, port=port,\n config_block=config_block_lines)", "docstring": "parse `listen` sections, and return a config.Listen\n\nArgs:\nlisten_node (TreeNode): Description\n\nReturns:\nconfig.Listen: an object", "source": "juraj-google-style"}
33{"code": "def parent_index(self, relations=None):\n g = None\n if (relations is None):\n g = self.get_graph()\n else:\n g = self.get_filtered_graph(relations)\n l = []\n for n in g:\n l.append(([n] + list(g.predecessors(n))))\n return l", "docstring": "Returns a mapping of nodes to all direct parents\n\nArguments\n---------\nrelations : list[str]\nlist of relations used to filter\n\nReturns:\nlist\nlist of lists [[CLASS_1, PARENT_1,1, ..., PARENT_1,N], [CLASS_2, PARENT_2,1, PARENT_2,2, ... ] ... ]", "source": "codesearchnet"}
34{"code": "def remove(text, exclude):\n exclude = ''.join((str(symbol) for symbol in exclude))\n return text.translate(str.maketrans('', '', exclude))", "docstring": "Remove ``exclude`` symbols from ``text``.\n\nExample:\n>>> remove(\"example text\", string.whitespace)\n'exampletext'\n\nArgs:\ntext (str): The text to modify\nexclude (iterable): The symbols to exclude\n\nReturns:\n``text`` with ``exclude`` symbols removed", "source": "codesearchnet"}
35{"code": "def _ParseEntryArrayObject(self, file_object, file_offset):\n entry_array_object_map = self._GetDataTypeMap('systemd_journal_entry_array_object')\n try:\n (entry_array_object, _) = self._ReadStructureFromFileObject(file_object, file_offset, entry_array_object_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to parse entry array object at offset: 0x{0:08x} with error: {1!s}'.format(file_offset, exception))\n if (entry_array_object.object_type != self._OBJECT_TYPE_ENTRY_ARRAY):\n raise errors.ParseError('Unsupported object type: {0:d}.'.format(entry_array_object.object_type))\n if (entry_array_object.object_flags != 0):\n raise errors.ParseError('Unsupported object flags: 0x{0:02x}.'.format(entry_array_object.object_flags))\n return entry_array_object", "docstring": "Parses an entry array object.\n\nArgs:\nfile_object (dfvfs.FileIO): a file-like object.\nfile_offset (int): offset of the entry array object relative to the start\nof the file-like object.\n\nReturns:\nsystemd_journal_entry_array_object: entry array object.\n\nRaises:\nParseError: if the entry array object cannot be parsed.", "source": "codesearchnet"}
36{"code": "def merge_tags(left, right, factory=Tags):\n if isinstance(left, Mapping):\n tags = dict(left)\n elif hasattr(left, 'tags'):\n tags = _tags_to_dict(left.tags)\n else:\n tags = _tags_to_dict(left)\n if isinstance(right, Mapping):\n tags.update(right)\n elif hasattr(left, 'tags'):\n tags.update(_tags_to_dict(right.tags))\n else:\n tags.update(_tags_to_dict(right))\n return factory(**tags)", "docstring": "Merge two sets of tags into a new troposphere object\n\nArgs:\nleft (Union[dict, troposphere.Tags]): dictionary or Tags object to be\nmerged with lower priority\nright (Union[dict, troposphere.Tags]): dictionary or Tags object to be\nmerged with higher priority\nfactory (type): Type of object to create. Defaults to the troposphere\nTags class.", "source": "codesearchnet"}
37{"code": "def write_uint32(self, value, little_endian=True):\n if little_endian:\n endian = '<'\n else:\n endian = '>'\n return self.pack(('%sI' % endian), value)", "docstring": "Pack the value as an unsigned integer and write 4 bytes to the stream.\n\nArgs:\nvalue:\nlittle_endian (bool): specify the endianness. (Default) Little endian.\n\nReturns:\nint: the number of bytes written.", "source": "codesearchnet"}
38{"code": "def _ParseItems(self, parser_mediator, msiecf_file):\n \n format_version = msiecf_file.format_version\n\n decode_error = False\n cache_directories = []\n for cache_directory_name in iter(msiecf_file.cache_directories):\n try:\n cache_directory_name = cache_directory_name.decode('ascii')\n except UnicodeDecodeError:\n decode_error = True\n cache_directory_name = cache_directory_name.decode(\n 'ascii', errors='replace')\n\n cache_directories.append(cache_directory_name)\n\n if decode_error:\n parser_mediator.ProduceExtractionWarning((\n 'unable to decode cache directory names. Characters that cannot '\n 'be decoded will be replaced with \"?\" or \"\\\\ufffd\".'))\n\n for item_index in range(0, msiecf_file.number_of_items):\n try:\n msiecf_item = msiecf_file.get_item(item_index)\n if isinstance(msiecf_item, pymsiecf.leak):\n self._ParseLeak(parser_mediator, cache_directories, msiecf_item)\n\n elif isinstance(msiecf_item, pymsiecf.redirected):\n self._ParseRedirected(parser_mediator, msiecf_item)\n\n elif isinstance(msiecf_item, pymsiecf.url):\n self._ParseUrl(\n parser_mediator, format_version, cache_directories, msiecf_item)\n\n except IOError as exception:\n parser_mediator.ProduceExtractionWarning(\n 'Unable to parse item: {0:d} with error: {1!s}'.format(\n item_index, exception))\n\n for item_index in range(0, msiecf_file.number_of_recovered_items):\n try:\n msiecf_item = msiecf_file.get_recovered_item(item_index)\n if isinstance(msiecf_item, pymsiecf.leak):\n self._ParseLeak(\n parser_mediator, cache_directories, msiecf_item, recovered=True)\n\n elif isinstance(msiecf_item, pymsiecf.redirected):\n self._ParseRedirected(parser_mediator, msiecf_item, recovered=True)\n\n elif isinstance(msiecf_item, pymsiecf.url):\n self._ParseUrl(\n parser_mediator, format_version, cache_directories, msiecf_item,\n recovered=True)\n\n except IOError as exception:\n parser_mediator.ProduceExtractionWarning(\n 'Unable to parse recovered item: {0:d} with error: {1!s}'.format(\n item_index, exception))", "docstring": "Parses a MSIE Cache File (MSIECF) items.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nmsiecf_file (pymsiecf.file): MSIECF file.", "source": "juraj-google-style"}
39{"code": "def trace_cpu(self, graph, tensor_fetches, op_fetches=None):\n if isinstance(graph, func_graph.FuncGraph) or isinstance(graph, function._FuncGraph):\n logging.warning('Tensor Tracer is not supported for tracing FuncGraphs. Ignoring tracing.')\n return tensor_fetches\n if graph in TensorTracer._traced_graphs:\n logging.warning('Graph is already rewritten with tensor tracer, ignoring multiple calls.')\n return tensor_fetches\n else:\n TensorTracer._traced_graphs.add(graph)\n self._parameters = tensor_tracer_flags.TTParameters()\n self._tt_config.device_type = _DEVICE_TYPE_CPU\n self._tt_config.num_replicas = 1\n self._tt_config.num_replicas_per_host = 1\n self._tt_config.num_hosts = 1\n self._replica_id = 0\n if self._parameters.graph_dump_path:\n graph_io.write_graph(graph, self._parameters.graph_dump_path, 'graph_before_tt.pbtxt')\n with graph.as_default():\n tensor_fetches = self._trace_execution(graph, tensor_fetches, op_fetches, on_tpu=False)\n if self._parameters.graph_dump_path:\n graph_io.write_graph(graph, self._parameters.graph_dump_path, 'graph_after_tt.pbtxt')\n return tensor_fetches", "docstring": "Traces the tensors generated by CPU Ops in a TF graph.\n\nArgs:\ngraph: the graph of Ops executed on the CPU.\ntensor_fetches: a (list,tuple,or a single object) of tensor fetches\nreturned by model_fn given to session.run. Function must be provided\nwith as least one tensor to fetch.\nop_fetches: A list of op fetches returned by model_fn given to\nsession.run. op_fetches and tensor_fetches are used to determine the\nnodes that will be executed. Can be None.\n\nReturns:\ntensor_fetches: an exact copy of tensor_fetches that has additional\ndependencies.", "source": "github-repos"}
40{"code": "def fitness(self, width, height): \n \n assert(width > 0 and height > 0)\n \n rect, max_rect = self._select_position(width, height)\n if rect is None:\n return None\n\n \n return self._rect_fitness(max_rect, rect.width, rect.height)", "docstring": "Metric used to rate how much space is wasted if a rectangle is placed.\nReturns a value greater or equal to zero, the smaller the value the more\n'fit' is the rectangle. If the rectangle can't be placed, returns None.\n\nArguments:\nwidth (int, float): Rectangle width\nheight (int, float): Rectangle height\n\nReturns:\nint, float: Rectangle fitness\nNone: Rectangle can't be placed", "source": "juraj-google-style"}
41{"code": "def _create_events_writer(self, directory):\n \n total_size = 0\n events_files = self._fetch_events_files_on_disk()\n for file_name in events_files:\n file_path = os.path.join(self._events_directory, file_name)\n total_size += tf.io.gfile.stat(file_path).length\n\n if total_size >= self.total_file_size_cap_bytes:\n \n \n for file_name in events_files:\n if total_size < self.total_file_size_cap_bytes:\n break\n\n file_path = os.path.join(self._events_directory, file_name)\n file_size = tf.io.gfile.stat(file_path).length\n try:\n tf.io.gfile.remove(file_path)\n total_size -= file_size\n logger.info(\n \"Deleted %s because events files take up over %d bytes\",\n file_path, self.total_file_size_cap_bytes)\n except IOError as err:\n logger.error(\"Deleting %s failed: %s\", file_path, err)\n\n \n self._events_file_count += 1\n file_path = \"%s.%d.%d\" % (\n os.path.join(directory, DEBUGGER_EVENTS_FILE_STARTING_TEXT),\n time.time(), self._events_file_count)\n logger.info(\"Creating events file %s\", file_path)\n return pywrap_tensorflow.EventsWriter(tf.compat.as_bytes(file_path))", "docstring": "Creates a new events writer.\n\nArgs:\ndirectory: The directory in which to write files containing events.\n\nReturns:\nA new events writer, which corresponds to a new events file.", "source": "juraj-google-style"}
42{"code": "def iter_cast(inputs, dst_type, return_type=None):\n \n if not isinstance(inputs, collections_abc.Iterable):\n raise TypeError('inputs must be an iterable object')\n if not isinstance(dst_type, type):\n raise TypeError('\"dst_type\" must be a valid type')\n\n out_iterable = six.moves.map(dst_type, inputs)\n\n if return_type is None:\n return out_iterable\n else:\n return return_type(out_iterable)", "docstring": "Cast elements of an iterable object into some type.\n\nArgs:\ninputs (Iterable): The input object.\ndst_type (type): Destination type.\nreturn_type (type, optional): If specified, the output object will be\nconverted to this type, otherwise an iterator.\n\nReturns:\niterator or specified type: The converted object.", "source": "juraj-google-style"}
43{"code": "def __init__(\n self, password=None, parent=None, recovery_password=None,\n startup_key=None, **kwargs):\n \n if not parent:\n raise ValueError('Missing parent value.')\n\n super(BDEPathSpec, self).__init__(parent=parent, **kwargs)\n self.password = password\n self.recovery_password = recovery_password\n self.startup_key = startup_key", "docstring": "Initializes a path specification.\n\nNote that the BDE path specification must have a parent.\n\nArgs:\npassword (Optional[str]): password.\nparent (Optional[PathSpec]): parent path specification.\nrecovery_password (Optional[str]): recovery password.\nstartup_key (Optional[str]): name of the startup key file.\n\nRaises:\nValueError: when parent is not set.", "source": "juraj-google-style"}
44{"code": "def install_antivirus(version=None, latest=False, synch=False, skip_commit=False):\n if ((not version) and (latest is False)):\n raise CommandExecutionError('Version option must not be none.')\n if (synch is True):\n s = 'yes'\n else:\n s = 'no'\n if (skip_commit is True):\n c = 'yes'\n else:\n c = 'no'\n if (latest is True):\n query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install><commit>{0}</commit><sync-to-peer>{1}</sync-to-peer><version>latest</version></install></upgrade></anti-virus></request>'.format(c, s)}\n else:\n query = {'type': 'op', 'cmd': '<request><anti-virus><upgrade><install><commit>{0}</commit><sync-to-peer>{1}</sync-to-peer><version>{2}</version></install></upgrade></anti-virus></request>'.format(c, s, version)}\n return _get_job_results(query)", "docstring": "Install anti-virus packages.\n\nArgs:\nversion(str): The version of the PANOS file to install.\n\nlatest(bool): If true, the latest anti-virus file will be installed.\nThe specified version option will be ignored.\n\nsynch(bool): If true, the anti-virus will synch to the peer unit.\n\nskip_commit(bool): If true, the install will skip committing to the device.\n\nCLI Example:\n\n.. code-block:: bash\n\nsalt '*' panos.install_antivirus 8.0.0", "source": "codesearchnet"}
45{"code": "def answer(self, c, details):\n \n if c in [Settings.SUCCESS, Settings.CREATED, Settings.ACCEPTED]:\n return details\n elif c == Settings.BAD_REQUEST:\n raise ErrAtlasBadRequest(c, details)\n elif c == Settings.UNAUTHORIZED:\n raise ErrAtlasUnauthorized(c, details)\n elif c == Settings.FORBIDDEN:\n raise ErrAtlasForbidden(c, details)\n elif c == Settings.NOTFOUND:\n raise ErrAtlasNotFound(c, details)\n elif c == Settings.METHOD_NOT_ALLOWED:\n raise ErrAtlasMethodNotAllowed(c, details)\n elif c == Settings.CONFLICT:\n raise ErrAtlasConflict(c, details)\n else:\n \n raise ErrAtlasServerErrors(c, details)", "docstring": "Answer will provide all necessary feedback for the caller\n\nArgs:\nc (int): HTTP Code\ndetails (dict): Response payload\n\nReturns:\ndict: Response payload\n\nRaises:\nErrAtlasBadRequest\nErrAtlasUnauthorized\nErrAtlasForbidden\nErrAtlasNotFound\nErrAtlasMethodNotAllowed\nErrAtlasConflict\nErrAtlasServerErrors", "source": "juraj-google-style"}
46{"code": "def create_cert_binding(name, site, hostheader='', ipaddress='*', port=443, sslflags=0):\n name = six.text_type(name).upper()\n binding_info = _get_binding_info(hostheader, ipaddress, port)\n if (_iisVersion() < 8):\n binding_info = (binding_info.rpartition(':')[0] + ':')\n binding_path = 'IIS:\\\\SslBindings\\\\{0}'.format(binding_info.replace(':', '!'))\n if (sslflags not in _VALID_SSL_FLAGS):\n message = \"Invalid sslflags '{0}' specified. Valid sslflags range: {1}..{2}\".format(sslflags, _VALID_SSL_FLAGS[0], _VALID_SSL_FLAGS[(- 1)])\n raise SaltInvocationError(message)\n current_bindings = list_bindings(site)\n if (binding_info not in current_bindings):\n log.error('Binding not present: %s', binding_info)\n return False\n current_name = None\n for current_binding in current_bindings:\n if (binding_info == current_binding):\n current_name = current_bindings[current_binding]['certificatehash']\n log.debug('Current certificate thumbprint: %s', current_name)\n log.debug('New certificate thumbprint: %s', name)\n if (name == current_name):\n log.debug('Certificate already present for binding: %s', name)\n return True\n certs = _list_certs()\n if (name not in certs):\n log.error('Certificate not present: %s', name)\n return False\n if (_iisVersion() < 8):\n iis7path = binding_path.replace('\\\\*!', '\\\\0.0.0.0!')\n if iis7path.endswith('!'):\n iis7path = iis7path[:(- 1)]\n ps_cmd = ['New-Item', '-Path', \"'{0}'\".format(iis7path), '-Thumbprint', \"'{0}'\".format(name)]\n else:\n ps_cmd = ['New-Item', '-Path', \"'{0}'\".format(binding_path), '-Thumbprint', \"'{0}'\".format(name), '-SSLFlags', '{0}'.format(sslflags)]\n cmd_ret = _srvmgr(ps_cmd)\n if (cmd_ret['retcode'] != 0):\n msg = 'Unable to create certificate binding: {0}\\nError: {1}'.format(name, cmd_ret['stderr'])\n raise CommandExecutionError(msg)\n new_cert_bindings = list_cert_bindings(site)\n if (binding_info not in new_cert_bindings):\n log.error('Binding not present: %s', binding_info)\n return False\n if (name == new_cert_bindings[binding_info]['certificatehash']):\n log.debug('Certificate binding created successfully: %s', name)\n return True\n log.error('Unable to create certificate binding: %s', name)\n return False", "docstring": "Assign a certificate to an IIS Web Binding.\n\n.. versionadded:: 2016.11.0\n\n.. note::\n\nThe web binding that the certificate is being assigned to must already\nexist.\n\nArgs:\nname (str): The thumbprint of the certificate.\nsite (str): The IIS site name.\nhostheader (str): The host header of the binding.\nipaddress (str): The IP address of the binding.\nport (int): The TCP port of the binding.\nsslflags (int): Flags representing certificate type and certificate storage of the binding.\n\nReturns:\nbool: True if successful, otherwise False\n\nCLI Example:\n\n.. code-block:: bash\n\nsalt '*' win_iis.create_cert_binding name='AAA000' site='site0' hostheader='example.com' ipaddress='*' port='443'", "source": "codesearchnet"}
47{"code": "def _Stat(self, path, ext_attrs=False):\n \n \n local_path = client_utils.CanonicalPathToLocalPath(path)\n result = client_utils.StatEntryFromPath(\n local_path, self.pathspec, ext_attrs=ext_attrs)\n\n \n try:\n result.symlink = utils.SmartUnicode(os.readlink(local_path))\n except (OSError, AttributeError):\n pass\n\n return result", "docstring": "Returns stat information of a specific path.\n\nArgs:\npath: A unicode string containing the path.\next_attrs: Whether the call should also collect extended attributes.\n\nReturns:\na StatResponse proto\n\nRaises:\nIOError when call to os.stat() fails", "source": "juraj-google-style"}
48{"code": "def _context_callbacks(app, key, original_context=_CONTEXT_MISSING):\n\n def _get_context(dummy_app):\n 'Set the context proxy so that it points to a specific context.\\n '\n _CONTEXT_LOCALS.context = _CONTEXT_LOCALS(key)\n\n def _clear_context(dummy_app):\n 'Remove the context proxy that points to a specific context and\\n restore the original context, if there was one.\\n '\n try:\n del _CONTEXT_LOCALS.context\n except AttributeError:\n pass\n if (original_context is not _CONTEXT_MISSING):\n setattr(_CONTEXT_LOCALS, key, original_context)\n _CONTEXT_CALLBACK_MAP[app] = (_get_context, _clear_context)\n appcontext_pushed.connect(_get_context, app)\n appcontext_popped.connect(_clear_context, app)\n return (_get_context, _clear_context)", "docstring": "Register the callbacks we need to properly pop and push the\napp-local context for a component.\n\nArgs:\napp (flask.Flask): The app who this context belongs to. This is the\nonly sender our Blinker signal will listen to.\nkey (str): The key on ``_CONTEXT_LOCALS`` that this app's context\nlistens to.\n\nKwargs:\noriginal_context (dict): The original context present whenever\nthese callbacks were registered. We will restore the context to\nthis value whenever the app context gets popped.\n\nReturns:\n(function, function): A two-element tuple of the dynamic functions\nwe generated as appcontext callbacks. The first element is the\ncallback for ``appcontext_pushed`` (i.e., get and store the\ncurrent context) and the second element is the callback for\n``appcontext_popped`` (i.e., restore the current context to\nto it's original value).", "source": "codesearchnet"}
49{"code": "def parse_variant(store, institute_obj, case_obj, variant_obj, update=False, genome_build='37',\n get_compounds = True):\n \n has_changed = False\n compounds = variant_obj.get('compounds', [])\n if compounds and get_compounds:\n \n \n if 'not_loaded' not in compounds[0]:\n new_compounds = store.update_variant_compounds(variant_obj)\n variant_obj['compounds'] = new_compounds\n has_changed = True\n\n \n variant_obj['compounds'] = sorted(variant_obj['compounds'],\n key=lambda compound: -compound['combined_score'])\n\n \n variant_genes = variant_obj.get('genes')\n if variant_genes is not None:\n for gene_obj in variant_genes:\n \n if not gene_obj['hgnc_id']:\n continue\n \n if gene_obj.get('hgnc_symbol') is None:\n hgnc_gene = store.hgnc_gene(gene_obj['hgnc_id'], build=genome_build)\n if not hgnc_gene:\n continue\n has_changed = True\n gene_obj['hgnc_symbol'] = hgnc_gene['hgnc_symbol']\n\n \n \n if update and has_changed:\n variant_obj = store.update_variant(variant_obj)\n\n variant_obj['comments'] = store.events(institute_obj, case=case_obj,\n variant_id=variant_obj['variant_id'], comments=True)\n\n if variant_genes:\n variant_obj.update(get_predictions(variant_genes))\n if variant_obj.get('category') == 'cancer':\n variant_obj.update(get_variant_info(variant_genes))\n\n for compound_obj in compounds:\n compound_obj.update(get_predictions(compound_obj.get('genes', [])))\n\n if isinstance(variant_obj.get('acmg_classification'), int):\n acmg_code = ACMG_MAP[variant_obj['acmg_classification']]\n variant_obj['acmg_classification'] = ACMG_COMPLETE_MAP[acmg_code]\n\n\n \n variant_length = variant_obj.get('length')\n variant_obj['length'] = {100000000000: 'inf', -1: 'n.d.'}.get(variant_length, variant_length)\n if not 'end_chrom' in variant_obj:\n variant_obj['end_chrom'] = variant_obj['chromosome']\n\n return variant_obj", "docstring": "Parse information about variants.\n\n- Adds information about compounds\n- Updates the information about compounds if necessary and 'update=True'\n\nArgs:\nstore(scout.adapter.MongoAdapter)\ninstitute_obj(scout.models.Institute)\ncase_obj(scout.models.Case)\nvariant_obj(scout.models.Variant)\nupdate(bool): If variant should be updated in database\ngenome_build(str)", "source": "juraj-google-style"}
50{"code": "def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):\n split_image = images_kwargs.get('split_image', None) or self.split_image\n max_image_size = images_kwargs.get('max_image_size', None) or self.max_image_size\n resized_height, resized_width = select_best_resolution((height, width), self.split_resolutions)\n num_patches = 1 if not split_image else resized_height \n return num_patches", "docstring": "A utility that returns number of image patches for a given image size.\n\nArgs:\nheight (`int`):\nHeight of the input image.\nwidth (`int`):\nWidth of the input image.\nimages_kwargs (`dict`, *optional*)\nAny kwargs to override defaults of the image processor.\nReturns:\n`int`: Number of patches per image.", "source": "github-repos"}
51{"code": "def _get_weights(max_length):\n weights = [1]\n for i in range(1, max_length):\n weights.append(((weights[(i - 1)] * len(_ALPHABET)) + 1))\n weights.reverse()\n return weights", "docstring": "Get weights for each offset in str of certain max length.\n\nArgs:\nmax_length: max length of the strings.\n\nReturns:\nA list of ints as weights.\n\nExample:\nIf max_length is 2 and alphabet is \"ab\", then we have order \"\", \"a\", \"aa\",\n\"ab\", \"b\", \"ba\", \"bb\". So the weight for the first char is 3.", "source": "codesearchnet"}
52{"code": "def rmdir(path, dir_fd=None):\n \n system = get_instance(path)\n system.remove(system.ensure_dir_path(path))", "docstring": "Remove a directory.\n\nEquivalent to \"os.rmdir\".\n\nArgs:\npath (path-like object): Path or URL.\ndir_fd: directory descriptors;\nsee the os.rmdir() description for how it is interpreted.\nNot supported on cloud storage objects.", "source": "juraj-google-style"}
53{"code": "def update_state(self, *args, **kwargs):\n raise NotImplementedError('Must be implemented in subclasses.')", "docstring": "Accumulates statistics for the metric.\n\nNote: This function is executed as a graph function in graph mode.\nThis means:\na) Operations on the same resource are executed in textual order.\nThis should make it easier to do things like add the updated\nvalue of a variable to another, for example.\nb) You don't need to worry about collecting the update ops to execute.\nAll update ops added to the graph by this function will be executed.\nAs a result, code should generally work the same way with graph or\neager execution.\n\nArgs:\n*args:\n**kwargs: A mini-batch of inputs to the Metric.", "source": "github-repos"}
54{"code": "def plot(self, figure_list):\n \n \n if not self.data:\n return\n\n \n if not self.is_running:\n self._plot_refresh = True\n\n axes_list = self.get_axes_layout(figure_list)\n if self._plot_refresh is True:\n self._plot(axes_list)\n self._plot_refresh = False\n for figure in figure_list:\n if figure.axes:\n figure.set_tight_layout(True)\n else:\n self._update_plot(axes_list)", "docstring": "plots the data contained in self.data, which should be a dictionary or a deque of dictionaries\nfor the latter use the last entry\nArgs:\nfigure_list: list of figure objects that are passed to self.get_axes_layout to get axis objects for plotting", "source": "juraj-google-style"}
55{"code": "def allzeros(msg):\n d = hex2bin(data(msg))\n if (bin2int(d) > 0):\n return False\n else:\n return True", "docstring": "check if the data bits are all zeros\n\nArgs:\nmsg (String): 28 bytes hexadecimal message string\n\nReturns:\nbool: True or False", "source": "codesearchnet"}
56{"code": "def _config_parser_to_defaultdict(config_parser):\n config = defaultdict(defaultdict)\n for (section, section_content) in config_parser.items():\n if (section != 'DEFAULT'):\n for (option, option_value) in section_content.items():\n config[section][option] = option_value\n return config", "docstring": "Convert a ConfigParser to a defaultdict.\n\nArgs:\nconfig_parser (ConfigParser): A ConfigParser.", "source": "codesearchnet"}
57{"code": "def _save_sorted_results(self, run_stats, scores, image_count, filename):\n \n with open(filename, 'w') as f:\n writer = csv.writer(f)\n writer.writerow(['SubmissionID', 'ExternalTeamId', 'Score',\n 'MedianTime', 'ImageCount'])\n\n def get_second(x):\n \n return x[1]\n for s_id, score in sorted(iteritems(scores),\n key=get_second, reverse=True):\n external_id = self.submissions.get_external_id(s_id)\n stat = run_stats.get(\n s_id, collections.defaultdict(lambda: float('NaN')))\n writer.writerow([s_id, external_id, score,\n stat['median_eval_time'],\n image_count[s_id]])", "docstring": "Saves sorted (by score) results of the evaluation.\n\nArgs:\nrun_stats: dictionary with runtime statistics for submissions,\ncan be generated by WorkPiecesBase.compute_work_statistics\nscores: dictionary mapping submission ids to scores\nimage_count: dictionary with number of images processed by submission\nfilename: output filename", "source": "juraj-google-style"}
58{"code": "def scale(self, scalar, ignored_terms=None):\n \n\n if ignored_terms is None:\n ignored_terms = set()\n else:\n ignored_terms = {asfrozenset(term) for term in ignored_terms}\n\n for term in self:\n if term not in ignored_terms:\n self[term] *= scalar", "docstring": "Multiply the polynomial by the given scalar.\n\nArgs:\nscalar (number):\nValue to multiply the polynomial by.\n\nignored_terms (iterable, optional):\nBiases associated with these terms are not scaled.", "source": "juraj-google-style"}
59{"code": "def build_transaction(self, inputs, outputs):\n \n \n inputs = [{'output': '{}:{}'.format(input['txid'], input['vout']),\n 'value': input['amount']} for input in inputs]\n tx = bitcoin.mktx(inputs, outputs)\n return tx", "docstring": "Thin wrapper around ``bitcoin.mktx(inputs, outputs)``\n\nArgs:\ninputs (dict): inputs in the form of\n``{'output': 'txid:vout', 'value': amount in satoshi}``\noutputs (dict): outputs in the form of\n``{'address': to_address, 'value': amount in satoshi}``\nReturns:\ntransaction", "source": "juraj-google-style"}
60{"code": "def create_epub(self, output_directory, epub_name=None):\n\n def createTOCs_and_ContentOPF():\n for (epub_file, name) in ((self.toc_html, 'toc.html'), (self.toc_ncx, 'toc.ncx'), (self.opf, 'content.opf')):\n epub_file.add_chapters(self.chapters)\n epub_file.write(os.path.join(self.OEBPS_DIR, name))\n\n def create_zip_archive(epub_name):\n try:\n assert (isinstance(epub_name, basestring) or (epub_name is None))\n except AssertionError:\n raise TypeError('epub_name must be string or None')\n if (epub_name is None):\n epub_name = self.title\n epub_name = ''.join([c for c in epub_name if (c.isalpha() or c.isdigit() or (c == ' '))]).rstrip()\n epub_name_with_path = os.path.join(output_directory, epub_name)\n try:\n os.remove(os.path.join(epub_name_with_path, '.zip'))\n except OSError:\n pass\n shutil.make_archive(epub_name_with_path, 'zip', self.EPUB_DIR)\n return (epub_name_with_path + '.zip')\n\n def turn_zip_into_epub(zip_archive):\n epub_full_name = (zip_archive.strip('.zip') + '.epub')\n try:\n os.remove(epub_full_name)\n except OSError:\n pass\n os.rename(zip_archive, epub_full_name)\n return epub_full_name\n createTOCs_and_ContentOPF()\n epub_path = turn_zip_into_epub(create_zip_archive(epub_name))\n return epub_path", "docstring": "Create an epub file from this object.\n\nArgs:\noutput_directory (str): Directory to output the epub file to\nepub_name (Option[str]): The file name of your epub. This should not contain\n.epub at the end. If this argument is not provided, defaults to the title of the epub.", "source": "codesearchnet"}
61{"code": "def render(self, mode='human'):\n if (mode == 'human'):\n if (self.viewer is None):\n from ._image_viewer import ImageViewer\n if (self.spec is None):\n caption = self._rom_path.split('/')[(- 1)]\n else:\n caption = self.spec.id\n self.viewer = ImageViewer(caption=caption, height=SCREEN_HEIGHT, width=SCREEN_WIDTH)\n self.viewer.show(self.screen)\n elif (mode == 'rgb_array'):\n return self.screen\n else:\n render_modes = [repr(x) for x in self.metadata['render.modes']]\n msg = 'valid render modes are: {}'.format(', '.join(render_modes))\n raise NotImplementedError(msg)", "docstring": "Render the environment.\n\nArgs:\nmode (str): the mode to render with:\n- human: render to the current display\n- rgb_array: Return an numpy.ndarray with shape (x, y, 3),\nrepresenting RGB values for an x-by-y pixel image\n\nReturns:\na numpy array if mode is 'rgb_array', None otherwise", "source": "codesearchnet"}
62{"code": "def VerifyStructure(self, parser_mediator, lines):\n try:\n structure = self._GDS_LINE.parseString(lines)\n except pyparsing.ParseException as exception:\n logger.debug('Not a Google Drive Sync log file: {0!s}'.format(exception))\n return False\n date_time = dfdatetime_time_elements.TimeElementsInMilliseconds()\n try:\n datetime_iso8601 = self._GetISO8601String(structure.date_time)\n date_time.CopyFromStringISO8601(datetime_iso8601)\n except ValueError as exception:\n logger.debug('Not a Google Drive Sync log file, invalid date/time: {0!s} with error: {1!s}'.format(structure.date_time, exception))\n return False\n return True", "docstring": "Verify that this file is a Google Drive Sync log file.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nlines (str): one or more lines from the text file.\n\nReturns:\nbool: True if this is the correct parser, False otherwise.", "source": "codesearchnet"}
63{"code": "def _average_precision(self, rec, prec):\n mrec = np.concatenate(([0.0], rec, [1.0]))\n mpre = np.concatenate(([0.0], prec, [0.0]))\n for i in range((mpre.size - 1), 0, (- 1)):\n mpre[(i - 1)] = np.maximum(mpre[(i - 1)], mpre[i])\n i = np.where((mrec[1:] != mrec[:(- 1)]))[0]\n ap = np.sum(((mrec[(i + 1)] - mrec[i]) * mpre[(i + 1)]))\n return ap", "docstring": "calculate average precision\n\nParams:\n----------\nrec : numpy.array\ncumulated recall\nprec : numpy.array\ncumulated precision\nReturns:\n----------\nap as float", "source": "codesearchnet"}
64{"code": "def GetParserObjectByName(cls, parser_name):\n \n parser_class = cls._parser_classes.get(parser_name, None)\n if parser_class:\n return parser_class()\n return None", "docstring": "Retrieves a specific parser object by its name.\n\nArgs:\nparser_name (str): name of the parser.\n\nReturns:\nBaseParser: parser object or None.", "source": "juraj-google-style"}
65{"code": "def create_video(video_data):\n serializer = VideoSerializer(data=video_data)\n if serializer.is_valid():\n serializer.save()\n return video_data.get('edx_video_id')\n else:\n raise ValCannotCreateError(serializer.errors)", "docstring": "Called on to create Video objects in the database\n\ncreate_video is used to create Video objects whose children are EncodedVideo\nobjects which are linked to Profile objects. This is an alternative to the HTTP\nrequests so it can be used internally. The VideoSerializer is used to\ndeserialize this object. If there are duplicate profile_names, the entire\ncreation will be rejected. If the profile is not found in the database, the\nvideo will not be created.\nArgs:\nvideo_data (dict):\n{\nurl: api url to the video\nedx_video_id: ID of the video\nduration: Length of video in seconds\nclient_video_id: client ID of video\nencoded_video: a list of EncodedVideo dicts\nurl: url of the video\nfile_size: size of the video in bytes\nprofile: ID of the profile\ncourses: Courses associated with this video\nimage: poster image file name for a particular course\n}\n\nRaises:\nRaises ValCannotCreateError if the video cannot be created.\n\nReturns the successfully created Video object", "source": "codesearchnet"}
66{"code": "def load_from_checkpoint(self, sess, latest_filename=None):\n self._create_initializers()\n if self._save_path:\n ckpt = tf.train.get_checkpoint_state(os.path.dirname(self._save_path), latest_filename)\n if (ckpt and ckpt.all_model_checkpoint_paths):\n self._saver = tf.train.Saver(saver_def=self._saver.as_saver_def())\n self._saver.set_last_checkpoints(list(ckpt.all_model_checkpoint_paths))\n if self._saver.last_checkpoints:\n self._saver.restore(sess, self._saver.last_checkpoints[(- 1)])\n return self._saver.last_checkpoints[(- 1)]\n else:\n return None", "docstring": "Loads the model from the most recent checkpoint.\n\nThis gets the most current list of checkpoints each time it is called.\n\nArgs:\nsess: The current session.\nlatest_filename: The filename for the latest set of checkpoints, defaults\nto 'checkpoints'.\nReturns:\nThe loaded checkpoint or None if it failed to load.", "source": "codesearchnet"}
67{"code": "def _CalculateDigestHash(self, file_entry, data_stream_name):\n \n file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)\n if not file_object:\n return None\n\n try:\n file_object.seek(0, os.SEEK_SET)\n\n hasher_object = hashers_manager.HashersManager.GetHasher('sha256')\n\n data = file_object.read(self._READ_BUFFER_SIZE)\n while data:\n hasher_object.Update(data)\n data = file_object.read(self._READ_BUFFER_SIZE)\n\n finally:\n file_object.close()\n\n return hasher_object.GetStringDigest()", "docstring": "Calculates a SHA-256 digest of the contents of the file entry.\n\nArgs:\nfile_entry (dfvfs.FileEntry): file entry whose content will be hashed.\ndata_stream_name (str): name of the data stream whose content is to be\nhashed.\n\nReturns:\nstr: hexadecimal representation of the SHA-256 hash or None if the digest\ncannot be determined.", "source": "juraj-google-style"}
68{"code": "def df_categorical_column(category_values, num_rows=100, probabilities=None):\n \n splitter = np.random.choice(range(len(category_values)), num_rows, p=probabilities)\n return pd.Series(pd.Categorical.from_codes(splitter, categories=category_values))", "docstring": "Generate a categorical column with random data\nArgs:\ncategory_values (list): A list of category values (e.g. ['red', 'blue', 'green'])\nnum_rows (int): The number of rows to generate (default = 100)\nprobabilities (list): A list of probabilities of each value (e.g. [0.6, 0.2, 0.2]) (default=None an equal probability)", "source": "juraj-google-style"}
69{"code": "def getWeights(self, term_i=None):\n assert self.init, 'GP not initialised'\n if (term_i == None):\n if (self.gp.mean.n_terms == 1):\n term_i = 0\n else:\n print('VarianceDecomposition: Specify fixed effect term index')\n return self.gp.mean.B[term_i]", "docstring": "Return weights for fixed effect term term_i\n\nArgs:\nterm_i: fixed effect term index\nReturns:\nweights of the spefied fixed effect term.\nThe output will be a KxL matrix of weights will be returned,\nwhere K is F.shape[1] and L is A.shape[1] of the correspoding fixed effect term\n(L will be always 1 for single-trait analysis).", "source": "codesearchnet"}
70{"code": "class DisjunctiveConstraint(Constraint):\n\n def __init__(self, nested_token_ids: List[List[int]]):\n super(Constraint, self).__init__()\n if not isinstance(nested_token_ids, list) or len(nested_token_ids) == 0:\n raise ValueError(f'`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.')\n if any((not isinstance(token_ids, list) for token_ids in nested_token_ids)):\n raise ValueError(f'`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.')\n if any((any((not isinstance(token_id, int) or token_id < 0 for token_id in token_ids)) for token_ids in nested_token_ids)):\n raise ValueError(f'Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.')\n self.trie = DisjunctiveTrie(nested_token_ids)\n self.token_ids = nested_token_ids\n self.seqlen = self.trie.max_height\n self.current_seq = []\n self.completed = False\n\n def advance(self):\n token_list = self.trie.next_tokens(self.current_seq)\n if len(token_list) == 0:\n return None\n else:\n return token_list\n\n def does_advance(self, token_id: int):\n if not isinstance(token_id, int):\n raise TypeError(f'`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}')\n next_tokens = self.trie.next_tokens(self.current_seq)\n return token_id in next_tokens\n\n def update(self, token_id: int):\n if not isinstance(token_id, int):\n raise TypeError(f'`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}')\n stepped = False\n completed = False\n reset = False\n if self.does_advance(token_id):\n self.current_seq.append(token_id)\n stepped = True\n else:\n reset = True\n self.reset()\n completed = self.trie.reached_leaf(self.current_seq)\n self.completed = completed\n return (stepped, completed, reset)\n\n def reset(self):\n self.completed = False\n self.current_seq = []\n\n def remaining(self):\n if self.completed:\n return 0\n else:\n return self.seqlen - len(self.current_seq)\n\n def copy(self, stateful=False):\n new_constraint = DisjunctiveConstraint(self.token_ids)\n if stateful:\n new_constraint.seq_len = self.seqlen\n new_constraint.current_seq = self.current_seq\n new_constraint.completed = self.completed\n return new_constraint", "docstring": "A special [`Constraint`] that is fulfilled by fulfilling just one of several constraints.\n\nArgs:\nnested_token_ids (`List[List[int]]`):\nA list of words, where each word is a list of ids. This constraint is fulfilled by generating just one from\nthe list of words.", "source": "github-repos"}
71{"code": "def _get_formatted_date(dataset_date, date_format=None):\n if dataset_date:\n if date_format:\n return dataset_date.strftime(date_format)\n else:\n return dataset_date.date().isoformat()\n else:\n return None", "docstring": "Get supplied dataset date as string in specified format.\nIf no format is supplied, an ISO 8601 string is returned.\n\nArgs:\ndataset_date (Optional[datetime.datetime]): dataset date in datetime.datetime format\ndate_format (Optional[str]): Date format. None is taken to be ISO 8601. Defaults to None.\n\nReturns:\nOptional[str]: Dataset date string or None if no date is set", "source": "codesearchnet"}
72{"code": "def resize_annotation(self, annotation: Dict[str, Any], orig_size: Tuple[int, int], target_size: Tuple[int, int], threshold: float=0.5, interpolation: 'F.InterpolationMode'=None):\n interpolation = interpolation if interpolation is not None else F.InterpolationMode.NEAREST\n ratio_height, ratio_width = [target / orig for target, orig in zip(target_size, orig_size)]\n new_annotation = {}\n new_annotation['size'] = target_size\n for key, value in annotation.items():\n if key == 'boxes':\n boxes = value\n scaled_boxes = boxes * torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32, device=boxes.device)\n new_annotation['boxes'] = scaled_boxes\n elif key == 'area':\n area = value\n scaled_area = area * (ratio_width * ratio_height)\n new_annotation['area'] = scaled_area\n elif key == 'masks':\n masks = value[:, None]\n masks = [F.resize(mask, target_size, interpolation=interpolation) for mask in masks]\n masks = torch.stack(masks).to(torch.float32)\n masks = masks[:, 0] > threshold\n new_annotation['masks'] = masks\n elif key == 'size':\n new_annotation['size'] = target_size\n else:\n new_annotation[key] = value\n return new_annotation", "docstring": "Resizes an annotation to a target size.\n\nArgs:\nannotation (`Dict[str, Any]`):\nThe annotation dictionary.\norig_size (`Tuple[int, int]`):\nThe original size of the input image.\ntarget_size (`Tuple[int, int]`):\nThe target size of the image, as returned by the preprocessing `resize` step.\nthreshold (`float`, *optional*, defaults to 0.5):\nThe threshold used to binarize the segmentation masks.\nresample (`InterpolationMode`, defaults to `InterpolationMode.NEAREST`):\nThe resampling filter to use when resizing the masks.", "source": "github-repos"}
73{"code": "def _GetCachedFileByPath(self, key_path_upper):\n \n longest_key_path_prefix_upper = ''\n longest_key_path_prefix_length = len(longest_key_path_prefix_upper)\n for key_path_prefix_upper in self._registry_files:\n if key_path_upper.startswith(key_path_prefix_upper):\n key_path_prefix_length = len(key_path_prefix_upper)\n if key_path_prefix_length > longest_key_path_prefix_length:\n longest_key_path_prefix_upper = key_path_prefix_upper\n longest_key_path_prefix_length = key_path_prefix_length\n\n if not longest_key_path_prefix_upper:\n return None, None\n\n registry_file = self._registry_files.get(\n longest_key_path_prefix_upper, None)\n return longest_key_path_prefix_upper, registry_file", "docstring": "Retrieves a cached Windows Registry file for a key path.\n\nArgs:\nkey_path_upper (str): Windows Registry key path, in upper case with\na resolved root key alias.\n\nReturns:\ntuple: consist:\n\nstr: key path prefix\nWinRegistryFile: corresponding Windows Registry file or None if not\navailable.", "source": "juraj-google-style"}
74{"code": "def patch_on_path(src: symbolic.Symbolic, regex: str, value: Any=None, value_fn: Optional[Callable[[Any], Any]]=None, skip_notification: Optional[bool]=None) -> Any:\n regex = re.compile(regex)\n return _conditional_patch(src, lambda k, v, p: regex.match(str(k)), value, value_fn, skip_notification)", "docstring": "Recursively patch values on matched paths.\n\nExample::\n\nd = pg.Dict(a={'x': 1}, b=2)\nprint(pg.patching.patch_on_path(d, '.*x', value=3))\n# {a={x=1}, b=2}\n\nArgs:\nsrc: symbolic value to patch.\nregex: Regex for key path.\nvalue: New value for field that satisfy `condition`.\nvalue_fn: Callable object that produces new value based on old value.\nIf not None, `value` must be None.\nskip_notification: If True, `on_change` event will not be triggered for this\noperation. If None, the behavior is decided by `pg.notify_on_rebind`.\nPlease see `symbolic.Symbolic.rebind` for details.\n\nReturns:\n`src` after being patched.", "source": "github-repos"}
75{"code": "def set_user(uid=None, username=None, password=None, priv=None, status=None):\n \n\n conf = \"\"\n if not uid:\n raise salt.exceptions.CommandExecutionError(\"The user ID must be specified.\")\n\n if status:\n conf += ' accountStatus=\"{0}\"'.format(status)\n\n if username:\n conf += ' name=\"{0}\"'.format(username)\n\n if priv:\n conf += ' priv=\"{0}\"'.format(priv)\n\n if password:\n conf += ' pwd=\"{0}\"'.format(password)\n\n dn = \"sys/user-ext/user-{0}\".format(uid)\n\n inconfig = .format(uid,\n conf)\n\n ret = __proxy__['cimc.set_config_modify'](dn, inconfig, False)\n\n return ret", "docstring": "Sets a CIMC user with specified configurations.\n\n.. versionadded:: 2019.2.0\n\nArgs:\nuid(int): The user ID slot to create the user account in.\n\nusername(str): The name of the user.\n\npassword(str): The clear text password of the user.\n\npriv(str): The privilege level of the user.\n\nstatus(str): The account status of the user.\n\nCLI Example:\n\n.. code-block:: bash\n\nsalt '*' cimc.set_user 11 username=admin password=foobar priv=admin active", "source": "juraj-google-style"}
76{"code": "def forward(self, layer_input):\n bsz, length, emb_size = layer_input.size()\n layer_input = layer_input.reshape(-1, emb_size)\n _, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)\n expert_inputs = layer_input[batch_index]\n hidden_states = self.input_linear(expert_inputs, expert_size)\n chunked_hidden_states = hidden_states.chunk(2, dim=-1)\n hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]\n expert_outputs = self.output_linear(hidden_states, expert_size)\n expert_outputs = expert_outputs * batch_gates[:, None]\n zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)\n layer_output = zeros.index_add(0, batch_index, expert_outputs)\n layer_output = layer_output.view(bsz, length, self.input_size)\n layer_output = layer_output + self.bias\n return (layer_output, router_logits)", "docstring": "Forward pass of the mixture of experts layer.\n\nArgs:\nlayer_input (Tensor):\nInput tensor.\n\nReturns:\nTensor:\nOutput tensor.\nTensor:\nRouter logits.", "source": "github-repos"}
77{"code": "def business_days_in_period(self, date_tensor, period_tensor):\n return self.business_days_between(date_tensor, date_tensor + period_tensor)", "docstring": "Calculates number of business days in a period.\n\nIncludes the dates in `date_tensor`, but excludes final dates resulting from\naddition of `period_tensor`.\n\nArgs:\ndate_tensor: `DateTensor` of starting dates.\nperiod_tensor: PeriodTensor, should be broadcastable to `date_tensor`.\n\nReturns:\nAn int32 Tensor with the number of business days in given periods that\nstart at given dates.", "source": "github-repos"}
78{"code": "def get_widget_or_404(self):\n field_id = self.kwargs.get('field_id', self.request.GET.get('field_id', None))\n if (not field_id):\n raise Http404('No \"field_id\" provided.')\n try:\n key = signing.loads(field_id)\n except BadSignature:\n raise Http404('Invalid \"field_id\".')\n else:\n cache_key = ('%s%s' % (settings.SELECT2_CACHE_PREFIX, key))\n widget_dict = cache.get(cache_key)\n if (widget_dict is None):\n raise Http404('field_id not found')\n if (widget_dict.pop('url') != self.request.path):\n raise Http404('field_id was issued for the view.')\n (qs, qs.query) = widget_dict.pop('queryset')\n self.queryset = qs.all()\n widget_dict['queryset'] = self.queryset\n widget_cls = widget_dict.pop('cls')\n return widget_cls(**widget_dict)", "docstring": "Get and return widget from cache.\n\nRaises:\nHttp404: If if the widget can not be found or no id is provided.\n\nReturns:\nModelSelect2Mixin: Widget from cache.", "source": "codesearchnet"}
79{"code": "def CheckPath(self, path, path_segment_separator=None):\n \n if not self._case_sensitive:\n path = path.lower()\n\n if path_segment_separator is None:\n path_segment_separator = self._path_segment_separator\n\n path_segments = path.split(path_segment_separator)\n number_of_path_segments = len(path_segments)\n\n scan_object = self._root_node\n while scan_object:\n if isinstance(scan_object, py2to3.STRING_TYPES):\n break\n\n if scan_object.path_segment_index >= number_of_path_segments:\n scan_object = scan_object.default_value\n continue\n\n path_segment = path_segments[scan_object.path_segment_index]\n scan_object = scan_object.GetScanObject(path_segment)\n\n if not isinstance(scan_object, py2to3.STRING_TYPES):\n return False\n\n filter_path_segments = scan_object.split(self._path_segment_separator)\n return filter_path_segments == path_segments", "docstring": "Checks if a path matches the scan tree-based path filter.\n\nArgs:\npath: a string containing the path.\npath_segment_separator: optional string containing the path segment\nseparator. None defaults to the path segment\nseparator that was set when the path filter\nscan tree was initialized.\n\nReturns:\nA boolean indicating if the path matches the filter.", "source": "juraj-google-style"}
80{"code": "def _gather_saveables_for_checkpoint(self) -> Dict[str, Callable[..., Any]]:\n\n def _saveable_factory(name=self._common_name):\n saveables = []\n num_shards = len(self.values)\n for shard_id in range(num_shards):\n saveables.append(TPUEmbeddingShardedSaveable(self.values[shard_id], shard_id, num_shards, self.shard_dim, name))\n return saveables\n return {base.VARIABLE_VALUE_KEY: _saveable_factory}", "docstring": "Overrides Trackable method.\n\nReturns:\nA dictionary mapping attribute names to `SaveableObject` factories.", "source": "github-repos"}
81{"code": "def convert_to_layout_rules(x):\n if isinstance(x, LayoutRules):\n return x\n if isinstance(x, str):\n x = _parse_string_to_list_of_pairs(x)\n return LayoutRules(x)", "docstring": "Converts input to a LayoutRules.\n\nArgs:\nx: LayoutRules, str, or set-like of string pairs.\n\nReturns:\nLayoutRules.", "source": "codesearchnet"}
82{"code": "def filter_set(self, name):\n \n\n filter_set = filter_sets[name]\n for name, filter in iter(filter_set.filters.items()):\n self.filters[name] = filter\n self.descriptions += filter_set.descriptions", "docstring": "Adds filters from a particular global :class:`FilterSet`.\n\nArgs:\nname (str): The name of the set whose filters should be added.", "source": "juraj-google-style"}
83{"code": "def execute_task(self, task, workflow_id, data=None):\n \n start_time = datetime.utcnow()\n\n store_doc = DataStore(**self.app.user_options['config'].data_store,\n auto_connect=True).get(workflow_id)\n store_loc = 'log.{}.tasks.{}'.format(task.dag_name, task.name)\n\n def handle_callback(message, event_type, exc=None):\n msg = '{}: {}'.format(message, str(exc)) if exc is not None else message\n\n \n if event_type == JobEventName.Stopped:\n logger.warning(msg)\n elif event_type == JobEventName.Aborted:\n logger.error(msg)\n else:\n logger.info(msg)\n\n current_time = datetime.utcnow()\n\n \n if event_type != JobEventName.Started:\n duration = (current_time - start_time).total_seconds()\n\n store_doc.set(key='{}.end_time'.format(store_loc),\n value=current_time,\n section=DataStoreDocumentSection.Meta)\n\n store_doc.set(key='{}.duration'.format(store_loc),\n value=duration,\n section=DataStoreDocumentSection.Meta)\n else:\n \n store_doc.set(key='{}.start_time'.format(store_loc),\n value=start_time,\n section=DataStoreDocumentSection.Meta)\n\n store_doc.set(key='{}.worker'.format(store_loc),\n value=self.request.hostname,\n section=DataStoreDocumentSection.Meta)\n\n store_doc.set(key='{}.queue'.format(store_loc),\n value=task.queue,\n section=DataStoreDocumentSection.Meta)\n duration = None\n\n \n self.send_event(event_type,\n job_type=JobType.Task,\n name=task.name,\n queue=task.queue,\n time=current_time,\n workflow_id=workflow_id,\n duration=duration)\n\n \n self.update_state(meta={'name': task.name,\n 'queue': task.queue,\n 'type': JobType.Task,\n 'workflow_id': workflow_id})\n\n \n handle_callback('Start task <{}>'.format(task.name), JobEventName.Started)\n\n \n return task._run(\n data=data,\n store=store_doc,\n signal=TaskSignal(Client(\n SignalConnection(**self.app.user_options['config'].signal, auto_connect=True),\n request_key=workflow_id),\n task.dag_name),\n context=TaskContext(task.name, task.dag_name, task.workflow_name,\n workflow_id, self.request.hostname),\n success_callback=partial(handle_callback,\n message='Complete task <{}>'.format(task.name),\n event_type=JobEventName.Succeeded),\n stop_callback=partial(handle_callback,\n message='Stop task <{}>'.format(task.name),\n event_type=JobEventName.Stopped),\n abort_callback=partial(handle_callback,\n message='Abort workflow <{}> by task <{}>'.format(\n task.workflow_name, task.name),\n event_type=JobEventName.Aborted))", "docstring": "Celery task that runs a single task on a worker.\n\nArgs:\nself (Task): Reference to itself, the celery task object.\ntask (BaseTask): Reference to the task object that performs the work\nin its run() method.\nworkflow_id (string): The unique ID of the workflow run that started this task.\ndata (MultiTaskData): An optional MultiTaskData object that contains the data\nthat has been passed down from upstream tasks.", "source": "juraj-google-style"}
84{"code": "def from_config(cls, config, custom_objects=None):\n with generic_utils.SharedObjectLoadingScope():\n input_tensors, output_tensors, created_layers = reconstruct_from_config(config, custom_objects)\n model = cls(inputs=input_tensors, outputs=output_tensors, name=config.get('name'))\n connect_ancillary_layers(model, created_layers)\n return model", "docstring": "Instantiates a Model from its config (output of `get_config()`).\n\nArgs:\nconfig: Model config dictionary.\ncustom_objects: Optional dictionary mapping names\n(strings) to custom classes or functions to be\nconsidered during deserialization.\n\nReturns:\nA model instance.\n\nRaises:\nValueError: In case of improperly formatted config dict.", "source": "github-repos"}
85{"code": "async def find_movie(self, query):\n \n params = OrderedDict([\n ('query', query), ('include_adult', False),\n ])\n url = self.url_builder('search/movie', {}, params)\n data = await self.get_data(url)\n if data is None:\n return\n return [\n Movie.from_json(item, self.config['data'].get('images'))\n for item in data.get('results', [])\n ]", "docstring": "Retrieve movie data by search query.\n\nArguments:\nquery (:py:class:`str`): Query to search for.\n\nReturns:\n:py:class:`list`: Possible matches.", "source": "juraj-google-style"}
86{"code": "def dataset_exists(client, dataset_reference):\n \n from google.cloud.exceptions import NotFound\n\n try:\n client.get_dataset(dataset_reference)\n return True\n except NotFound:\n return False", "docstring": "Return if a dataset exists.\n\nArgs:\nclient (google.cloud.bigquery.client.Client):\nA client to connect to the BigQuery API.\ndataset_reference (google.cloud.bigquery.dataset.DatasetReference):\nA reference to the dataset to look for.\n\nReturns:\nbool: ``True`` if the dataset exists, ``False`` otherwise.", "source": "juraj-google-style"}
87{"code": "def dispose(json_str):\n \n result_str = list(json_str)\n escaped = False\n normal = True\n sl_comment = False\n ml_comment = False\n quoted = False\n\n a_step_from_comment = False\n a_step_from_comment_away = False\n\n former_index = None\n\n for index, char in enumerate(json_str):\n\n if escaped: \n escaped = False\n continue\n\n if a_step_from_comment: \n if char != '/' and char != '*':\n a_step_from_comment = False\n normal = True\n continue\n\n if a_step_from_comment_away: \n if char != '/':\n a_step_from_comment_away = False\n\n if char == '\"':\n if normal and not escaped:\n \n quoted = True\n normal = False\n elif quoted and not escaped:\n \n quoted = False\n normal = True\n\n elif char == '\\\\':\n \n if normal or quoted:\n escaped = True\n\n elif char == '/':\n if a_step_from_comment:\n \n a_step_from_comment = False\n sl_comment = True\n normal = False\n former_index = index - 1\n elif a_step_from_comment_away:\n \n a_step_from_comment_away = False\n normal = True\n ml_comment = False\n for i in range(former_index, index + 1):\n result_str[i] = \"\"\n\n elif normal:\n \n a_step_from_comment = True\n normal = False\n\n elif char == '*':\n if a_step_from_comment:\n \n a_step_from_comment = False\n ml_comment = True\n normal = False\n former_index = index - 1\n elif ml_comment:\n a_step_from_comment_away = True\n elif char == '\\n':\n if sl_comment:\n sl_comment = False\n normal = True\n for i in range(former_index, index + 1):\n result_str[i] = \"\"\n elif char == ']' or char == '}':\n if normal:\n _remove_last_comma(result_str, index)\n\n \n return (\"\" if isinstance(json_str, str) else u\"\").join(result_str)", "docstring": "Clear all comments in json_str.\n\nClear JS-style comments like // and /**/ in json_str.\nAccept a str or unicode as input.\n\nArgs:\njson_str: A json string of str or unicode to clean up comment\n\nReturns:\nstr: The str without comments (or unicode if you pass in unicode)", "source": "juraj-google-style"}
88{"code": "def _PrintPreprocessingInformation(self, storage_reader, session_number=None):\n knowledge_base_object = knowledge_base.KnowledgeBase()\n storage_reader.ReadPreprocessingInformation(knowledge_base_object)\n system_configuration = knowledge_base_object.GetSystemConfigurationArtifact(session_identifier=session_number)\n if (not system_configuration):\n return\n title = 'System configuration'\n table_view = views.ViewsFactory.GetTableView(self._views_format_type, title=title)\n hostname = 'N/A'\n if system_configuration.hostname:\n hostname = system_configuration.hostname.name\n operating_system = (system_configuration.operating_system or 'N/A')\n operating_system_product = (system_configuration.operating_system_product or 'N/A')\n operating_system_version = (system_configuration.operating_system_version or 'N/A')\n code_page = (system_configuration.code_page or 'N/A')\n keyboard_layout = (system_configuration.keyboard_layout or 'N/A')\n time_zone = (system_configuration.time_zone or 'N/A')\n table_view.AddRow(['Hostname', hostname])\n table_view.AddRow(['Operating system', operating_system])\n table_view.AddRow(['Operating system product', operating_system_product])\n table_view.AddRow(['Operating system version', operating_system_version])\n table_view.AddRow(['Code page', code_page])\n table_view.AddRow(['Keyboard layout', keyboard_layout])\n table_view.AddRow(['Time zone', time_zone])\n table_view.Write(self._output_writer)\n title = 'User accounts'\n table_view = views.ViewsFactory.GetTableView(self._views_format_type, column_names=['Username', 'User directory'], title=title)\n for user_account in system_configuration.user_accounts:\n table_view.AddRow([user_account.username, user_account.user_directory])\n table_view.Write(self._output_writer)", "docstring": "Prints the details of the preprocessing information.\n\nArgs:\nstorage_reader (StorageReader): storage reader.\nsession_number (Optional[int]): session number.", "source": "codesearchnet"}
89{"code": "def get_common_register(start, end):\n \n registers = defaultdict(int)\n for line in lines(start, end):\n insn = line.insn\n\n for operand in insn.operands:\n\n if not operand.type.has_phrase:\n continue\n\n if not operand.base:\n continue\n\n register_name = operand.base\n registers[register_name] += 1\n\n return max(registers.iteritems(), key=operator.itemgetter(1))[0]", "docstring": "Get the register most commonly used in accessing structs.\n\nAccess to is considered for every opcode that accesses memory\nin an offset from a register::\n\nmov eax, [ebx + 5]\n\nFor every access, the struct-referencing registers, in this case\n`ebx`, are counted. The most used one is returned.\n\nArgs:\nstart: The adderss to start at\nend: The address to finish at", "source": "juraj-google-style"}
90{"code": "def mme_delete(case_obj, mme_base_url, mme_token):\n server_responses = []\n if ((not mme_base_url) or (not mme_token)):\n return 'Please check that Matchmaker connection parameters are valid'\n for patient in case_obj['mme_submission']['patients']:\n patient_id = patient['id']\n url = ''.join([mme_base_url, '/patient/delete/', patient_id])\n resp = matchmaker_request(url=url, token=mme_token, method='DELETE')\n server_responses.append({'patient_id': patient_id, 'message': resp.get('message'), 'status_code': resp.get('status_code')})\n return server_responses", "docstring": "Delete all affected samples for a case from MatchMaker\n\nArgs:\ncase_obj(dict) a scout case object\nmme_base_url(str) base url of the MME server\nmme_token(str) auth token of the MME server\n\nReturns:\nserver_responses(list): a list of object of this type:\n{\n'patient_id': patient_id\n'message': server_message,\n'status_code': server_status_code\n}", "source": "codesearchnet"}
91{"code": "def segment_to_vector(self, seg):\n ft_dict = {ft: val for (val, ft) in self.fts(seg)}\n return [ft_dict[name] for name in self.names]", "docstring": "Given a Unicode IPA segment, return a list of feature specificiations\nin cannonical order.\n\nArgs:\nseg (unicode): IPA consonant or vowel\n\nReturns:\nlist: feature specifications ('+'/'-'/'0') in the order from\n`FeatureTable.names`", "source": "codesearchnet"}
92{"code": "def measure(*qubits: raw_types.Qid, key: Optional[str]=None, invert_mask: Tuple[(bool, ...)]=()) -> gate_operation.GateOperation:\n for qubit in qubits:\n if isinstance(qubit, np.ndarray):\n raise ValueError('measure() was called a numpy ndarray. Perhaps you meant to call measure_state_vector on numpy array?')\n elif (not isinstance(qubit, raw_types.Qid)):\n raise ValueError('measure() was called with type different than Qid.')\n if (key is None):\n key = _default_measurement_key(qubits)\n return MeasurementGate(len(qubits), key, invert_mask).on(*qubits)", "docstring": "Returns a single MeasurementGate applied to all the given qubits.\n\nThe qubits are measured in the computational basis.\n\nArgs:\n*qubits: The qubits that the measurement gate should measure.\nkey: The string key of the measurement. If this is None, it defaults\nto a comma-separated list of the target qubits' str values.\ninvert_mask: A list of Truthy or Falsey values indicating whether\nthe corresponding qubits should be flipped. None indicates no\ninverting should be done.\n\nReturns:\nAn operation targeting the given qubits with a measurement.\n\nRaises:\nValueError if the qubits are not instances of Qid.", "source": "codesearchnet"}
93{"code": "def exists(self, workflow_id):\n try:\n db = self._client[self.database]\n col = db[WORKFLOW_DATA_COLLECTION_NAME]\n return (col.find_one({'_id': ObjectId(workflow_id)}) is not None)\n except ConnectionFailure:\n raise DataStoreNotConnected()", "docstring": "Checks whether a document with the specified workflow id already exists.\n\nArgs:\nworkflow_id (str): The workflow id that should be checked.\n\nRaises:\nDataStoreNotConnected: If the data store is not connected to the server.\n\nReturns:\nbool: ``True`` if a document with the specified workflow id exists.", "source": "codesearchnet"}
94{"code": "def compare_mim_panels(self, existing_panel, new_panel):\n existing_genes = set([gene['hgnc_id'] for gene in existing_panel['genes']])\n new_genes = set([gene['hgnc_id'] for gene in new_panel['genes']])\n return new_genes.difference(existing_genes)", "docstring": "Check if the latest version of OMIM differs from the most recent in database\nReturn all genes that where not in the previous version.\n\nArgs:\nexisting_panel(dict)\nnew_panel(dict)\n\nReturns:\nnew_genes(set(str))", "source": "codesearchnet"}
95{"code": "def call(self, input_ids: Optional[tf.Tensor]=None, position_ids: Optional[tf.Tensor]=None, token_type_ids: Optional[tf.Tensor]=None, inputs_embeds: Optional[tf.Tensor]=None, past_key_values_length=0, training: bool=False) -> tf.Tensor:\n assert not (input_ids is None and inputs_embeds is None)\n if input_ids is not None:\n check_embeddings_within_bounds(input_ids, self.config.vocab_size)\n inputs_embeds = tf.gather(params=self.weight, indices=input_ids)\n input_shape = shape_list(inputs_embeds)[:-1]\n if token_type_ids is None:\n token_type_ids = tf.fill(dims=input_shape, value=0)\n if position_ids is None:\n position_ids = tf.expand_dims(tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0)\n position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)\n token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)\n final_embeddings = inputs_embeds + position_embeds + token_type_embeds\n final_embeddings = self.LayerNorm(inputs=final_embeddings)\n final_embeddings = self.dropout(inputs=final_embeddings, training=training)\n return final_embeddings", "docstring": "Applies embedding based on inputs tensor.\n\nReturns:\nfinal_embeddings (`tf.Tensor`): output embedding tensor.", "source": "github-repos"}
96{"code": "def _add_unitary_single(self, gate, qubit):\n \n \n indexes = einsum_vecmul_index([qubit], self._number_of_qubits)\n \n gate_tensor = np.array(gate, dtype=complex)\n \n self._statevector = np.einsum(indexes, gate_tensor,\n self._statevector,\n dtype=complex,\n casting='no')", "docstring": "Apply an arbitrary 1-qubit unitary matrix.\n\nArgs:\ngate (matrix_like): a single qubit gate matrix\nqubit (int): the qubit to apply gate to", "source": "juraj-google-style"}
97{"code": "def _get_rand_attn_plan(from_seq_length, from_block_size, num_rand_blocks):\n plan_from_length = []\n plan_num_rand_blocks = []\n if 2 * num_rand_blocks + 5 < from_seq_length \n plan_from_length.append(int((2 * num_rand_blocks + 5) * from_block_size))\n plan_num_rand_blocks.append(num_rand_blocks)\n plan_from_length.append(from_seq_length)\n plan_num_rand_blocks.append(0)\n elif num_rand_blocks + 5 < from_seq_length \n plan_from_length.append(int((num_rand_blocks + 5) * from_block_size))\n plan_num_rand_blocks.append(num_rand_blocks \n plan_from_length.append(from_seq_length)\n plan_num_rand_blocks.append(num_rand_blocks - num_rand_blocks \n else:\n plan_from_length.append(from_seq_length)\n plan_num_rand_blocks.append(num_rand_blocks)\n return (plan_from_length, plan_num_rand_blocks)", "docstring": "Gives the plan of where to put random attention.\n\nArgs:\nfrom_seq_length: int. length of from sequence.\nfrom_block_size: int. size of block in from sequence.\nnum_rand_blocks: int. Number of random chunks per row.\n\nReturns:\nplan_from_length: ending location of from block plan_num_rand_blocks: number of random ending location for\neach block", "source": "github-repos"}
98{"code": "def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, show_row_points=True, row_points_size=10, show_row_labels=False, show_column_points=True, column_points_size=30, show_column_labels=False, legend_n_cols=1):\n utils.validation.check_is_fitted(self, 'total_inertia_')\n if (ax is None):\n (fig, ax) = plt.subplots(figsize=figsize)\n ax = plot.stylize_axis(ax)\n if (show_row_points or show_row_labels):\n row_coords = self.row_coordinates(X)\n if show_row_points:\n ax.scatter(row_coords.iloc[(:, x_component)], row_coords.iloc[(:, y_component)], s=row_points_size, label=None, color=plot.GRAY['dark'], alpha=0.6)\n if show_row_labels:\n for (_, row) in row_coords.iterrows():\n ax.annotate(row.name, (row[x_component], row[y_component]))\n if (show_column_points or show_column_labels):\n col_coords = self.column_coordinates(X)\n x = col_coords[x_component]\n y = col_coords[y_component]\n prefixes = col_coords.index.str.split('_').map((lambda x: x[0]))\n for prefix in prefixes.unique():\n mask = (prefixes == prefix)\n if show_column_points:\n ax.scatter(x[mask], y[mask], s=column_points_size, label=prefix)\n if show_column_labels:\n for (i, label) in enumerate(col_coords[mask].index):\n ax.annotate(label, (x[mask][i], y[mask][i]))\n ax.legend(ncol=legend_n_cols)\n ax.set_title('Row and column principal coordinates')\n ei = self.explained_inertia_\n ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, (100 * ei[x_component])))\n ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, (100 * ei[y_component])))\n return ax", "docstring": "Plot row and column principal coordinates.\n\nArgs:\nax (matplotlib.Axis): A fresh one will be created and returned if not provided.\nfigsize ((float, float)): The desired figure size if `ax` is not provided.\nx_component (int): Number of the component used for the x-axis.\ny_component (int): Number of the component used for the y-axis.\nshow_row_points (bool): Whether to show row principal components or not.\nrow_points_size (float): Row principal components point size.\nshow_row_labels (bool): Whether to show row labels or not.\nshow_column_points (bool): Whether to show column principal components or not.\ncolumn_points_size (float): Column principal components point size.\nshow_column_labels (bool): Whether to show column labels or not.\nlegend_n_cols (int): Number of columns used for the legend.\n\nReturns:\nmatplotlib.Axis", "source": "codesearchnet"}
99{"code": "def __init__(self, name, description, *labels):\n super(StringGauge, self).__init__('StringGauge', _string_gauge_methods, len(labels), name, description, *labels)", "docstring": "Creates a new StringGauge.\n\nArgs:\nname: name of the new metric.\ndescription: description of the new metric.\n*labels: The label list of the new metric.", "source": "github-repos"}
100{"code": "def join_tokens_to_sentences(tokens):\n text = ''\n for (entry, next_entry) in zip(tokens, tokens[1:]):\n text += entry\n if (next_entry not in SENTENCE_STOPS):\n text += ' '\n text += tokens[(- 1)]\n return text", "docstring": "Correctly joins tokens to multiple sentences\n\nInstead of always placing white-space between the tokens, it will distinguish\nbetween the next symbol and *not* insert whitespace if it is a sentence\nsymbol (e.g. '.', or '?')\n\nArgs:\ntokens: array of string tokens\nReturns:\nJoint sentences as one string", "source": "codesearchnet"}
101{"code": "def _run_task_hook(hooks, method, task, queue_name):\n \n if hooks is not None:\n try:\n getattr(hooks, method)(task, queue_name)\n except NotImplementedError:\n \n return False\n\n return True\n return False", "docstring": "Invokes hooks.method(task, queue_name).\n\nArgs:\nhooks: A hooks.Hooks instance or None.\nmethod: The name of the method to invoke on the hooks class e.g.\n\"enqueue_kickoff_task\".\ntask: The taskqueue.Task to pass to the hook method.\nqueue_name: The name of the queue to pass to the hook method.\n\nReturns:\nTrue if the hooks.Hooks instance handled the method, False otherwise.", "source": "juraj-google-style"}
102{"code": "def get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers):\n \n\n signal = get_timing_signal_1d(num_layers, channels)\n layer_signal = tf.expand_dims(signal[:, layer, :], axis=1)\n\n return layer_signal", "docstring": "Add sinusoids of different frequencies as layer (vertical) timing signal.\n\nArgs:\nchannels: dimension of the timing signal\nlayer: layer num\nnum_layers: total number of layers\n\nReturns:\na Tensor of timing signals [1, 1, channels].", "source": "juraj-google-style"}
103{"code": "def index_subdirectory(directory, class_indices, follow_links, formats):\n dirname = os.path.basename(directory)\n valid_files = iter_valid_files(directory, follow_links, formats)\n labels = []\n filenames = []\n for root, fname in valid_files:\n labels.append(class_indices[dirname])\n absolute_path = tf.io.gfile.join(root, fname)\n relative_path = tf.io.gfile.join(dirname, os.path.relpath(absolute_path, directory))\n filenames.append(relative_path)\n return (filenames, labels)", "docstring": "Recursively walks directory and list image paths and their class index.\n\nArgs:\ndirectory: string, target directory.\nclass_indices: dict mapping class names to their index.\nfollow_links: boolean, whether to recursively follow subdirectories\n(if False, we only list top-level images in `directory`).\nformats: Allowlist of file extensions to index (e.g. \".jpg\", \".txt\").\n\nReturns:\ntuple `(filenames, labels)`. `filenames` is a list of relative file\npaths, and `labels` is a list of integer labels corresponding\nto these files.", "source": "github-repos"}
104{"code": "def timeseries_from_mat(filename, varname=None, fs=1.0):\n import scipy.io as sio\n if (varname is None):\n mat_dict = sio.loadmat(filename)\n if (len(mat_dict) > 1):\n raise ValueError('Must specify varname: file contains more than one variable. ')\n else:\n mat_dict = sio.loadmat(filename, variable_names=(varname,))\n array = mat_dict.popitem()[1]\n return Timeseries(array, fs=fs)", "docstring": "load a multi-channel Timeseries from a MATLAB .mat file\n\nArgs:\nfilename (str): .mat file to load\nvarname (str): variable name. only needed if there is more than one\nvariable saved in the .mat file\nfs (scalar): sample rate of timeseries in Hz. (constant timestep assumed)\n\nReturns:\nTimeseries", "source": "codesearchnet"}
105{"code": "def __init__(self, token, vendor='test'):\n \n self.token = token\n self.vendor = vendor", "docstring": "Construct Retsly client\n\nArgs:\ntoken (string): access token\nvendor (string): vendor ID", "source": "juraj-google-style"}
106{"code": "def map_on_gpu(map_func):\n\n def _apply_fn(dataset):\n return _MapOnGpuDataset(dataset, map_func)\n return _apply_fn", "docstring": "Maps `map_func` across the elements of this dataset.\n\nNOTE: This is a highly experimental version of `tf.data.Dataset.map` that runs\n`map_func` on GPU. It must be used after applying the\n`tf.data.experimental.copy_to_device` transformation with a GPU device\nargument.\n\nArgs:\nmap_func: A function mapping a nested structure of tensors (having shapes\nand types defined by `self.output_shapes` and `self.output_types`) to\nanother nested structure of tensors.\n\nReturns:\nA `Dataset` transformation function, which can be passed to\n`tf.data.Dataset.apply`.", "source": "github-repos"}
107{"code": "def expand_with_style(template, style, data, body_subtree='body'):\n \n if template.has_defines:\n return template.expand(data, style=style)\n else:\n tokens = []\n execute_with_style_LEGACY(template, style, data, tokens.append,\n body_subtree=body_subtree)\n return JoinTokens(tokens)", "docstring": "Expand a data dictionary with a template AND a style.\n\nDEPRECATED -- Remove this entire function in favor of expand(d, style=style)\n\nA style is a Template instance that factors out the common strings in several\n\"body\" templates.\n\nArgs:\ntemplate: Template instance for the inner \"page content\"\nstyle: Template instance for the outer \"page style\"\ndata: Data dictionary, with a 'body' key (or body_subtree", "source": "juraj-google-style"}
108{"code": "def wrap_py_func(f, args, kwargs=None):\n tensor_args = []\n tensor_args_idx = {}\n n_args = len(args)\n arg_is_tensor = tuple(map(tensor_util.is_tf_type, args))\n for i in range(n_args):\n if arg_is_tensor[i]:\n tensor_args_idx[i] = len(tensor_args)\n tensor_args.append(args[i])\n if kwargs:\n kwarg_keys = tuple(kwargs.keys())\n kwarg_is_tensor = {k: tensor_util.is_tf_type(kwargs[k]) for k in kwarg_keys}\n for k in kwarg_keys:\n if kwarg_is_tensor[k]:\n tensor_args_idx[k] = len(tensor_args)\n tensor_args.append(kwargs[k])\n else:\n kwarg_keys = ()\n\n def f_wrapper(*tensor_args):\n f_args = tuple((tensor_args[tensor_args_idx[i]] if arg_is_tensor[i] else a for i, a in enumerate(args)))\n f_kwargs = {k: tensor_args[tensor_args_idx[k]] if kwarg_is_tensor[k] else kwargs[k] for i, k in enumerate(kwarg_keys)}\n f(*f_args, **f_kwargs)\n return 1\n return script_ops.eager_py_func(f_wrapper, tensor_args, dtypes.int32)", "docstring": "Helper that wraps a callable to py_func.\n\nThe helper passes tensor arguments through the py_func interface. Non-tensor\narguments are allowed, and will be passed to f directly. Note that non-tensor\narguments are captured by f will not update every time the wrapper is\ncalled (this is consistent with its argument list, which only includes\nthe tensor arguments). In general, it's safest not to reuse this wrapper.\n\nArgs:\nf: Callable\nargs: Positional arguments for f, as list or tuple.\nkwargs: Keyword arguments for f, as dict with string keys. May be None.\n\nReturns:\nThe return values of f converted to tensor.\nRaises:\nValueError: if any of the arguments are incorrect.", "source": "github-repos"}
109{"code": "def cut3d(self, cut3d_input, workdir):\n (self.stdin_fname, self.stdout_fname, self.stderr_fname) = map(os.path.join, (3 * [os.path.abspath(workdir)]), ['cut3d.stdin', 'cut3d.stdout', 'cut3d.stderr'])\n cut3d_input.write(self.stdin_fname)\n retcode = self._execute(workdir, with_mpirun=False)\n if (retcode != 0):\n raise RuntimeError(('Error while running cut3d in %s.' % workdir))\n output_filepath = cut3d_input.output_filepath\n if (output_filepath is not None):\n if (not os.path.isabs(output_filepath)):\n output_filepath = os.path.abspath(os.path.join(workdir, output_filepath))\n if (not os.path.isfile(output_filepath)):\n raise RuntimeError(('The file was not converted correctly in %s.' % workdir))\n return (self.stdout_fname, output_filepath)", "docstring": "Runs cut3d with a Cut3DInput\n\nArgs:\ncut3d_input: a Cut3DInput object.\nworkdir: directory where cut3d is executed.\n\nReturns:\n(string) absolute path to the standard output of the cut3d execution.\n(string) absolute path to the output filepath. None if output is required.", "source": "codesearchnet"}
110{"code": "def message(self, value):\n \n if value == self._defaults['message'] and 'message' in self._values:\n del self._values['message']\n else:\n self._values['message'] = value", "docstring": "The message property.\n\nArgs:\nvalue (string). the property value.", "source": "juraj-google-style"}
111{"code": "def detect_events(self, max_attempts=3):\n for _ in xrange(max_attempts):\n try:\n with KindleCloudReaderAPI.get_instance(self.uname, self.pword) as kcr:\n self.books = kcr.get_library_metadata()\n self.progress = kcr.get_library_progress()\n except KindleAPIError:\n continue\n else:\n break\n else:\n return None\n progress_map = {book.asin: self.progress[book.asin].locs[1] for book in self.books}\n new_events = self._snapshot.calc_update_events(progress_map)\n update_event = UpdateEvent(datetime.now().replace(microsecond=0))\n new_events.append(update_event)\n self._event_buf.extend(new_events)\n return new_events", "docstring": "Returns a list of `Event`s detected from differences in state\nbetween the current snapshot and the Kindle Library.\n\n`books` and `progress` attributes will be set with the latest API\nresults upon successful completion of the function.\n\nReturns:\nIf failed to retrieve progress, None\nElse, the list of `Event`s", "source": "codesearchnet"}
112{"code": "def from_optimize_result(cls, result, n, m, index=None):\n \n coords = pd.DataFrame(result.x.reshape((m, n)), index=index)\n projection = cls(coords)\n projection.stress = result.fun\n return projection", "docstring": "Construct a Projection from the output of an optimization.\n\nArgs:\nresult (:py:class:`scipy.optimize.OptimizeResult`): Object\nreturned by :py:func:`scipy.optimize.minimize`.\nn (`int`): Number of dimensions.\nm (`int`): Number of samples.\nindex (`list-like`): Names of samples. (Optional).\n\nReturns:\n:py:class:`pymds.Projection`", "source": "juraj-google-style"}
113{"code": "def set(self, key, value):\n changed = super().set(key=key, value=value)\n if (not changed):\n return False\n self._log.info('Saving configuration to \"%s\"...', self._filename)\n with open(self._filename, 'w') as stream:\n stream.write(self.content)\n self._log.info('Saved configuration to \"%s\".', self._filename)\n return True", "docstring": "Updates the value of the given key in the file.\n\nArgs:\nkey (str): Key of the property to update.\nvalue (str): New value of the property.\n\nReturn:\nbool: Indicates whether or not a change was made.", "source": "codesearchnet"}
114{"code": "def bridge_to_vlan(br):\n \n cmd = 'ovs-vsctl br-to-vlan {0}'.format(br)\n result = __salt__['cmd.run_all'](cmd)\n if result['retcode'] != 0:\n return False\n return int(result['stdout'])", "docstring": "Returns the VLAN ID of a bridge.\n\nArgs:\nbr: A string - bridge name\n\nReturns:\nVLAN ID of the bridge. The VLAN ID is 0 if the bridge is not a fake\nbridge. If the bridge does not exist, False is returned.\n\nCLI Example:\n\n.. code-block:: bash\n\nsalt '*' openvswitch.bridge_to_parent br0", "source": "juraj-google-style"}
115{"code": "def reset(self):\n self.lattice.reset()\n for atom in self.atoms.atoms:\n atom.reset()", "docstring": "Reset all counters for this simulation.\n\nArgs:\nNone\n\nReturns:\nNone", "source": "codesearchnet"}
116{"code": "def dedupe_all_lists(obj, exclude_keys=()):\n squared_dedupe_len = 10\n if isinstance(obj, dict):\n new_obj = {}\n for (key, value) in obj.items():\n if (key in exclude_keys):\n new_obj[key] = value\n else:\n new_obj[key] = dedupe_all_lists(value)\n return new_obj\n elif isinstance(obj, (list, tuple, set)):\n new_elements = [dedupe_all_lists(v) for v in obj]\n if (len(new_elements) < squared_dedupe_len):\n new_obj = dedupe_list(new_elements)\n else:\n new_obj = dedupe_list_of_dicts(new_elements)\n return type(obj)(new_obj)\n else:\n return obj", "docstring": "Recursively remove duplucates from all lists.\n\nArgs:\nobj: collection to deduplicate\nexclude_keys (Container[str]): key names to ignore for deduplication", "source": "codesearchnet"}
117{"code": "def easeInOutQuint(n):\n _checkRange(n)\n n = (2 * n)\n if (n < 1):\n return (0.5 * (n ** 5))\n else:\n n = (n - 2)\n return (0.5 * ((n ** 5) + 2))", "docstring": "A quintic tween function that accelerates, reaches the midpoint, and then decelerates.\n\nArgs:\nn (float): The time progress, starting at 0.0 and ending at 1.0.\n\nReturns:\n(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().", "source": "codesearchnet"}
118{"code": "def _create_ssh_keys(self):\n (ret, _, _) = utils.run_command(['ssh-keygen', '-t', 'rsa', '-m', 'PEM', '-N', '', '-f', self.paths.ssh_id_rsa()])\n if (ret != 0):\n raise RuntimeError('Failed to crate ssh keys at %s', self.paths.ssh_id_rsa())", "docstring": "Generate a pair of ssh keys for this prefix\n\nReturns:\nNone\n\nRaises:\nRuntimeError: if it fails to create the keys", "source": "codesearchnet"}
119{"code": "def packet_meta_data(self):\n \n\n \n for item in self.input_stream:\n\n \n output = {}\n\n \n timestamp = item['timestamp']\n buf = item['raw_buf']\n\n \n output['timestamp'] = datetime.datetime.utcfromtimestamp(timestamp)\n\n \n eth = dpkt.ethernet.Ethernet(buf)\n output['eth'] = {'src': eth.src, 'dst': eth.dst, 'type':eth.type, 'len': len(eth)}\n\n \n packet = eth.data\n\n \n if hasattr(packet, 'data'):\n output['packet'] = {'type': packet.__class__.__name__, 'data': packet.data}\n else:\n output['packet'] = {'type': None, 'data': None}\n\n \n if output['packet']['type'] == 'IP':\n\n \n df = bool(packet.off & dpkt.ip.IP_DF)\n mf = bool(packet.off & dpkt.ip.IP_MF)\n offset = packet.off & dpkt.ip.IP_OFFMASK\n\n \n output['packet'].update({'src':packet.src, 'dst':packet.dst, 'p': packet.p, 'len':packet.len, 'ttl':packet.ttl,\n 'df':df, 'mf': mf, 'offset': offset, 'checksum': packet.sum})\n\n \n elif output['packet']['type'] == 'IP6':\n\n \n output['packet'].update({'src':packet.src, 'dst':packet.dst, 'p': packet.p, 'len':packet.plen, 'ttl':packet.hlim})\n\n \n else:\n output['packet'].update(data_utils.make_dict(packet))\n\n \n \n output['transport'] = None\n\n \n \n output['application'] = None\n\n \n yield output", "docstring": "Pull out the metadata about each packet from the input_stream\nArgs:\nNone\nReturns:\ngenerator (dictionary): a generator that contains packet meta data in the form of a dictionary", "source": "juraj-google-style"}
120{"code": "def make_repr(inst, attrs):\n \n \n arg_str = \", \".join(\n \"%s=%r\" % (a, getattr(inst, a)) for a in attrs if hasattr(inst, a))\n repr_str = \"%s(%s)\" % (inst.__class__.__name__, arg_str)\n return repr_str", "docstring": "Create a repr from an instance of a class\n\nArgs:\ninst: The class instance we are generating a repr of\nattrs: The attributes that should appear in the repr", "source": "juraj-google-style"}
121{"code": "def set_category(self, category):\n \n \n \n if isinstance(category, Category):\n name = category.name\n else:\n name = category\n self.find(\"category\").text = name", "docstring": "Set package category\n\nArgs:\ncategory: String of an existing category's name, or a\nCategory object.", "source": "juraj-google-style"}
122{"code": "def convert_relu(params, w_name, scope_name, inputs, layers, weights, names):\n print('Converting relu ...')\n if (names == 'short'):\n tf_name = ('RELU' + random_string(4))\n elif (names == 'keep'):\n tf_name = w_name\n else:\n tf_name = (w_name + str(random.random()))\n relu = keras.layers.Activation('relu', name=tf_name)\n layers[scope_name] = relu(layers[inputs[0]])", "docstring": "Convert relu layer.\n\nArgs:\nparams: dictionary with layer parameters\nw_name: name prefix in state_dict\nscope_name: pytorch scope name\ninputs: pytorch node inputs\nlayers: dictionary with keras tensors\nweights: pytorch state_dict\nnames: use short names for keras layers", "source": "codesearchnet"}
123{"code": "def _sideral(date, longitude=0.0, model='mean', eop_correction=True, terms=106):\n t = date.change_scale('UT1').julian_century\n theta = (((67310.54841 + (((876600 * 3600) + 8640184.812866) * t)) + (0.093104 * (t ** 2))) - (6.2e-06 * (t ** 3)))\n theta /= 240.0\n if (model == 'apparent'):\n theta += equinox(date, eop_correction, terms)\n theta += longitude\n theta %= 360.0\n return theta", "docstring": "Get the sideral time at a defined date\n\nArgs:\ndate (Date):\nlongitude (float): Longitude of the observer (in degrees)\nEast positive/West negative.\nmodel (str): 'mean' or 'apparent' for GMST and GAST respectively\nReturn:\nfloat: Sideral time in degrees\n\nGMST: Greenwich Mean Sideral Time\nLST: Local Sideral Time (Mean)\nGAST: Greenwich Apparent Sideral Time", "source": "codesearchnet"}
124{"code": "def read_field_h5(xdmf_file, fieldname, snapshot, header=None):\n if (header is None):\n (header, xdmf_root) = read_geom_h5(xdmf_file, snapshot)\n else:\n xdmf_root = xmlET.parse(str(xdmf_file)).getroot()\n npc = (header['nts'] \n flds = np.zeros(_flds_shape(fieldname, header))\n data_found = False\n for elt_subdomain in xdmf_root[0][0][snapshot].findall('Grid'):\n ibk = int(elt_subdomain.get('Name').startswith('meshYang'))\n for data_attr in elt_subdomain.findall('Attribute'):\n if (data_attr.get('Name') != fieldname):\n continue\n (icore, fld) = _get_field(xdmf_file, data_attr.find('DataItem'))\n fld = fld.T\n shp = fld.shape\n if ((shp[(- 1)] == 1) and (header['nts'][0] == 1)):\n fld = fld.reshape((shp[0], 1, shp[1], shp[2]))\n if (header['rcmb'] < 0):\n fld = fld[((2, 0, 1), ...)]\n elif (shp[(- 1)] == 1):\n fld = fld.reshape((shp[0], shp[1], 1, shp[2]))\n if (header['rcmb'] < 0):\n fld = fld[((0, 2, 1), ...)]\n elif (header['nts'][1] == 1):\n fld = fld.reshape((1, shp[0], 1, shp[1]))\n ifs = [(((icore \n if header['zp']:\n fld = fld[(:, :, :, :(- 1))]\n flds[(:, ifs[0]:((ifs[0] + npc[0]) + header['xp']), ifs[1]:((ifs[1] + npc[1]) + header['yp']), ifs[2]:(ifs[2] + npc[2]), ibk)] = fld\n data_found = True\n flds = _post_read_flds(flds, header)\n return ((header, flds) if data_found else None)", "docstring": "Extract field data from hdf5 files.\n\nArgs:\nxdmf_file (:class:`pathlib.Path`): path of the xdmf file.\nfieldname (str): name of field to extract.\nsnapshot (int): snapshot number.\nheader (dict): geometry information.\nReturns:\n(dict, numpy.array): geometry information and field data. None\nis returned if data is unavailable.", "source": "codesearchnet"}
125{"code": "def populate_settings_dir(force: bool = False) -> bool:\n \n res = False\n if _default_settings_path == _settings_path:\n return res\n\n for src in list(_default_settings_path.glob('**/*.json')):\n dest = _settings_path / src.relative_to(_default_settings_path)\n if not force and dest.exists():\n continue\n res = True\n dest.parent.mkdir(parents=True, exist_ok=True)\n shutil.copy(src, dest)\n return res", "docstring": "Populate settings directory with default settings files\n\nArgs:\nforce: if ``True``, replace existing settings files with default ones\n\nReturns:\n``True`` if any files were copied and ``False`` otherwise", "source": "juraj-google-style"}
126{"code": "def save(self, out_path):\n \n\n out = {\n 'selectors': [str(x) for x in self.selectors],\n 'trace': [{'stream': str(DataStream.FromEncoded(x.stream)), 'time': x.raw_time, 'value': x.value, 'reading_id': x.reading_id} for x in self]\n }\n\n with open(out_path, \"wb\") as outfile:\n json.dump(out, outfile, indent=4)", "docstring": "Save an ascii representation of this simulation trace.\n\nArgs:\nout_path (str): The output path to save this simulation trace.", "source": "juraj-google-style"}
127{"code": "def get(self, key):\n \n\n \n value = self.child_datastore.get(key)\n return self.deserializedValue(value)", "docstring": "Return the object named by key or None if it does not exist.\nRetrieves the value from the ``child_datastore``, and de-serializes\nit on the way out.\n\nArgs:\nkey: Key naming the object to retrieve\n\nReturns:\nobject or None", "source": "juraj-google-style"}
128{"code": "def order_for(self, qubits: Iterable[raw_types.Qid]) -> Tuple[(raw_types.Qid, ...)]:\n return self._explicit_func(qubits)", "docstring": "Returns a qubit tuple ordered corresponding to the basis.\n\nArgs:\nqubits: Qubits that should be included in the basis. (Additional\nqubits may be added into the output by the basis.)\n\nReturns:\nA tuple of qubits in the same order that their single-qubit\nmatrices would be passed into `np.kron` when producing a matrix for\nthe entire system.", "source": "codesearchnet"}
129{"code": "def threat(self, name, owner=None, **kwargs):\n return Threat(self.tcex, name, owner=owner, **kwargs)", "docstring": "Create the Threat TI object.\n\nArgs:\nowner:\nname:\n**kwargs:\n\nReturn:", "source": "codesearchnet"}
130{"code": "def angles( self ):\n \n ( a, b, c ) = [ row for row in self.matrix ]\n return [ angle( b, c ), angle( a, c ), angle( a, b ) ]", "docstring": "The cell angles (in degrees).\n\nArgs:\nNone\n\nReturns:\n(list(alpha,beta,gamma)): The cell angles.", "source": "juraj-google-style"}
131{"code": "def add_user(\n self, user, first_name=None, last_name=None, email=None, password=None):\n \n self.service.add_user(\n user, first_name, last_name, email, password,\n self.url_prefix, self.auth, self.session, self.session_send_opts)", "docstring": "Add a new user.\n\nArgs:\nuser (string): User name.\nfirst_name (optional[string]): User's first name. Defaults to None.\nlast_name (optional[string]): User's last name. Defaults to None.\nemail: (optional[string]): User's email address. Defaults to None.\npassword: (optional[string]): User's password. Defaults to None.\n\nRaises:\nrequests.HTTPError on failure.", "source": "juraj-google-style"}
132{"code": "def add(self, other, axis=\"columns\", level=None, fill_value=None):\n \n return self._binary_op(\n \"add\", other, axis=axis, level=level, fill_value=fill_value\n )", "docstring": "Add this DataFrame to another or a scalar/list.\n\nArgs:\nother: What to add this this DataFrame.\naxis: The axis to apply addition over. Only applicaable to Series\nor list 'other'.\nlevel: A level in the multilevel axis to add over.\nfill_value: The value to fill NaN.\n\nReturns:\nA new DataFrame with the applied addition.", "source": "juraj-google-style"}
133{"code": "def on_value_event(self, event):\n \n if not event.summary.value:\n logger.warn(\"The summary of the event lacks a value.\")\n return\n\n \n \n watch_key = event.summary.value[0].node_name\n if not watch_key.endswith(constants.DEBUG_NUMERIC_SUMMARY_SUFFIX):\n \n \n return\n\n \n \n \n node_name_and_output_slot = watch_key[\n :-len(constants.DEBUG_NUMERIC_SUMMARY_SUFFIX)]\n\n shape = tensor_util.make_ndarray(event.summary.value[0].tensor).shape\n if (len(shape) != 1 or\n shape[0] < constants.MIN_DEBUG_NUMERIC_SUMMARY_TENSOR_LENGTH):\n logger.warn(\"Health-pill tensor either lacks a dimension or is \"\n \"shaped incorrectly: %s\" % shape)\n return\n\n match = re.match(r\"^(.*):(\\d+)$\", node_name_and_output_slot)\n if not match:\n logger.warn(\n (\"A event with a health pill has an invalid node name and output \"\n \"slot combination, (i.e., an unexpected debug op): %r\"),\n node_name_and_output_slot)\n return\n\n if self._session_run_index >= 0:\n event.step = self._session_run_index\n else:\n \n \n \n event.step = int(time.time() * 1e6)\n\n \n \n self._events_writer_manager.write_event(event)\n\n alert = numerics_alert.extract_numerics_alert(event)\n if self._numerics_alert_callback and alert:\n self._numerics_alert_callback(alert)", "docstring": "Records the summary values based on an updated message from the debugger.\n\nLogs an error message if writing the event to disk fails.\n\nArgs:\nevent: The Event proto to be processed.", "source": "juraj-google-style"}
134{"code": "def set_instrument(self, instrument=None):\n \n if instrument is None:\n instrument = self.tester\n\n if instrument in [\"arbin\", \"arbin_res\"]:\n self._set_arbin()\n self.tester = \"arbin\"\n\n elif instrument == \"arbin_sql\":\n self._set_arbin_sql()\n self.tester = \"arbin\"\n\n elif instrument == \"arbin_experimental\":\n self._set_arbin_experimental()\n self.tester = \"arbin\"\n\n elif instrument in [\"pec\", \"pec_csv\"]:\n self._set_pec()\n self.tester = \"pec\"\n\n elif instrument in [\"biologics\", \"biologics_mpr\"]:\n self._set_biologic()\n self.tester = \"biologic\"\n\n elif instrument == \"custom\":\n self._set_custom()\n self.tester = \"custom\"\n\n else:\n raise Exception(f\"option does not exist: '{instrument}'\")", "docstring": "Set the instrument (i.e. tell cellpy the file-type you use).\n\nArgs:\ninstrument: (str) in [\"arbin\", \"bio-logic-csv\", \"bio-logic-bin\",...]\n\nSets the instrument used for obtaining the data (i.e. sets fileformat)", "source": "juraj-google-style"}
135{"code": "def _prefer_static_concat_shape(first_shape, second_shape_int_list):\n second_shape_int_list_static = [tensor_util.constant_value(s) for s in second_shape_int_list]\n if isinstance(first_shape, tensor_shape.TensorShape) and all((s is not None for s in second_shape_int_list_static)):\n return first_shape.concatenate(second_shape_int_list_static)\n return array_ops.concat([first_shape, second_shape_int_list], axis=0)", "docstring": "Concatenate a shape with a list of integers as statically as possible.\n\nArgs:\nfirst_shape: `TensorShape` or `Tensor` instance. If a `TensorShape`,\n`first_shape.is_fully_defined()` must return `True`.\nsecond_shape_int_list: `list` of scalar integer `Tensor`s.\n\nReturns:\n`Tensor` representing concatenating `first_shape` and\n`second_shape_int_list` as statically as possible.", "source": "github-repos"}
136{"code": "def partial_derivative(self, X, y=0):\n \n self.check_fit()\n\n U, V = self.split_matrix(X)\n\n if self.theta == 0:\n return V\n\n else:\n num = np.multiply(self._g(U), self._g(V)) + self._g(U)\n den = np.multiply(self._g(U), self._g(V)) + self._g(1)\n return (num / den) - y", "docstring": "Compute partial derivative :math:`C(u|v)` of cumulative distribution.\n\nArgs:\nX: `np.ndarray`\ny: `float`\n\nReturns:\nnp.ndarray", "source": "juraj-google-style"}
137{"code": "def processes(self, processes):\n if (self._processes > 1):\n self._pool.close()\n self._pool.join()\n self._pool = multiprocessing.Pool(processes)\n else:\n self._pool = None\n self._logger.log('debug', 'Number of processes set to {}'.format(processes))", "docstring": "Set the number of concurrent processes the ABC will utilize for\nfitness function evaluation; if <= 1, single process is used\n\nArgs:\nprocesses (int): number of concurrent processes", "source": "codesearchnet"}
138{"code": "def post_process_semantic_segmentation(self, outputs, target_sizes: Optional[list[tuple]]=None):\n logits = outputs.logits\n if target_sizes is not None:\n if len(logits) != len(target_sizes):\n raise ValueError('Make sure that you pass in as many target sizes as the batch dimension of the logits')\n semantic_segmentation = []\n for idx in range(len(logits)):\n resized_logits = torch.nn.functional.interpolate(logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode='bilinear', align_corners=False)\n semantic_map = resized_logits[0].argmax(dim=0)\n semantic_segmentation.append(semantic_map)\n else:\n semantic_segmentation = logits.argmax(dim=1)\n semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]\n return semantic_segmentation", "docstring": "Converts the output of [`MobileNetV2ForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.\n\nArgs:\noutputs ([`MobileNetV2ForSemanticSegmentation`]):\nRaw outputs of the model.\ntarget_sizes (`List[Tuple]` of length `batch_size`, *optional*):\nList of tuples corresponding to the requested final size (height, width) of each prediction. If unset,\npredictions will not be resized.\n\nReturns:\nsemantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic\nsegmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is\nspecified). Each entry of each `torch.Tensor` correspond to a semantic class id.", "source": "github-repos"}
139{"code": "def __enter__(self) -> str:\n if self._name is None and self._values is not None:\n raise ValueError('At least one of name (%s) and default_name (%s) must be provided.' % (self._name, self._default_name))\n g = get_default_graph()\n if self._values and (not g.building_function):\n g_from_inputs = _get_graph_from_inputs(self._values)\n if g_from_inputs is not g:\n g = g_from_inputs\n self._g_manager = g.as_default()\n self._g_manager.__enter__()\n else:\n self._g_manager = None\n else:\n self._g_manager = None\n try:\n self._name_scope = g.name_scope(self._name)\n return self._name_scope.__enter__()\n except:\n if self._g_manager is not None:\n self._g_manager.__exit__(*sys.exc_info())\n raise", "docstring": "Start the scope block.\n\nReturns:\nThe scope name.\n\nRaises:\nValueError: if neither `name` nor `default_name` is provided\nbut `values` are.", "source": "github-repos"}
140{"code": "def stop_workflow(config, *, names=None):\n jobs = list_jobs(config, filter_by_type=JobType.Workflow)\n if (names is not None):\n filtered_jobs = []\n for job in jobs:\n if ((job.id in names) or (job.name in names) or (job.workflow_id in names)):\n filtered_jobs.append(job)\n else:\n filtered_jobs = jobs\n success = []\n failed = []\n for job in filtered_jobs:\n client = Client(SignalConnection(**config.signal, auto_connect=True), request_key=job.workflow_id)\n if client.send(Request(action='stop_workflow')).success:\n success.append(job)\n else:\n failed.append(job)\n return (success, failed)", "docstring": "Stop one or more workflows.\n\nArgs:\nconfig (Config): Reference to the configuration object from which the\nsettings for the workflow are retrieved.\nnames (list): List of workflow names, workflow ids or workflow job ids for the\nworkflows that should be stopped. If all workflows should be\nstopped, set it to None.\n\nReturns:\ntuple: A tuple of the workflow jobs that were successfully stopped and the ones\nthat could not be stopped.", "source": "codesearchnet"}
141{"code": "async def verify_chain_of_trust(chain):\n \n log_path = os.path.join(chain.context.config[\"task_log_dir\"], \"chain_of_trust.log\")\n scriptworker_log = logging.getLogger('scriptworker')\n with contextual_log_handler(\n chain.context, path=log_path, log_obj=scriptworker_log,\n formatter=AuditLogFormatter(\n fmt=chain.context.config['log_fmt'],\n datefmt=chain.context.config['log_datefmt'],\n )\n ):\n try:\n \n await build_task_dependencies(chain, chain.task, chain.name, chain.task_id)\n \n await download_cot(chain)\n \n verify_cot_signatures(chain)\n \n await download_cot_artifacts(chain)\n \n task_count = await verify_task_types(chain)\n check_num_tasks(chain, task_count)\n \n await verify_worker_impls(chain)\n await trace_back_to_tree(chain)\n except (BaseDownloadError, KeyError, AttributeError) as exc:\n log.critical(\"Chain of Trust verification error!\", exc_info=True)\n if isinstance(exc, CoTError):\n raise\n else:\n raise CoTError(str(exc))\n log.info(\"Good.\")", "docstring": "Build and verify the chain of trust.\n\nArgs:\nchain (ChainOfTrust): the chain we're operating on\n\nRaises:\nCoTError: on failure", "source": "juraj-google-style"}
142{"code": "def async_noop(name=None):\n with ops.name_scope(name, 'async_noop') as name:\n cond_init_value = constant_op.constant(False, name='cond_init_value')\n func_graph_signature = [tensor_spec.TensorSpec(shape=(), dtype=dtypes.bool)]\n cond_graph = func_graph_module.func_graph_from_py_func('cond_graph', lambda x: x, [cond_init_value], {}, signature=func_graph_signature, func_graph=util.WhileCondFuncGraph('cond_graph', collections=ops.get_default_graph()._collections), add_control_dependencies=False)\n body_graph = func_graph_module.func_graph_from_py_func('body_graph', lambda x: x, [cond_init_value], {}, signature=func_graph_signature, func_graph=util.WhileBodyFuncGraph('body_graph', collections=ops.get_default_graph()._collections), add_control_dependencies=False)\n while_op, _ = util.get_op_and_outputs(gen_functional_ops._while([cond_init_value], util.create_new_tf_function(cond_graph), util.create_new_tf_function(body_graph), output_shapes=[[]], name=name))\n util.maybe_set_lowering_attr(while_op, lower_using_switch_merge=False)\n return while_op", "docstring": "Returns a no-op that is implemented as an async kernel.\n\nThis operation may be useful to implement \"aggressive inter-op parallelism\"\nbecause it will cause any immediate downstream operations to be scheduled\non different threads.\n\nArgs:\nname: The name of the operation.", "source": "github-repos"}
143{"code": "def splitdrive(self, path):\n \n path = make_string_path(path)\n if self.is_windows_fs:\n if len(path) >= 2:\n path = self.normcase(path)\n sep = self._path_separator(path)\n \n \n if sys.version_info >= (2, 7, 8):\n if (path[0:2] == sep * 2) and (\n path[2:3] != sep):\n \n \n sep_index = path.find(sep, 2)\n if sep_index == -1:\n return path[:0], path\n sep_index2 = path.find(sep, sep_index + 1)\n if sep_index2 == sep_index + 1:\n return path[:0], path\n if sep_index2 == -1:\n sep_index2 = len(path)\n return path[:sep_index2], path[sep_index2:]\n if path[1:2] == self._matching_string(path, ':'):\n return path[:2], path[2:]\n return path[:0], path", "docstring": "Splits the path into the drive part and the rest of the path.\n\nTaken from Windows specific implementation in Python 3.5\nand slightly adapted.\n\nArgs:\npath: the full path to be splitpath.\n\nReturns:\nA tuple of the drive part and the rest of the path, or of\nan empty string and the full path if drive letters are\nnot supported or no drive is present.", "source": "juraj-google-style"}
144{"code": "def __init__(self, symbol, precedence, associative=False):\n \n self.symbol = symbol\n self.precedence = precedence\n self.associative = associative", "docstring": "Constructor.\n\nArgs:\nsymbol: The character which represents this operation, such as '+' for\naddition.\nprecedence: Operator precedence. This will determine where parentheses\nare used.\nassociative: If true, the order of the operands does not matter.", "source": "juraj-google-style"}
145{"code": "def copy(self, source_file_names, destination_file_names):\n if not len(source_file_names) == len(destination_file_names):\n message = 'Unable to copy unequal number of sources and destinations'\n raise BeamIOError(message)\n src_dest_pairs = list(zip(source_file_names, destination_file_names))\n return s3io.S3IO(options=self._options).copy_paths(src_dest_pairs)", "docstring": "Recursively copy the file tree from the source to the destination\n\nArgs:\nsource_file_names: list of source file objects that needs to be copied\ndestination_file_names: list of destination of the new object\n\nRaises:\n``BeamIOError``: if any of the copy operations fail", "source": "github-repos"}
146{"code": "def highlight(text: str, color_code: int, bold: bool=False) -> str:\n \n return '{}\\033[{}m{}\\033[0m'.format(\n '\\033[1m' if bold else '',\n color_code,\n text,)", "docstring": "Wraps the given string with terminal color codes.\n\nArgs:\ntext: The content to highlight.\ncolor_code: The color to highlight with, e.g. 'shelltools.RED'.\nbold: Whether to bold the content in addition to coloring.\n\nReturns:\nThe highlighted string.", "source": "juraj-google-style"}
147{"code": "def can_convert_arrays(arrays):\n return all(tree.flatten(tree.map_structure(array_slicing.can_slice_array, arrays)))", "docstring": "Check if array like-inputs can be handled by `ArrayDataAdapter`\n\nArgs:\ninputs: Structure of `Tensor`s, NumPy arrays, or tensor-like.\n\nReturns:\n`True` if `arrays` can be handled by `ArrayDataAdapter`, `False`\notherwise.", "source": "github-repos"}
148{"code": "def readDivPressure(fileName):\n try:\n df = pandas.read_csv(fileName, sep=None, engine='python')\n pandasformat = True\n except ValueError:\n pandasformat = False\n df.columns = ['site', 'divPressureValue']\n scaleFactor = max(df['divPressureValue'].abs())\n if (scaleFactor > 0):\n df['divPressureValue'] = [(x / scaleFactor) for x in df['divPressureValue']]\n assert (len(df['site'].tolist()) == len(set(df['site'].tolist()))), 'There is at least one non-unique site in {0}'.format(fileName)\n assert (max(df['divPressureValue'].abs()) <= 1), 'The scaling produced a diversifying pressure value with an absolute value greater than one.'\n sites = df['site'].tolist()\n divPressure = {}\n for r in sites:\n divPressure[r] = df[(df['site'] == r)]['divPressureValue'].tolist()[0]\n return divPressure", "docstring": "Reads in diversifying pressures from some file.\n\nScale diversifying pressure values so absolute value of the max value is 1,\nunless all values are zero.\n\nArgs:\n`fileName` (string or readable file-like object)\nFile holding diversifying pressure values. Can be\ncomma-, space-, or tab-separated file. The first column\nis the site (consecutively numbered, sites starting\nwith one) and the second column is the diversifying pressure values.\n\nReturns:\n`divPressure` (dict keyed by ints)\n`divPressure[r][v]` is the diversifying pressure value of site `r`.", "source": "codesearchnet"}
149{"code": "def create_per_test_excerpt(self, current_test_info):\n \n self.pause()\n dest_path = current_test_info.output_path\n utils.create_dir(dest_path)\n self._ad.log.debug('AdbLog excerpt location: %s', dest_path)\n shutil.move(self.adb_logcat_file_path, dest_path)\n self.resume()", "docstring": "Convenient method for creating excerpts of adb logcat.\n\nTo use this feature, call this method at the end of: `setup_class`,\n`teardown_test`, and `teardown_class`.\n\nThis moves the current content of `self.adb_logcat_file_path` to the\nlog directory specific to the current test.\n\nArgs:\ncurrent_test_info: `self.current_test_info` in a Mobly test.", "source": "juraj-google-style"}
150{"code": "def _reverse_seq(input_seq, lengths):\n if lengths is None:\n return list(reversed(input_seq))\n flat_input_seq = tuple((nest.flatten(input_) for input_ in input_seq))\n flat_results = [[] for _ in range(len(input_seq))]\n for sequence in zip(*flat_input_seq):\n input_shape = tensor_shape.unknown_shape(rank=sequence[0].get_shape().rank)\n for input_ in sequence:\n input_shape.assert_is_compatible_with(input_.get_shape())\n input_.set_shape(input_shape)\n s_joined = array_ops_stack.stack(sequence)\n s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1)\n result = array_ops_stack.unstack(s_reversed)\n for r, flat_result in zip(result, flat_results):\n r.set_shape(input_shape)\n flat_result.append(r)\n results = [nest.pack_sequence_as(structure=input_, flat_sequence=flat_result) for input_, flat_result in zip(input_seq, flat_results)]\n return results", "docstring": "Reverse a list of Tensors up to specified lengths.\n\nArgs:\ninput_seq: Sequence of seq_len tensors of dimension (batch_size, n_features)\nor nested tuples of tensors.\nlengths: A `Tensor` of dimension batch_size, containing lengths for each\nsequence in the batch. If \"None\" is specified, simply reverses the list.\n\nReturns:\ntime-reversed sequence", "source": "github-repos"}
151{"code": "def prepare_for_tokenization(self, artists: str, genres: str, lyrics: str, is_split_into_words: bool=False) -> Tuple[str, str, str, Dict[str, Any]]:\n for idx in range(len(self.version)):\n if self.version[idx] == 'v3':\n artists[idx] = artists[idx].lower()\n genres[idx] = [genres[idx].lower()]\n else:\n artists[idx] = self._normalize(artists[idx]) + '.v2'\n genres[idx] = [self._normalize(genre) + '.v2' for genre in genres[idx].split('_')]\n if self.version[0] == 'v2':\n self.out_of_vocab = regex.compile('[^A-Za-z0-9.,:;!?\\\\-\\'\\\\\"()\\\\[\\\\] \\\\t\\\\n]+')\n vocab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\\'\"()[] \\t\\n'\n self.vocab = {vocab[index]: index + 1 for index in range(len(vocab))}\n self.vocab['<unk>'] = 0\n self.n_vocab = len(vocab) + 1\n self.lyrics_encoder = self.vocab\n self.lyrics_decoder = {v: k for k, v in self.vocab.items()}\n self.lyrics_decoder[0] = ''\n else:\n self.out_of_vocab = regex.compile('[^A-Za-z0-9.,:;!?\\\\-+\\'\\\\\"()\\\\[\\\\] \\\\t\\\\n]+')\n lyrics = self._run_strip_accents(lyrics)\n lyrics = lyrics.replace('\\\\', '\\n')\n lyrics = (self.out_of_vocab.sub('', lyrics), [], [])\n return (artists, genres, lyrics)", "docstring": "Performs any necessary transformations before tokenization.\n\nArgs:\nartist (`str`):\nThe artist name to prepare. This will mostly lower the string\ngenres (`str`):\nThe genre name to prepare. This will mostly lower the string.\nlyrics (`str`):\nThe lyrics to prepare.\nis_split_into_words (`bool`, *optional*, defaults to `False`):\nWhether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the\ntokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)\nwhich it will tokenize. This is useful for NER or token classification.", "source": "github-repos"}
152{"code": "def depthwise_conv2d(x, depthwise_kernel, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1)):\n if data_format is None:\n data_format = image_data_format()\n if data_format not in {'channels_first', 'channels_last'}:\n raise ValueError('Unknown data_format: ' + str(data_format))\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n x = nn.depthwise_conv2d(x, depthwise_kernel, strides=strides, padding=padding, rate=dilation_rate, data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = array_ops.transpose(x, (0, 3, 1, 2))\n return x", "docstring": "2D convolution with separable filters.\n\nArgs:\nx: input tensor\ndepthwise_kernel: convolution kernel for the depthwise convolution.\nstrides: strides tuple (length 2).\npadding: string, `\"same\"` or `\"valid\"`.\ndata_format: string, `\"channels_last\"` or `\"channels_first\"`.\ndilation_rate: tuple of integers,\ndilation rates for the separable convolution.\n\nReturns:\nOutput tensor.\n\nRaises:\nValueError: if `data_format` is neither `channels_last` or\n`channels_first`.", "source": "github-repos"}
153{"code": "def pack(self, tensors):\n self._assert_eager()\n if len(tensors) != len(self.components):\n raise ValueError('Creating a parallel tensor requires one tensor per component. Got {} but was expecting {}.'.format(len(tensors), len(self.components)))\n with ops.device(None):\n tensors = variable_utils.convert_variables_to_tensors(tensors)\n return nest.map_structure(self._pack_tensor, *tensors, expand_composites=True)", "docstring": "Create a tensor on the parallel device from a sequence of tensors.\n\nArgs:\ntensors: A list of tensors, one per device in `self.components`. The list\ncan contain composite tensors and nests (lists, dicts, etc. supported by\n`tf.nest`) with the same structure for each device, but every component\nof nests must already be a `tf.Tensor` or composite. Passing\n`tf.Variable` objects reads their value, it does not share a mutable\nreference between the packed and unpacked forms.\n\nReturns:\nA tensor placed on the ParallelDevice. For nested structures, returns a\nsingle structure containing tensors placed on the ParallelDevice (same\nstructure as each component of `tensors`).\n\nRaises:\nValueError: If the length of `tensors` does not match the number of\ncomponent devices, or if there are non-tensor inputs.", "source": "github-repos"}
154{"code": "def decode_event(self, log_topics, log_data):\n if ((not len(log_topics)) or (log_topics[0] not in self.event_data)):\n raise ValueError('Unknown log type')\n event_id_ = log_topics[0]\n event = self.event_data[event_id_]\n unindexed_types = [type_ for (type_, indexed) in zip(event['types'], event['indexed']) if (not indexed)]\n unindexed_args = decode_abi(unindexed_types, log_data)\n indexed_count = 1\n result = {}\n for (name, type_, indexed) in zip(event['names'], event['types'], event['indexed']):\n if indexed:\n topic_bytes = utils.zpad(utils.encode_int(log_topics[indexed_count]), 32)\n indexed_count += 1\n value = decode_single(process_type(type_), topic_bytes)\n else:\n value = unindexed_args.pop(0)\n result[name] = value\n result['_event_type'] = utils.to_string(event['name'])\n return result", "docstring": "Return a dictionary representation the log.\n\nNote:\nThis function won't work with anonymous events.\n\nArgs:\nlog_topics (List[bin]): The log's indexed arguments.\nlog_data (bin): The encoded non-indexed arguments.", "source": "codesearchnet"}
155{"code": "def write(self, string):\n (x, y) = self._normalizeCursor(*self._cursor)\n (width, height) = self.get_size()\n wrapper = _textwrap.TextWrapper(initial_indent=(' ' * x), width=width)\n writeLines = []\n for line in string.split('\\n'):\n if line:\n writeLines += wrapper.wrap(line)\n wrapper.initial_indent = ''\n else:\n writeLines.append([])\n for line in writeLines:\n (x, y) = self._normalizeCursor(x, y)\n self.draw_str(x, y, line[x:], self._fg, self._bg)\n y += 1\n x = 0\n y -= 1\n self._cursor = (x, y)", "docstring": "This method mimics basic file-like behaviour.\n\nBecause of this method you can replace sys.stdout or sys.stderr with\na :any:`Console` or :any:`Window` instance.\n\nThis is a convoluted process and behaviour seen now can be excepted to\nchange on later versions.\n\nArgs:\nstring (Text): The text to write out.\n\n.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`", "source": "codesearchnet"}
156{"code": "def projects(self, term, field=None, **kwargs):\n \n params = kwargs\n params['q'] = term\n if field:\n params['f'] = self._FIELD_MAP[field]\n else:\n params['f'] = 'pro.t'\n baseuri = self._BASE_URI + 'projects'\n res = self.session.get(baseuri, params=params)\n self.handle_http_error(res)\n return res", "docstring": "Search for projects. Defaults to project_title. Other fields\nare:\nproject_reference\nproject_abstract\n\nArgs:\nterm (str): Term to search for.\nkwargs (dict): additional keywords passed into\nrequests.session.get params keyword.", "source": "juraj-google-style"}
157{"code": "def _on_status_message(self, sequence, topic, message):\n self._logger.debug(('Received message on (topic=%s): %s' % (topic, message)))\n try:\n conn_key = self._find_connection(topic)\n except ArgumentError:\n self._logger.warn('Dropping message that does not correspond with a known connection, message=%s', message)\n return\n if messages.ConnectionResponse.matches(message):\n if (self.name != message['client']):\n self._logger.debug('Connection response received for a different client, client=%s, name=%s', message['client'], self.name)\n return\n self.conns.finish_connection(conn_key, message['success'], message.get('failure_reason', None))\n else:\n self._logger.warn('Dropping message that did not correspond with a known schema, message=%s', message)", "docstring": "Process a status message received\n\nArgs:\nsequence (int): The sequence number of the packet received\ntopic (string): The topic this message was received on\nmessage (dict): The message itself", "source": "codesearchnet"}
158{"code": "def to_css(self):\n if (self.a == 1.0):\n return ('rgb(%d, %d, %d)' % (self.r, self.g, self.b))\n else:\n return ('rgba(%d, %d, %d, %s)' % (self.r, self.g, self.b, self.a))", "docstring": "Generate the CSS representation of this RGB color.\n\nReturns:\nstr, ``\"rgb(...)\"`` or ``\"rgba(...)\"``", "source": "codesearchnet"}
159{"code": "def _estimate_step_duration(self, current, now):\n if current:\n if self._time_after_first_step is not None and current > 1:\n time_per_unit = (now - self._time_after_first_step) / (current - 1)\n else:\n time_per_unit = (now - self._start) / current\n if current == 1:\n self._time_after_first_step = now\n return time_per_unit\n else:\n return 0", "docstring": "Estimate the duration of a single step.\n\nGiven the step number `current` and the corresponding time `now`\nthis function returns an estimate for how long a single step\ntakes. If this is called before one step has been completed\n(i.e. `current == 0`) then zero is given as an estimate. The duration\nestimate ignores the duration of the (assumed to be non-representative)\nfirst step for estimates when more steps are available (i.e. `current>1`).\nArgs:\ncurrent: Index of current step.\nnow: The current time.\nReturns: Estimate of the duration of a single step.", "source": "github-repos"}
160{"code": "def process_rewards(self, rewards):\n \n\n min_reward, max_reward = self.reward_range\n\n \n rewards = np.clip(rewards, min_reward, max_reward)\n \n rewards = np.around(rewards, decimals=0).astype(np.int64)\n return rewards", "docstring": "Clips, rounds, and changes to integer type.\n\nArgs:\nrewards: numpy array of raw (float) rewards.\n\nReturns:\nprocessed_rewards: numpy array of np.int64", "source": "juraj-google-style"}
161{"code": "def _filter_top_k(x, k):\n _, top_k_idx = ops.top_k(x, k)\n top_k_mask = ops.sum(ops.one_hot(top_k_idx, ops.shape(x)[-1], axis=-1), axis=-2)\n return x * top_k_mask + NEG_INF * (1 - top_k_mask)", "docstring": "Filters top-k values in the last dim of x and set the rest to NEG_INF.\n\nUsed for computing top-k prediction values in dense labels (which has the\nsame shape as predictions) for recall and precision top-k metrics.\n\nArgs:\nx: tensor with any dimensions.\nk: the number of values to keep.\n\nReturns:\ntensor with same shape and dtype as x.", "source": "github-repos"}
162{"code": "def _get_nan_block_id(partition_class, n_row=1, n_col=1, transpose=False):\n global _NAN_BLOCKS\n if transpose:\n (n_row, n_col) = (n_col, n_row)\n shape = (n_row, n_col)\n if (shape not in _NAN_BLOCKS):\n arr = np.tile(np.array(np.NaN), shape)\n _NAN_BLOCKS[shape] = partition_class.put(pandas.DataFrame(data=arr))\n return _NAN_BLOCKS[shape]", "docstring": "A memory efficient way to get a block of NaNs.\n\nArgs:\npartition_class (BaseFramePartition): The class to use to put the object\nin the remote format.\nn_row(int): The number of rows.\nn_col(int): The number of columns.\ntranspose(bool): If true, swap rows and columns.\nReturns:\nObjectID of the NaN block.", "source": "codesearchnet"}
163{"code": "def is_user_in_group(self, user, group):\n \n search_url = \"%s/%s/%s/%s/%s\" % (self.url, \"group\", group,\n \"user\", user)\n response = self.jss.get(search_url)\n \n length = len(response)\n result = False\n if length == 1:\n \n pass\n elif length == 2:\n if response.findtext(\"ldap_user/username\") == user:\n if response.findtext(\"ldap_user/is_member\") == \"Yes\":\n result = True\n elif len(response) >= 2:\n raise JSSGetError(\"Unexpected response.\")\n return result", "docstring": "Test for whether a user is in a group.\n\nThere is also the ability in the API to test for whether\nmultiple users are members of an LDAP group, but you should just\ncall is_user_in_group over an enumerated list of users.\n\nArgs:\nuser: String username.\ngroup: String group name.\n\nReturns bool.", "source": "juraj-google-style"}
164{"code": "def _GetAccountsData(self, metadata_dict):\n (instance_data, project_data) = self._GetInstanceAndProjectAttributes(metadata_dict)\n valid_keys = [instance_data.get('sshKeys'), instance_data.get('ssh-keys')]\n block_project = instance_data.get('block-project-ssh-keys', '').lower()\n if ((block_project != 'true') and (not instance_data.get('sshKeys'))):\n valid_keys.append(project_data.get('ssh-keys'))\n valid_keys.append(project_data.get('sshKeys'))\n accounts_data = '\\n'.join([key for key in valid_keys if key])\n return self._ParseAccountsData(accounts_data)", "docstring": "Get the user accounts specified in metadata server contents.\n\nArgs:\nmetadata_dict: json, the deserialized contents of the metadata server.\n\nReturns:\ndict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.", "source": "codesearchnet"}
165{"code": "def quad_genz_keister_24(order):\n order = sorted(GENZ_KEISTER_24.keys())[order]\n (abscissas, weights) = GENZ_KEISTER_24[order]\n abscissas = numpy.array(abscissas)\n weights = numpy.array(weights)\n weights /= numpy.sum(weights)\n abscissas *= numpy.sqrt(2)\n return (abscissas, weights)", "docstring": "Hermite Genz-Keister 24 rule.\n\nArgs:\norder (int):\nThe quadrature order. Must be in the interval (0, 8).\n\nReturns:\n(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):\nAbscissas and weights\n\nExamples:\n>>> abscissas, weights = quad_genz_keister_24(1)\n>>> print(numpy.around(abscissas, 4))\n[-1.7321 0. 1.7321]\n>>> print(numpy.around(weights, 4))\n[0.1667 0.6667 0.1667]", "source": "codesearchnet"}
166{"code": "def preemphasis(signal, shift=1, cof=0.98):\n rolled_signal = np.roll(signal, shift)\n return (signal - (cof * rolled_signal))", "docstring": "preemphasising on the signal.\n\nArgs:\nsignal (array): The input signal.\nshift (int): The shift step.\ncof (float): The preemphasising coefficient. 0 equals to no filtering.\n\nReturns:\narray: The pre-emphasized signal.", "source": "codesearchnet"}
167{"code": "def _ParseFSMVariables(self, template):\n \n\n self.values = []\n\n for line in template:\n self._line_num += 1\n line = line.rstrip()\n\n \n if not line:\n return\n\n \n if self.comment_regex.match(line):\n continue\n\n if line.startswith('Value '):\n try:\n value = TextFSMValue(\n fsm=self, max_name_len=self.MAX_NAME_LEN,\n options_class=self._options_cls)\n value.Parse(line)\n except TextFSMTemplateError as error:\n raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num))\n\n if value.name in self.header:\n raise TextFSMTemplateError(\n \"Duplicate declarations for Value '%s'. Line: %s.\"\n % (value.name, self._line_num))\n\n try:\n self._ValidateOptions(value)\n except TextFSMTemplateError as error:\n raise TextFSMTemplateError('%s Line %s.' % (error, self._line_num))\n\n self.values.append(value)\n self.value_map[value.name] = value.template\n \n elif not self.values:\n raise TextFSMTemplateError('No Value definitions found.')\n else:\n raise TextFSMTemplateError(\n 'Expected blank line after last Value entry. Line: %s.'\n % (self._line_num))", "docstring": "Extracts Variables from start of template file.\n\nValues are expected as a contiguous block at the head of the file.\nThese will be line separated from the State definitions that follow.\n\nArgs:\ntemplate: Valid template file, with Value definitions at the top.\n\nRaises:\nTextFSMTemplateError: If syntax or semantic errors are found.", "source": "juraj-google-style"}
168{"code": "def __init__(self, df, grouping_column_names):\n \n \n self.df = df\n self.grouping_columns = []\n self.grouping_column_types = []\n\n if isinstance(grouping_column_names, str):\n grouping_column_names = [grouping_column_names]\n for column_name in grouping_column_names:\n column = df[column_name]\n if isinstance(column, LazyOpResult):\n self.grouping_column_types.append(column.weld_type)\n self.grouping_columns.append(column.expr)\n elif isinstance(column, np.ndarray):\n column_type = numpyImpl.numpy_to_weld_type_mapping[\n str(column.dtype)]\n self.grouping_column_types.append(column_type)\n self.grouping_columns.append(column)\n\n self.grouping_column_names = grouping_column_names\n self.column_names = []\n for x in df._get_column_names():\n if x not in self.grouping_column_names:\n self.column_names.append(x)\n\n self.columns = []\n self.column_types = []\n for column_name in self.column_names:\n column = df[column_name]\n column_type = None\n if isinstance(column, LazyOpResult):\n column_type = column.weld_type\n column = column.expr\n elif isinstance(column, np.ndarray):\n column_type = numpyImpl.numpy_to_weld_type_mapping[\n str(column.dtype)]\n\n self.columns.append(column)\n self.column_types.append(column_type)", "docstring": "Summary\n\nArgs:\ndf (TYPE): Description\ngrouping_column_name (TYPE): Description", "source": "juraj-google-style"}
169{"code": "def _DrawStations(self, color=\"\n \n stations=self._stations\n tmpstrs = []\n for y in stations:\n tmpstrs.append(' <polyline class=\"Station\" stroke=\"%s\" \\\n points=\"%s,%s, %s,%s\" />' %(color,20,20+y+.5,self._gwidth+20,20+y+.5))\n return \"\".join(tmpstrs)", "docstring": "Generates svg with a horizontal line for each station/stop.\n\nArgs:\n# Class Stop is defined in transitfeed.py\nstations: [Stop, Stop, ...]\n\nReturns:\n# A string containing a polyline tag for each stop\n\" <polyline class=\"Station\" stroke=\"#336633\" points=\"20,0 ...\"", "source": "juraj-google-style"}
170{"code": "def get(self):\n parser = reqparse.RequestParser()\n parser.add_argument('search', type=str, required=True)\n parser.add_argument('limit', type=int)\n args = parser.parse_args()\n if (not args['search']):\n return make_error(400, 'text_search cannot be empty')\n if (not args['limit']):\n del args['limit']\n pool = current_app.config['bigchain_pool']\n with pool() as bigchain:\n assets = bigchain.text_search(**args)\n try:\n return list(assets)\n except OperationError as e:\n return make_error(400, '({}): {}'.format(type(e).__name__, e))", "docstring": "API endpoint to perform a text search on the assets.\n\nArgs:\nsearch (str): Text search string to query the text index\nlimit (int, optional): Limit the number of returned documents.\n\nReturn:\nA list of assets that match the query.", "source": "codesearchnet"}
171{"code": "def normalize(input_tensor, output_tensor):\n \n image_dims = utils.get_img_shape(input_tensor)[1:]\n return output_tensor / np.prod(image_dims)", "docstring": "Normalizes the `output_tensor` with respect to `input_tensor` dimensions.\nThis makes regularizer weight factor more or less uniform across various input image dimensions.\n\nArgs:\ninput_tensor: An tensor of shape: `(samples, channels, image_dims...)` if `image_data_format=\nchannels_first` or `(samples, image_dims..., channels)` if `image_data_format=channels_last`.\noutput_tensor: The tensor to normalize.\n\nReturns:\nThe normalized tensor.", "source": "juraj-google-style"}
172{"code": "def ast_dict_to_objects(ast_dict: Mapping[str, Any], bel_obj) -> BELAst:\n \n ast_subject = ast_dict.get(\"subject\", None)\n ast_object = ast_dict.get(\"object\", None)\n\n bel_subject = None\n bel_object = None\n bel_relation = ast_dict.get(\"relation\")\n\n if ast_subject:\n bel_subject = function_ast_to_objects(ast_subject, bel_obj)\n\n if ast_object:\n bel_object = function_ast_to_objects(ast_object, bel_obj)\n\n ast_obj = BELAst(bel_subject, bel_relation, bel_object, bel_obj.spec)\n\n return ast_obj", "docstring": "Convert Tatsu AST dictionary to BEL AST object\n\nArgs:\nast_dict (Mapping[str, Any])\n\nReturns:\nBELAst: object representing the BEL Statement AST", "source": "juraj-google-style"}
173{"code": "def __init__(self, message=None, orig_exc=None, context=None):\n \n self.orig_exc = orig_exc\n if message is not None:\n self.error_message = message\n elif orig_exc is not None:\n \n self.error_message = \"%s\" % orig_exc\n\n self.context = context or StatikErrorContext()\n if not isinstance(self.context, StatikErrorContext):\n raise TypeError(\"Statik error context must be of type StatikErrorContext\")", "docstring": "Constructor.\n\nArgs:\nmessage: An optional message to override the predefined error message.\norig_exc: The original exception from which this error was generated.\ncontext: An optional ErrorContext instance to provide additional information during\nerror rendering.", "source": "juraj-google-style"}
174{"code": "def _get_node_attribute_at_index(self, node_index, attr, attr_name):\n if not self._inbound_nodes:\n raise AttributeError(f'The layer {self.name} has never been called and thus has no defined {attr_name}.')\n if not len(self._inbound_nodes) > node_index:\n raise ValueError(f'Asked to get {attr_name} at node {node_index}, but the operation has only {len(self._inbound_nodes)} inbound nodes.')\n values = getattr(self._inbound_nodes[node_index], attr)\n if isinstance(values, list) and len(values) == 1:\n return values[0]\n else:\n return values", "docstring": "Private utility to retrieves an attribute (e.g. inputs) from a node.\n\nThis is used to implement the properties:\n- output\n- input\n\nArgs:\nnode_index: Integer index of the node from which\nto retrieve the attribute.\nattr: Exact node attribute name.\nattr_name: Human-readable attribute name, for error messages.\n\nReturns:\nThe operation's attribute `attr` at the node of index `node_index`.", "source": "github-repos"}
175{"code": "def get_evaluation_parameter(self, parameter_name, default_value=None):\n \n if \"evaluation_parameters\" in self._expectations_config and \\\n parameter_name in self._expectations_config['evaluation_parameters']:\n return self._expectations_config['evaluation_parameters'][parameter_name]\n else:\n return default_value", "docstring": "Get an evaluation parameter value that has been stored in meta.\n\nArgs:\nparameter_name (string): The name of the parameter to store.\ndefault_value (any): The default value to be returned if the parameter is not found.\n\nReturns:\nThe current value of the evaluation parameter.", "source": "juraj-google-style"}
176{"code": "def printMe(self, selfTag, selfValue):\n \n if len(selfValue) == 0:\n return ''\n \n \n elif len(selfValue) == 1 and not ancestor(selfValue[0]) is Single:\n text = '<{tag}>{value}</{tag}>\\n'.format(\n tag=selfTag, value=selfValue[0])\n return text\n else:\n valueText = ''\n for element in selfValue:\n \n \n \n \n if singleOrPair(element) == 'Single':\n \n valueText += element.printMe(element.tag, element.value)\n elif singleOrPair(element) == 'Pair':\n valueText += element.printMe(element.key, element.value)\n else:\n \n valueText += str(element) + '\\n'\n valueText = indent(valueText, 4)\n text = '<{tag}>\\n'.format(\n tag=selfTag) + valueText + '</{tag}>\\n'.format(tag=selfTag)\n return text", "docstring": "Parse the single and its value and return the parsed str.\n\nArgs:\nselfTag (str): The tag. Normally just ``self.tag``\nselfValue (list): a list of value elements(single, subclasses, str, int). Normally just ``self.value``\n\nReturns:\nstr: A parsed text", "source": "juraj-google-style"}
177{"code": "def load_obs(self, mask_threshold=0.5):\n \n print(\"Loading obs \", self.run_date, self.model_name, self.forecast_variable)\n start_date = self.run_date + timedelta(hours=self.start_hour)\n end_date = self.run_date + timedelta(hours=self.end_hour)\n mrms_grid = MRMSGrid(start_date, end_date, self.mrms_variable, self.mrms_path)\n mrms_grid.load_data()\n if len(mrms_grid.data) > 0:\n self.raw_obs[self.mrms_variable] = np.where(mrms_grid.data > 100, 100, mrms_grid.data)\n self.period_obs[self.mrms_variable] = self.raw_obs[self.mrms_variable].max(axis=0)\n if self.obs_mask:\n mask_grid = MRMSGrid(start_date, end_date, self.mask_variable, self.mrms_path)\n mask_grid.load_data()\n self.raw_obs[self.mask_variable] = np.where(mask_grid.data >= mask_threshold, 1, 0)\n self.period_obs[self.mask_variable] = self.raw_obs[self.mask_variable].max(axis=0)", "docstring": "Loads observations and masking grid (if needed).\n\nArgs:\nmask_threshold: Values greater than the threshold are kept, others are masked.", "source": "juraj-google-style"}
178{"code": "def _blocking_poll(self, timeout=None):\n \n if self._result_set:\n return\n\n retry_ = self._retry.with_deadline(timeout)\n\n try:\n retry_(self._done_or_raise)()\n except exceptions.RetryError:\n raise concurrent.futures.TimeoutError(\n \"Operation did not complete within the designated \" \"timeout.\"\n )", "docstring": "Poll and wait for the Future to be resolved.\n\nArgs:\ntimeout (int):\nHow long (in seconds) to wait for the operation to complete.\nIf None, wait indefinitely.", "source": "juraj-google-style"}
179{"code": "def run_compiler(self, compiler=GCC, inputs=None, output=None):\n prog = RunningProgram(self, *compiler_cmdline(compiler=compiler, inputs=inputs, output=output))\n prog.expect_exit_status(0)", "docstring": "Runs a compiler in the working directory.\n\nArgs:\ncompiler (tuple): The compiler program and its command-line arguments,\nincluding placeholders for output and input files.\ninputs (tuple): The list of input files for the compiler.\noutput (str): The name of the output file.", "source": "codesearchnet"}
180{"code": "def get_function_arguments(obj, func):\n func_name = '_inspect_%s' % func\n if hasattr(obj, func_name):\n f = getattr(obj, func_name)\n return f()\n f = getattr(obj, func)\n return get_function_args_defaults(f)", "docstring": "Return the function arguments based on the name provided. If they have\na _inspect_function attached to the class then use that otherwise default\nto the modified version of python inspect library.\n\nReturns:\nSame as get_function_args_defaults.", "source": "github-repos"}
181{"code": "def ExamineEvent(self, mediator, event):\n if (self._session_end_timestamp is None):\n self._session_end_timestamp = (event.timestamp + self._maximum_pause_microseconds)\n self._events_per_session.append(0)\n if (event.timestamp > self._session_end_timestamp):\n self._session_counter += 1\n self._events_per_session.append(0)\n self._session_end_timestamp = (event.timestamp + self._maximum_pause_microseconds)\n self._events_per_session[(- 1)] += 1\n label = 'session_{0:d}'.format(self._session_counter)\n event_tag = self._CreateEventTag(event, self._EVENT_TAG_COMMENT, [label])\n mediator.ProduceEventTag(event_tag)\n self._number_of_event_tags += 1", "docstring": "Analyzes an EventObject and tags it as part of a session.\n\nArgs:\nmediator (AnalysisMediator): mediates interactions between analysis\nplugins and other components, such as storage and dfvfs.\nevent (EventObject): event to examine.", "source": "codesearchnet"}
182{"code": "def set_file_idx_offset(self, file_idx_offset=0):\n if isinstance(file_idx_offset, int):\n self.file_idx_offset = file_idx_offset\n elif (file_idx_offset == 'auto'):\n self.file_idx_offset = self.storage.max_file_idx()\n else:\n raise ValueError('\"file_idx_offset\" must be an integer or `auto`')", "docstring": "Set offset of file index.\n\nArgs:\nfile_idx_offset: It can be either an integer or 'auto'. If set\nto an integer, the filename will start from\n``file_idx_offset`` + 1. If set to ``'auto'``, the filename\nwill start from existing max file index plus 1.", "source": "codesearchnet"}
183{"code": "def execute_interactive_code(elem, doc):\n code_lines = [l[4:] for l in elem.text.split('\\n')]\n code_blocks = [[code_lines[0]]]\n for line in code_lines[1:]:\n if (line.startswith(' ') or (line == '')):\n code_blocks[(- 1)].append(line)\n else:\n code_blocks.append([line])\n final_code = []\n try:\n child = replwrap.REPLWrapper('python', '>>> ', None)\n except NameError:\n pf.debug(('Can not run interactive session. No output produced ' + '(Code was:\\n{!s}\\n)'.format(elem)))\n pf.debug('Please pip install pexpect.')\n return ''\n for code_block in code_blocks:\n result = child.run_command(('\\n'.join(code_block) + '\\n')).rstrip('\\r\\n')\n final_code += [(('>>> ' if (i == 0) else '... ') + l) for (i, l) in enumerate(code_block)]\n if result:\n final_code += [r for r in result.split('\\n') if (r.strip() not in code_block)]\n return '\\n'.join(final_code)", "docstring": "Executes code blocks for a python shell.\n\nParses the code in `elem.text` into blocks and\nexecutes them.\n\nArgs:\nelem The AST element.\ndoc The document.\n\nReturn:\nThe code with inline results.", "source": "codesearchnet"}
184{"code": "def write_file(self, filename):\n with open(filename, 'w') as f:\n f.write(self.__str__())", "docstring": "Write the PWSCF input file.\n\nArgs:\nfilename (str): The string filename to output to.", "source": "codesearchnet"}
185{"code": "def __init__(self, device: 'cirq.google.XmonDevice', seed=None) -> None:\n \n self._c = device.qubits\n self._c_adj = chip_as_adjacency_list(device)\n self._rand = np.random.RandomState(seed)", "docstring": "Greedy sequence search constructor.\n\nArgs:\ndevice: Chip description.\nseed: Optional seed value for random number generator.", "source": "juraj-google-style"}
186{"code": "def from_grid_locator(locator):\n \n if not len(locator) in (4, 6, 8):\n raise ValueError('Locator must be 4, 6 or 8 characters long %r'\n % locator)\n\n \n \n locator = list(locator)\n\n \n locator[0] = ord(locator[0]) - 65\n locator[1] = ord(locator[1]) - 65\n\n \n locator[2] = int(locator[2])\n locator[3] = int(locator[3])\n\n if len(locator) >= 6:\n \n \n locator[4] = ord(locator[4].lower()) - 97\n locator[5] = ord(locator[5].lower()) - 97\n\n if len(locator) == 8:\n \n locator[6] = int(locator[6])\n locator[7] = int(locator[7])\n\n \n \n if not 0 <= locator[0] <= 17 \\\n or not 0 <= locator[1] <= 17 \\\n or not 0 <= locator[2] <= 9 \\\n or not 0 <= locator[3] <= 9:\n raise ValueError('Invalid values in locator %r' % locator)\n\n \n if len(locator) >= 6:\n if not 0 <= locator[4] <= 23 \\\n or not 0 <= locator[5] <= 23:\n raise ValueError('Invalid values in locator %r' % locator)\n\n \n if len(locator) == 8:\n if not 0 <= locator[6] <= 9 \\\n or not 0 <= locator[7] <= 9:\n raise ValueError('Invalid values in locator %r' % locator)\n\n longitude = LONGITUDE_FIELD * locator[0] \\\n + LONGITUDE_SQUARE * locator[2]\n latitude = LATITUDE_FIELD * locator[1] \\\n + LATITUDE_SQUARE * locator[3]\n\n if len(locator) >= 6:\n longitude += LONGITUDE_SUBSQUARE * locator[4]\n latitude += LATITUDE_SUBSQUARE * locator[5]\n\n if len(locator) == 8:\n longitude += LONGITUDE_EXTSQUARE * locator[6] + LONGITUDE_EXTSQUARE / 2\n latitude += LATITUDE_EXTSQUARE * locator[7] + LATITUDE_EXTSQUARE / 2\n else:\n longitude += LONGITUDE_EXTSQUARE * 5\n latitude += LATITUDE_EXTSQUARE * 5\n\n \n longitude -= 180\n latitude -= 90\n\n return latitude, longitude", "docstring": "Calculate geodesic latitude/longitude from Maidenhead locator.\n\nArgs:\nlocator (str): Maidenhead locator string\n\nReturns:\ntuple of float: Geodesic latitude and longitude values\n\nRaises:\nValueError: Incorrect grid locator length\nValueError: Invalid values in locator string", "source": "juraj-google-style"}
187{"code": "def _reset_offset(self, partition):\n \n timestamp = self._subscriptions.assignment[partition].reset_strategy\n if timestamp is OffsetResetStrategy.EARLIEST:\n strategy = 'earliest'\n elif timestamp is OffsetResetStrategy.LATEST:\n strategy = 'latest'\n else:\n raise NoOffsetForPartitionError(partition)\n\n log.debug(\"Resetting offset for partition %s to %s offset.\",\n partition, strategy)\n offsets = self._retrieve_offsets({partition: timestamp})\n if partition not in offsets:\n raise NoOffsetForPartitionError(partition)\n offset = offsets[partition][0]\n\n \n \n if self._subscriptions.is_assigned(partition):\n self._subscriptions.seek(partition, offset)", "docstring": "Reset offsets for the given partition using the offset reset strategy.\n\nArguments:\npartition (TopicPartition): the partition that needs reset offset\n\nRaises:\nNoOffsetForPartitionError: if no offset reset strategy is defined", "source": "juraj-google-style"}
188{"code": "def get_static_value(x):\n if isinstance(x, core.Tensor) and (x.dtype.is_floating or x.dtype.is_complex):\n return None\n return tensor_util.constant_value(x)", "docstring": "A version of tf.get_static_value that returns None on float dtypes.\n\nIt returns None on float dtypes in order to avoid breaking gradients.\n\nArgs:\nx: a tensor.\n\nReturns:\nSame as `tf.get_static_value`, except that it returns None when `x` has a\nfloat dtype.", "source": "github-repos"}
189{"code": "def db_get(table, record, column, if_exists=False):\n cmd = ['ovs-vsctl', '--format=json', '--columns={0}'.format(column)]\n if if_exists:\n cmd += ['--if-exists']\n cmd += ['list', table, record]\n result = __salt__['cmd.run_all'](cmd)\n if (result['retcode'] != 0):\n raise CommandExecutionError(result['stderr'])\n output = _stdout_parse_json(result['stdout'])\n if (output['data'] and output['data'][0]):\n return output['data'][0][0]\n else:\n return None", "docstring": "Gets a column's value for a specific record.\n\nArgs:\ntable: A string - name of the database table.\nrecord: A string - identifier of the record.\ncolumn: A string - name of the column.\nif_exists: A boolean - if True, it is not an error if the record does\nnot exist.\n\nReturns:\nThe column's value.\n\nCLI Example:\n.. code-block:: bash\n\nsalt '*' openvswitch.db_get Port br0 vlan_mode", "source": "codesearchnet"}
190{"code": "def remove(self, word):\n self._dictionary.pop(word.lower())\n self._update_dictionary()", "docstring": "Remove a word from the word frequency list\n\nArgs:\nword (str): The word to remove", "source": "codesearchnet"}
191{"code": "def fileToMD5(filename, block_size=(256 * 128), binary=False):\n md5 = hashlib.md5()\n with open(filename, 'rb') as f:\n for chunk in iter((lambda : f.read(block_size)), b''):\n md5.update(chunk)\n if (not binary):\n return md5.hexdigest()\n return md5.digest()", "docstring": "A function that calculates the MD5 hash of a file.\n\nArgs:\n-----\nfilename: Path to the file.\nblock_size: Chunks of suitable size. Block size directly depends on\nthe block size of your filesystem to avoid performances issues.\nBlocks of 4096 octets (Default NTFS).\nbinary: A boolean representing whether the returned info is in binary\nformat or not.\n\nReturns:\n--------\nstring: The MD5 hash of the file.", "source": "codesearchnet"}
192{"code": "def pluralize(wordtext, num=2, plural_suffix='s'):\n if (num == 1):\n return wordtext\n elif wordtext.endswith(\"'s\"):\n return (wordtext[:(- 2)] + \"s'\")\n else:\n return (wordtext + plural_suffix)\n return ((wordtext + plural_suffix) if (num != 1) else wordtext)", "docstring": "r\"\"\"\nHeuristically changes a word to its plural form if `num` is not 1\n\nArgs:\nwordtext (str): word in singular form\nnum (int): a length of an associated list if applicable (default = 2)\nplural_suffix (str): heurstic plural form (default = 's')\n\nReturns:\nstr: pluralized form. Can handle some genitive cases\n\nCommandLine:\npython -m utool.util_str pluralize\n\nExample:\n>>> # ENABLE_DOCTEST\n>>> from utool.util_str import * # NOQA\n>>> wordtext = 'foo'\n>>> result = pluralize(wordtext)\n>>> print(result)\nfoos", "source": "codesearchnet"}
193{"code": "def price(self, valuation_date, market, model=None, name=None):\n name = name or self._name + '_price'\n with tf.name_scope(name):\n discount_curve = market.discount_curve\n coupon_cf = self._cashflows.price(valuation_date, market, model)\n principal_cf = self._notional * discount_curve.get_discount_factor(self._maturity_date)\n return coupon_cf + principal_cf", "docstring": "Returns the dirty price of the bonds on the valuation date.\n\nArgs:\nvaluation_date: A scalar `DateTensor` specifying the date on which\nvaluation is being desired.\nmarket: A namedtuple of type `InterestRateMarket` which contains the\nnecessary information for pricing the bonds.\nmodel: Reserved for future use.\nname: Python str. The name to give to the ops created by this function.\nDefault value: `None` which maps to 'price'.\n\nReturns:\nA Rank 1 `Tensor` of real dtype containing the dirty price of each bond\nbased on the input market data.", "source": "github-repos"}
194{"code": "def get_concept_item_mapping(self, concepts=None, lang=None):\n \n if concepts is None:\n concepts = self.filter(active=True)\n if lang is not None:\n concepts = concepts.filter(lang=lang)\n if lang is None:\n languages = set([concept.lang for concept in concepts])\n if len(languages) > 1:\n raise Exception('Concepts has multiple languages')\n lang = list(languages)[0]\n item_lists = Item.objects.filter_all_reachable_leaves_many([json.loads(concept.query)\n for concept in concepts], lang)\n return dict(zip([c.pk for c in concepts], item_lists))", "docstring": "Get mapping of concepts to items belonging to concept.\n\nArgs:\nconcepts (list of Concept): Defaults to None meaning all concepts\nlang (str): language of concepts, if None use language of concepts\n\nReturns:\ndict: concept (int) -> list of item ids (int)", "source": "juraj-google-style"}
195{"code": "def getCurrentStrDatetime():\n i = datetime.datetime.now()\n strTime = ('%s-%s-%s_%sh%sm' % (i.year, i.month, i.day, i.hour, i.minute))\n return strTime", "docstring": "Generating the current Datetime with a given format\n\nReturns:\n--------\nstring: The string of a date.", "source": "codesearchnet"}
196{"code": "def get(self, uri):\n uri = (self.URI + uri)\n return self._client.get(uri)", "docstring": "Gets an index resource by URI.\n\nArgs:\nuri: The resource URI.\n\nReturns:\ndict: The index resource.", "source": "codesearchnet"}
197{"code": "def element_wise(self, func, *args, **kwargs):\n s = self.shape\n emat = [func(o, *args, **kwargs) for o in self.matrix.ravel()]\n return Matrix(np_array(emat).reshape(s))", "docstring": "Apply a function to each matrix element and return the result in a\nnew operator matrix of the same shape.\n\nArgs:\nfunc (FunctionType): A function to be applied to each element. It\nmust take the element as its first argument.\nargs: Additional positional arguments to be passed to `func`\nkwargs: Additional keyword arguments to be passed to `func`\n\nReturns:\nMatrix: Matrix with results of `func`, applied element-wise.", "source": "codesearchnet"}
198{"code": "def get_committed_signatures(vcs):\n \n committed_path = _get_committed_history_path(vcs)\n known_signatures = []\n if os.path.exists(committed_path):\n with open(committed_path, 'r') as f:\n known_signatures = f.read().split()\n return known_signatures", "docstring": "Get the list of committed signatures\n\nArgs:\nvcs (easyci.vcs.base.Vcs)\n\nReturns:\nlist(basestring) - list of signatures", "source": "juraj-google-style"}
199{"code": "def add(self, command, *args):\n \n\n cmd = Command(command, args)\n self.commands.append(cmd)", "docstring": "Add a command to this command file.\n\nArgs:\ncommand (str): The command to add\n*args (str): The parameters to call the command with", "source": "juraj-google-style"}
200{"code": "def _expanded_sql(self, sampling=None):\n udfs = []\n subqueries = []\n expanded_sql = ''\n\n def _recurse_subqueries(query):\n 'Recursively scan subqueries and add their pieces to global scope udfs and subqueries\\n '\n if query._subqueries:\n for subquery in query._subqueries:\n _recurse_subqueries(subquery[1])\n subqueries.extend([s for s in query._subqueries if (s not in subqueries)])\n if query._udfs:\n udfs.extend([u[1] for u in query._udfs if (u[1] not in udfs)])\n _recurse_subqueries(self)\n if udfs:\n expanded_sql += '\\n'.join([udf._expanded_sql() for udf in udfs])\n expanded_sql += '\\n'\n\n def _indent_query(subquery):\n return (' ' + subquery._sql.replace('\\n', '\\n '))\n if subqueries:\n expanded_sql += ('WITH ' + '\\n),\\n'.join([('%s AS (\\n%s' % (sq[0], _indent_query(sq[1]))) for sq in subqueries]))\n expanded_sql += '\\n)\\n\\n'\n expanded_sql += (sampling(self._sql) if sampling else self._sql)\n return expanded_sql", "docstring": "Get the expanded SQL of this object, including all subqueries, UDFs, and external datasources\n\nReturns:\nThe expanded SQL string of this object", "source": "codesearchnet"}
201{"code": "def GetMessages(self, files):\n \n result = {}\n for file_name in files:\n file_desc = self.pool.FindFileByName(file_name)\n for desc in file_desc.message_types_by_name.values():\n result[desc.full_name] = self.GetPrototype(desc)\n\n \n \n \n \n \n \n \n \n\n for extension in file_desc.extensions_by_name.values():\n if extension.containing_type.full_name not in self._classes:\n self.GetPrototype(extension.containing_type)\n extended_class = self._classes[extension.containing_type.full_name]\n extended_class.RegisterExtension(extension)\n return result", "docstring": "Gets all the messages from a specified file.\n\nThis will find and resolve dependencies, failing if the descriptor\npool cannot satisfy them.\n\nArgs:\nfiles: The file names to extract messages from.\n\nReturns:\nA dictionary mapping proto names to the message classes. This will include\nany dependent messages as well as any messages defined in the same file as\na specified message.", "source": "juraj-google-style"}
202{"code": "def load_and_save_resfile(filename, outfile=None, outdir=None, mass=1.00):\n \n d = CellpyData()\n\n if not outdir:\n outdir = prms.Paths[\"cellpydatadir\"]\n\n if not outfile:\n outfile = os.path.basename(filename).split(\".\")[0] + \".h5\"\n outfile = os.path.join(outdir, outfile)\n\n print(\"filename:\", filename)\n print(\"outfile:\", outfile)\n print(\"outdir:\", outdir)\n print(\"mass:\", mass, \"mg\")\n\n d.from_raw(filename)\n d.set_mass(mass)\n d.make_step_table()\n d.make_summary()\n d.save(filename=outfile)\n d.to_csv(datadir=outdir, cycles=True, raw=True, summary=True)\n return outfile", "docstring": "Load a raw data file and save it as cellpy-file.\n\nArgs:\nmass (float): active material mass [mg].\noutdir (path): optional, path to directory for saving the hdf5-file.\noutfile (str): optional, name of hdf5-file.\nfilename (str): name of the resfile.\n\nReturns:\nout_file_name (str): name of saved file.", "source": "juraj-google-style"}
203{"code": "def highest_stored_id(self):\n shared = [0]\n\n def _keep_max(_i, reading):\n if (reading.reading_id > shared[0]):\n shared[0] = reading.reading_id\n self.engine.scan_storage('storage', _keep_max)\n self.engine.scan_storage('streaming', _keep_max)\n return shared[0]", "docstring": "Scan through the stored readings and report the highest stored id.\n\nReturns:\nint: The highest stored id.", "source": "codesearchnet"}
204{"code": "def validate(cls, mapper_spec):\n \n if mapper_spec.input_reader_class() != cls:\n raise BadReaderParamsError(\"Input reader class mismatch\")\n params = _get_params(mapper_spec)\n if cls.BATCH_SIZE_PARAM in params:\n try:\n batch_size = int(params[cls.BATCH_SIZE_PARAM])\n if batch_size < 1:\n raise BadReaderParamsError(\"Bad batch size: %s\" % batch_size)\n except ValueError, e:\n raise BadReaderParamsError(\"Bad batch size: %s\" % e)", "docstring": "Validates mapper spec.\n\nArgs:\nmapper_spec: The MapperSpec for this InputReader.\n\nRaises:\nBadReaderParamsError: required parameters are missing or invalid.", "source": "juraj-google-style"}
205{"code": "def _CreateFeedMapping(client, feed_details):\n \n \n feed_mapping_service = client.GetService('FeedMappingService',\n version='v201809')\n\n \n operation = {\n \n 'operand': {\n 'criterionType': DSA_PAGE_FEED_CRITERION_TYPE,\n 'feedId': feed_details.feed_id,\n \n 'attributeFieldMappings': [\n {\n 'feedAttributeId': feed_details.url_attribute_id,\n 'fieldId': DSA_PAGE_URLS_FIELD_ID\n },\n {\n 'feedAttributeId': feed_details.label_attribute_id,\n 'fieldId': DSA_LABEL_FIELD_ID\n }\n ]\n },\n 'operator': 'ADD'\n }\n\n \n feed_mapping_service.mutate([operation])", "docstring": "Creates the feed mapping for DSA page feeds.\n\nArgs:\nclient: an AdWordsClient instance.\nfeed_details: a _DSAFeedDetails instance.", "source": "juraj-google-style"}
206{"code": "def open_channel_with_funding(self, registry_address_hex, token_address_hex, peer_address_hex, total_deposit, settle_timeout=None):\n registry_address = decode_hex(registry_address_hex)\n peer_address = decode_hex(peer_address_hex)\n token_address = decode_hex(token_address_hex)\n try:\n self._discovery.get(peer_address)\n except KeyError:\n print('Error: peer {} not found in discovery'.format(peer_address_hex))\n return None\n self._api.channel_open(registry_address, token_address, peer_address, settle_timeout=settle_timeout)\n return self._api.set_total_channel_deposit(registry_address, token_address, peer_address, total_deposit)", "docstring": "Convenience method to open a channel.\n\nArgs:\nregistry_address_hex (str): hex encoded address of the registry for the channel.\ntoken_address_hex (str): hex encoded address of the token for the channel.\npeer_address_hex (str): hex encoded address of the channel peer.\ntotal_deposit (int): amount of total funding for the channel.\nsettle_timeout (int): amount of blocks for the settle time (if None use app defaults).\n\nReturn:\nnetting_channel: the (newly opened) netting channel object.", "source": "codesearchnet"}
207{"code": "def register_backend(self, config_contents):\n \n if config_contents is None:\n return\n self.__register_class(config_contents)\n self.__api_configs.append(config_contents)\n self.__register_methods(config_contents)", "docstring": "Register a single API and its config contents.\n\nArgs:\nconfig_contents: Dict containing API configuration.", "source": "juraj-google-style"}
208{"code": "def setup(argv):\n \n parser = argparse.ArgumentParser(\n description='Compute Jekyl- and prose-aware wordcounts',\n epilog='Accepted filetypes: plaintext, markdown, markdown (Jekyll)')\n parser.add_argument('-S', '--split-hyphens', action='store_true',\n dest='split_hyphens',\n help='split hyphenated words rather than counting '\n 'them as one word (\"non-trivial\" counts as two words '\n 'rather than one)')\n parser.add_argument('-u', '--update', action='store_true',\n help='update the jekyll file in place with the counts.'\n ' Does nothing if the file is not a Jekyll markdown '\n 'file. Implies format=yaml, invalid with input '\n 'from STDIN and non-Jekyll files.')\n parser.add_argument('-f', '--format', nargs='?',\n choices=['yaml', 'json', 'default'], default='default',\n help='output format.')\n parser.add_argument('-i', '--indent', type=int, nargs='?', default=4,\n help='indentation depth (default: 4).')\n parser.add_argument('file', type=argparse.FileType('rb'),\n help='file to parse (or - for STDIN)')\n return parser.parse_args(argv)", "docstring": "Sets up the ArgumentParser.\n\nArgs:\nargv: an array of arguments", "source": "juraj-google-style"}
209{"code": "def _lookup_in_all_namespaces(self, symbol):\n namespace = self.namespaces\n namespace_stack = []\n for current in symbol.namespace_stack:\n namespace = namespace.get(current)\n if ((namespace is None) or (not isinstance(namespace, dict))):\n break\n namespace_stack.append(namespace)\n for namespace in reversed(namespace_stack):\n try:\n return self._lookup_namespace(symbol, namespace)\n except Error:\n pass\n return None", "docstring": "Helper for lookup_symbol that looks for symbols in all namespaces.\n\nArgs:\nsymbol: Symbol", "source": "codesearchnet"}
210{"code": "def expand_by_device(original_parallelism, device_parallelism, data):\n \n device_to_datum = {\n device_parallelism.devices[i]: data[i]\n for i in range(device_parallelism.n)}\n return [device_to_datum[d] for d in original_parallelism.devices]", "docstring": "Opposite of reduce_by_device().\n\nArgs:\noriginal_parallelism: a expert_utils.Parallelism object.\ndevice_parallelism: a expert_utils.Parallelism object.\ndata: a list of tensors with length device_parallelism.n\n\nReturns:\na list of Tensors with length original_parallelism.n", "source": "juraj-google-style"}
211{"code": "def _FormatInAddrExToken(self, token_data):\n \n protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.net_type, 'UNKNOWN')\n if token_data.net_type == 4:\n ip_address = self._FormatPackedIPv6Address(token_data.ip_address[:4])\n elif token_data.net_type == 16:\n ip_address = self._FormatPackedIPv6Address(token_data.ip_address)\n return {\n 'protocols': protocol,\n 'net_type': token_data.net_type,\n 'address': ip_address}", "docstring": "Formats an extended IPv4 address token as a dictionary of values.\n\nArgs:\ntoken_data (bsm_token_data_in_addr_ex): AUT_IN_ADDR_EX token data.\n\nReturns:\ndict[str, str]: token values.", "source": "juraj-google-style"}
212{"code": "def from_string(string):\n lines = string.split('\\n')\n toks = lines[0].split()\n lengths = [float(i) for i in toks]\n toks = lines[1].split()\n angles = [float(i) for i in toks[0:3]]\n a = lengths.pop((- 1))\n lengths.insert(0, a)\n alpha = angles.pop((- 1))\n angles.insert(0, alpha)\n latt = Lattice.from_lengths_and_angles(lengths, angles)\n sp = []\n coords = []\n chrg = []\n for l in lines[4:]:\n m = re.match(('\\\\d+\\\\s+(\\\\w+)\\\\s+([0-9\\\\-\\\\.]+)\\\\s+([0-9\\\\-\\\\.]+)\\\\s+' + '([0-9\\\\-\\\\.]+)\\\\s+(?:0\\\\s+){8}([0-9\\\\-\\\\.]+)'), l.strip())\n if m:\n sp.append(m.group(1))\n coords.append([float(m.group(i)) for i in [3, 4, 2]])\n chrg.append(m.group(5))\n return ZeoCssr(Structure(latt, sp, coords, site_properties={'charge': chrg}))", "docstring": "Reads a string representation to a ZeoCssr object.\n\nArgs:\nstring: A string representation of a ZeoCSSR.\n\nReturns:\nZeoCssr object.", "source": "codesearchnet"}
213{"code": "def _ParseRedirected(\n self, parser_mediator, msiecf_item, recovered=False):\n \n date_time = dfdatetime_semantic_time.SemanticTime('Not set')\n\n event_data = MSIECFRedirectedEventData()\n event_data.offset = msiecf_item.offset\n event_data.recovered = recovered\n event_data.url = msiecf_item.location\n\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Extract data from a MSIE Cache Files (MSIECF) redirected item.\n\nEvery item is stored as an event object, one for each timestamp.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nmsiecf_item (pymsiecf.redirected): MSIECF redirected item.\nrecovered (Optional[bool]): True if the item was recovered.", "source": "juraj-google-style"}
214{"code": "def __call__(self, w):\n return w", "docstring": "Applies the constraint to the input weight variable.\n\nBy default, the inputs weight variable is not modified.\nUsers should override this method to implement their own projection\nfunction.\n\nArgs:\nw: Input weight variable.\n\nReturns:\nProjected variable (by default, returns unmodified inputs).", "source": "github-repos"}
215{"code": "def get_data_source_instance(data_source, sagemaker_session):\n \n parsed_uri = urlparse(data_source)\n if parsed_uri.scheme == 'file':\n return LocalFileDataSource(parsed_uri.netloc + parsed_uri.path)\n elif parsed_uri.scheme == 's3':\n return S3DataSource(parsed_uri.netloc, parsed_uri.path, sagemaker_session)", "docstring": "Return an Instance of :class:`sagemaker.local.data.DataSource` that can handle\nthe provided data_source URI.\n\ndata_source can be either file:// or s3://\n\nArgs:\ndata_source (str): a valid URI that points to a data source.\nsagemaker_session (:class:`sagemaker.session.Session`): a SageMaker Session to interact with\nS3 if required.\n\nReturns\n:class:`sagemaker.local.data.DataSource`: an Instance of a Data Source", "source": "juraj-google-style"}
216{"code": "def __init__(self, channel):\n \n self.ListDocuments = channel.unary_unary(\n '/google.cloud.dialogflow.v2beta1.Documents/ListDocuments',\n request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_document__pb2.ListDocumentsRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_document__pb2.ListDocumentsResponse.FromString,\n )\n self.GetDocument = channel.unary_unary(\n '/google.cloud.dialogflow.v2beta1.Documents/GetDocument',\n request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_document__pb2.GetDocumentRequest.SerializeToString,\n response_deserializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_document__pb2.Document.FromString,\n )\n self.CreateDocument = channel.unary_unary(\n '/google.cloud.dialogflow.v2beta1.Documents/CreateDocument',\n request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_document__pb2.CreateDocumentRequest.SerializeToString,\n response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,\n )\n self.DeleteDocument = channel.unary_unary(\n '/google.cloud.dialogflow.v2beta1.Documents/DeleteDocument',\n request_serializer=google_dot_cloud_dot_dialogflow__v2beta1_dot_proto_dot_document__pb2.DeleteDocumentRequest.SerializeToString,\n response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString,\n )", "docstring": "Constructor.\n\nArgs:\nchannel: A grpc.Channel.", "source": "juraj-google-style"}
217{"code": "def _get_first_op_from_collection(self, key):\n try:\n op_list = ops.get_collection(key)\n if len(op_list) > 1:\n logging.info('Found %d %s operations. Returning the first one.', len(op_list), key)\n if op_list:\n return op_list[0]\n except LookupError:\n pass\n return None", "docstring": "Returns the first `Operation` from a collection.\n\nArgs:\nkey: A string collection key.\n\nReturns:\nThe first Op found in a collection, or `None` if the collection is empty.", "source": "github-repos"}
218{"code": "def request(self, subject, callback, msg=None):\n inbox = self._build_inbox()\n s = self.subscribe(inbox, callback)\n self.unsubscribe(s, 1)\n self.publish(subject, msg, inbox)\n return s", "docstring": "ublish a message with an implicit inbox listener as the reply.\nMessage is optional.\n\nArgs:\nsubject (string): a string with the subject\ncallback (function): callback to be called\nmsg (string=None): payload string", "source": "codesearchnet"}
219{"code": "def set_page_artid(self, page_start=None, page_end=None, artid=None):\n if (page_end and (not page_start)):\n raise ValueError('End_page provided without start_page')\n self._ensure_reference_field('publication_info', {})\n publication_info = self.obj['reference']['publication_info']\n if page_start:\n publication_info['page_start'] = page_start\n if page_end:\n publication_info['page_end'] = page_end\n if artid:\n publication_info['artid'] = artid", "docstring": "Add artid, start, end pages to publication info of a reference.\n\nArgs:\npage_start(Optional[string]): value for the field page_start\npage_end(Optional[string]): value for the field page_end\nartid(Optional[string]): value for the field artid\n\nRaises:\nValueError: when no start_page given for an end_page", "source": "codesearchnet"}
220{"code": "def bounce(sequence):\n \n N = len(sequence)\n def f(i):\n div, mod = divmod(i, N)\n if div % 2 == 0:\n return sequence[mod]\n else:\n return sequence[N-mod-1]\n return partial(force, sequence=_advance(f))", "docstring": "Return a driver function that can advance a \"bounced\" sequence\nof values.\n\n.. code-block:: none\n\nseq = [0, 1, 2, 3]\n\n# bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...]\n\nArgs:\nsequence (seq) : a sequence of values for the driver to bounce", "source": "juraj-google-style"}
221{"code": "def data_group_association(self, xid):\n \n groups = []\n group_data = None\n\n \n if self.groups.get(xid) is not None:\n group_data = self.groups.get(xid)\n del self.groups[xid]\n elif self.groups_shelf.get(xid) is not None:\n group_data = self.groups_shelf.get(xid)\n del self.groups_shelf[xid]\n\n if group_data is not None:\n \n group_data = self.data_group_type(group_data)\n groups.append(group_data)\n\n \n for assoc_xid in group_data.get('associatedGroupXid', []):\n groups.extend(self.data_group_association(assoc_xid))\n\n return groups", "docstring": "Return group dict array following all associations.\n\nArgs:\nxid (str): The xid of the group to retrieve associations.\n\nReturns:\nlist: A list of group dicts.", "source": "juraj-google-style"}
222{"code": "def update_ports(self, ports, id_or_uri):\n ports = merge_default_values(ports, {'type': 'port'})\n uri = (self._client.build_uri(id_or_uri) + '/update-ports')\n return self._client.update(uri=uri, resource=ports)", "docstring": "Updates the switch ports. Only the ports under the management of OneView and those that are unlinked are\nsupported for update.\n\nNote:\nThis method is available for API version 300 or later.\n\nArgs:\nports: List of Switch Ports.\nid_or_uri: Can be either the switch id or the switch uri.\n\nReturns:\ndict: Switch", "source": "codesearchnet"}
223{"code": "def feature_path(self, gff_path):\n if (not gff_path):\n self.feature_dir = None\n self.feature_file = None\n else:\n if (not op.exists(gff_path)):\n raise OSError('{}: file does not exist!'.format(gff_path))\n if (not op.dirname(gff_path)):\n self.feature_dir = '.'\n else:\n self.feature_dir = op.dirname(gff_path)\n self.feature_file = op.basename(gff_path)", "docstring": "Load a GFF file with information on a single sequence and store features in the ``features`` attribute\n\nArgs:\ngff_path: Path to GFF file.", "source": "codesearchnet"}
224{"code": "def serialize_keras_object(instance):\n _, instance = tf_decorator.unwrap(instance)\n if instance is None:\n return None\n supports_masking = getattr(instance, 'supports_masking', False) or (hasattr(instance, 'compute_mask') and (not is_default(instance.compute_mask)))\n if supports_masking and is_default(instance.get_config):\n warnings.warn('Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument.', category=CustomMaskWarning)\n if hasattr(instance, 'get_config'):\n name = get_registered_name(instance.__class__)\n try:\n config = instance.get_config()\n except NotImplementedError as e:\n if _SKIP_FAILED_SERIALIZATION:\n return serialize_keras_class_and_config(name, {_LAYER_UNDEFINED_CONFIG_KEY: True})\n raise e\n serialization_config = {}\n for key, item in config.items():\n if isinstance(item, str):\n serialization_config[key] = item\n continue\n try:\n serialized_item = serialize_keras_object(item)\n if isinstance(serialized_item, dict) and (not isinstance(item, dict)):\n serialized_item['__passive_serialization__'] = True\n serialization_config[key] = serialized_item\n except ValueError:\n serialization_config[key] = item\n name = get_registered_name(instance.__class__)\n return serialize_keras_class_and_config(name, serialization_config, instance)\n if hasattr(instance, '__name__'):\n return get_registered_name(instance)\n raise ValueError('Cannot serialize', instance)", "docstring": "Serialize a Keras object into a JSON-compatible representation.\n\nCalls to `serialize_keras_object` while underneath the\n`SharedObjectSavingScope` context manager will cause any objects re-used\nacross multiple layers to be saved with a special shared object ID. This\nallows the network to be re-created properly during deserialization.\n\nArgs:\ninstance: The object to serialize.\n\nReturns:\nA dict-like, JSON-compatible representation of the object's config.", "source": "github-repos"}
225{"code": "def _checkTimeValue( timevalue, maxvalue ): \n \n if maxvalue is None:\n raise TypeError('The maxvalue (for the time value) must not be None!')\n minimalmodbus._checkNumerical(timevalue, minvalue=0, maxvalue=maxvalue, description='time value')", "docstring": "Check that the given timevalue is valid.\n\nArgs:\n* timevalue (numerical): The time value to be checked. Must be positive.\n* maxvalue (numerical): Upper limit for time value. Must be positive.\n\nRaises:\nTypeError, ValueError", "source": "juraj-google-style"}
226{"code": "def __new__(mcs, classname, baseclasses, attrs):\n if not baseclasses:\n raise TypeError('Expected non-empty baseclass. Does Distribution not subclass _BaseDistribution?')\n which_base = [base for base in baseclasses if base == _BaseDistribution or issubclass(base, Distribution)]\n base = which_base[0]\n if base == _BaseDistribution:\n return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs)\n if not issubclass(base, Distribution):\n raise TypeError(\"First parent class declared for %s must be Distribution, but saw '%s'\" % (classname, base.__name__))\n for attr in _DISTRIBUTION_PUBLIC_METHOD_WRAPPERS:\n special_attr = '_%s' % attr\n class_attr_value = attrs.get(attr, None)\n if attr in attrs:\n continue\n base_attr_value = getattr(base, attr, None)\n if not base_attr_value:\n raise AttributeError(\"Internal error: expected base class '%s' to implement method '%s'\" % (base.__name__, attr))\n class_special_attr_value = attrs.get(special_attr, None)\n if class_special_attr_value is None:\n continue\n class_special_attr_docstring = tf_inspect.getdoc(class_special_attr_value)\n if not class_special_attr_docstring:\n continue\n class_attr_value = _copy_fn(base_attr_value)\n class_attr_docstring = tf_inspect.getdoc(base_attr_value)\n if class_attr_docstring is None:\n raise ValueError('Expected base class fn to contain a docstring: %s.%s' % (base.__name__, attr))\n class_attr_value.__doc__ = _update_docstring(class_attr_value.__doc__, 'Additional documentation from `%s`:\\n\\n%s' % (classname, class_special_attr_docstring))\n attrs[attr] = class_attr_value\n return abc.ABCMeta.__new__(mcs, classname, baseclasses, attrs)", "docstring": "Control the creation of subclasses of the Distribution class.\n\nThe main purpose of this method is to properly propagate docstrings\nfrom private Distribution methods, like `_log_prob`, into their\npublic wrappers as inherited by the Distribution base class\n(e.g. `log_prob`).\n\nArgs:\nclassname: The name of the subclass being created.\nbaseclasses: A tuple of parent classes.\nattrs: A dict mapping new attributes to their values.\n\nReturns:\nThe class object.\n\nRaises:\nTypeError: If `Distribution` is not a subclass of `BaseDistribution`, or\nthe new class is derived via multiple inheritance and the first\nparent class is not a subclass of `BaseDistribution`.\nAttributeError: If `Distribution` does not implement e.g. `log_prob`.\nValueError: If a `Distribution` public method lacks a docstring.", "source": "github-repos"}
227{"code": "def import_image_from_data(self, data, repository=None, tag=None,\n changes=None):\n \n\n u = self._url('/images/create')\n params = _import_image_params(\n repository, tag, src='-', changes=changes\n )\n headers = {'Content-Type': 'application/tar'}\n return self._result(\n self._post(\n u, data=data, params=params, headers=headers, timeout=None\n )\n )", "docstring": "Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but\nallows importing in-memory bytes data.\n\nArgs:\ndata (bytes collection): Bytes collection containing valid tar data\nrepository (str): The repository to create\ntag (str): The tag to apply", "source": "juraj-google-style"}
228{"code": "def eere_station(station_code):\n \n with open(env.SRC_PATH + '/eere_meta.csv') as eere_meta:\n stations = csv.DictReader(eere_meta)\n for station in stations:\n if station['station_code'] == station_code:\n return station\n raise KeyError('station not found')", "docstring": "Station information.\n\nArgs:\nstation_code (str): station code.\n\nReturns (dict): station information", "source": "juraj-google-style"}
229{"code": "def get_sample_dataset(dataset_properties):\n kwargs = dataset_properties.copy()\n data_type = kwargs.pop('type')\n if (data_type == 'multiclass'):\n try:\n (X, y) = datasets.make_classification(random_state=8, **kwargs)\n splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)\n except Exception as e:\n raise exceptions.UserError(repr(e))\n elif (data_type == 'iris'):\n (X, y) = datasets.load_iris(return_X_y=True)\n splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)\n elif (data_type == 'mnist'):\n (X, y) = datasets.load_digits(return_X_y=True)\n splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)\n elif (data_type == 'breast_cancer'):\n (X, y) = datasets.load_breast_cancer(return_X_y=True)\n splits = model_selection.StratifiedKFold(n_splits=2, random_state=8).split(X, y)\n elif (data_type == 'boston'):\n (X, y) = datasets.load_boston(return_X_y=True)\n splits = model_selection.KFold(n_splits=2, random_state=8).split(X)\n elif (data_type == 'diabetes'):\n (X, y) = datasets.load_diabetes(return_X_y=True)\n splits = model_selection.KFold(n_splits=2, random_state=8).split(X)\n else:\n raise exceptions.UserError('Unknown dataset type {}'.format(dataset_properties['type']))\n return (X, y, splits)", "docstring": "Returns sample dataset\n\nArgs:\ndataset_properties (dict): Dictionary corresponding to the properties of the dataset\nused to verify the estimator and metric generators.\n\nReturns:\nX (array-like): Features array\n\ny (array-like): Labels array\n\nsplits (iterator): This is an iterator that returns train test splits for\ncross-validation purposes on ``X`` and ``y``.", "source": "codesearchnet"}
230{"code": "def _load_stop_words(self, language=None):\n \n self._logger.debug('Loading stop words')\n\n loaded = False\n\n if language:\n file_path = 'data/stop-' + language\n loaded = self._parse_stop_words_file(os.path.join(PATH, file_path))\n else:\n for file in os.listdir(os.path.join(PATH, 'data')):\n loaded = self._parse_stop_words_file(os.path.join(PATH, 'data', file)) or loaded\n\n return loaded", "docstring": "Load stop words into __stop_words set.\n\nStop words will be loaded according to the language code\nreceived during instantiation.\n\nArgs:\nlanguage: Language code.\n\nReturns:\nA boolean indicating whether a file was loaded.", "source": "juraj-google-style"}
231{"code": "def ParseCookieRow(self, parser_mediator, query, row, **unused_kwargs):\n \n query_hash = hash(query)\n\n cookie_data = self._GetRowValue(query_hash, row, 'value')\n cookie_name = self._GetRowValue(query_hash, row, 'name')\n\n hostname = self._GetRowValue(query_hash, row, 'host')\n if hostname.startswith('.'):\n hostname = hostname[1:]\n\n is_secure = bool(self._GetRowValue(query_hash, row, 'isSecure'))\n if is_secure:\n url_scheme = 'https'\n else:\n url_scheme = 'http'\n\n path = self._GetRowValue(query_hash, row, 'path')\n url = '{0:s}:\n\n event_data = FirefoxCookieEventData()\n event_data.cookie_name = cookie_name\n event_data.data = cookie_data\n event_data.host = hostname\n event_data.httponly = bool(self._GetRowValue(query_hash, row, 'isHttpOnly'))\n event_data.offset = self._GetRowValue(query_hash, row, 'id')\n event_data.path = path\n event_data.query = query\n event_data.secure = is_secure\n event_data.url = url\n\n timestamp = self._GetRowValue(query_hash, row, 'creationTime')\n if timestamp:\n date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(\n timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = self._GetRowValue(query_hash, row, 'lastAccessed')\n if timestamp:\n date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(\n timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n timestamp = self._GetRowValue(query_hash, row, 'expiry')\n if timestamp:\n \n \n \n \n \n \n\n date_time = dfdatetime_posix_time.PosixTime(\n timestamp=timestamp)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_EXPIRATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n \n \n for cookie_plugin in self._cookie_plugins:\n try:\n cookie_plugin.UpdateChainAndProcess(\n parser_mediator, cookie_name=cookie_name, cookie_data=cookie_data,\n url=url)\n except errors.WrongPlugin:\n pass", "docstring": "Parses a cookie row.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nquery (str): query that created the row.\nrow (sqlite3.Row): row.", "source": "juraj-google-style"}
232{"code": "def change_subscription(self, topics):\n if self._user_assignment:\n raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE)\n if isinstance(topics, six.string_types):\n topics = [topics]\n if (self.subscription == set(topics)):\n log.warning('subscription unchanged by change_subscription(%s)', topics)\n return\n for t in topics:\n self._ensure_valid_topic_name(t)\n log.info('Updating subscribed topics to: %s', topics)\n self.subscription = set(topics)\n self._group_subscription.update(topics)\n for tp in set(self.assignment.keys()):\n if (tp.topic not in self.subscription):\n del self.assignment[tp]", "docstring": "Change the topic subscription.\n\nArguments:\ntopics (list of str): topics for subscription\n\nRaises:\nIllegalStateErrror: if assign_from_user has been used already\nTypeError: if a topic is None or a non-str\nValueError: if a topic is an empty string or\n- a topic name is '.' or '..' or\n- a topic name does not consist of ASCII-characters/'-'/'_'/'.'", "source": "codesearchnet"}
233{"code": "def _add_name_scope_wrapper(func, api_signature):\n if 'name' not in api_signature.parameters:\n return func\n func_signature = tf_inspect.signature(func)\n func_argspec = tf_inspect.getargspec(func)\n if 'name' in func_signature.parameters or func_argspec.keywords is not None:\n return func\n name_index = list(api_signature.parameters).index('name')\n\n def wrapped_func(*args, **kwargs):\n if name_index < len(args):\n name = args[name_index]\n args = args[:name_index] + args[name_index + 1:]\n else:\n name = kwargs.pop('name', None)\n if name is None:\n return func(*args, **kwargs)\n else:\n with ops.name_scope(name):\n return func(*args, **kwargs)\n wrapped_func = tf_decorator.make_decorator(func, wrapped_func)\n wrapped_func.__signature__ = func_signature.replace(parameters=list(func_signature.parameters.values()) + [api_signature.parameters['name']])\n del wrapped_func._tf_decorator\n return wrapped_func", "docstring": "Wraps `func` to expect a \"name\" arg, and use it to call `ops.name_scope`.\n\nIf `func` already expects a \"name\" arg, or if `api_signature` does not\nexpect a \"name\" arg, then returns `func` as-is.\n\nArgs:\nfunc: The function to wrap. Signature must match `api_signature` (except\nthe \"name\" parameter may be missing.\napi_signature: The signature of the original API (used to find the index for\nthe \"name\" parameter).\n\nReturns:\nThe wrapped function (or the original function if no wrapping is needed).", "source": "github-repos"}
234{"code": "def computeAccuracy(model, size, top):\n \n accuracy = []\n\n \n filename = os.path.join(os.path.dirname(__file__), \"msnbc990928.zip\")\n with zipfile.ZipFile(filename) as archive:\n with archive.open(\"msnbc990928.seq\") as datafile:\n \n for _ in xrange(7):\n next(datafile)\n\n \n for _ in xrange(LEARNING_RECORDS):\n next(datafile)\n\n \n \n for _ in xrange(size):\n pages = readUserSession(datafile)\n model.resetSequenceStates()\n for i in xrange(len(pages) - 1):\n result = model.run({\"page\": pages[i]})\n inferences = result.inferences[\"multiStepPredictions\"][1]\n\n \n predicted = sorted(inferences.items(), key=itemgetter(1), reverse=True)[:top]\n\n \n accuracy.append(1 if pages[i + 1] in zip(*predicted)[0] else 0)\n\n return np.mean(accuracy)", "docstring": "Compute prediction accuracy by checking if the next page in the sequence is\nwithin the top N predictions calculated by the model\nArgs:\nmodel: HTM model\nsize: Sample size\ntop: top N predictions to use\n\nReturns: Probability the next page in the sequence is within the top N\npredicted pages", "source": "juraj-google-style"}
235{"code": "def set_day_time(self, hour):\n \n self._should_write_to_command_buffer = True\n command_to_send = DayTimeCommand(hour % 24)\n self._commands.add_command(command_to_send)", "docstring": "Queue up a change day time command. It will be applied when `tick` or `step` is called next.\nBy the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere\nor directional light in the world, the command will not function properly but will not cause a crash.\n\nArgs:\nhour (int): The hour in military time, between 0 and 23 inclusive.", "source": "juraj-google-style"}
236{"code": "def create_token(self, *, holder_name, card_number, credit_card_cvv, expiration_date, token_type='credit_card', identity_document=None, billing_address=None, additional_details=None):\n headers = self.client._get_public_headers()\n payload = {'token_type': token_type, 'credit_card_cvv': credit_card_cvv, 'card_number': card_number, 'expiration_date': expiration_date, 'holder_name': holder_name, 'identity_document': identity_document, 'billing_address': billing_address, 'additional_details': additional_details}\n endpoint = '/tokens'\n return self.client._post((self.client.URL_BASE + endpoint), json=payload, headers=headers)", "docstring": "When creating a Token, remember to use the public-key header instead of the private-key header,\nand do not include the app-id header.\n\nArgs:\nholder_name: Name of the credit card holder.\ncard_number: Credit card number.\ncredit_card_cvv: The CVV number on the card (3 or 4 digits) to be encrypted.\nexpiration_date: Credit card expiration date. Possible formats: mm-yyyy, mm-yy, mm.yyyy,\nmm.yy, mm/yy, mm/yyyy, mm yyyy, or mm yy.\ntoken_type: The type of token\nbilling_address: Address.\nidentity_document: National identity document of the card holder.\nadditional_details: Optional additional data stored with your token in key/value pairs.\n\nReturns:", "source": "codesearchnet"}
237{"code": "def gpio_get(self, pins=None):\n \n if pins is None:\n pins = range(4)\n\n size = len(pins)\n indices = (ctypes.c_uint8 * size)(*pins)\n statuses = (ctypes.c_uint8 * size)()\n result = self._dll.JLINK_EMU_GPIO_GetState(ctypes.byref(indices),\n ctypes.byref(statuses),\n size)\n if result < 0:\n raise errors.JLinkException(result)\n\n return list(statuses)", "docstring": "Returns a list of states for the given pins.\n\nDefaults to the first four pins if an argument is not given.\n\nArgs:\nself (JLink): the ``JLink`` instance\npins (list): indices of the GPIO pins whose states are requested\n\nReturns:\nA list of states.\n\nRaises:\nJLinkException: on error.", "source": "juraj-google-style"}
238{"code": "def json_set_fields(recipe, variables):\n if isinstance(recipe, dict):\n for key, value in list(recipe.items()):\n if isinstance(value, dict) and 'field' in value:\n variable_value = variables.get(value['field']['name'], value['field'].get('default'))\n field_value = get_field_value(value, variable_value)\n if field_value is None and value.get('default') is None:\n del recipe[key]\n else:\n recipe[key] = field_value\n else:\n json_set_fields(value, variables)\n elif isinstance(recipe, list) or isinstance(recipe, tuple):\n for index, value in enumerate(recipe):\n if isinstance(value, dict) and 'field' in value:\n variable_value = variables.get(value['field']['name'], value['field'].get('default'))\n recipe[index] = get_field_value(value, variable_value)\n else:\n json_set_fields(value, variables)\n return recipe", "docstring": "Recusrsively replaces fields in script JSON with values provided.\n\nField has format: { \"field\":{ \"name\":\"???\", \"kind\":\"???\", \"default\":???,\n\"description\":\"???\" }}\n\nIf field value is empty and field default is null, the value is removed\nfrom JSON as a parameter,\nallowing the python task to pick a default value. Allows optional\nparameters to exist.\n\nArgs:\nrecipe: (dict) A dictionary representation of the JSON script.\nvariables: (dict) A lookup table of all values to be replaced, key is name\nof field.\n\nReturns:\nNothig. Struct is modified in place.", "source": "github-repos"}
239{"code": "def has_no_checked_field(self, locator, **kwargs):\n kwargs['checked'] = True\n return self.has_no_selector('field', locator, **kwargs)", "docstring": "Checks if the page or current node has no radio button or checkbox with the given label,\nvalue, or id that is currently checked.\n\nArgs:\nlocator (str): The label, name, or id of a checked field.\n**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.\n\nReturns:\nbool: Whether it doesn't exist.", "source": "codesearchnet"}
240{"code": "def extrapolation_step():\n\n def step_fn(time, next_time, coord_grid, value_grid, boundary_conditions, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, num_steps_performed, dtype=None, name=None):\n \n del num_steps_performed\n name = name or 'extrapolation_step'\n return parabolic_equation_step(time, next_time, coord_grid, value_grid, boundary_conditions, second_order_coeff_fn, first_order_coeff_fn, zeroth_order_coeff_fn, inner_second_order_coeff_fn, inner_first_order_coeff_fn, time_marching_scheme=extrapolation_scheme, dtype=dtype, name=name)\n return step_fn", "docstring": "Creates a stepper function with Extrapolation time marching scheme.\n\nExtrapolation scheme combines two half-steps and the full time step to obtain\ndesirable properties. See more details below in `extrapolation_scheme`.\n\nIt is slower than Crank-Nicolson scheme, but deals better with value grids\nthat have discontinuities. Consider also `oscillation_damped_crank_nicolson`,\nan efficient combination of Crank-Nicolson and Extrapolation schemes.\n\nReturns:\nCallable to be used in finite-difference PDE solvers (see fd_solvers.py).", "source": "github-repos"}
241{"code": "def to_string(self, other_separation_char=None):\n \n separation_char = self._separation_char\n if other_separation_char is not None:\n separation_char = other_separation_char\n return separation_char.join(self._locations_list)", "docstring": "String representation of :class:`LocationDescriptor` object.\n\nArgs:\nother_separation_char: If needed, another separator character can be used.\n\nReturns:", "source": "juraj-google-style"}
242{"code": "def update_user(self, user_id,\n roles=None, netmask=None,\n secret=None, pubkey=None):\n \n arguments = {'roles': roles,\n 'netmask': netmask,\n 'secret': secret,\n 'pubkey': pubkey}\n return self.do_req('PUT',\n self.merchant_api_base_url + '/user/' +\n user_id + '/', arguments)", "docstring": "Update user. Returns the raw response object.\n\nArguments:\nuser_id:\nUser id of user to update\nroles:\nRole\nnetmask:\nLimit user connections by netmask, for example 192.168.1.0/24\nsecret:\nSecret used when authenticating with mCASH\npubkey:\nRSA key used for authenticating by signing", "source": "juraj-google-style"}
243{"code": "class _LazyAutoMapping(OrderedDict[type[PretrainedConfig], _LazyAutoMappingValue]):\n\n def __init__(self, config_mapping, model_mapping) -> None:\n self._config_mapping = config_mapping\n self._reverse_config_mapping = {v: k for k, v in config_mapping.items()}\n self._model_mapping = model_mapping\n self._model_mapping._model_mapping = self\n self._extra_content = {}\n self._modules = {}\n\n def __len__(self) -> int:\n common_keys = set(self._config_mapping.keys()).intersection(self._model_mapping.keys())\n return len(common_keys) + len(self._extra_content)\n\n def __getitem__(self, key: type[PretrainedConfig]) -> _LazyAutoMappingValue:\n if key in self._extra_content:\n return self._extra_content[key]\n model_type = self._reverse_config_mapping[key.__name__]\n if model_type in self._model_mapping:\n model_name = self._model_mapping[model_type]\n return self._load_attr_from_module(model_type, model_name)\n model_types = [k for k, v in self._config_mapping.items() if v == key.__name__]\n for mtype in model_types:\n if mtype in self._model_mapping:\n model_name = self._model_mapping[mtype]\n return self._load_attr_from_module(mtype, model_name)\n raise KeyError(key)\n\n def _load_attr_from_module(self, model_type, attr):\n module_name = model_type_to_module_name(model_type)\n if module_name not in self._modules:\n self._modules[module_name] = importlib.import_module(f'.{module_name}', 'transformers.models')\n return getattribute_from_module(self._modules[module_name], attr)\n\n def keys(self) -> list[type[PretrainedConfig]]:\n mapping_keys = [self._load_attr_from_module(key, name) for key, name in self._config_mapping.items() if key in self._model_mapping.keys()]\n return mapping_keys + list(self._extra_content.keys())\n\n def get(self, key: type[PretrainedConfig], default: _T) -> Union[_LazyAutoMappingValue, _T]:\n try:\n return self.__getitem__(key)\n except KeyError:\n return default\n\n def __bool__(self) -> bool:\n return bool(self.keys())\n\n def values(self) -> list[_LazyAutoMappingValue]:\n mapping_values = [self._load_attr_from_module(key, name) for key, name in self._model_mapping.items() if key in self._config_mapping.keys()]\n return mapping_values + list(self._extra_content.values())\n\n def items(self) -> list[tuple[type[PretrainedConfig], _LazyAutoMappingValue]]:\n mapping_items = [(self._load_attr_from_module(key, self._config_mapping[key]), self._load_attr_from_module(key, self._model_mapping[key])) for key in self._model_mapping.keys() if key in self._config_mapping.keys()]\n return mapping_items + list(self._extra_content.items())\n\n def __iter__(self) -> Iterator[type[PretrainedConfig]]:\n return iter(self.keys())\n\n def __contains__(self, item: type) -> bool:\n if item in self._extra_content:\n return True\n if not hasattr(item, '__name__') or item.__name__ not in self._reverse_config_mapping:\n return False\n model_type = self._reverse_config_mapping[item.__name__]\n return model_type in self._model_mapping\n\n def register(self, key: type[PretrainedConfig], value: _LazyAutoMappingValue, exist_ok=False) -> None:\n \n if hasattr(key, '__name__') and key.__name__ in self._reverse_config_mapping:\n model_type = self._reverse_config_mapping[key.__name__]\n if model_type in self._model_mapping.keys() and (not exist_ok):\n raise ValueError(f\"'{key}' is already used by a Transformers model.\")\n self._extra_content[key] = value", "docstring": "\" A mapping config to object (model or tokenizer for instance) that will load keys and values when it is accessed.\n\nArgs:\n- config_mapping: The map model type to config class\n- model_mapping: The map model type to model (or tokenizer) class", "source": "github-repos"}
244{"code": "def enable_plugin(self, name, timeout=0):\n \n url = self._url('/plugins/{0}/enable', name)\n params = {'timeout': timeout}\n res = self._post(url, params=params)\n self._raise_for_status(res)\n return True", "docstring": "Enable an installed plugin.\n\nArgs:\nname (string): The name of the plugin. The ``:latest`` tag is\noptional, and is the default if omitted.\ntimeout (int): Operation timeout (in seconds). Default: 0\n\nReturns:\n``True`` if successful", "source": "juraj-google-style"}
245{"code": "def read_from_hdx(identifier, configuration=None):\n showcase = Showcase(configuration=configuration)\n result = showcase._load_from_hdx('showcase', identifier)\n if result:\n return showcase\n return None", "docstring": "Reads the showcase given by identifier from HDX and returns Showcase object\n\nArgs:\nidentifier (str): Identifier of showcase\nconfiguration (Optional[Configuration]): HDX configuration. Defaults to global configuration.\n\nReturns:\nOptional[Showcase]: Showcase object if successful read, None if not", "source": "codesearchnet"}
246{"code": "def __init__(self, name, distribution_fn, required_gpus=None, required_physical_gpus=0, required_tpu=False, use_cloud_tpu=False, has_chief=False, num_workers=1, num_ps=0, share_gpu=True, pool_runner_fn=None, no_xla=False):\n object.__init__(self)\n self._name = name\n self._distribution_fn = distribution_fn\n self.required_gpus = required_gpus\n self.required_physical_gpus = required_physical_gpus\n self.required_tpu = required_tpu\n self.use_cloud_tpu = use_cloud_tpu\n self.has_chief = has_chief\n self.num_workers = num_workers\n self.num_ps = num_ps\n self.share_gpu = share_gpu\n self._pool_runner_fn = pool_runner_fn\n self.no_xla = no_xla", "docstring": "Initialize NamedDistribution.\n\nArgs:\nname: Name that will be a part of the name of the test case.\ndistribution_fn: A callable that creates a `tf.distribute.Strategy`.\nrequired_gpus: The number of GPUs that the strategy requires. Only one of\n`required_gpus` and `required_physical_gpus` should be set.\nrequired_physical_gpus: Number of physical GPUs required. Only one of\n`required_gpus` and `required_physical_gpus` should be set.\nrequired_tpu: Whether the strategy requires TPU.\nuse_cloud_tpu: Whether the strategy requires cloud TPU.\nhas_chief: Whether the strategy requires a chief worker.\nnum_workers: The number of workers that the strategy requires.\nnum_ps: The number of parameter servers.\nshare_gpu: Whether to share GPUs among workers.\npool_runner_fn: An optional callable that returns a MultiProcessPoolRunner\nto run the test.\nno_xla: Whether to skip in XLA tests.", "source": "github-repos"}
247{"code": "def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n super(ExtensionInformation, self).read(istream, kmip_version=kmip_version)\n tstream = BytearrayStream(istream.read(self.length))\n self.extension_name.read(tstream, kmip_version=kmip_version)\n if self.is_tag_next(Tags.EXTENSION_TAG, tstream):\n self.extension_tag = ExtensionTag()\n self.extension_tag.read(tstream, kmip_version=kmip_version)\n if self.is_tag_next(Tags.EXTENSION_TYPE, tstream):\n self.extension_type = ExtensionType()\n self.extension_type.read(tstream, kmip_version=kmip_version)\n self.is_oversized(tstream)\n self.validate()", "docstring": "Read the data encoding the ExtensionInformation object and decode it\ninto its constituent parts.\n\nArgs:\nistream (Stream): A data stream containing encoded object data,\nsupporting a read method; usually a BytearrayStream object.\nkmip_version (KMIPVersion): An enumeration defining the KMIP\nversion with which the object will be decoded. Optional,\ndefaults to KMIP 1.0.", "source": "codesearchnet"}
248{"code": "def _ReformatMessageString(self, message_string):\n\n def _PlaceHolderSpecifierReplacer(match_object):\n 'Replaces message string place holders into Python format() style.'\n expanded_groups = []\n for group in match_object.groups():\n try:\n place_holder_number = (int(group, 10) - 1)\n expanded_group = '{{{0:d}:s}}'.format(place_holder_number)\n except ValueError:\n expanded_group = group\n expanded_groups.append(expanded_group)\n return ''.join(expanded_groups)\n if (not message_string):\n return None\n message_string = self._WHITE_SPACE_SPECIFIER_RE.sub('', message_string)\n message_string = self._TEXT_SPECIFIER_RE.sub('\\\\\\\\\\\\1', message_string)\n message_string = self._CURLY_BRACKETS.sub('\\\\1\\\\1', message_string)\n return self._PLACE_HOLDER_SPECIFIER_RE.sub(_PlaceHolderSpecifierReplacer, message_string)", "docstring": "Reformats the message string.\n\nArgs:\nmessage_string (str): message string.\n\nReturns:\nstr: message string in Python format() (PEP 3101) style.", "source": "codesearchnet"}
249{"code": "def evaluate_ising(linear, quad, state):\n if (_numpy and isinstance(state, np.ndarray)):\n return evaluate_ising(linear, quad, state.tolist())\n energy = 0.0\n for (index, value) in uniform_iterator(linear):\n energy += (state[index] * value)\n for ((index_a, index_b), value) in six.iteritems(quad):\n energy += ((value * state[index_a]) * state[index_b])\n return energy", "docstring": "Calculate the energy of a state given the Hamiltonian.\n\nArgs:\nlinear: Linear Hamiltonian terms.\nquad: Quadratic Hamiltonian terms.\nstate: Vector of spins describing the system state.\n\nReturns:\nEnergy of the state evaluated by the given energy function.", "source": "codesearchnet"}
250{"code": "def setColumn(self, header, values):\n if any((isinstance(value, basestring) for value in values)):\n values = list(map(str, values))\n self._impl.setColumnStr(header, values, len(values))\n elif all((isinstance(value, Real) for value in values)):\n values = list(map(float, values))\n self._impl.setColumnDbl(header, values, len(values))\n else:\n print(values)\n raise NotImplementedError", "docstring": "Set the values of a column.\n\nArgs:\nheader: The header of the column to be set.\n\nvalues: The values to set.", "source": "codesearchnet"}
251{"code": "def layer(self, queryset, stylename=None):\n \n cls = RasterLayer if hasattr(queryset, 'image') else VectorLayer\n layer = cls(queryset, style=stylename)\n try:\n style = self.map.find_style(layer.stylename)\n except KeyError:\n self.map.append_style(layer.stylename, layer.style())\n layer.styles.append(layer.stylename)\n self.map.layers.append(layer._layer)\n return layer", "docstring": "Returns a map Layer.\n\nArguments:\nqueryset -- QuerySet for Layer\nKeyword args:\nstylename -- str name of style to apply", "source": "juraj-google-style"}
252{"code": "def set_from_tree(self, address_value_dict):\n for (address, value) in address_value_dict.items():\n if (address in self._state):\n self._state[address].set_result(result=value, from_tree=True)", "docstring": "Set the result for each future at the given addresses with the value\nstored in the merkle database.\n\nArgs:\naddress_value_dict (dict of str: bytes): The unique\nfull addresses that the bytes values should be set with.", "source": "codesearchnet"}
253{"code": "def groups_invite(self, *, channel: str, user: str, **kwargs) -> SlackResponse:\n \n self._validate_xoxp_token()\n kwargs.update({\"channel\": channel, \"user\": user})\n return self.api_call(\"groups.invite\", json=kwargs)", "docstring": "Invites a user to a private channel.\n\nArgs:\nchannel (str): The group id. e.g. 'G1234567890'\nuser (str): The user id. e.g. 'U1234567890'", "source": "juraj-google-style"}
254{"code": "def PluginTagToContent(self, plugin_name):\n \n if plugin_name not in self._plugin_to_tag_to_content:\n raise KeyError('Plugin %r could not be found.' % plugin_name)\n return self._plugin_to_tag_to_content[plugin_name]", "docstring": "Returns a dict mapping tags to content specific to that plugin.\n\nArgs:\nplugin_name: The name of the plugin for which to fetch plugin-specific\ncontent.\n\nRaises:\nKeyError: if the plugin name is not found.\n\nReturns:\nA dict mapping tags to plugin-specific content (which are always strings).\nThose strings are often serialized protos.", "source": "juraj-google-style"}
255{"code": "def Draw(self, stoplist=None, triplist=None, height=520):\n \n output = str()\n if not triplist:\n triplist = []\n if not stoplist:\n stoplist = []\n\n if not self._cache or triplist or stoplist:\n self._gheight = height\n self._tlist=triplist\n self._slist=stoplist\n self._decorators = []\n self._stations = self._BuildStations(stoplist)\n self._cache = \"%s %s %s %s\" % (self._DrawBox(),\n self._DrawHours(),\n self._DrawStations(),\n self._DrawTrips(triplist))\n\n\n\n output = \"%s %s %s %s\" % (self._DrawHeader(),\n self._cache,\n self._DrawDecorators(),\n self._DrawFooter())\n return output", "docstring": "Main interface for drawing the marey graph.\n\nIf called without arguments, the data generated in the previous call\nwill be used. New decorators can be added between calls.\n\nArgs:\n# Class Stop is defined in transitfeed.py\nstoplist: [Stop, Stop, ...]\n# Class Trip is defined in transitfeed.py\ntriplist: [Trip, Trip, ...]\n\nReturns:\n# A string that contain a svg/xml web-page with a marey graph.\n\" <svg width=\"1440\" height=\"520\" version=\"1.1\" ... \"", "source": "juraj-google-style"}
256{"code": "def add_comment(node, text, location='above'):\n anno.setanno(node, 'comment', dict(location=location, text=text), safe=False)\n return node", "docstring": "Add a comment to the given node.\n\nIf the `SourceWithCommentGenerator` class is used these comments will be\noutput as part of the source code.\n\nNote that a node can only contain one comment. Subsequent calls to\n`add_comment` will ovverride the existing comments.\n\nArgs:\nnode: The AST node whose containing statement will be commented.\ntext: A comment string.\nlocation: Where the comment should appear. Valid values are 'above',\n'below' and 'right'\n\nReturns:\nThe node with the comment stored as an annotation.", "source": "codesearchnet"}
257{"code": "def _padded_split(tensor, pieces):\n shape = tensor.shape\n if 1 != len(shape):\n raise ValueError('input tensor must be 1D')\n tensor_len = shape.dims[0].value\n with ops.colocate_with(tensor):\n if tensor_len % pieces != 0:\n chunk_size = 1 + tensor_len \n if pieces > tensor_len:\n pad_len = pieces - tensor_len\n extended_whole = array_ops.concat([tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)\n parts = array_ops.split(extended_whole, pieces)\n return (parts, pad_len)\n elif (pieces - 1) * chunk_size >= tensor_len:\n pad_len = pieces * chunk_size % tensor_len\n extended_whole = array_ops.concat([tensor, array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)\n parts = array_ops.split(extended_whole, pieces)\n return (parts, pad_len)\n else:\n last_chunk_size = tensor_len - (pieces - 1) * chunk_size\n pad_len = chunk_size - last_chunk_size\n piece_lens = [chunk_size for _ in range(pieces - 1)] + [last_chunk_size]\n parts = array_ops.split(tensor, piece_lens)\n parts[-1] = array_ops.concat([parts[-1], array_ops.zeros([pad_len], dtype=tensor.dtype)], 0)\n return (parts, pad_len)\n else:\n return (array_ops.split(tensor, pieces), 0)", "docstring": "Like split for 1D tensors but pads-out case where len % pieces != 0.\n\nArgs:\ntensor: `tf.Tensor` that must be 1D.\npieces: a positive integer specifying the number of pieces into which\ntensor should be split.\n\nReturns:\nlist of `tf.Tensor` of length pieces, which hold the values of\nthin input tensor, in order. The final tensor may\nbe zero-padded on the end to make its size equal to those of all\nof the other tensors.\n\nRaises:\nValueError: The input tensor is not 1D.", "source": "github-repos"}
258{"code": "def update_nanopubstore_start_dt(url: str, start_dt: str):\n hostname = urllib.parse.urlsplit(url)[1]\n start_dates_doc = state_mgmt.get(start_dates_doc_key)\n if (not start_dates_doc):\n start_dates_doc = {'_key': start_dates_doc_key, 'start_dates': [{'nanopubstore': hostname, 'start_dt': start_dt}]}\n state_mgmt.insert(start_dates_doc)\n else:\n for (idx, start_date) in enumerate(start_dates_doc['start_dates']):\n if (start_date['nanopubstore'] == hostname):\n start_dates_doc['start_dates'][idx]['start_dt'] = start_dt\n break\n else:\n start_dates_doc['start_dates'].append({'nanopubstore': hostname, 'start_dt': start_dt})\n state_mgmt.replace(start_dates_doc)", "docstring": "Add nanopubstore start_dt to belapi.state_mgmt collection\n\nArgs:\nurl: url of nanopubstore\nstart_dt: datetime of last query against nanopubstore for new ID's", "source": "codesearchnet"}
259{"code": "def clean(self, value, *_):\n \n\n if not value or not isinstance(value, LocalizedValue):\n return None\n\n \n is_all_null = True\n for lang_code, _ in settings.LANGUAGES:\n if value.get(lang_code) is not None:\n is_all_null = False\n break\n\n \n \n if is_all_null and self.null:\n return None\n\n return value", "docstring": "Cleans the specified value into something we\ncan store in the database.\n\nFor example, when all the language fields are\nleft empty, and the field is allowed to be null,\nwe will store None instead of empty keys.\n\nArguments:\nvalue:\nThe value to clean.\n\nReturns:\nThe cleaned value, ready for database storage.", "source": "juraj-google-style"}
260{"code": "def _findOptionValueAdvAudit(option):\n \n if 'lgpo.adv_audit_data' not in __context__:\n system_root = os.environ.get('SystemRoot', 'C:\\\\Windows')\n f_audit = os.path.join(system_root, 'security', 'audit', 'audit.csv')\n f_audit_gpo = os.path.join(system_root, 'System32', 'GroupPolicy',\n 'Machine', 'Microsoft', 'Windows NT',\n 'Audit', 'audit.csv')\n\n \n if not __salt__['file.file_exists'](f_audit):\n if __salt__['file.file_exists'](f_audit_gpo):\n \n __salt__['file.copy'](f_audit_gpo, f_audit)\n else:\n field_names = _get_audit_defaults('fieldnames')\n \n \n __salt__['file.makedirs'](f_audit)\n __salt__['file.write'](f_audit, ','.join(field_names))\n\n audit_settings = {}\n with salt.utils.files.fopen(f_audit, mode='r') as csv_file:\n reader = csv.DictReader(csv_file)\n\n for row in reader:\n audit_settings.update(\n {row['Subcategory']: row['Setting Value']})\n\n __context__['lgpo.adv_audit_data'] = audit_settings\n\n return __context__['lgpo.adv_audit_data'].get(option, None)", "docstring": "Get the Advanced Auditing policy as configured in\n``C:\\\\Windows\\\\Security\\\\Audit\\\\audit.csv``\n\nArgs:\noption (str): The name of the setting as it appears in audit.csv\n\nReturns:\nbool: ``True`` if successful, otherwise ``False``", "source": "juraj-google-style"}
261{"code": "def flatten(self, d=None):\n \n if d is None:\n d = {}\n if self.name is not None:\n d[self.name] = self\n for child in self.children:\n child.flatten(d=d)\n return d", "docstring": "Flatten tree structure to a one level dictionary.\n\n\nArgs:\nd (dict, optional): output dictionary to update\n\nReturns:\ndict: Node.name -> Node. The returned dictionary includes the\ncurrent Node and all its children.", "source": "juraj-google-style"}
262{"code": "def _revoke(self, http):\n \n self._do_revoke(http, self.refresh_token or self.access_token)", "docstring": "Revokes this credential and deletes the stored copy (if it exists).\n\nArgs:\nhttp: an object to be used to make HTTP requests.", "source": "juraj-google-style"}
263{"code": "def __init__(self, *, content: content_api.ProcessorContentTypes | None=None, content_factory: PreambleFactory | None=None):\n if content is not None and content_factory is not None:\n raise ValueError('Only one of `content` and `content_factory` must be provided.')\n self._content = None if content is None else content_api.ProcessorContent(content)\n self._content_factory = content_factory", "docstring": "Constructs a Preamble processor.\n\nArgs:\ncontent: content to prepend.\ncontent_factory: function for returning a content given no input. This is\nhelpful for when contents are not fully known on __init__, e.g. if they\ndepend on the user or time of the request.\n\nRaises:\nValueError if both `content` and `content_factory` are provided.", "source": "github-repos"}
264{"code": "def get(self, request, customer_uuid):\n context = self._build_context(request, customer_uuid)\n manage_learners_form = ManageLearnersForm(user=request.user, enterprise_customer=context[self.ContextParameters.ENTERPRISE_CUSTOMER])\n context.update({self.ContextParameters.MANAGE_LEARNERS_FORM: manage_learners_form})\n return render(request, self.template, context)", "docstring": "Handle GET request - render linked learners list and \"Link learner\" form.\n\nArguments:\nrequest (django.http.request.HttpRequest): Request instance\ncustomer_uuid (str): Enterprise Customer UUID\n\nReturns:\ndjango.http.response.HttpResponse: HttpResponse", "source": "codesearchnet"}
265{"code": "def _safe_get(self, revision, key):\n \n if self.has_revision(revision):\n return self.raw_answers[revision].get(key)\n else:\n return None", "docstring": "Get an answer data (vote or rationale) by revision\n\nArgs:\nrevision (int): the revision number for student answer, could be\n0 (original) or 1 (revised)\nkey (str); key for retrieve answer data, could be VOTE_KEY or\nRATIONALE_KEY\n\nReturns:\nthe answer data or None if revision doesn't exists", "source": "juraj-google-style"}
266{"code": "def register_items(self, items):\n for item in items:\n item.set_parent(self)\n self.items.extend(items)", "docstring": "Bulk ``register_item``.\n\nArgs:\nitems (iterable[Tree]):\nSequence of nodes to be registered as children.", "source": "codesearchnet"}
267{"code": "def broadcast_recv_v2(shape, dtype, group_size, group_key, instance_key, communication_hint='auto', timeout=0):\n return gen_collective_ops.collective_bcast_recv_v2(T=dtype, group_size=group_size, group_key=group_key, instance_key=instance_key, shape=shape, communication_hint=communication_hint.lower(), timeout_seconds=timeout)", "docstring": "Receives a broadcasts tensor, across devices.\n\nArgs:\nshape: an int tensor. Shape of the tensor to be received.\ndtype: Type of the tensor to be received.\ngroup_size: an int32 tensor. One plus the number of receiving tensors, i.e.\nthe total number of devices participating. Each tensor must reside on a\ndifferent device.\ngroup_key: an int32 tensor identifying the group of devices.\ninstance_key: an int32 tensor identifying the participating group of Ops.\ncommunication_hint: preferred collective communication. The implementation\nmay fall back to another mechanism. Options include `auto`, `ring`, and\n`nccl`.\ntimeout: If set to a non zero, set a completion timeout to detect staleness.\nIf the timer goes off, a DeadlineExceededError is raised.\nThe timeout value in seconds. This feature is experimental.\n\nReturns:\nAn Op implementing the broadcast receive.", "source": "github-repos"}
268{"code": "def _GetAccountsData(self, metadata_dict):\n \n instance_data, project_data = self._GetInstanceAndProjectAttributes(\n metadata_dict)\n valid_keys = [instance_data.get('sshKeys'), instance_data.get('ssh-keys')]\n block_project = instance_data.get('block-project-ssh-keys', '').lower()\n if block_project != 'true' and not instance_data.get('sshKeys'):\n valid_keys.append(project_data.get('ssh-keys'))\n valid_keys.append(project_data.get('sshKeys'))\n accounts_data = '\\n'.join([key for key in valid_keys if key])\n return self._ParseAccountsData(accounts_data)", "docstring": "Get the user accounts specified in metadata server contents.\n\nArgs:\nmetadata_dict: json, the deserialized contents of the metadata server.\n\nReturns:\ndict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.", "source": "juraj-google-style"}
269{"code": "def _recompute_attrs_type_from_mro(self, all_attrs: dict[str, Attribute], type_params: 'dict[str | int, _base.BaseValue]') -> None:\n for typ_name, typ_obj in type_params.items():\n for attr in all_attrs.values():\n if typ_name == attr.typ.cls.name:\n attr.typ = typ_obj", "docstring": "Traverse the MRO and apply Generic type params to class attributes.\n\nThis IS REQUIRED for dataclass instances that inherits from a Generic.\n\nArgs:\nall_attrs: All __init__ attributes of a class.\ntype_params: List of ParameterizedClass instances that will override\nTypeVar attributes in all_attrs.", "source": "github-repos"}
270{"code": "def check_exists(self):\n response = self.repo.api.http_request('HEAD', self.uri)\n self.status_code = response.status_code\n if (self.status_code == 200):\n self.exists = True\n elif (self.status_code == 410):\n self.exists = False\n elif (self.status_code == 404):\n self.exists = False\n return self.exists", "docstring": "Check if resource exists, update self.exists, returns\n\nReturns:\nNone: sets self.exists", "source": "codesearchnet"}
271{"code": "def render_unregistered(error=None):\n \n return template(\n read_index_template(),\n registered=False,\n error=error,\n seeder_data=None,\n url_id=None,\n )", "docstring": "Render template file for the unregistered user.\n\nArgs:\nerror (str, default None): Optional error message.\n\nReturns:\nstr: Template filled with data.", "source": "juraj-google-style"}
272{"code": "def _hat_integral(self, x):\n x = tf.cast(x, self.power.dtype)\n t = (self.power - 1.0)\n return tf.exp((((- t) * tf.math.log1p(x)) - tf.math.log(t)))", "docstring": "Integral of the `hat` function, used for sampling.\n\nWe choose a `hat` function, h(x) = x^(-power), which is a continuous\n(unnormalized) density touching each positive integer at the (unnormalized)\npmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt;\nwhich is needed for sampling purposes.\n\nArguments:\nx: A Tensor of points x at which to evaluate H(x).\n\nReturns:\nA Tensor containing evaluation H(x) at x.", "source": "codesearchnet"}
273{"code": "def get(self, key):\n \n data = self._store.get(key)\n if not data:\n return None\n value, expire = data\n if expire and time.time() > expire:\n del self._store[key]\n return None\n return value", "docstring": "Get an item from the cache\nArgs:\nkey: item key\nReturns:\nthe value of the item or None if the item isn't in the cache", "source": "juraj-google-style"}
274{"code": "def ragged_shape(input: ragged_tensor.Ragged, name: Optional[str]=None, out_type=dtypes.int32) -> dynamic_ragged_shape.DynamicRaggedShape:\n with ops.name_scope(name, 'RaggedShape', [input]):\n return dynamic_ragged_shape.DynamicRaggedShape.from_tensor(input, out_type)", "docstring": "Returns the shape of a RaggedTensor.\n\nArgs:\ninput: A `RaggedTensor`\nname: A name for the operation (optional).\nout_type: dtype used to encode the shape.\n\nReturns:\nA `tf.experimental.DynamicRaggedShape`", "source": "github-repos"}
275{"code": "def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression:\n \n if isinstance(expression, Operation):\n if hasattr(expression, 'variable_name'):\n variable_name = renaming.get(expression.variable_name, expression.variable_name)\n return create_operation_expression(\n expression, [rename_variables(o, renaming) for o in op_iter(expression)], variable_name=variable_name\n )\n operands = [rename_variables(o, renaming) for o in op_iter(expression)]\n return create_operation_expression(expression, operands)\n elif isinstance(expression, Expression):\n expression = expression.__copy__()\n expression.variable_name = renaming.get(expression.variable_name, expression.variable_name)\n return expression", "docstring": "Rename the variables in the expression according to the given dictionary.\n\nArgs:\nexpression:\nThe expression in which the variables are renamed.\nrenaming:\nThe renaming dictionary. Maps old variable names to new ones.\nVariable names not occuring in the dictionary are left unchanged.\n\nReturns:\nThe expression with renamed variables.", "source": "juraj-google-style"}
276{"code": "def config_from_url(u, **kwargs):\n path = u.path.lstrip('/').split('/')\n if ((len(path) > 2) or (not path)):\n raise AssertionError('zmq url format: zmq:\n typ = path[0].upper()\n try:\n topic = path[1]\n except IndexError as _:\n topic = ''\n param = dict(urllib.parse.parse_qsl(u.query))\n transport = param.get('transport', 'tcp')\n _id = ('%s-%s-%s-%s' % (typ, topic, transport, u.netloc))\n if (kwargs.get('prefix') is not None):\n _id = ('%s-%s' % (kwargs.get('prefix'), _id))\n return {'id': _id, 'typ_str': typ, 'typ': getattr(zmq, typ), 'topic': topic, 'transport': transport, 'url': ('%s:", "docstring": "Returns dict containing zmq configuration arguments\nparsed from xbahn url\n\nArguments:\n\n- u (urlparse.urlparse result)\n\nReturns:\n\ndict:\n- id (str): connection index key\n- typ_str (str): string representation of zmq socket type\n- typ (int): zmq socket type (PUB, SUB, REQ, REP, PUSH, PULL)\n- topic (str): subscription topic\n- url (str): url to use with zmq's bind function", "source": "codesearchnet"}
277{"code": "async def on_message(message):\n \n\n \n server = message.server\n author = message.author\n channel = message.channel\n content = message.content\n\n data = datatools.get_data()\n\n if not data[\"discord\"][\"servers\"][server.id][_data.modulename][\"activated\"]:\n return\n\n \n if server is not None and author != channel.server.me:\n \n if channel.server.me in message.mentions:\n\n logger.info(\"Bot was mentioned, summoning Mitsuku\")\n await client.send_typing(channel)\n\n \n if channel.id not in data[\"discord\"][\"servers\"][server.id][_data.modulename][\"channels\"]:\n new_serverdata = data\n new_serverdata[\"discord\"][\"servers\"][server.id][_data.modulename][\"channels\"][channel.id] = \\\n api_mitsuku.get_botcust2()\n datatools.write_data(new_serverdata)\n\n \n botcust2 = data[\"discord\"][\"servers\"][server.id][_data.modulename][\"channels\"][channel.id]\n\n \n content = content.replace(\"<@{}>\".format(str(channel.server.me.id)), ' ')\n content = content.replace(\"<@!{}>\".format(str(channel.server.me.id)), ' ')\n\n \n if botcust2:\n response = api_mitsuku.query(botcust2, content)\n if response:\n await client.send_message(channel, response)\n else:\n await client.send_message(channel, \"```Couldn't get readable response from Mitsuku.```\")\n else:\n await client.send_message(channel, \"```Couldn't initialise with Mitsuku.```\")", "docstring": "The on_message event handler for this module\n\nArgs:\nmessage (discord.Message): Input message", "source": "juraj-google-style"}
278{"code": "def output_forecasts_csv(self, forecasts, mode, csv_path, run_date_format=\"%Y%m%d-%H%M\"):\n \n merged_forecasts = pd.merge(forecasts[\"condition\"],\n forecasts[\"dist\"],\n on=[\"Step_ID\",\"Track_ID\",\"Ensemble_Member\",\"Forecast_Hour\"])\n all_members = self.data[mode][\"combo\"][\"Ensemble_Member\"]\n members = np.unique(all_members)\n all_run_dates = pd.DatetimeIndex(self.data[mode][\"combo\"][\"Run_Date\"])\n run_dates = pd.DatetimeIndex(np.unique(all_run_dates))\n print(run_dates)\n for member in members:\n for run_date in run_dates:\n mem_run_index = (all_run_dates == run_date) & (all_members == member)\n member_forecast = merged_forecasts.loc[mem_run_index]\n member_forecast.to_csv(join(csv_path, \"hail_forecasts_{0}_{1}_{2}.csv\".format(self.ensemble_name,\n member,\n run_date.strftime\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t (run_date_format))))\n return", "docstring": "Output hail forecast values to csv files by run date and ensemble member.\n\nArgs:\nforecasts:\nmode:\ncsv_path:\nReturns:", "source": "juraj-google-style"}
279{"code": "def load_config(self, settings=None):\n \n self._load_defaults()\n if settings:\n self.update(settings)\n else:\n config_paths = _get_config_files()\n for p in config_paths:\n conf = _process_config_file([p])\n self.update(conf)\n self._loaded = True\n self._validate()", "docstring": "Load the configuration either from the config file, or from the given settings.\n\nArgs:\nsettings (dict): If given, the settings are pulled from this dictionary. Otherwise, the\nconfig file is used.", "source": "juraj-google-style"}
280{"code": "def pbs_for_set_no_merge(document_path, document_data):\n \n extractor = DocumentExtractor(document_data)\n\n if extractor.deleted_fields:\n raise ValueError(\n \"Cannot apply DELETE_FIELD in a set request without \"\n \"specifying 'merge=True' or 'merge=[field_paths]'.\"\n )\n\n \n \n write_pbs = [extractor.get_update_pb(document_path)]\n\n if extractor.has_transforms:\n transform_pb = extractor.get_transform_pb(document_path)\n write_pbs.append(transform_pb)\n\n return write_pbs", "docstring": "Make ``Write`` protobufs for ``set()`` methods.\n\nArgs:\ndocument_path (str): A fully-qualified document path.\ndocument_data (dict): Property names and values to use for\nreplacing a document.\n\nReturns:\nList[google.cloud.firestore_v1beta1.types.Write]: One\nor two ``Write`` protobuf instances for ``set()``.", "source": "juraj-google-style"}
281{"code": "async def event_wait(event: asyncio.Event, timeout=None):\n if (timeout is None):\n (await event.wait())\n return True\n try:\n (await asyncio.wait_for(event.wait(), timeout))\n except asyncio.TimeoutError:\n return False\n return True", "docstring": "Wait on an an asyncio event with an optional timeout\n\nReturns:\ntrue if the event got set, None if timed out", "source": "codesearchnet"}
282{"code": "def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, causal_attention_mask: torch.Tensor, output_attentions: Optional[bool]=False) -> Tuple[torch.FloatTensor]:\n residual = hidden_states\n hidden_states = self.layer_norm1(hidden_states)\n hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, causal_attention_mask=causal_attention_mask, output_attentions=output_attentions)\n hidden_states = residual + hidden_states\n residual = hidden_states\n hidden_states = self.layer_norm2(hidden_states)\n hidden_states = self.mlp(hidden_states)\n hidden_states = residual + hidden_states\n outputs = (hidden_states,)\n if output_attentions:\n outputs += (attn_weights,)\n return outputs", "docstring": "Args:\nhidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\nattention_mask (`torch.FloatTensor`): attention mask of size\n`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.\n`(config.encoder_attention_heads,)`.\noutput_attentions (`bool`, *optional*):\nWhether or not to return the attentions tensors of all attention layers. See `attentions` under\nreturned tensors for more detail.", "source": "github-repos"}
283{"code": "def _check(cls, name, val, can_be_zero=False, val_type=float):\n valid_types = [val_type]\n if (val_type is float):\n valid_types.append(int)\n if (type(val) not in valid_types):\n raise TypeError(('Expect type %s for parameter %s' % (val_type.__name__, name)))\n if (val < 0):\n raise ValueError(('Value for parameter %s has to be greater than 0' % name))\n if ((not can_be_zero) and (val == 0)):\n raise ValueError(('Value for parameter %s can not be 0' % name))\n return val", "docstring": "Check init arguments.\n\nArgs:\nname: name of the argument. For logging purpose.\nval: value. Value has to be non negative number.\ncan_be_zero: whether value can be zero.\nval_type: Python type of the value.\n\nReturns:\nThe value.\n\nRaises:\nValueError: when invalid value is passed in.\nTypeError: when invalid value type is passed in.", "source": "codesearchnet"}
284{"code": "def DetermineType(value):\n object_type = type(value)\n if (not hasattr(object_type, '__name__')):\n return None\n type_string = getattr(object_type, '__module__', '')\n if type_string:\n type_string += '.'\n type_string += object_type.__name__\n return type_string", "docstring": "Determines the type of val, returning a \"full path\" string.\n\nFor example:\nDetermineType(5) -> __builtin__.int\nDetermineType(Foo()) -> com.google.bar.Foo\n\nArgs:\nvalue: Any value, the value is irrelevant as only the type metadata\nis checked\n\nReturns:\nType path string. None if type cannot be determined.", "source": "codesearchnet"}
285{"code": "def mape(y, p):\n \n\n filt = np.abs(y) > EPS\n return np.mean(np.abs(1 - p[filt] / y[filt]))", "docstring": "Mean Absolute Percentage Error (MAPE).\n\nArgs:\ny (numpy.array): target\np (numpy.array): prediction\n\nReturns:\ne (numpy.float64): MAPE", "source": "juraj-google-style"}
286{"code": "def _evolve(self, state, qargs=None):\n \n \n if qargs is not None:\n return SuperOp(self)._evolve(state, qargs)\n\n \n state = self._format_state(state)\n if state.shape[0] != self._input_dim:\n raise QiskitError(\n \"QuantumChannel input dimension is not equal to state dimension.\"\n )\n if state.ndim == 1 and self._data[1] is None and len(\n self._data[0]) == 1:\n \n \n return np.dot(self._data[0][0], state)\n \n state = self._format_state(state, density_matrix=True)\n kraus_l, kraus_r = self._data\n if kraus_r is None:\n kraus_r = kraus_l\n return np.einsum('AiB,BC,AjC->ij', kraus_l, state,\n np.conjugate(kraus_r))", "docstring": "Evolve a quantum state by the QuantumChannel.\n\nArgs:\nstate (QuantumState): The input statevector or density matrix.\nqargs (list): a list of QuantumState subsystem positions to apply\nthe operator on.\n\nReturns:\nQuantumState: the output quantum state.\n\nRaises:\nQiskitError: if the operator dimension does not match the\nspecified QuantumState subsystem dimensions.", "source": "juraj-google-style"}
287{"code": "def get_smeared_densities(self, sigma):\n \n from scipy.ndimage.filters import gaussian_filter1d\n smeared_dens = {}\n diff = [self.energies[i + 1] - self.energies[i]\n for i in range(len(self.energies) - 1)]\n avgdiff = sum(diff) / len(diff)\n for spin, dens in self.densities.items():\n smeared_dens[spin] = gaussian_filter1d(dens, sigma / avgdiff)\n return smeared_dens", "docstring": "Returns the Dict representation of the densities, {Spin: densities},\nbut with a Gaussian smearing of std dev sigma applied about the fermi\nlevel.\n\nArgs:\nsigma: Std dev of Gaussian smearing function.\n\nReturns:\nDict of Gaussian-smeared densities.", "source": "juraj-google-style"}
288{"code": "def get_mask(self, layers=None, output='vector', in_global_mask=True):\n if in_global_mask:\n output = 'vector'\n if (layers is None):\n layers = self.layers.keys()\n elif (not isinstance(layers, list)):\n layers = [layers]\n layers = map((lambda x: (x if isinstance(x, string_types) else self.stack[x])), layers)\n layers = [self.layers[l] for l in layers if (l in self.layers)]\n layers.append(self.full)\n layers = np.vstack(layers).T.astype(bool)\n mask = layers.all(axis=1)\n mask = self.get_image(mask, output)\n return (mask[self.global_mask] if in_global_mask else mask)", "docstring": "Set the current mask by taking the conjunction of all specified\nlayers.\n\nArgs:\nlayers: Which layers to include. See documentation for add() for\nformat.\ninclude_global_mask: Whether or not to automatically include the\nglobal mask (i.e., self.volume) in the conjunction.", "source": "codesearchnet"}
289{"code": "def nice_join(seq, sep=', ', conjuction='or'):\n seq = [str(x) for x in seq]\n if ((len(seq) <= 1) or (conjuction is None)):\n return sep.join(seq)\n else:\n return ('%s %s %s' % (sep.join(seq[:(- 1)]), conjuction, seq[(- 1)]))", "docstring": "Join together sequences of strings into English-friendly phrases using\nthe conjunction ``or`` when appropriate.\n\nArgs:\nseq (seq[str]) : a sequence of strings to nicely join\nsep (str, optional) : a sequence delimiter to use (default: \", \")\nconjunction (str or None, optional) : a conjuction to use for the last\ntwo items, or None to reproduce basic join behaviour (default: \"or\")\n\nReturns:\na joined string\n\nExamples:\n>>> nice_join([\"a\", \"b\", \"c\"])\n'a, b or c'", "source": "codesearchnet"}
290{"code": "def before_starting_server(self):", "docstring": "Performs the preparation steps before starting the remote server.\n\nFor example, subclass can check or modify the device settings at this\nstage.\n\nNOTE: Any error at this stage will abort the initialization without cleanup.\nSo do not acquire resources in this function, or this function should\nrelease the acquired resources if an error occurs.\n\nRaises:\nerrors.ServerStartPreCheckError: when prechecks for starting the server\nfailed.", "source": "github-repos"}
291{"code": "def AtMaximumDepth(self, search_depth):\n \n if self._location_segments is not None:\n if search_depth >= self._number_of_location_segments:\n return True\n\n return False", "docstring": "Determines if the find specification is at maximum depth.\n\nArgs:\nsearch_depth (int): number of location path segments to compare.\n\nReturns:\nbool: True if at maximum depth, False if not.", "source": "juraj-google-style"}
292{"code": "def create(self, path, mime_type='application/octet-stream', compression_type=CompressionTypes.AUTO):\n return self._path_open(path, 'wb', mime_type, compression_type)", "docstring": "Returns a write channel for the given file path.\n\nArgs:\npath: string path of the file object to be written to the system\nmime_type: MIME type to specify the type of content in the file object\ncompression_type: Type of compression to be used for this object\n\nReturns: file handle with a close function for the user to use", "source": "github-repos"}
293{"code": "def broadcast_to(x, shape):\n if any_symbolic_tensors((x,)):\n return BroadcastTo(shape=shape).symbolic_call(x)\n return backend.numpy.broadcast_to(x, shape)", "docstring": "Broadcast a tensor to a new shape.\n\nArgs:\nx: The tensor to broadcast.\nshape: The shape of the desired tensor. A single integer `i` is\ninterpreted as `(i,)`.\n\nReturns:\nA tensor with the desired shape.\n\nExamples:\n>>> x = keras.ops.array([1, 2, 3])\n>>> keras.ops.broadcast_to(x, (3, 3))\narray([[1, 2, 3],\n[1, 2, 3],\n[1, 2, 3]])", "source": "github-repos"}
294{"code": "def add_review(self, reviewer, product, review, date=None):\n \n if not isinstance(reviewer, self._reviewer_cls):\n raise TypeError(\n \"Type of given reviewer isn't acceptable:\", reviewer,\n \", expected:\", self._reviewer_cls)\n elif not isinstance(product, self._product_cls):\n raise TypeError(\n \"Type of given product isn't acceptable:\", product,\n \", expected:\", self._product_cls)\n r = self._review_cls(review, date=date)\n self.graph.add_edge(reviewer, product, review=r)\n return r", "docstring": "Add a new review from a given reviewer to a given product.\n\nArgs:\nreviewer: an instance of Reviewer.\nproduct: an instance of Product.\nreview: a float value.\ndate: date the review issued.\n\nReturns:\nthe added new review object.\n\nRaises:\nTypeError: when given reviewer and product aren't instance of\nspecified reviewer and product class when this graph is constructed.", "source": "juraj-google-style"}
295{"code": "def remote_file(self, branch='master', filename=''):\n \n LOG.info('Retrieving \"%s\" from \"%s\".', filename, self.git_short)\n\n file_contents = ''\n\n try:\n file_blob = self.project.files.get(file_path=filename, ref=branch)\n except gitlab.exceptions.GitlabGetError:\n file_blob = None\n\n LOG.debug('GitLab file response:\\n%s', file_blob)\n\n if not file_blob:\n msg = 'Project \"{0}\" is missing file \"{1}\" in \"{2}\" branch.'.format(self.git_short, filename, branch)\n LOG.warning(msg)\n raise FileNotFoundError(msg)\n else:\n file_contents = b64decode(file_blob.content).decode()\n\n LOG.debug('Remote file contents:\\n%s', file_contents)\n return file_contents", "docstring": "Read the remote file on Git Server.\n\nArgs:\nbranch (str): Git Branch to find file.\nfilename (str): Name of file to retrieve relative to root of\nrepository.\n\nReturns:\nstr: Contents of remote file.\n\nRaises:\nFileNotFoundError: Requested file missing.", "source": "juraj-google-style"}
296{"code": "class IncSlidingMeanTracker(IncMeanTracker):\n\n def __init__(self, window_size):\n super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)", "docstring": "Sliding window mean tracker using incremental calculation.\n\nArgs:\nwindow_size: The size of the sliding window.", "source": "github-repos"}
297{"code": "def get_added_vocab(self) -> dict[str, int]:\n return self._added_tokens_encoder", "docstring": "Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from\nthe fast call because for now we always add the tokens even if they are already in the vocabulary. This is\nsomething we should change.\n\nReturns:\n`Dict[str, int]`: The added tokens.", "source": "github-repos"}
298{"code": "def to_query(self, fields=None):\n \n \n from . import _query\n if fields is None:\n fields = '*'\n elif isinstance(fields, list):\n fields = ','.join(fields)\n return _query.Query('SELECT %s FROM %s' % (fields, self._repr_sql_()), context=self._context)", "docstring": "Return a Query for this Table.\n\nArgs:\nfields: the fields to return. If None, all fields will be returned. This can be a string\nwhich will be injected into the Query after SELECT, or a list of field names.\n\nReturns:\nA Query object that will return the specified fields from the records in the Table.", "source": "juraj-google-style"}
299{"code": "def _add_material(self, x_bot_left, y_bot_left, x_top_right, y_top_right, n_material, angle=0):\n x_mask = np.logical_and((x_bot_left <= self.x), (self.x <= x_top_right))\n y_mask = np.logical_and((y_bot_left <= self.y), (self.y <= y_top_right))\n xy_mask = np.kron(y_mask, x_mask).reshape((y_mask.size, x_mask.size))\n self.n[xy_mask] = n_material\n if angle:\n self._add_triangular_sides(xy_mask, angle, y_top_right, y_bot_left, x_top_right, x_bot_left, n_material)\n return self.n", "docstring": "A low-level function that allows writing a rectangle refractive\nindex profile to a `Structure`.\n\nArgs:\nx_bot_left (float): The bottom-left x-coordinate of the\nrectangle.\ny_bot_left (float): The bottom-left y-coordinate of the\nrectangle.\nx_top_right (float): The top-right x-coordinate of the\nrectangle.\ny_top_right (float): The top-right y-coordinate of the\nrectangle.\nn_material (float): The refractive index of the points\nencompassed by the defined rectangle.\nangle (float): The angle in degrees of the sidewalls\nof the defined rectangle. Default is 0. This\nis useful for creating a ridge with angled\nsidewalls.", "source": "codesearchnet"}
300{"code": "def _ParseFileEntry(self, knowledge_base, file_entry):\n file_object = file_entry.GetFileObject()\n try:\n self._ParseFileData(knowledge_base, file_object)\n finally:\n file_object.close()", "docstring": "Parses a file entry for a preprocessing attribute.\n\nArgs:\nknowledge_base (KnowledgeBase): to fill with preprocessing information.\nfile_entry (dfvfs.FileEntry): file entry that contains the artifact\nvalue data.\n\nRaises:\nPreProcessFail: if the preprocessing fails.", "source": "codesearchnet"}
301{"code": "def plot(self, figsize=None, rotation=45):\n \n\n fig, ax = plt.subplots(figsize=figsize)\n\n plt.imshow(self._cm, interpolation='nearest', cmap=plt.cm.Blues, aspect='auto')\n plt.title('Confusion matrix')\n plt.colorbar()\n tick_marks = np.arange(len(self._labels))\n plt.xticks(tick_marks, self._labels, rotation=rotation)\n plt.yticks(tick_marks, self._labels)\n if isinstance(self._cm, list):\n \n thresh = max(max(self._cm)) / 2.\n for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):\n plt.text(j, i, self._cm[i][j], horizontalalignment=\"center\",\n color=\"white\" if self._cm[i][j] > thresh else \"black\")\n else:\n \n thresh = self._cm.max() / 2.\n for i, j in itertools.product(range(len(self._labels)), range(len(self._labels))):\n plt.text(j, i, self._cm[i, j], horizontalalignment=\"center\",\n color=\"white\" if self._cm[i, j] > thresh else \"black\")\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')", "docstring": "Plot the confusion matrix.\n\nArgs:\nfigsize: tuple (x, y) of ints. Sets the size of the figure\nrotation: the rotation angle of the labels on the x-axis.", "source": "juraj-google-style"}
302{"code": "def save(self, path, compressed=True, exist_ok=False):\n \n path = os.path.expandvars(os.path.expanduser(path))\n if os.path.isfile(path) and not exist_ok:\n raise OSError(17, os.strerror(17), path)\n\n if os.path.isdir(path):\n path = os.path.join(path, \"out.gdg\")\n\n if compressed:\n bytes_written = cgaddag.gdg_save_compressed(self.gdg, path.encode(\"ascii\"))\n else:\n bytes_written = cgaddag.gdg_save(self.gdg, path.encode(\"ascii\"))\n\n if bytes_written == -1:\n errno = ctypes.c_int.in_dll(ctypes.pythonapi, \"errno\").value\n raise OSError(errno, os.strerror(errno), path)\n\n return bytes_written", "docstring": "Save the GADDAG to file.\n\nArgs:\npath: path to save the GADDAG to.\ncompressed: compress the saved GADDAG using gzip.\nexist_ok: overwrite existing file at `path`.", "source": "juraj-google-style"}
303{"code": "def prefix2ns(self, prefix: YangIdentifier, mid: ModuleId) -> YangIdentifier:\n try:\n mdata = self.modules[mid]\n except KeyError:\n raise ModuleNotRegistered(*mid) from None\n try:\n return mdata.prefix_map[prefix][0]\n except KeyError:\n raise UnknownPrefix(prefix, mid) from None", "docstring": "Return the namespace corresponding to a prefix.\n\nArgs:\nprefix: Prefix associated with a module and its namespace.\nmid: Identifier of the module in which the prefix is declared.\n\nRaises:\nModuleNotRegistered: If `mid` is not registered in the data model.\nUnknownPrefix: If `prefix` is not declared.", "source": "codesearchnet"}
304{"code": "def read32(self, offset):\n \n if not isinstance(offset, (int, long)):\n raise TypeError(\"Invalid offset type, should be integer.\")\n\n offset = self._adjust_offset(offset)\n self._validate_offset(offset, 4)\n return struct.unpack(\"=L\", self.mapping[offset:offset + 4])[0]", "docstring": "Read 32-bits from the specified `offset` in bytes, relative to the\nbase physical address of the MMIO region.\n\nArgs:\noffset (int, long): offset from base physical address, in bytes.\n\nReturns:\nint: 32-bit value read.\n\nRaises:\nTypeError: if `offset` type is invalid.\nValueError: if `offset` is out of bounds.", "source": "juraj-google-style"}
305{"code": "def upload_to_metta(train_features_path, train_labels_path, test_features_path, test_labels_path, train_quarter, test_quarter, num_dimensions):\n \n train_config = metta_config(train_quarter, num_dimensions)\n test_config = metta_config(test_quarter, num_dimensions)\n\n X_train = pd.read_csv(train_features_path, sep=',')\n X_train.columns = ['doc2vec_'+str(i) for i in range(X_train.shape[1])]\n \n Y_train = pd.read_csv(train_labels_path)\n Y_train.columns = ['onet_soc_code']\n train = pd.concat([X_train, Y_train], axis=1)\n\n X_test = pd.read_csv(test_features_path, sep=',')\n X_test.columns = ['doc2vec_'+str(i) for i in range(X_test.shape[1])]\n \n Y_test = pd.read_csv(test_labels_path)\n Y_test.columns = ['onet_soc_code']\n test = pd.concat([X_test, Y_test], axis=1)\n \n \n \n \n metta.archive_train_test(\n train_config,\n X_train,\n test_config,\n X_test,\n directory='wdi'\n )", "docstring": "Store train and test matrices using metta\n\nArgs:\ntrain_features_path (str) Path to matrix with train features\ntrain_labels_path (str) Path to matrix with train labels\ntest_features_path (str) Path to matrix with test features\ntest_labels_path (str) Path to matrix with test labels\ntrain_quarter (str) Quarter of train matrix\ntest_quarter (str) Quarter of test matrix\nnum_dimensions (int) Number of features", "source": "juraj-google-style"}
306{"code": "def CheckSchema(self, database):\n \n schema_match = False\n if self.SCHEMAS:\n for schema in self.SCHEMAS:\n if database and database.schema == schema:\n schema_match = True\n\n return schema_match", "docstring": "Checks the schema of a database with that defined in the plugin.\n\nArgs:\ndatabase (SQLiteDatabase): database.\n\nReturns:\nbool: True if the schema of the database matches that defined by\nthe plugin, or False if the schemas do not match or no schema\nis defined by the plugin.", "source": "juraj-google-style"}
307{"code": "def _ConvertValueBinaryDataToFloatingPointValue(self, value):\n \n if not value:\n return None\n\n value_length = len(value)\n if value_length not in (4, 8):\n raise errors.ParseError('Unsupported value data size: {0:d}'.format(\n value_length))\n\n if value_length == 4:\n floating_point_map = self._GetDataTypeMap('float32le')\n elif value_length == 8:\n floating_point_map = self._GetDataTypeMap('float64le')\n\n try:\n return self._ReadStructureFromByteStream(value, 0, floating_point_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError(\n 'Unable to parse floating-point value with error: {0!s}'.format(\n exception))", "docstring": "Converts a binary data value into a floating-point value.\n\nArgs:\nvalue (bytes): binary data value containing an ASCII string or None.\n\nReturns:\nfloat: floating-point representation of binary data value or None if\nvalue is not set.\n\nRaises:\nParseError: if the floating-point value data size is not supported or\nif the value cannot be parsed.", "source": "juraj-google-style"}
308{"code": "def do_put(endpoint, body, access_token):\n headers = {'content-type': 'application/json', 'Authorization': ('Bearer ' + access_token)}\n headers['User-Agent'] = get_user_agent()\n return requests.put(endpoint, data=body, headers=headers)", "docstring": "Do an HTTP PUT request and return JSON.\n\nArgs:\nendpoint (str): Azure Resource Manager management endpoint.\nbody (str): JSON body of information to put.\naccess_token (str): A valid Azure authentication token.\n\nReturns:\nHTTP response. JSON body.", "source": "codesearchnet"}
309{"code": "def from_json_value(v):\n if isinstance(v, extra_types.JsonValue):\n if v.string_value is not None:\n return v.string_value\n elif v.boolean_value is not None:\n return v.boolean_value\n elif v.integer_value is not None:\n return v.integer_value\n elif v.double_value is not None:\n return v.double_value\n elif v.array_value is not None:\n return from_json_value(v.array_value)\n elif v.object_value is not None:\n return from_json_value(v.object_value)\n elif v.is_null:\n return None\n elif isinstance(v, extra_types.JsonArray):\n return [from_json_value(e) for e in v.entries]\n elif isinstance(v, extra_types.JsonObject):\n return {p.key: from_json_value(p.value) for p in v.properties}\n raise TypeError('Cannot convert %s from a JSON value.' % repr(v))", "docstring": "For internal use only; no backwards-compatibility guarantees.\n\nConverts ``extra_types.JsonValue`` objects into Python objects.\n\nArgs:\nv: ``JsonValue`` object to be converted.\n\nReturns:\nA Python object structured as values, lists, and dictionaries corresponding\nto ``JsonValue``, ``JsonArray`` and ``JsonObject`` types.\n\nRaises:\nTypeError: if the ``JsonValue`` object contains a type that is\nnot supported.\n\nThe types supported are ``str``, ``bool``, ``list``, ``dict``, and ``None``.\nThe Dataflow API returns JsonValue(s) in many places and it is quite\nconvenient to be able to convert these hierarchical objects to much simpler\nPython objects.", "source": "github-repos"}
310{"code": "def print_level(log_function, fmt, level, *args):\n if _SILENT:\n return\n msg = (fmt % args)\n spaces = (' ' * level)\n log_function(('%s%s' % (spaces, msg)))", "docstring": "Print a formatted message to stdout prepended by spaces. Useful for\nprinting hierarchical information, like bullet lists.\n\nNote:\nIf the application is running in \"Silent Mode\"\n(i.e., ``_SILENT == True``), this function will return\nimmediately and no message will be printed.\n\nArgs:\nlog_function: The function that will be called to output the formatted\nmessage.\nfmt (str): A Python formatted string.\nlevel (int): Used to determing how many spaces to print. The formula\nis ``' ' * level ``.\n*args: Variable length list of arguments. Values are plugged into the\nformat string.\n\nExamples:\n>>> print_level(\"%s %d\", 0, \"TEST\", 0)\nTEST 0\n>>> print_level(\"%s %d\", 1, \"TEST\", 1)\nTEST 1\n>>> print_level(\"%s %d\", 2, \"TEST\", 2)\nTEST 2", "source": "codesearchnet"}
311{"code": "def clear_agent(self, short_name, client_id):\n \n\n if short_name not in self.services:\n raise ArgumentError(\"Unknown service name\", short_name=short_name)\n\n if short_name not in self.agents:\n raise ArgumentError(\"No agent registered for service\", short_name=short_name)\n\n if client_id != self.agents[short_name]:\n raise ArgumentError(\"Client was not registered for service\", short_name=short_name,\n client_id=client_id, current_client=self.agents[short_name])\n\n del self.agents[short_name]", "docstring": "Remove a client id from being the command handler for a service.\n\nArgs:\nshort_name (str): The name of the service to set an agent\nfor.\nclient_id (str): A globally unique id for the client that\nshould no longer receive commands for this service.", "source": "juraj-google-style"}
312{"code": "def get_staged_signatures(vcs):\n \n staged_path = _get_staged_history_path(vcs)\n known_signatures = []\n if os.path.exists(staged_path):\n with open(staged_path, 'r') as f:\n known_signatures = f.read().split()\n return known_signatures", "docstring": "Get the list of staged signatures\n\nArgs:\nvcs (easyci.vcs.base.Vcs)\n\nReturns:\nlist(basestring) - list of signatures", "source": "juraj-google-style"}
313{"code": "def combine_assignments(self, assignments):\n group_by_fn = collections.defaultdict(list)\n for a in assignments:\n if (not isinstance(a, Assign)):\n raise ValueError('ops should be instances of mtf.Assign')\n group_by_fn[a.assign_fn].append(a)\n assignments_set = set(assignments)\n self._operations = [op for op in self._operations if (op not in assignments_set)]\n ret = []\n for (fn, ops) in six.iteritems(group_by_fn):\n variables = []\n values = []\n for a in ops:\n variables.extend(a.variables)\n values.extend(a.inputs)\n ret.append(Assign(variables, values, fn))\n return ret", "docstring": "Rewrite the current graph to combine \"Assign\" operations.\n\nCombine similar Assign operations into grouped Assign operations.\nThis is useful when using the rewrite_stack_variables() optimization,\nsince variables can only be stacked if they are present in the same set\nof Assign operations.\n\nThis function takes a list of Assign operations and returns a possibly\nshorter list of Assign operations. The input Assignment operations\nare removed from the graph and become invalid.\n\nArgs:\nassignments: a list of Assign objects\nReturns:\na list of Assign objects", "source": "codesearchnet"}
314{"code": "def register_layouts(layouts, app, url=\"/api/props/\", brand=\"Pyxley\"):\n \n def props(name):\n if name not in layouts:\n \n name = list(layouts.keys())[0]\n return jsonify({\"layouts\": layouts[name][\"layout\"]})\n\n def apps():\n paths = []\n for i, k in enumerate(layouts.keys()):\n if i == 0:\n paths.append({\n \"path\": \"/\",\n \"label\": layouts[k].get(\"title\", k)\n })\n\n paths.append({\n \"path\": \"/\"+k,\n \"label\": layouts[k].get(\"title\", k)\n })\n\n return jsonify({\"brand\": brand, \"navlinks\": paths})\n\n app.add_url_rule(url+\"<string:name>/\", view_func=props)\n app.add_url_rule(url, view_func=apps)", "docstring": "register UILayout with the flask app\n\ncreate a function that will send props for each UILayout\n\nArgs:\nlayouts (dict): dict of UILayout objects by name\napp (object): flask app\nurl (string): address of props; default is /api/props/", "source": "juraj-google-style"}
315{"code": "def when_matches_async(self, path, good_value, bad_values=None):\n when = When(good_value, bad_values)\n future = self.subscribe(path, when)\n when.set_future_context(future, weakref.proxy(self))\n return future", "docstring": "Wait for an attribute to become a given value\n\nArgs:\npath (list): The path to wait to\ngood_value: If it is a callable then expect it to return\nTrue if we are satisfied and raise on error. If it is not\ncallable then compare each value against this one and return\nif it matches.\nbad_values (list): values to raise an error on\n\nReturns:\nFuture: a single Future that will resolve when the path matches\ngood_value or bad_values", "source": "codesearchnet"}
316{"code": "def parse_message(message):\n error_message = []\n func_tags = []\n node_tags = []\n pos = 0\n for match in re.finditer(_INTERPOLATION_PATTERN, message):\n parsed_tag = _ParseTag(match.group('type'), match.group('name'))\n if parsed_tag.type == 'function_node':\n error_message.append(match.group('sep'))\n func_tags.append(parsed_tag)\n else:\n error_message.append(match.group())\n node_tags.append(parsed_tag)\n pos = match.end()\n error_message.append(message[pos:])\n return (''.join(error_message), func_tags, node_tags)", "docstring": "Extract function tags and node tags from a message.\n\nTags are named tuples representing the string {{type name}}. For example,\nin \"123{{node Foo}}456{{function_node Bar}}789\", there are two tags: a node\ntag and a function tag.\n\nArgs:\nmessage: An error message, possibly from an OpError.\n\nReturns:\nA tuple containing the original message with function nodes stripped,\nfunction tags, and node tags.\n\nFor example, if message is \"123{{node Foo}}456{{function_node Bar}}789\"\nthen this function returns (\"123{{node Foo}}456789\",\n[_ParseTag(\"function_node\", \"Bar\")], [_ParseTag(\"node\", \"Foo\")]).", "source": "github-repos"}
317{"code": "def batch_insert(self, records, typecast=False):\n \n return self._batch_request(self.insert, records)", "docstring": "Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)\nTo change the rate limit use ``airtable.API_LIMIT = 0.2``\n(5 per second)\n\n>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]\n>>> airtable.batch_insert(records)\n\nArgs:\nrecords(``list``): Records to insert\ntypecast(``boolean``): Automatic data conversion from string values.\n\nReturns:\nrecords (``list``): list of added records", "source": "juraj-google-style"}
318{"code": "def _pull_out_perm_lhs(lhs, rest, out_port, in_port):\n (out_inv, lhs_red) = lhs._factor_lhs(out_port)\n return (lhs_red << Feedback.create(SeriesProduct.create(*rest), out_port=out_inv, in_port=in_port))", "docstring": "Pull out a permutation from the Feedback of a SeriesProduct with itself.\n\nArgs:\nlhs (CPermutation): The permutation circuit\nrest (tuple): The other SeriesProduct operands\nout_port (int): The feedback output port index\nin_port (int): The feedback input port index\n\nReturns:\nCircuit: The simplified circuit", "source": "codesearchnet"}
319{"code": "def isprocess(pid, error=False):\n try:\n os.kill(pid, 0)\n return True\n except OSError:\n return False", "docstring": "Check that a process is running.\n\nArguments:\n\npid (int): Process ID to check.\n\nReturns:\n\nTrue if the process is running, else false.", "source": "codesearchnet"}
320{"code": "def _examples_from_path_handler(self, request):\n examples_count = int(request.args.get('max_examples'))\n examples_path = request.args.get('examples_path')\n sampling_odds = float(request.args.get('sampling_odds'))\n self.example_class = (tf.train.SequenceExample if (request.args.get('sequence_examples') == 'true') else tf.train.Example)\n try:\n platform_utils.throw_if_file_access_not_allowed(examples_path, self._logdir, self._has_auth_group)\n example_strings = platform_utils.example_protos_from_path(examples_path, examples_count, parse_examples=False, sampling_odds=sampling_odds, example_class=self.example_class)\n self.examples = [self.example_class.FromString(ex) for ex in example_strings]\n self.generate_sprite(example_strings)\n json_examples = [json_format.MessageToJson(example) for example in self.examples]\n self.updated_example_indices = set(range(len(json_examples)))\n return http_util.Respond(request, {'examples': json_examples, 'sprite': (True if self.sprite else False)}, 'application/json')\n except common_utils.InvalidUserInputError as e:\n return http_util.Respond(request, {'error': e.message}, 'application/json', code=400)", "docstring": "Returns JSON of the specified examples.\n\nArgs:\nrequest: A request that should contain 'examples_path' and 'max_examples'.\n\nReturns:\nJSON of up to max_examlpes of the examples in the path.", "source": "codesearchnet"}
321{"code": "def unsubscribe(self, topic):\n del self.queues[topic]\n try:\n self.client.unsubscribe(topic)\n except operationError as exc:\n raise InternalError('Could not unsubscribe from topic', topic=topic, message=exc.message)", "docstring": "Unsubscribe from messages on a given topic\n\nArgs:\ntopic (string): The MQTT topic to unsubscribe from", "source": "codesearchnet"}
322{"code": "def get_table_metadata(engine, table):\n \n metadata = MetaData()\n metadata.reflect(bind=engine, only=[table])\n table_metadata = Table(table, metadata, autoload=True)\n return table_metadata", "docstring": "Extract all useful infos from the given table\n\nArgs:\nengine: SQLAlchemy connection engine\ntable: table name\n\nReturns:\nDictionary of infos", "source": "juraj-google-style"}
323{"code": "def _duplicate_example(self, request):\n \n index = int(request.args.get('index'))\n if index >= len(self.examples):\n return http_util.Respond(request, {'error': 'invalid index provided'},\n 'application/json', code=400)\n new_example = self.example_class()\n new_example.CopyFrom(self.examples[index])\n self.examples.append(new_example)\n self.updated_example_indices.add(len(self.examples) - 1)\n self.generate_sprite([ex.SerializeToString() for ex in self.examples])\n return http_util.Respond(request, {}, 'application/json')", "docstring": "Duplicates the specified example.\n\nArgs:\nrequest: A request that should contain 'index'.\n\nReturns:\nAn empty response.", "source": "juraj-google-style"}
324{"code": "def similar_text(self, *args, **kwargs):\n return SimilarRequest(self, *args, mode='text', **kwargs).send()", "docstring": "Search for documents that are similar to directly supplied text or to the textual content of an existing document.\n\nArgs:\ntext -- Text to found something similar to.\nlen -- Number of keywords to extract from the source.\nquota -- Minimum number of keywords matching in the destination.\n\nKeyword args:\noffset -- Number of results to skip before returning the following ones.\ndocs -- Number of documents to retrieve. Default is 10.\nquery -- An optional query that all found documents have to match against. See Search().\nSee Request.__init__()\n\nReturns:\nA ListResponse object.", "source": "codesearchnet"}
325{"code": "def connect(self, funds: typing.TokenAmount, initial_channel_target: int=3, joinable_funds_target: float=0.4):\n token = self.raiden.chain.token(self.token_address)\n token_balance = token.balance_of(self.raiden.address)\n if (token_balance < funds):\n raise InvalidAmount(f'Insufficient balance for token {pex(self.token_address)}')\n if (funds <= 0):\n raise InvalidAmount('The funds to use in the connection need to be a positive integer')\n if ((joinable_funds_target < 0) or (joinable_funds_target > 1)):\n raise InvalidAmount(f'joinable_funds_target should be between 0 and 1. Given: {joinable_funds_target}')\n with self.lock:\n self.funds = funds\n self.initial_channel_target = initial_channel_target\n self.joinable_funds_target = joinable_funds_target\n log_open_channels(self.raiden, self.registry_address, self.token_address, funds)\n qty_network_channels = views.count_token_network_channels(views.state_from_raiden(self.raiden), self.registry_address, self.token_address)\n if (not qty_network_channels):\n log.info('Bootstrapping token network.', node=pex(self.raiden.address), network_id=pex(self.registry_address), token_id=pex(self.token_address))\n self.api.channel_open(self.registry_address, self.token_address, self.BOOTSTRAP_ADDR)\n else:\n self._open_channels()", "docstring": "Connect to the network.\n\nSubsequent calls to `connect` are allowed, but will only affect the spendable\nfunds and the connection strategy parameters for the future. `connect` will not\nclose any channels.\n\nNote: the ConnectionManager does not discriminate manually opened channels from\nautomatically opened ones. If the user manually opened channels, those deposit\namounts will affect the funding per channel and the number of new channels opened.\n\nArgs:\nfunds: Target amount of tokens spendable to join the network.\ninitial_channel_target: Target number of channels to open.\njoinable_funds_target: Amount of funds not initially assigned.", "source": "codesearchnet"}
326{"code": "def get_string(self, distance=6, velocity=8, charge=3):\n file_template = 'Generated by pymatgen.io.lammps.data.LammpsData\\n\\n{stats}\\n\\n{box}\\n\\n{body}\\n'\n box = self.box.get_string(distance)\n body_dict = OrderedDict()\n body_dict['Masses'] = self.masses\n types = OrderedDict()\n types['atom'] = len(self.masses)\n if self.force_field:\n all_ff_kws = (SECTION_KEYWORDS['ff'] + SECTION_KEYWORDS['class2'])\n ff_kws = [k for k in all_ff_kws if (k in self.force_field)]\n for kw in ff_kws:\n body_dict[kw] = self.force_field[kw]\n if (kw in SECTION_KEYWORDS['ff'][2:]):\n types[kw.lower()[:(- 7)]] = len(self.force_field[kw])\n body_dict['Atoms'] = self.atoms\n counts = OrderedDict()\n counts['atoms'] = len(self.atoms)\n if (self.velocities is not None):\n body_dict['Velocities'] = self.velocities\n if self.topology:\n for kw in SECTION_KEYWORDS['topology']:\n if (kw in self.topology):\n body_dict[kw] = self.topology[kw]\n counts[kw.lower()] = len(self.topology[kw])\n all_stats = (list(counts.values()) + list(types.values()))\n stats_template = ('{:>%d} {}' % len(str(max(all_stats))))\n count_lines = [stats_template.format(v, k) for (k, v) in counts.items()]\n type_lines = [stats_template.format(v, (k + ' types')) for (k, v) in types.items()]\n stats = '\\n'.join(((count_lines + ['']) + type_lines))\n map_coords = (lambda q: ('{:.%df}' % distance).format(q))\n map_velos = (lambda q: ('{:.%df}' % velocity).format(q))\n map_charges = (lambda q: ('{:.%df}' % charge).format(q))\n formatters = {'x': map_coords, 'y': map_coords, 'z': map_coords, 'vx': map_velos, 'vy': map_velos, 'vz': map_velos, 'q': map_charges}\n section_template = '{kw}\\n\\n{df}\\n'\n parts = []\n for (k, v) in body_dict.items():\n index = (True if (k != 'PairIJ Coeffs') else False)\n df_string = v.to_string(header=False, formatters=formatters, index_names=False, index=index)\n parts.append(section_template.format(kw=k, df=df_string))\n body = '\\n'.join(parts)\n return file_template.format(stats=stats, box=box, body=body)", "docstring": "Returns the string representation of LammpsData, essentially\nthe string to be written to a file.\n\nArgs:\ndistance (int): No. of significant figures to output for\nbox settings (bounds and tilt) and atomic coordinates.\nDefault to 6.\nvelocity (int): No. of significant figures to output for\nvelocities. Default to 8.\ncharge (int): No. of significant figures to output for\ncharges. Default to 3.\n\nReturns:\nString representation", "source": "codesearchnet"}
327{"code": "def ack_deadline(self):\n target = min([(self._last_histogram_size * 2), (self._last_histogram_size + 100)])\n if (len(self.ack_histogram) > target):\n self._ack_deadline = self.ack_histogram.percentile(percent=99)\n return self._ack_deadline", "docstring": "Return the current ack deadline based on historical time-to-ack.\n\nThis method is \"sticky\". It will only perform the computations to\ncheck on the right ack deadline if the histogram has gained a\nsignificant amount of new information.\n\nReturns:\nint: The ack deadline.", "source": "codesearchnet"}
328{"code": "def PrivateKeyFromNEP2(nep2_key, passphrase):\n if ((not nep2_key) or (len(nep2_key) != 58)):\n raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key)))\n ADDRESS_HASH_SIZE = 4\n ADDRESS_HASH_OFFSET = (len(NEP_FLAG) + len(NEP_HEADER))\n try:\n decoded_key = base58.b58decode_check(nep2_key)\n except Exception as e:\n raise ValueError('Invalid nep2_key')\n address_hash = decoded_key[ADDRESS_HASH_OFFSET:(ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE)]\n encrypted = decoded_key[(- 32):]\n pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')\n derived = scrypt.hash(pwd_normalized, address_hash, N=SCRYPT_ITERATIONS, r=SCRYPT_BLOCKSIZE, p=SCRYPT_PARALLEL_FACTOR, buflen=SCRYPT_KEY_LEN_BYTES)\n derived1 = derived[:32]\n derived2 = derived[32:]\n cipher = AES.new(derived2, AES.MODE_ECB)\n decrypted = cipher.decrypt(encrypted)\n private_key = xor_bytes(decrypted, derived1)\n kp_new = KeyPair(priv_key=private_key)\n kp_new_address = kp_new.GetAddress()\n kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode('utf-8')).digest()\n kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest()\n kp_new_address_hash = kp_new_address_hash_tmp2[:4]\n if (kp_new_address_hash != address_hash):\n raise ValueError('Wrong passphrase')\n return private_key", "docstring": "Gets the private key from a NEP-2 encrypted private key\n\nArgs:\nnep2_key (str): The nep-2 encrypted private key\npassphrase (str): The password to encrypt the private key with, as unicode string\n\nReturns:\nbytes: The private key", "source": "codesearchnet"}
329{"code": "def __init__(self, min_shard_bytes=256 << 10, max_shards=1, bytes_per_string=16):\n if min_shard_bytes < 1:\n raise ValueError(f'Argument `min_shard_bytes` must be positive. Received: {min_shard_bytes}')\n if max_shards < 1:\n raise ValueError(f'Argument `max_shards` must be positive. Received: {max_shards}')\n if bytes_per_string < 1:\n raise ValueError(f'Argument `bytes_per_string` must be positive. Received: {bytes_per_string}')\n self._min_shard_bytes = min_shard_bytes\n self._max_shards = max_shards\n self._bytes_per_string = bytes_per_string", "docstring": "Creates a new `MinSizePartitioner`.\n\nArgs:\nmin_shard_bytes: Minimum bytes of each shard. Defaults to 256K.\nmax_shards: Upper bound on the number of shards. Defaults to 1.\nbytes_per_string: If the partition value is of type string, this provides\nan estimate of how large each string is.", "source": "github-repos"}
330{"code": "def AddDir(self, dirpath):\n if (dirpath not in self._dirs):\n self._dirs.add(dirpath)\n return True\n return False", "docstring": "Adds a directory path as a source.\n\nArgs:\ndirpath: a string representing a path to the directory.\n\nReturns:\nTrue if the directory is not an already existing source.", "source": "codesearchnet"}
331{"code": "def tf_step(self, time, variables, **kwargs):\n \n fn_loss = kwargs[\"fn_loss\"]\n if variables is None:\n variables = tf.trainable_variables\n return tf.gradients(fn_loss, variables)", "docstring": "Creates the TensorFlow operations for performing an optimization step on the given variables, including\nactually changing the values of the variables.\n\nArgs:\ntime: Time tensor. Not used for this optimizer.\nvariables: List of variables to optimize.\n**kwargs:\nfn_loss : loss function tensor to differentiate.\n\nReturns:\nList of delta tensors corresponding to the updates for each optimized variable.", "source": "juraj-google-style"}
332{"code": "def _get_files_set(path, start_tag, end_tag):\n with open(path, 'r') as f:\n contents = f.read()\n start = contents.find(start_tag) + len(start_tag) + 1\n end = contents.find(end_tag)\n contents = contents[start:end]\n file_paths = [file_path.strip().strip('\"') for file_path in contents.split(',')]\n return set((file_path for file_path in file_paths if file_path))", "docstring": "Get set of file paths from the given file.\n\nArgs:\npath: Path to file. File at `path` is expected to contain a list of paths\nwhere entire list starts with `start_tag` and ends with `end_tag`. List\nmust be comma-separated and each path entry must be surrounded by double\nquotes.\nstart_tag: String that indicates start of path list.\nend_tag: String that indicates end of path list.\n\nReturns:\nList of string paths.", "source": "github-repos"}
333{"code": "def path_size(p: tcod.path.AStar) -> int:\n return int(lib.TCOD_path_size(p._path_c))", "docstring": "Return the current length of the computed path.\n\nArgs:\np (AStar): An AStar instance.\nReturns:\nint: Length of the path.", "source": "codesearchnet"}
334{"code": "def GetLineWidth(line):\n if isinstance(line, unicode):\n width = 0\n for uc in unicodedata.normalize('NFC', line):\n if (unicodedata.east_asian_width(uc) in ('W', 'F')):\n width += 2\n elif (not unicodedata.combining(uc)):\n width += 1\n return width\n else:\n return len(line)", "docstring": "Determines the width of the line in column positions.\n\nArgs:\nline: A string, which may be a Unicode string.\n\nReturns:\nThe width of the line in column positions, accounting for Unicode\ncombining characters and wide characters.", "source": "codesearchnet"}
335{"code": "def transpose(self, name=None):\n if (name is None):\n name = (self.module_name + '_transpose')\n return AddBias(output_shape=(lambda : self._input_shape), bias_dims=self._bias_dims, initializers=self._initializers, regularizers=self._regularizers, name=name)", "docstring": "Returns transposed `AddBias` module.\n\nArgs:\nname: Optional string assigning name of transpose module. The default name\nis constructed by appending \"_transpose\" to `self.module_name`.\n\nReturns:\nTransposed `AddBias` module.", "source": "codesearchnet"}
336{"code": "def _make_callable(self, feed_arrays, feed_symbols, symbol_vals, session):\n callable_opts = config_pb2.CallableOptions()\n for x in feed_arrays:\n callable_opts.feed.append(x.name)\n if self.feed_dict:\n for key in sorted(self.feed_dict.keys()):\n callable_opts.feed.append(key.name)\n for x, y in zip(feed_symbols, symbol_vals):\n connection = callable_opts.tensor_connection.add()\n if x.dtype != y.dtype:\n y = math_ops.cast(y, dtype=x.dtype)\n from_tensor = _as_graph_element(y)\n if from_tensor is None:\n from_tensor = y\n connection.from_tensor = from_tensor.name\n connection.to_tensor = x.name\n for x in self.outputs + self.fetches:\n callable_opts.fetch.append(x.name)\n callable_opts.target.append(self.updates_op.name)\n if self.run_options:\n callable_opts.run_options.CopyFrom(self.run_options)\n callable_fn = session._make_callable_from_options(callable_opts)\n self._callable_fn = callable_fn\n self._feed_arrays = feed_arrays\n self._feed_symbols = feed_symbols\n self._symbol_vals = symbol_vals\n self._fetches = list(self.fetches)\n self._session = session", "docstring": "Generates a callable that runs the graph.\n\nArgs:\nfeed_arrays: List of input tensors to be fed Numpy arrays at runtime.\nfeed_symbols: List of input tensors to be fed symbolic tensors at runtime.\nsymbol_vals: List of symbolic tensors to be fed to `feed_symbols`.\nsession: Session to use to generate the callable.\n\nReturns:\nFunction that runs the graph according to the above options.", "source": "github-repos"}
337{"code": "def apply(self, elements, *args, **kwargs):\n return self.extract_output(self.add_inputs(self.create_accumulator(*args, **kwargs), elements, *args, **kwargs), *args, **kwargs)", "docstring": "Returns result of applying this CombineFn to the input values.\n\nArgs:\nelements: the set of values to combine.\n*args: Additional arguments and side inputs.\n**kwargs: Additional arguments and side inputs.", "source": "github-repos"}
338{"code": "def check_valid(money):\n \n if not isinstance(money, sc_messages.Money):\n raise ValueError(u'Inputs should be of type %s' % (sc_messages.Money,))\n currency = money.currencyCode\n if not currency or len(currency) != 3:\n raise ValueError(_MSG_3_LETTERS_LONG)\n units = money.units\n nanos = money.nanos\n if ((units > 0) and (nanos < 0)) or ((units < 0) and (nanos > 0)):\n raise ValueError(_MSG_UNITS_NANOS_MISMATCH)\n if abs(nanos) > MAX_NANOS:\n raise ValueError(_MSG_NANOS_OOB)", "docstring": "Determine if an instance of `Money` is valid.\n\nArgs:\nmoney (:class:`endpoints_management.gen.servicecontrol_v1_messages.Money`): the\ninstance to test\n\nRaises:\nValueError: if the money instance is invalid", "source": "juraj-google-style"}
339{"code": "def stop(self, **kwargs):\n path = ('%s/%s/stop' % (self.manager.path, self.get_id()))\n self.manager.gitlab.http_post(path, **kwargs)", "docstring": "Stop the environment.\n\nArgs:\n**kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\nGitlabAuthenticationError: If authentication is not correct\nGitlabStopError: If the operation failed", "source": "codesearchnet"}
340{"code": "def bernoulli(key, mean=np.float32(0.5), shape=None):\n mean = tf_np.asarray(mean)\n if shape is None:\n shape = mean.shape\n return uniform(key, shape) < mean", "docstring": "Sample Bernoulli random values with given shape and mean.\n\nArgs:\nkey: the RNG key.\nmean: optional, an array_like broadcastable to `shape` for the mean of the\nrandom variables (default 0.5).\nshape: optional, a tuple of nonnegative integers representing the shape\n(default to `mean`'s shape).\n\nReturns:\nA random array with the specified shape and boolean dtype.", "source": "github-repos"}
341{"code": "def stringify(self, use_bytes=False):\n \n def _str_value(value):\n if isinstance(value, (list, tuple)):\n value = (self.EOL + '\\t').join(map(_str_value, value))\n elif callable(value):\n value = _str_value(value())\n return value\n\n s = self.EOL.join((\"{key}: {value}\".format(key=key,\n value=_str_value(value))\n for key, value in self._header_data.values()\n if value is not None))\n return s + (self.EOL * 2)", "docstring": "Returns representation of headers as a valid HTTP header string. This\nis called by __str__.\n\nArgs:\nuse_bytes (bool): Returns a bytes object instead of a str.", "source": "juraj-google-style"}
342{"code": "def decrypt_report(self, device_id, root, data, **kwargs):\n report_key = self._verify_derive_key(device_id, root, **kwargs)\n try:\n from Crypto.Cipher import AES\n import Crypto.Util.Counter\n except ImportError:\n raise NotFoundError\n ctr = Crypto.Util.Counter.new(128)\n encryptor = AES.new(bytes(report_key[:16]), AES.MODE_CTR, counter=ctr)\n decrypted = encryptor.decrypt(bytes(data))\n return {'data': decrypted}", "docstring": "Decrypt a buffer of report data on behalf of a device.\n\nArgs:\ndevice_id (int): The id of the device that we should encrypt for\nroot (int): The root key type that should be used to generate the report\ndata (bytearray): The data that we should decrypt\n**kwargs: There are additional specific keyword args that are required\ndepending on the root key used. Typically, you must specify\n- report_id (int): The report id\n- sent_timestamp (int): The sent timestamp of the report\n\nThese two bits of information are used to construct the per report\nsigning and encryption key from the specific root key type.\n\nReturns:\ndict: The decrypted data and any associated metadata about the data.\nThe data itself must always be a bytearray stored under the 'data'\nkey, however additional keys may be present depending on the encryption method\nused.\n\nRaises:\nNotFoundError: If the auth provider is not able to decrypt the data.", "source": "codesearchnet"}
343{"code": "def list_stack(list_, opts):\n assert isinstance(opts, ListStackOpts)\n if isinstance(list_, tensor_array_ops.TensorArray):\n return _tf_tensorarray_stack(list_)\n elif tensor_util.is_tf_type(list_):\n if list_.dtype == dtypes.variant:\n return _tf_tensor_list_stack(list_, opts)\n else:\n return list_\n else:\n return _py_list_stack(list_, opts)", "docstring": "The list stack function.\n\nThis does not have a direct correspondent in Python. The closest idiom to\nthis is tf.append or np.stack. It's different from those in the sense that it\naccepts a Tensor list, rather than a list of tensors. It can also accept\nTensorArray. When the target is anything else, the dispatcher will rely on\nctx.original_call for fallback.\n\nArgs:\nlist_: An entity that supports append semantics.\nopts: A ListStackOpts object.\n\nReturns:\nThe output of the stack operation, typically a Tensor.", "source": "github-repos"}
344{"code": "def get_v1_names(symbol: Any) -> Sequence[str]:\n names_v1 = []\n tensorflow_api_attr_v1 = API_ATTRS_V1[TENSORFLOW_API_NAME].names\n keras_api_attr_v1 = API_ATTRS_V1[KERAS_API_NAME].names\n if not hasattr(symbol, '__dict__'):\n return names_v1\n if tensorflow_api_attr_v1 in symbol.__dict__:\n names_v1.extend(getattr(symbol, tensorflow_api_attr_v1))\n if keras_api_attr_v1 in symbol.__dict__:\n names_v1.extend(getattr(symbol, keras_api_attr_v1))\n return names_v1", "docstring": "Get a list of TF 1.* names for this symbol.\n\nArgs:\nsymbol: symbol to get API names for.\n\nReturns:\nList of all API names for this symbol.", "source": "github-repos"}
345{"code": "def getVarianceComps(self, univariance=False):\n \n RV=sp.zeros((self.P,self.n_randEffs))\n for term_i in range(self.n_randEffs):\n RV[:,term_i] = self.getTraitCovar(term_i).diagonal()\n if univariance:\n RV /= RV.sum(1)[:,sp.newaxis]\n return RV", "docstring": "Return the estimated variance components\n\nArgs:\nunivariance: Boolean indicator, if True variance components are normalized to sum up to 1 for each trait\nReturns:\nvariance components of all random effects on all phenotypes [P, n_randEffs matrix]", "source": "juraj-google-style"}
346{"code": "def set_datetime_format(self, format):\n if (not (format in ['UNIX', 'RFC3339'])):\n return\n self.datetime_format = format\n self.set_header('Accept-Datetime-Format', self.datetime_format)", "docstring": "Set the Accept-Datetime-Format header to an acceptable\nvalue\n\nArgs:\nformat: UNIX or RFC3339", "source": "codesearchnet"}
347{"code": "def __init__(self, feature_set='spe+'):\n \n filename = filenames[feature_set]\n self.segments, self.seg_dict, self.names = self._read_table(filename)\n self.seg_seq = {seg[0]: i for (i, seg) in enumerate(self.segments)}\n self.weights = self._read_weights()\n self.seg_regex = self._build_seg_regex()\n self.longest_seg = max([len(x) for x in self.seg_dict.keys()])\n self.xsampa = xsampa.XSampa()", "docstring": "Construct a FeatureTable object\n\nArgs:\nfeature_set (str): the feature set that the FeatureTable will use;\ncurrently, there is only one of these (\"spe+\")", "source": "juraj-google-style"}
348{"code": "def is_finite_number(value):\n if (not isinstance(value, (numbers.Integral, float))):\n return False\n if isinstance(value, bool):\n return False\n if isinstance(value, float):\n if (math.isnan(value) or math.isinf(value)):\n return False\n if (abs(value) > (2 ** 53)):\n return False\n return True", "docstring": "Validates if the given value is a number, enforces\nabsolute limit of 2^53 and restricts NAN, INF, -INF.\n\nArgs:\nvalue: Value to be validated.\n\nReturns:\nBoolean: True if value is a number and not NAN, INF, -INF or\ngreater than absolute limit of 2^53 else False.", "source": "codesearchnet"}
349{"code": "def FindServiceByName(self, full_name):\n \n full_name = _NormalizeFullyQualifiedName(full_name)\n if full_name not in self._service_descriptors:\n self._FindFileContainingSymbolInDb(full_name)\n return self._service_descriptors[full_name]", "docstring": "Loads the named service descriptor from the pool.\n\nArgs:\nfull_name: The full name of the service descriptor to load.\n\nReturns:\nThe service descriptor for the named service.\n\nRaises:\nKeyError: if the service cannot be found in the pool.", "source": "juraj-google-style"}
350{"code": "def exists(self, uri):\n \n \n try:\n urllib.request.urlopen(uri)\n return True\n except urllib.error.HTTPError:\n return False", "docstring": "Method returns true is the entity exists in the Repository,\nfalse, otherwise\n\nArgs:\nuri(str): Entity URI\n\nReturns:\nbool", "source": "juraj-google-style"}
351{"code": "def stripped_op_list_for_graph(graph_def):\n used_ops = ops_used_by_graph_def(graph_def)\n op_defs = []\n for op in sorted(used_ops):\n op_def = op_def_registry.get(op)\n if op_def is not None:\n op_defs.append(op_def)\n return op_def_pb2.OpList(op=op_defs)", "docstring": "Collect the stripped OpDefs for ops used by a graph.\n\nThis function computes the `stripped_op_list` field of `MetaGraphDef` and\nsimilar protos. The result can be communicated from the producer to the\nconsumer, which can then use the C++ function\n`RemoveNewDefaultAttrsFromGraphDef` to improve forwards compatibility.\n\nArgs:\ngraph_def: A `GraphDef` proto, as from `graph.as_graph_def()`.\n\nReturns:\nAn `OpList` of ops used by the graph.", "source": "github-repos"}
352{"code": "def _add_sample_measure(self, measure_params, num_samples):\n \n \n measured_qubits = list({qubit for qubit, cmembit in measure_params})\n num_measured = len(measured_qubits)\n \n axis = list(range(self._number_of_qubits))\n for qubit in reversed(measured_qubits):\n \n \n axis.remove(self._number_of_qubits - 1 - qubit)\n probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2,\n axis=tuple(axis)),\n 2 ** num_measured)\n \n samples = self._local_random.choice(range(2 ** num_measured),\n num_samples, p=probabilities)\n \n memory = []\n for sample in samples:\n classical_memory = self._classical_memory\n for count, (qubit, cmembit) in enumerate(sorted(measure_params)):\n qubit_outcome = int((sample & (1 << count)) >> count)\n membit = 1 << cmembit\n classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit)\n value = bin(classical_memory)[2:]\n memory.append(hex(int(value, 2)))\n return memory", "docstring": "Generate memory samples from current statevector.\n\nArgs:\nmeasure_params (list): List of (qubit, cmembit) values for\nmeasure instructions to sample.\nnum_samples (int): The number of memory samples to generate.\n\nReturns:\nlist: A list of memory values in hex format.", "source": "juraj-google-style"}
353{"code": "def _PrintAnalysisStatusUpdateWindow(self, processing_status):\n if self._stdout_output_writer:\n self._ClearScreen()\n output_text = 'plaso - {0:s} version {1:s}\\n\\n'.format(self._tool_name, plaso.__version__)\n self._output_writer.Write(output_text)\n self._PrintAnalysisStatusHeader(processing_status)\n table_view = views.CLITabularTableView(column_names=['Identifier', 'PID', 'Status', 'Memory', 'Events', 'Tags', 'Reports'], column_sizes=[23, 7, 15, 15, 15, 15, 0])\n self._AddsAnalysisProcessStatusTableRow(processing_status.foreman_status, table_view)\n for worker_status in processing_status.workers_status:\n self._AddsAnalysisProcessStatusTableRow(worker_status, table_view)\n table_view.Write(self._output_writer)\n self._output_writer.Write('\\n')\n if processing_status.aborted:\n self._output_writer.Write('Processing aborted - waiting for clean up.\\n\\n')\n if self._stdout_output_writer:\n sys.stdout.flush()", "docstring": "Prints an analysis status update in window mode.\n\nArgs:\nprocessing_status (ProcessingStatus): processing status.", "source": "codesearchnet"}
354{"code": "def bel_edges(self, nanopub: Mapping[(str, Any)], namespace_targets: Mapping[(str, List[str])]={}, rules: List[str]=[], orthologize_target: str=None) -> List[Mapping[(str, Any)]]:\n edges = bel.edge.edges.create_edges(nanopub, self.endpoint, namespace_targets=namespace_targets, rules=rules, orthologize_target=orthologize_target)\n return edges", "docstring": "Create BEL Edges from BEL nanopub\n\nArgs:\nnanopub (Mapping[str, Any]): bel nanopub\nnamespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize\nrules (List[str]): which computed edge rules to process, default is all,\nlook at BEL Specification yaml file for computed edge signature keys,\ne.g. degradation, if any rule in list is 'skip', then skip computing edges\njust return primary_edge\northologize_target (str): species to convert BEL into, e.g. TAX:10090 for mouse, default option does not orthologize\n\nReturns:\nList[Mapping[str, Any]]: edge list with edge attributes (e.g. context)", "source": "codesearchnet"}
355{"code": "def GetRootKey(self):\n root_registry_key = virtual.VirtualWinRegistryKey('')\n for mapped_key in self._MAPPED_KEYS:\n key_path_segments = key_paths.SplitKeyPath(mapped_key)\n if (not key_path_segments):\n continue\n registry_key = root_registry_key\n for name in key_path_segments[:(- 1)]:\n sub_registry_key = registry_key.GetSubkeyByName(name)\n if (not sub_registry_key):\n sub_registry_key = virtual.VirtualWinRegistryKey(name)\n registry_key.AddSubkey(sub_registry_key)\n registry_key = sub_registry_key\n sub_registry_key = registry_key.GetSubkeyByName(key_path_segments[(- 1)])\n if ((not sub_registry_key) and isinstance(registry_key, virtual.VirtualWinRegistryKey)):\n sub_registry_key = virtual.VirtualWinRegistryKey(key_path_segments[(- 1)], registry=self)\n registry_key.AddSubkey(sub_registry_key)\n return root_registry_key", "docstring": "Retrieves the Windows Registry root key.\n\nReturns:\nWinRegistryKey: Windows Registry root key.\n\nRaises:\nRuntimeError: if there are multiple matching mappings and\nthe correct mapping cannot be resolved.", "source": "codesearchnet"}
356{"code": "def update(self, force=False):\n if (self.is_404 and (not force)):\n return 0\n if self._last_modified:\n headers = {'If-Modified-Since': self._last_modified}\n else:\n headers = None\n try:\n res = self._board._requests_session.get(self._api_url, headers=headers)\n except:\n return 0\n if (res.status_code == 304):\n return 0\n elif (res.status_code == 404):\n self.is_404 = True\n self._board._thread_cache.pop(self.id, None)\n return 0\n elif (res.status_code == 200):\n if self.is_404:\n self.is_404 = False\n self._board._thread_cache[self.id] = self\n self.want_update = False\n self.omitted_images = 0\n self.omitted_posts = 0\n self._last_modified = res.headers['Last-Modified']\n posts = res.json()['posts']\n original_post_count = len(self.replies)\n self.topic = Post(self, posts[0])\n if (self.last_reply_id and (not force)):\n self.replies.extend((Post(self, p) for p in posts if (p['no'] > self.last_reply_id)))\n else:\n self.replies[:] = [Post(self, p) for p in posts[1:]]\n new_post_count = len(self.replies)\n post_count_delta = (new_post_count - original_post_count)\n if (not post_count_delta):\n return 0\n self.last_reply_id = self.replies[(- 1)].post_number\n return post_count_delta\n else:\n res.raise_for_status()", "docstring": "Fetch new posts from the server.\n\nArguments:\nforce (bool): Force a thread update, even if thread has 404'd.\n\nReturns:\nint: How many new posts have been fetched.", "source": "codesearchnet"}
357{"code": "def unwrap_aliases(data_type):\n \n unwrapped_alias = False\n while is_alias(data_type):\n unwrapped_alias = True\n data_type = data_type.data_type\n return data_type, unwrapped_alias", "docstring": "Convenience method to unwrap all Alias(es) from around a DataType.\n\nArgs:\ndata_type (DataType): The target to unwrap.\n\nReturn:\nTuple[DataType, bool]: The underlying data type and a bool indicating\nwhether the input type had at least one alias layer.", "source": "juraj-google-style"}
358{"code": "def Matches(self, file_entry):\n if (not self._filters):\n return True\n results = []\n for file_entry_filter in self._filters:\n result = file_entry_filter.Matches(file_entry)\n results.append(result)\n return ((True in results) or (False not in results))", "docstring": "Compares the file entry against the filter collection.\n\nArgs:\nfile_entry (dfvfs.FileEntry): file entry to compare.\n\nReturns:\nbool: True if the file entry matches one of the filters. If no filters\nare provided or applicable the result will be True.", "source": "codesearchnet"}
359{"code": "def GetFileObjectByPathSpec(self, path_spec):\n file_entry = self.GetFileEntryByPathSpec(path_spec)\n if (not file_entry):\n return None\n return file_entry.GetFileObject()", "docstring": "Retrieves a file-like object for a path specification.\n\nArgs:\npath_spec (PathSpec): a path specification.\n\nReturns:\nFileIO: a file-like object or None if not available.", "source": "codesearchnet"}
360{"code": "def resolve_variables(variables, context, provider):\n \n for variable in variables:\n variable.resolve(context, provider)", "docstring": "Given a list of variables, resolve all of them.\n\nArgs:\nvariables (list of :class:`stacker.variables.Variable`): list of\nvariables\ncontext (:class:`stacker.context.Context`): stacker context\nprovider (:class:`stacker.provider.base.BaseProvider`): subclass of the\nbase provider", "source": "juraj-google-style"}
361{"code": "def write(self, symbol, data):\n cursor = self._collection.find()\n for res in cursor:\n library = self._arctic_lib.arctic[res['library_name']]\n dslice = self._slice(data, to_dt(res['start'], mktz('UTC')), to_dt(res['end'], mktz('UTC')))\n if (len(dslice) != 0):\n library.write(symbol, dslice)", "docstring": "Split the tick data to the underlying collections and write the data to each low\nlevel library.\n\nArgs:\nsymbol (str): the symbol for the timeseries data\ndata (list of dicts or pandas dataframe): Tick data to write\nif a list of dicts is given the list must be in time order and the time must be stored in\nan element named 'index' the value of which must be a timezone aware datetime.\nFor a pandas dataframe the index must be a datetime", "source": "codesearchnet"}
362{"code": "def to_utc_datetime(self, has_tz: bool=False) -> datetime.datetime:\n epoch = self._epoch_datetime_utc()\n if not has_tz:\n epoch = epoch.replace(tzinfo=None)\n return epoch + datetime.timedelta(microseconds=self.micros)", "docstring": "Returns a ``datetime.datetime`` object of UTC for this Timestamp.\n\nNote that this method returns a ``datetime.datetime`` object without a\ntimezone info by default, as builtin `datetime.datetime.utcnow` method. If\nthis is used as part of the processed data, one should set has_tz=True to\navoid offset due to default timezone mismatch.\n\nArgs:\nhas_tz: whether the timezone info is attached, default to False.\n\nReturns:\na ``datetime.datetime`` object of UTC for this Timestamp.", "source": "github-repos"}
363{"code": "def SetKeyPathPrefix(self, key_path_prefix):\n self._key_path_prefix = key_path_prefix\n self._key_path_prefix_length = len(key_path_prefix)\n self._key_path_prefix_upper = key_path_prefix.upper()", "docstring": "Sets the Window Registry key path prefix.\n\nArgs:\nkey_path_prefix (str): Windows Registry key path prefix.", "source": "codesearchnet"}
364{"code": "class FlaxForceTokensLogitsProcessor(FlaxLogitsProcessor):\n\n def __init__(self, force_token_map):\n force_token_map = dict(force_token_map)\n force_token_array = jnp.ones(max(force_token_map.keys()) + 1, dtype=jnp.int32) * -1\n for index, token in force_token_map.items():\n if token is not None:\n force_token_array = force_token_array.at[index].set(token)\n self.force_token_array = jnp.int32(force_token_array)\n\n def __call__(self, input_ids: jnp.ndarray, scores: jnp.ndarray, cur_len: int) -> jnp.ndarray:\n\n def _force_token(generation_idx):\n batch_size = scores.shape[0]\n current_token = self.force_token_array[generation_idx]\n new_scores = jnp.ones_like(scores, dtype=scores.dtype) * -float('inf')\n updates = jnp.zeros((batch_size, 1), dtype=scores.dtype)\n new_scores = lax.dynamic_update_slice(new_scores, updates, (0, current_token))\n return new_scores\n scores = lax.cond(cur_len >= self.force_token_array.shape[0], lambda: scores, lambda: lax.cond(self.force_token_array[cur_len] >= 0, lambda: _force_token(cur_len), lambda: scores))\n return scores", "docstring": "[`FlaxLogitsProcessor`] that takes a list of pairs of integers which indicates a mapping from generation indices to\ntoken indices that will be forced before sampling. The processor will set their log probs to 0 and all other tokens\nto `-inf` so that they are sampled at their corresponding index.\n\nArgs:\nforce_token_map (`list`):\nMap giving token ids and indices where they will be forced to be sampled.", "source": "github-repos"}
365{"code": "def pad_image(self, image: np.ndarray, size: Dict[str, int], random_padding: bool=False, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None) -> np.ndarray:\n output_height, output_width = (size['height'], size['width'])\n input_height, input_width = get_image_size(image, channel_dim=input_data_format)\n delta_width = output_width - input_width\n delta_height = output_height - input_height\n if random_padding:\n pad_top = np.random.randint(low=0, high=delta_height + 1)\n pad_left = np.random.randint(low=0, high=delta_width + 1)\n else:\n pad_top = delta_height \n pad_left = delta_width \n pad_bottom = delta_height - pad_top\n pad_right = delta_width - pad_left\n padding = ((pad_top, pad_bottom), (pad_left, pad_right))\n return pad(image, padding, data_format=data_format, input_data_format=input_data_format)", "docstring": "Pad the image to the specified size.\n\nArgs:\nimage (`np.ndarray`):\nThe image to be padded.\nsize (`Dict[str, int]`):\nThe size `{\"height\": h, \"width\": w}` to pad the image to.\nrandom_padding (`bool`, *optional*, defaults to `False`):\nWhether to use random padding or not.\ndata_format (`str` or `ChannelDimension`, *optional*):\nThe data format of the output image. If unset, the same format as the input image is used.\ninput_data_format (`ChannelDimension` or `str`, *optional*):\nThe channel dimension format of the input image. If not provided, it will be inferred.", "source": "github-repos"}
366{"code": "def mcast_ip_mask(ip_addr_and_mask, return_tuple=True):\n \n regex_mcast_ip_and_mask = __re.compile(\"^(((2[2-3][4-9])|(23[0-3]))\\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))\\.((25[0-5])|(2[0-4][0-9])|(1[0-9][0-9])|([1-9]?[0-9]))/((3[0-2])|([1-2][0-9])|[3-9]))$\")\n if return_tuple:\n while not regex_mcast_ip_and_mask.match(ip_addr_and_mask):\n print(\"Not a good multicast IP and CIDR mask combo.\")\n print(\"Please try again.\")\n ip_addr_and_mask = input(\"Please enter a multicast IP address and mask in the follwing format x.x.x.x/x: \")\n ip_cidr_split = ip_addr_and_mask.split(\"/\")\n ip_addr = ip_cidr_split[0]\n cidr = ip_cidr_split[1]\n return ip_addr, cidr\n elif not return_tuple:\n if not regex_mcast_ip_and_mask.match(ip_addr_and_mask):\n return False\n else:\n return True", "docstring": "Function to check if a address is multicast and that the CIDR mask is good\nArgs:\nip_addr_and_mask: Multicast IP address and mask in the following format 239.1.1.1/24\nreturn_tuple: Set to True it returns a IP and mask in a tuple, set to False returns True or False\n\nReturns: see return_tuple for return options", "source": "juraj-google-style"}
367{"code": "def _ParseBooleanValue(self, byte_stream):\n if (byte_stream == b'\\x00'):\n return False\n if (byte_stream == b'\\x01'):\n return True\n raise errors.ParseError('Unsupported boolean value.')", "docstring": "Parses a boolean value.\n\nArgs:\nbyte_stream (bytes): byte stream.\n\nReturns:\nbool: boolean value.\n\nRaises:\nParseError: when the boolean value cannot be parsed.", "source": "codesearchnet"}
368{"code": "def threat(self, name, owner=None, **kwargs):\n \n return Threat(self.tcex, name, owner=owner, **kwargs)", "docstring": "Create the Threat TI object.\n\nArgs:\nowner:\nname:\n**kwargs:\n\nReturn:", "source": "juraj-google-style"}
369{"code": "def sspro_results(self):\n return ssbio.protein.sequence.utils.fasta.load_fasta_file_as_dict_of_seqs(self.out_sspro)", "docstring": "Parse the SSpro output file and return a dict of secondary structure compositions.\n\nReturns:\ndict: Keys are sequence IDs, values are the lists of secondary structure predictions.\nH: helix\nE: strand\nC: the rest", "source": "codesearchnet"}
370{"code": "def put_path(self, url, path):\n cache_path = self._url_to_path(url)\n try:\n dir = os.path.dirname(cache_path)\n os.makedirs(dir)\n except OSError as e:\n if (e.errno != errno.EEXIST):\n raise Error(('Failed to create cache directories for ' % cache_path))\n try:\n os.unlink(cache_path)\n except OSError:\n pass\n try:\n os.link(path, cache_path)\n except OSError:\n try:\n shutil.copyfile(path, cache_path)\n except IOError:\n raise Error(('Failed to cache %s as %s for %s' % (path, cache_path, url)))", "docstring": "Puts a resource already on disk into the disk cache.\n\nArgs:\nurl: The original url of the resource\npath: The resource already available on disk\n\nRaises:\nCacheError: If the file cannot be put in cache", "source": "codesearchnet"}
371{"code": "def is_apk_installed(device: AndroidDevice, package_name: str) -> bool:\n try:\n out = device.adb.shell(['pm', 'list', 'package'])\n return bool(utils.grep('^package:%s$' % package_name, out))\n except adb.AdbError as error:\n raise errors.DeviceError(device, error)", "docstring": "Check if the given apk is already installed.\n\nArgs:\ndevice: AndroidDevice, Mobly's Android controller object.\npackage_name: str, name of the package.\n\nReturns:\nTrue if package is installed. False otherwise.", "source": "github-repos"}
372{"code": "def run_inference(self, batch: Sequence[pandas.DataFrame], model: BaseEstimator, inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionResult]:\n for dataframe in iter(batch):\n if dataframe.shape[0] != 1:\n raise ValueError('Only dataframes with single rows are supported.')\n predictions, splits = self._model_inference_fn(model, batch, inference_args)\n return utils._convert_to_result(splits, predictions, model_id=self._model_uri)", "docstring": "Runs inferences on a batch of pandas dataframes.\n\nArgs:\nbatch: A sequence of examples as numpy arrays. They should\nbe single examples.\nmodel: A dataframe model or pipeline. Must implement predict(X).\nWhere the parameter X is a pandas dataframe.\ninference_args: Any additional arguments for an inference.\n\nReturns:\nAn Iterable of type PredictionResult.", "source": "github-repos"}
373{"code": "def config_cmd_handler(conf, config='config'):\n if (conf[config].create or conf[config].update):\n conf.create_config_(update=conf[config].update)\n if conf[config].create_local:\n conf.create_config_(index=(- 1), update=conf[config].update)\n if conf[config].edit:\n if (not conf.config_files_[0].is_file()):\n conf.create_config_(update=conf[config].update)\n subprocess.call(shlex.split('{} {}'.format(conf[config].editor, conf.config_files_[0])))", "docstring": "Implement the behavior of a subcmd using config_conf_section\n\nArgs:\nconf (:class:`~loam.manager.ConfigurationManager`): it should contain a\nsection created with :func:`config_conf_section` function.\nconfig (str): name of the configuration section created with\n:func:`config_conf_section` function.", "source": "codesearchnet"}
374{"code": "def AddArguments(cls, argument_group):\n \n shared_4n6time_output.Shared4n6TimeOutputArgumentsHelper.AddArguments(\n argument_group)\n MySQL4n6TimeDatabaseArgumentsHelper.AddArguments(argument_group)", "docstring": "Adds command line arguments the helper supports to an argument group.\n\nThis function takes an argument parser or an argument group object and adds\nto it all the command line arguments this helper supports.\n\nArgs:\nargument_group (argparse._ArgumentGroup|argparse.ArgumentParser):\nargparse group.", "source": "juraj-google-style"}
375{"code": "def get_kwdefaults(func, parse_source=False):\n r\n \n \n argspec = inspect.getargspec(func)\n kwdefaults = {}\n if argspec.args is None or argspec.defaults is None:\n pass\n else:\n args = argspec.args\n defaults = argspec.defaults\n \n kwpos = len(args) - len(defaults)\n kwdefaults = OrderedDict(zip(args[kwpos:], defaults))\n if parse_source and argspec.keywords:\n \n keyword_defaults = parse_func_kwarg_keys(func, with_vals=True)\n for key, val in keyword_defaults:\n assert key not in kwdefaults, 'parsing error'\n kwdefaults[key] = val\n return kwdefaults", "docstring": "r\"\"\"\nArgs:\nfunc (func):\n\nReturns:\ndict:\n\nCommandLine:\npython -m utool.util_inspect get_kwdefaults\n\nExample:\n>>> # ENABLE_DOCTEST\n>>> from utool.util_inspect import * # NOQA\n>>> import utool as ut\n>>> func = dummy_func\n>>> parse_source = True\n>>> kwdefaults = get_kwdefaults(func, parse_source)\n>>> print('kwdefaults = %s' % (ut.repr4(kwdefaults),))", "source": "juraj-google-style"}
376{"code": "def write_config_files(self, host, hyperparameters, input_data_config):\n config_path = os.path.join(self.container_root, host, 'input', 'config')\n resource_config = {'current_host': host, 'hosts': self.hosts}\n json_input_data_config = {}\n for c in input_data_config:\n channel_name = c['ChannelName']\n json_input_data_config[channel_name] = {'TrainingInputMode': 'File'}\n if ('ContentType' in c):\n json_input_data_config[channel_name]['ContentType'] = c['ContentType']\n _write_json_file(os.path.join(config_path, 'hyperparameters.json'), hyperparameters)\n _write_json_file(os.path.join(config_path, 'resourceconfig.json'), resource_config)\n _write_json_file(os.path.join(config_path, 'inputdataconfig.json'), json_input_data_config)", "docstring": "Write the config files for the training containers.\n\nThis method writes the hyperparameters, resources and input data configuration files.\n\nArgs:\nhost (str): Host to write the configuration for\nhyperparameters (dict): Hyperparameters for training.\ninput_data_config (dict): Training input channels to be used for training.\n\nReturns: None", "source": "codesearchnet"}
377{"code": "def get_vcf_entry(variant_obj, case_id=None):\n \n if variant_obj['category'] == 'snv':\n var_type = 'TYPE'\n else:\n var_type = 'SVTYPE'\n\n info_field = ';'.join(\n [\n 'END='+str(variant_obj['end']),\n var_type+'='+variant_obj['sub_category'].upper()\n ]\n )\n\n variant_string = \"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\t{6}\\t{7}\".format(\n variant_obj['chromosome'],\n variant_obj['position'],\n variant_obj['dbsnp_id'],\n variant_obj['reference'],\n variant_obj['alternative'],\n variant_obj['quality'],\n ';'.join(variant_obj['filters']),\n info_field\n )\n\n if case_id:\n variant_string += \"\\tGT\"\n for sample in variant_obj['samples']:\n variant_string += \"\\t\" + sample['genotype_call']\n\n return variant_string", "docstring": "Get vcf entry from variant object\n\nArgs:\nvariant_obj(dict)\nReturns:\nvariant_string(str): string representing variant in vcf format", "source": "juraj-google-style"}
378{"code": "def _stringify_path(path_or_buffer):\n \n\n try:\n import pathlib\n _PATHLIB_INSTALLED = True\n except ImportError:\n _PATHLIB_INSTALLED = False\n\n if hasattr(path_or_buffer, '__fspath__'):\n return path_or_buffer.__fspath__()\n\n if _PATHLIB_INSTALLED and isinstance(path_or_buffer, pathlib.Path):\n return text_type(path_or_buffer)\n\n return path_or_buffer", "docstring": "Convert path like object to string\n\nArgs:\npath_or_buffer: object to be converted\n\nReturns:\nstring_path_or_buffer: maybe string version of path_or_buffer", "source": "juraj-google-style"}
379{"code": "def get_max_id(cls, session):\n id_base = None\n for c in ([cls] + list(cls.__bases__)):\n for base_class in c.__bases__:\n if (base_class.__name__ == 'Base'):\n if (id_base is None):\n id_base = c\n else:\n raise RuntimeError(('Multiple base object classes for class ' + cls.__name__))\n if (id_base is None):\n raise RuntimeError(('Error searching for base class of ' + cls.__name__))\n max_id = session.query(func.max(id_base.id)).scalar()\n if (max_id is None):\n max_id = 0\n return max_id", "docstring": "Get the current max value of the ``id`` column.\n\nWhen creating and storing ORM objects in bulk, :mod:`sqlalchemy` does not automatically\ngenerate an incrementing primary key ``id``. To do this manually, one needs to know the\ncurrent max ``id``. For ORM object classes that are derived from other ORM object classes,\nthe max ``id`` of the lowest base class is returned. This is designed to be used with\ninheritance by joining, in which derived and base class objects have identical ``id`` values.\n\nArgs:\nsession: database session to operate in", "source": "codesearchnet"}
380{"code": "def property_get(self, callself: 'cfg.Variable', is_class: bool=False) -> 'BaseValue':\n del callself, is_class\n return self", "docstring": "Bind this value to the given self or cls.\n\nThis function is similar to __get__ except at the abstract level. This does\nnot trigger any code execution inside the VM. See __get__ for more details.\n\nArgs:\ncallself: The Variable that should be passed as self or cls when the call\nis made. We only need one of self or cls, so having them share a\nparameter prevents accidentally passing in both.\nis_class: Whether callself is self or cls. Should be cls only when we want\nto directly pass in a class to bind a class method to, rather than\npassing in an instance and calling get_class().\n\nReturns:\nAnother abstract value that should be returned in place of this one. The\ndefault implementation returns self, so this can always be called safely.", "source": "github-repos"}
381{"code": "def gather(weights, indices, dim, output_shape=None):\n \n dim = convert_to_dimension(dim)\n output_shape = convert_to_shape(output_shape)\n if weights.dtype == tf.bool:\n return cast(gather(to_float(weights), indices, dim, output_shape), tf.bool)\n return einsum([one_hot(indices, dim, dtype=weights.dtype), weights],\n reduced_dims=[dim], output_shape=output_shape)", "docstring": "Shorthand for einsum([one_hot(indices, dim)], weights, reduced_dims=[dim]).\n\nArgs:\nweights: a Tensor\nindices: a Tensor with integer type\ndim: a Dimension\noutput_shape: an optional mtf.Shape\nReturns:\na Tensor", "source": "juraj-google-style"}
382{"code": "def __init__(self, enum_values=None, case_sensitive=True):\n \n super(EnumParser, self).__init__()\n self.enum_values = enum_values\n self.case_sensitive = case_sensitive", "docstring": "Initialize EnumParser.\n\nArgs:\nenum_values: Array of values in the enum.\ncase_sensitive: Whether or not the enum is to be case-sensitive.", "source": "juraj-google-style"}
383{"code": "def GetBlockByHeight(self, height):\n \n hash = self.GetBlockHash(height)\n if hash is not None:\n return self.GetBlockByHash(hash)", "docstring": "Get a block by its height.\nArgs:\nheight(int): the height of the block to retrieve.\n\nReturns:\nneo.Core.Block: block instance.", "source": "juraj-google-style"}
384{"code": "def clear_executor_errors(self):\n if self._context_handle:\n pywrap_tfe.TFE_ContextClearExecutors(self._context_handle)\n else:\n raise ValueError('Context is not initialized.')", "docstring": "Clear errors in both local executors and remote workers.\n\nAfter receiving errors from remote workers, additional requests on the fly\ncould further taint the status on the remote workers due to the async nature\nof remote execution. Calling this method block on waiting for all pending\nnodes in remote executors to finish and clear their error statuses.\n\nRaises:\nValueError: if context is not initialized.", "source": "github-repos"}
385{"code": "def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):\n for flag_name in flag_names:\n mark_flag_as_required(flag_name, flag_values)", "docstring": "Ensures that flags are not None during program execution.\n\nRecommended usage:\n\nif __name__ == '__main__':\nflags.mark_flags_as_required(['flag1', 'flag2', 'flag3'])\napp.run()\n\nArgs:\nflag_names: Sequence[str], names of the flags.\nflag_values: flags.FlagValues, optional FlagValues instance where the flags\nare defined.\nRaises:\nAttributeError: If any of flag name has not already been defined as a flag.", "source": "codesearchnet"}
386{"code": "def load_model(itos_filename, classifier_filename, num_classes):\n itos = pickle.load(Path(itos_filename).open('rb'))\n stoi = collections.defaultdict((lambda : 0), {str(v): int(k) for (k, v) in enumerate(itos)})\n (bptt, em_sz, nh, nl) = (70, 400, 1150, 3)\n dps = (np.array([0.4, 0.5, 0.05, 0.3, 0.4]) * 0.5)\n vs = len(itos)\n model = get_rnn_classifer(bptt, (20 * 70), num_classes, vs, emb_sz=em_sz, n_hid=nh, n_layers=nl, pad_token=1, layers=[(em_sz * 3), 50, num_classes], drops=[dps[4], 0.1], dropouti=dps[0], wdrop=dps[1], dropoute=dps[2], dropouth=dps[3])\n model.load_state_dict(torch.load(classifier_filename, map_location=(lambda storage, loc: storage)))\n model.reset()\n model.eval()\n return (stoi, model)", "docstring": "Load the classifier and int to string mapping\n\nArgs:\nitos_filename (str): The filename of the int to string mapping file (usually called itos.pkl)\nclassifier_filename (str): The filename of the trained classifier\n\nReturns:\nstring to int mapping, trained classifer model", "source": "codesearchnet"}
387{"code": "def get_rel_pos(self, q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:\n max_rel_dist = int(2 * max(q_size, k_size) - 1)\n rel_pos_resized = F.interpolate(rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode='linear')\n rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)\n q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)\n k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)\n relative_coords = q_coords - k_coords + (k_size - 1) * max(q_size / k_size, 1.0)\n return rel_pos_resized[relative_coords.long()]", "docstring": "Get relative positional embeddings according to the relative positions of\nquery and key sizes.\n\nArgs:\nq_size (int):\nsize of the query.\nk_size (int):\nsize of key k.\nrel_pos (`torch.Tensor`):\nrelative position embeddings (L, channel).\n\nReturns:\nExtracted positional embeddings according to relative positions.", "source": "github-repos"}
388{"code": "def get_transformation(self, struct1, struct2):\n if self._primitive_cell:\n raise ValueError('get_transformation cannot be used with the primitive cell option')\n (struct1, struct2) = self._process_species((struct1, struct2))\n (s1, s2, fu, s1_supercell) = self._preprocess(struct1, struct2, False)\n ratio = (fu if s1_supercell else (1 / fu))\n if (s1_supercell and (fu > 1)):\n raise ValueError('Struct1 must be the supercell, not the other way around')\n if ((len(s1) * ratio) >= len(s2)):\n match = self._strict_match(s1, s2, fu=fu, s1_supercell=False, use_rms=True, break_on_match=False)\n if (match is None):\n return None\n mapping = [(list(match[4]).index(i) if (i in match[4]) else None) for i in range(len(s1))]\n return (match[2], match[3], mapping)\n else:\n match = self._strict_match(s2, s1, fu=fu, s1_supercell=True, use_rms=True, break_on_match=False)\n if (match is None):\n return None\n not_included = list(range((len(s2) * fu)))\n for i in match[4]:\n not_included.remove(i)\n mapping = (list(match[4]) + not_included)\n return (match[2], (- match[3]), mapping)", "docstring": "Returns the supercell transformation, fractional translation vector,\nand a mapping to transform struct2 to be similar to struct1.\n\nArgs:\nstruct1 (Structure): Reference structure\nstruct2 (Structure): Structure to transform.\n\nReturns:\nsupercell (numpy.ndarray(3, 3)): supercell matrix\nvector (numpy.ndarray(3)): fractional translation vector\nmapping (list(int or None)):\nThe first len(struct1) items of the mapping vector are the\nindices of struct1's corresponding sites in struct2 (or None\nif there is no corresponding site), and the other items are\nthe remaining site indices of struct2.", "source": "codesearchnet"}
389{"code": "def serialize_example(transformed_json_data, features, feature_indices, target_name):\n import six\n import tensorflow as tf\n from trainer import feature_transforms\n line = str(transformed_json_data[target_name][0])\n for (name, info) in feature_indices:\n if (features[name]['transform'] in [feature_transforms.IDENTITY_TRANSFORM, feature_transforms.SCALE_TRANSFORM]):\n line += (' %d:%s' % (info['index_start'], str(transformed_json_data[name][0])))\n elif (features[name]['transform'] in [feature_transforms.ONE_HOT_TRANSFORM, feature_transforms.MULTI_HOT_TRANSFORM]):\n for i in range(info['size']):\n if (i in transformed_json_data[name]):\n line += (' %d:1' % (info['index_start'] + i))\n elif (features[name]['transform'] in [feature_transforms.IMAGE_TRANSFORM]):\n for i in range(info['size']):\n line += (' %d:%s' % ((info['index_start'] + i), str(transformed_json_data[name][i])))\n return line", "docstring": "Makes an instance of data in libsvm format.\n\nArgs:\ntransformed_json_data: dict of transformed data.\nfeatures: features config.\nfeature_indices: output of feature_transforms.get_transformed_feature_indices()\n\nReturns:\nThe text line representation of an instance in libsvm format.", "source": "codesearchnet"}
390{"code": "def make_input_feature_spec(include_label=True):\n result = {}\n if include_label:\n result['clicked'] = tf.io.FixedLenFeature(shape=[], dtype=tf.int64)\n for name in _INTEGER_COLUMN_NAMES:\n result[name] = tf.io.VarLenFeature(dtype=tf.int64)\n for name in _CATEGORICAL_COLUMN_NAMES:\n result[name] = tf.io.VarLenFeature(dtype=tf.string)\n return result", "docstring": "Input schema definition.\n\nArgs:\ninclude_label: Indicates whether the label feature should be included.\n\nReturns:\nA `Schema` object.", "source": "github-repos"}
391{"code": "def _add_step(self, step):\n self._closed()\n self.has_workflow_step = (self.has_workflow_step or step.is_workflow)\n self.wf_steps[step.name_in_workflow] = step", "docstring": "Add a step to the workflow.\n\nArgs:\nstep (Step): a step from the steps library.", "source": "codesearchnet"}
392{"code": "def inspect_file(path):\n with open(path, 'rb') as f:\n (labels, count) = inspect((tx.decode(line) for line in f))\n return (labels, count)", "docstring": "Inspect SDFile structure\n\nReturns:\ntuple: (data label list, number of records)", "source": "codesearchnet"}
393{"code": "def sign_hash(private_key, hash, hash_algo):\n \n hash_algo = _hash_algorithms[hash_algo]\n return get_privatekey(private_key).sign(\n hash,\n padding.PKCS1v15(),\n utils.Prehashed(hash_algo),\n )", "docstring": "Sign the given hash with the given private key.\n\nArgs:\nprivate_key (str): PEM enoded private key\nhash (byte str): hash to sign\nhash_algo (str): name of hash algorithm used\n\nReturns:\nbyte string representing the signature", "source": "juraj-google-style"}
394{"code": "def process_one_file(options):\n log.info('Process %s => %s', options.input, options.output)\n try:\n ret = check_or_generate_pyi(options)\n except utils.UsageError:\n logging.exception('')\n return 1\n if not options.check:\n if options.pickle_output:\n pyi_output = options.verify_pickle\n else:\n pyi_output = options.output\n if pyi_output:\n _write_pyi_output(options, ret.pyi, pyi_output)\n if options.pickle_output:\n log.info('write pickle %r => %r', options.input, options.output)\n write_pickle(ret.ast, options, ret.context.loader)\n if options.unused_imports_info_files:\n if options.use_rewrite:\n pass\n else:\n cwd = os.getcwd()\n unused_paths = sorted(ret.context.loader.get_unused_imports_map_paths())\n with options.open_function(options.unused_imports_info_files, 'wt', encoding='utf-8') as f:\n for unused_path in unused_paths:\n f.write(f'{os.path.relpath(unused_path, cwd)}\\n')\n exit_status = handle_errors(ret.context.errorlog, options)\n ret.context.program = None\n if options.touch and (not exit_status):\n with options.open_function(options.touch, 'a'):\n os.utime(options.touch, None)\n return exit_status", "docstring": "Check a .py file or generate a .pyi for it, according to options.\n\nArgs:\noptions: config.Options object.\n\nReturns:\nAn error code (0 means no error).", "source": "github-repos"}
395{"code": "def get_errors(self):\n errors = []\n errors.extend(self._get_signature_errors())\n errors.extend(self._get_additional_errors())\n errors.extend(self._get_entry_errors())\n return (errors if errors else None)", "docstring": "Verify that this MAR file is well formed.\n\nReturns:\nA list of strings describing errors in the MAR file\nNone if this MAR file appears well formed.", "source": "codesearchnet"}
396{"code": "def from_dict(vpc_config, do_sanitize=False):\n if do_sanitize:\n vpc_config = sanitize(vpc_config)\n if (vpc_config is None):\n return (None, None)\n return (vpc_config[SUBNETS_KEY], vpc_config[SECURITY_GROUP_IDS_KEY])", "docstring": "Extracts subnets and security group ids as lists from a VpcConfig dict\n\nArgs:\nvpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds'\ndo_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values\n\nReturns:\nTuple of lists as (subnets, security_group_ids)\nIf vpc_config parameter is None, returns (None, None)\n\nRaises:\nValueError if sanitize enabled and vpc_config is invalid\nKeyError if sanitize disabled and vpc_config is missing key(s)", "source": "codesearchnet"}
397{"code": "def __call__(self,\n state: Sequence[tf.Tensor],\n timestep: tf.Tensor) -> Sequence[tf.Tensor]:\n \n raise NotImplementedError", "docstring": "Returns action fluents for the current `state` and `timestep`.\n\nArgs:\nstate (Sequence[tf.Tensor]): The current state fluents.\ntimestep (tf.Tensor): The current timestep.\n\nReturns:\nSequence[tf.Tensor]: A tuple of action fluents.", "source": "juraj-google-style"}
398{"code": "def compute_output_shape(self, input_shape):\n \n input_shape = tf.TensorShape(input_shape).as_list()\n if self.data_format == 'channels_last':\n space = input_shape[1:-1]\n new_space = []\n for i in range(len(space)):\n new_dim = tf_layers_util.conv_output_length(\n space[i],\n self.kernel_size[i],\n padding=self.padding,\n stride=self.strides[i],\n dilation=self.dilation_rate[i])\n new_space.append(new_dim)\n return tf.TensorShape([input_shape[0]] + new_space + [self.filters])\n else:\n space = input_shape[2:]\n new_space = []\n for i in range(len(space)):\n new_dim = tf_layers_util.conv_output_length(\n space[i],\n self.kernel_size[i],\n padding=self.padding,\n stride=self.strides[i],\n dilation=self.dilation_rate[i])\n new_space.append(new_dim)\n return tf.TensorShape([input_shape[0], self.filters] + new_space)", "docstring": "Computes the output shape of the layer.\n\nArgs:\ninput_shape: Shape tuple (tuple of integers) or list of shape tuples\n(one per output tensor of the layer). Shape tuples can include None for\nfree dimensions, instead of an integer.\n\nReturns:\noutput_shape: A tuple representing the output shape.", "source": "juraj-google-style"}
399{"code": "def read_data_to_asp(file: str) -> List[str]:\n \n if file.endswith(\".json\"):\n with open(file) as f:\n data = json.load(f)\n return schema2asp(data2schema(data))\n elif file.endswith(\".csv\"):\n df = pd.read_csv(file)\n df = df.where((pd.notnull(df)), None)\n data = list(df.T.to_dict().values())\n schema = data2schema(data)\n asp = schema2asp(schema)\n return asp\n else:\n raise Exception(\"invalid file type\")", "docstring": "Reads the given JSON file and generates the ASP definition.\nArgs:\nfile: the json data file\nReturns:\nthe asp definition.", "source": "juraj-google-style"}
400{"code": "def orient_averaged_fixed(tm):\n \n S = np.zeros((2,2), dtype=complex)\n Z = np.zeros((4,4))\n ap = np.linspace(0, 360, tm.n_alpha+1)[:-1]\n aw = 1.0/tm.n_alpha\n\n for alpha in ap:\n for (beta, w) in zip(tm.beta_p, tm.beta_w):\n (S_ang, Z_ang) = tm.get_SZ_single(alpha=alpha, beta=beta)\n S += w * S_ang\n Z += w * Z_ang\n\n sw = tm.beta_w.sum()\n \n S *= aw/sw\n Z *= aw/sw\n\n return (S, Z)", "docstring": "Compute the T-matrix using variable orientation scatterers.\n\nThis method uses a fast Gaussian quadrature and is suitable\nfor most use. Uses the set particle orientation PDF, ignoring\nthe alpha and beta attributes.\n\nArgs:\ntm: TMatrix (or descendant) instance.\n\nReturns:\nThe amplitude (S) and phase (Z) matrices.", "source": "juraj-google-style"}
401{"code": "def __init__(self, options):\n \n\n self.queue = Queue(options)\n self.routing = Routing(options)\n self.__options = options\n self.__should_spawn_new_requests = False\n self.__should_stop = False\n self.__stopping = False\n self.__stopped = False\n self.__threads = {}\n self.__lock = threading.Lock()\n\n signal.signal(signal.SIGINT, self.__signal_handler)\n DebugHelper.setup(self.__options)", "docstring": "Constructs a Crawler instance.\n\nArgs:\noptions (:class:`nyawc.Options`): The options to use for the current crawling runtime.", "source": "juraj-google-style"}
402{"code": "def MultiHeadedAttentionQKV(\n feature_depth, num_heads=8, dropout=0.0, mode='train'):\n \n return combinators.Serial(\n combinators.Parallel(\n combinators.Parallel(\n core.Dense(feature_depth),\n core.Dense(feature_depth),\n core.Dense(feature_depth),\n ),\n combinators.Identity()\n ),\n PureMultiHeadedAttention( \n feature_depth=feature_depth, num_heads=num_heads,\n dropout=dropout, mode=mode),\n core.Dense(feature_depth),\n )", "docstring": "Transformer-style multi-headed attention.\n\nAccepts inputs of the form (q, k, v), mask.\n\nArgs:\nfeature_depth: int: depth of embedding\nnum_heads: int: number of attention heads\ndropout: float: dropout rate\nmode: str: 'train' or 'eval'\n\nReturns:\nMulti-headed self-attention layer.", "source": "juraj-google-style"}
403{"code": "def add_update_resource_views(self, resource_views):\n \n \n if not isinstance(resource_views, list):\n raise HDXError('ResourceViews should be a list!')\n for resource_view in resource_views:\n self.add_update_resource_view(resource_view)", "docstring": "Add new or update existing resource views in resource with new metadata.\n\nArgs:\nresource_views (List[Union[ResourceView,Dict]]): A list of resource views metadata from ResourceView objects or dictionaries\n\nReturns:\nNone", "source": "juraj-google-style"}
404{"code": "def FromEvent(cls, service_event):\n \n _, _, name = service_event.key_path.rpartition(\n WindowsService._REGISTRY_KEY_PATH_SEPARATOR)\n service_type = service_event.regvalue.get('Type', '')\n image_path = service_event.regvalue.get('ImagePath', '')\n start_type = service_event.regvalue.get('Start', '')\n service_dll = service_event.regvalue.get('ServiceDll', '')\n object_name = service_event.regvalue.get('ObjectName', '')\n\n if service_event.pathspec:\n source = (service_event.pathspec.location, service_event.key_path)\n else:\n source = ('Unknown', 'Unknown')\n return cls(\n name=name, service_type=service_type, image_path=image_path,\n start_type=start_type, object_name=object_name,\n source=source, service_dll=service_dll)", "docstring": "Creates a service object from an event.\n\nArgs:\nservice_event (EventObject): event to create a new service object from.\n\nReturns:\nWindowsService: service.", "source": "juraj-google-style"}
405{"code": "def fetch(version='bayestar2017'):\n doi = {'bayestar2015': '10.7910/DVN/40C44C', 'bayestar2017': '10.7910/DVN/LCYHJG'}\n try:\n doi = doi[version]\n except KeyError as err:\n raise ValueError('Version \"{}\" does not exist. Valid versions are: {}'.format(version, ', '.join(['\"{}\"'.format(k) for k in doi.keys()])))\n requirements = {'bayestar2015': {'contentType': 'application/x-hdf'}, 'bayestar2017': {'filename': 'bayestar2017.h5'}}[version]\n local_fname = os.path.join(data_dir(), 'bayestar', '{}.h5'.format(version))\n fetch_utils.dataverse_download_doi(doi, local_fname, file_requirements=requirements)", "docstring": "Downloads the specified version of the Bayestar dust map.\n\nArgs:\nversion (Optional[:obj:`str`]): The map version to download. Valid versions are\n:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and\n:obj:`'bayestar2015'` (Green, Schlafly, Finkbeiner et al. 2015). Defaults\nto :obj:`'bayestar2017'`.\n\nRaises:\n:obj:`ValueError`: The requested version of the map does not exist.\n\n:obj:`DownloadError`: Either no matching file was found under the given DOI, or\nthe MD5 sum of the file was not as expected.\n\n:obj:`requests.exceptions.HTTPError`: The given DOI does not exist, or there\nwas a problem connecting to the Dataverse.", "source": "codesearchnet"}
406{"code": "def _FetchServerCertificate(self):\n if self.server_certificate:\n return True\n response = self.http_manager.OpenServerEndpoint('server.pem', verify_cb=self.VerifyServerPEM)\n if response.Success():\n self.server_certificate = response.data\n return True\n self.timer.SlowPoll()\n return False", "docstring": "Attempts to fetch the server cert.\n\nReturns:\nTrue if we succeed.", "source": "codesearchnet"}
407{"code": "def create_team(self, name):\n request = self._get_request()\n return request.post(self.TEAM_CREATE_URL, {'name': name})", "docstring": "Creates a new Team\n\nCreates a new Team and makes you a member. You must not currently belong to a team to invoke.\n\nArgs:\n\nname (str): The name of your team\n\nReturns:\nA Team object", "source": "codesearchnet"}
408{"code": "def get_integer_index(miller_index: bool, round_dp: int=4, verbose: bool=True) -> Tuple[(int, int, int)]:\n miller_index = np.asarray(miller_index)\n miller_index /= min([m for m in miller_index if (m != 0)])\n miller_index /= np.max(np.abs(miller_index))\n md = [Fraction(n).limit_denominator(12).denominator for n in miller_index]\n miller_index *= reduce((lambda x, y: (x * y)), md)\n int_miller_index = np.int_(np.round(miller_index, 1))\n miller_index /= np.abs(reduce(gcd, int_miller_index))\n miller_index = np.array([round(h, round_dp) for h in miller_index])\n int_miller_index = np.int_(np.round(miller_index, 1))\n if (np.any((np.abs((miller_index - int_miller_index)) > 1e-06)) and verbose):\n warnings.warn('Non-integer encountered in Miller index')\n else:\n miller_index = int_miller_index\n miller_index += 0\n\n def n_minus(index):\n return len([h for h in index if (h < 0)])\n if (n_minus(miller_index) > n_minus((miller_index * (- 1)))):\n miller_index *= (- 1)\n if ((sum((miller_index != 0)) == 2) and (n_minus(miller_index) == 1) and (abs(min(miller_index)) > max(miller_index))):\n miller_index *= (- 1)\n return tuple(miller_index)", "docstring": "Attempt to convert a vector of floats to whole numbers.\n\nArgs:\nmiller_index (list of float): A list miller indexes.\nround_dp (int, optional): The number of decimal places to round the\nmiller index to.\nverbose (bool, optional): Whether to print warnings.\n\nReturns:\n(tuple): The Miller index.", "source": "codesearchnet"}
409{"code": "def extract_distribution(monitoring_info_proto):\n if not is_distribution(monitoring_info_proto):\n raise ValueError('Unsupported type %s' % monitoring_info_proto.type)\n return _decode_distribution(coders.VarIntCoder(), monitoring_info_proto.payload)", "docstring": "Returns a tuple of (count, sum, min, max).\n\nArgs:\nproto: The monitoring info for the distribution.", "source": "github-repos"}
410{"code": "def export_default_instruments(target_folder, source_folder = None, raise_errors = False, verbose=True):\n \n print('export_def_instr called')\n instruments_to_load = get_classes_in_folder(source_folder, Instrument, verbose = True)\n print('instruments to load:')\n print(instruments_to_load)\n\n if verbose:\n print(('attempt to load {:d} instruments: '.format(len(instruments_to_load))))\n loaded_instruments, failed = Instrument.load_and_append(instruments_to_load, raise_errors = raise_errors)\n print('loaded instruments:')\n print(loaded_instruments, failed)\n\n for name, value in loaded_instruments.items():\n filename = os.path.join(target_folder, '{:s}.b26'.format(name))\n\n value.save_b26(filename)\n\n if verbose:\n print('\\n================================================')\n print('================================================')\n print(('saved {:d} instruments, {:d} failed'.format(len(loaded_instruments), len(failed))))\n if failed != {}:\n for error_name, error in failed.items():\n print(('failed to create instruments: ', error_name, error))", "docstring": "tries to instantiate all the instruments that are imported in /instruments/__init__.py\nand saves instruments that could be instantiate into a .b2 file in the folder path\nArgs:\ntarget_folder: target path for .b26 files", "source": "juraj-google-style"}
411{"code": "def account_states(self, **kwargs):\n \n path = self._get_id_path('account_states')\n\n response = self._GET(path, kwargs)\n self._set_attrs_to_values(response)\n return response", "docstring": "This method lets users get the status of whether or not the movie has\nbeen rated or added to their favourite or watch lists. A valid session\nid is required.\n\nArgs:\nsession_id: see Authentication.\n\nReturns:\nA dict representation of the JSON returned from the API.", "source": "juraj-google-style"}
412{"code": "def load_pos_model(lang='en', version='2'):\n src_dir = 'pos{}'.format(version)\n p = locate_resource(src_dir, lang)\n fh = _open(p)\n return dict(np.load(fh))", "docstring": "Return a part of speech tagger parameters for `lang` and of version `version`\n\nArgs:\nlang (string): language code.\nversion (string): version of the parameters to be used.", "source": "codesearchnet"}
413{"code": "def _parse_service(service) -> tuple[str, str]:\n if not isinstance(service, str):\n raise ValueError(f'`service` must be a string, but `service` was of type {type(service)}. service={service}')\n if not service:\n raise ValueError('`service` must not be empty')\n parts = service.split(':\n if len(parts) == 2:\n protocol, address = parts\n elif len(parts) == 1:\n address = parts[0]\n protocol = _pywrap_utils_exp.TF_DATA_DefaultProtocol()\n else:\n raise ValueError(f\"Malformed `service` string has multiple ':\n return (protocol, address)", "docstring": "Converts a tf.data service string into a (protocol, address) tuple.\n\nArgs:\nservice: A string in the format \"protocol://address\" or just \"address\". If\nthe string is only an address, the default protocol will be used.\n\nReturns:\nThe (protocol, address) tuple", "source": "github-repos"}
414{"code": "def pre_fetch(self, feed):\n pass", "docstring": "Pre-fetches all required items to be update into the cache.\n\nThis increases performance for update operations.\n\nArgs:\nfeed: List of feed items to retrieve", "source": "github-repos"}
415{"code": "def output(self, _filename):\n \n\n for contract in self.slither.contracts_derived:\n txt = \"\\nContract %s\"%contract.name\n table = PrettyTable([\"Function\",\n \"require or assert\"])\n for function in contract.functions:\n require = function.all_slithir_operations()\n require = [ir for ir in require if isinstance(ir, SolidityCall) and ir.function in require_or_assert]\n require = [ir.node for ir in require]\n table.add_row([function.name, self._convert([str(m.expression) for m in set(require)])])\n txt += \"\\n\"+str(table)\n self.info(txt)", "docstring": "_filename is not used\nArgs:\n_filename(string)", "source": "juraj-google-style"}
416{"code": "def find_elb(name='', env='', region=''):\n \n LOG.info('Find %s ELB in %s [%s].', name, env, region)\n\n url = '{0}/applications/{1}/loadBalancers'.format(API_URL, name)\n response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n assert response.ok\n\n elb_dns = None\n accounts = response.json()\n for account in accounts:\n if account['account'] == env and account['region'] == region:\n elb_dns = account['dnsname']\n break\n else:\n raise SpinnakerElbNotFound('Elb for \"{0}\" in region {1} not found'.format(name, region))\n\n LOG.info('Found: %s', elb_dns)\n return elb_dns", "docstring": "Get an application's AWS elb dns name.\n\nArgs:\nname (str): ELB name\nenv (str): Environment/account of ELB\nregion (str): AWS Region\n\nReturns:\nstr: elb DNS record", "source": "juraj-google-style"}
417{"code": "def item(self, key):\n return _item.Item(self._name, key, context=self._context)", "docstring": "Retrieves an Item object for the specified key in this bucket.\n\nThe item need not exist.\n\nArgs:\nkey: the key of the item within the bucket.\nReturns:\nAn Item instance representing the specified key.", "source": "codesearchnet"}
418{"code": "def transform(self, target_type: Type[T], value: F, context: PipelineContext=None) -> T:\n pass", "docstring": "Transforms an object to a new type.\n\nArgs:\ntarget_type: The type to be converted to.\nvalue: The object to be transformed.\ncontext: The context of the transformation (mutable).", "source": "codesearchnet"}
419{"code": "def MultiDeleteAttributes(self, subjects, attributes, start=None, end=None, sync=True):\n for subject in subjects:\n self.DeleteAttributes(subject, attributes, start=start, end=end, sync=sync)", "docstring": "Remove all specified attributes from a list of subjects.\n\nArgs:\nsubjects: The list of subjects that will have these attributes removed.\nattributes: A list of attributes.\nstart: A timestamp, attributes older than start will not be deleted.\nend: A timestamp, attributes newer than end will not be deleted.\nsync: If true we block until the operation completes.", "source": "codesearchnet"}
420{"code": "def _ProcessFileEntry(self, mediator, file_entry):\n display_name = mediator.GetDisplayName()\n logger.debug('[ProcessFileEntry] processing file entry: {0:s}'.format(display_name))\n reference_count = mediator.resolver_context.GetFileObjectReferenceCount(file_entry.path_spec)\n try:\n if self._IsMetadataFile(file_entry):\n self._ProcessMetadataFile(mediator, file_entry)\n else:\n file_entry_processed = False\n for data_stream in file_entry.data_streams:\n if self._abort:\n break\n if self._CanSkipDataStream(file_entry, data_stream):\n logger.debug('[ProcessFileEntry] Skipping datastream {0:s} for {1:s}: {2:s}'.format(data_stream.name, file_entry.type_indicator, display_name))\n continue\n self._ProcessFileEntryDataStream(mediator, file_entry, data_stream)\n file_entry_processed = True\n if (not file_entry_processed):\n self._ProcessFileEntryDataStream(mediator, file_entry, None)\n finally:\n new_reference_count = mediator.resolver_context.GetFileObjectReferenceCount(file_entry.path_spec)\n if (reference_count != new_reference_count):\n if mediator.resolver_context.ForceRemoveFileObject(file_entry.path_spec):\n logger.warning('File-object not explicitly closed for file: {0:s}'.format(display_name))\n logger.debug('[ProcessFileEntry] done processing file entry: {0:s}'.format(display_name))", "docstring": "Processes a file entry.\n\nArgs:\nmediator (ParserMediator): mediates the interactions between\nparsers and other components, such as storage and abort signals.\nfile_entry (dfvfs.FileEntry): file entry.", "source": "codesearchnet"}
421{"code": "def forward(self, spectrogram: torch.FloatTensor):\n batch_size, _, seq_length = spectrogram.shape\n hidden_states = self.input_conv(spectrogram)\n hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)\n for resblock in self.resblocks:\n hidden_states = resblock(hidden_states)\n kernel_hidden_states = self.kernel_conv(hidden_states)\n bias_hidden_states = self.bias_conv(hidden_states)\n kernels = kernel_hidden_states.view(batch_size, self.conv_layers, self.conv_in_channels, self.conv_out_channels, self.conv_kernel_size, seq_length).contiguous()\n biases = bias_hidden_states.view(batch_size, self.conv_layers, self.conv_out_channels, seq_length).contiguous()\n return (kernels, biases)", "docstring": "Maps a conditioning log-mel spectrogram to a tensor of convolutional kernels and biases, for use in location\nvariable convolutional layers. Note that the input spectrogram should have shape (batch_size, input_channels,\nseq_length).\n\nArgs:\nspectrogram (`torch.FloatTensor` of shape `(batch_size, input_channels, seq_length)`):\nTensor containing the log-mel spectrograms.\n\nReturns:\nTuple[`torch.FloatTensor, `torch.FloatTensor`]: tuple of tensors where the first element is the tensor of\nlocation variable convolution kernels of shape `(batch_size, self.conv_layers, self.conv_in_channels,\nself.conv_out_channels, self.conv_kernel_size, seq_length)` and the second element is the tensor of\nlocation variable convolution biases of shape `(batch_size, self.conv_layers. self.conv_out_channels,\nseq_length)`.", "source": "github-repos"}
422{"code": "def find_matching_symlink(path, source):\n\n def to_abs(target):\n if os.path.isabs(target):\n return target\n else:\n return os.path.normpath(os.path.join(path, target))\n abs_source = to_abs(source)\n for name in os.listdir(path):\n linkpath = os.path.join(path, name)\n if os.path.islink:\n source_ = os.readlink(linkpath)\n if (to_abs(source_) == abs_source):\n return name\n return None", "docstring": "Find a symlink under `path` that points at `source`.\n\nIf source is relative, it is considered relative to `path`.\n\nReturns:\nstr: Name of symlink found, or None.", "source": "codesearchnet"}
423{"code": "def extract_storm_patches(label_grid, data, x_grid, y_grid, times, dx=1, dt=1, patch_radius=16):\n storm_objects = []\n if (len(label_grid.shape) == 3):\n ij_grid = np.indices(label_grid.shape[1:])\n for (t, time) in enumerate(times):\n storm_objects.append([])\n centers = list(center_of_mass(data[t], labels=label_grid[t], index=np.arange(1, (label_grid[t].max() + 1))))\n if (len(centers) > 0):\n for (o, center) in enumerate(centers):\n int_center = np.round(center).astype(int)\n obj_slice_buff = [slice((int_center[0] - patch_radius), (int_center[0] + patch_radius)), slice((int_center[1] - patch_radius), (int_center[1] + patch_radius))]\n storm_objects[(- 1)].append(STObject(data[t][obj_slice_buff], np.where((label_grid[t][obj_slice_buff] == (o + 1)), 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], time, time, dx=dx, step=dt))\n if (t > 0):\n dims = storm_objects[(- 1)][(- 1)].timesteps[0].shape\n storm_objects[(- 1)][(- 1)].estimate_motion(time, data[(t - 1)], dims[1], dims[0])\n else:\n ij_grid = np.indices(label_grid.shape)\n storm_objects.append([])\n centers = list(center_of_mass(data, labels=label_grid, index=np.arange(1, (label_grid.max() + 1))))\n if (len(centers) > 0):\n for (o, center) in enumerate(centers):\n int_center = np.round(center).astype(int)\n obj_slice_buff = (slice((int_center[0] - patch_radius), (int_center[0] + patch_radius)), slice((int_center[1] - patch_radius), (int_center[1] + patch_radius)))\n storm_objects[(- 1)].append(STObject(data[obj_slice_buff], np.where((label_grid[obj_slice_buff] == (o + 1)), 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], times[0], times[0], dx=dx, step=dt))\n return storm_objects", "docstring": "After storms are labeled, this method extracts boxes of equal size centered on each storm from the grid and places\nthem into STObjects. The STObjects contain intensity, location, and shape information about each storm\nat each timestep.\n\nArgs:\nlabel_grid: 2D or 3D array output by label_storm_objects.\ndata: 2D or 3D array used as input to label_storm_objects.\nx_grid: 2D array of x-coordinate data, preferably on a uniform spatial grid with units of length.\ny_grid: 2D array of y-coordinate data.\ntimes: List or array of time values, preferably as integers\ndx: grid spacing in same units as x_grid and y_grid.\ndt: period elapsed between times\npatch_radius: Number of grid points from center of mass to extract\n\nReturns:\nstorm_objects: list of lists containing STObjects identified at each time.", "source": "codesearchnet"}
424{"code": "def GetPresetsByOperatingSystem(self, operating_system):\n \n preset_definitions = []\n for preset_definition in self._definitions.values():\n for preset_operating_system in preset_definition.operating_systems:\n if preset_operating_system.IsEquivalent(operating_system):\n preset_definitions.append(preset_definition)\n\n return preset_definitions", "docstring": "Retrieves preset definitions for a specific operating system.\n\nArgs:\noperating_system (OperatingSystemArtifact): an operating system artifact\nattribute container.\n\nReturns:\nlist[PresetDefinition]: preset definition that correspond with the\noperating system.", "source": "juraj-google-style"}
425{"code": "def _create_hunt(self, name, args):\n \n runner_args = self.grr_api.types.CreateHuntRunnerArgs()\n runner_args.description = self.reason\n hunt = self.grr_api.CreateHunt(\n flow_name=name, flow_args=args, hunt_runner_args=runner_args)\n print('{0!s}: Hunt created'.format(hunt.hunt_id))\n self._check_approval_wrapper(hunt, hunt.Start)\n return hunt", "docstring": "Create specified hunt.\n\nArgs:\nname: string containing hunt name.\nargs: proto (*FlowArgs) for type of hunt, as defined in GRR flow proto.\n\nReturns:\nThe newly created GRR hunt object.\n\nRaises:\nValueError: if approval is needed and approvers were not specified.", "source": "juraj-google-style"}
426{"code": "def _merge_nrows(nrows, static_nrows, value, dtype, validate):\n static_value_nrows = tensor_shape.dimension_at_index(value.shape, 0)\n if isinstance(value, tensor.Tensor):\n value_nrows = array_ops.shape(value, out_type=dtype)[0]\n else:\n value_nrows = value.nrows()\n if nrows is None:\n nrows = value_nrows\n elif static_value_nrows.value is not None and static_nrows.value is not None:\n if not static_value_nrows.is_compatible_with(static_nrows):\n raise ValueError('fields have incompatible nrows')\n nrows = value_nrows\n elif validate:\n nrows = control_flow_ops.with_dependencies([check_ops.assert_equal(nrows, value_nrows, message='fields have incompatible nrows')], nrows)\n return (nrows, static_nrows._merge_with(static_value_nrows))", "docstring": "Merges `nrows` with `nrows(value)`.\n\nChecks that `value` has the expected number of rows (`nrows`), and returns\n`nrows`. If `validate` is true, then add validation ops that check that\nthe `nrows` values match.\n\nArgs:\nnrows: scalar integer Tensor.\nstatic_nrows: tf.Dimension: static value of nrows, if known.\nvalue: Tensor or RaggedTensor or StructuredTensor\ndtype: dtype for `nrows`.\nvalidate: bool -- whether to add validation ops.\n\nReturns:\nA tuple `(nrows, static_nrows)`.", "source": "github-repos"}
427{"code": "def _add_logger_by_name(self, name):\n data = dict(request.forms)\n loc = data.pop('loc', '')\n port = data.pop('port', None)\n conn_type = data.pop('conn_type', None)\n if ((not port) or (not conn_type)):\n e = 'Port and/or conn_type not set'\n raise ValueError(e)\n address = [loc, int(port)]\n if ('rotate_log' in data):\n data['rotate_log'] = (True if (data == 'true') else False)\n if ('rotate_log_delta' in data):\n data['rotate_log_delta'] = int(data['rotate_log_delta'])\n self._logger_manager.add_logger(name, address, conn_type, **data)", "docstring": "Handles POST requests for adding a new logger.\n\nExpects logger configuration to be passed in the request's query string.\nThe logger name is included in the URL and the address components and\nconnection type should be included as well. The loc attribute is\ndefaulted to \"localhost\" when making the socket connection if not\ndefined.\n\nloc = IP / interface\nport = port / protocol\nconn_type = udp or ethernet\n\nRaises:\nValueError:\nif the port or connection type are not supplied.", "source": "codesearchnet"}
428{"code": "def removeMapIdentity(self, subject, vendorSpecific=None):\n \n response = self.removeMapIdentityResponse(subject, vendorSpecific)\n return self._read_boolean_response(response)", "docstring": "See Also: removeMapIdentityResponse()\n\nArgs:\nsubject:\nvendorSpecific:\n\nReturns:", "source": "juraj-google-style"}
429{"code": "def fill_list(self, list, input_list):\n \n for name in input_list:\n \n item = QtGui.QStandardItem(name)\n item.setSelectable(True)\n item.setEditable(False)\n\n list.model().appendRow(item)", "docstring": "fills a tree with nested parameters\nArgs:\ntree: QtGui.QTreeView to fill\nparameters: dictionary or Parameter object which contains the information to use to fill", "source": "juraj-google-style"}
430{"code": "class Phi4MultimodalVisionEncoder(nn.Module):\n\n def __init__(self, config: Phi4MultimodalVisionConfig):\n super().__init__()\n self.config = config\n self.layers = nn.ModuleList([Phi4MultimodalVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)])\n self.gradient_checkpointing = False\n\n @can_return_tuple\n def forward(self, inputs_embeds, attention_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None) -> BaseModelOutput:\n \n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n encoder_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n hidden_states = inputs_embeds\n for encoder_layer in self.layers:\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n layer_outputs = encoder_layer(hidden_states, attention_mask, output_attentions=output_attentions)\n hidden_states = layer_outputs[0]\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n return BaseModelOutput(last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions)", "docstring": "Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a\n[`Phi4MultimodalVisionEncoderLayer`].\n\nArgs:\nconfig: Phi4MultimodalVisionConfig", "source": "github-repos"}
431{"code": "def need(self, folder, page=None, perpage=None):\n \n assert isinstance(page, int) or page is None\n assert isinstance(perpage, int) or perpage is None\n return self.get('need', params={'folder': folder,\n 'page': page,\n 'perpage': perpage})", "docstring": "Returns lists of files which are needed by this device in order\nfor it to become in sync.\n\nArgs:\nfolder (str):\npage (int): If defined applies pagination accross the\ncollection of results.\nperpage (int): If defined applies pagination across the\ncollection of results.\n\nReturns:\ndict", "source": "juraj-google-style"}
432{"code": "def l1_regularizer(weight=1.0, scope=None):\n\n def regularizer(tensor):\n with tf.name_scope(scope, 'L1Regularizer', [tensor]):\n l1_weight = tf.convert_to_tensor(weight, dtype=tensor.dtype.base_dtype, name='weight')\n return tf.multiply(l1_weight, tf.reduce_sum(tf.abs(tensor)), name='value')\n return regularizer", "docstring": "Define a L1 regularizer.\n\nArgs:\nweight: scale the loss by this factor.\nscope: Optional scope for name_scope.\n\nReturns:\na regularizer function.", "source": "codesearchnet"}
433{"code": "def size(self, path):\n try:\n return s3io.S3IO(options=self._options).size(path)\n except Exception as e:\n raise BeamIOError('size() operation failed', {path: e})", "docstring": "Get size of path on the FileSystem.\n\nArgs:\npath: string path in question.\n\nReturns: int size of path according to the FileSystem.\n\nRaises:\n``BeamIOError``: if path doesn't exist.", "source": "github-repos"}
434{"code": "def issued_at(self):\n issued_at = self._issued_at\n if (issued_at is None):\n self._issued_at = int(time.time())\n return self._issued_at", "docstring": "Time when access token was requested, as seconds since epoch.\n\nNote:\nAccessing this property when there wasn't any request attempts\nwill return current time.\n\nReturns:\nint", "source": "codesearchnet"}
435{"code": "def __init__(self, editor):\n \n self.editor = editor\n self.timer = QTimer(self.editor)\n self.timer.setSingleShot(True)\n self.timer.timeout.connect(self.do_autosave)\n self._enabled = False \n self._interval = self.DEFAULT_AUTOSAVE_INTERVAL", "docstring": "Constructor.\n\nAutosave is disabled after construction and needs to be enabled\nexplicitly if required.\n\nArgs:\neditor (Editor): editor plugin.", "source": "juraj-google-style"}
436{"code": "def set_learning_phase(value):\n warnings.warn('`tf.keras.backend.set_learning_phase` is deprecated and will be removed after 2020-10-11. To update it, simply pass a True/False value to the `training` argument of the `__call__` method of your layer or model.')\n deprecated_internal_set_learning_phase(value)", "docstring": "Sets the learning phase to a fixed value.\n\nThe backend learning phase affects any code that calls\n`backend.learning_phase()`\nIn particular, all Keras built-in layers use the learning phase as the default\nfor the `training` arg to `Layer.__call__`.\n\nUser-written layers and models can achieve the same behavior with code that\nlooks like:\n\n```python\ndef call(self, inputs, training=None):\nif training is None:\ntraining = backend.learning_phase()\n```\n\nArgs:\nvalue: Learning phase value, either 0 or 1 (integers).\n0 = test, 1 = train\n\nRaises:\nValueError: if `value` is neither `0` nor `1`.", "source": "github-repos"}
437{"code": "def get_all_counters(obj, instance_list=None):\n (counters, instances_avail) = win32pdh.EnumObjectItems(None, None, obj, (- 1), 0)\n if (instance_list is None):\n instance_list = instances_avail\n if (not isinstance(instance_list, list)):\n instance_list = [instance_list]\n counter_list = []\n for counter in counters:\n for instance in instance_list:\n instance = ('*' if (instance.lower() == '_total') else instance)\n counter_list.append((obj, instance, counter))\n else:\n counter_list.append((obj, None, counter))\n return (get_counters(counter_list) if counter_list else {})", "docstring": "Get the values for all counters available to a Counter object\n\nArgs:\n\nobj (str):\nThe name of the counter object. You can get a list of valid names\nusing the ``list_objects`` function\n\ninstance_list (list):\nA list of instances to return. Use this to narrow down the counters\nthat are returned.\n\n.. note::\n``_Total`` is returned as ``*``", "source": "codesearchnet"}
438{"code": "def from_yaml(cls, yaml_path, filename=None):\n \n if filename:\n \n yaml_path = os.path.join(os.path.dirname(yaml_path), filename)\n assert yaml_path.endswith(\".yaml\"), \\\n \"Expected a/path/to/<yamlname>.yaml, got %r\" % yaml_path\n yamlname = os.path.basename(yaml_path)[:-5]\n log.debug(\"Parsing %s\", yaml_path)\n with open(yaml_path) as f:\n text = f.read()\n \n ds = yaml.load(text, Loader=yaml.RoundTripLoader)\n docstring = None\n sections = []\n for d in ds:\n assert len(d) == 1, \\\n \"Expected section length 1, got %d\" % len(d)\n lineno = d._yaml_line_col.line + 1\n name = list(d)[0]\n sections.append(cls(\n yaml_path, lineno, name, d[name]))\n if name == \"builtin.defines.docstring\":\n docstring = d[name][\"value\"]\n\n return sections, yamlname, docstring", "docstring": "Split a dictionary into parameters controllers parts blocks defines\n\nArgs:\nyaml_path (str): File path to YAML file, or a file in the same dir\nfilename (str): If give, use this filename as the last element in\nthe yaml_path (so yaml_path can be __file__)\n\nReturns:\ntuple: (sections, yamlname, docstring) where sections is a\nlist of created sections", "source": "juraj-google-style"}
439{"code": "def chebyshev(coefs, time, domain):\n return (Chebyshev(coefs, domain=domain)(time) - (0.5 * coefs[0]))", "docstring": "Evaluate a Chebyshev Polynomial\n\nArgs:\ncoefs (list, np.array): Coefficients defining the polynomial\ntime (int, float): Time where to evaluate the polynomial\ndomain (list, tuple): Domain (or time interval) for which the polynomial is defined: [left, right]\n\nReference: Appendix A in the MSG Level 1.5 Image Data Format Description.", "source": "codesearchnet"}
440{"code": "def get_num_bytes(self, batch: Sequence[torch.Tensor]) -> int:\n return sum((el.element_size() for tensor in batch for el in tensor.values()))", "docstring": "Returns:\nThe number of bytes of data for a batch of dict of Tensors.", "source": "github-repos"}
441{"code": "def convert_coco_poly_to_mask(segmentations, height: int, width: int, device: torch.device) -> torch.Tensor:\n try:\n from pycocotools import mask as coco_mask\n except ImportError:\n raise ImportError('Pycocotools is not installed in your environment.')\n masks = []\n for polygons in segmentations:\n rles = coco_mask.frPyObjects(polygons, height, width)\n mask = coco_mask.decode(rles)\n if len(mask.shape) < 3:\n mask = mask[..., None]\n mask = torch.as_tensor(mask, dtype=torch.uint8, device=device)\n mask = torch.any(mask, axis=2)\n masks.append(mask)\n if masks:\n masks = torch.stack(masks, axis=0)\n else:\n masks = torch.zeros((0, height, width), dtype=torch.uint8, device=device)\n return masks", "docstring": "Convert a COCO polygon annotation to a mask.\n\nArgs:\nsegmentations (`List[List[float]]`):\nList of polygons, each polygon represented by a list of x-y coordinates.\nheight (`int`):\nHeight of the mask.\nwidth (`int`):\nWidth of the mask.", "source": "github-repos"}
442{"code": "def __init__(self, path_map: Mapping[str, os.PathLike[str]], expected_input_key_map: Optional[Mapping[str, Collection[str]]]=None):\n self.path_map: Mapping[str, os.PathLike[str]] = path_map\n self.expected_input_key_map: Mapping[str, Collection[str]] = {}\n if expected_input_key_map is not None:\n if set(path_map.keys()) != set(expected_input_key_map.keys()):\n raise KeyError('The `path_map` and `expected_input_key_map` should have the same set of keys.')\n self.expected_input_key_map = expected_input_key_map", "docstring": "Initializes TFRecord represenatative dataset saver.\n\nArgs:\npath_map: Signature def key -> path mapping. Each path is a TFRecord file\nto which a `RepresentativeDataset` is saved. The signature def keys\nshould be a subset of the `SignatureDef` keys of the\n`representative_dataset` argument of the `save()` call.\nexpected_input_key_map: Signature def key -> expected input keys. If set,\nvalidate that the sample has same set of input keys before saving.\n\nRaises:\nKeyError: If path_map and expected_input_key_map have different keys.", "source": "github-repos"}
443{"code": "def collections(self):\n iterator = self._firestore_api.list_collection_ids(self._database_string, metadata=self._rpc_metadata)\n iterator.client = self\n iterator.item_to_value = _item_to_collection_ref\n return iterator", "docstring": "List top-level collections of the client's database.\n\nReturns:\nSequence[~.firestore_v1beta1.collection.CollectionReference]:\niterator of subcollections of the current document.", "source": "codesearchnet"}
444{"code": "def add_sample_file(self, sample_path, source, reference, method='', file_format='raw', file_password='', sample_name='', campaign='', confidence='', description='', bucket_list=[]):\n if os.path.isfile(sample_path):\n data = {'api_key': self.api_key, 'username': self.username, 'source': source, 'reference': reference, 'method': method, 'filetype': file_format, 'upload_type': 'file', 'campaign': campaign, 'confidence': confidence, 'description': description, 'bucket_list': ','.join(bucket_list)}\n if (sample_name != ''):\n data['filename'] = sample_name\n with open(sample_path, 'rb') as fdata:\n if file_password:\n data['password'] = file_password\n r = requests.post('{0}/samples/'.format(self.url), data=data, files={'filedata': fdata}, verify=self.verify, proxies=self.proxies)\n if (r.status_code == 200):\n result_data = json.loads(r.text)\n return result_data\n else:\n log.error('Error with status code {0} and message {1}'.format(r.status_code, r.text))\n return None", "docstring": "Adds a file sample. For meta data only use add_sample_meta.\n\nArgs:\nsample_path: The path on disk of the sample to upload\nsource: Source of the information\nreference: A reference where more information can be found\nmethod: The method for obtaining the sample.\nfile_format: Must be raw, zip, or rar.\nfile_password: The password of a zip or rar archived sample\nsample_name: Specify a filename for the sample rather than using\nthe name on disk\ncampaign: An associated campaign\nconfidence: The campaign confidence\ndescription: A text description of the sample\nbucket_list: A list of bucket list items to add\nReturns:\nA JSON sample object or None if there was an error.", "source": "codesearchnet"}
445{"code": "def find_eq_stress(strains, stresses, tol=1e-10):\n stress_array = np.array(stresses)\n strain_array = np.array(strains)\n eq_stress = stress_array[np.all((abs(strain_array) < tol), axis=(1, 2))]\n if (eq_stress.size != 0):\n all_same = (abs((eq_stress - eq_stress[0])) < 1e-08).all()\n if ((len(eq_stress) > 1) and (not all_same)):\n raise ValueError('Multiple stresses found for equilibrium strain state, please specify equilibrium stress or remove extraneous stresses.')\n eq_stress = eq_stress[0]\n else:\n warnings.warn('No eq state found, returning zero voigt stress')\n eq_stress = Stress(np.zeros((3, 3)))\n return eq_stress", "docstring": "Finds stress corresponding to zero strain state in stress-strain list\n\nArgs:\nstrains (Nx3x3 array-like): array corresponding to strains\nstresses (Nx3x3 array-like): array corresponding to stresses\ntol (float): tolerance to find zero strain state", "source": "codesearchnet"}
446{"code": "def parse_env(config_schema, env):\n try:\n return {key: item_schema.parse(key, env.get(key)) for (key, item_schema) in config_schema.items()}\n except KeyError as error:\n raise MissingConfigError('Required config not set: {}'.format(error.args[0]))", "docstring": "Parse the values from a given environment against a given config schema\n\nArgs:\nconfig_schema: A dict which maps the variable name to a Schema object\nthat describes the requested value.\nenv: A dict which represents the value of each variable in the\nenvironment.", "source": "codesearchnet"}
447{"code": "def PluginAssets(self, plugin_name):\n \n with self._accumulators_mutex:\n \n items = list(six.iteritems(self._accumulators))\n\n return {run: accum.PluginAssets(plugin_name) for run, accum in items}", "docstring": "Get index of runs and assets for a given plugin.\n\nArgs:\nplugin_name: Name of the plugin we are checking for.\n\nReturns:\nA dictionary that maps from run_name to a list of plugin\nassets for that run.", "source": "juraj-google-style"}
448{"code": "def verify_signature(amazon_cert: crypto.X509, signature: str, request_body: bytes) -> bool:\n \n signature = base64.b64decode(signature)\n\n try:\n crypto.verify(amazon_cert, signature, request_body, 'sha1')\n result = True\n except crypto.Error:\n result = False\n\n return result", "docstring": "Verifies Alexa request signature.\n\nArgs:\namazon_cert: Pycrypto X509 Amazon certificate.\nsignature: Base64 decoded Alexa request signature from Signature HTTP header.\nrequest_body: full HTTPS request body\nReturns:\nresult: True if verification was successful, False if not.", "source": "juraj-google-style"}
449{"code": "def trace_region_count(self):\n \n cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS\n data = ctypes.c_uint32(0)\n res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))\n if (res == 1):\n raise errors.JLinkException('Failed to get trace region count.')\n return data.value", "docstring": "Retrieves a count of the number of available trace regions.\n\nArgs:\nself (JLink): the ``JLink`` instance.\n\nReturns:\nCount of the number of available trace regions.", "source": "juraj-google-style"}
450{"code": "def ProcessPathSpec(self, mediator, path_spec):\n \n self.last_activity_timestamp = time.time()\n self.processing_status = definitions.STATUS_INDICATOR_RUNNING\n\n file_entry = path_spec_resolver.Resolver.OpenFileEntry(\n path_spec, resolver_context=mediator.resolver_context)\n\n if file_entry is None:\n display_name = mediator.GetDisplayNameForPathSpec(path_spec)\n logger.warning(\n 'Unable to open file entry with path spec: {0:s}'.format(\n display_name))\n self.processing_status = definitions.STATUS_INDICATOR_IDLE\n return\n\n mediator.SetFileEntry(file_entry)\n\n try:\n if file_entry.IsDirectory():\n self._ProcessDirectory(mediator, file_entry)\n self._ProcessFileEntry(mediator, file_entry)\n\n finally:\n mediator.ResetFileEntry()\n\n self.last_activity_timestamp = time.time()\n self.processing_status = definitions.STATUS_INDICATOR_IDLE", "docstring": "Processes a path specification.\n\nArgs:\nmediator (ParserMediator): mediates the interactions between\nparsers and other components, such as storage and abort signals.\npath_spec (dfvfs.PathSpec): path specification.", "source": "juraj-google-style"}
451{"code": "def Serialize(self, writer):\n \n super(Block, self).Serialize(writer)\n writer.WriteSerializableArray(self.Transactions)", "docstring": "Serialize full object.\n\nArgs:\nwriter (neo.IO.BinaryWriter):", "source": "juraj-google-style"}
452{"code": "def __init__(self, initialization_list=None):\n \n if initialization_list:\n \n self._trackers = {}\n for value_category_key, description_list in initialization_list.items():\n description = EventTrackerDescription._make(description_list)\n self._trackers[value_category_key] = _EventTracker(\n event_count=description.event_count,\n first_timestamp=description.first_timestamp,\n last_timestamp=description.last_timestamp)\n else:\n \n self._trackers = {\n constants.NAN_KEY: _EventTracker(),\n constants.NEG_INF_KEY: _EventTracker(),\n constants.POS_INF_KEY: _EventTracker(),\n }", "docstring": "Stores alert history for a single device, tensor pair.\n\nArgs:\ninitialization_list: (`list`) An optional list parsed from JSON read\nfrom disk. That entity is used to initialize this NumericsAlertHistory.\nUse the create_jsonable_object method of this class to create such an\nobject.", "source": "juraj-google-style"}
453{"code": "def is_remote_path(filepath):\n if re.match('^(/cns|/cfs|/gcs|/hdfs|/readahead|/placer|/tfhub|.*:\n return True\n return False", "docstring": "Determines if a given filepath indicates a remote location.\n\nThis function checks if the filepath represents a known remote pattern\nsuch as GCS (`/gcs`), CNS (`/cns`), CFS (`/cfs`), HDFS (`/hdfs`), Placer\n(`/placer`), TFHub (`/tfhub`), or a URL (`.*://`).\n\nArgs:\nfilepath (str): The path to be checked.\n\nReturns:\nbool: True if the filepath is a recognized remote path, otherwise False", "source": "github-repos"}
454{"code": "def _set_median_session_metrics(session_group, aggregation_metric):\n measurements = sorted(_measurements(session_group, aggregation_metric), key=operator.attrgetter('metric_value.value'))\n median_session = measurements[((len(measurements) - 1) \n del session_group.metric_values[:]\n session_group.metric_values.MergeFrom(session_group.sessions[median_session].metric_values)", "docstring": "Sets the metrics for session_group to those of its \"median session\".\n\nThe median session is the session in session_group with the median value\nof the metric given by 'aggregation_metric'. The median is taken over the\nsubset of sessions in the group whose 'aggregation_metric' was measured\nat the largest training step among the sessions in the group.\n\nArgs:\nsession_group: A SessionGroup protobuffer.\naggregation_metric: A MetricName protobuffer.", "source": "codesearchnet"}
455{"code": "def start_scan(self, active):\n \n try:\n self.bable.start_scan(self._on_device_found, active_scan=active, sync=True)\n except bable_interface.BaBLEException as err:\n \n if self._active_scan != active:\n raise err\n\n self._active_scan = active\n self.scanning = True", "docstring": "Start a scan. Will call self._on_device_found for each device scanned.\nArgs:\nactive (bool): Indicate if it is an active scan (probing for scan response) or not.", "source": "juraj-google-style"}
456{"code": "def register_type_spec_from_value_converter(type_object, converter_fn, allow_subclass=False):\n _, type_object = tf_decorator.unwrap(type_object)\n _TYPE_CONVERSION_FUNCTION_REGISTRY.append((type_object, converter_fn, allow_subclass))", "docstring": "Registers a function for converting values with a given type to TypeSpecs.\n\nIf multiple registered `type_object`s match a value, then the most recent\nregistration takes precedence. Custom converters should not be defined for\n`CompositeTensor`s; use `CompositeTensor._type_spec` instead.\n\nArgs:\ntype_object: A Python `type` object representing the type of values accepted\nby `converter_fn`.\nconverter_fn: A function that takes one argument (an instance of the type\nrepresented by `type_object`) and returns a `TypeSpec`.\nallow_subclass: If true, then use `isinstance(value, type_object)` to check\nfor matches. If false, then use `type(value) is type_object`.", "source": "github-repos"}
457{"code": "def decode(self, probs, sizes=None):\n \n _, max_probs = torch.max(probs.transpose(0, 1), 2)\n strings = self.convert_to_strings(max_probs.view(max_probs.size(0), max_probs.size(1)), sizes)\n return self.process_strings(strings, remove_repetitions=True)", "docstring": "Returns the argmax decoding given the probability matrix. Removes\nrepeated elements in the sequence, as well as blanks.\n\nArguments:\nprobs: Tensor of character probabilities from the network. Expected shape of seq_length x batch x output_dim\nsizes(optional): Size of each sequence in the mini-batch\nReturns:\nstrings: sequences of the model's best guess for the transcription on inputs", "source": "juraj-google-style"}
458{"code": "def get_instance_status(self):\n status_url = self._get_url('status_path')\n res = self.rest_client.session.get(status_url)\n _handle_http_errors(res)\n return res.json()", "docstring": "Get the status the instance for this Streaming Analytics service.\n\nReturns:\ndict: JSON response for the instance status operation.", "source": "codesearchnet"}
459{"code": "def hpo_diseases(username, password, hpo_ids, p_value_treshold=1):\n \n \n try:\n results = query_phenomizer.query(username, password, *hpo_ids)\n diseases = [result for result in results\n if result['p_value'] <= p_value_treshold]\n return diseases\n except SystemExit:\n return None", "docstring": "Return the list of HGNC symbols that match annotated HPO terms.\n\nArgs:\nusername (str): username to use for phenomizer connection\npassword (str): password to use for phenomizer connection\n\nReturns:\nquery_result: a generator of dictionaries on the form\n{\n'p_value': float,\n'disease_source': str,\n'disease_nr': int,\n'gene_symbols': list(str),\n'description': str,\n'raw_line': str\n}", "source": "juraj-google-style"}
460{"code": "def _build(self, x, prev_state):\n x.get_shape().with_rank(2)\n self._batch_size = x.get_shape().as_list()[0]\n self._dtype = x.dtype\n x_zeros = tf.concat([x, tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)], 1)\n x_ones = tf.concat([x, tf.ones(shape=(self._batch_size, 1), dtype=self._dtype)], 1)\n halting_linear = basic.Linear(name='halting_linear', output_size=1)\n body = functools.partial(self._body, halting_linear=halting_linear, x_ones=x_ones)\n cumul_halting_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)\n iteration_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)\n core_output_size = [x.value for x in self._core.output_size]\n out_init = tf.zeros(shape=((self._batch_size,) + tuple(core_output_size)), dtype=self._dtype)\n cumul_state_init = _nested_zeros_like(prev_state)\n remainder_init = tf.zeros(shape=(self._batch_size, 1), dtype=self._dtype)\n (unused_final_x, final_out, unused_final_state, final_cumul_state, unused_final_halting, final_iteration, final_remainder) = tf.while_loop(self._cond, body, [x_zeros, out_init, prev_state, cumul_state_init, cumul_halting_init, iteration_init, remainder_init])\n act_output = basic.Linear(name='act_output_linear', output_size=self._output_size)(final_out)\n return ((act_output, (final_iteration, final_remainder)), final_cumul_state)", "docstring": "Connects the core to the graph.\n\nArgs:\nx: Input `Tensor` of shape `(batch_size, input_size)`.\nprev_state: Previous state. This could be a `Tensor`, or a tuple of\n`Tensor`s.\n\nReturns:\nThe tuple `(output, state)` for this core.\n\nRaises:\nValueError: if the `Tensor` `x` does not have rank 2.", "source": "codesearchnet"}
461{"code": "def flowshow(flow, win_name='', wait_time=0):\n flow = flowread(flow)\n flow_img = flow2rgb(flow)\n imshow(rgb2bgr(flow_img), win_name, wait_time)", "docstring": "Show optical flow.\n\nArgs:\nflow (ndarray or str): The optical flow to be displayed.\nwin_name (str): The window name.\nwait_time (int): Value of waitKey param.", "source": "codesearchnet"}
462{"code": "def recall_at_k(y_true: List[int], y_pred: List[List[np.ndarray]], k: int):\n num_examples = float(len(y_pred))\n predictions = np.array(y_pred)\n predictions = np.flip(np.argsort(predictions, (- 1)), (- 1))[(:, :k)]\n num_correct = 0\n for el in predictions:\n if (0 in el):\n num_correct += 1\n return (float(num_correct) / num_examples)", "docstring": "Calculates recall at k ranking metric.\n\nArgs:\ny_true: Labels. Not used in the calculation of the metric.\ny_predicted: Predictions.\nEach prediction contains ranking score of all ranking candidates for the particular data sample.\nIt is supposed that the ranking score for the true candidate goes first in the prediction.\n\nReturns:\nRecall at k", "source": "codesearchnet"}
463{"code": "def today(boo):\n tod = datetime.strptime(datetime.today().date().isoformat().replace('-', ' '), '%Y %m %d')\n if boo:\n return int(str(tod).replace('-', '')[:8])\n else:\n return str(tod)[:10]", "docstring": "Return today's date as either a String or a Number, as specified by the User.\n\nArgs:\nboo: if true, function returns Number (20151230); if false, returns String (\"2015-12-30\")\nReturns:\neither a Number or a string, dependent upon the user's input", "source": "codesearchnet"}
464{"code": "def builder(structdef_url: str, fhir_context: context.FhirPathContext) -> expressions.Builder:\n structdef = fhir_context.get_structure_definition(structdef_url)\n struct_type = _fhir_path_data_types.StructureDataType.from_proto(structdef)\n return expressions.Builder(_evaluation.RootMessageNode(fhir_context, struct_type), _PRIMITIVE_HANDLER)", "docstring": "Returns a FHIRPath expression builder.\n\nThis gives the caller tab suggestions and early error detection when\nbuilding FHIRPath expressions. See the documentation on the returned\nexpressions.Builder for more details.\n\nArgs:\nstructdef_url: the URL of the FHIR StructureDefinition to use.\nfhir_context: a DefinitionLoader used to load FHIR structure definitions and\ndependencies.\nReturns: a builder object to creae FHIRPath expressions.", "source": "github-repos"}
465{"code": "def python_executable(check=True, short=False):\n r\n if not check:\n python_exe = 'python'\n else:\n from os.path import isdir\n python_exe_long = unixpath(sys.executable)\n python_exe = python_exe_long\n if short:\n python_exe_short = basename(python_exe_long)\n found = search_env_paths(python_exe_short, key_list=['PATH'],\n verbose=False)\n found = [f for f in found if not isdir(f)]\n if len(found) > 0:\n if found[0] == python_exe_long:\n \n python_exe = python_exe_short\n return python_exe", "docstring": "r\"\"\"\nArgs:\nshort (bool): (default = False)\n\nReturns:\nstr:\n\nExample:\n>>> # ENABLE_DOCTEST\n>>> from utool.util_cplat import * # NOQA\n>>> short = False\n>>> result = python_executable(short)\n>>> print(result)", "source": "juraj-google-style"}
466{"code": "def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n local_stream = utils.BytearrayStream()\n if self._unique_identifier:\n self._unique_identifier.write(local_stream, kmip_version=kmip_version)\n if self._usage_limits_count:\n self._usage_limits_count.write(local_stream, kmip_version=kmip_version)\n if self._cryptographic_usage_mask:\n self._cryptographic_usage_mask.write(local_stream, kmip_version=kmip_version)\n if self._lease_time:\n self._lease_time.write(local_stream, kmip_version=kmip_version)\n self.length = local_stream.length()\n super(CheckResponsePayload, self).write(output_stream, kmip_version=kmip_version)\n output_stream.write(local_stream.buffer)", "docstring": "Write the data encoding the Check response payload to a stream.\n\nArgs:\noutput_stream (stream): A data stream in which to encode object\ndata, supporting a write method; usually a BytearrayStream\nobject.\nkmip_version (KMIPVersion): An enumeration defining the KMIP\nversion with which the object will be encoded. Optional,\ndefaults to KMIP 1.0.\n\nRaises:\nValueError: Raised if the data attribute is not defined.", "source": "codesearchnet"}
467{"code": "def set_role(self, name, value=None, default=False, disable=False):\n \n cmd = self.command_builder('username %s role' % name, value=value,\n default=default, disable=disable)\n return self.configure(cmd)", "docstring": "Configures the user role vale in EOS\n\nArgs:\nname (str): The name of the user to create\n\nvalue (str): The value to configure for the user role\n\ndefault (bool): Configure the user role using the EOS CLI\ndefault command\n\ndisable (bool): Negate the user role using the EOS CLI no command\n\nReturns:\nTrue if the operation was successful otherwise False", "source": "juraj-google-style"}
468{"code": "def set_forced_variation(self, experiment_key, user_id, variation_key):\n if (not self.is_valid):\n self.logger.error(enums.Errors.INVALID_DATAFILE.format('set_forced_variation'))\n return False\n if (not validator.is_non_empty_string(experiment_key)):\n self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment_key'))\n return False\n if (not isinstance(user_id, string_types)):\n self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id'))\n return False\n return self.config.set_forced_variation(experiment_key, user_id, variation_key)", "docstring": "Force a user into a variation for a given experiment.\n\nArgs:\nexperiment_key: A string key identifying the experiment.\nuser_id: The user ID.\nvariation_key: A string variation key that specifies the variation which the user.\nwill be forced into. If null, then clear the existing experiment-to-variation mapping.\n\nReturns:\nA boolean value that indicates if the set completed successfully.", "source": "codesearchnet"}
469{"code": "def get_inter_op_parallelism_threads():\n return context.context().inter_op_parallelism_threads", "docstring": "Get number of threads used for parallelism between independent operations.\n\nDetermines the number of threads used by independent non-blocking operations.\n0 means the system picks an appropriate number.\n\nReturns:\nNumber of parallel threads", "source": "github-repos"}
470{"code": "def read_data_event(self, whence, complete=False, can_flush=False):\n \n return Transition(None, _read_data_handler(whence, self, complete, can_flush))", "docstring": "Creates a transition to a co-routine for retrieving data as bytes.\n\nArgs:\nwhence (Coroutine): The co-routine to return to after the data is satisfied.\ncomplete (Optional[bool]): True if STREAM_END should be emitted if no bytes are read or\navailable; False if INCOMPLETE should be emitted in that case.\ncan_flush (Optional[bool]): True if NEXT may be requested after INCOMPLETE is emitted as a result of this\ndata request.", "source": "juraj-google-style"}
471{"code": "def _GetIdentifierFromPath(self, parser_mediator):\n \n file_entry = parser_mediator.GetFileEntry()\n path = file_entry.path_spec.location\n file_system = file_entry.GetFileSystem()\n path_segments = file_system.SplitPath(path)\n return path_segments[-2]", "docstring": "Extracts a container or a graph ID from a JSON file's path.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\n\nReturns:\nstr: container or graph identifier.", "source": "juraj-google-style"}
472{"code": "def if_sqlserver_disable_constraints_triggers(session: SqlASession, tablename: str) -> None:\n with if_sqlserver_disable_constraints(session, tablename):\n with if_sqlserver_disable_triggers(session, tablename):\n (yield)", "docstring": "If we're running under SQL Server, disable triggers AND constraints for the\nspecified table while the resource is held.\n\nArgs:\nsession: SQLAlchemy :class:`Session`\ntablename: table name", "source": "codesearchnet"}
473{"code": "def json(self, include_id=False, date_fmt=None, object_id_fmt=str):\n (has_slots, d) = _get_dict(self)\n _id = self._id\n if (not include_id):\n self._id = None\n object_ids = {k: v for (k, v) in d.items() if isinstance(v, bson.ObjectId)}\n for (k, v) in object_ids.items():\n if (object_id_fmt is None):\n setattr(self, k, None)\n else:\n setattr(self, k, object_id_fmt(v))\n datetimes = {k: v for (k, v) in d.items() if isinstance(v, datetime.datetime)}\n for (k, v) in datetimes.items():\n if (date_fmt is None):\n ts = (time.mktime(v.timetuple()) + (v.microsecond / 1000000.0))\n setattr(self, k, ts)\n else:\n setattr(self, k, v.strftime(date_fmt))\n j = marshal_dict(self, JSON_TYPES, 'json', include_id=include_id, date_fmt=date_fmt, object_id_fmt=object_id_fmt)\n self._id = _id\n for (k, v) in object_ids.items():\n setattr(self, k, v)\n for (k, v) in datetimes.items():\n setattr(self, k, v)\n return j", "docstring": "Helper method to convert to MongoDB documents to JSON\n\nThis includes helpers to convert non-JSON compatible types\nto valid JSON types. HOWEVER, it cannot recurse into nested\nclasses.\n\nArgs:\ninclude_id: bool, True to cast _id to a str,\nFalse to omit from the result\ndate_fmt: str-or-None: None to cast to UNIX timestamp,\nstr (strftime format) to convert to string,\nfor example: '%Y-%m-%d_%H:%M:%S'\nobject_id_fmt: type, Cast the bson.ObjectId's to this format,\nor None to exclude. This only applies to\nObjectId variables other than _id.\nReturns:\ndict", "source": "codesearchnet"}
474{"code": "def get_minimum_indentation(text):\n lines = text.split('\\n')\n indentations = [get_indentation(line_) for line_ in lines if (len(line_.strip()) > 0)]\n if (len(indentations) == 0):\n return 0\n return min(indentations)", "docstring": "r\"\"\"\nreturns the number of preceding spaces\n\nArgs:\ntext (str): unicode text\n\nReturns:\nint: indentation\n\nCommandLine:\npython -m utool.util_str --exec-get_minimum_indentation --show\n\nExample:\n>>> # ENABLE_DOCTEST\n>>> from utool.util_str import * # NOQA\n>>> import utool as ut\n>>> text = ' foo\\n bar'\n>>> result = get_minimum_indentation(text)\n>>> print(result)\n3", "source": "codesearchnet"}
475{"code": "def parse(self, text, layers=None):\n \n params = {\n \"text\": text,\n \"key\": self.key,\n }\n\n if layers is not None:\n \n if isinstance(layers, six.string_types):\n params[\"layers\"] = layers\n\n \n elif isinstance(layers, collections.Iterable):\n params[\"layers\"] = \",\".join(layers)\n\n req = requests.get(self.NLU_URL, params=params)\n return req.json()", "docstring": "Parsing passed text to json.\n\nArgs:\ntext: Text to parse.\nlayers (optional): Special fields. Only one string\nor iterable object (e.g \"Data\", (\"Data\", \"Fio\")).\nOnly these fields will be returned.\n\n\nReturns:\nThe parsed text into a json object.", "source": "juraj-google-style"}
476{"code": "def update_panel(self, panel_obj, version=None, date_obj=None):\n \n LOG.info(\"Updating panel %s\", panel_obj['panel_name'])\n \n date = panel_obj['date']\n if version:\n LOG.info(\"Updating version from {0} to version {1}\".format(\n panel_obj['version'], version))\n panel_obj['version'] = version\n \n if date_obj:\n date = date_obj\n else:\n date = date_obj or dt.datetime.now()\n panel_obj['date'] = date\n\n updated_panel = self.panel_collection.find_one_and_replace(\n {'_id': panel_obj['_id']},\n panel_obj,\n return_document=pymongo.ReturnDocument.AFTER\n )\n\n return updated_panel", "docstring": "Replace a existing gene panel with a new one\n\nKeeps the object id\n\nArgs:\npanel_obj(dict)\nversion(float)\ndate_obj(datetime.datetime)\n\nReturns:\nupdated_panel(dict)", "source": "juraj-google-style"}
477{"code": "def _retrieve_info(self, request):\n info = _metadata.get_service_account_info(request, service_account=self._service_account_email)\n self._service_account_email = info['email']\n self._scopes = info['scopes']", "docstring": "Retrieve information about the service account.\n\nUpdates the scopes and retrieves the full service account email.\n\nArgs:\nrequest (google.auth.transport.Request): The object used to make\nHTTP requests.", "source": "codesearchnet"}
478{"code": "def _fix_unknown_dimension(self, input_shape, output_shape):\n output_shape = list(output_shape)\n msg = 'total size of new array must be unchanged, input_shape = {}, output_shape = {}'.format(input_shape, output_shape)\n known, unknown = (1, None)\n for index, dim in enumerate(output_shape):\n if dim < 0:\n if unknown is None:\n unknown = index\n else:\n raise ValueError('Can only specify one unknown dimension.')\n else:\n known *= dim\n original = np.prod(input_shape, dtype=int)\n if unknown is not None:\n if known == 0 or original % known != 0:\n raise ValueError(msg)\n output_shape[unknown] = original \n elif original != known:\n raise ValueError(msg)\n return output_shape", "docstring": "Find and replace a missing dimension in an output shape.\n\nThis is a near direct port of the internal Numpy function\n`_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c`\n\nArgs:\ninput_shape: Shape of array being reshaped\noutput_shape: Desired shape of the array with at most\na single -1 which indicates a dimension that should be\nderived from the input shape.\n\nReturns:\nThe new output shape with a -1 replaced with its computed value.\n\nRaises:\nValueError: If the total array size of the output_shape is\ndifferent than the input_shape, or more than one unknown dimension\nis specified.", "source": "github-repos"}
479{"code": "def to_json(self):\n for pool in self._pools:\n if (pool is not None):\n pool.flush(True)\n return {'filehandles': pickle.dumps(self._filehandles)}", "docstring": "Returns writer state to serialize in json.\n\nReturns:\nA json-izable version of the OutputWriter state.", "source": "codesearchnet"}
480{"code": "def find_elb(name='', env='', region=''):\n LOG.info('Find %s ELB in %s [%s].', name, env, region)\n url = '{0}/applications/{1}/loadBalancers'.format(API_URL, name)\n response = requests.get(url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n assert response.ok\n elb_dns = None\n accounts = response.json()\n for account in accounts:\n if ((account['account'] == env) and (account['region'] == region)):\n elb_dns = account['dnsname']\n break\n else:\n raise SpinnakerElbNotFound('Elb for \"{0}\" in region {1} not found'.format(name, region))\n LOG.info('Found: %s', elb_dns)\n return elb_dns", "docstring": "Get an application's AWS elb dns name.\n\nArgs:\nname (str): ELB name\nenv (str): Environment/account of ELB\nregion (str): AWS Region\n\nReturns:\nstr: elb DNS record", "source": "codesearchnet"}
481{"code": "def add(name, beacon_data, **kwargs):\n \n ret = {'comment': 'Failed to add beacon {0}.'.format(name),\n 'result': False}\n\n if name in list_(return_yaml=False, **kwargs):\n ret['comment'] = 'Beacon {0} is already configured.'.format(name)\n return ret\n\n \n \n if any('beacon_module' in key for key in beacon_data):\n res = next(value for value in beacon_data if 'beacon_module' in value)\n beacon_name = res['beacon_module']\n else:\n beacon_name = name\n\n if beacon_name not in list_available(return_yaml=False, **kwargs):\n ret['comment'] = 'Beacon \"{0}\" is not available.'.format(beacon_name)\n return ret\n\n if 'test' in kwargs and kwargs['test']:\n ret['result'] = True\n ret['comment'] = 'Beacon: {0} would be added.'.format(name)\n else:\n try:\n \n \n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'name': name,\n 'beacon_data': beacon_data,\n 'func': 'validate_beacon'},\n 'manage_beacons')\n if res:\n event_ret = eventer.get_event(\n tag='/salt/minion/minion_beacon_validation_complete',\n wait=kwargs.get('timeout', 30))\n valid = event_ret['valid']\n vcomment = event_ret['vcomment']\n\n if not valid:\n ret['result'] = False\n ret['comment'] = ('Beacon {0} configuration invalid, '\n 'not adding.\\n{1}'.format(name, vcomment))\n return ret\n\n except KeyError:\n \n \n ret['result'] = False\n ret['comment'] = 'Event module not available. Beacon add failed.'\n return ret\n\n try:\n res = __salt__['event.fire']({'name': name,\n 'beacon_data': beacon_data,\n 'func': 'add'}, 'manage_beacons')\n if res:\n event_ret = eventer.get_event(\n tag='/salt/minion/minion_beacon_add_complete',\n wait=kwargs.get('timeout', 30))\n if event_ret and event_ret['complete']:\n beacons = event_ret['beacons']\n if name in beacons and beacons[name] == beacon_data:\n ret['result'] = True\n ret['comment'] = 'Added beacon: {0}.'.format(name)\n elif event_ret:\n ret['result'] = False\n ret['comment'] = event_ret['comment']\n else:\n ret['result'] = False\n ret['comment'] = 'Did not receive the manage event ' \\\n 'before the timeout of {0}s' \\\n ''.format(kwargs.get('timeout', 30))\n return ret\n except KeyError:\n \n \n ret['result'] = False\n ret['comment'] = 'Event module not available. Beacon add failed.'\n return ret", "docstring": "Add a beacon on the minion\n\nArgs:\n\nname (str):\nName of the beacon to configure\n\nbeacon_data (dict):\nDictionary or list containing configuration for beacon.\n\nReturns:\ndict: Boolean and status message on success or failure of add.\n\nCLI Example:\n\n.. code-block:: bash\n\nsalt '*' beacons.add ps \"[{'processes': {'salt-master': 'stopped', 'apache2': 'stopped'}}]\"", "source": "juraj-google-style"}
482{"code": "def download_to_directory(self, directory, url, basename=None, overwrite=False, subdir=None):\n log = getLogger('ocrd.resolver.download_to_directory')\n log.debug('directory=|%s| url=|%s| basename=|%s| overwrite=|%s| subdir=|%s|', directory, url, basename, overwrite, subdir)\n if (url is None):\n raise Exception(\"'url' must be a string\")\n if (directory is None):\n raise Exception(\"'directory' must be a string\")\n if (basename is None):\n if ((subdir is not None) or (directory and url.startswith(('file:\n basename = url.rsplit('/', 1)[(- 1)]\n else:\n basename = safe_filename(url)\n if (subdir is not None):\n basename = join(subdir, basename)\n outfilename = join(directory, basename)\n if (exists(outfilename) and (not overwrite)):\n log.debug('File already exists and overwrite=False: %s', outfilename)\n return outfilename\n outfiledir = outfilename.rsplit('/', 1)[0]\n if (not isdir(outfiledir)):\n makedirs(outfiledir)\n log.debug(\"Downloading <%s> to '%s'\", url, outfilename)\n if url.startswith('file:\n url = url[len('file:\n if (':\n copyfile(url, outfilename)\n else:\n response = requests.get(url)\n if (response.status_code != 200):\n raise Exception(('Not found: %s (HTTP %d)' % (url, response.status_code)))\n with open(outfilename, 'wb') as outfile:\n outfile.write(response.content)\n return outfilename", "docstring": "Download a file to the workspace.\n\nEarly Shortcut: If url is a file://-URL and that file is already in the directory, keep it there.\n\nIf basename is not given but subdir is, assume user knows what she's doing and use last URL segment as the basename.\nIf basename is not given and no subdir is given, use the alnum characters in the URL as the basename.\n\nArgs:\ndirectory (string): Directory to download files to\nbasename (string, None): basename part of the filename on disk.\nurl (string): URL to download from\noverwrite (boolean): Whether to overwrite existing files with that name\nsubdir (string, None): Subdirectory to create within the directory. Think fileGrp.\n\nReturns:\nLocal filename", "source": "codesearchnet"}
483{"code": "def _create_tpu_topology(core_locations: List[_CoreLocation], num_tasks: int, num_devices_per_task: int) -> topology.Topology:\n assert min([l.x for l in core_locations]) == 0\n assert min([l.y for l in core_locations]) == 0\n assert min([l.z for l in core_locations]) == 0\n assert min([l.core for l in core_locations]) == 0\n x_max = max([l.x for l in core_locations])\n y_max = max([l.y for l in core_locations])\n z_max = max([l.z for l in core_locations])\n core_max = max([l.core for l in core_locations])\n mesh_shape = [x_max + 1, y_max + 1, z_max + 1, core_max + 1]\n device_coordinates = [[l.x, l.y, l.z, l.core] for l in core_locations]\n device_coordinates = numpy_compat.np_asarray(device_coordinates).reshape(num_tasks, num_devices_per_task, 4)\n return topology.Topology(mesh_shape=mesh_shape, device_coordinates=device_coordinates)", "docstring": "Returns a Topology object build from a _CoreLocation list.\n\nArgs:\ncore_locations: A list of _CoreLocation objects sorted first by TF task ID\nand then by per-task device ordinals.\nnum_tasks: The number of TF tasks in the cluster.\nnum_devices_per_task: The number of TPU devices local to each task.", "source": "github-repos"}
484{"code": "def export_to_tf_tensor(self, x, laid_out_x):\n \n return self.combine_slices(laid_out_x.all_slices, x.shape)", "docstring": "Turn a Tensor into a tf.Tensor.\n\nArgs:\nx: a Tensor\nlaid_out_x: a LaidOutTensor\nReturns:\na tf.Tensor", "source": "juraj-google-style"}
485{"code": "def _get_record(self, model_class, record_id):\n url = '{host}/{namespace}/{model}/{id}'.format(host=self._host, namespace=self._namespace, model=self._translate_name(model_class.__name__), id=record_id)\n data = self._get_json(url)['data']\n fresh_model = model_class(data['attributes'])\n fresh_model.id = data['id']\n fresh_model.validate()\n if (self._cache is not None):\n self._cache.set_record(model_class.__name__, fresh_model.id, fresh_model)\n return fresh_model", "docstring": "Get a single record from the API.\n\nArgs:\nmodel_class (:class:`cinder_data.model.CinderModel`): A subclass of\n:class:`cinder_data.model.CinderModel` of your chosen model.\nrecord_id (int): The id of the record requested.\n\nReturns:\n:class:`cinder_data.model.CinderModel`: An instance of model_class or None.", "source": "codesearchnet"}
486{"code": "def _VerifyMethodCall(self):\n expected = self._PopNextMethod()\n while isinstance(expected, MethodGroup):\n (expected, method) = expected.MethodCalled(self)\n if (method is not None):\n return method\n if (expected != self):\n raise UnexpectedMethodCallError(self, expected)\n return expected", "docstring": "Verify the called method is expected.\n\nThis can be an ordered method, or part of an unordered set.\n\nReturns:\nThe expected mock method.\n\nRaises:\nUnexpectedMethodCall if the method called was not expected.", "source": "codesearchnet"}
487{"code": "def migrate(connection, dsn):\n all_migrations = _get_all_migrations()\n logger.debug('Collected migrations: {}'.format(all_migrations))\n for (version, modname) in all_migrations:\n if (_is_missed(connection, version) and (version <= SCHEMA_VERSION)):\n logger.info('Missed migration: {} migration is missed. Migrating...'.format(version))\n module = __import__(modname, fromlist='dummy')\n trans = connection.begin()\n try:\n module.Migration().migrate(connection)\n _update_version(connection, version)\n trans.commit()\n except:\n trans.rollback()\n logger.error(\"Failed to migrate '{}' on {} \".format(version, dsn))\n raise", "docstring": "Collects all migrations and applies missed.\n\nArgs:\nconnection (sqlalchemy connection):", "source": "codesearchnet"}
488{"code": "def decode_conjure_enum_type(cls, obj, conjure_type):\n if (not (isinstance(obj, str) or (str(type(obj)) == \"<type 'unicode'>\"))):\n raise Exception('Expected to find str type but found {} instead'.format(type(obj)))\n if (obj in conjure_type.__members__):\n return conjure_type[obj]\n else:\n return conjure_type['UNKNOWN']", "docstring": "Decodes json into a conjure enum type.\n\nArgs:\nobj: the json object to decode\nconjure_type: a class object which is the enum type\nwe're decoding into.\nReturns:\nAn instance of enum of type conjure_type.", "source": "codesearchnet"}
489{"code": "def get_privkey(self, address: AddressHex, password: str) -> PrivateKey:\n address = add_0x_prefix(address).lower()\n if (not self.address_in_keystore(address)):\n raise ValueError(('Keystore file not found for %s' % address))\n with open(self.accounts[address]) as data_file:\n data = json.load(data_file)\n acc = Account(data, password, self.accounts[address])\n return acc.privkey", "docstring": "Find the keystore file for an account, unlock it and get the private key\n\nArgs:\naddress: The Ethereum address for which to find the keyfile in the system\npassword: Mostly for testing purposes. A password can be provided\nas the function argument here. If it's not then the\nuser is interactively queried for one.\nReturns\nThe private key associated with the address", "source": "codesearchnet"}
490{"code": "def List(self, request, global_params=None):\n config = self.GetMethodConfig('List')\n return self._RunMethod(config, request, global_params=global_params)", "docstring": "Lists `WorkerPool`s.\n\nArgs:\nrequest: (CloudbuildProjectsLocationsWorkerPoolsListRequest) input message\nglobal_params: (StandardQueryParameters, default: None) global arguments\nReturns:\n(ListWorkerPoolsResponse) The response message.", "source": "github-repos"}
491{"code": "def create_workspace(self, did, name, version_id=None):\n payload = {'isPublic': True, 'name': name}\n if version_id:\n payload['versionId'] = version_id\n return self._api.request('post', (('/api/documents/d/' + did) + '/workspaces'), body=payload)", "docstring": "Create a workspace in the specified document.\n\nArgs:\n- did (str): the document id of where to create the new workspace\n- name (str): the new name of the copied workspace.\n- version_id (str): the ID of the version to be copied into a new workspace\n\nReturns:\n- requests.Response: Onshape response data", "source": "codesearchnet"}
492{"code": "def get_resource_from_handle(self, resource_handle, verify_repo=True):\n \n if verify_repo:\n \n \n \n \n if resource_handle.variables.get(\"repository_type\") != self.name():\n raise ResourceError(\"repository_type mismatch - requested %r, \"\n \"repository_type is %r\"\n % (resource_handle.variables[\"repository_type\"],\n self.name()))\n\n if resource_handle.variables.get(\"location\") != self.location:\n raise ResourceError(\"location mismatch - requested %r, \"\n \"repository location is %r \"\n % (resource_handle.variables[\"location\"],\n self.location))\n\n resource = self.pool.get_resource_from_handle(resource_handle)\n resource._repository = self\n return resource", "docstring": "Get a resource.\n\nArgs:\nresource_handle (`ResourceHandle`): Handle of the resource.\n\nReturns:\n`PackageRepositoryResource` instance.", "source": "juraj-google-style"}
493{"code": "def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id):\n feed_item_target_service = client.GetService('FeedItemTargetService', 'v201809')\n ad_group_target = {'xsi_type': 'FeedItemAdGroupTarget', 'feedId': feed_item['feedId'], 'feedItemId': feed_item['feedItemId'], 'adGroupId': adgroup_id}\n operation = {'operator': 'ADD', 'operand': ad_group_target}\n response = feed_item_target_service.mutate([operation])\n new_ad_group_target = response['value'][0]\n print(('Feed item target for feed ID %s and feed item ID %s was created to restrict serving to ad group ID %s' % (new_ad_group_target['feedId'], new_ad_group_target['feedItemId'], new_ad_group_target['adGroupId'])))", "docstring": "Restricts the feed item to an ad group.\n\nArgs:\nclient: an AdWordsClient instance.\nfeed_item: The feed item.\nadgroup_id: The ad group ID.", "source": "codesearchnet"}
494{"code": "def RegisterOutputs(cls, output_classes, disabled=False):\n \n for output_class in output_classes:\n cls.RegisterOutput(output_class, disabled)", "docstring": "Registers output classes.\n\nThe output classes are identified based on their NAME attribute.\n\nArgs:\noutput_classes (list[type]): output module classes.\ndisabled (Optional[bool]): True if the output module is disabled due to\nthe module not loading correctly or not.\n\nRaises:\nKeyError: if output class is already set for the corresponding name.", "source": "juraj-google-style"}
495{"code": "def Git(repository, directory, rev=None, prefix=None, shallow_clone=True):\n \n repository_loc = str(prefix)\n if prefix is None:\n repository_loc = str(CFG[\"tmp_dir\"])\n\n from benchbuild.utils.cmd import git\n\n src_dir = local.path(repository_loc) / directory\n if not source_required(src_dir):\n Copy(src_dir, \".\")\n return\n\n extra_param = []\n if shallow_clone:\n extra_param.append(\"--depth\")\n extra_param.append(\"1\")\n\n git(\"clone\", extra_param, repository, src_dir)\n if rev:\n with local.cwd(src_dir):\n git(\"checkout\", rev)\n\n update_hash(src_dir)\n Copy(src_dir, \".\")\n return repository_loc", "docstring": "Get a clone of the given repo\n\nArgs:\nrepository (str): Git URL of the SOURCE repo.\ndirectory (str): Name of the repo folder on disk.\ntgt_root (str): TARGET folder for the git repo.\nDefaults to ``CFG[\"tmpdir\"]``\nshallow_clone (bool): Only clone the repository shallow\nDefaults to true", "source": "juraj-google-style"}
496{"code": "def GetAttribute(self, identifier):\n \n if not self._is_parsed:\n self._Parse()\n self._is_parsed = True\n\n if identifier not in self._attributes:\n return None\n\n return self._attributes[identifier]", "docstring": "Retrieves a specific attribute.\n\nArgs:\nidentifier (str): identifier of the attribute within the volume.\n\nReturns:\nVolumeAttribute: volume attribute or None if not available.", "source": "juraj-google-style"}
497{"code": "def RefreshResumableUploadState(self):\n if (self.strategy != RESUMABLE_UPLOAD):\n return\n self.EnsureInitialized()\n refresh_request = http_wrapper.Request(url=self.url, http_method='PUT', headers={'Content-Range': 'bytes */*'})\n refresh_response = http_wrapper.MakeRequest(self.http, refresh_request, redirections=0, retries=self.num_retries)\n range_header = self._GetRangeHeaderFromResponse(refresh_response)\n if (refresh_response.status_code in (http_client.OK, http_client.CREATED)):\n self.__complete = True\n self.__progress = self.total_size\n self.stream.seek(self.progress)\n self.__final_response = refresh_response\n elif (refresh_response.status_code == http_wrapper.RESUME_INCOMPLETE):\n if (range_header is None):\n self.__progress = 0\n else:\n self.__progress = (self.__GetLastByte(range_header) + 1)\n self.stream.seek(self.progress)\n else:\n raise exceptions.HttpError.FromResponse(refresh_response)", "docstring": "Talk to the server and refresh the state of this resumable upload.\n\nReturns:\nResponse if the upload is complete.", "source": "codesearchnet"}
498{"code": "def copy_table(self, src, dst):\n self.create_table_from(dst, src)\n self.execute('INSERT INTO {dst} SELECT * FROM {src}'.format(dst=dst, src=src))\n self.commit()", "docstring": "Create a carbon copy of the source table.\n\nArguments:\n\nsrc (str): The name of the table to copy.\ndst (str): The name of the target duplicate table.\n\nRaises:\n\nsql.OperationalError: If source table does not exist.", "source": "codesearchnet"}
499{"code": "def get_full_path(path):\n if path_utils.isabs(path):\n return path\n else:\n return path_utils.join(_pytype_source_dir(), path)", "docstring": "Full path to a file or directory within the pytype source tree.\n\nArguments:\npath: An absolute or relative path.\n\nReturns:\npath for absolute paths.\nfull path resolved relative to pytype/ for relative paths.", "source": "github-repos"}
500{"code": "def decode_schedule(string):\n \n splits = string.split()\n steps = [int(x[1:]) for x in splits[1:] if x[0] == '@']\n pmfs = np.reshape(\n [float(x) for x in splits[1:] if x[0] != '@'], [len(steps), -1])\n return splits[0], tuplize(steps), tuplize(pmfs)", "docstring": "Decodes a string into a schedule tuple.\n\nArgs:\nstring: The string encoding of a schedule tuple.\n\nReturns:\nA schedule tuple, see encode_schedule for details.", "source": "juraj-google-style"}
501{"code": "def get_representations_of_kind(kind, start=None, end=None):\n \n q = Property.query(ancestor=Property.key_for_kind(kind))\n if start is not None and start != '':\n q = q.filter(Property.key >= Property.key_for_property(kind, start))\n if end is not None:\n if end == '':\n return {}\n q = q.filter(Property.key < Property.key_for_property(kind, end))\n\n result = {}\n for property in q:\n result[property.property_name] = property.property_representation\n\n return result", "docstring": "Return all representations of properties of kind in the specified range.\n\nNOTE: This function does not return unindexed properties.\n\nArgs:\nkind: name of kind whose properties you want.\nstart: only return properties >= start if start is not None.\nend: only return properties < end if end is not None.\n\nReturns:\nA dictionary mapping property names to its list of representations.", "source": "juraj-google-style"}
502{"code": "def _update_version(connection, version):\n if (connection.engine.name == 'sqlite'):\n connection.execute('PRAGMA user_version = {}'.format(version))\n elif (connection.engine.name == 'postgresql'):\n connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_SCHEMA_NAME)))\n connection.execute(DDL('CREATE SCHEMA IF NOT EXISTS {};'.format(POSTGRES_PARTITION_SCHEMA_NAME)))\n connection.execute('CREATE TABLE IF NOT EXISTS {}.user_version(version INTEGER NOT NULL);'.format(POSTGRES_SCHEMA_NAME))\n if connection.execute('SELECT * FROM {}.user_version;'.format(POSTGRES_SCHEMA_NAME)).fetchone():\n connection.execute('UPDATE {}.user_version SET version = {};'.format(POSTGRES_SCHEMA_NAME, version))\n else:\n connection.execute('INSERT INTO {}.user_version (version) VALUES ({})'.format(POSTGRES_SCHEMA_NAME, version))\n else:\n raise DatabaseMissingError('Do not know how to migrate {} engine.'.format(connection.engine.driver))", "docstring": "Updates version in the db to the given version.\n\nArgs:\nconnection (sqlalchemy connection): sqlalchemy session where to update version.\nversion (int): version of the migration.", "source": "codesearchnet"}
503{"code": "def AddScanNode(self, path_spec, parent_scan_node):\n scan_node = self._scan_nodes.get(path_spec, None)\n if scan_node:\n raise KeyError('Scan node already exists.')\n scan_node = SourceScanNode(path_spec)\n if parent_scan_node:\n if (parent_scan_node.path_spec not in self._scan_nodes):\n raise RuntimeError('Parent scan node not present.')\n scan_node.parent_node = parent_scan_node\n parent_scan_node.sub_nodes.append(scan_node)\n if (not self._root_path_spec):\n self._root_path_spec = path_spec\n self._scan_nodes[path_spec] = scan_node\n if path_spec.IsFileSystem():\n self._file_system_scan_nodes[path_spec] = scan_node\n self.updated = True\n return scan_node", "docstring": "Adds a scan node for a certain path specification.\n\nArgs:\npath_spec (PathSpec): path specification.\nparent_scan_node (SourceScanNode): parent scan node or None.\n\nReturns:\nSourceScanNode: scan node.\n\nRaises:\nKeyError: if the scan node already exists.\nRuntimeError: if the parent scan node is not present.", "source": "codesearchnet"}
504{"code": "def _combine_multiple_returns(self, signatures: 'list[tuple[PyTDSignature, dict[str, cfg.Variable], matcher.GoodMatch]]'):\n options = []\n for sig, _, _ in signatures:\n t = sig.pytd_sig.return_type\n params = pytd_utils.GetTypeParameters(t)\n if params:\n replacement = {}\n for param_type in params:\n replacement[param_type] = pytd.AnythingType()\n replace_visitor = visitors.ReplaceTypeParameters(replacement)\n t = t.Visit(replace_visitor)\n options.append(t)\n if len(set(options)) == 1:\n return options[0]\n ret_type = optimize.Optimize(pytd_utils.JoinTypes(options))\n return ret_type.Visit(visitors.ReplaceUnionsWithAny())", "docstring": "Combines multiple return types.\n\nArgs:\nsignatures: The candidate signatures.\n\nReturns:\nThe combined return type.", "source": "github-repos"}
505{"code": "def remove_time_limit_wrapper(env):\n \n if isinstance(env, gym.wrappers.TimeLimit):\n env = env.env\n env_ = env\n while isinstance(env_, gym.Wrapper):\n if isinstance(env_, gym.wrappers.TimeLimit):\n raise ValueError(\"Can remove only top-level TimeLimit gym.Wrapper.\")\n env_ = env_.env\n return env", "docstring": "Removes top level TimeLimit Wrapper.\n\nRemoves TimeLimit Wrapper from top level if exists, throws error if any other\nTimeLimit Wrapper is present in stack.\n\nArgs:\nenv: environment\n\nReturns:\nthe env with removed time limit wrapper.", "source": "juraj-google-style"}
506{"code": "def has_overlap(self, interval: 'Interval') -> bool:\n \n if self.begin < interval.end and interval.begin < self.end:\n return True\n return False", "docstring": "Check if self has overlap with `interval`.\n\nArgs:\ninterval: interval to be examined\n\nReturns:\nbool: True if self has overlap with `interval` otherwise False", "source": "juraj-google-style"}
507{"code": "def _Open(self, path_spec=None, mode='rb'):\n \n if not path_spec:\n raise ValueError('Missing path specification.')\n\n if path_spec.HasParent():\n raise errors.PathSpecError('Unsupported path specification with parent.')\n\n location = getattr(path_spec, 'location', None)\n\n if location is None:\n raise errors.PathSpecError('Path specification missing location.')\n\n \n \n try:\n is_device = pysmdev.check_device(location)\n except IOError as exception:\n \n \n \n \n\n \n exception_string = str(exception)\n if not isinstance(exception_string, py2to3.UNICODE_TYPE):\n exception_string = py2to3.UNICODE_TYPE(\n exception_string, errors='replace')\n\n if ' access denied ' in exception_string:\n raise errors.AccessError(\n 'Access denied to file: {0:s} with error: {1!s}'.format(\n location, exception_string))\n is_device = False\n\n if not is_device:\n try:\n stat_info = os.stat(location)\n except OSError as exception:\n raise IOError('Unable to open file with error: {0!s}.'.format(\n exception))\n\n \n \n if stat.S_ISCHR(stat_info.st_mode) or stat.S_ISBLK(stat_info.st_mode):\n is_device = True\n\n if is_device:\n self._file_object = pysmdev.handle()\n self._file_object.open(location, mode=mode)\n self._size = self._file_object.media_size\n\n else:\n self._file_object = open(location, mode=mode)\n self._size = stat_info.st_size", "docstring": "Opens the file-like object defined by path specification.\n\nArgs:\npath_spec (PathSpec): path specification.\nmode (Optional[str]): file access mode.\n\nRaises:\nAccessError: if the access to open the file was denied.\nIOError: if the file-like object could not be opened.\nOSError: if the file-like object could not be opened.\nPathSpecError: if the path specification is incorrect.\nValueError: if the path specification is invalid.", "source": "juraj-google-style"}
508{"code": "def get_reaction(self, reactants, products):\n return self._make_request('/reaction', payload={'reactants[]': reactants, 'products[]': products}, mp_decode=False)", "docstring": "Gets a reaction from the Materials Project.\n\nArgs:\nreactants ([str]): List of formulas\nproducts ([str]): List of formulas\n\nReturns:\nrxn", "source": "codesearchnet"}
509{"code": "def get_placeholders(arg, check_duplicates=False):\n \n placeholders = []\n last_match = None\n arg = normalize_placeholders(arg)\n for cur_match in re.finditer(r'\\s*{{|}}\\s*', arg):\n matched_text = cur_match.group().strip()\n if not last_match and matched_text == '{{':\n last_match = cur_match\n continue\n\n last_matched_text = '' if not last_match else last_match.group().strip()\n \n if (not last_matched_text and matched_text == '}}') or (last_matched_text == '{{' and matched_text != '}}'):\n raise CLIError(PLACEHOLDER_BRACKETS_ERROR.format(arg))\n elif last_matched_text == '{{' and matched_text == '}}':\n \n start_index, end_index = last_match.span()[1], cur_match.span()[0]\n placeholders.append(arg[start_index: end_index].strip())\n last_match = None\n\n \n if last_match:\n raise CLIError(PLACEHOLDER_BRACKETS_ERROR.format(arg))\n\n \n if check_duplicates and len(placeholders) != len(set(placeholders)):\n raise CLIError(DUPLICATED_PLACEHOLDER_ERROR.format(arg))\n\n return placeholders", "docstring": "Get all the placeholders' names in order.\nUse the regex below to locate all the opening ({{) and closing brackets (}}).\nAfter that, extract \"stuff\" inside the brackets.\n\nArgs:\narg: The word which this function performs searching on.\ncheck_duplicates: True if we want to check for duplicated positional arguments.\n\nReturns:\nA list of positional arguments in order.", "source": "juraj-google-style"}
510{"code": "def put(self, key, value):\n key = self._service_key(key)\n self._service_ops['put'](key, value)", "docstring": "Stores the object `value` named by `key` in `service`.\n\nArgs:\nkey: Key naming `value`.\nvalue: the object to store.", "source": "codesearchnet"}
511{"code": "def take_profit_replace(self, accountID, orderID, **kwargs):\n return self.replace(accountID, orderID, order=TakeProfitOrderRequest(**kwargs))", "docstring": "Shortcut to replace a pending Take Profit Order in an Account\n\nArgs:\naccountID : The ID of the Account\norderID : The ID of the Take Profit Order to replace\nkwargs : The arguments to create a TakeProfitOrderRequest\n\nReturns:\nv20.response.Response containing the results from submitting\nthe request", "source": "codesearchnet"}
512{"code": "def create_position_ids_from_inputs_embeds(self, inputs_embeds):\n input_shape = inputs_embeds.size()[:-1]\n sequence_length = input_shape[1]\n position_ids = torch.arange(self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device)\n return position_ids.unsqueeze(0).expand(input_shape)", "docstring": "We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.\n\nArgs:\ninputs_embeds: torch.Tensor\n\nReturns: torch.Tensor", "source": "github-repos"}
513{"code": "def __init__(self, source, strict=True):\n \n self._visited_top_module = False\n if not source:\n raise ValueError('The source code of the tree is required.')\n self._source = source\n self._strict = strict\n\n \n \n self._current_lineno = None \n self._current_offset = None \n\n super(LanguageFence, self).__init__()", "docstring": "Creates a LanguageFence.\n\nArgs:\nsource: String, the source code of the AST that will be verified.\nstrict: Boolean, set to False to allow unsafe constructs.\nRaises:\nValueError: if source code has not been supplied.", "source": "juraj-google-style"}
514{"code": "class PhrasalConstraint(Constraint):\n\n def __init__(self, token_ids: List[int]):\n super(Constraint, self).__init__()\n if not isinstance(token_ids, list) or len(token_ids) == 0:\n raise ValueError(f'`token_ids` has to be a non-empty list, but is {token_ids}.')\n if any((not isinstance(token_id, int) or token_id < 0 for token_id in token_ids)):\n raise ValueError(f'Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.')\n self.token_ids = token_ids\n self.seqlen = len(self.token_ids)\n self.fulfilled_idx = -1\n self.completed = False\n\n def advance(self):\n if self.completed:\n return None\n return self.token_ids[self.fulfilled_idx + 1]\n\n def does_advance(self, token_id: int):\n if not isinstance(token_id, int):\n raise TypeError(f'`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}')\n if self.completed:\n return False\n return token_id == self.token_ids[self.fulfilled_idx + 1]\n\n def update(self, token_id: int):\n if not isinstance(token_id, int):\n raise TypeError(f'`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}')\n stepped = False\n completed = False\n reset = False\n if self.does_advance(token_id):\n self.fulfilled_idx += 1\n stepped = True\n if self.fulfilled_idx == self.seqlen - 1:\n completed = True\n self.completed = completed\n else:\n reset = True\n self.reset()\n return (stepped, completed, reset)\n\n def reset(self):\n self.completed = False\n self.fulfilled_idx = 0\n\n def remaining(self):\n return self.seqlen - (self.fulfilled_idx + 1)\n\n def copy(self, stateful=False):\n new_constraint = PhrasalConstraint(self.token_ids)\n if stateful:\n new_constraint.seq_len = self.seqlen\n new_constraint.fulfilled_idx = self.fulfilled_idx\n new_constraint.completed = self.completed\n return new_constraint", "docstring": "[`Constraint`] enforcing that an ordered sequence of tokens is included in the output.\n\nArgs:\ntoken_ids (`List[int]`):\nThe id of the token that must be generated by the output.", "source": "github-repos"}
515{"code": "def create_lock_key(self, device, new_device_json, id_override=None, type_override=None):\n object_id = (id_override or device.object_id())\n object_type = (type_override or device.object_type())\n url_string = '{}/{}s/{}/keys'.format(self.BASE_URL, object_type, object_id)\n try:\n arequest = requests.post(url_string, data=json.dumps(new_device_json), headers=API_HEADERS)\n response_json = arequest.json()\n return response_json\n except requests.exceptions.RequestException:\n return None", "docstring": "Create a new lock key code.\n\nArgs:\ndevice (WinkDevice): The device the change is being requested for.\nnew_device_json (String): The JSON string required to create the device.\nid_override (String, optional): A device ID used to override the\npassed in device's ID. Used to make changes on sub-devices.\ni.e. Outlet in a Powerstrip. The Parent device's ID.\ntype_override (String, optional): Used to override the device type\nwhen a device inherits from a device other than WinkDevice.\nReturns:\nresponse_json (Dict): The API's response in dictionary format", "source": "codesearchnet"}
516{"code": "def recover_cfg(self, start=None, end=None, symbols=None, callback=None, arch_mode=None):\n \n \n if arch_mode is None:\n arch_mode = self.binary.architecture_mode\n\n \n self._load(arch_mode=arch_mode)\n\n \n start = start if start else self.binary.entry_point\n\n cfg, _ = self._recover_cfg(start=start, end=end, symbols=symbols, callback=callback)\n\n return cfg", "docstring": "Recover CFG.\n\nArgs:\nstart (int): Start address.\nend (int): End address.\nsymbols (dict): Symbol table.\ncallback (function): A callback function which is called after each successfully recovered CFG.\narch_mode (int): Architecture mode.\n\nReturns:\nControlFlowGraph: A CFG.", "source": "juraj-google-style"}
517{"code": "async def join(\n self,\n *,\n remote_addrs: Iterable[str],\n listen_addr: str = \"0.0.0.0:2377\",\n join_token: str,\n advertise_addr: str = None,\n data_path_addr: str = None\n ) -> bool:\n \n\n data = {\n \"RemoteAddrs\": list(remote_addrs),\n \"JoinToken\": join_token,\n \"ListenAddr\": listen_addr,\n \"AdvertiseAddr\": advertise_addr,\n \"DataPathAddr\": data_path_addr,\n }\n\n await self.docker._query(\"swarm/join\", method=\"POST\", data=clean_map(data))\n\n return True", "docstring": "Join a swarm.\n\nArgs:\nlisten_addr\nUsed for inter-manager communication\n\nadvertise_addr\nExternally reachable address advertised to other nodes.\n\ndata_path_addr\nAddress or interface to use for data path traffic.\n\nremote_addrs\nAddresses of manager nodes already participating in the swarm.\n\njoin_token\nSecret token for joining this swarm.", "source": "juraj-google-style"}
518{"code": "def deleted(self, deleted_since, filters=None, params=None):\n return self.tc_requests.deleted(self.api_type, self.api_sub_type, deleted_since, owner=self.owner, filters=filters, params=params)", "docstring": "Gets the indicators deleted.\n\nArgs:\nparams:\nfilters:\ndeleted_since: Date since its been deleted", "source": "codesearchnet"}
519{"code": "def _get_js_files(cls, extra_files):\n \n return cls._get_media_files(\n packager=Packager(),\n media_packages=getattr(cls, 'js_packages', {}),\n media_type='js',\n extra_files=extra_files)", "docstring": "Return all JavaScript files from the Media class.\n\nArgs:\nextra_files (list):\nThe contents of the Media class's original :py:attr:`js`\nattribute, if one was provided.\n\nReturns:\nlist:\nThe JavaScript files to return for the :py:attr:`js` attribute.", "source": "juraj-google-style"}
520{"code": "def _decode_quadratic_biases(quadratic_string, edgelist):\n quadratic_bytes = base64.b64decode(quadratic_string)\n return {tuple(edge): bias for (edge, bias) in zip(edgelist, struct.unpack(('<' + ('d' * (len(quadratic_bytes)", "docstring": "Inverse of _serialize_quadratic_biases\n\nArgs:\nquadratic_string (str) : base 64 encoded string of little\nendian 8 byte floats, one for each of the edges.\nedgelist (list): a list of edges of the form [(node1, node2), ...].\n\nReturns:\ndict: J. A dict of the form {edge1: bias1, ...} where each\nedge is of the form (node1, node2).\n\nExample:\n>>> _decode_quadratic_biases('AAAAAAAA8L8AAAAAAADwP5qZmZmZmdk/',\n... [(0, 1), (1, 2), (0, 2)])\n{(0, 1): -1.0, (0, 2): 0.4, (1, 2): 1.0}", "source": "codesearchnet"}
521{"code": "def convert_to_rgb(image: ImageInput) -> ImageInput:\n requires_backends(convert_to_rgb, ['vision'])\n if not isinstance(image, PIL.Image.Image):\n return image\n if image.mode == 'RGB':\n return image\n image = image.convert('RGBA')\n new_image = PIL.Image.new('RGBA', image.size, 'WHITE')\n new_image.paste(image, (0, 0), image)\n new_image = new_image.convert('RGB')\n return new_image", "docstring": "Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image\nas is.\nArgs:\nimage (Image):\nThe image to convert.", "source": "github-repos"}
522{"code": "def use_external_data_format(num_parameters: int) -> bool:\n return compute_serialized_parameters_size(num_parameters, ParameterFormat.Float) >= EXTERNAL_DATA_FORMAT_SIZE_LIMIT", "docstring": "Flag indicating if the model requires using external data format\n\nArgs:\nnum_parameters: Number of parameter on the model\n\nReturns:\nTrue if model.num_parameters() * size_of(float32) >= 2Gb False otherwise", "source": "github-repos"}
523{"code": "def belspec_yaml2json(yaml_fn: str, json_fn: str) -> str:\n try:\n spec_dict = yaml.load(open(yaml_fn, 'r').read(), Loader=yaml.SafeLoader)\n spec_dict['admin'] = {}\n spec_dict['admin']['version_underscored'] = spec_dict['version'].replace('.', '_')\n spec_dict['admin']['parser_fn'] = yaml_fn.replace('.yaml', '_parser.py')\n add_relations(spec_dict)\n add_functions(spec_dict)\n add_namespaces(spec_dict)\n enhance_function_signatures(spec_dict)\n add_function_signature_help(spec_dict)\n with open(json_fn, 'w') as f:\n json.dump(spec_dict, f)\n except Exception as e:\n log.error('Warning: BEL Specification {yaml_fn} could not be read. Cannot proceed.'.format(yaml_fn))\n sys.exit()\n return spec_dict['version']", "docstring": "Enhance BEL specification and save as JSON file\n\nLoad all BEL Specification YAML files and convert to JSON files\nafter enhancing them. Also create a bel_versions.json file with\nall available BEL versions for fast loading.\n\nArgs:\nyaml_fn: original YAML version of BEL Spec\njson_fn: enhanced JSON version of BEL Spec\nReturns:\nstr: version of BEL Spec", "source": "codesearchnet"}
524{"code": "def GetMessages(self, formatter_mediator, event):\n \n if self.DATA_TYPE != event.data_type:\n raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(\n event.data_type))\n\n event_values = event.CopyToDict()\n\n trigger_type = event_values.get('trigger_type', None)\n if trigger_type is not None:\n event_values['trigger_type'] = self._TRIGGER_TYPES.get(\n trigger_type, '0x{0:04x}'.format(trigger_type))\n\n return self._ConditionalFormatMessages(event_values)", "docstring": "Determines the formatted message strings for an event object.\n\nArgs:\nformatter_mediator (FormatterMediator): mediates the interactions\nbetween formatters and other components, such as storage and Windows\nEventLog resources.\nevent (EventObject): event.\n\nReturns:\ntuple(str, str): formatted message string and short message string.\n\nRaises:\nWrongFormatter: if the event object cannot be formatted by the formatter.", "source": "juraj-google-style"}
525{"code": "def etherscan_verify_contract(\n chain_id: int,\n apikey: str,\n source_module: DeploymentModule,\n contract_name: str,\n):\n \n etherscan_api = api_of_chain_id[chain_id]\n deployment_info = get_contracts_deployment_info(\n chain_id=chain_id,\n module=source_module,\n )\n if deployment_info is None:\n raise FileNotFoundError(\n f'Deployment file not found for chain_id={chain_id} and module={source_module}',\n )\n contract_manager = ContractManager(contracts_precompiled_path())\n\n data = post_data_for_etherscan_verification(\n apikey=apikey,\n deployment_info=deployment_info['contracts'][contract_name],\n source=join_sources(source_module=source_module, contract_name=contract_name),\n contract_name=contract_name,\n metadata=json.loads(contract_manager.contracts[contract_name]['metadata']),\n constructor_args=get_constructor_args(\n deployment_info=deployment_info,\n contract_name=contract_name,\n contract_manager=contract_manager,\n ),\n )\n response = requests.post(etherscan_api, data=data)\n content = json.loads(response.content.decode())\n print(content)\n print(f'Status: {content[\"status\"]}; {content[\"message\"]} ; GUID = {content[\"result\"]}')\n\n etherscan_url = etherscan_api.replace('api-', '').replace('api', '')\n etherscan_url += '/verifyContract2?a=' + data['contractaddress']\n manual_submission_guide = f\n\n if content['status'] != '1':\n if content['result'] == 'Contract source code already verified':\n return\n else:\n raise ValueError(\n 'Etherscan submission failed for an unknown reason\\n' +\n manual_submission_guide,\n )\n\n \n guid = content['result']\n status = '0'\n retries = 10\n while status == '0' and retries > 0:\n retries -= 1\n r = guid_status(etherscan_api=etherscan_api, guid=guid)\n status = r['status']\n if r['result'] == 'Fail - Unable to verify':\n raise ValueError(manual_submission_guide)\n if r['result'] == 'Pass - Verified':\n return\n print('Retrying...')\n sleep(5)\n raise TimeoutError(manual_submission_guide)", "docstring": "Calls Etherscan API for verifying the Solidity source of a contract.\n\nArgs:\nchain_id: EIP-155 chain id of the Ethereum chain\napikey: key for calling Etherscan API\nsource_module: a module name to look up contracts_source_path()\ncontract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc.", "source": "juraj-google-style"}
526{"code": "def delete(self, customer_id, token_id, data={}, **kwargs):\n url = '{}/{}/tokens/{}'.format(self.base_url, customer_id, token_id)\n return self.delete_url(url, data, **kwargs)", "docstring": "Delete Given Token For a Customer\n\nArgs:\ncustomer_id : Customer Id for which tokens have to be deleted\ntoken_id : Id for which TOken object has to be deleted\nReturns:\nDict for deleted token", "source": "codesearchnet"}
527{"code": "def add_rect(self, width, height, rid=None): \n \n assert(width > 0 and height >0)\n\n \n section, rotated = self._select_fittest_section(width, height)\n if not section:\n return None\n \n if rotated:\n width, height = height, width\n \n \n self._sections.remove(section)\n self._split(section, width, height)\n \n \n rect = Rectangle(section.x, section.y, width, height, rid)\n self.rectangles.append(rect)\n return rect", "docstring": "Add rectangle of widthxheight dimensions.\n\nArguments:\nwidth (int, float): Rectangle width\nheight (int, float): Rectangle height\nrid: Optional rectangle user id\n\nReturns:\nRectangle: Rectangle with placemente coordinates\nNone: If the rectangle couldn be placed.", "source": "juraj-google-style"}
528{"code": "def make_usage_key_from_deprecated_string(self, location_url):\n warnings.warn('make_usage_key_from_deprecated_string is deprecated! Please use make_usage_key', DeprecationWarning, stacklevel=2)\n return BlockUsageLocator.from_string(location_url).replace(run=self.run)", "docstring": "Deprecated mechanism for creating a UsageKey given a CourseKey and a serialized Location.\n\nNOTE: this prejudicially takes the tag, org, and course from the url not self.\n\nRaises:\nInvalidKeyError: if the url does not parse", "source": "codesearchnet"}
529{"code": "def _load_generic(packname, package, section, target):\n \n from acorn.config import settings\n spack = settings(packname)\n if spack.has_section(section):\n secitems = dict(spack.items(section))\n for fqdn, active in secitems.items():\n target[fqdn] = active == \"1\"", "docstring": "Loads the settings for generic options that take FQDN and a boolean value\n(1 or 0).\n\nArgs:\npackname (str): name of the package to get config settings for.\npackage: actual package object.", "source": "juraj-google-style"}
530{"code": "def init_logger(logger_name='sip', log_level=None, p3_mode: bool=True, show_thread: bool=False, propagate: bool=False, show_log_origin=False):\n log = logging.getLogger(logger_name)\n log.propagate = propagate\n for handler in log.handlers:\n log.removeHandler(handler)\n _debug = ('%(filename)s:%(lineno)d | ' if show_log_origin else '')\n if p3_mode:\n _prefix = '%(asctime)s - %(name)s - %(levelname)s'\n if show_thread:\n _format = '{} - %(threadName)s - {}%(message)s'.format(_prefix, _debug)\n else:\n _format = '{} - {}%(message)s'.format(_prefix, _debug)\n formatter = logging.Formatter(_format)\n formatter.converter = time.gmtime\n else:\n _prefix = '%(asctime)s | %(name)s | %(levelname)s'\n if show_thread:\n _format = '{} | %(threadName)s | {}%(message)s'.format(_prefix, _debug)\n else:\n _format = '{} | {}%(message)s'.format(_prefix, _debug)\n formatter = SIPFormatter(_format, datefmt='%Y-%m-%dT%H:%M:%S.%fZ')\n handler = logging.StreamHandler(stream=sys.stdout)\n handler.setFormatter(formatter)\n log.addHandler(handler)\n if log_level:\n log.setLevel(log_level)\n else:\n log.setLevel(os.getenv('SIP_LOG_LEVEL', 'DEBUG'))", "docstring": "Initialise the SIP logger.\n\nAttaches a stdout stream handler to the 'sip' logger. This will\napply to all logger objects with a name prefixed by 'sip.'\n\nThis function respects the 'SIP_LOG_LEVEL' environment variable to\nset the logging level.\n\nArgs:\nlogger_name (str, optional): Name of the logger object.\nlog_level (str or int, optional): Logging level for the SIP logger.\np3_mode (bool, optional): Print logging statements in a format that\nP3 can support.\nshow_thread (bool, optional): Display the thread in the log message.\npropagate (bool, optional): Propagate settings to parent loggers.\nshow_log_origin (boo, optional): If true show the origin\n(file, line no.) of log messages.", "source": "codesearchnet"}
531{"code": "def create_image_table(self, r=None):\n logger.info('Creating image table...')\n if (r is not None):\n self.r = r\n self.image_table = ImageTable(self)", "docstring": "Create and store a new ImageTable instance based on the current\nDataset. Will generally be called privately, but may be useful as a\nconvenience method in cases where the user wants to re-generate the\ntable with a new smoothing kernel of different radius.\n\nArgs:\nr (int): An optional integer indicating the radius of the smoothing\nkernel. By default, this is None, which will keep whatever\nvalue is currently set in the Dataset instance.", "source": "codesearchnet"}
532{"code": "def delete_lines(self, lines):\n for (k, i) in enumerate(lines):\n del self[(i - k)]", "docstring": "Delete all lines with given line numbers.\n\nArgs:\nlines (list): List of integers corresponding to line numbers to delete", "source": "codesearchnet"}
533{"code": "def with_embedding_spec(self, column_name: str='embedding', convert_fn: Optional[Callable[[List[float]], Any]]=None) -> 'ColumnSpecsBuilder':\n\n def value_fn(chunk: Chunk) -> Any:\n if chunk.embedding is None or chunk.embedding.dense_embedding is None:\n raise ValueError(f'Expected chunk to contain embedding. {chunk}')\n values = chunk.embedding.dense_embedding\n if convert_fn:\n return convert_fn(values)\n return '{' + ','.join((str(x) for x in values)) + '}'\n self._specs.append(ColumnSpec.vector(column_name=column_name, value_fn=value_fn))\n return self", "docstring": "Add embedding :class:`.ColumnSpec` with optional conversion.\n\nArgs:\ncolumn_name: Name for the embedding column (defaults to \"embedding\")\nconvert_fn: Optional function to convert the dense embedding values\nIf None, uses default PostgreSQL array format\n\nReturns:\nSelf for method chaining\n\nExample:\n>>> builder.with_embedding_spec(\n... column_name=\"embedding_vector\",\n... convert_fn=lambda values: '{' + ','.join(f\"{x:.4f}\"\n... for x in values) + '}'\n... )", "source": "github-repos"}
534{"code": "def flatten(inputs, scope=None):\n \n if len(inputs.get_shape()) < 2:\n raise ValueError('Inputs must be have a least 2 dimensions')\n dims = inputs.get_shape()[1:]\n k = dims.num_elements()\n with tf.name_scope(scope, 'Flatten', [inputs]):\n return tf.reshape(inputs, [-1, k])", "docstring": "Flattens the input while maintaining the batch_size.\n\nAssumes that the first dimension represents the batch.\n\nArgs:\ninputs: a tensor of size [batch_size, ...].\nscope: Optional scope for name_scope.\n\nReturns:\na flattened tensor with shape [batch_size, k].\nRaises:\nValueError: if inputs.shape is wrong.", "source": "juraj-google-style"}
535{"code": "def json_dumps(self, data):\n return json.dumps(data, separators=(',', ':'), sort_keys=True, cls=self.json_encoder, ensure_ascii=False).encode('utf8')", "docstring": "Standardized json.dumps function with separators and sorted keys set\n\nArgs:\ndata (dict or list): data to be dumped\n\nReturns:\nstring: json", "source": "codesearchnet"}
536{"code": "def guess_depth(packages):\n if (len(packages) == 1):\n return (packages[0].count('.') + 2)\n return (min((p.count('.') for p in packages)) + 1)", "docstring": "Guess the optimal depth to use for the given list of arguments.\n\nArgs:\npackages (list of str): list of packages.\n\nReturns:\nint: guessed depth to use.", "source": "codesearchnet"}
537{"code": "def create_mock_system_install_device(self, api_level, code_name='REL'):\n self.mock_device.build_info = {'build_version_sdk': bytearray(api_level, 'utf8'), 'build_version_codename': code_name}\n return self.mock_device", "docstring": "Create a mock device with a particular API level.\n\nArgs:\napi_level: A string reflecting the value of the ro.build.version.sdk\nproperty.\ncode_name: The codename of the device's build, defaults to 'REL'\n\nReturns:\nA mock object for the AndroidDevice.", "source": "github-repos"}
538{"code": "def _use_prototype(self, spec, prototypes):\n \n prototype = spec['based-on']\n del spec['based-on']\n for attr in prototype:\n if attr not in spec:\n spec[attr] = copy.deepcopy(prototype[attr])\n\n return spec", "docstring": "Populates the given spec with the values of it's declared prototype\n\nArgs:\nspec (dict): spec to update\nprototypes (dict): Configuration spec containing the prototypes\n\nReturns:\ndict: updated spec", "source": "juraj-google-style"}
539{"code": "def _batch_prepare_for_model(self, batch_ids_pairs: List[Tuple[List[int], None]], batch_entity_ids_pairs: List[Tuple[Optional[List[int]], Optional[List[int]]]], batch_entity_token_spans_pairs: List[Tuple[Optional[List[Tuple[int, int]]], Optional[List[Tuple[int, int]]]]], add_special_tokens: bool=True, padding_strategy: PaddingStrategy=PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy=TruncationStrategy.DO_NOT_TRUNCATE, max_length: Optional[int]=None, max_entity_length: Optional[int]=None, stride: int=0, pad_to_multiple_of: Optional[int]=None, padding_side: Optional[str]=None, return_tensors: Optional[str]=None, return_token_type_ids: Optional[bool]=None, return_attention_mask: Optional[bool]=None, return_overflowing_tokens: bool=False, return_special_tokens_mask: bool=False, return_length: bool=False, verbose: bool=True) -> BatchEncoding:\n batch_outputs = {}\n for input_ids, entity_ids, entity_token_span_pairs in zip(batch_ids_pairs, batch_entity_ids_pairs, batch_entity_token_spans_pairs):\n first_ids, second_ids = input_ids\n first_entity_ids, second_entity_ids = entity_ids\n first_entity_token_spans, second_entity_token_spans = entity_token_span_pairs\n outputs = self.prepare_for_model(first_ids, second_ids, entity_ids=first_entity_ids, pair_entity_ids=second_entity_ids, entity_token_spans=first_entity_token_spans, pair_entity_token_spans=second_entity_token_spans, add_special_tokens=add_special_tokens, padding=PaddingStrategy.DO_NOT_PAD.value, truncation=truncation_strategy.value, max_length=max_length, max_entity_length=max_entity_length, stride=stride, pad_to_multiple_of=None, padding_side=None, return_attention_mask=False, return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask, return_length=return_length, return_tensors=None, prepend_batch_axis=False, verbose=verbose)\n for key, value in outputs.items():\n if key not in batch_outputs:\n batch_outputs[key] = []\n batch_outputs[key].append(value)\n batch_outputs = self.pad(batch_outputs, padding=padding_strategy.value, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, padding_side=padding_side, return_attention_mask=return_attention_mask)\n batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)\n return batch_outputs", "docstring": "Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It\nadds special tokens, truncates sequences if overflowing while taking into account the special tokens and\nmanages a moving window (with user defined stride) for overflowing tokens\n\n\nArgs:\nbatch_ids_pairs: list of tokenized input ids or input ids pairs\nbatch_entity_ids_pairs: list of entity ids or entity ids pairs\nbatch_entity_token_spans_pairs: list of entity spans or entity spans pairs\nmax_entity_length: The maximum length of the entity sequence.", "source": "github-repos"}
540{"code": "def _html_tree_view_config(cls) -> Dict[str, Any]:\n return {}", "docstring": "Returns the config (rendering arguments) of current extension.\n\nReturns:\nA dictionary of rendering arguments for the subtree. These arguments\nwill override the arguments passed to `view.render()`. See the\n`render()` method for the full list of arguments.", "source": "github-repos"}
541{"code": "def bind(self, extension: Extension) -> 'DictMentor':\n if (not Extension.is_valid_extension(extension)):\n raise ValueError('Cannot bind extension due to missing interface requirements')\n self._extensions.append(extension)\n return self", "docstring": "Add any predefined or custom extension.\n\nArgs:\nextension: Extension to add to the processor.\n\nReturns:\nThe DictMentor itself for chaining.", "source": "codesearchnet"}
542{"code": "def _CreateImage(media_service, opener, url):\n \n \n image_data = opener.open(url).read().decode('utf-8')\n image = {\n 'type': 'IMAGE',\n 'data': image_data,\n 'xsi_type': 'Image'\n }\n\n return media_service.upload(image)[0]", "docstring": "Creates an image and uploads it to the server.\n\nArgs:\nmedia_service: a SudsServiceProxy instance for AdWords's MediaService.\nopener: an OpenerDirector instance.\nurl: a str URL used to load image data.\n\nReturns:\nThe image that was successfully uploaded.", "source": "juraj-google-style"}
543{"code": "def check(self):\n errors = []\n results = []\n for fn in self._files:\n if (not os.path.isdir(fn)):\n try:\n with open(fn, 'r') as f:\n line_ct = 1\n for line in f:\n for word in split_words(line):\n if ((word in self._misspelling_dict) or (word.lower() in self._misspelling_dict)):\n results.append([fn, line_ct, word])\n line_ct += 1\n except UnicodeDecodeError:\n pass\n except IOError:\n errors.append(('%s' % sys.exc_info()[1]))\n return (errors, results)", "docstring": "Checks the files for misspellings.\n\nReturns:\n(errors, results)\nerrors: List of system errors, usually file access errors.\nresults: List of spelling errors - each tuple is filename,\nline number and misspelled word.", "source": "codesearchnet"}
544{"code": "def get_residue_annotations(self, seq_resnum, seqprop=None, structprop=None, chain_id=None, use_representatives=False):\n if use_representatives:\n if (seqprop and structprop and chain_id):\n raise ValueError('Overriding sequence, structure, and chain IDs with representatives. Set use_representatives to False if custom IDs are to be used.')\n elif ((not seqprop) or (not structprop) or (not chain_id)):\n raise ValueError('Input sequence, structure, and chain to map between, or set use_representatives to True.')\n if use_representatives:\n seqprop = self.representative_sequence\n structprop = self.representative_structure\n chain_id = self.representative_chain\n f = SeqFeature(FeatureLocation((seq_resnum - 1), seq_resnum))\n seq_features = f.extract(seqprop)\n all_info = ssbio.utils.clean_single_dict(indict=seq_features.letter_annotations, prepend_to_keys='seq_', remove_keys_containing='_chain_index')\n all_info['seq_resnum'] = seq_resnum\n all_info['seq_residue'] = str(seq_features.seq)\n if structprop:\n chain = structprop.chains.get_by_id(chain_id)\n mapping_to_structure_resnum = self.map_seqprop_resnums_to_structprop_resnums(resnums=seq_resnum, seqprop=seqprop, structprop=structprop, chain_id=chain_id, use_representatives=use_representatives)\n if (f.location.end.position in mapping_to_structure_resnum):\n struct_resnum = mapping_to_structure_resnum[f.location.end.position]\n struct_f = SeqFeature(FeatureLocation((struct_resnum - 1), struct_resnum))\n struct_seq_features = struct_f.extract(chain.seq_record)\n struct_info = ssbio.utils.clean_single_dict(indict=struct_seq_features.letter_annotations, prepend_to_keys='struct_', remove_keys_containing='structure_resnums')\n struct_info['struct_resnum'] = struct_resnum\n struct_info['struct_residue'] = str(struct_seq_features.seq)\n all_info.update(struct_info)\n if (seq_features.seq != struct_seq_features.seq):\n log.warning('Sequence residue ({}{}) does not match structure residue ({}{}). This may simply be due to differences in the structure'.format(seq_features.seq, seq_resnum, struct_seq_features.seq, struct_resnum))\n return all_info", "docstring": "Get all residue-level annotations stored in the SeqProp ``letter_annotations`` field for a given residue number.\n\nUses the representative sequence, structure, and chain ID stored by default. If other properties from other\nstructures are desired, input the proper IDs. An alignment for the given sequence to the structure must\nbe present in the sequence_alignments list.\n\nArgs:\nseq_resnum (int): Residue number in the sequence\nseqprop (SeqProp): SeqProp object\nstructprop (StructProp): StructProp object\nchain_id (str): ID of the structure's chain to get annotation from\nuse_representatives (bool): If the representative sequence/structure/chain IDs should be used\n\nReturns:\ndict: All available letter_annotations for this residue number", "source": "codesearchnet"}
545{"code": "def update_panel(store, panel_name, csv_lines, option):\n \n new_genes= []\n panel_obj = store.gene_panel(panel_name)\n if panel_obj is None:\n return None\n try:\n new_genes = parse_genes(csv_lines) \n except SyntaxError as error:\n flash(error.args[0], 'danger')\n return None\n\n \n if option == 'replace':\n \n for gene in panel_obj['genes']:\n \n gene['hgnc_symbol'] = gene['symbol']\n store.add_pending(panel_obj, gene, action='delete', info=None)\n\n for new_gene in new_genes:\n if not new_gene['hgnc_id']:\n flash(\"gene missing hgnc id: {}\".format(new_gene['hgnc_symbol']),'danger')\n continue\n gene_obj = store.hgnc_gene(new_gene['hgnc_id'])\n if gene_obj is None:\n flash(\"gene not found: {} - {}\".format(new_gene['hgnc_id'], new_gene['hgnc_symbol']),'danger')\n continue\n if new_gene['hgnc_symbol'] and gene_obj['hgnc_symbol'] != new_gene['hgnc_symbol']:\n flash(\"symbol mis-match: {0} | {1}\".format(\n gene_obj['hgnc_symbol'], new_gene['hgnc_symbol']), 'warning')\n\n info_data = {\n 'disease_associated_transcripts': new_gene['transcripts'],\n 'reduced_penetrance': new_gene['reduced_penetrance'],\n 'mosaicism': new_gene['mosaicism'],\n 'inheritance_models': new_gene['inheritance_models'],\n 'database_entry_version': new_gene['database_entry_version'],\n }\n if option == 'replace': \n action = 'add'\n else: \n existing_genes = {gene['hgnc_id'] for gene in panel_obj['genes']}\n action = 'edit' if gene_obj['hgnc_id'] in existing_genes else 'add'\n store.add_pending(panel_obj, gene_obj, action=action, info=info_data)\n\n return panel_obj", "docstring": "Update an existing gene panel with genes.\n\nArgs:\nstore(scout.adapter.MongoAdapter)\npanel_name(str)\ncsv_lines(iterable(str)): Stream with genes\noption(str): 'add' or 'replace'\n\nReturns:\npanel_obj(dict)", "source": "juraj-google-style"}
546{"code": "def SetIndexName(self, index_name):\n self._index_name = index_name\n logger.debug('Elasticsearch index name: {0:s}'.format(index_name))", "docstring": "Set the index name.\n\nArgs:\nindex_name (str): name of the index.", "source": "codesearchnet"}
547{"code": "class Reshape(Layer):\n\n def __init__(self, target_shape, **kwargs):\n super().__init__(**kwargs)\n self.target_shape = tuple(target_shape)\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], *operation_utils.compute_reshape_output_shape(input_shape[1:], self.target_shape, 'target_shape'))\n\n def compute_output_spec(self, inputs):\n output_shape = self.compute_output_shape(inputs.shape)\n return KerasTensor(shape=output_shape, dtype=inputs.dtype, sparse=inputs.sparse)\n\n def build(self, input_shape):\n sample_output_shape = operation_utils.compute_reshape_output_shape(input_shape[1:], self.target_shape, 'target_shape')\n self._resolved_target_shape = tuple((-1 if d is None else d for d in sample_output_shape))\n\n def call(self, inputs):\n return ops.reshape(inputs, (ops.shape(inputs)[0],) + self._resolved_target_shape)\n\n def get_config(self):\n config = {'target_shape': self.target_shape}\n base_config = super().get_config()\n return {**base_config, **config}", "docstring": "Layer that reshapes inputs into the given shape.\n\nArgs:\ntarget_shape: Target shape. Tuple of integers, does not include the\nsamples dimension (batch size).\n\nInput shape:\nArbitrary, although all dimensions in the input shape must be\nknown/fixed. Use the keyword argument `input_shape` (tuple of integers,\ndoes not include the samples/batch size axis) when using this layer as\nthe first layer in a model.\n\nOutput shape:\n`(batch_size, *target_shape)`\n\nExample:\n\n>>> x = keras.Input(shape=(12,))\n>>> y = keras.layers.Reshape((3, 4))(x)\n>>> y.shape\n(None, 3, 4)\n\n>>> # also supports shape inference using `-1` as dimension\n>>> y = keras.layers.Reshape((-1, 2, 2))(x)\n>>> y.shape\n(None, 3, 2, 2)", "source": "github-repos"}
548{"code": "def delete(self, file_path, branch, commit_message, **kwargs):\n \n path = '%s/%s' % (self.path, file_path.replace('/', '%2F'))\n data = {'branch': branch, 'commit_message': commit_message}\n self.gitlab.http_delete(path, query_data=data, **kwargs)", "docstring": "Delete a file on the server.\n\nArgs:\nfile_path (str): Path of the file to remove\nbranch (str): Branch from which the file will be removed\ncommit_message (str): Commit message for the deletion\n**kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\nGitlabAuthenticationError: If authentication is not correct\nGitlabDeleteError: If the server cannot perform the request", "source": "juraj-google-style"}
549{"code": "def set_package_releases(self, project_name, versions):\n self.packages[project_name] = sorted(versions, reverse=True)", "docstring": "Storage package information in ``self.packages``\n\nArgs:\nproject_name (str): This will be used as a the key in the\ndictionary.\nversions (list): List of ``str`` representing the available\nversions of a project.", "source": "codesearchnet"}
550{"code": "def l2_normalize(x, axis=None):\n return nn.l2_normalize(x, axis=axis)", "docstring": "Normalizes a tensor wrt the L2 norm alongside the specified axis.\n\nArgs:\nx: Tensor or variable.\naxis: axis along which to perform normalization.\n\nReturns:\nA tensor.", "source": "github-repos"}
551{"code": "def set_control_scheme(self, index):\n \n self._current_control_scheme = index % self._num_control_schemes\n self._control_scheme_buffer[0] = self._current_control_scheme", "docstring": "Sets the control scheme for the agent. See :obj:`ControlSchemes`.\n\nArgs:\nindex (int): The control scheme to use. Should be set with an enum from :obj:`ControlSchemes`.", "source": "juraj-google-style"}
552{"code": "def get(self, key):\n \n self._create_file_if_none_exists()\n with open(self.filename, 'rb') as file_object:\n cache_pickle = pickle.load(file_object)\n val = cache_pickle.get(key, None)\n return val", "docstring": "Gets a value by a key.\n\nArgs:\nkey (str): Key to retrieve the value.\n\nReturns: Retrieved value.", "source": "juraj-google-style"}
553{"code": "def show(self, displayAll = False):\n\t\t\n\t\tfrom pprint import pprint\n\t\tif displayAll:\n\t\t\tpprint(self.attributes)\n\t\telse:\n\t\t\tdisp_attr = {}\n\t\t\tfor key in self.disp_attr_keys:\n\t\t\t\ttry:\n\t\t\t\t\tdisp_attr[key] = self.attributes[key]\n\t\t\t\texcept KeyError:\n\t\t\t\t\tif key == 'lowercaseEmail':\n\t\t\t\t\t\tdisp_attr[key] = disp_attr['email'].lower()\n\t\t\t\t\telse:\n\t\t\t\t\t\tdisp_attr[key] = None\n\t\t\tpprint(disp_attr)\n\t\tdel pprint", "docstring": "Prints relevant attributes of an object\nArgs:\ndisplayAll\t\tif True displays ALL class attributes.", "source": "juraj-google-style"}
554{"code": "def find_and_replace_userids(self, text):\n \n\n match = True\n pattern = re.compile('<@([A-Z0-9]{9})>')\n while match:\n match = pattern.search(text)\n if match:\n name = self.get_user_display_name(match.group(1))\n text = re.sub(re.compile(match.group(0)), '@' + name, text)\n\n return text", "docstring": "Finds occurrences of Slack userids and attempts to replace them with\ndisplay names.\n\nArgs:\ntext (string): The message text\nReturns:\nstring: The message text with userids replaced.", "source": "juraj-google-style"}
555{"code": "def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:\n \n df = pd.DataFrame(index=table.index)\n\n for column in self.columns:\n df = column.update_dataframe(df, table=table, validate=validate)\n\n return df", "docstring": "Return a fully recoded dataframe.\n\nArgs:\ntable (pd.DataFrame): A dataframe on which to apply recoding logic.\nvalidate (bool): If ``True``, recoded table must pass validation tests.", "source": "juraj-google-style"}
556{"code": "def ResetConsoleAttr(encoding=None):\n return GetConsoleAttr(encoding=encoding, reset=True)", "docstring": "Resets the console attribute state to the console default.\n\nArgs:\nencoding: Reset to this encoding instead of the default.\nascii -- ASCII. This is the default.\nutf8 -- UTF-8 unicode.\nwin -- Windows code page 437.\n\nReturns:\nThe global ConsoleAttr state object.", "source": "github-repos"}
557{"code": "def match_files(self, file_metas: List[FileMetadata], pattern: str) -> Iterator[FileMetadata]:\n re_pattern = re.compile(self.translate_pattern(pattern))\n match = re_pattern.match\n for file_metadata in file_metas:\n if match(file_metadata.path):\n yield file_metadata", "docstring": "Filter :class:`FileMetadata` objects by *pattern*\n\nArgs:\nfile_metas (list of :class:`FileMetadata`):\nFiles to consider when matching\npattern (str): File pattern\n\nSee Also:\n:meth:`translate_pattern`\n\nReturns:\nGenerator of matching :class:`FileMetadata`", "source": "github-repos"}
558{"code": "def __init__(self, output, start_height, end_height):\n \n self.Output = output\n self.StartHeight = start_height\n self.EndHeight = end_height", "docstring": "Create instance.\n\nArgs:\noutput (int): the index of the previous output.\nstart_height (int): start block number.\nend_height (int): end block number.", "source": "juraj-google-style"}
559{"code": "def xcompile(source_code, args=0, optimize=True):\n code = crianza.compile(crianza.parse(source_code), optimize=optimize)\n return crianza.native.compile(code, args=args)", "docstring": "Parses Crianza source code and returns a native Python function.\n\nArgs:\nargs: The resulting function's number of input parameters.\n\nReturns:\nA callable Python function.", "source": "codesearchnet"}
560{"code": "def load(self):\n df = pd.read_csv(self.input_file, sep=',', quotechar='\"', encoding='utf-8', dtype=object)\n df = df[['NUTS-Code', 'Description']]\n df.columns = ['key', 'name']\n df = df[(df['key'].str.len() == 4)]\n df = df[(df['key'].str[2:] != 'ZZ')]\n return df", "docstring": "Load data, from default location\n\nReturns:\npandas.DataFrame: columns 'key' (NUTS2 code), 'name'", "source": "codesearchnet"}
561{"code": "def solve_for_fermi_energy(self, temperature, chemical_potentials, bulk_dos):\n \n\n fdos = FermiDos(bulk_dos, bandgap=self.band_gap)\n\n def _get_total_q(ef):\n\n qd_tot = sum([\n d['charge'] * d['conc']\n for d in self.defect_concentrations(\n chemical_potentials=chemical_potentials, temperature=temperature, fermi_level=ef)\n ])\n qd_tot += fdos.get_doping(fermi=ef + self.vbm, T=temperature)\n return qd_tot\n\n return bisect(_get_total_q, -1., self.band_gap + 1.)", "docstring": "Solve for the Fermi energy self-consistently as a function of T\nand p_O2\nObservations are Defect concentrations, electron and hole conc\nArgs:\nbulk_dos: bulk system dos (pymatgen Dos object)\ngap: Can be used to specify experimental gap.\nWill be useful if the self consistent Fermi level\nis > DFT gap\nReturns:\nFermi energy", "source": "juraj-google-style"}
562{"code": "def _FormatReturnOrExitToken(self, token_data):\n \n error_string = bsmtoken.BSM_ERRORS.get(token_data.status, 'UNKNOWN')\n return {\n 'error': error_string,\n 'token_status': token_data.status,\n 'call_status': token_data.return_value}", "docstring": "Formats a return or exit token as a dictionary of values.\n\nArgs:\ntoken_data (bsm_token_data_exit|bsm_token_data_return32|\nbsm_token_data_return64): AUT_EXIT, AUT_RETURN32 or\nAUT_RETURN64 token data.\n\nReturns:\ndict[str, str]: token values.", "source": "juraj-google-style"}
563{"code": "def process(self, rpc_executor, mark_streamer=None):\n if (self.func is None):\n raise ProcessingFunctionError('No processing function set for node', stream=self.stream)\n results = self.func(*[x[0] for x in self.inputs], rpc_executor=rpc_executor, mark_streamer=mark_streamer)\n if (results is None):\n results = []\n return results", "docstring": "Run this node's processing function.\n\nArgs:\nrpc_executor (RPCExecutor): An object capable of executing RPCs\nin case we need to do that.\nmark_streamer (callable): Function that can be called to manually\nmark a streamer as triggered by index.\n\nReturns:\nlist(IOTileReading): A list of IOTileReadings with the results of\nthe processing function or an empty list if no results were\nproduced", "source": "codesearchnet"}
564{"code": "def run(self, group_x=1, group_y=1, group_z=1) -> None:\n return self.mglo.run(group_x, group_y, group_z)", "docstring": "Run the compute shader.\n\nArgs:\ngroup_x (int): The number of work groups to be launched in the X dimension.\ngroup_y (int): The number of work groups to be launched in the Y dimension.\ngroup_z (int): The number of work groups to be launched in the Z dimension.", "source": "codesearchnet"}
565{"code": "def remove(self, *l):\n for a in flatten(l):\n self._remove([self.Inner(a)], self.l)", "docstring": "remove inner from outer\n\nArgs:\n*l element that is passes into Inner init", "source": "codesearchnet"}
566{"code": "def __add_action(self, relative_directory, action):\n \n generator_action_container = self.__actions.retrieve_element_or_default(relative_directory, None)\n\n if generator_action_container is None:\n generator_action_container = GeneratorActionContainer()\n generator_action_container.add_generator_action(action)\n self.__actions.add_element(location=relative_directory, element=generator_action_container)\n else:\n generator_action_container.add_generator_action(action)", "docstring": "Add action into the dictionary of actions.\n\nArgs:\nrelative_directory:\naction:", "source": "juraj-google-style"}
567{"code": "def find_test_functions(tree: ast.AST, skip_noqa: bool = False) -> List[ast.FunctionDef]:\n \n function_finder = TestFuncLister(skip_noqa)\n function_finder.visit(tree)\n return function_finder.get_found_funcs()", "docstring": "Collect functions that look like tests.\n\nArgs:\ntree\nskip_noqa: Flag used by command line debugger to skip functions that\nare marked with \"# noqa\". Defaults to ``False``.", "source": "juraj-google-style"}
568{"code": "def _FormatMessage(template, parameters):\n \n def GetParameter(m):\n try:\n return parameters[int(m.group(0)[1:])]\n except IndexError:\n return INVALID_EXPRESSION_INDEX\n\n parts = template.split('$$')\n return '$'.join(re.sub(r'\\$\\d+', GetParameter, part) for part in parts)", "docstring": "Formats the message. Unescapes '$$' with '$'.\n\nArgs:\ntemplate: message template (e.g. 'a = $0, b = $1').\nparameters: substitution parameters for the format.\n\nReturns:\nFormatted message with parameters embedded in template placeholders.", "source": "juraj-google-style"}
569{"code": "def get_package_for_module(module):\n \n if isinstance(module, six.string_types):\n try:\n module = sys.modules[module]\n except KeyError:\n return None\n\n try:\n return six.text_type(module.package)\n except AttributeError:\n if module.__name__ == '__main__':\n try:\n file_name = module.__file__\n except AttributeError:\n pass\n else:\n base_name = os.path.basename(file_name)\n split_name = os.path.splitext(base_name)\n if len(split_name) == 1:\n return six.text_type(base_name)\n return u'.'.join(split_name[:-1])\n\n return six.text_type(module.__name__)", "docstring": "Get package name for a module.\n\nHelper calculates the package name of a module.\n\nArgs:\nmodule: Module to get name for. If module is a string, try to find\nmodule in sys.modules.\n\nReturns:\nIf module contains 'package' attribute, uses that as package name.\nElse, if module is not the '__main__' module, the module __name__.\nElse, the base name of the module file name. Else None.", "source": "juraj-google-style"}
570{"code": "def mkdir_interactive(dirpath):\n \n from benchbuild.utils.cmd import mkdir\n if os.path.exists(dirpath):\n return\n\n response = ui.ask(\n \"The directory {dirname} does not exist yet. \"\n \"Should I create it?\".format(dirname=dirpath),\n default_answer=True,\n default_answer_str=\"yes\")\n\n if response:\n mkdir(\"-p\", dirpath)\n print(\"Created directory {0}.\".format(dirpath))", "docstring": "Create a directory if required.\n\nThis will query the user for a confirmation.\n\nArgs:\ndirname: The path to create.", "source": "juraj-google-style"}
571{"code": "def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:\n if token_ids_1 is None:\n return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]\n cls = [self.cls_token_id]\n sep = [self.sep_token_id]\n return cls + token_ids_0 + sep + token_ids_1 + sep", "docstring": "Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and\nadding special tokens. A BERT sequence has the following format:\n\n- single sequence: `[CLS] X [SEP]`\n- pair of sequences: `[CLS] A [SEP] B [SEP]`\n\nArgs:\ntoken_ids_0 (`List[int]`):\nList of IDs to which the special tokens will be added.\ntoken_ids_1 (`List[int]`, *optional*):\nOptional second list of IDs for sequence pairs.\n\nReturns:\n`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.", "source": "github-repos"}
572{"code": "def __process_instr(self, instr, avoid, next_addr, initial_state, execution_state, trace_current):\n if (instr.mnemonic == ReilMnemonic.JCC):\n not_taken_addr = next_addr\n (address, index) = split_address(instr.address)\n logger.debug('[+] Processing branch: {:\n if isinstance(instr.operands[0], ReilRegisterOperand):\n next_ip = self.__process_branch_cond(instr, avoid, initial_state, execution_state, trace_current, not_taken_addr)\n else:\n next_ip = self.__process_branch_uncond(instr, trace_current, not_taken_addr)\n else:\n trace_current += [(instr, None)]\n self.__cpu.execute(instr)\n next_ip = next_addr\n return next_ip", "docstring": "Process a REIL instruction.\n\nArgs:\ninstr (ReilInstruction): Instruction to process.\navoid (list): List of addresses to avoid while executing the code.\nnext_addr (int): Address of the following instruction.\ninitial_state (State): Initial execution state.\nexecution_state (Queue): Queue of execution states.\ntrace_current (list): Current trace.\n\nReturns:\nint: Returns the next address to execute.", "source": "codesearchnet"}
573{"code": "def _GetSources(self, event_object):\n \n try:\n source_short, source_long = (\n formatters_manager.FormattersManager.GetSourceStrings(event_object))\n except KeyError as exception:\n logging.warning(\n 'Unable to correctly assemble event with error: {0!s}'.format(\n exception))\n\n return source_short, source_long", "docstring": "Returns properly formatted source strings.\n\nArgs:\nevent_object: the event object (instance od EventObject).", "source": "juraj-google-style"}
574{"code": "def bespoke_md5(self, md5):\n r = requests.post('http:\n self._output(r.text)", "docstring": "Performs Bespoke MD5 lookup on an MD5.\n\nArgs:\nmd5 - A hash.", "source": "codesearchnet"}
575{"code": "def map_vals(func, dict_):\n if (not hasattr(func, '__call__')):\n func = func.__getitem__\n keyval_list = [(key, func(val)) for (key, val) in six.iteritems(dict_)]\n dictclass = (OrderedDict if isinstance(dict_, OrderedDict) else dict)\n newdict = dictclass(keyval_list)\n return newdict", "docstring": "applies a function to each of the keys in a dictionary\n\nArgs:\nfunc (callable): a function or indexable object\ndict_ (dict): a dictionary\n\nReturns:\nnewdict: transformed dictionary\n\nCommandLine:\npython -m ubelt.util_dict map_vals\n\nExample:\n>>> import ubelt as ub\n>>> dict_ = {'a': [1, 2, 3], 'b': []}\n>>> func = len\n>>> newdict = ub.map_vals(func, dict_)\n>>> assert newdict == {'a': 3, 'b': 0}\n>>> print(newdict)\n>>> # Can also use indexables as `func`\n>>> dict_ = {'a': 0, 'b': 1}\n>>> func = [42, 21]\n>>> newdict = ub.map_vals(func, dict_)\n>>> assert newdict == {'a': 42, 'b': 21}\n>>> print(newdict)", "source": "codesearchnet"}
576{"code": "def SetSerializersProfiler(self, serializers_profiler):\n self._serializers_profiler = serializers_profiler\n if self._storage_file:\n self._storage_file.SetSerializersProfiler(serializers_profiler)", "docstring": "Sets the serializers profiler.\n\nArgs:\nserializers_profiler (SerializersProfiler): serializers profiler.", "source": "codesearchnet"}
577{"code": "def tanh(x):\n if any_symbolic_tensors((x,)):\n return Tanh().symbolic_call(x)\n return backend.numpy.tanh(x)", "docstring": "Hyperbolic tangent, element-wise.\n\nArguments:\nx: Input tensor.\n\nReturns:\nOutput tensor of same shape as `x`.", "source": "github-repos"}
578{"code": "def __init__(self, sync_frequency=1, update_weight=1.0, scope='synchronization', summary_labels=()):\n \n assert isinstance(sync_frequency, int) and sync_frequency > 0\n self.sync_frequency = sync_frequency\n\n assert isinstance(update_weight, float) and update_weight > 0.0\n self.update_weight = update_weight\n\n super(Synchronization, self).__init__(scope=scope, summary_labels=summary_labels)", "docstring": "Creates a new synchronization optimizer instance.\n\nArgs:\nsync_frequency: The interval between optimization calls actually performing a\nsynchronization step.\nupdate_weight: The update weight, 1.0 meaning a full assignment of the source\nvariables values.", "source": "juraj-google-style"}
579{"code": "def create_card(self, card_json):\n return trolly.card.Card(trello_client=self, card_id=card_json['id'], name=card_json['name'], data=card_json)", "docstring": "Create a Card object from JSON object\n\nReturns:\nCard: The card from the given `card_json`.", "source": "codesearchnet"}
580{"code": "def write_gtiff_file(f_name, n_rows, n_cols, data, geotransform, srs, nodata_value, gdal_type=GDT_Float32):\n UtilClass.mkdir(os.path.dirname(FileClass.get_file_fullpath(f_name)))\n driver = gdal_GetDriverByName(str('GTiff'))\n try:\n ds = driver.Create(f_name, n_cols, n_rows, 1, gdal_type)\n except Exception:\n print(('Cannot create output file %s' % f_name))\n return\n ds.SetGeoTransform(geotransform)\n try:\n ds.SetProjection(srs.ExportToWkt())\n except (AttributeError or Exception):\n ds.SetProjection(srs)\n ds.GetRasterBand(1).SetNoDataValue(nodata_value)\n if (isinstance(data, numpy.ndarray) and (data.dtype in [numpy.dtype('int'), numpy.dtype('float')])):\n data = numpy.where(numpy.isnan(data), nodata_value, data)\n ds.GetRasterBand(1).WriteArray(data)\n ds = None", "docstring": "Output Raster to GeoTiff format file.\n\nArgs:\nf_name: output gtiff file name.\nn_rows: Row count.\nn_cols: Col count.\ndata: 2D array data.\ngeotransform: geographic transformation.\nsrs: coordinate system.\nnodata_value: nodata value.\ngdal_type (:obj:`pygeoc.raster.GDALDataType`): output raster data type,\nGDT_Float32 as default.", "source": "codesearchnet"}
581{"code": "def __init__(self, datastore_client):\n \n super(AversarialBatches, self).__init__(\n datastore_client=datastore_client,\n entity_kind_batches=KIND_ADVERSARIAL_BATCH,\n entity_kind_images=KIND_ADVERSARIAL_IMAGE)", "docstring": "Initializes AversarialBatches.\n\nArgs:\ndatastore_client: instance of CompetitionDatastoreClient", "source": "juraj-google-style"}
582{"code": "def has_mixture_channel(val: Any) -> bool:\n mixture_getter = getattr(val, '_has_mixture_', None)\n result = (NotImplemented if (mixture_getter is None) else mixture_getter())\n if (result is not NotImplemented):\n return result\n result = has_unitary(val)\n if ((result is not NotImplemented) and result):\n return result\n return (mixture_channel(val, None) is not None)", "docstring": "Returns whether the value has a mixture channel representation.\n\nIn contrast to `has_mixture` this method falls back to checking whether\nthe value has a unitary representation via `has_channel`.\n\nReturns:\nIf `val` has a `_has_mixture_` method and its result is not\nNotImplemented, that result is returned. Otherwise, if `val` has a\n`_has_unitary_` method and its results is not NotImplemented, that\nresult is returned. Otherwise, if the value has a `_mixture_` method\nthat is not a non-default value, True is returned. Returns False if none\nof these functions.", "source": "codesearchnet"}
583{"code": "def __init__(self, *value):\n \n tag = self.__class__.__name__.replace('Single', '').lower()\n super().__init__(tag, value)", "docstring": "init\n\nset self.tag to classname. e.g.::\n\nArraySingle.tag -> 'array'\n\nArgs:\n*value: the elements you want to put into single's value(list), can be one element or several seperate by comma, or put into a list or combination of those. *value will be flattend to a single one deminision list. In subclasses' init, raw data should be converted to single if needed according to specific subclass.", "source": "juraj-google-style"}
584{"code": "def check_loss_and_target_compatibility(targets, loss_fns, output_shapes):\n key_loss_fns = {losses.mean_squared_error, losses.binary_crossentropy, losses.categorical_crossentropy}\n key_loss_classes = (losses.MeanSquaredError, losses.BinaryCrossentropy, losses.CategoricalCrossentropy)\n for y, loss, shape in zip(targets, loss_fns, output_shapes):\n if y is None or loss is None or tensor_util.is_tf_type(y):\n continue\n if losses.is_categorical_crossentropy(loss):\n if y.shape[-1] == 1:\n raise ValueError('You are passing a target array of shape ' + str(y.shape) + ' while using as loss `categorical_crossentropy`. `categorical_crossentropy` expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:\\n```\\nfrom keras.utils import to_categorical\\ny_binary = to_categorical(y_int)\\n```\\n\\nAlternatively, you can use the loss function `sparse_categorical_crossentropy` instead, which does expect integer targets.')\n is_loss_wrapper = isinstance(loss, losses.LossFunctionWrapper)\n if isinstance(loss, key_loss_classes) or (is_loss_wrapper and loss.fn in key_loss_fns):\n for target_dim, out_dim in zip(y.shape[1:], shape[1:]):\n if out_dim is not None and target_dim != out_dim:\n loss_name = loss.name\n if loss_name is None:\n loss_type = loss.fn if is_loss_wrapper else type(loss)\n loss_name = loss_type.__name__\n raise ValueError('A target array with shape ' + str(y.shape) + ' was passed for an output of shape ' + str(shape) + ' while using as loss `' + loss_name + '`. This loss expects targets to have the same shape as the output.')", "docstring": "Does validation on the compatibility of targets and loss functions.\n\nThis helps prevent users from using loss functions incorrectly. This check\nis purely for UX purposes.\n\nArgs:\ntargets: list of Numpy arrays of targets.\nloss_fns: list of loss functions.\noutput_shapes: list of shapes of model outputs.\n\nRaises:\nValueError: if a loss function or target array\nis incompatible with an output.", "source": "github-repos"}
585{"code": "def check_hardware(self, expected):\n \n\n if len(expected) < 10:\n expected += '\\0'*(10 - len(expected))\n\n err, = self.rpc(0x00, 0x03, expected, result_format=\"L\")\n if err == 0:\n return True\n\n return False", "docstring": "Make sure the hardware version is what we expect.\n\nThis convenience function is meant for ensuring that we are talking to\na tile that has the correct hardware version.\n\nArgs:\nexpected (str): The expected hardware string that is compared\nagainst what is reported by the hardware_version RPC.\n\nReturns:\nbool: true if the hardware is the expected version, false otherwise", "source": "juraj-google-style"}
586{"code": "def wake_up(func):\n\n @wraps(func)\n def wrapped(*args, **kwargs):\n\n def valid_result(result):\n \"Check if TeslaAPI result succesful.\\n\\n Parameters\\n ----------\\n result : tesla API result\\n This is the result of a Tesla Rest API call.\\n\\n Returns\\n -------\\n bool\\n Tesla API failure can be checked in a dict with a bool in\\n ['response']['result'], a bool, or None or\\n ['response']['reason'] == 'could_not_wake_buses'\\n Returns true when a failure state not detected.\\n\\n \"\n try:\n return ((result is not None) and (result is not False) and ((result is True) or ((isinstance(result, dict) and isinstance(result['response'], dict) and (('result' in result['response']) and (result['response']['result'] is True))) or (('reason' in result['response']) and (result['response']['reason'] != 'could_not_wake_buses')) or ('result' not in result['response']))))\n except TypeError as exception:\n _LOGGER.error('Result: %s, %s', result, exception)\n retries = 0\n sleep_delay = 2\n inst = args[0]\n vehicle_id = args[1]\n result = None\n if ((vehicle_id is not None) and (vehicle_id in inst.car_online) and inst.car_online[vehicle_id]):\n try:\n result = func(*args, **kwargs)\n except TeslaException:\n pass\n if valid_result(result):\n return result\n _LOGGER.debug('wake_up needed for %s -> %s \\nInfo: args:%s, kwargs:%s, vehicle_id:%s, car_online:%s', func.__name__, result, args, kwargs, vehicle_id, inst.car_online)\n inst.car_online[vehicle_id] = False\n while (('wake_if_asleep' in kwargs) and kwargs['wake_if_asleep'] and ((vehicle_id is None) or ((vehicle_id is not None) and (vehicle_id in inst.car_online) and (not inst.car_online[vehicle_id])))):\n result = inst._wake_up(vehicle_id)\n _LOGGER.debug('%s(%s): Wake Attempt(%s): %s', func.__name__, vehicle_id, retries, result)\n if (not result):\n if (retries < 5):\n time.sleep((sleep_delay ** (retries + 2)))\n retries += 1\n continue\n else:\n inst.car_online[vehicle_id] = False\n raise RetryLimitError\n else:\n break\n retries = 0\n while True:\n try:\n result = func(*args, **kwargs)\n _LOGGER.debug('%s(%s): Retry Attempt(%s): %s', func.__name__, vehicle_id, retries, result)\n except TeslaException:\n pass\n finally:\n retries += 1\n time.sleep((sleep_delay ** (retries + 1)))\n if valid_result(result):\n return result\n if (retries >= 5):\n raise RetryLimitError\n return wrapped", "docstring": "Wrap a API f so it will attempt to wake the vehicle if asleep.\n\nThe command f is run once if the vehicle_id was last reported\nonline. Assuming f returns None and wake_if_asleep is True, 5 attempts\nwill be made to wake the vehicle to reissue the command. In addition,\nif there is a `could_not_wake_buses` error, it will retry the command\n\nArgs:\ninst (Controller): The instance of a controller\nvehicle_id (string): The vehicle to attempt to wake.\nTODO: This currently requires a vehicle_id, but update() does not; This\nshould also be updated to allow that case\nwake_if_asleep (bool): Keyword arg to force a vehicle awake. Must be\nset in the wrapped function f\nThrows:\nRetryLimitError", "source": "codesearchnet"}
587{"code": "def rematerialized_call(self, layer_call, *args, **kwargs):\n\n def compute_size(x):\n return math.prod([d or 1 for d in x.shape]) if isinstance(x, KerasTensor) else 0\n if self._remat_mode.mode == 'full':\n return remat.remat(layer_call)\n elif self._remat_mode.mode == 'list_of_layers' and self.name in self._remat_mode.layer_names:\n return remat.remat(layer_call)\n elif self._remat_mode.mode == 'larger_than':\n output_spec = self.compute_output_spec(*args, **kwargs)\n output_size = sum(tree.flatten(tree.map_structure(compute_size, output_spec)))\n if output_size and output_size > self._remat_mode.output_size_threshold:\n return remat.remat(layer_call)\n elif self._remat_mode.mode == 'activations':\n has_activation = hasattr(self, 'activation') and self.activation is not None\n if has_activation:\n\n @functools.wraps(layer_call)\n def rematerialized_activation_call_wrapper(*args, **kwargs):\n original_activation = self.activation\n self.activation = remat.remat(original_activation)\n try:\n return layer_call(*args, **kwargs)\n finally:\n self.activation = original_activation\n return rematerialized_activation_call_wrapper\n return layer_call", "docstring": "Enable rematerialization dynamically for layer's call method.\n\nArgs:\nlayer_call: The original `call` method of a layer.\n\nReturns:\nRematerialized layer's `call` method.", "source": "github-repos"}
588{"code": "def update_additional_charge(self, *, recurring_billing_id, description, plan_value, plan_tax, plan_tax_return_base,\n currency):\n \n payload = {\n \"description\": description,\n \"additionalValues\": [\n {\n \"name\": \"ITEM_VALUE\",\n \"value\": plan_value,\n \"currency\": currency\n },\n {\n \"name\": \"ITEM_TAX\",\n \"value\": plan_tax,\n \"currency\": currency\n },\n {\n \"name\": \"ITEM_TAX_RETURN_BASE\",\n \"value\": plan_tax_return_base,\n \"currency\": currency\n }\n ]\n }\n fmt = 'recurringBillItems/{}'.format(recurring_billing_id)\n return self.client._put(self.url + fmt, payload=payload, headers=self.get_headers())", "docstring": "Updates the information from an additional charge in an invoice.\n\nArgs:\nrecurring_billing_id: Identifier of the additional charge.\ndescription:\nplan_value:\nplan_tax:\nplan_tax_return_base:\ncurrency:\n\nReturns:", "source": "juraj-google-style"}
589{"code": "def cdnode(self, astr_path):\n \n\n \n \n l_absPath = []\n b_valid, l_absPath = self.b_pathInTree(astr_path)\n if b_valid:\n \n self.l_cwd = l_absPath[:]\n self.snode_current = self.snode_root\n self.sbranch_current = self.sbranch_root\n \n for node in l_absPath[1:]:\n self.snode_current = self.snode_current.d_nodes[node]\n self.sbranch_current.dict_branch = self.snode_current.snode_parent.d_nodes\n return {\"status\": True, \"path\": self.l_cwd}\n return {\"status\": False, \"path\": []}", "docstring": "Change working node to astr_path.\n\nThe path is converted to a list, split on '/'. By performing a 'cd'\nall parent and derived nodes need to be updated relative to\nnew location.\n\nArgs:\nastr_path (string): The path to cd to.\n\nReturns:\n{\"status\" : True/False , \"path\": l_cwd -- the path as list}", "source": "juraj-google-style"}
590{"code": "def with_options(self, options, name=None) -> 'DatasetV2':\n return _OptionsDataset(self, options, name=name)", "docstring": "Returns a new `tf.data.Dataset` with the given options set.\n\nThe options are \"global\" in the sense they apply to the entire dataset.\nIf options are set multiple times, they are merged as long as different\noptions do not use different non-default values.\n\n>>> ds = tf.data.Dataset.range(5)\n>>> ds = ds.interleave(lambda x: tf.data.Dataset.range(5),\n... cycle_length=3,\n... num_parallel_calls=3)\n>>> options = tf.data.Options()\n>>> # This will make the interleave order non-deterministic.\n>>> options.deterministic = False\n>>> ds = ds.with_options(options)\n\nArgs:\noptions: A `tf.data.Options` that identifies the options the use.\nname: (Optional.) A name for the tf.data operation.\n\nReturns:\nA new `Dataset` with the transformation applied as described above.\n\nRaises:\nValueError: when an option is set more than once to a non-default value", "source": "github-repos"}
591{"code": "def form_to_params(fn=None, return_json=True):\n \n def forms_to_params_decorator(fn):\n @handle_type_error\n @wraps(fn)\n def forms_to_params_wrapper(*args, **kwargs):\n kwargs.update(\n dict(request.forms)\n )\n\n if not return_json:\n return fn(*args, **kwargs)\n\n return encode_json_body(\n fn(*args, **kwargs)\n )\n\n return forms_to_params_wrapper\n\n if fn: \n return forms_to_params_decorator(fn)\n\n return forms_to_params_decorator", "docstring": "Convert bottle forms request to parameters for the wrapped function.\n\nArgs:\nreturn_json (bool, default True): Should the decorator automatically\nconvert returned value to JSON?", "source": "juraj-google-style"}
592{"code": "def request(\n self, main_type, sub_type, result_limit, result_start, owner=None, filters=None, params=None\n ):\n \n params = params or {}\n\n if owner:\n params['owner'] = owner\n if filters and filters.filters:\n params['filters'] = filters.filters_string\n params['resultLimit'] = result_limit or params.get('result_limit', self.result_limit)\n params['resultStart'] = result_start or params.get('result_start', 0)\n if not sub_type:\n url = '/v2/{}'.format(main_type)\n else:\n url = '/v2/{}/{}'.format(main_type, sub_type)\n\n return self.tcex.session.get(url, params=params)", "docstring": "Args:\nmain_type:\nsub_type:\nresult_limit:\nresult_start:\nowner:\nfilters:\nparams:\n\nReturn:", "source": "juraj-google-style"}
593{"code": "def assign(self, droplet_id):\n return self.get_data(('floating_ips/%s/actions/' % self.ip), type=POST, params={'type': 'assign', 'droplet_id': droplet_id})", "docstring": "Assign a FloatingIP to a Droplet.\n\nArgs:\ndroplet_id: int - droplet id", "source": "codesearchnet"}
594{"code": "def __main():\n \n if len(sys.argv) < 3:\n sys.stderr.write('usage: {0} <detail|list> <system|system+user>\\n'.format(sys.argv[0]))\n sys.exit(64)\n user_pkgs = False\n version_only = False\n if six.text_type(sys.argv[1]) == 'list':\n version_only = True\n if six.text_type(sys.argv[2]) == 'system+user':\n user_pkgs = True\n import salt.utils.json\n import timeit\n\n def run():\n \n pkg_list = WinSoftware(user_pkgs=user_pkgs, version_only=version_only)\n print(salt.utils.json.dumps(pkg_list.data, sort_keys=True, indent=4)) \n print('Total: {}'.format(len(pkg_list))) \n\n print('Time Taken: {}'.format(timeit.timeit(run, number=1)))", "docstring": "This module can also be run directly for testing\nArgs:\ndetail|list : Provide ``detail`` or version ``list``.\nsystem|system+user: System installed and System and User installs.", "source": "juraj-google-style"}
595{"code": "def diffuse_horizontal_illuminance(self, value=999999.0):\n if (value is not None):\n try:\n value = float(value)\n except ValueError:\n raise ValueError('value {} need to be of type float for field `diffuse_horizontal_illuminance`'.format(value))\n if (value < 0.0):\n raise ValueError('value need to be greater or equal 0.0 for field `diffuse_horizontal_illuminance`')\n self._diffuse_horizontal_illuminance = value", "docstring": "Corresponds to IDD Field `diffuse_horizontal_illuminance`\nwill be missing if >= 999900\n\nArgs:\nvalue (float): value for IDD Field `diffuse_horizontal_illuminance`\nUnit: lux\nvalue >= 0.0\nMissing value: 999999.0\nif `value` is None it will not be checked against the\nspecification and is assumed to be a missing value\n\nRaises:\nValueError: if `value` is not a valid value", "source": "codesearchnet"}
596{"code": "def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':\n if (not hasattr(self.noisy_moments, '_not_overridden')):\n return self.noisy_moments([ops.Moment([operation])], operation.qubits)\n if (not hasattr(self.noisy_moment, '_not_overridden')):\n return self.noisy_moment(ops.Moment([operation]), operation.qubits)\n assert False, 'Should be unreachable.'", "docstring": "Adds noise to an individual operation.\n\nArgs:\noperation: The operation to make noisy.\n\nReturns:\nAn OP_TREE corresponding to the noisy operations implementing the\nnoisy version of the given operation.", "source": "codesearchnet"}
597{"code": "def _is_subscribed_identity(tensor):\n if tensor.op.type != 'Identity':\n return False\n match = re.match('(?P<prefix_name>^.*?)/subscription/Identity[^/]+', tensor.name)\n if match is None or len(match.groups()) != 1:\n return False\n prefix_name = match.group('prefix_name')\n assert len(tensor.op.inputs) == 1, 'Op {} must only have one input'.format(tensor.op.name)\n source_tensor = tensor.op.inputs[0]\n if prefix_name != source_tensor.op.name:\n return False\n return True", "docstring": "Checks if the given tensor is an identity op returned by `subscribe()`.\n\nArgs:\ntensor: A `tf.Tensor` to check.\n\nReturns:\nTrue if the given tensor matches the criteria for subscription identities:\nits op type is `Identity`, its name matches the name of its input and\nconforms to the convention for subscribed nodes.\nFalse otherwise.", "source": "github-repos"}
598{"code": "def update(self, resource, timeout=(- 1)):\n return self._client.update(resource, timeout=timeout, default_values=self.DEFAULT_VALUES)", "docstring": "Updates only name for the Artifact Bundle.\n\nArgs:\nresource (dict): Object to update.\ntimeout:\nTimeout in seconds. Waits for task completion by default. The timeout does not abort the operation\nin OneView, it just stops waiting for its completion.\n\nReturns:\ndict: Updated resource.", "source": "codesearchnet"}
599{"code": "def get_matching_text(string_list, match_min_size=30, ignore='', end_characters='.!\\r\\n'):\n \n \n a = string_list[0]\n for i in range(1, len(string_list)):\n b = string_list[i]\n result = get_matching_text_in_strs(a, b, match_min_size=match_min_size, ignore=ignore,\n end_characters=end_characters)\n a = ''.join(result)\n return a", "docstring": "Returns a string containing matching blocks of text in a list of strings followed by non-matching.\n\nArgs:\nstring_list (List[str]): List of strings to match\nmatch_min_size (int): Minimum block size to match on. Defaults to 30.\nignore (str): Any characters to ignore in matching. Defaults to ''.\nend_characters (str): End characters to look for. Defaults to '.\\r\\n'.\n\nReturns:\nstr: String containing matching blocks of text followed by non-matching", "source": "juraj-google-style"}
600{"code": "def capture_insert_from_model(cls, table_name, record_id, *, exclude_fields=()):\n exclude_cols = ()\n if exclude_fields:\n model_cls = get_connected_model_for_table_name(table_name)\n exclude_cols = cls._fieldnames_to_colnames(model_cls, exclude_fields)\n raw_query = sql.SQL('\\n SELECT {schema}.hc_capture_insert_from_row(\\n hstore({schema}.{table_name}.*),\\n %(table_name)s,\\n ARRAY[{exclude_cols}]::text[] -- cast to type expected by stored procedure\\n ) AS id\\n FROM {schema}.{table_name}\\n WHERE id = %(record_id)s\\n ').format(schema=sql.Identifier(settings.HEROKU_CONNECT_SCHEMA), table_name=sql.Identifier(table_name), exclude_cols=sql.SQL(', ').join((sql.Identifier(col) for col in exclude_cols)))\n params = {'record_id': record_id, 'table_name': table_name}\n result_qs = TriggerLog.objects.raw(raw_query, params)\n return list(result_qs)", "docstring": "Create a fresh insert record from the current model state in the database.\n\nFor read-write connected models, this will lead to the attempted creation of a\ncorresponding object in Salesforce.\n\nArgs:\ntable_name (str): The name of the table backing the connected model (without schema)\nrecord_id (int): The primary id of the connected model\nexclude_fields (Iterable[str]): The names of fields that will not be included in the\nwrite record\n\nReturns:\nA list of the created TriggerLog entries (usually one).\n\nRaises:\nLookupError: if ``table_name`` does not belong to a connected model", "source": "codesearchnet"}
601{"code": "def __add__(self, other: Any) -> 'KeyPath':\n if other is None:\n return self\n if isinstance(other, str):\n other = KeyPath.parse(other)\n elif isinstance(other, KeyPathSet):\n other = other.copy()\n other.rebase(self)\n return other\n elif not isinstance(other, KeyPath):\n other = KeyPath(other)\n assert isinstance(other, KeyPath)\n return KeyPath(other.keys, self)", "docstring": "Concatenates a KeyPath equivalent object.\n\nArgs:\nother: Object to add, which can be None, int (as a 1-level KeyPath),\nstring (parsed as a KeyPath), a KeyPath object, or any other object as\na single key.\n\nReturns:\nNewly concatenated KeyPath.\n\nRaises:\nValueError: If other is a string that cannot be parsed into a KeyPath.", "source": "github-repos"}
602{"code": "def get(self, id):\n request_url = (self._client.base_api_url + self.detail_url.format(id=id))\n response = self._client.session.get(request_url)\n self.validate_request_success(response_text=response.text, request_url=request_url, status_code=response.status_code, expected_status_code=HTTP_200_OK)\n return self.response_data_to_model_instance(response.json())", "docstring": "Get the model instance with a given id.\n\nArgs:\nid (int or str): The primary identifier (e.g., pk or UUID)\nfor the task instance to get.\n\nReturns:\n:class:`saltant.models.resource.Model`:\nA :class:`saltant.models.resource.Model` subclass\ninstance representing the resource requested.", "source": "codesearchnet"}
603{"code": "def imatch_any(patterns, name):\n \n \n if not patterns:\n return True\n return any(imatch(pattern, name) for pattern in patterns)", "docstring": "Test if a name matches any of a list of patterns (case insensitive).\n\nWill return `True` if ``patterns`` is an empty list.\n\nArguments:\npatterns (list): A list of wildcard pattern, e.g ``[\"*.py\",\n\"*.pyc\"]``\nname (str): A filename.\n\nReturns:\nbool: `True` if the name matches at least one of the patterns.", "source": "juraj-google-style"}
604{"code": "def decode_event(self, log_topics, log_data):\n \n \n\n \n \n if not len(log_topics) or log_topics[0] not in self.event_data:\n raise ValueError('Unknown log type')\n\n event_id_ = log_topics[0]\n\n event = self.event_data[event_id_]\n\n \n \n \n \n unindexed_types = [\n type_\n for type_, indexed in zip(event['types'], event['indexed'])\n if not indexed\n ]\n unindexed_args = decode_abi(unindexed_types, log_data)\n\n \n \n indexed_count = 1 \n\n result = {}\n for name, type_, indexed in zip(\n event['names'], event['types'], event['indexed']):\n if indexed:\n topic_bytes = utils.zpad(\n utils.encode_int(log_topics[indexed_count]),\n 32,\n )\n indexed_count += 1\n value = decode_single(process_type(type_), topic_bytes)\n else:\n value = unindexed_args.pop(0)\n\n result[name] = value\n result['_event_type'] = utils.to_string(event['name'])\n\n return result", "docstring": "Return a dictionary representation the log.\n\nNote:\nThis function won't work with anonymous events.\n\nArgs:\nlog_topics (List[bin]): The log's indexed arguments.\nlog_data (bin): The encoded non-indexed arguments.", "source": "juraj-google-style"}
605{"code": "def _get_subcommand(name):\n \n \n _LOGGER.debug('Accessing subcommand \"%s\".', name)\n if name not in settings.subcommands:\n raise ValueError(\n '\"{subcommand}\" is not a {command} command. \\'{command} help -a\\' '\n 'lists all available subcommands.'.format(\n command=settings.command, subcommand=name)\n )\n return settings.subcommands[name]", "docstring": "Return the function for the specified subcommand.\n\nArgs:\nname: The name of a subcommand.\n\nReturns:\nThe loadable object from the entry point represented by the subcommand.", "source": "juraj-google-style"}
606{"code": "def GetDataByPath(self, path):\n \n _, path_data = self._paths.get(path, (None, None))\n return path_data", "docstring": "Retrieves the data associated to a path.\n\nArgs:\npath (str): path of the file entry.\n\nReturns:\nbytes: data or None if not available.", "source": "juraj-google-style"}
607{"code": "def dict2str(self, d: Dict, joiner: str) -> str:\n result = str()\n for key in d:\n result = ((result + str(key)) + ' : ')\n if isinstance(d[key], list):\n result = ((result + self.list2str(d[key], joiner)) + joiner)\n elif isinstance(d[key], dict):\n result = ((result + self.dict2str(d[key], joiner)) + joiner)\n elif d[key]:\n result = ((result + str(d[key])) + joiner)\n return result", "docstring": "Convert dict to str as input for tokenizer\n\nArgs:\nd (dict): dict for converting\njoiner (str): join the elements using this string to separate them.\n\nReturns: the value of the dict as a string", "source": "codesearchnet"}
608{"code": "def read_until(self, expected_commands, timeout):\n msg = timeouts.loop_until_timeout_or_valid(timeout, (lambda : self.read_message(timeout)), (lambda m: (m.command in expected_commands)), 0)\n if (msg.command not in expected_commands):\n raise usb_exceptions.AdbTimeoutError('Timed out establishing connection, waiting for: %s', expected_commands)\n return msg", "docstring": "Read AdbMessages from this transport until we get an expected command.\n\nThe ADB protocol specifies that before a successful CNXN handshake, any\nother packets must be ignored, so this method provides the ability to\nignore unwanted commands. It's primarily used during the initial\nconnection to the device. See Read() for more details, including more\nexceptions that may be raised.\n\nArgs:\nexpected_commands: Iterable of expected command responses, like\n('CNXN', 'AUTH').\ntimeout: timeouts.PolledTimeout object to use for timeout.\n\nReturns:\nThe ADB message received that matched one of expected_commands.\n\nRaises:\nAdbProtocolError: If timeout expires between reads, this can happen\nif we are getting spammed with unexpected commands.", "source": "codesearchnet"}
609{"code": "def forall(self, vars_list: List[str]) -> 'TensorFluent':\n \n return self._aggregation_op(tf.reduce_all, self, vars_list)", "docstring": "Returns the TensorFluent for the forall aggregation function.\n\nArgs:\nvars_list: The list of variables to be aggregated over.\n\nReturns:\nA TensorFluent wrapping the forall aggregation function.", "source": "juraj-google-style"}
610{"code": "def download_file(url, file_path, mkdir=False):\n \n folder, fname = os.path.split(file_path)\n return download_file_by_name(url, folder, fname, mkdir)", "docstring": "Write a string of data to file.\n\nArgs:\nurl: A string to a valid URL.\nfile_path: Full path to intended download location (e.g. c:/ladybug/testPts.pts)\nmkdir: Set to True to create the directory if doesn't exist (Default: False)", "source": "juraj-google-style"}
611{"code": "def preprocess_input(features, target, train_config, preprocess_output_dir, model_type):\n target_name = train_config['target_column']\n key_name = train_config['key_column']\n with tf.name_scope('numerical_feature_preprocess'):\n if train_config['numerical_columns']:\n numerical_analysis_file = os.path.join(preprocess_output_dir, NUMERICAL_ANALYSIS)\n if (not file_io.file_exists(numerical_analysis_file)):\n raise ValueError(('File %s not found in %s' % (NUMERICAL_ANALYSIS, preprocess_output_dir)))\n numerical_anlysis = json.loads(python_portable_string(file_io.read_file_to_string(numerical_analysis_file)))\n for name in train_config['numerical_columns']:\n if ((name == target_name) or (name == key_name)):\n continue\n transform_config = train_config['transforms'].get(name, {})\n transform_name = transform_config.get('transform', None)\n if (transform_name == 'scale'):\n value = float(transform_config.get('value', 1.0))\n features[name] = _scale_tensor(features[name], range_min=numerical_anlysis[name]['min'], range_max=numerical_anlysis[name]['max'], scale_min=(- value), scale_max=value)\n elif ((transform_name == 'identity') or (transform_name is None)):\n pass\n else:\n raise ValueError(('For numerical variables, only scale and identity are supported: Error for %s' % name))\n if (target is not None):\n with tf.name_scope('target_feature_preprocess'):\n if (target_name in train_config['categorical_columns']):\n labels = train_config['vocab_stats'][target_name]['labels']\n table = tf.contrib.lookup.string_to_index_table_from_tensor(labels)\n target = table.lookup(target)\n with tf.name_scope('categorical_feature_preprocess'):\n for name in train_config['categorical_columns']:\n if ((name == key_name) or (name == target_name)):\n continue\n transform_config = train_config['transforms'].get(name, {})\n transform_name = transform_config.get('transform', None)\n if is_dnn_model(model_type):\n if ((transform_name == 'embedding') or (transform_name == 'one_hot') or (transform_name is None)):\n map_vocab = True\n else:\n raise ValueError(('Unknown transform %s' % transform_name))\n elif is_linear_model(model_type):\n if ((transform_name == 'one_hot') or (transform_name is None)):\n map_vocab = True\n elif (transform_name == 'embedding'):\n map_vocab = False\n else:\n raise ValueError(('Unknown transform %s' % transform_name))\n if map_vocab:\n labels = train_config['vocab_stats'][name]['labels']\n table = tf.contrib.lookup.string_to_index_table_from_tensor(labels)\n features[name] = table.lookup(features[name])\n return (features, target)", "docstring": "Perform some transformations after reading in the input tensors.\n\nArgs:\nfeatures: dict of feature_name to tensor\ntarget: tensor\ntrain_config: our training config object\npreprocess_output_dir: folder should contain the vocab files.\nmodel_type: the tf model type.\n\nRaises:\nValueError: if wrong transforms are used\n\nReturns:\nNew features dict and new target tensor.", "source": "codesearchnet"}
612{"code": "def get_extension_by_name(cert_obj, extension_name):\n try:\n return cert_obj.extensions.get_extension_for_oid(getattr(cryptography.x509.oid.ExtensionOID, extension_name))\n except cryptography.x509.ExtensionNotFound:\n pass", "docstring": "Get a standard certificate extension by attribute name.\n\nArgs:\ncert_obj: cryptography.Certificate\nCertificate containing a standard extension.\n\nextension_name : str\nExtension name. E.g., 'SUBJECT_DIRECTORY_ATTRIBUTES'.\n\nReturns:\nCryptography.Extension", "source": "codesearchnet"}
613{"code": "def get_psd_product(self, vector, dtype=None):\n \n \n if dtype is None:\n dtype = self.nn_dtype\n vector = tf.cast(vector, self.nn_dtype)\n alpha = tf.reshape(vector[0], shape=[1, 1])\n beta = vector[1:]\n \n \n h_beta = self.get_h_product(beta)\n\n \n result = tf.concat(\n [\n alpha * self.nu + tf.reduce_sum(tf.multiply(beta, self.vector_g)),\n tf.multiply(alpha, self.vector_g) + h_beta\n ],\n axis=0)\n return tf.cast(result, dtype)", "docstring": "Function that provides matrix product interface with PSD matrix.\n\nArgs:\nvector: the vector to be multiplied with matrix M\n\nReturns:\nresult_product: Matrix product of M and vector", "source": "juraj-google-style"}
614{"code": "def create_from_settings(settings):\n return Connection(settings['url'], settings['base_url'], settings['user'], settings['password'], authorizations=settings['authorizations'], debug=settings['debug'])", "docstring": "Create a connection with given settings.\n\nArgs:\nsettings (dict): A dictionary of settings\n\nReturns:\n:class:`Connection`. The connection", "source": "codesearchnet"}
615{"code": "def _ReadSemanticDataTypeDefinition(self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values):\n return self._ReadDataTypeDefinition(definitions_registry, definition_values, data_type_definition_class, definition_name, supported_definition_values)", "docstring": "Reads a semantic data type definition.\n\nArgs:\ndefinitions_registry (DataTypeDefinitionsRegistry): data type definitions\nregistry.\ndefinition_values (dict[str, object]): definition values.\ndata_type_definition_class (str): data type definition class.\ndefinition_name (str): name of the definition.\nsupported_definition_values (set[str]): names of the supported definition\nvalues.\n\nReturns:\nSemanticDataTypeDefinition: semantic data type definition.\n\nRaises:\nDefinitionReaderError: if the definitions values are missing or if\nthe format is incorrect.", "source": "codesearchnet"}
616{"code": "def update_hparams_for_universal_transformer(hparams):\n \n hparams.daisy_chain_variables = False \n\n \n \n hparams.add_hparam(\"mix_with_transformer\", None)\n\n \n hparams.add_hparam(\"num_mixedin_layers\", 2)\n \n hparams.add_hparam(\"num_inrecurrence_layers\", 1)\n\n \n \n hparams.add_hparam(\"recurrence_type\", \"basic\")\n\n \n hparams.add_hparam(\"num_rec_steps\", hparams.num_hidden_layers)\n\n \n hparams.add_hparam(\"add_position_timing_signal\", True)\n if hparams.add_position_timing_signal:\n hparams.pos = None\n \n \n hparams.add_hparam(\"position_start_index\", None)\n\n \n hparams.add_hparam(\"add_step_timing_signal\", True)\n \n hparams.add_hparam(\"step_timing_signal_type\", \"learned\")\n\n \n \n hparams.add_hparam(\"add_or_concat_timing_signal\", \"add\")\n\n \n \n hparams.add_hparam(\"add_sru\", False)\n\n \n \n hparams.add_hparam(\"transformer_ffn_type\", \"fc\")\n\n \n hparams.add_hparam(\"transform_bias_init\", -1.0)\n hparams.add_hparam(\"couple_carry_transform_gates\", True)\n\n \n \n hparams.add_hparam(\"depth_embedding\", True)\n \n hparams.add_hparam(\"dwa_elements\", True)\n\n \n \n \n hparams.add_hparam(\"gate_ffn_layer\", \"dense\")\n\n \n hparams.add_hparam(\"lstm_forget_bias\", 1.0)\n \n hparams.add_hparam(\"use_memory_as_final_state\", False)\n \n hparams.add_hparam(\"add_ffn_unit_to_the_transition_function\", False)\n\n \n hparams.add_hparam(\"act_type\", \"basic\")\n \n hparams.add_hparam(\"act_max_steps\", 2 * hparams.num_hidden_layers)\n hparams.add_hparam(\"act_halting_bias_init\", 1.0)\n hparams.add_hparam(\"act_epsilon\", 0.01)\n hparams.add_hparam(\"act_loss_weight\", 0.01)\n\n return hparams", "docstring": "Adds default hparams for all of the variants of the Universal Transformer.\n\nArgs:\nhparams: default hparams (usually one of the standard hparams from\ntransformer model (like \"transformer_base\")\n\nReturns:\nhparams with default values for Universal Transformers hyper-parameters", "source": "juraj-google-style"}
617{"code": "def play_from_queue(self, index, start=True):\n if (not self.speaker_info):\n self.get_speaker_info()\n uri = 'x-rincon-queue:{0}\n self.avTransport.SetAVTransportURI([('InstanceID', 0), ('CurrentURI', uri), ('CurrentURIMetaData', '')])\n self.avTransport.Seek([('InstanceID', 0), ('Unit', 'TRACK_NR'), ('Target', (index + 1))])\n if start:\n self.play()", "docstring": "Play a track from the queue by index.\n\nThe index number is required as an argument, where the first index\nis 0.\n\nArgs:\nindex (int): 0-based index of the track to play\nstart (bool): If the item that has been set should start playing", "source": "codesearchnet"}
618{"code": "def figure_naming(pretitle='', posttitle='', prefile='', postfile=''):\n if pretitle:\n pretitle = ('%s -- ' % pretitle)\n if posttitle:\n posttitle = (' -- %s' % posttitle)\n if prefile:\n prefile = ('%s_' % prefile)\n if postfile:\n postfile = ('_%s' % postfile)\n return (pretitle, posttitle, prefile, postfile)", "docstring": "Helper function to define the strings that handle pre-post conventions\nfor viewing - plotting title and saving options.\n\nArgs:\npretitle(str): String to include before the general title of the figure.\nposttitle(str): String to include after the general title of the figure.\nprefile(str): String to include before the general filename of the figure.\npostfile(str): String to include after the general filename of the figure.\n\nReturns:\nstr: String to include in the figure name and title, in a suitable form.", "source": "codesearchnet"}
619{"code": "def initialize(\n self, config_file: str = \"bmi_config.txt\", initialize_indicators=True\n ):\n \n self.t = 0.0\n if not os.path.isfile(config_file):\n self.create_bmi_config_file(config_file)\n\n self.s0 = [\n pd.read_csv(\n config_file, index_col=0, header=None, error_bad_lines=False\n )[1]\n for _ in range(self.res)\n ]\n self.s0_original = self.s0[0].copy(deep=True)\n\n self.latent_state_vector = self.construct_default_initial_state()\n\n for n in self.nodes(data=True):\n rv = LatentVar(n[0])\n n[1][\"rv\"] = rv\n n[1][\"update_function\"] = self.default_update_function\n rv.dataset = [1.0 for _ in range(self.res)]\n rv.partial_t = self.s0[0][f\"∂({n[0]})/∂t\"]\n if initialize_indicators:\n for indicator in n[1][\"indicators\"].values():\n indicator.samples = np.random.normal(\n indicator.mean * np.array(n[1][\"rv\"].dataset),\n scale=0.01,\n )", "docstring": "Initialize the executable AnalysisGraph with a config file.\n\nArgs:\nconfig_file\n\nReturns:\nAnalysisGraph", "source": "juraj-google-style"}
620{"code": "def find_base_model_checkpoint(model_type: str, model_files: Optional[Dict[str, Union[Path, List[Path]]]]=None) -> str:\n if model_files is None:\n model_files = get_model_files(model_type)\n module_files = model_files['model_files']\n for fname in module_files:\n if 'modeling' not in str(fname):\n continue\n with open(fname, 'r', encoding='utf-8') as f:\n content = f.read()\n if _re_checkpoint_for_doc.search(content) is not None:\n checkpoint = _re_checkpoint_for_doc.search(content).groups()[0]\n checkpoint = checkpoint.replace('\"', '')\n checkpoint = checkpoint.replace(\"'\", '')\n return checkpoint\n return ''", "docstring": "Finds the model checkpoint used in the docstrings for a given model.\n\nArgs:\nmodel_type (`str`): A valid model type (like \"bert\" or \"gpt2\")\nmodel_files (`Dict[str, Union[Path, List[Path]]`, *optional*):\nThe files associated to `model_type`. Can be passed to speed up the function, otherwise will be computed.\n\nReturns:\n`str`: The checkpoint used.", "source": "github-repos"}
621{"code": "def _to_tensor_list_helper(encode_fn, element_spec, element):\n nest.assert_same_structure(element_spec, element)\n\n def reduce_fn(state, value):\n spec, component = value\n if isinstance(spec, internal.TensorSpec):\n try:\n component = ops.convert_to_tensor(component, spec.dtype)\n except (TypeError, ValueError):\n raise ValueError(f'Value {component} is not convertible to a tensor with dtype {spec.dtype} and shape {spec.shape}.')\n if not component.shape.is_compatible_with(spec.shape):\n raise ValueError(f'Value {component} is not convertible to a tensor with dtype {spec.dtype} and shape {spec.shape}.')\n return encode_fn(state, spec, component)\n return functools.reduce(reduce_fn, zip(nest.flatten(element_spec), nest.flatten(element)), [])", "docstring": "Returns a tensor list representation of the element.\n\nArgs:\nencode_fn: Method that constructs a tensor list representation from the\ngiven element spec and element.\nelement_spec: A nested structure of `tf.TypeSpec` objects representing to\nelement type specification.\nelement: The element to convert to tensor list representation.\n\nReturns:\nA tensor list representation of `element`.\n\nRaises:\nValueError: If `element_spec` and `element` do not have the same number of\nelements or if the two structures are not nested in the same way.\nTypeError: If `element_spec` and `element` differ in the type of sequence\nin any of their substructures.", "source": "github-repos"}
622{"code": "def to_frame(data_list, exc_cols=None, **kwargs):\n from collections import OrderedDict\n return pd.DataFrame(pd.Series(data_list).apply(OrderedDict).tolist(), **kwargs).drop(columns=([] if (exc_cols is None) else exc_cols))", "docstring": "Dict in Python 3.6 keeps insertion order, but cannot be relied upon\nThis method is to keep column names in order\nIn Python 3.7 this method is redundant\n\nArgs:\ndata_list: list of dict\nexc_cols: exclude columns\n\nReturns:\npd.DataFrame\n\nExample:\n>>> d_list = [\n... dict(sid=1, symbol='1 HK', price=89),\n... dict(sid=700, symbol='700 HK', price=350)\n... ]\n>>> to_frame(d_list)\nsid symbol price\n0 1 1 HK 89\n1 700 700 HK 350\n>>> to_frame(d_list, exc_cols=['price'])\nsid symbol\n0 1 1 HK\n1 700 700 HK", "source": "codesearchnet"}
623{"code": "def emit_obj_snapshot(self, category: str, name: str, timestamp: int, pid: int, tid: int, object_id: int, snapshot: Dict[str, Any]) -> None:\n event = self._create_event('O', category, name, pid, tid, timestamp)\n event['id'] = object_id\n event['args'] = {'snapshot': snapshot}\n self._events.append(event)", "docstring": "Adds an object snapshot event to the trace.\n\nArgs:\ncategory: The event category as a string.\nname: The event name as a string.\ntimestamp: The timestamp of this event as a long integer.\npid: Identifier of the process generating this event as an integer.\ntid: Identifier of the thread generating this event as an integer.\nobject_id: Identifier of the object as an integer.\nsnapshot: A JSON-compatible representation of the object.", "source": "github-repos"}
624{"code": "def create_additional_charge(self, *, subscription_id, description, plan_value, plan_tax, plan_tax_return_base,\n currency):\n \n payload = {\n \"description\": description,\n \"additionalValues\": [\n {\n \"name\": \"ITEM_VALUE\",\n \"value\": plan_value,\n \"currency\": currency\n },\n {\n \"name\": \"ITEM_TAX\",\n \"value\": plan_tax,\n \"currency\": currency\n },\n {\n \"name\": \"ITEM_TAX_RETURN_BASE\",\n \"value\": plan_tax_return_base,\n \"currency\": currency\n }\n ]\n }\n fmt = 'subscriptions/{}/recurringBillItems'.format(subscription_id)\n return self.client._post(self.url + fmt, json=payload, headers=self.get_headers())", "docstring": "Adds extra charges to the respective invoice for the current period.\n\nArgs:\nsubscription_id: Identification of the subscription\ndescription:\nplan_value:\nplan_tax:\nplan_tax_return_base:\ncurrency:\n\nReturns:", "source": "juraj-google-style"}
625{"code": "def calc_clusters(returns, n=None, plot=False):\n \n \n corr = returns.corr()\n\n \n diss = 1 - corr\n\n \n \n \n mds = sklearn.manifold.MDS(dissimilarity='precomputed')\n xy = mds.fit_transform(diss)\n\n def routine(k):\n \n km = sklearn.cluster.KMeans(n_clusters=k)\n km_fit = km.fit(xy)\n labels = km_fit.labels_\n centers = km_fit.cluster_centers_\n\n \n mappings = dict(zip(returns.columns, labels))\n\n \n totss = 0\n withinss = 0\n \n avg = np.array([np.mean(xy[:, 0]), np.mean(xy[:, 1])])\n for idx, lbl in enumerate(labels):\n withinss += sum((xy[idx] - centers[lbl]) ** 2)\n totss += sum((xy[idx] - avg) ** 2)\n pvar_expl = 1.0 - withinss / totss\n\n return mappings, pvar_expl, labels\n\n if n:\n result = routine(n)\n else:\n n = len(returns.columns)\n n1 = int(np.ceil(n * 0.6666666666))\n for i in range(2, n1 + 1):\n result = routine(i)\n if result[1] > 0.9:\n break\n\n if plot:\n fig, ax = plt.subplots()\n ax.scatter(xy[:, 0], xy[:, 1], c=result[2], s=90)\n for i, txt in enumerate(returns.columns):\n ax.annotate(txt, (xy[i, 0], xy[i, 1]), size=14)\n\n \n tmp = result[0]\n \n inv_map = {}\n for k, v in iteritems(tmp):\n inv_map[v] = inv_map.get(v, [])\n inv_map[v].append(k)\n\n return inv_map", "docstring": "Calculates the clusters based on k-means\nclustering.\n\nArgs:\n* returns (pd.DataFrame): DataFrame of returns\n* n (int): Specify # of clusters. If None, this\nwill be automatically determined\n* plot (bool): Show plot?\n\nReturns:\n* dict with structure: {cluster# : [col names]}", "source": "juraj-google-style"}
626{"code": "def get_country_name_from_iso2(cls, iso2, use_live=True, exception=None):\n \n \n iso3 = cls.get_iso3_from_iso2(iso2, use_live=use_live, exception=exception)\n if iso3 is not None:\n return cls.get_country_name_from_iso3(iso3, exception=exception)\n return None", "docstring": "Get country name from ISO2 code\n\nArgs:\niso2 (str): ISO2 code for which to get country name\nuse_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\nexception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.\n\nReturns:\nOptional[str]: Country name", "source": "juraj-google-style"}
627{"code": "def create_report(self, uri, timeout=(- 1)):\n logger.debug('Creating Report (uri = %s)'.format(uri))\n (task, _) = self._connection.post(uri, {})\n if (not task):\n raise exceptions.HPOneViewException(RESOURCE_CLIENT_TASK_EXPECTED)\n task = self._task_monitor.get_completed_task(task, timeout)\n return task['taskOutput']", "docstring": "Creates a report and returns the output.\n\nArgs:\nuri: URI\ntimeout:\nTimeout in seconds. Wait for task completion by default. The timeout does not abort the operation\nin OneView; it just stops waiting for its completion.\n\nReturns:\nlist:", "source": "codesearchnet"}
628{"code": "def go_in(self, vertex):\n \n if self.vertex_in:\n self.vertex_in.edges_in.remove(self)\n self.vertex_in = vertex\n vertex.edges_in.add(self)", "docstring": "Tell the edge to go into this vertex.\n\nArgs:\nvertex (Vertex): vertex to go into.", "source": "juraj-google-style"}
629{"code": "def recipe_anonymize_query(config, auth_read, from_project, from_dataset, from_query, to_project, to_dataset, to_table):\n anonymize(config, {'auth': auth_read, 'bigquery': {'from': {'project': from_project, 'dataset': from_dataset, 'query': from_query}, 'to': {'project': to_project, 'dataset': to_dataset, 'table': to_table}}})", "docstring": "Runs a query and anynonamizes all rows. Used to create sample table for\ndashboards.\n\nArgs:\nauth_read (authentication) - Credentials used.\nfrom_project (string) - Original project to read from.\nfrom_dataset (string) - Original dataset to read from.\nfrom_query (string) - Query to read data.\nto_project (string) - Anonymous data will be writen to.\nto_dataset (string) - Anonymous data will be writen to.\nto_table (string) - Anonymous data will be writen to.", "source": "github-repos"}
630{"code": "def get_all_keys(tweet, parent_key=''):\n items = []\n for (k, v) in tweet.items():\n new_key = ((parent_key + ' ') + k)\n if isinstance(v, dict):\n items.extend(get_all_keys(v, parent_key=new_key))\n else:\n items.append(new_key.strip(' '))\n return items", "docstring": "Takes a tweet object and recursively returns a list of all keys contained\nin this level and all nexstted levels of the tweet.\n\nArgs:\ntweet (Tweet): the tweet dict\nparent_key (str): key from which this process will start, e.g., you can\nget keys only under some key that is not the top-level key.\n\nReturns:\nlist of all keys in nested dicts.\n\nExample:\n>>> import tweet_parser.tweet_checking as tc\n>>> tweet = {\"created_at\": 124125125125, \"text\": \"just setting up my twttr\",\n... \"nested_field\": {\"nested_1\": \"field\", \"nested_2\": \"field2\"}}\n>>> tc.get_all_keys(tweet)\n['created_at', 'text', 'nested_field nested_1', 'nested_field nested_2']", "source": "codesearchnet"}
631{"code": "def _CreateAnalysisPlugins(self, options):\n \n if not self._analysis_plugins:\n return {}\n\n analysis_plugins = (\n analysis_manager.AnalysisPluginManager.GetPluginObjects(\n self._analysis_plugins))\n\n for analysis_plugin in analysis_plugins.values():\n helpers_manager.ArgumentHelperManager.ParseOptions(\n options, analysis_plugin)\n\n return analysis_plugins", "docstring": "Creates the analysis plugins.\n\nArgs:\noptions (argparse.Namespace): command line arguments.\n\nReturns:\ndict[str, AnalysisPlugin]: analysis plugins and their names.", "source": "juraj-google-style"}
632{"code": "def all(script, face=True, vert=True):\n \n filter_xml = ''.join([\n ' <filter name=\"Select All\">\\n',\n ' <Param name=\"allFaces\" ',\n 'value=\"{}\" '.format(str(face).lower()),\n 'description=\"DSelect all Faces\" ',\n 'type=\"RichBool\" ',\n '/>\\n',\n ' <Param name=\"allVerts\" ',\n 'value=\"{}\" '.format(str(vert).lower()),\n 'description=\"Select all Vertices\" ',\n 'type=\"RichBool\" ',\n '/>\\n',\n ' </filter>\\n'])\n util.write_filter(script, filter_xml)\n return None", "docstring": "Select all the faces of the current mesh\n\nArgs:\nscript: the FilterScript object or script filename to write\nthe filter to.\nfaces (bool): If True the filter will select all the faces.\nverts (bool): If True the filter will select all the vertices.\n\nLayer stack:\nNo impacts\n\nMeshLab versions:\n2016.12\n1.3.4BETA", "source": "juraj-google-style"}
633{"code": "def _ParseRecurseKeys(self, parser_mediator, root_key):\n \n for registry_key in root_key.RecurseKeys():\n if parser_mediator.abort:\n break\n\n self._ParseKey(parser_mediator, registry_key)", "docstring": "Parses the Registry keys recursively.\n\nArgs:\nparser_mediator (ParserMediator): parser mediator.\nroot_key (dfwinreg.WinRegistryKey): root Windows Registry key.", "source": "juraj-google-style"}
634{"code": "def vol_tetra(vt1, vt2, vt3, vt4):\n \n vol_tetra = np.abs(np.dot((vt1 - vt4),\n np.cross((vt2 - vt4), (vt3 - vt4)))) / 6\n return vol_tetra", "docstring": "Calculate the volume of a tetrahedron, given the four vertices of vt1,\nvt2, vt3 and vt4.\nArgs:\nvt1 (array-like): coordinates of vertex 1.\nvt2 (array-like): coordinates of vertex 2.\nvt3 (array-like): coordinates of vertex 3.\nvt4 (array-like): coordinates of vertex 4.\nReturns:\n(float): volume of the tetrahedron.", "source": "juraj-google-style"}
635{"code": "def _check(cls, name, val, can_be_zero=False, val_type=float):\n \n valid_types = [val_type]\n if val_type is float:\n valid_types.append(int)\n\n if type(val) not in valid_types:\n raise TypeError(\n 'Expect type %s for parameter %s' % (val_type.__name__, name))\n if val < 0:\n raise ValueError(\n 'Value for parameter %s has to be greater than 0' % name)\n if not can_be_zero and val == 0:\n raise ValueError(\n 'Value for parameter %s can not be 0' % name)\n return val", "docstring": "Check init arguments.\n\nArgs:\nname: name of the argument. For logging purpose.\nval: value. Value has to be non negative number.\ncan_be_zero: whether value can be zero.\nval_type: Python type of the value.\n\nReturns:\nThe value.\n\nRaises:\nValueError: when invalid value is passed in.\nTypeError: when invalid value type is passed in.", "source": "juraj-google-style"}
636{"code": "def while_stmt(test, body, get_state, set_state, symbol_names, opts):\n with func_graph.FuncGraph('tmp').as_default():\n init_test = test()\n if tensors.is_dense_tensor(init_test):\n _tf_while_stmt(test, body, get_state, set_state, symbol_names, opts)\n return\n if not init_test:\n return\n body()\n _py_while_stmt(test, body, get_state, set_state, opts)", "docstring": "Functional form of a while statement.\n\nThe loop operates on a so-called state, which includes all symbols that are\nvariant across loop iterations. In what follows we refer to state as either\na tuple of entities that represent an actual state, or a list of arguments\nof the corresponding types.\n\nThe inputs and outputs of the callables representing the loop blocks are not\nexplicit - instead, these functions must use nonlocal/global for side effects.\nThe inputs and outputs are instead controlled by the set_state/get_state\nfunctions.\n\nArgs:\ntest: Callable with boolean return type. The loop condition.\nbody: Callable representing the actual loop body.\nget_state: Additional callable which can capture additional state (such as\nthe values of composite symbols). This is only useful when staging the\nloop.\nset_state: Additional callable which save values captured by get_state back\ninto the Python environment. This is only useful when staging the loop.\nsymbol_names: Tuple containing the names of all loop variables.\nopts: Optional dict of extra loop parameters.\n\nReturns:\nTuple containing the final state.", "source": "github-repos"}
637{"code": "def thumbnail(self, image: 'torch.Tensor', size: SizeDict) -> 'torch.Tensor':\n input_height, input_width = image.shape[-2:]\n output_height, output_width = (size.height, size.width)\n height = min(input_height, output_height)\n width = min(input_width, output_width)\n if height == input_height and width == input_width:\n return image\n if input_height > input_width:\n width = int(input_width * height / input_height)\n elif input_width > input_height:\n height = int(input_height * width / input_width)\n return self.resize(image, size=SizeDict(width=width, height=height), interpolation=F.InterpolationMode.BICUBIC)", "docstring": "Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any\ncorresponding dimension of the specified size.\n\nArgs:\nimage (`torch.Tensor`):\nThe image to be resized.\nsize (`Dict[str, int]`):\nThe size `{\"height\": h, \"width\": w}` to resize the image to.\nresample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\nThe resampling filter to use.\ndata_format (`Optional[Union[str, ChannelDimension]]`, *optional*):\nThe data format of the output image. If unset, the same format as the input image is used.\ninput_data_format (`ChannelDimension` or `str`, *optional*):\nThe channel dimension format of the input image. If not provided, it will be inferred.", "source": "github-repos"}
638{"code": "def __init__(self, save_steps=None, save_secs=None, output_dir='', show_dataflow=True, show_memory=False):\n self._output_file = os.path.join(output_dir, 'timeline-{}.json')\n self._file_writer = SummaryWriterCache.get(output_dir)\n self._show_dataflow = show_dataflow\n self._show_memory = show_memory\n self._timer = SecondOrStepTimer(every_secs=save_secs, every_steps=save_steps)", "docstring": "Initializes a hook that takes periodic profiling snapshots.\n\n`options.run_metadata` argument of `tf.Session.Run` is used to collect\nmetadata about execution. This hook sets the metadata and dumps it in Chrome\nTrace format.\n\n\nArgs:\nsave_steps: `int`, save profile traces every N steps. Exactly one of\n`save_secs` and `save_steps` should be set.\nsave_secs: `int` or `float`, save profile traces every N seconds.\noutput_dir: `string`, the directory to save the profile traces to.\nDefaults to the current directory.\nshow_dataflow: `bool`, if True, add flow events to the trace connecting\nproducers and consumers of tensors.\nshow_memory: `bool`, if True, add object snapshot events to the trace\nshowing the sizes and lifetimes of tensors.", "source": "github-repos"}
639{"code": "def acquire(self):\n \n if os.path.exists(self.path):\n try:\n pid = None\n\n with open(self.path, 'r') as f:\n line = f.readline().strip()\n pid = int(line)\n\n \n \n if not psutil.pid_exists(pid):\n os.remove(self.path)\n\n except ValueError as e:\n \n os.remove(self.path)\n\n except IOError as e:\n \n \n pass\n\n try:\n self.fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_RDWR)\n\n \n \n to_write = '%s%s' % (os.getpid(), os.linesep)\n os.write(self.fd, to_write.encode())\n\n except OSError as e:\n if not os.path.exists(self.path):\n raise\n return False\n\n self.acquired = True\n return True", "docstring": "Attempts to acquire a lock for the J-Link lockfile.\n\nIf the lockfile exists but does not correspond to an active process,\nthe lockfile is first removed, before an attempt is made to acquire it.\n\nArgs:\nself (Jlock): the ``JLock`` instance\n\nReturns:\n``True`` if the lock was acquired, otherwise ``False``.\n\nRaises:\nOSError: on file errors.", "source": "juraj-google-style"}
640{"code": "def get_service_health(service_id: str) -> str:\n \n \n if DC.get_replicas(service_id) != DC.get_actual_replica(service_id):\n health_status = \"Unhealthy\"\n else:\n health_status = \"Healthy\"\n\n return health_status", "docstring": "Get the health of a service using service_id.\n\nArgs:\nservice_id\n\nReturns:\nstr, health status", "source": "juraj-google-style"}
641{"code": "def bbox_clip(bboxes, img_shape):\n \n assert bboxes.shape[-1] % 4 == 0\n clipped_bboxes = np.empty_like(bboxes, dtype=bboxes.dtype)\n clipped_bboxes[..., 0::2] = np.maximum(\n np.minimum(bboxes[..., 0::2], img_shape[1] - 1), 0)\n clipped_bboxes[..., 1::2] = np.maximum(\n np.minimum(bboxes[..., 1::2], img_shape[0] - 1), 0)\n return clipped_bboxes", "docstring": "Clip bboxes to fit the image shape.\n\nArgs:\nbboxes (ndarray): Shape (..., 4*k)\nimg_shape (tuple): (height, width) of the image.\n\nReturns:\nndarray: Clipped bboxes.", "source": "juraj-google-style"}
642{"code": "def intersect(self, other):\n \n self.automaton = fst.intersect(self.automaton, other.automaton)\n return self", "docstring": "Constructs an unminimized DFA recognizing\nthe intersection of the languages of two given DFAs.\nArgs:\nother (DFA): The other DFA that will be used\nfor the intersect operation\nReturns:\nReturns:\nDFA: The resulting DFA", "source": "juraj-google-style"}
643{"code": "def make_innermost_getter(getter):\n\n @functools.wraps(getter)\n def _new_getter(kernel_results, *args, **kwargs):\n 'Wrapped getter.'\n results_stack = []\n while hasattr(kernel_results, 'inner_results'):\n results_stack.append(kernel_results)\n kernel_results = kernel_results.inner_results\n return getter(kernel_results, *args, **kwargs)\n return _new_getter", "docstring": "Wraps a getter so it applies to the inner-most results in `kernel_results`.\n\nThe wrapped getter unwraps `kernel_results` and returns the return value of\n`getter` called with the first results without an `inner_results` attribute.\n\nArgs:\ngetter: A callable that takes Kernel results and returns some value.\n\nReturns:\nnew_getter: A wrapped `getter`.", "source": "codesearchnet"}
644{"code": "def _op_in_graph_mode(tensor):\n if context.executing_eagerly():\n return tensor\n return tensor.op", "docstring": "Returns the tensor's op in graph mode, or the tensor in eager mode.\n\nThis is useful because sometimes an op is needed in graph mode instead of a\ntensor. In eager mode, there are no ops.\n\nArgs:\ntensor: A tensor.\n\nReturns:\nThe tensor's op in graph mode. The tensor in eager mode.", "source": "github-repos"}
645{"code": "def new_from_json(cls, json_data):\n json_data_as_unicode = _helpers._from_bytes(json_data)\n data = json.loads(json_data_as_unicode)\n module_name = data['_module']\n try:\n module_obj = __import__(module_name)\n except ImportError:\n module_name = module_name.replace('.googleapiclient', '')\n module_obj = __import__(module_name)\n module_obj = __import__(module_name, fromlist=module_name.split('.')[:(- 1)])\n kls = getattr(module_obj, data['_class'])\n return kls.from_json(json_data_as_unicode)", "docstring": "Utility class method to instantiate a Credentials subclass from JSON.\n\nExpects the JSON string to have been produced by to_json().\n\nArgs:\njson_data: string or bytes, JSON from to_json().\n\nReturns:\nAn instance of the subclass of Credentials that was serialized with\nto_json().", "source": "codesearchnet"}
646{"code": "def _find_channel_index(data_format):\n \n for i, c in enumerate(data_format):\n if c == \"C\":\n return i\n raise ValueError(\"data_format requires a channel dimension. Got: {}\"\n .format(data_format))", "docstring": "Returns the index of the channel dimension.\n\nArgs:\ndata_format: A string of characters corresponding to Tensor dimensionality.\n\nReturns:\nchannel_index: An integer indicating the channel dimension.\n\nRaises:\nValueError: If no channel dimension was found.", "source": "juraj-google-style"}
647{"code": "def is_distributed(partition_column, lower_bound, upper_bound):\n if ((partition_column is not None) and (lower_bound is not None) and (upper_bound is not None)):\n if (upper_bound > lower_bound):\n return True\n else:\n raise InvalidArguments('upper_bound must be greater than lower_bound.')\n elif ((partition_column is None) and (lower_bound is None) and (upper_bound is None)):\n return False\n else:\n raise InvalidArguments('Invalid combination of partition_column, lower_bound, upper_bound.All these arguments should be passed (distributed) or none of them (standard pandas).')", "docstring": "Check if is possible distribute a query given that args\n\nArgs:\npartition_column: column used to share the data between the workers\nlower_bound: the minimum value to be requested from the partition_column\nupper_bound: the maximum value to be requested from the partition_column\n\nReturns:\nTrue for distributed or False if not", "source": "codesearchnet"}
648{"code": "def convert_constant(params, w_name, scope_name, inputs, layers, weights, names):\n print('Converting constant ...')\n params_list = params['value'].numpy()\n\n def target_layer(x, value=params_list):\n return tf.constant(value.tolist(), shape=value.shape)\n lambda_layer = keras.layers.Lambda(target_layer)\n layers[(scope_name + '_np')] = params_list\n layers[scope_name] = lambda_layer(layers[list(layers.keys())[0]])", "docstring": "Convert constant layer.\n\nArgs:\nparams: dictionary with layer parameters\nw_name: name prefix in state_dict\nscope_name: pytorch scope name\ninputs: pytorch node inputs\nlayers: dictionary with keras tensors\nweights: pytorch state_dict\nnames: use short names for keras layers", "source": "codesearchnet"}
649{"code": "def file_move(filename, settings):\n \n if len(settings) != 1:\n raise ValueError(\"Settings must only contain one item with key \"\n \"'dest'.\")\n for k, v in settings.items():\n if k == \"dest\":\n shutil.move(filename, v)", "docstring": "Moves a file. {'_file_move': {'dest': 'new_file_name'}}\n\nArgs:\nfilename (str): Filename.\nsettings (dict): Must be {\"dest\": path of new file}", "source": "juraj-google-style"}
650{"code": "def metropolis_hastings_step(current_state: State, proposed_state: State, energy_change: FloatTensor, seed=None) -> Tuple[(State, tf.Tensor, tf.Tensor)]:\n flat_current = tf.nest.flatten(current_state)\n flat_proposed = nest.flatten_up_to(current_state, proposed_state)\n flat_current = [(p if (c is None) else c) for (p, c) in zip(flat_proposed, flat_current)]\n current_state = tf.nest.pack_sequence_as(current_state, flat_current)\n current_state = tf.nest.map_structure(tf.convert_to_tensor, current_state)\n proposed_state = tf.nest.map_structure(tf.convert_to_tensor, proposed_state)\n energy_change = tf.convert_to_tensor(value=energy_change)\n log_accept_ratio = (- energy_change)\n log_uniform = tf.math.log(tf.random.uniform(shape=tf.shape(input=log_accept_ratio), dtype=log_accept_ratio.dtype.base_dtype, seed=seed))\n is_accepted = (log_uniform < log_accept_ratio)\n next_state = mcmc_util.choose(is_accepted, proposed_state, current_state, name='choose_next_state')\n return (next_state, is_accepted, log_uniform)", "docstring": "Metropolis-Hastings step.\n\nThis probabilistically chooses between `current_state` and `proposed_state`\nbased on the `energy_change` so as to preserve detailed balance.\n\nEnergy change is the negative of `log_accept_ratio`.\n\nArgs:\ncurrent_state: Current state.\nproposed_state: Proposed state.\nenergy_change: E(proposed_state) - E(previous_state).\nseed: For reproducibility.\n\nReturns:\nnew_state: The chosen state.\nis_accepted: Whether the proposed state was accepted.\nlog_uniform: The random number that was used to select between the two\nstates.", "source": "codesearchnet"}
651{"code": "def expand_unique_results(y, idx):\n expanded = tf.gather(y, idx, axis=0)\n return expanded", "docstring": "Inverse of unique_bitstrings_with_counts.\n\nArgs:\ny: Values to pick according to `idx`.\nidx: The index at which to place each value of `y` in the output.\n\nReturns:\nexpanded: `tf.Tensor` such that `expanded[i] == y[idx[i]]`.", "source": "github-repos"}
652{"code": "def _weight_generator(self, reviewers):\n scores = [r.anomalous_score for r in reviewers]\n mu = np.average(scores)\n sigma = np.std(scores)\n if sigma:\n\n def w(v):\n 'Compute a weight for the given reviewer.\\n\\n Args:\\n v: anomalous score of a reviewer.\\n Returns:\\n weight of the given anomalous score.\\n '\n try:\n exp = math.exp(((self.alpha * (v - mu)) / sigma))\n return (1.0 / (1.0 + exp))\n except OverflowError:\n return 0.0\n return w\n else:\n return (lambda v: 1.0)", "docstring": "Compute a weight function for the given reviewers.\n\nArgs:\nreviewers: a set of reviewers to compute weight function.\n\nReturns:\na function computing a weight for a reviewer.", "source": "codesearchnet"}
653{"code": "def _run_graph_for_calibration_eager_mode(model_dir: str, tags: Collection[str], representative_dataset_map: rd.RepresentativeDatasetMapping) -> None:\n root: autotrackable.AutoTrackable = load.load(model_dir, tags)\n for signature_key, repr_ds in representative_dataset_map.items():\n try:\n _run_function_for_calibration_eager_mode(func=root.signatures[signature_key], representative_dataset=repr_ds)\n except Exception as ex:\n raise ValueError(f'Failed to run representative dataset through the function with the signature key: {signature_key}.') from ex", "docstring": "Runs the graph for calibration in eager mode.\n\nThis function assumes _eager mode_ (enabled in TF2 by default) when running\nthe graph. This step is used in order to collect the statistics in\nCustomAggregatorOp for quantization using the representative dataset for the\nactual data provided for inference.\n\nArgs:\nmodel_dir: Path to SavedModel directory.\ntags: Collection of tags identifying the MetaGraphDef within the SavedModel.\nrepresentative_dataset_map: A map where signature keys are mapped to\ncorresponding representative datasets.\n\nRaises:\nValueError: When running the function with the representative dataset fails.", "source": "github-repos"}
654{"code": "def delete(self, personId):\n check_type(personId, basestring, may_be_none=False)\n self._session.delete(((API_ENDPOINT + '/') + personId))", "docstring": "Remove a person from the system.\n\nOnly an admin can remove a person.\n\nArgs:\npersonId(basestring): The ID of the person to be deleted.\n\nRaises:\nTypeError: If the parameter types are incorrect.\nApiError: If the Webex Teams cloud returns an error.", "source": "codesearchnet"}
655{"code": "def get_module_names(p):\n \n mods = list()\n mods = [f.split('.')[0] for f in listdir(p)\n if isfile(join(p, f)) and not f.endswith('.pyc') and not f.startswith('__')]\n print len(mods)\n return mods", "docstring": "Accepts a path to search for modules. The method will filter on files\nthat end in .pyc or files that start with __.\n\nArguments:\np (string): The path to search\nReturns:\nlist of file names", "source": "juraj-google-style"}
656{"code": "def build(bucket_name, version, force, verbose):\n if verbose:\n log.setLevel('DEBUG')\n if (not version):\n version = setuptools_scm.get_version()\n release = ('dev' if ('dev' in version) else 'release')\n tarball = TARBALL_FORMAT.format(version)\n tarball_path = os.path.join(tempfile.gettempdir(), tarball)\n s3_key = os.path.join(release, tarball)\n try:\n run('npm i')\n run('./node_modules/.bin/gulp build.prod')\n except ExecutionError:\n log.exception('Failed executing command')\n return\n log.debug('Creating archive')\n tar = tarfile.open(tarball_path, 'w:gz')\n for (root, dirnames, filenames) in os.walk('dist'):\n for f in filenames:\n tar.add(os.path.join(root, f), recursive=False, filter=strip_path)\n tar.close()\n log.debug('Uploading {} to s3:\n try:\n bucket = get_bucket_resource(bucket_name)\n if (s3_file_exists(bucket, s3_key) and (not force)):\n log.error('File already exists in S3, use --force to overwrite')\n return\n bucket.upload_file(tarball_path, os.path.join(release, tarball))\n except ClientError:\n log.exception('AWS API failure')", "docstring": "Build and upload a new tarball\n\nArgs:\nbucket_name (str): Name of the bucket to upload to\nversion (str): Override build version. Defaults to using SCM based versioning (git tags)\nforce (bool): Overwrite existing files in S3, if present\nverbose (bool): Verbose output", "source": "codesearchnet"}
657{"code": "def plot_conductivity_mu(self, temp=600, output='eig',\n relaxation_time=1e-14, xlim=None):\n \n import matplotlib.pyplot as plt\n cond = self._bz.get_conductivity(relaxation_time=relaxation_time,\n output=output, doping_levels=False)[\n temp]\n plt.figure(figsize=(9, 7))\n plt.semilogy(self._bz.mu_steps, cond, linewidth=3.0)\n self._plot_bg_limits()\n self._plot_doping(temp)\n if output == 'eig':\n plt.legend(['$\\\\Sigma_1$', '$\\\\Sigma_2$', '$\\\\Sigma_3$'])\n if xlim is None:\n plt.xlim(-0.5, self._bz.gap + 0.5)\n else:\n plt.xlim(xlim)\n plt.ylim([1e13 * relaxation_time, 1e20 * relaxation_time])\n plt.ylabel(\"conductivity,\\n $\\\\Sigma$ (1/($\\\\Omega$ m))\", fontsize=30.0)\n plt.xlabel(\"E-E$_f$ (eV)\", fontsize=30.0)\n plt.xticks(fontsize=25)\n plt.yticks(fontsize=25)\n plt.tight_layout()\n return plt", "docstring": "Plot the conductivity in function of Fermi level. Semi-log plot\n\nArgs:\ntemp: the temperature\nxlim: a list of min and max fermi energy by default (0, and band\ngap)\ntau: A relaxation time in s. By default none and the plot is by\nunits of relaxation time\n\nReturns:\na matplotlib object", "source": "juraj-google-style"}
658{"code": "def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):\n vision_data = {}\n if image_sizes is not None:\n num_image_tokens = [self.image_seq_length] * len(image_sizes)\n num_image_patches = [1] * len(image_sizes)\n vision_data.update({'num_image_tokens': num_image_tokens, 'num_image_patches': num_image_patches})\n return MultiModalData(**vision_data)", "docstring": "Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.\n\nArgs:\nimage_sizes (List[List[str]], *optional*):\nThe input sizes formatted as (height, width) per each image.\nReturns:\nDict[str, List[int]]: A dictionary mapping each modality (\"image\", \"video\", \"audio\")\nto a list containing the number of placeholder tokens required. If the model doesn't accept\na certain modality or no input sizes are provided, the dict value is set to an empty list.", "source": "github-repos"}
659{"code": "def parse_kegg_gene_metadata(infile):\n metadata = defaultdict(str)\n with open(infile) as mf:\n kegg_parsed = bs_kegg.parse(mf.read())\n if ('DBLINKS' in kegg_parsed.keys()):\n if ('UniProt' in kegg_parsed['DBLINKS']):\n unis = str(kegg_parsed['DBLINKS']['UniProt']).split(' ')\n if isinstance(unis, list):\n metadata['uniprot'] = unis[0]\n else:\n metadata['uniprot'] = unis\n if ('NCBI-ProteinID' in kegg_parsed['DBLINKS']):\n metadata['refseq'] = str(kegg_parsed['DBLINKS']['NCBI-ProteinID'])\n if ('STRUCTURE' in kegg_parsed.keys()):\n metadata['pdbs'] = str(kegg_parsed['STRUCTURE']['PDB']).split(' ')\n else:\n metadata['pdbs'] = None\n if ('ORGANISM' in kegg_parsed.keys()):\n metadata['taxonomy'] = str(kegg_parsed['ORGANISM'])\n return metadata", "docstring": "Parse the KEGG flatfile and return a dictionary of metadata.\n\nDictionary keys are:\nrefseq\nuniprot\npdbs\ntaxonomy\n\nArgs:\ninfile: Path to KEGG flatfile\n\nReturns:\ndict: Dictionary of metadata", "source": "codesearchnet"}
660{"code": "def cubic_jacobian_polynomial(nodes):\n jac_parts = _helpers.matrix_product(nodes, _CUBIC_JACOBIAN_HELPER)\n jac_at_nodes = np.empty((1, 15), order='F')\n jac_at_nodes[(0, 0)] = two_by_two_det(jac_parts[(:, :2)])\n jac_at_nodes[(0, 1)] = two_by_two_det(jac_parts[(:, 2:4)])\n jac_at_nodes[(0, 2)] = two_by_two_det(jac_parts[(:, 4:6)])\n jac_at_nodes[(0, 3)] = two_by_two_det(jac_parts[(:, 6:8)])\n jac_at_nodes[(0, 4)] = two_by_two_det(jac_parts[(:, 8:10)])\n jac_at_nodes[(0, 5)] = two_by_two_det(jac_parts[(:, 10:12)])\n jac_at_nodes[(0, 6)] = two_by_two_det(jac_parts[(:, 12:14)])\n jac_at_nodes[(0, 7)] = two_by_two_det(jac_parts[(:, 14:16)])\n jac_at_nodes[(0, 8)] = two_by_two_det(jac_parts[(:, 16:18)])\n jac_at_nodes[(0, 9)] = two_by_two_det(jac_parts[(:, 18:20)])\n jac_at_nodes[(0, 10)] = two_by_two_det(jac_parts[(:, 20:22)])\n jac_at_nodes[(0, 11)] = two_by_two_det(jac_parts[(:, 22:24)])\n jac_at_nodes[(0, 12)] = two_by_two_det(jac_parts[(:, 24:26)])\n jac_at_nodes[(0, 13)] = two_by_two_det(jac_parts[(:, 26:28)])\n jac_at_nodes[(0, 14)] = two_by_two_det(jac_parts[(:, 28:)])\n bernstein = _helpers.matrix_product(jac_at_nodes, _QUARTIC_TO_BERNSTEIN)\n bernstein /= _QUARTIC_BERNSTEIN_FACTOR\n return bernstein", "docstring": "r\"\"\"Compute the Jacobian determinant of a cubic surface.\n\n.. note::\n\nThis is used **only** by :meth:`Surface._compute_valid` (which is\nin turn used to compute / cache the :attr:`Surface.is_valid`\nproperty).\n\nConverts :math:`\\det(J(s, t))` to a polynomial on the reference\ntriangle and represents it as a surface object.\n\n.. note::\n\nThis assumes that ``nodes`` is ``2 x 10`` but doesn't verify this.\n(However, the right multiplication by ``_CUBIC_JACOBIAN_HELPER``\nwould fail if ``nodes`` wasn't ``R x 10`` and then the ensuing\ndeterminants would fail if there weren't 2 rows.)\n\nArgs:\nnodes (numpy.ndarray): A 2 x 10 array of nodes in a surface.\n\nReturns:\nnumpy.ndarray: 1 x 15 array, coefficients in Bernstein basis.", "source": "codesearchnet"}
661{"code": "def iaf_flow(one_hot_assignments, scale_weights, scale_bias, num_codes, summary=True, name=None):\n with tf.name_scope(name, default_name='iaf'):\n padded_assignments = tf.pad(one_hot_assignments, [[0, 0], [0, 0], [1, 0], [0, 0]])[(:, :, :(- 1), :)]\n scale_bijector = tfp.distributions.bijectors.Affine(scale_tril=tfp.distributions.fill_triangular(scale_weights))\n scale = scale_bijector.forward(tf.transpose(padded_assignments, [0, 1, 3, 2]))\n scale = tf.transpose(scale, [0, 1, 3, 2])\n scale = tf.nn.softplus(scale)\n scale = (scale + tf.nn.softplus(scale_bias[(tf.newaxis, tf.newaxis, ...)]))\n scale = scale[(..., :(- 1))]\n z = one_hot_assignments[(..., :(- 1))]\n unnormalized_probs = tf.concat([(z * scale), one_hot_assignments[(..., (- 1), tf.newaxis)]], axis=(- 1))\n normalizer = tf.reduce_sum(unnormalized_probs, axis=(- 1))\n flow_output = (unnormalized_probs / normalizer[(..., tf.newaxis)])\n inverse_log_det_jacobian = ((- tf.reduce_sum(tf.log(scale), axis=(- 1))) + (num_codes * tf.log(normalizer)))\n if summary:\n tf.summary.histogram('iaf/scale', tf.reshape(scale, [(- 1)]))\n tf.summary.histogram('iaf/inverse_log_det_jacobian', tf.reshape(inverse_log_det_jacobian, [(- 1)]))\n return (flow_output, inverse_log_det_jacobian)", "docstring": "Performs a single IAF flow using scale and normalization transformations.\n\nArgs:\none_hot_assignments: Assignments Tensor with shape [num_samples, batch_size,\nlatent_size, num_codes].\nscale_weights: Tensor corresponding to lower triangular matrix used to\nautoregressively generate scale matrix from assignments. To ensure the\nlower-triangular matrix has length of latent_size, scale_weights should\nbe a rank-one tensor with size latent_size * (latent_size + 1) / 2.\nscale_bias: Bias tensor to be added to scale tensor, with shape\n[latent_size, num_codes]. If scale weights are zero, initialize scale_bias\nto be log(exp(1.) / 2. - 1) so initial transformation is identity.\nnum_codes: Number of codes in codebook.\nsummary: Whether to save summaries.\nname: String used for name scope.\n\nReturns:\nflow_output: Transformed one-hot assignments.\ninverse_log_det_jacobian: Inverse log deteriminant of Jacobian corresponding\nto transformation.", "source": "codesearchnet"}
662{"code": "def build_global(self, global_node):\n\n \n config_block_lines = self.__build_config_block(\n global_node.config_block)\n return config.Global(config_block=config_block_lines)", "docstring": "parse `global` section, and return the config.Global\n\nArgs:\nglobal_node (TreeNode): `global` section treenode\n\nReturns:\nconfig.Global: an object", "source": "juraj-google-style"}
663{"code": "def register_many(self, *args):\n \n params = []\n for name in args:\n params.append(self.register(name))\n\n return params", "docstring": "Register many configuration names.\n\nArguments:\n*args: Config names as strings.\n\nReturns:\nlist: List of registered configs.", "source": "juraj-google-style"}
664{"code": "def _send(self, email_message):\n \n pre_send.send(self.__class__, message=email_message)\n\n if not email_message.recipients():\n return False\n\n from_email = sanitize_address(email_message.from_email,\n email_message.encoding)\n recipients = [sanitize_address(addr, email_message.encoding)\n for addr in email_message.recipients()]\n message = email_message.message().as_bytes(linesep='\\r\\n')\n\n try:\n result = self.conn.send_raw_email(\n Source=from_email,\n Destinations=recipients,\n RawMessage={\n 'Data': message\n }\n )\n message_id = result['MessageId']\n post_send.send(\n self.__class__,\n message=email_message,\n message_id=message_id\n )\n except ClientError:\n if not self.fail_silently:\n raise\n return False\n return True", "docstring": "Sends an individual message via the Amazon SES HTTP API.\n\nArgs:\nemail_message: A single Django EmailMessage object.\nReturns:\nTrue if the EmailMessage was sent successfully, otherwise False.\nRaises:\nClientError: An interaction with the Amazon SES HTTP API\nfailed.", "source": "juraj-google-style"}
665{"code": "def map(self, key_pattern, func, all_args, timeout=None):\n results = []\n keys = [make_key(key_pattern, func, args, {}) for args in all_args]\n cached = dict(zip(keys, self.get_many(keys)))\n cache_to_add = {}\n for (key, args) in zip(keys, all_args):\n val = cached[key]\n if (val is None):\n val = func(*args)\n cache_to_add[key] = (val if (val is not None) else NONE_RESULT)\n if (val == NONE_RESULT):\n val = None\n results.append(val)\n if cache_to_add:\n self.set_many(cache_to_add, timeout)\n return results", "docstring": "Cache return value of multiple calls.\n\nArgs:\nkey_pattern (str): the key pattern to use for generating\nkeys for caches of the decorated function.\nfunc (function): the function to call.\nall_args (list): a list of args to be used to make calls to\nthe function.\ntimeout (int): the cache timeout\n\nReturns:\nA list of the return values of the calls.\n\nExample::\n\ndef add(a, b):\nreturn a + b\n\ncache.map(key_pat, add, [(1, 2), (3, 4)]) == [3, 7]", "source": "codesearchnet"}
666{"code": "def forward(self, inputs: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor):\n mean = loc.transpose(-1, -2)\n mean = mean.unsqueeze(-2)\n mean = mean.repeat(1, 1, self.num_patches, 1)\n stdev = scale.transpose(-1, -2)\n stdev = stdev.unsqueeze(-2)\n stdev = stdev.repeat(1, 1, self.num_patches, 1)\n concat_stats = torch.cat([mean, stdev], dim=-1)\n concat_stats = self.map_scale_expansion(concat_stats)\n concat_stats = self.map_scale_compression(concat_stats)\n inputs = torch.cat([inputs, concat_stats], dim=-1)\n inputs = self.inverse_trans_expansion(inputs)\n inputs = self.inverse_trans_compression(inputs)\n return inputs", "docstring": "Args:\ninputs (`torch.Tensor` of shape `(batch_size, num_input_channels, num_patch, d_model)`)\nloc (`torch.Tensor` of shape `(batch_size, 1, num_input_channels)`)\nscale (`torch.Tensor` of shape `(batch_size, 1, num_input_channels)`)\nReturns:\n`torch.Tensor` of shape `(batch_size, num_input_channels, num_patch, d_model)`", "source": "github-repos"}
667{"code": "def _validate_ids(self, resource_ids):\n for resource_id in resource_ids:\n if (self._id_regex.fullmatch(resource_id) is None):\n LOGGER.debug('Invalid resource id requested: %s', resource_id)\n raise _ResponseFailed(self._status.INVALID_ID)", "docstring": "Validates a list of ids, raising a ResponseFailed error if invalid.\n\nArgs:\nresource_id (list of str): The ids to validate\n\nRaises:\nResponseFailed: The id was invalid, and a status of INVALID_ID\nwill be sent with the response.", "source": "codesearchnet"}
668{"code": "def _find_children_hints(call, graph_def):\n name_to_input_name, _, _ = _extract_graph_summary(graph_def)\n input_names, output_names = call.flattened_inputs_and_outputs()\n reachable_by_input = _bfs_for_reachable_nodes(input_names, name_to_input_name)\n reachable_by_output = _bfs_for_reachable_nodes(output_names, name_to_input_name)\n output_nodes_set = set(output_names)\n children_hints = []\n out = _graph_pb2.GraphDef()\n out.library.CopyFrom(graph_def.library)\n out.versions.CopyFrom(graph_def.versions)\n function_def_nodes = set()\n for node in graph_def.node:\n out.node.extend([_copy.deepcopy(node)])\n n = _tensor_name_base(node.name)\n if n in reachable_by_output:\n if n not in reachable_by_input and n not in output_nodes_set:\n if node.op == 'While' or node.op == 'StatelessWhile':\n body_name = node.attr['body'].func.name\n inputs_outside_loop = node.input\n for function_def in graph_def.library.function:\n if function_def.signature.name == body_name:\n function_inputs = function_def.signature.input_arg\n assert len(inputs_outside_loop) == len(function_inputs)\n nodes_mapping = {}\n for i, function_input in enumerate(function_inputs):\n nodes_mapping[function_input.name] = inputs_outside_loop[i]\n children_hints_in_loop, new_nodes = _find_children_hints_in_while_loop(function_def, nodes_mapping)\n function_def_nodes.update([x.name for x in new_nodes])\n children_hints.extend(children_hints_in_loop)\n out.node.extend(new_nodes)\n return (children_hints, out, function_def_nodes)", "docstring": "Find all children hints.\n\nFor a given OpHint, we find all children hints inside it, we also copy all the\nnodes inside function defs (if applicable) to the original graph_def, they are\nreturned in a list as well.\n\nArgs:\ncall: Parent OpHint that contains children ophints.\ngraph_def: Original graph def.\n\nReturns:\nOrdered children hints inside the parent ophint; new graph def that contains\nnodes inside function defs (if applicable); nodes inside function defs.", "source": "github-repos"}
669{"code": "def Lock(fd, path, blocking):\n \n operation = fcntl.LOCK_EX if blocking else fcntl.LOCK_EX | fcntl.LOCK_NB\n try:\n fcntl.flock(fd, operation)\n except IOError as e:\n if e.errno == errno.EWOULDBLOCK:\n raise IOError('Exception locking %s. File already locked.' % path)\n else:\n raise IOError('Exception locking %s. %s.' % (path, str(e)))", "docstring": "Lock the provided file descriptor.\n\nArgs:\nfd: int, the file descriptor of the file to lock.\npath: string, the name of the file to lock.\nblocking: bool, whether the function should return immediately.\n\nRaises:\nIOError, raised from flock while attempting to lock a file.", "source": "juraj-google-style"}
670{"code": "def cycle_iters(iters: t.List[t.Iterator], take: int=1) -> t.Iterator:\n while iters:\n for i, it in enumerate(iters):\n try:\n for j in range(take):\n logger.debug(f'yielding item {j!r} from iterable {i!r}.')\n yield next(it)\n except StopIteration:\n iters.remove(it)", "docstring": "Evenly cycle through a list of iterators.\n\nArgs:\niters: A list of iterators to evely cycle through.\ntake: Yield N items at a time. When not set to 1, this will yield\nmultiple items from the same collection.\n\nReturns:\nAn iteration across several iterators in a round-robin order.", "source": "github-repos"}
671{"code": "def _index(array, item, key=None):\n for (i, el) in enumerate(array):\n resolved_el = (key(el) if key else el)\n if (resolved_el == item):\n return i\n return (- 1)", "docstring": "Array search function.\n\nWritten, because ``.index()`` method for array doesn't have `key` parameter\nand raises `ValueError`, if the item is not found.\n\nArgs:\narray (list): List of items, which will be searched.\nitem (whatever): Item, which will be matched to elements in `array`.\nkey (function, default None): Function, which will be used for lookup\ninto each element in `array`.\n\nReturn:\nIndex of `item` in `array`, if the `item` is in `array`, else `-1`.", "source": "codesearchnet"}
672{"code": "def aggregate_and_return_name_for_output(self, fused_op_name, output_index, out_graphdef):\n del fused_op_name, output_index, out_graphdef\n raise RuntimeError('Unimplemented abstract method.')", "docstring": "Add node(s) to graph representing output operands and returns type.\n\nArgs:\nfused_op_name: name of the fused op stub name.\noutput_index: Output index that we are currently processing from stub.\nout_graphdef: The destination graphdef we are currently building up.\n\nReturns:\nThe datatype of this identity.\n\nRaises:\nRuntimeError: if the method is not implemented.", "source": "github-repos"}
673{"code": "def fixed_gaussian_prior_builder(getter, name, dtype=None, *args, **kwargs):\n del getter\n del args\n del kwargs\n loc = tf.constant(0.0, shape=(), dtype=dtype)\n scale = tf.constant(0.01, shape=(), dtype=dtype)\n return tfp.distributions.Normal(loc=loc, scale=scale, name='{}_prior_dist'.format(name))", "docstring": "A pre-canned builder for fixed gaussian prior distributions.\n\nGiven a true `getter` function and arguments forwarded from `tf.get_variable`,\nreturn a distribution object for a scalar-valued fixed gaussian prior which\nwill be broadcast over a variable of the requisite shape.\n\nArgs:\ngetter: The `getter` passed to a `custom_getter`. Please see the\ndocumentation for `tf.get_variable`.\nname: The `name` argument passed to `tf.get_variable`.\ndtype: The `dtype` argument passed to `tf.get_variable`.\n*args: See positional arguments passed to `tf.get_variable`.\n**kwargs: See keyword arguments passed to `tf.get_variable`.\n\nReturns:\nAn instance of `tfp.distributions.Normal` representing the prior\ndistribution over the variable in question.", "source": "codesearchnet"}
674{"code": "def fetch_raw(self, method, url, params=None, headers=None, data=None):\n if (not urllib.parse.urlparse(url).hostname.endswith('.google.com')):\n raise Exception('expected google.com domain')\n headers = (headers or {})\n headers.update(self._authorization_headers)\n return self._session.request(method, url, params=params, headers=headers, data=data, proxy=self._proxy)", "docstring": "Make an HTTP request using aiohttp directly.\n\nAutomatically uses configured HTTP proxy, and adds Google authorization\nheader and cookies.\n\nArgs:\nmethod (str): Request method.\nurl (str): Request URL.\nparams (dict): (optional) Request query string parameters.\nheaders (dict): (optional) Request headers.\ndata: (str): (optional) Request body data.\n\nReturns:\naiohttp._RequestContextManager: ContextManager for a HTTP response.\n\nRaises:\nSee ``aiohttp.ClientSession.request``.", "source": "codesearchnet"}
675{"code": "def set_charge_and_spin(self, charge, spin_multiplicity=None):\n self._charge = charge\n nelectrons = 0\n for site in self._sites:\n for (sp, amt) in site.species.items():\n if (not isinstance(sp, DummySpecie)):\n nelectrons += (sp.Z * amt)\n nelectrons -= charge\n self._nelectrons = nelectrons\n if spin_multiplicity:\n if (((nelectrons + spin_multiplicity) % 2) != 1):\n raise ValueError('Charge of {} and spin multiplicity of {} is not possible for this molecule'.format(self._charge, spin_multiplicity))\n self._spin_multiplicity = spin_multiplicity\n else:\n self._spin_multiplicity = (1 if ((nelectrons % 2) == 0) else 2)", "docstring": "Set the charge and spin multiplicity.\n\nArgs:\ncharge (int): Charge for the molecule. Defaults to 0.\nspin_multiplicity (int): Spin multiplicity for molecule.\nDefaults to None, which means that the spin multiplicity is\nset to 1 if the molecule has no unpaired electrons and to 2\nif there are unpaired electrons.", "source": "codesearchnet"}
676{"code": "def apply(self, s, active=None):\n \n if active is None:\n active = self.active\n return self.group.apply(s, active=active)", "docstring": "Apply the REPP's rewrite rules to the input string *s*.\n\nArgs:\ns (str): the input string to process\nactive (optional): a collection of external module names\nthat may be applied if called\nReturns:\na :class:`REPPResult` object containing the processed\nstring and characterization maps", "source": "juraj-google-style"}
677{"code": "def state_province_region(self, value=None):\n \n if value is not None:\n try:\n value = str(value)\n except ValueError:\n raise ValueError(\n 'value {} need to be of type str '\n 'for field `state_province_region`'.format(value))\n if ',' in value:\n raise ValueError('value should not contain a comma '\n 'for field `state_province_region`')\n\n self._state_province_region = value", "docstring": "Corresponds to IDD Field `state_province_region`\n\nArgs:\nvalue (str): value for IDD Field `state_province_region`\nif `value` is None it will not be checked against the\nspecification and is assumed to be a missing value\n\nRaises:\nValueError: if `value` is not a valid value", "source": "juraj-google-style"}
678{"code": "def get_artifact_url(context, task_id, path):\n if path.startswith('public/'):\n url = context.queue.buildUrl('getLatestArtifact', task_id, path)\n else:\n url = context.queue.buildSignedUrl('getLatestArtifact', task_id, path)\n return url", "docstring": "Get a TaskCluster artifact url.\n\nArgs:\ncontext (scriptworker.context.Context): the scriptworker context\ntask_id (str): the task id of the task that published the artifact\npath (str): the relative path of the artifact\n\nReturns:\nstr: the artifact url\n\nRaises:\nTaskClusterFailure: on failure.", "source": "codesearchnet"}
679{"code": "def alignment(layer, decay_ratio=2):\n\n def inner(T):\n batch_n = T(layer).get_shape().as_list()[0]\n arr = T(layer)\n accum = 0\n for d in [1, 2, 3, 4]:\n for i in range((batch_n - d)):\n (a, b) = (i, (i + d))\n (arr1, arr2) = (arr[a], arr[b])\n accum += (tf.reduce_mean(((arr1 - arr2) ** 2)) / (decay_ratio ** float(d)))\n return (- accum)\n return inner", "docstring": "Encourage neighboring images to be similar.\n\nWhen visualizing the interpolation between two objectives, it's often\ndesireable to encourage analagous boejcts to be drawn in the same position,\nto make them more comparable.\n\nThis term penalizes L2 distance between neighboring images, as evaluated at\nlayer.\n\nIn general, we find this most effective if used with a paramaterization that\nshares across the batch. (In fact, that works quite well by iteself, so this\nfunction may just be obselete.)\n\nArgs:\nlayer: layer to penalize at.\ndecay_ratio: how much to decay penalty as images move apart in batch.\n\nReturns:\nObjective.", "source": "codesearchnet"}
680{"code": "def as_text(bytes_or_text, encoding='utf-8'):\n \n if isinstance(bytes_or_text, _six.text_type):\n return bytes_or_text\n elif isinstance(bytes_or_text, bytes):\n return bytes_or_text.decode(encoding)\n else:\n raise TypeError('Expected binary or unicode string, got %r' % bytes_or_text)", "docstring": "Returns the given argument as a unicode string.\nArgs:\nbytes_or_text: A `bytes`, `str, or `unicode` object.\nencoding: A string indicating the charset for decoding unicode.\nReturns:\nA `unicode` (Python 2) or `str` (Python 3) object.\nRaises:\nTypeError: If `bytes_or_text` is not a binary or unicode string.", "source": "juraj-google-style"}
681{"code": "def _read_range(self, start, end=0):\n \n \n response = self._client.request(\n 'GET', self.name, headers=dict(Range=self._http_range(start, end)),\n timeout=self._TIMEOUT)\n\n if response.status_code == 416:\n \n return b''\n\n \n return _handle_http_errors(response).content", "docstring": "Read a range of bytes in stream.\n\nArgs:\nstart (int): Start stream position.\nend (int): End stream position.\n0 To not specify end.\n\nReturns:\nbytes: number of bytes read", "source": "juraj-google-style"}
682{"code": "def _cast_to_type_if_compatible(name, param_type, value):\n fail_msg = (\"Could not cast hparam '%s' of type '%s' from value %r\" % (name, param_type, value))\n if issubclass(param_type, type(None)):\n return value\n if (issubclass(param_type, (six.string_types, six.binary_type)) and (not isinstance(value, (six.string_types, six.binary_type)))):\n raise ValueError(fail_msg)\n if (issubclass(param_type, bool) != isinstance(value, bool)):\n raise ValueError(fail_msg)\n if (issubclass(param_type, numbers.Integral) and (not isinstance(value, numbers.Integral))):\n raise ValueError(fail_msg)\n if (issubclass(param_type, numbers.Number) and (not isinstance(value, numbers.Number))):\n raise ValueError(fail_msg)\n return param_type(value)", "docstring": "Cast hparam to the provided type, if compatible.\n\nArgs:\nname: Name of the hparam to be cast.\nparam_type: The type of the hparam.\nvalue: The value to be cast, if compatible.\n\nReturns:\nThe result of casting `value` to `param_type`.\n\nRaises:\nValueError: If the type of `value` is not compatible with param_type.\n* If `param_type` is a string type, but `value` is not.\n* If `param_type` is a boolean, but `value` is not, or vice versa.\n* If `param_type` is an integer type, but `value` is not.\n* If `param_type` is a float type, but `value` is not a numeric type.", "source": "codesearchnet"}
683{"code": "def prepare(self, variables):\n initializedsteps = []\n if (variables is None):\n variables = dict()\n for (step, params, _resources, _files) in self.steps:\n new_params = _complete_parameters(params, variables)\n initializedsteps.append(step(new_params))\n return initializedsteps", "docstring": "Initialize all steps in this recipe using their parameters.\n\nArgs:\nvariables (dict): A dictionary of global variable definitions\nthat may be used to replace or augment the parameters given\nto each step.\n\nReturns:\nlist of RecipeActionObject like instances: The list of instantiated\nsteps that can be used to execute this recipe.", "source": "codesearchnet"}
684{"code": "def parse(raw_config):\n config_dict = yaml_to_ordered_dict(raw_config)\n if config_dict:\n for top_level_key in ['stacks', 'pre_build', 'post_build', 'pre_destroy', 'post_destroy']:\n top_level_value = config_dict.get(top_level_key)\n if isinstance(top_level_value, dict):\n tmp_list = []\n for (key, value) in top_level_value.items():\n tmp_dict = copy.deepcopy(value)\n if (top_level_key == 'stacks'):\n tmp_dict['name'] = key\n tmp_list.append(tmp_dict)\n config_dict[top_level_key] = tmp_list\n try:\n return Config(config_dict, strict=True)\n except SchematicsError as e:\n raise exceptions.InvalidConfig(e.errors)", "docstring": "Parse a raw yaml formatted stacker config.\n\nArgs:\nraw_config (str): the raw stacker configuration string in yaml format.\n\nReturns:\n:class:`Config`: the parsed stacker config.", "source": "codesearchnet"}
685{"code": "def iterable(obj, strok=False):\n try:\n iter(obj)\n except Exception:\n return False\n else:\n return (strok or (not isinstance(obj, six.string_types)))", "docstring": "Checks if the input implements the iterator interface. An exception is made\nfor strings, which return False unless `strok` is True\n\nArgs:\nobj (object): a scalar or iterable input\n\nstrok (bool): if True allow strings to be interpreted as iterable\n\nReturns:\nbool: True if the input is iterable\n\nExample:\n>>> obj_list = [3, [3], '3', (3,), [3, 4, 5], {}]\n>>> result = [iterable(obj) for obj in obj_list]\n>>> assert result == [False, True, False, True, True, True]\n>>> result = [iterable(obj, strok=True) for obj in obj_list]\n>>> assert result == [False, True, True, True, True, True]", "source": "codesearchnet"}
686{"code": "def __get_first_available_id(self):\n traps = self.get_all()\n if traps:\n used_ids = [0]\n for trap in traps:\n used_uris = trap.get('uri')\n used_ids.append(int(used_uris.split('/')[(- 1)]))\n used_ids.sort()\n return self.__findFirstMissing(used_ids, 0, (len(used_ids) - 1))\n else:\n return 1", "docstring": "Private method to get the first available id.\nThe id can only be an integer greater than 0.\n\nReturns:\nint: The first available id", "source": "codesearchnet"}
687{"code": "def get_thread(self, thread_id, update_if_cached=True, raise_404=False):\n \n \n cached_thread = self._thread_cache.get(thread_id)\n if cached_thread:\n if update_if_cached:\n cached_thread.update()\n return cached_thread\n\n res = self._requests_session.get(\n self._url.thread_api_url(\n thread_id = thread_id\n )\n )\n\n \n if raise_404:\n res.raise_for_status()\n elif not res.ok:\n return None\n\n thread = Thread._from_request(self, res, thread_id)\n self._thread_cache[thread_id] = thread\n\n return thread", "docstring": "Get a thread from 4chan via 4chan API.\n\nArgs:\nthread_id (int): Thread ID\nupdate_if_cached (bool): Whether the thread should be updated if it's already in our cache\nraise_404 (bool): Raise an Exception if thread has 404'd\n\nReturns:\n:class:`basc_py4chan.Thread`: Thread object", "source": "juraj-google-style"}
688{"code": "def configure_interface(self, name, commands):\n \n commands = make_iterable(commands)\n commands.insert(0, 'interface %s' % name)\n return self.configure(commands)", "docstring": "Configures the specified interface with the commands\n\nArgs:\nname (str): The interface name to configure\ncommands: The commands to configure in the interface\n\nReturns:\nTrue if the commands completed successfully", "source": "juraj-google-style"}
689{"code": "def convert_timedelta_type(obj):\n if isinstance(obj, dt.timedelta):\n return (obj.total_seconds() * 1000.0)\n elif isinstance(obj, np.timedelta64):\n return (obj / NP_MS_DELTA)", "docstring": "Convert any recognized timedelta value to floating point absolute\nmilliseconds.\n\nArg:\nobj (object) : the object to convert\n\nReturns:\nfloat : milliseconds", "source": "codesearchnet"}
690{"code": "def get_path_spec(self, path, action=None):\n path_spec = None\n path_name = None\n for base_path in self.paths.keys():\n if (path == base_path):\n path_spec = self.paths[base_path]\n path_name = base_path\n if (path_spec is None):\n for base_path in self.paths.keys():\n regex_from_path = re.compile((re.sub('{[^/]*}', '([^/]*)', base_path) + '$'))\n if re.match(regex_from_path, path):\n path_spec = self.paths[base_path]\n path_name = base_path\n if ((path_spec is not None) and (action is not None)):\n if (action not in path_spec.keys()):\n return (None, None)\n else:\n path_spec = path_spec[action]\n return (path_name, path_spec)", "docstring": "Get the specification matching with the given path.\n\nArgs:\npath: path we want the specification.\naction: get the specification for the given action.\n\nReturns:\nA tuple with the base name of the path and the specification.\nOr (None, None) if no specification is found.", "source": "codesearchnet"}
691{"code": "def ParseFileLNKFile(\n self, parser_mediator, file_object, display_name):\n \n lnk_file = pylnk.file()\n lnk_file.set_ascii_codepage(parser_mediator.codepage)\n\n try:\n lnk_file.open_file_object(file_object)\n except IOError as exception:\n parser_mediator.ProduceExtractionWarning(\n 'unable to open file with error: {0!s}'.format(exception))\n return\n\n link_target = None\n if lnk_file.link_target_identifier_data:\n \n \n display_name = parser_mediator.GetFilename()\n shell_items_parser = shell_items.ShellItemsParser(display_name)\n shell_items_parser.ParseByteStream(\n parser_mediator, lnk_file.link_target_identifier_data,\n codepage=parser_mediator.codepage)\n\n link_target = shell_items_parser.CopyToPath()\n\n event_data = WinLnkLinkEventData()\n event_data.birth_droid_file_identifier = (\n lnk_file.birth_droid_file_identifier)\n event_data.birth_droid_volume_identifier = (\n lnk_file.birth_droid_volume_identifier)\n event_data.command_line_arguments = lnk_file.command_line_arguments\n event_data.description = lnk_file.description\n event_data.drive_serial_number = lnk_file.drive_serial_number\n event_data.drive_type = lnk_file.drive_type\n event_data.droid_file_identifier = lnk_file.droid_file_identifier\n event_data.droid_volume_identifier = lnk_file.droid_volume_identifier\n event_data.env_var_location = lnk_file.environment_variables_location\n event_data.file_attribute_flags = lnk_file.file_attribute_flags\n event_data.file_size = lnk_file.file_size\n event_data.icon_location = lnk_file.icon_location\n event_data.link_target = link_target\n event_data.local_path = lnk_file.local_path\n event_data.network_path = lnk_file.network_path\n event_data.relative_path = lnk_file.relative_path\n event_data.volume_label = lnk_file.volume_label\n event_data.working_directory = lnk_file.working_directory\n\n access_time = lnk_file.get_file_access_time_as_integer()\n if access_time != 0:\n date_time = dfdatetime_filetime.Filetime(timestamp=access_time)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n creation_time = lnk_file.get_file_creation_time_as_integer()\n if creation_time != 0:\n date_time = dfdatetime_filetime.Filetime(timestamp=creation_time)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n modification_time = lnk_file.get_file_modification_time_as_integer()\n if modification_time != 0:\n date_time = dfdatetime_filetime.Filetime(timestamp=modification_time)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n if access_time == 0 and creation_time == 0 and modification_time == 0:\n date_time = dfdatetime_semantic_time.SemanticTime('Not set')\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_NOT_A_TIME)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n if lnk_file.droid_file_identifier:\n try:\n self._ParseDistributedTrackingIdentifier(\n parser_mediator, lnk_file.droid_file_identifier, display_name)\n except (TypeError, ValueError) as exception:\n parser_mediator.ProduceExtractionWarning(\n 'unable to read droid file identifier with error: {0!s}.'.format(\n exception))\n\n if lnk_file.birth_droid_file_identifier:\n try:\n self._ParseDistributedTrackingIdentifier(\n parser_mediator, lnk_file.birth_droid_file_identifier, display_name)\n except (TypeError, ValueError) as exception:\n parser_mediator.ProduceExtractionWarning((\n 'unable to read birth droid file identifier with error: '\n '{0!s}.').format(exception))\n\n lnk_file.close()", "docstring": "Parses a Windows Shortcut (LNK) file-like object.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nfile_object (dfvfs.FileIO): file-like object.\ndisplay_name (str): display name.", "source": "juraj-google-style"}
692{"code": "def merge(prior, latest):\n if (not _buckets_nearly_equal(prior, latest)):\n _logger.error(u'Bucket options do not match. From %s To: %s', prior, latest)\n raise ValueError(u'Bucket options do not match')\n if (len(prior.bucketCounts) != len(latest.bucketCounts)):\n _logger.error(u'Bucket count sizes do not match. From %s To: %s', prior, latest)\n raise ValueError(u'Bucket count sizes do not match')\n if (prior.count <= 0):\n return\n old_count = latest.count\n old_mean = latest.mean\n old_summed_variance = latest.sumOfSquaredDeviation\n bucket_counts = latest.bucketCounts\n latest.count += prior.count\n latest.maximum = max(prior.maximum, latest.maximum)\n latest.minimum = min(prior.minimum, latest.minimum)\n latest.mean = (((old_count * old_mean) + (prior.count * prior.mean)) / latest.count)\n latest.sumOfSquaredDeviation = (((old_summed_variance + prior.sumOfSquaredDeviation) + (old_count * ((latest.mean - old_mean) ** 2))) + (prior.count * ((latest.mean - prior.mean) ** 2)))\n for (i, (x, y)) in enumerate(zip(prior.bucketCounts, bucket_counts)):\n bucket_counts[i] = (x + y)", "docstring": "Merge `prior` into `latest`.\n\nN.B, this mutates latest. It ensures that the statistics and histogram are\nupdated to correctly include the original values from both instances.\n\nArgs:\nprior (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):\nan instance\nlatest (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):\nan instance to be updated\n\nRaises:\nValueError: if the bucket options of `prior` and `latest` do not match\nValueError: if the bucket counts of `prior` and `latest` do not match", "source": "codesearchnet"}
693{"code": "def GrabFileSystem(self, path_spec):\n identifier = self._GetFileSystemCacheIdentifier(path_spec)\n self._file_system_cache.GrabObject(identifier)", "docstring": "Grabs a cached file system object defined by path specification.\n\nArgs:\npath_spec (PathSpec): path specification.", "source": "codesearchnet"}
694{"code": "def credits(self, **kwargs):\n \n path = self._get_id_path('credits')\n\n response = self._GET(path, kwargs)\n self._set_attrs_to_values(response)\n return response", "docstring": "Get the cast and crew information for a specific movie id.\n\nArgs:\nappend_to_response: (optional) Comma separated, any movie method.\n\nReturns:\nA dict representation of the JSON returned from the API.", "source": "juraj-google-style"}
695{"code": "def ias60(msg):\n \n d = hex2bin(data(msg))\n\n if d[12] == '0':\n return None\n\n ias = bin2int(d[13:23]) \n return ias", "docstring": "Indicated airspeed\n\nArgs:\nmsg (String): 28 bytes hexadecimal message (BDS60) string\n\nReturns:\nint: indicated airspeed in knots", "source": "juraj-google-style"}
696{"code": "def sparse_retain(sp_input, to_retain):\n sp_input = _convert_to_sparse_tensor(sp_input)\n to_retain = ops.convert_to_tensor(to_retain)\n retain_shape = to_retain.get_shape()\n retain_shape.assert_has_rank(1)\n if sp_input.values.get_shape().dims is not None:\n sp_input.values.get_shape().dims[0].assert_is_compatible_with(tensor_shape.dimension_at_index(retain_shape, 0))\n where_true = array_ops.reshape(array_ops.where_v2(to_retain), [-1])\n new_indices = array_ops.gather(sp_input.indices, where_true)\n new_values = array_ops.gather(sp_input.values, where_true)\n return sparse_tensor.SparseTensor(new_indices, new_values, array_ops.identity(sp_input.dense_shape))", "docstring": "Retains specified non-empty values within a `SparseTensor`.\n\nFor example, if `sp_input` has shape `[4, 5]` and 4 non-empty string values:\n\n[0, 1]: a\n[0, 3]: b\n[2, 0]: c\n[3, 1]: d\n\nand `to_retain = [True, False, False, True]`, then the output will\nbe a `SparseTensor` of shape `[4, 5]` with 2 non-empty values:\n\n[0, 1]: a\n[3, 1]: d\n\nArgs:\nsp_input: The input `SparseTensor` with `N` non-empty elements.\nto_retain: A bool vector of length `N` with `M` true values.\n\nReturns:\nA `SparseTensor` with the same shape as the input and `M` non-empty\nelements corresponding to the true positions in `to_retain`.\n\nRaises:\nTypeError: If `sp_input` is not a `SparseTensor`.", "source": "github-repos"}
697{"code": "def get_submission_ids(self, tournament=1):\n \n query = \n arguments = {'tournament': tournament}\n data = self.raw_query(query, arguments)['data']['rounds'][0]\n if data is None:\n return None\n mapping = {item['username']: item['submissionId']\n for item in data['leaderboard']}\n return mapping", "docstring": "Get dict with username->submission_id mapping.\n\nArgs:\ntournament (int): ID of the tournament (optional, defaults to 1)\n\nReturns:\ndict: username->submission_id mapping, string->string\n\nExample:\n>>> NumerAPI().get_submission_ids()\n{'1337ai': '93c46857-fed9-4594-981e-82db2b358daf',\n'1x0r': '108c7601-822c-4910-835d-241da93e2e24',\n...\n}", "source": "juraj-google-style"}
698{"code": "def _delete_example(self, request):\n \n index = int(request.args.get('index'))\n if index >= len(self.examples):\n return http_util.Respond(request, {'error': 'invalid index provided'},\n 'application/json', code=400)\n del self.examples[index]\n self.updated_example_indices = set([\n i if i < index else i - 1 for i in self.updated_example_indices])\n self.generate_sprite([ex.SerializeToString() for ex in self.examples])\n return http_util.Respond(request, {}, 'application/json')", "docstring": "Deletes the specified example.\n\nArgs:\nrequest: A request that should contain 'index'.\n\nReturns:\nAn empty response.", "source": "juraj-google-style"}
699{"code": "def restore_app_connection(self, port=None):", "docstring": "Reconnects to the app after device USB was disconnected.\n\nInstead of creating new instance of the client:\n- Uses the given port (or finds a new available host_port if none is\ngiven).\n- Tries to connect to remote server with selected port.\n\nMust be implemented by subclasses.\n\nArgs:\nport: If given, this is the host port from which to connect to remote\ndevice port. If not provided, find a new available port as host\nport.\n\nRaises:\nAppRestoreConnectionError: When the app was not able to be\nreconnected.", "source": "github-repos"}
700{"code": "def nac_p(msg):\n \n tc = typecode(msg)\n\n if tc not in [29, 31]:\n raise RuntimeError(\"%s: Not a target state and status message, \\\n or operation status message, expecting TC = 29 or 31\" % msg)\n\n msgbin = common.hex2bin(msg)\n\n if tc == 29:\n NACp = common.bin2int(msgbin[71:75])\n elif tc == 31:\n NACp = common.bin2int(msgbin[76:80])\n\n try:\n EPU = uncertainty.NACp[NACp]['EPU']\n VEPU = uncertainty.NACp[NACp]['VEPU']\n except KeyError:\n EPU, VEPU = uncertainty.NA, uncertainty.NA\n\n return EPU, VEPU", "docstring": "Calculate NACp, Navigation Accuracy Category - Position\n\nArgs:\nmsg (string): 28 bytes hexadecimal message string, TC = 29 or 31\n\nReturns:\nint or string: 95% horizontal accuracy bounds, Estimated Position Uncertainty\nint or string: 95% vertical accuracy bounds, Vertical Estimated Position Uncertainty", "source": "juraj-google-style"}
701{"code": "def register_module_for_export(module, export_name):\n for (used_name, _) in tf_v1.get_collection(_EXPORT_MODULES_COLLECTION):\n if (used_name == export_name):\n raise ValueError(('There is already a module registered to be exported as %r' % export_name))\n tf_v1.add_to_collection(_EXPORT_MODULES_COLLECTION, (export_name, module))", "docstring": "Register a Module to be exported under `export_name`.\n\n\nThis function registers `module` to be exported by `LatestModuleExporter`\nunder a subdirectory named `export_name`.\n\nNote that `export_name` must be unique for each module exported from the\ncurrent graph. It only controls the export subdirectory name and it has\nno scope effects such as the `name` parameter during Module instantiation.\n\nArgs:\nmodule: Module instance to be exported.\nexport_name: subdirectory name to use when performing the export.\n\nRaises:\nValueError: if `export_name` is already taken in the current graph.", "source": "codesearchnet"}
702{"code": "def verify_signature(public_key, signature, hash, hash_algo):\n \n hash_algo = _hash_algorithms[hash_algo]\n try:\n return get_publickey(public_key).verify(\n signature,\n hash,\n padding.PKCS1v15(),\n utils.Prehashed(hash_algo),\n ) is None\n except InvalidSignature:\n return False", "docstring": "Verify the given signature is correct for the given hash and public key.\n\nArgs:\npublic_key (str): PEM encoded public key\nsignature (bytes): signature to verify\nhash (bytes): hash of data\nhash_algo (str): hash algorithm used\n\nReturns:\nTrue if the signature is valid, False otherwise", "source": "juraj-google-style"}
703{"code": "def get_video_features(self, pixel_values: torch.FloatTensor, vision_feature_layer: Union[int, List[int]], vision_feature_select_strategy: str):\n batch_size, frames, channels, height, width = pixel_values.shape\n pixel_values = pixel_values.view(batch_size * frames, channels, height, width)\n video_features = self.vision_tower(pixel_values, output_hidden_states=True)\n if isinstance(vision_feature_layer, int):\n selected_video_feature = video_features.hidden_states[vision_feature_layer]\n else:\n hs_pool = [video_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]\n selected_video_feature = torch.cat(hs_pool, dim=-1)\n if vision_feature_select_strategy == 'default':\n selected_video_feature = selected_video_feature[:, 1:]\n elif vision_feature_select_strategy == 'full':\n selected_video_feature = selected_video_feature\n video_features = self.multi_modal_projector(selected_video_feature)\n video_features = self.apply_pooling(video_features)\n video_features = video_features.reshape(batch_size, frames * video_features.shape[1], -1)\n return video_features", "docstring": "Obtains video last hidden states from the vision tower, apply multimodal projection and pooling.\n\nArgs:\npixel_values (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)\nThe tensors corresponding to the input video.\nvision_feature_layer (`Union[int, List[int]], *optional*, defaults to -2`):\nThe index of the layer to select the vision feature. If multiple indices are provided,\nthe vision feature of the corresponding indices will be concatenated to form the\nvision features.\nvision_feature_select_strategy (`str`):\nThe feature selection strategy used to select the vision feature from the vision backbone.\nCan be one of `\"default\"` or `\"full\"`\nReturns:\nvideo_features (List[`torch.Tensor`]): List of video feature tensor, each contains all the visual feature of all patches\nand are of shape `(num_videos, video_length, embed_dim)`).", "source": "github-repos"}
704{"code": "def extract_paths(disk_path, disk_root, paths, ignore_nopath):\n with guestfs_conn_mount_ro(disk_path, disk_root) as conn:\n for (guest_path, host_path) in paths:\n msg = 'Extracting guestfs:\n LOGGER.debug(msg)\n try:\n _copy_path(conn, guest_path, host_path)\n except ExtractPathNoPathError as err:\n if ignore_nopath:\n LOGGER.debug('%s - ignoring', err)\n else:\n raise", "docstring": "Extract paths from a disk using guestfs\n\nArgs:\ndisk_path(str): path to the disk\ndisk_root(str): root partition\npaths(list of tuples): files to extract in\n`[(src1, dst1), (src2, dst2)...]` format, if ``srcN`` is a\ndirectory in the guest, and ``dstN`` does not exist on the host,\nit will be created. If ``srcN`` is a file on the guest, it will be\ncopied exactly to ``dstN``\nignore_nopath(bool): If set to True, ignore paths in the guest that\ndo not exit\n\nReturns:\nNone\n\nRaises:\n:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing\npath was found on the guest, and `ignore_nopath` is False.\n:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures.", "source": "codesearchnet"}
705{"code": "def delete_item(self, key: InstanceKey) -> \"InstanceNode\":\n \n if not isinstance(self.value, StructuredValue):\n raise InstanceValueError(self.json_pointer(), \"scalar value\")\n newval = self.value.copy()\n try:\n del newval[key]\n except (KeyError, IndexError, TypeError):\n raise NonexistentInstance(self.json_pointer(),\n f\"item '{key}'\") from None\n return self._copy(newval)", "docstring": "Delete an item (member or entry) from receiver's value.\n\nArgs:\nkey: Key of the item (instance name or index).\n\nRaises:\nNonexistentInstance: If receiver's value doesn't contain the item.\nInstanceValueError: If the receiver's value is a scalar.", "source": "juraj-google-style"}
706{"code": "def broadcast_to(rt_input, shape, broadcast_inner_dimensions=True):\n if not isinstance(shape, RaggedTensorDynamicShape):\n raise TypeError('shape must be a RaggedTensorDynamicShape')\n rt_input = ragged_tensor.convert_to_tensor_or_ragged_tensor(rt_input)\n if shape.num_partitioned_dimensions == 0:\n return _broadcast_to_uniform_shape(rt_input, shape, broadcast_inner_dimensions)\n else:\n return _broadcast_to_ragged_shape(rt_input, shape, broadcast_inner_dimensions)", "docstring": "Broadcasts a potentially ragged tensor to a ragged shape.\n\nTiles `rt_input` as necessary to match the given shape.\n\nBehavior is undefined if `rt_input` is not broadcast-compatible with `shape`.\n\nArgs:\nrt_input: The potentially ragged tensor to broadcast.\nshape: A `RaggedTensorDynamicShape`\nbroadcast_inner_dimensions: If false, then inner dimensions will not be\ntiled.\n\nReturns:\nA potentially ragged tensor whose values are taken from\n`rt_input`, and whose shape matches `shape`.", "source": "github-repos"}
707{"code": "def _make_cloud_datastore_context(app_id, external_app_ids=()):\n from . import model\n if (not datastore_pbs._CLOUD_DATASTORE_ENABLED):\n raise datastore_errors.BadArgumentError(datastore_pbs.MISSING_CLOUD_DATASTORE_MESSAGE)\n import googledatastore\n try:\n from google.appengine.datastore import cloud_datastore_v1_remote_stub\n except ImportError:\n from google3.apphosting.datastore import cloud_datastore_v1_remote_stub\n current_app_id = os.environ.get('APPLICATION_ID', None)\n if (current_app_id and (current_app_id != app_id)):\n raise ValueError(('Cannot create a Cloud Datastore context that connects to an application (%s) that differs from the application already connected to (%s).' % (app_id, current_app_id)))\n os.environ['APPLICATION_ID'] = app_id\n id_resolver = datastore_pbs.IdResolver(((app_id,) + tuple(external_app_ids)))\n project_id = id_resolver.resolve_project_id(app_id)\n endpoint = googledatastore.helper.get_project_endpoint_from_env(project_id)\n datastore = googledatastore.Datastore(project_endpoint=endpoint, credentials=googledatastore.helper.get_credentials_from_env())\n conn = model.make_connection(_api_version=datastore_rpc._CLOUD_DATASTORE_V1, _id_resolver=id_resolver)\n try:\n stub = cloud_datastore_v1_remote_stub.CloudDatastoreV1RemoteStub(datastore)\n apiproxy_stub_map.apiproxy.RegisterStub(datastore_rpc._CLOUD_DATASTORE_V1, stub)\n except:\n pass\n try:\n apiproxy_stub_map.apiproxy.RegisterStub('memcache', _ThrowingStub())\n except:\n pass\n try:\n apiproxy_stub_map.apiproxy.RegisterStub('taskqueue', _ThrowingStub())\n except:\n pass\n return make_context(conn=conn)", "docstring": "Creates a new context to connect to a remote Cloud Datastore instance.\n\nThis should only be used outside of Google App Engine.\n\nArgs:\napp_id: The application id to connect to. This differs from the project\nid as it may have an additional prefix, e.g. \"s~\" or \"e~\".\nexternal_app_ids: A list of apps that may be referenced by data in your\napplication. For example, if you are connected to s~my-app and store keys\nfor s~my-other-app, you should include s~my-other-app in the external_apps\nlist.\nReturns:\nAn ndb.Context that can connect to a Remote Cloud Datastore. You can use\nthis context by passing it to ndb.set_context.", "source": "codesearchnet"}
708{"code": "def _get_mu_tensor(self):\n root = self._get_cubic_root()\n dr = (self._h_max / self._h_min)\n mu = tf.maximum((root ** 2), (((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1)) ** 2))\n return mu", "docstring": "Get the min mu which minimize the surrogate.\n\nReturns:\nThe mu_t.", "source": "codesearchnet"}
709{"code": "def exec_inspect(self, exec_id):\n if isinstance(exec_id, dict):\n exec_id = exec_id.get('Id')\n res = self._get(self._url('/exec/{0}/json', exec_id))\n return self._result(res, True)", "docstring": "Return low-level information about an exec command.\n\nArgs:\nexec_id (str): ID of the exec instance\n\nReturns:\n(dict): Dictionary of values returned by the endpoint.\n\nRaises:\n:py:class:`docker.errors.APIError`\nIf the server returns an error.", "source": "codesearchnet"}
710{"code": "def remove_binding(site, hostheader='', ipaddress='*', port=80):\n \n name = _get_binding_info(hostheader, ipaddress, port)\n current_bindings = list_bindings(site)\n\n if name not in current_bindings:\n log.debug('Binding already absent: %s', name)\n return True\n ps_cmd = ['Remove-WebBinding',\n '-HostHeader', \"'{0}'\".format(hostheader),\n '-IpAddress', \"'{0}'\".format(ipaddress),\n '-Port', \"'{0}'\".format(port)]\n\n cmd_ret = _srvmgr(ps_cmd)\n\n if cmd_ret['retcode'] != 0:\n msg = 'Unable to remove binding: {0}\\nError: {1}' \\\n ''.format(site, cmd_ret['stderr'])\n raise CommandExecutionError(msg)\n\n if name not in list_bindings(site):\n log.debug('Binding removed successfully: %s', site)\n return True\n\n log.error('Unable to remove binding: %s', site)\n return False", "docstring": "Remove an IIS binding.\n\nArgs:\nsite (str): The IIS site name.\nhostheader (str): The host header of the binding.\nipaddress (str): The IP address of the binding.\nport (int): The TCP port of the binding.\n\nReturns:\nbool: True if successful, otherwise False\n\nCLI Example:\n\n.. code-block:: bash\n\nsalt '*' win_iis.remove_binding site='site0' hostheader='example.com' ipaddress='*' port='80'", "source": "juraj-google-style"}
711{"code": "def get_config(self, name):\n if (name not in self.registry):\n msg = \"Given config name '{}' is not registered.\"\n raise NotRegisteredError(msg.format(name))\n return copy.deepcopy(self.registry[name])", "docstring": "Return a registred configuration for given config name.\n\nArguments:\nname (string): A registred config name.\n\nRaises:\nNotRegisteredError: If given config name does not exist in\nregistry.\n\nReturns:\ndict: Configuration.", "source": "codesearchnet"}
712{"code": "def read(self, key):\n \n key = quote(key, safe='~')\n url = '/internal/playbooks/keyValue/{}'.format(key)\n r = self.tcex.session.get(url)\n data = r.content\n if data is not None and not isinstance(data, str):\n data = str(r.content, 'utf-8')\n return data", "docstring": "Read data from remote KV store for the provided key.\n\nArgs:\nkey (string): The key to read in remote KV store.\n\nReturns:\n(any): The response data from the remote KV store.", "source": "juraj-google-style"}
713{"code": "def _handle_offset_response(self, future, response):\n timestamp_offset_map = {}\n for (topic, part_data) in response.topics:\n for partition_info in part_data:\n (partition, error_code) = partition_info[:2]\n partition = TopicPartition(topic, partition)\n error_type = Errors.for_code(error_code)\n if (error_type is Errors.NoError):\n if (response.API_VERSION == 0):\n offsets = partition_info[2]\n assert (len(offsets) <= 1), 'Expected OffsetResponse with one offset'\n if (not offsets):\n offset = UNKNOWN_OFFSET\n else:\n offset = offsets[0]\n log.debug('Handling v0 ListOffsetResponse response for %s. Fetched offset %s', partition, offset)\n if (offset != UNKNOWN_OFFSET):\n timestamp_offset_map[partition] = (offset, None)\n else:\n (timestamp, offset) = partition_info[2:]\n log.debug('Handling ListOffsetResponse response for %s. Fetched offset %s, timestamp %s', partition, offset, timestamp)\n if (offset != UNKNOWN_OFFSET):\n timestamp_offset_map[partition] = (offset, timestamp)\n elif (error_type is Errors.UnsupportedForMessageFormatError):\n log.debug('Cannot search by timestamp for partition %s because the message format version is before 0.10.0', partition)\n elif (error_type is Errors.NotLeaderForPartitionError):\n log.debug('Attempt to fetch offsets for partition %s failed due to obsolete leadership information, retrying.', partition)\n future.failure(error_type(partition))\n return\n elif (error_type is Errors.UnknownTopicOrPartitionError):\n log.warning(('Received unknown topic or partition error in ListOffset request for partition %s. The topic/partition ' + 'may not exist or the user may not have Describe access to it.'), partition)\n future.failure(error_type(partition))\n return\n else:\n log.warning('Attempt to fetch offsets for partition %s failed due to: %s', partition, error_type)\n future.failure(error_type(partition))\n return\n if (not future.is_done):\n future.success(timestamp_offset_map)", "docstring": "Callback for the response of the list offset call above.\n\nArguments:\nfuture (Future): the future to update based on response\nresponse (OffsetResponse): response from the server\n\nRaises:\nAssertionError: if response does not match partition", "source": "codesearchnet"}
714{"code": "def get_full_url(self, url):\n \n \n request = Request('GET', url)\n preparedrequest = self.session.prepare_request(request)\n return preparedrequest.url", "docstring": "Get full url including any additional parameters\n\nArgs:\nurl (str): URL for which to get full url\n\nReturns:\nstr: Full url including any additional parameters", "source": "juraj-google-style"}
715{"code": "def business_days_between(self, from_dates, to_dates):\n from_biz, from_is_bizday = self._to_biz_space(dt.convert_to_date_tensor(from_dates).ordinal())\n to_biz, to_is_bizday = self._to_biz_space(dt.convert_to_date_tensor(to_dates).ordinal())\n from_biz = tf.where(from_is_bizday, from_biz, from_biz + 1)\n to_biz = tf.where(to_is_bizday, to_biz, to_biz + 1)\n return tf.math.maximum(to_biz - from_biz, 0)", "docstring": "Calculates number of business between pairs of dates.\n\nFor each pair, the initial date is included in the difference, and the final\ndate is excluded. If the final date is the same or earlier than the initial\ndate, zero is returned.\n\nArgs:\nfrom_dates: `DateTensor` of initial dates.\nto_dates: `DateTensor` of final dates, should be broadcastable to\n`from_dates`.\n\nReturns:\nAn int32 Tensor with the number of business days between the\ncorresponding pairs of dates.", "source": "github-repos"}
716{"code": "def get_optional_artifacts_per_task_id(upstream_artifacts):\n \n \n \n optional_artifacts_per_task_id = {}\n\n for artifact_definition in upstream_artifacts:\n if artifact_definition.get('optional', False) is True:\n task_id = artifact_definition['taskId']\n artifacts_paths = artifact_definition['paths']\n\n add_enumerable_item_to_dict(\n dict_=optional_artifacts_per_task_id,\n key=task_id, item=artifacts_paths\n )\n\n return optional_artifacts_per_task_id", "docstring": "Return every optional artifact defined in ``upstream_artifacts``, ordered by taskId.\n\nArgs:\nupstream_artifacts: the list of upstream artifact definitions\n\nReturns:\ndict: list of paths to downloaded artifacts ordered by taskId", "source": "juraj-google-style"}
717{"code": "def find_executable(cls, name, check_syspaths=False):\n \n exe = which(name)\n\n if not exe and check_syspaths:\n paths = cls.get_syspaths()\n env = os.environ.copy()\n env[\"PATH\"] = os.pathsep.join(paths)\n exe = which(name, env=env)\n\n if not exe:\n raise RuntimeError(\"Couldn't find executable '%s'.\" % name)\n return exe", "docstring": "Find an executable.\n\nArgs:\nname (str): Program name.\ncheck_syspaths (bool): If True, check the standard system paths as\nwell, if program was not found on current $PATH.\n\nReturns:\nstr: Full filepath of executable.", "source": "juraj-google-style"}
718{"code": "def wait_for_other_workers(self):\n if not self._worker_barrier:\n return\n self._worker_barrier.wait()", "docstring": "Waits for other workers to reach the same call to this method.\n\nRaises:\nValueError: if `worker_barrier` is not passed to the __init__ method.", "source": "github-repos"}
719{"code": "def _validate_user_inputs(self, attributes=None, event_tags=None):\n if (attributes and (not validator.are_attributes_valid(attributes))):\n self.logger.error('Provided attributes are in an invalid format.')\n self.error_handler.handle_error(exceptions.InvalidAttributeException(enums.Errors.INVALID_ATTRIBUTE_FORMAT))\n return False\n if (event_tags and (not validator.are_event_tags_valid(event_tags))):\n self.logger.error('Provided event tags are in an invalid format.')\n self.error_handler.handle_error(exceptions.InvalidEventTagException(enums.Errors.INVALID_EVENT_TAG_FORMAT))\n return False\n return True", "docstring": "Helper method to validate user inputs.\n\nArgs:\nattributes: Dict representing user attributes.\nevent_tags: Dict representing metadata associated with an event.\n\nReturns:\nBoolean True if inputs are valid. False otherwise.", "source": "codesearchnet"}
720{"code": "def _process_params(self):\n self._sort_to_str()\n if ('rows' not in self._solr_params):\n self._solr_params['rows'] = self._cfg['row_size']\n for (key, val) in self._solr_params.items():\n if (isinstance(val, str) and six.PY2):\n self._solr_params[key] = val.encode(encoding='UTF-8')\n return self._solr_params", "docstring": "Adds default row size if it's not given in the query.\nConverts param values into unicode strings.\n\nReturns:\nProcessed self._solr_params dict.", "source": "codesearchnet"}
721{"code": "def jobs_get(self, job_id, project_id=None):\n \n if project_id is None:\n project_id = self._project_id\n url = Api._ENDPOINT + (Api._JOBS_PATH % (project_id, job_id))\n return datalab.utils.Http.request(url, credentials=self._credentials)", "docstring": "Issues a request to retrieve information about a job.\n\nArgs:\njob_id: the id of the job\nproject_id: the project id to use to fetch the results; use None for the default project.\nReturns:\nA parsed result object.\nRaises:\nException if there is an error performing the operation.", "source": "juraj-google-style"}
722{"code": "def _get_event_handlers():\n import os\n import importlib\n event_handlers = {'on_ready': [], 'on_resume': [], 'on_error': [], 'on_message': [], 'on_socket_raw_receive': [], 'on_socket_raw_send': [], 'on_message_delete': [], 'on_message_edit': [], 'on_reaction_add': [], 'on_reaction_remove': [], 'on_reaction_clear': [], 'on_channel_delete': [], 'on_channel_create': [], 'on_channel_update': [], 'on_member_join': [], 'on_member_remove': [], 'on_member_update': [], 'on_server_join': [], 'on_server_remove': [], 'on_server_update': [], 'on_server_role_create': [], 'on_server_role_delete': [], 'on_server_role_update': [], 'on_server_emojis_update': [], 'on_server_available': [], 'on_server_unavailable': [], 'on_voice_state_update': [], 'on_member_ban': [], 'on_member_unban': [], 'on_typing': [], 'on_group_join': [], 'on_group_remove': []}\n database_dir = '{}/modules'.format(os.path.dirname(os.path.realpath(__file__)))\n for module_name in os.listdir(database_dir):\n module_dir = '{}/{}'.format(database_dir, module_name)\n if (os.path.isdir(module_dir) and (not module_name.startswith('_'))):\n module_event_handlers = os.listdir(module_dir)\n for event_handler in event_handlers.keys():\n if ('{}.py'.format(event_handler) in module_event_handlers):\n import_name = '.discord_modis.modules.{}.{}'.format(module_name, event_handler)\n logger.debug('Found event handler {}'.format(import_name[23:]))\n try:\n event_handlers[event_handler].append(importlib.import_module(import_name, 'modis'))\n except Exception as e:\n logger.exception(e)\n return event_handlers", "docstring": "Gets dictionary of event handlers and the modules that define them\n\nReturns:\nevent_handlers (dict): Contains \"all\", \"on_ready\", \"on_message\", \"on_reaction_add\", \"on_error\"", "source": "codesearchnet"}
723{"code": "def _execute(self, connection, query, fetch=True):\n cursor = connection.cursor()\n try:\n cursor.execute(query)\n except Exception as e:\n from ambry.mprlib.exceptions import BadSQLError\n raise BadSQLError('Failed to execute query: {}; {}'.format(query, e))\n if fetch:\n return cursor.fetchall()\n else:\n return cursor", "docstring": "Executes given query using given connection.\n\nArgs:\nconnection (apsw.Connection): connection to the sqlite db who stores mpr data.\nquery (str): sql query\nfetch (boolean, optional): if True, fetch query result and return it. If False, do not fetch.\n\nReturns:\niterable with query result.", "source": "codesearchnet"}
724{"code": "def allan_variance(data, dt, tmax=10):\n \n allanvar = []\n nmax = len(data) if len(data) < tmax / dt else int(tmax / dt)\n for i in range(1, nmax+1):\n databis = data[len(data) % i:]\n y = databis.reshape(len(data)\n allanvar.append(((y[1:] - y[:-1])**2).mean() / 2)\n return dt * np.arange(1, nmax+1), np.array(allanvar)", "docstring": "Calculate Allan variance.\n\nArgs:\ndata (np.ndarray): Input data.\ndt (float): Time between each data.\ntmax (float): Maximum time.\n\nReturns:\nvk (np.ndarray): Frequency.\nallanvar (np.ndarray): Allan variance.", "source": "juraj-google-style"}
725{"code": "def bgr2gray(img, keepdim=False):\n \n out_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n if keepdim:\n out_img = out_img[..., None]\n return out_img", "docstring": "Convert a BGR image to grayscale image.\n\nArgs:\nimg (ndarray): The input image.\nkeepdim (bool): If False (by default), then return the grayscale image\nwith 2 dims, otherwise 3 dims.\n\nReturns:\nndarray: The converted grayscale image.", "source": "juraj-google-style"}
726{"code": "def to_url(self, site='amazon', country='us'):\n try:\n try:\n (url, tlds) = URL_MAP[site]\n except ValueError:\n tlds = None\n url = URL_MAP[site]\n except KeyError:\n raise SiteError(site)\n inject = {'isbn': self._isbn}\n if tlds:\n if (country not in tlds):\n raise CountryError(country)\n tld = tlds[country]\n if (not tld):\n tld = country\n inject['tld'] = tld\n return (url % inject)", "docstring": "Generate a link to an online book site.\n\nArgs:\nsite (str): Site to create link to\ncountry (str): Country specific version of ``site``\n\nReturns:\n``str``: URL on ``site`` for book\n\nRaises:\nSiteError: Unknown site value\nCountryError: Unknown country value", "source": "codesearchnet"}
727{"code": "def deduplicate_readonly_buffers(tflite_model):\n model = flatbuffer_utils.convert_bytearray_to_object(tflite_model)\n read_only_buffer_indices = set()\n for subgraph in model.subgraphs:\n read_only_input_tensor_indices = set()\n for op in subgraph.operators:\n if op.inputs is None:\n continue\n for i, input_tensor_idx in enumerate(op.inputs):\n if op.mutatingVariableInputs is not None:\n if i < len(op.mutatingVariableInputs) and op.mutatingVariableInputs[i]:\n continue\n if subgraph.tensors[input_tensor_idx].isVariable:\n continue\n read_only_input_tensor_indices.add(input_tensor_idx)\n for op in subgraph.operators:\n if op.outputs is not None:\n for output_tensor_idx in op.outputs:\n read_only_input_tensor_indices.discard(output_tensor_idx)\n if op.intermediates is not None:\n for intermediate_tensor_idx in op.intermediates:\n read_only_input_tensor_indices.discard(intermediate_tensor_idx)\n if subgraph.inputs is not None:\n for input_tensor_idx in subgraph.inputs:\n read_only_input_tensor_indices.discard(input_tensor_idx)\n if subgraph.outputs is not None:\n for output_tensor_idx in subgraph.outputs:\n read_only_input_tensor_indices.discard(output_tensor_idx)\n for tensor_idx in read_only_input_tensor_indices:\n read_only_buffer_indices.add(subgraph.tensors[tensor_idx].buffer)\n for buffer_idx in read_only_buffer_indices.copy():\n if buffer_idx < 0 or (model.buffers[buffer_idx].data is None or isinstance(model.buffers[buffer_idx].data, list) or model.buffers[buffer_idx].data.size == 0):\n read_only_buffer_indices.discard(buffer_idx)\n\n class BufferIndex:\n \n\n def __init__(self, idx, size, hash_value):\n self.idx = idx\n self.size = size\n self.hash_value = hash_value\n read_only_buffers = list(map(lambda index: BufferIndex(index, model.buffers[index].data.size, hashlib.md5(model.buffers[index].data.data.tobytes()).hexdigest()), read_only_buffer_indices))\n read_only_buffers = sorted(read_only_buffers, key=lambda buffer: (buffer.size, buffer.hash_value), reverse=True)\n duplicate_buffer_map = {}\n for i, buffer_i in enumerate(read_only_buffers):\n if buffer_i.idx in duplicate_buffer_map:\n continue\n for buffer_j in read_only_buffers[i + 1:]:\n if buffer_j.idx in duplicate_buffer_map:\n continue\n if buffer_i.size != buffer_j.size:\n break\n if buffer_i.hash_value != buffer_j.hash_value:\n continue\n duplicate_buffer_map[buffer_j.idx] = buffer_i.idx\n for subgraph in model.subgraphs:\n for op in subgraph.operators:\n if op.inputs is None:\n continue\n for input_tensor in op.inputs:\n buffer_idx = subgraph.tensors[input_tensor].buffer\n if buffer_idx in duplicate_buffer_map:\n subgraph.tensors[input_tensor].buffer = duplicate_buffer_map[buffer_idx]\n for idx in duplicate_buffer_map:\n model.buffers[idx].data = None\n return flatbuffer_utils.convert_object_to_bytearray(model)", "docstring": "Generates a new model byte array after deduplicating readonly buffers.\n\nThis function should be invoked after the model optimization toolkit. The\nmodel optimization toolkit assumes that each tensor object owns its each\nbuffer separately.\n\nArgs:\ntflite_model: TFLite flatbuffer in a byte array to be deduplicated.\n\nReturns:\nTFLite flatbuffer in a bytes array, processed with the deduplication method.", "source": "github-repos"}
728{"code": "def on_train_batch_begin(self, batch, logs=None):\n if self._should_call_train_batch_hooks:\n self._call_batch_hook(ModeKeys.TRAIN, 'begin', batch, logs=logs)", "docstring": "Calls the `on_train_batch_begin` methods of its callbacks.\n\nArgs:\nbatch: Integer, index of batch within the current epoch.\nlogs: Dict, contains the return value of `model.train_step`. Typically,\nthe values of the `Model`'s metrics are returned. Example:\n`{'loss': 0.2, 'accuracy': 0.7}`.", "source": "github-repos"}
729{"code": "def _get_update_method(self):\n if getattr(self, '_update_uses_post', False):\n http_method = self.gitlab.http_post\n else:\n http_method = self.gitlab.http_put\n return http_method", "docstring": "Return the HTTP method to use.\n\nReturns:\nobject: http_put (default) or http_post", "source": "codesearchnet"}
730{"code": "def _ScanEncryptedVolume(self, scan_context, scan_node):\n \n if not scan_node or not scan_node.path_spec:\n raise errors.ScannerError('Invalid or missing scan node.')\n\n credentials = credentials_manager.CredentialsManager.GetCredentials(\n scan_node.path_spec)\n if not credentials:\n raise errors.ScannerError('Missing credentials for scan node.')\n\n if not self._mediator:\n raise errors.ScannerError(\n 'Unable to proceed. Encrypted volume found but no mediator to '\n 'determine how it should be unlocked.')\n\n if self._mediator.UnlockEncryptedVolume(\n self._source_scanner, scan_context, scan_node, credentials):\n self._source_scanner.Scan(\n scan_context, scan_path_spec=scan_node.path_spec)", "docstring": "Scans an encrypted volume scan node for volume and file systems.\n\nArgs:\nscan_context (SourceScannerContext): source scanner context.\nscan_node (SourceScanNode): volume scan node.\n\nRaises:\nScannerError: if the format of or within the source is not supported,\nthe scan node is invalid, there are no credentials defined for\nthe format or no mediator is provided and a locked scan node was\nfound, e.g. an encrypted volume,", "source": "juraj-google-style"}
731{"code": "def check_output_variable(self, variable):\n \n match = False\n if variable in self.out_variables:\n match = True\n return match", "docstring": "Check to see if output variable was requested by downstream app.\n\nUsing the auto generated dictionary of output variables check to see if provided\nvariable was requested by downstream app.\n\nArgs:\nvariable (string): The variable name, not the full variable.\n\nReturns:\n(boolean): Boolean value indicator whether a match was found.", "source": "juraj-google-style"}
732{"code": "def _PairwiseCheck(self, pair_comparator, strict=False):\n i = iter(self._actual)\n try:\n prev = next(i)\n while True:\n current = next(i)\n if not pair_comparator(prev, current):\n strictly = 'strictly ' if strict else ''\n self._FailComparingValues('is {0}ordered'.format(strictly), (prev, current))\n prev = current\n except StopIteration:\n pass", "docstring": "Iterates over this subject and compares adjacent elements.\n\nFor example, compares element 0 with element 1, 1 with 2, ... n-1 with n.\n\nArgs:\npair_comparator: A function accepting two arguments. If the arguments are\nordered as expected, the function should return True, otherwise False.\nstrict: whether the pair comparator function is strict.", "source": "github-repos"}
733{"code": "def generate_sjson_from_srt(srt_subs):\n \n sub_starts = []\n sub_ends = []\n sub_texts = []\n for sub in srt_subs:\n sub_starts.append(sub.start.ordinal)\n sub_ends.append(sub.end.ordinal)\n sub_texts.append(sub.text.replace('\\n', ' '))\n\n sjson_subs = {\n 'start': sub_starts,\n 'end': sub_ends,\n 'text': sub_texts\n }\n return sjson_subs", "docstring": "Generate transcripts from sjson to SubRip (*.srt).\n\nArguments:\nsrt_subs(SubRip): \"SRT\" subs object\n\nReturns:\nSubs converted to \"SJSON\" format.", "source": "juraj-google-style"}
734{"code": "def add_callback(self, name, func):\n if (name == 'on_scan'):\n events = ['device_seen']\n\n def callback(_conn_string, _conn_id, _name, event):\n func(self.id, event, event.get('validity_period', 60))\n elif (name == 'on_report'):\n events = ['report', 'broadcast']\n\n def callback(_conn_string, conn_id, _name, event):\n func(conn_id, event)\n elif (name == 'on_trace'):\n events = ['trace']\n\n def callback(_conn_string, conn_id, _name, event):\n func(conn_id, event)\n elif (name == 'on_disconnect'):\n events = ['disconnection']\n\n def callback(_conn_string, conn_id, _name, _event):\n func(self.id, conn_id)\n else:\n raise ArgumentError('Unknown callback type {}'.format(name))\n self._adapter.register_monitor([None], events, callback)", "docstring": "Add a callback when device events happen.\n\nArgs:\nname (str): currently support 'on_scan' and 'on_disconnect'\nfunc (callable): the function that should be called", "source": "codesearchnet"}
735{"code": "def write_auth(msg_type, profile_name, auth, cfg):\n \n key_fmt = profile_name + \"_\" + msg_type\n pwd = []\n for k, v in CONFIG[msg_type][\"auth\"].items():\n pwd.append(auth[k])\n\n if len(pwd) > 1:\n cfg.pwd[key_fmt] = \" :: \".join(pwd)\n else:\n cfg.pwd[key_fmt] = pwd[0]", "docstring": "Write the settings into the auth portion of the cfg.\n\nArgs:\n:msg_type: (str) message type to create config entry.\n:profile_name: (str) name of the profile entry\n:auth: (dict) auth parameters\n:cfg: (jsonconfig.Config) config instance.", "source": "juraj-google-style"}
736{"code": "def _indexed_slices_to_tensor(value, dtype=None, name=None, as_ref=False):\n _ = as_ref\n if dtype and (not dtype.is_compatible_with(value.dtype)):\n raise ValueError(f'Incompatible tensor conversion requested to `dtype` {dtype.name} for IndexedSlices ({value}) with dtype {value.dtype.name}')\n if value.dense_shape is None:\n raise ValueError(f'Tensor conversion requested for IndexedSlices for argument `value` without dense_shape: {value!s}')\n if not context.executing_eagerly():\n dense_shape_value = tensor_util.constant_value(value.dense_shape)\n if dense_shape_value is not None:\n num_elements = np.prod(dense_shape_value)\n if num_elements >= _LARGE_SPARSE_NUM_ELEMENTS:\n warnings.warn('Converting sparse IndexedSlices to a dense Tensor with %d elements. This may consume a large amount of memory.' % num_elements)\n return gen_math_ops.unsorted_segment_sum(value.values, value.indices, value.dense_shape[0], name=name)", "docstring": "Converts an IndexedSlices object `value` to a Tensor.\n\nNOTE(mrry): This function is potentially expensive.\n\nArgs:\nvalue: An ops.IndexedSlices object.\ndtype: The dtype of the Tensor to be returned.\nname: Optional name to use for the returned Tensor.\nas_ref: True if a ref is requested.\n\nReturns:\nA dense Tensor representing the values in the given IndexedSlices.\n\nRaises:\nValueError: If the IndexedSlices does not have the same dtype.", "source": "github-repos"}
737{"code": "def __init__(self, time, status, latitude, longitude, speed, track, date,\n variation, mode=None):\n \n super(Position, self).__init__(latitude, longitude)\n self.time = time\n self.status = status\n self.speed = speed\n self.track = track\n self.date = date\n self.variation = variation\n self.mode = mode", "docstring": "Initialise a new ``Position`` object.\n\nArgs:\ntime (datetime.time): Time the fix was taken\nstatus (bool): Whether the data is active\nlatitude (float): Fix's latitude\nlongitude (float): Fix's longitude\nspeed (float): Ground speed\ntrack (float): Track angle\ndate (datetime.date): Date when position was taken\nvariation (float): Magnetic variation\nmode (str): Type of reading", "source": "juraj-google-style"}
738{"code": "def writeOutput(self, session, directory, name):\n self.project_directory = directory\n with tmp_chdir(directory):\n batchDirectory = self._getBatchDirectory(directory)\n self._writeReplacementFiles(session=session, directory=directory, name=name)\n self.write(session=session, directory=directory, name=name)\n self._writeXput(session=session, directory=batchDirectory, fileCards=self.OUTPUT_FILES, name=name)\n self._writeWMSDatasets(session=session, directory=batchDirectory, wmsDatasetCards=self.WMS_DATASETS, name=name)", "docstring": "Write only output files for a GSSHA project from the database to file.\n\nArgs:\nsession (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database\ndirectory (str): Directory where the files will be written.\nname (str): Name that will be given to project when written (e.g.: 'example'). Files that follow the project\nnaming convention will be given this name with the appropriate extension (e.g.: 'example.prj',\n'example.cmt', and 'example.gag'). Files that do not follow this convention will retain their original\nfile names.", "source": "codesearchnet"}
739{"code": "def WriteManyToPath(objs, filepath):\n with io.open(filepath, mode='w', encoding='utf-8') as filedesc:\n WriteManyToFile(objs, filedesc)", "docstring": "Serializes and writes given Python objects to a multi-document YAML file.\n\nArgs:\nobjs: An iterable of Python objects to serialize.\nfilepath: A path to the file into which the object is to be written.", "source": "codesearchnet"}
740{"code": "def build_model(hparams_set, model_name, data_dir, problem_name, beam_size=1):\n hparams = trainer_lib.create_hparams(hparams_set, data_dir=data_dir, problem_name=problem_name)\n translate_model = registry.model(model_name)(hparams, tf.estimator.ModeKeys.EVAL)\n inputs = tf.placeholder(tf.int32, shape=(1, None, 1, 1), name='inputs')\n targets = tf.placeholder(tf.int32, shape=(1, None, 1, 1), name='targets')\n translate_model({'inputs': inputs, 'targets': targets})\n att_mats = get_att_mats(translate_model)\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n samples = translate_model.infer({'inputs': inputs}, beam_size=beam_size)['outputs']\n return (inputs, targets, samples, att_mats)", "docstring": "Build the graph required to fetch the attention weights.\n\nArgs:\nhparams_set: HParams set to build the model with.\nmodel_name: Name of model.\ndata_dir: Path to directory containing training data.\nproblem_name: Name of problem.\nbeam_size: (Optional) Number of beams to use when decoding a translation.\nIf set to 1 (default) then greedy decoding is used.\n\nReturns:\nTuple of (\ninputs: Input placeholder to feed in ids to be translated.\ntargets: Targets placeholder to feed to translation when fetching\nattention weights.\nsamples: Tensor representing the ids of the translation.\natt_mats: Tensors representing the attention weights.\n)", "source": "codesearchnet"}
741{"code": "def setup_colorbars(self, plot_call_sign):\n \n self.fig.colorbar(plot_call_sign, cax=self.cbar_ax,\n ticks=self.cbar_ticks, orientation=self.cbar_orientation)\n \n (getattr(self.cbar_ax, 'set_' + self.cbar_var + 'ticklabels')\n (self.cbar_tick_labels, fontsize=self.cbar_ticks_fontsize))\n (getattr(self.cbar_ax, 'set_' + self.cbar_var + 'label')\n (self.cbar_label, fontsize=self.cbar_label_fontsize, labelpad=self.cbar_label_pad))\n\n return", "docstring": "Setup colorbars for each type of plot.\n\nTake all of the optional performed during ``__init__`` method and makes the colorbar.\n\nArgs:\nplot_call_sign (obj): Plot instance of ax.contourf with colormapping to\nadd as a colorbar.", "source": "juraj-google-style"}
742{"code": "def add_oxidation_state_by_site_fraction(structure, oxidation_states):\n \n try:\n for i, site in enumerate(structure):\n new_sp = collections.defaultdict(float)\n for j, (el, occu) in enumerate(get_z_ordered_elmap(site\n .species)):\n specie = Specie(el.symbol, oxidation_states[i][j])\n new_sp[specie] += occu\n structure[i] = new_sp\n return structure\n except IndexError:\n raise ValueError(\"Oxidation state of all sites must be \"\n \"specified in the list.\")", "docstring": "Add oxidation states to a structure by fractional site.\n\nArgs:\noxidation_states (list): List of list of oxidation states for each\nsite fraction for each site.\nE.g., [[2, 4], [3], [-2], [-2], [-2]]", "source": "juraj-google-style"}
743{"code": "def collate(self, merge_type=None, drop=[], drop_constant=False):\n from .element import Collator\n merge_type = (merge_type if merge_type else self.__class__)\n return Collator(self, merge_type=merge_type, drop=drop, drop_constant=drop_constant)()", "docstring": "Collate allows reordering nested containers\n\nCollation allows collapsing nested mapping types by merging\ntheir dimensions. In simple terms in merges nested containers\ninto a single merged type.\n\nIn the simple case a HoloMap containing other HoloMaps can\neasily be joined in this way. However collation is\nparticularly useful when the objects being joined are deeply\nnested, e.g. you want to join multiple Layouts recorded at\ndifferent times, collation will return one Layout containing\nHoloMaps indexed by Time. Changing the merge_type will allow\nmerging the outer Dimension into any other UniformNdMapping\ntype.\n\nArgs:\nmerge_type: Type of the object to merge with\ndrop: List of dimensions to drop\ndrop_constant: Drop constant dimensions automatically\n\nReturns:\nCollated Layout or HoloMap", "source": "codesearchnet"}
744{"code": "def get_thumbnail(self, mxcurl, width, height, method='scale', allow_remote=True):\n if (method not in ['scale', 'crop']):\n raise ValueError((\"Unsupported thumb method '%s'\" % method))\n query_params = {'width': width, 'height': height, 'method': method}\n if (not allow_remote):\n query_params['allow_remote'] = False\n if mxcurl.startswith('mxc:\n return self._send('GET', mxcurl[6:], query_params=query_params, api_path='/_matrix/media/r0/thumbnail/', return_json=False)\n else:\n raise ValueError((\"MXC URL '%s' did not begin with 'mxc:", "docstring": "Download raw media thumbnail from provided mxc URL.\n\nArgs:\nmxcurl (str): mxc media URL\nwidth (int): desired thumbnail width\nheight (int): desired thumbnail height\nmethod (str): thumb creation method. Must be\nin ['scale', 'crop']. Default 'scale'.\nallow_remote (bool): indicates to the server that it should not\nattempt to fetch the media if it is deemed remote. Defaults\nto true if not provided.", "source": "codesearchnet"}
745{"code": "def _handle_per_output_metrics(self, metrics_dict, y_true, y_pred, mask, weights=None):\n metric_results = []\n for metric_name, metric_fn in metrics_dict.items():\n with backend.name_scope(metric_name):\n metric_result = training_utils_v1.call_metric_function(metric_fn, y_true, y_pred, weights=weights, mask=mask)\n metric_results.append(metric_result)\n return metric_results", "docstring": "Calls metric functions for a single output.\n\nArgs:\nmetrics_dict: A dict with metric names as keys and metric fns as values.\ny_true: Target output.\ny_pred: Predicted output.\nmask: Computed mask value for the current output.\nweights: Weights to be applied on the current output.\n\nReturns:\nA list of metric result tensors.", "source": "github-repos"}
746{"code": "def seek(self, n):\n \n if self._mode != \"r\":\n raise UnsupportedOperation(\"not available in 'w' mode\")\n\n if 0 <= n < self._nb_markers:\n self._n = n\n self._bed.seek(self._get_seek_position(n))\n\n else:\n \n raise ValueError(\"invalid position in BED: {}\".format(n))", "docstring": "Gets to a certain marker position in the BED file.\n\nArgs:\nn (int): The index of the marker to seek to.", "source": "juraj-google-style"}
747{"code": "def _verify_barycentric(lambda1, lambda2, lambda3):\n weights_total = ((lambda1 + lambda2) + lambda3)\n if (not np.allclose(weights_total, 1.0, atol=0.0)):\n raise ValueError('Weights do not sum to 1', lambda1, lambda2, lambda3)\n if ((lambda1 < 0.0) or (lambda2 < 0.0) or (lambda3 < 0.0)):\n raise ValueError('Weights must be positive', lambda1, lambda2, lambda3)", "docstring": "Verifies that weights are barycentric and on the reference triangle.\n\nI.e., checks that they sum to one and are all non-negative.\n\nArgs:\nlambda1 (float): Parameter along the reference triangle.\nlambda2 (float): Parameter along the reference triangle.\nlambda3 (float): Parameter along the reference triangle.\n\nRaises:\nValueError: If the weights are not valid barycentric\ncoordinates, i.e. they don't sum to ``1``.\nValueError: If some weights are negative.", "source": "codesearchnet"}
748{"code": "def _insource_jedi_vim_test(data, ibs):\n \n \n data\n ibs\n import utool as ut\n xdata = ut.ColumnLists()\n xdata\n import ibeis\n xibs = ibeis.IBEISController()\n xibs", "docstring": "If jedi-vim supports google style docstrings you should be able to\nautocomplete ColumnLists methods for `data`\n\nArgs:\ndata (utool.ColumnLists): a column list objct\nibs (ibeis.IBEISController): an object", "source": "juraj-google-style"}
749{"code": "def filter_benchmarks(benchmarks, bench_funcs, base_ver):\n for bm in list(benchmarks):\n func = bench_funcs[bm]\n if (getattr(func, '_python2_only', False) and ((3, 0) <= base_ver)):\n benchmarks.discard(bm)\n logging.info(('Skipping Python2-only benchmark %s; not compatible with Python %s' % (bm, base_ver)))\n continue\n return benchmarks", "docstring": "Filters out benchmarks not supported by both Pythons.\n\nArgs:\nbenchmarks: a set() of benchmark names\nbench_funcs: dict mapping benchmark names to functions\npython: the interpereter commands (as lists)\n\nReturns:\nThe filtered set of benchmark names", "source": "codesearchnet"}
750{"code": "async def retry_request(*args, retry_exceptions=(asyncio.TimeoutError, ScriptWorkerRetryException), retry_async_kwargs=None, **kwargs):\n retry_async_kwargs = (retry_async_kwargs or {})\n return (await retry_async(request, retry_exceptions=retry_exceptions, args=args, kwargs=kwargs, **retry_async_kwargs))", "docstring": "Retry the ``request`` function.\n\nArgs:\n*args: the args to send to request() through retry_async().\nretry_exceptions (list, optional): the exceptions to retry on.\nDefaults to (ScriptWorkerRetryException, ).\nretry_async_kwargs (dict, optional): the kwargs for retry_async.\nIf None, use {}. Defaults to None.\n**kwargs: the kwargs to send to request() through retry_async().\n\nReturns:\nobject: the value from request().", "source": "codesearchnet"}
751{"code": "def terminate_and_create_image(name):\n \n node = _host_node()\n operation = _gcp().instances().delete(project=DEFAULT_PROJECT, zone=DEFAULT_ZONE,\n instance=node['real_name']).execute()\n while True:\n status = get_zone_operation_status(operation=operation)\n if status == 'DONE':\n break\n\n print 'Terminating instance [OPERATION %s]' % status\n time.sleep(5)\n\n body = {\n 'name': name,\n 'sourceDisk': node['source_disk'],\n }\n\n operation = _gcp().images().insert(project=DEFAULT_PROJECT, body=body).execute()\n while True:\n status = get_global_operation_status(operation=operation)\n if status == 'DONE':\n break\n\n print 'Creating image [OPERATION %s]' % status\n time.sleep(5)\n\n print 'Created image: %s' % operation['targetLink']", "docstring": "Create an image from a terminated host (with auto_delete_boot_disk=False)\n\nArgs:\nname: The name of the image", "source": "juraj-google-style"}
752{"code": "def count_ops(self):\n count_ops = {}\n for (instr, _, _) in self.data:\n if (instr.name in count_ops.keys()):\n count_ops[instr.name] += 1\n else:\n count_ops[instr.name] = 1\n return count_ops", "docstring": "Count each operation kind in the circuit.\n\nReturns:\ndict: a breakdown of how many operations of each kind.", "source": "codesearchnet"}
753{"code": "def rmod(self, other, axis=\"columns\", level=None, fill_value=None):\n \n return self._binary_op(\n \"rmod\", other, axis=axis, level=level, fill_value=fill_value\n )", "docstring": "Mod this DataFrame against another DataFrame/Series/scalar.\n\nArgs:\nother: The object to use to apply the div against this.\naxis: The axis to div over.\nlevel: The Multilevel index level to apply div over.\nfill_value: The value to fill NaNs with.\n\nReturns:\nA new DataFrame with the rdiv applied.", "source": "juraj-google-style"}
754{"code": "def save_as(self, filename=None):\n \n if filename is None:\n filename = self.filename\n if filename is None:\n filename = self.default_filename\n if filename is None:\n raise RuntimeError(\"Class '{}' has no default filename\".format(self.__class__.__name__))\n self._do_save_as(filename)\n self.filename = filename", "docstring": "Dumps object contents into file on disk.\n\nArgs:\nfilename (optional): defaults to self.filename. If passed, self.filename\nwill be updated to filename.", "source": "juraj-google-style"}
755{"code": "def _KeyToFilePath(key, api_version):\n\n def _ReplaceCapsWithDash(matchobj):\n match = matchobj.group(0)\n return '-%s' % match.lower()\n case_insensitive_key = re.sub('([A-Z]{1})', _ReplaceCapsWithDash, key)\n api_folder = _API_GOLDEN_FOLDER_V2 if api_version == 2 else _API_GOLDEN_FOLDER_V1\n if key.startswith('tensorflow.experimental.numpy'):\n api_folder = os.path.join(api_folder, '..', '..', '..', '..', '../third_party', 'py', 'numpy', 'tf_numpy_api')\n api_folder = os.path.normpath(api_folder)\n return os.path.join(api_folder, '%s.pbtxt' % case_insensitive_key)", "docstring": "From a given key, construct a filepath.\n\nFilepath will be inside golden folder for api_version.\n\nArgs:\nkey: a string used to determine the file path\napi_version: a number indicating the tensorflow API version, e.g. 1 or 2.\n\nReturns:\nA string of file path to the pbtxt file which describes the public API", "source": "github-repos"}
756{"code": "def set_contents(self, contents, encoding=None):\n self.encoding = encoding\n changed = self._set_initial_contents(contents)\n if (self._side_effect is not None):\n self._side_effect(self)\n return changed", "docstring": "Sets the file contents and size and increases the modification time.\nAlso executes the side_effects if available.\n\nArgs:\ncontents: (str, bytes, unicode) new content of file.\nencoding: (str) the encoding to be used for writing the contents\nif they are a unicode string.\nIf not given, the locale preferred encoding is used.\n\nRaises:\nIOError: if `st_size` is not a non-negative integer,\nor if it exceeds the available file system space.", "source": "codesearchnet"}
757{"code": "def saveAsTFRecords(df, output_dir):\n tf_rdd = df.rdd.mapPartitions(toTFExample(df.dtypes))\n tf_rdd.saveAsNewAPIHadoopFile(output_dir, 'org.tensorflow.hadoop.io.TFRecordFileOutputFormat', keyClass='org.apache.hadoop.io.BytesWritable', valueClass='org.apache.hadoop.io.NullWritable')", "docstring": "Save a Spark DataFrame as TFRecords.\n\nThis will convert the DataFrame rows to TFRecords prior to saving.\n\nArgs:\n:df: Spark DataFrame\n:output_dir: Path to save TFRecords", "source": "codesearchnet"}
758{"code": "def most_by_uncertain(self, y):\n \n return self.most_uncertain_by_mask((self.ds.y == y), y)", "docstring": "Extracts the predicted classes which correspond to the selected class (y) and have probabilities nearest to 1/number_of_classes (eg. 0.5 for 2 classes, 0.33 for 3 classes) for the selected class.\n\nArguments:\ny (int): the selected class\n\nReturns:\nidxs (numpy.ndarray): An array of indexes (numpy.ndarray)", "source": "juraj-google-style"}
759{"code": "def delete_knowledge_base(project_id, knowledge_base_id):\n import dialogflow_v2beta1 as dialogflow\n client = dialogflow.KnowledgeBasesClient()\n knowledge_base_path = client.knowledge_base_path(project_id, knowledge_base_id)\n response = client.delete_knowledge_base(knowledge_base_path)\n print('Knowledge Base deleted.'.format(response))", "docstring": "Deletes a specific Knowledge base.\n\nArgs:\nproject_id: The GCP project linked with the agent.\nknowledge_base_id: Id of the Knowledge base.", "source": "codesearchnet"}
760{"code": "def convert_pytorch_checkpoint_to_tf(model: BertModel, ckpt_dir: str, model_name: str):\n tensors_to_transpose = ('dense.weight', 'attention.self.query', 'attention.self.key', 'attention.self.value')\n var_map = (('layer.', 'layer_'), ('word_embeddings.weight', 'word_embeddings'), ('position_embeddings.weight', 'position_embeddings'), ('token_type_embeddings.weight', 'token_type_embeddings'), ('.', '/'), ('LayerNorm/weight', 'LayerNorm/gamma'), ('LayerNorm/bias', 'LayerNorm/beta'), ('weight', 'kernel'))\n if not os.path.isdir(ckpt_dir):\n os.makedirs(ckpt_dir)\n state_dict = model.state_dict()\n\n def to_tf_var_name(name: str):\n for patt, repl in iter(var_map):\n name = name.replace(patt, repl)\n return f'bert/{name}'\n\n def create_tf_var(tensor: np.ndarray, name: str, session: tf.Session):\n tf_dtype = tf.dtypes.as_dtype(tensor.dtype)\n tf_var = tf.get_variable(dtype=tf_dtype, shape=tensor.shape, name=name, initializer=tf.zeros_initializer())\n session.run(tf.variables_initializer([tf_var]))\n session.run(tf_var)\n return tf_var\n tf.reset_default_graph()\n with tf.Session() as session:\n for var_name in state_dict:\n tf_name = to_tf_var_name(var_name)\n torch_tensor = state_dict[var_name].numpy()\n if any((x in var_name for x in tensors_to_transpose)):\n torch_tensor = torch_tensor.T\n tf_var = create_tf_var(tensor=torch_tensor, name=tf_name, session=session)\n tf_var.assign(tf.cast(torch_tensor, tf_var.dtype))\n tf_weight = session.run(tf_var)\n print(f'Successfully created {tf_name}: {np.allclose(tf_weight, torch_tensor)}')\n saver = tf.train.Saver(tf.trainable_variables())\n saver.save(session, os.path.join(ckpt_dir, model_name.replace('-', '_') + '.ckpt'))", "docstring": "Args:\nmodel: BertModel Pytorch model instance to be converted\nckpt_dir: Tensorflow model directory\nmodel_name: model name\n\nCurrently supported HF models:\n\n- Y BertModel\n- N BertForMaskedLM\n- N BertForPreTraining\n- N BertForMultipleChoice\n- N BertForNextSentencePrediction\n- N BertForSequenceClassification\n- N BertForQuestionAnswering", "source": "github-repos"}
761{"code": "def Dump(obj, sort_keys=False, encoder=None):\n text = json.dumps(obj, indent=2, sort_keys=sort_keys, ensure_ascii=False, cls=encoder, separators=_SEPARATORS)\n if (compatibility.PY2 and isinstance(text, bytes)):\n text = text.decode('utf-8')\n return text", "docstring": "Stringifies a Python object into its JSON representation.\n\nArgs:\nobj: A Python object to convert to JSON.\nsort_keys: If True, output dictionaries keys in sorted (ascending) order.\nencoder: An (optional) encoder class to use.\n\nReturns:\nA JSON representation of the given object.", "source": "codesearchnet"}
762{"code": "def clear_list(self, **kwargs):\n \n path = self._get_id_path('clear')\n kwargs.update({'session_id': self.session_id})\n\n payload = {}\n\n response = self._POST(path, kwargs, payload)\n self._set_attrs_to_values(response)\n return response", "docstring": "Clears all of the items within a list. This is an irreversible action\nand should be treated with caution.\n\nA valid session id is required.\n\nArgs:\nconfirm: True (do it) | False (don't do it)\n\nReturns:\nA dict respresentation of the JSON returned from the API.", "source": "juraj-google-style"}
763{"code": "def CreateShowcaseAd(client, adgroup, expanded_image_filepath,\n collapsed_image_filepath):\n \n ad_group_ad_service = client.GetService('AdGroupAdService', 'v201809')\n\n showcase_ad = {\n 'adGroupId': adgroup['id'],\n 'ad': {\n 'xsi_type': 'ShowcaseAd',\n 'Ad.Type': 'ShowcaseAd',\n \n 'name': 'Showcase ad \n 'finalUrls': 'http:\n 'displayUrl': 'example.com',\n \n 'expandedImage': {\n 'mediaId': UploadImage(client, expanded_image_filepath)['mediaId']\n },\n \n 'collapsedImage': {\n 'mediaId':\n UploadImage(client, collapsed_image_filepath)['mediaId']\n }\n }\n }\n\n ad_operation = {\n 'operator': 'ADD',\n 'operand': showcase_ad\n }\n\n \n showcase_ad = ad_group_ad_service.mutate([ad_operation])['value'][0]\n\n print 'ShowcaseAd with ID \"%s\" was added.' % showcase_ad['ad']['id']\n\n return showcase_ad", "docstring": "Creates a showcase add for the given AdGroup with the given images.\n\nArgs:\nclient: an AdWordsClient instance.\nadgroup: a dict or suds object defining an AdGroup for a Shopping Campaign.\nexpanded_image_filepath: a str filepath to a .jpg file that will be used as\nthe Showcase Ad's expandedImage.\ncollapsed_image_filepath: a str filepath to a .jpg file that will be used as\nthe Showcase Ad's collapsedImage.\n\nReturns:\nThe created Showcase Ad as a sudsobject.", "source": "juraj-google-style"}
764{"code": "def _ReadLabels(self, artifact_definition_values, artifact_definition, name):\n labels = artifact_definition_values.get('labels', [])\n undefined_labels = set(labels).difference(self.labels)\n if undefined_labels:\n raise errors.FormatError('Artifact definition: {0:s} found undefined labels: {1:s}.'.format(name, ', '.join(undefined_labels)))\n artifact_definition.labels = labels", "docstring": "Reads the optional artifact definition labels.\n\nArgs:\nartifact_definition_values (dict[str, object]): artifact definition\nvalues.\nartifact_definition (ArtifactDefinition): an artifact definition.\nname (str): name of the artifact definition.\n\nRaises:\nFormatError: if there are undefined labels.", "source": "codesearchnet"}
765{"code": "def vals2bins(vals,res=100):\n \n \n if any(isinstance(el, list) for el in vals):\n vals = list(itertools.chain(*vals))\n return list(np.digitize(vals, np.linspace(np.min(vals), np.max(vals)+1, res+1)) - 1)", "docstring": "Maps values to bins\nArgs:\nvalues (list or list of lists) - list of values to map to colors\nres (int) - resolution of the color map (default: 100)\nReturns:\nlist of numbers representing bins", "source": "juraj-google-style"}
766{"code": "def If(cond, inputs, then_branch, else_branch, name=None):\n if isinstance(then_branch, function._DefinedFunction):\n tlist = [_.type for _ in then_branch.definition.signature.output_arg]\n return gen_functional_ops._if(cond, inputs, tlist, then_branch, else_branch, name=name)\n then_out = then_branch.structured_outputs\n else_out = else_branch.structured_outputs\n nest.assert_same_structure(then_out, else_out, expand_composites=True)\n tlist = nest.flatten(then_branch.output_dtypes)\n ret = gen_functional_ops._if(cond, inputs, tlist, then_branch, else_branch, name=name)\n return nest.pack_sequence_as(then_out, ret, expand_composites=True)", "docstring": "output = Cond(inputs) ?\n\nthen_branch(inputs) : else_branch(inputs).\n\nArgs:\ncond: A `Tensor`. A scalar. If the scalar is not a boolean, the scalar is\nconverted to a boolean according to the following rule: if the scalar is a\nnumerical value, non-zero means True and zero means False; if the scalar\nis a string, non-empty means True and empty means False.\ninputs: A list of input tensors.\nthen_branch: A function takes 'inputs' and returns a list of tensors, whose\ntypes are the same as what else_branch returns.\nelse_branch: A function takes 'inputs' and returns a list of tensors. whose\ntypes are the same as what then_branch returns.\nname: A name for the operation (optional).\n\nReturns:\nA list of tensors returned by either then_branch(inputs)\nor else_branch(inputs).", "source": "github-repos"}
767{"code": "def __str__(self):\n \n manu = self.manufacturer\n return '%s <Core Id. %s, Manu. %s>' % (self.name, self.Core, manu)", "docstring": "Returns a string representation of this instance.\n\nArgs:\nself (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance\n\nReturns:\nReturns a string specifying the device name, core, and manufacturer.", "source": "juraj-google-style"}
768{"code": "def _detect_gce_environment():\n http = transport.get_http_object(timeout=GCE_METADATA_TIMEOUT)\n try:\n (response, _) = transport.request(http, _GCE_METADATA_URI, headers=_GCE_HEADERS)\n return ((response.status == http_client.OK) and (response.get(_METADATA_FLAVOR_HEADER) == _DESIRED_METADATA_FLAVOR))\n except socket.error:\n logger.info('Timeout attempting to reach GCE metadata service.')\n return False", "docstring": "Determine if the current environment is Compute Engine.\n\nReturns:\nBoolean indicating whether or not the current environment is Google\nCompute Engine.", "source": "codesearchnet"}
769{"code": "def require_attribute(self, attribute: str, typ: Type = _Any) -> None:\n \n attr_nodes = [\n value_node for key_node, value_node in self.yaml_node.value\n if key_node.value == attribute\n ]\n if len(attr_nodes) == 0:\n raise RecognitionError(\n ('{}{}Missing required attribute {}').format(\n self.yaml_node.start_mark, os.linesep, attribute))\n attr_node = attr_nodes[0]\n\n if typ != _Any:\n recognized_types, message = self.__recognizer.recognize(\n attr_node, cast(Type, typ))\n if len(recognized_types) == 0:\n raise RecognitionError(message)", "docstring": "Require an attribute on the node to exist.\n\nIf `typ` is given, the attribute must have this type.\n\nArgs:\nattribute: The name of the attribute / mapping key.\ntyp: The type the attribute must have.", "source": "juraj-google-style"}
770{"code": "def list_adb_devices():\n out = adb.AdbProxy().devices()\n return parse_device_list(out, 'device')", "docstring": "List all android devices connected to the computer that are detected by\nadb.\n\nReturns:\nA list of android device serials. Empty if there's none.", "source": "github-repos"}
771{"code": "def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename):\n if (not tf.gfile.Exists(data_dir)):\n tf.gfile.MakeDirs(data_dir)\n file_path = generator_utils.maybe_download(tmp_dir, _TAR, _URL)\n tar_all = tarfile.open(file_path)\n tar_all.extractall(tmp_dir)\n tar_all.close()\n tar_train = tarfile.open(os.path.join(tmp_dir, 'train-novels.tar'))\n tar_train.extractall(tmp_dir)\n tar_train.close()\n vocab_path = os.path.join(data_dir, vocab_filename)\n if (not tf.gfile.Exists(vocab_path)):\n with tf.gfile.GFile(os.path.join(tmp_dir, _VOCAB), 'r') as infile:\n reader = csv.reader(infile, delimiter='\\t')\n words = [row[0] for row in reader]\n words = ([_UNK] + words[:vocab_size])\n with tf.gfile.GFile(vocab_path, 'w') as outfile:\n outfile.write('\\n'.join(words))", "docstring": "Downloading and preparing the dataset.\n\nArgs:\ntmp_dir: tem directory\ndata_dir: data directory\nvocab_size: size of vocabulary\nvocab_filename: name of vocab file", "source": "codesearchnet"}
772{"code": "def Bernoulli(cls, mean: 'TensorFluent', batch_size: Optional[int]=None) -> Tuple[(Distribution, 'TensorFluent')]:\n probs = mean.tensor\n dist = tf.distributions.Bernoulli(probs=probs, dtype=tf.bool)\n batch = mean.batch\n if ((not batch) and (batch_size is not None)):\n t = dist.sample(batch_size)\n batch = True\n else:\n t = dist.sample()\n scope = mean.scope.as_list()\n return (dist, TensorFluent(t, scope, batch=batch))", "docstring": "Returns a TensorFluent for the Bernoulli sampling op with given mean parameter.\n\nArgs:\nmean: The mean parameter of the Bernoulli distribution.\nbatch_size: The size of the batch (optional).\n\nReturns:\nThe Bernoulli distribution and a TensorFluent sample drawn from the distribution.", "source": "codesearchnet"}
773{"code": "def _map_across_full_axis_select_indices(self, axis, func, indices, keep_remaining=False):\n return self.data.apply_func_to_select_indices_along_full_axis(axis, func, indices, keep_remaining)", "docstring": "Maps function to select indices along full axis.\n\nArgs:\naxis: 0 for columns and 1 for rows.\nfunc: Callable mapping function over the BlockParitions.\nindices: indices along axis to map over.\nkeep_remaining: True if keep indices where function was not applied.\n\nReturns:\nBaseFrameManager containing the result of mapping func over axis on indices.", "source": "codesearchnet"}
774{"code": "def get_dataset(self, dataset_ref, retry=DEFAULT_RETRY):\n if isinstance(dataset_ref, str):\n dataset_ref = DatasetReference.from_string(dataset_ref, default_project=self.project)\n api_response = self._call_api(retry, method='GET', path=dataset_ref.path)\n return Dataset.from_api_repr(api_response)", "docstring": "Fetch the dataset referenced by ``dataset_ref``\n\nArgs:\ndataset_ref (Union[ \\\n:class:`~google.cloud.bigquery.dataset.DatasetReference`, \\\nstr, \\\n]):\nA reference to the dataset to fetch from the BigQuery API.\nIf a string is passed in, this method attempts to create a\ndataset reference from a string using\n:func:`~google.cloud.bigquery.dataset.DatasetReference.from_string`.\nretry (:class:`google.api_core.retry.Retry`):\n(Optional) How to retry the RPC.\n\nReturns:\ngoogle.cloud.bigquery.dataset.Dataset:\nA ``Dataset`` instance.", "source": "codesearchnet"}
775{"code": "def download(self, task, default_ext, timeout=5, max_retry=3, overwrite=False, **kwargs):\n file_url = task['file_url']\n task['success'] = False\n task['filename'] = None\n retry = max_retry\n if (not overwrite):\n with self.lock:\n self.fetched_num += 1\n filename = self.get_filename(task, default_ext)\n if self.storage.exists(filename):\n self.logger.info('skip downloading file %s', filename)\n return\n self.fetched_num -= 1\n while ((retry > 0) and (not self.signal.get('reach_max_num'))):\n try:\n response = self.session.get(file_url, timeout=timeout)\n except Exception as e:\n self.logger.error('Exception caught when downloading file %s, error: %s, remaining retry times: %d', file_url, e, (retry - 1))\n else:\n if self.reach_max_num():\n self.signal.set(reach_max_num=True)\n break\n elif (response.status_code != 200):\n self.logger.error('Response status code %d, file %s', response.status_code, file_url)\n break\n elif (not self.keep_file(task, response, **kwargs)):\n break\n with self.lock:\n self.fetched_num += 1\n filename = self.get_filename(task, default_ext)\n self.logger.info('image \n self.storage.write(filename, response.content)\n task['success'] = True\n task['filename'] = filename\n break\n finally:\n retry -= 1", "docstring": "Download the image and save it to the corresponding path.\n\nArgs:\ntask (dict): The task dict got from ``task_queue``.\ntimeout (int): Timeout of making requests for downloading images.\nmax_retry (int): the max retry times if the request fails.\n**kwargs: reserved arguments for overriding.", "source": "codesearchnet"}
776{"code": "def openResultsInBrowser(res):\n \n print(emphasis(\"\\n\\tOpening URIs in the default web browser...\"))\n\n urisToBrowser([\"https:\n \n time.sleep(2)\n\n uris = []\n for r in res:\n for att in r[\"attributes\"]:\n if att[\"type\"] == \"i3visio.uri\":\n uris.append(att[\"value\"])\n\n urisToBrowser(uris)", "docstring": "Method that collects the URI from a list of entities and opens them\n\nArgs:\n-----\nres: A list containing several i3visio entities.", "source": "juraj-google-style"}
777{"code": "def list_summaries(logdir):\n result = _SummaryFile()\n for dirpath, _, filenames in os.walk(logdir):\n for filename in filenames:\n if not filename.startswith('events.out.'):\n continue\n path = os.path.join(dirpath, filename)\n for event in _SummaryIterator(path):\n if event.graph_def:\n result.graph_defs.append(event.graph_def)\n if not event.summary:\n continue\n for value in event.summary.value:\n tag = value.tag\n kind = value.WhichOneof('value')\n container = {'simple_value': result.scalars, 'image': result.images, 'histo': result.histograms, 'tensor': result.tensors}.get(kind)\n if container is None:\n raise ValueError('Unexpected summary kind %r in event file %s:\\n%r' % (kind, path, event))\n elif kind == 'tensor' and tag != 'keras':\n plugin_name = value.metadata.plugin_data.plugin_name\n container = {'images': result.images, 'histograms': result.histograms, 'scalars': result.scalars}.get(plugin_name)\n if container is not None:\n result.convert_from_v2_summary_proto = True\n else:\n container = result.tensors\n container.add(_ObservedSummary(logdir=dirpath, tag=tag))\n return result", "docstring": "Read all summaries under the logdir into a `_SummaryFile`.\n\nArgs:\nlogdir: A path to a directory that contains zero or more event\nfiles, either as direct children or in transitive subdirectories.\nSummaries in these events must only contain old-style scalars,\nimages, and histograms. Non-summary events, like `graph_def`s, are\nignored.\n\nReturns:\nA `_SummaryFile` object reflecting all summaries written to any\nevent files in the logdir or any of its descendant directories.\n\nRaises:\nValueError: If an event file contains an summary of unexpected kind.", "source": "github-repos"}
778{"code": "def _clone_functional_model(model, clone_function, input_tensors=None, call_function=None):\n if not callable(clone_function):\n raise ValueError(f'Expected `clone_function` argument to be a callable. Received: clone_function={clone_function}')\n if not isinstance(model, Functional):\n raise ValueError(f'Expected `model` argument to be a Functional Model instance. Received: model={model}')\n if input_tensors is not None:\n if not all((isinstance(x, backend.KerasTensor) for x in tree.flatten(input_tensors))):\n raise ValueError(f'All entries in `input_tensors` must be KerasTensors. Received invalid values: inputs_tensors={input_tensors}')\n try:\n tree.assert_same_structure(input_tensors, model.input)\n except ValueError as e:\n raise ValueError(f'`input_tensors` must have the same structure as model.input\\nReference structure: {model.input}\\nReceived structure: {input_tensors}') from e\n else:\n input_tensors = tree.map_structure(lambda x: Input(batch_shape=x.shape, dtype=x.dtype, name=x.name), model.input)\n\n def operation_fn(layer):\n new_layer = clone_function(layer)\n return new_layer\n output_tensors = model._run_through_graph(input_tensors, operation_fn=operation_fn, call_fn=call_function)\n if functional_like_constructor(model.__class__):\n new_model = model.__class__(input_tensors, output_tensors, name=model.name)\n else:\n new_model = Functional(input_tensors, output_tensors, name=model.name)\n if model.compiled:\n compiled_config = model.get_compile_config()\n new_model.compile_from_config(compiled_config)\n return new_model", "docstring": "Clone a `Functional` model instance.\n\nModel cloning is similar to calling a model on new inputs,\nexcept that it creates new layers (and thus new weights) instead\nof sharing the weights of the existing layers.\n\nInput layers are always cloned.\n\nArgs:\nmodel: Instance of `Functional`.\ninput_tensors: optional list of input tensors\nto build the model upon. If not provided,\nplaceholders will be created.\nclone_function: callable to be applied on non-input layers in the model.\nBy default, it clones the layer (without copying the weights).\n\nReturns:\nAn instance of `Functional` reproducing the behavior\nof the original model, on top of new inputs tensors,\nusing newly instantiated weights.", "source": "github-repos"}
779{"code": "def _make_token_async(scopes, service_account_id):\n \n rpc = app_identity.create_rpc()\n app_identity.make_get_access_token_call(rpc, scopes, service_account_id)\n token, expires_at = yield rpc\n raise ndb.Return((token, expires_at))", "docstring": "Get a fresh authentication token.\n\nArgs:\nscopes: A list of scopes.\nservice_account_id: Internal-use only.\n\nRaises:\nAn ndb.Return with a tuple (token, expiration_time) where expiration_time is\nseconds since the epoch.", "source": "juraj-google-style"}
780{"code": "def listdir(path='.'):\n \n return [name.rstrip('/') for name, _ in\n get_instance(path).list_objects(path, first_level=True)]", "docstring": "Return a list containing the names of the entries in the directory given by\npath.\n\nEquivalent to \"os.listdir\".\n\nArgs:\npath (path-like object): Path or URL.\n\nReturns:\nlist of str: Entries names.", "source": "juraj-google-style"}
781{"code": "def render_latex(latex: str) -> PIL.Image:\n tmpfilename = 'circ'\n with tempfile.TemporaryDirectory() as tmpdirname:\n tmppath = os.path.join(tmpdirname, tmpfilename)\n with open((tmppath + '.tex'), 'w') as latex_file:\n latex_file.write(latex)\n subprocess.run(['pdflatex', '-halt-on-error', '-output-directory={}'.format(tmpdirname), '{}'.format((tmpfilename + '.tex'))], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True)\n subprocess.run(['pdftocairo', '-singlefile', '-png', '-q', (tmppath + '.pdf'), tmppath])\n img = PIL.Image.open((tmppath + '.png'))\n return img", "docstring": "Convert a single page LaTeX document into an image.\n\nTo display the returned image, `img.show()`\n\n\nRequired external dependencies: `pdflatex` (with `qcircuit` package),\nand `poppler` (for `pdftocairo`).\n\nArgs:\nA LaTeX document as a string.\n\nReturns:\nA PIL Image\n\nRaises:\nOSError: If an external dependency is not installed.", "source": "codesearchnet"}
782{"code": "def get_propagate_status(self, token, channel):\n \n url = self.url('sd/{}/{}/getPropagate/'.format(token, channel))\n req = self.remote_utils.get_url(url)\n if req.status_code is not 200:\n raise ValueError('Bad pair: {}/{}'.format(token, channel))\n return req.text", "docstring": "Get the propagate status for a token/channel pair.\n\nArguments:\ntoken (str): The token to check\nchannel (str): The channel to check\n\nReturns:\nstr: The status code", "source": "juraj-google-style"}
783{"code": "def get_dataset(self):\n raise NotImplementedError", "docstring": "Get a dataset instance for the current DataAdapter.\n\nNote that the dataset returned does not repeat for epoch, so caller might\nneed to create new iterator for the same dataset at the beginning of the\nepoch. This behavior might change in future.\n\nReturns:\nAn tf.dataset.Dataset. Caller might use the dataset in different\ncontext, eg iter(dataset) in eager to get the value directly, or in graph\nmode, provide the iterator tensor to Keras model function.", "source": "github-repos"}
784{"code": "def infer_transportation_mode(self, clf, min_time):\n \n self.transportation_modes = speed_clustering(clf, self.points, min_time)\n return self", "docstring": "In-place transportation mode inferring\n\nSee infer_transportation_mode function\n\nArgs:\nReturns:\n:obj:`Segment`: self", "source": "juraj-google-style"}
785{"code": "def parse_radl(data):\n \n\n if data is None:\n return None\n elif os.path.isfile(data):\n f = open(data)\n data = \"\".join(f.readlines())\n f.close()\n elif data.strip() == \"\":\n return RADL()\n data = data + \"\\n\"\n\n parser = RADLParser(lextab='radl')\n return parser.parse(data)", "docstring": "Parse a RADL document.\n\nArgs:\n- data(str): filepath to a RADL content or a string with content.\n\nReturn: RADL object.", "source": "juraj-google-style"}
786{"code": "def nx_gen_edge_values(G, key, edges=None, default=util_const.NoParam, on_missing='error', on_keyerr='default'):\n if (edges is None):\n edges = G.edges()\n if (on_missing is None):\n on_missing = 'error'\n if (on_keyerr is None):\n on_keyerr = 'default'\n if ((default is util_const.NoParam) and (on_keyerr == 'default')):\n on_keyerr = 'error'\n if (on_missing == 'error'):\n data_iter = (G.adj[u][v] for (u, v) in edges)\n elif (on_missing == 'default'):\n data_iter = ((G.adj[u][v] if G.has_edge(u, v) else {}) for (u, v) in edges)\n else:\n raise KeyError('on_missing={} must be error, filter or default'.format(on_missing))\n if (on_keyerr == 'error'):\n value_iter = (d[key] for d in data_iter)\n elif (on_keyerr == 'default'):\n value_iter = (d.get(key, default) for d in data_iter)\n else:\n raise KeyError('on_keyerr={} must be error or default'.format(on_keyerr))\n return value_iter", "docstring": "Generates attributes values of specific edges\n\nArgs:\non_missing (str): Strategy for handling nodes missing from G.\nCan be {'error', 'default'}. defaults to 'error'.\non_keyerr (str): Strategy for handling keys missing from node dicts.\nCan be {'error', 'default'}. defaults to 'default'\nif default is specified, otherwise defaults to 'error'.", "source": "codesearchnet"}
787{"code": "def _flush(self, buffer):\n \n with _handle_oss_error():\n self._bucket.put_object(key=self._key, data=buffer.tobytes())", "docstring": "Flush the write buffers of the stream if applicable.\n\nArgs:\nbuffer (memoryview): Buffer content.", "source": "juraj-google-style"}
788{"code": "def get_gates(self, x):\n \n\n \n x = tf.stop_gradient(x)\n \n x = tf.matmul(x, self.t_vectors)\n \n x = tf.sign(x) \n\n \n \n\n x = tf.matmul(x, self.t_group, transpose_b=True) / self.nb_hyperplanes\n \n \n \n x = tf.argmax(x, axis=-1)\n \n \n x = tf.one_hot(x, self.nb_buckets)\n \n return x", "docstring": "Return the bucket id of the given tensor.\n\nArgs:\nx (tf.Tensor): float32 of shape [length, depth]\n\nReturns:\ntf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets]\ncontaining the id of the bucket", "source": "juraj-google-style"}
789{"code": "def currentSelected(self):\n if self.commaRadioButton.isChecked():\n return ','\n elif self.semicolonRadioButton.isChecked():\n return ';'\n elif self.tabRadioButton.isChecked():\n return '\\t'\n elif self.otherRadioButton.isChecked():\n return self.otherSeparatorLineEdit.text()\n return", "docstring": "Returns the currently selected delimiter character.\n\nReturns:\nstr: One of `,`, `;`, `\\t`, `*other*`.", "source": "codesearchnet"}
790{"code": "def _player_step_tuple(self, envs_step_tuples):\n \n ob_real, reward_real, _, _ = envs_step_tuples[\"real_env\"]\n ob_sim, reward_sim, _, _ = envs_step_tuples[\"sim_env\"]\n ob_err = absolute_hinge_difference(ob_sim, ob_real)\n\n ob_real_aug = self._augment_observation(ob_real, reward_real,\n self.cumulative_real_reward)\n ob_sim_aug = self._augment_observation(ob_sim, reward_sim,\n self.cumulative_sim_reward)\n ob_err_aug = self._augment_observation(\n ob_err, reward_sim - reward_real,\n self.cumulative_sim_reward - self.cumulative_real_reward\n )\n ob = np.concatenate([ob_sim_aug, ob_real_aug, ob_err_aug], axis=1)\n _, reward, done, info = envs_step_tuples[\"real_env\"]\n return ob, reward, done, info", "docstring": "Construct observation, return usual step tuple.\n\nArgs:\nenvs_step_tuples: tuples.\n\nReturns:\nStep tuple: ob, reward, done, info\nob: concatenated images [simulated observation, real observation,\ndifference], with additional informations in header.\nreward: real environment reward\ndone: True iff. envs_step_tuples['real_env'][2] is True\ninfo: real environment info", "source": "juraj-google-style"}
791{"code": "def _remove_trailing_new_line(l):\n for n in sorted(new_lines_bytes, key=(lambda x: len(x)), reverse=True):\n if l.endswith(n):\n remove_new_line = slice(None, (- len(n)))\n return l[remove_new_line]\n return l", "docstring": "Remove a single instance of new line at the end of l if it exists.\n\nReturns:\nbytestring", "source": "codesearchnet"}
792{"code": "def _check_tf1_flags(flags, unparsed):\n\n def _get_message_unparsed(flag, orig_flag, new_flag):\n if flag.startswith(orig_flag):\n return '\\n Use {0} instead of {1}'.format(new_flag, orig_flag)\n return ''\n if unparsed:\n output = ''\n for flag in unparsed:\n output += _get_message_unparsed(flag, '--input_file', '--graph_def_file')\n output += _get_message_unparsed(flag, '--savedmodel_directory', '--saved_model_dir')\n output += _get_message_unparsed(flag, '--std_value', '--std_dev_values')\n output += _get_message_unparsed(flag, '--batch_size', '--input_shapes')\n output += _get_message_unparsed(flag, '--dump_graphviz', '--dump_graphviz_dir')\n if output:\n raise ValueError(output)\n if flags.graph_def_file and (not flags.input_arrays or not flags.output_arrays):\n raise ValueError('--input_arrays and --output_arrays are required with --graph_def_file')\n if flags.input_shapes:\n if not flags.input_arrays:\n raise ValueError('--input_shapes must be used with --input_arrays')\n if flags.input_shapes.count(':') != flags.input_arrays.count(','):\n raise ValueError('--input_shapes and --input_arrays must have the same number of items')\n if flags.std_dev_values or flags.mean_values:\n if bool(flags.std_dev_values) != bool(flags.mean_values):\n raise ValueError('--std_dev_values and --mean_values must be used together')\n if flags.std_dev_values.count(',') != flags.mean_values.count(','):\n raise ValueError('--std_dev_values, --mean_values must have the same number of items')\n if (flags.default_ranges_min is None) != (flags.default_ranges_max is None):\n raise ValueError('--default_ranges_min and --default_ranges_max must be used together')\n if flags.dump_graphviz_video and (not flags.dump_graphviz_dir):\n raise ValueError('--dump_graphviz_video must be used with --dump_graphviz_dir')\n if flags.custom_opdefs and (not flags.experimental_new_converter):\n raise ValueError('--custom_opdefs must be used with --experimental_new_converter')\n if flags.custom_opdefs and (not flags.allow_custom_ops):\n raise ValueError('--custom_opdefs must be used with --allow_custom_ops')\n if flags.experimental_select_user_tf_ops and (not flags.experimental_new_converter):\n raise ValueError('--experimental_select_user_tf_ops must be used with --experimental_new_converter')", "docstring": "Checks the parsed and unparsed flags to ensure they are valid in 1.X.\n\nRaises an error if previously support unparsed flags are found. Raises an\nerror for parsed flags that don't meet the required conditions.\n\nArgs:\nflags: argparse.Namespace object containing TFLite flags.\nunparsed: List of unparsed flags.\n\nRaises:\nValueError: Invalid flags.", "source": "github-repos"}
793{"code": "def reserve(self, *args, **kwargs):\n \n data = self.get_data('floating_ips/',\n type=POST,\n params={'region': self.region_slug})\n\n if data:\n self.ip = data['floating_ip']['ip']\n self.region = data['floating_ip']['region']\n\n return self", "docstring": "Creates a FloatingIP in a region without assigning\nit to a specific Droplet.\n\nNote: Every argument and parameter given to this method will be\nassigned to the object.\n\nArgs:\nregion_slug: str - region's slug (e.g. 'nyc3')", "source": "juraj-google-style"}
794{"code": "def __init__(self, filename, f_start=None, f_stop=None, t_start=None, t_stop=None, load_data=True, max_load=1.):\n \n super(H5Reader, self).__init__()\n\n if filename and os.path.isfile(filename) and h5py.is_hdf5(filename):\n\n \n self.freq_axis = 2\n self.time_axis = 0\n self.beam_axis = 1 \n self.stokes_axis = 4 \n\n self.filename = filename\n self.filestat = os.stat(filename)\n self.filesize = self.filestat.st_size/(1024.0**2)\n self.load_data = load_data\n self.h5 = h5py.File(self.filename)\n self.read_header()\n self.file_size_bytes = os.path.getsize(self.filename) \n self.n_ints_in_file = self.h5[\"data\"].shape[self.time_axis] \n self.n_channels_in_file = self.h5[\"data\"].shape[self.freq_axis] \n self.n_beams_in_file = self.header[b'nifs'] \n self.n_pols_in_file = 1 \n self._n_bytes = int(self.header[b'nbits'] / 8) \n self._d_type = self._setup_dtype()\n self.file_shape = (self.n_ints_in_file,self.n_beams_in_file,self.n_channels_in_file)\n\n if self.header[b'foff'] < 0:\n self.f_end = self.header[b'fch1']\n self.f_begin = self.f_end + self.n_channels_in_file*self.header[b'foff']\n else:\n self.f_begin = self.header[b'fch1']\n self.f_end = self.f_begin + self.n_channels_in_file*self.header[b'foff']\n\n self.t_begin = 0\n self.t_end = self.n_ints_in_file\n\n \n self._setup_selection_range(f_start=f_start, f_stop=f_stop, t_start=t_start, t_stop=t_stop, init=True)\n \n self._setup_chans()\n \n self._setup_freqs()\n\n \n if max_load is not None:\n if max_load > 1.0:\n logger.warning('Setting data limit > 1GB, please handle with care!')\n self.MAX_DATA_ARRAY_SIZE = max_load * MAX_DATA_ARRAY_SIZE_UNIT\n else:\n self.MAX_DATA_ARRAY_SIZE = MAX_DATA_ARRAY_SIZE_UNIT\n\n if self.file_size_bytes > self.MAX_DATA_ARRAY_SIZE:\n self.large_file = True\n else:\n self.large_file = False\n\n if self.load_data:\n if self.large_file:\n \n if self.f_start or self.f_stop or self.t_start or self.t_stop:\n if self.isheavy():\n logger.warning(\"Selection size of %.2f GB, exceeding our size limit %.2f GB. Instance created, header loaded, but data not loaded, please try another (t,v) selection.\" % (self._calc_selection_size() / (1024. ** 3), self.MAX_DATA_ARRAY_SIZE / (1024. ** 3)))\n self._init_empty_selection()\n else:\n self.read_data()\n else:\n logger.warning(\"The file is of size %.2f GB, exceeding our size limit %.2f GB. Instance created, header loaded, but data not loaded. You could try another (t,v) selection.\"%(self.file_size_bytes/(1024.**3), self.MAX_DATA_ARRAY_SIZE/(1024.**3)))\n self._init_empty_selection()\n else:\n self.read_data()\n else:\n logger.info(\"Skipping loading data ...\")\n self._init_empty_selection()\n else:\n raise IOError(\"Need a file to open, please give me one!\")", "docstring": "Constructor.\n\nArgs:\nfilename (str): filename of blimpy file.\nf_start (float): start frequency, in MHz\nf_stop (float): stop frequency, in MHz\nt_start (int): start time bin\nt_stop (int): stop time bin", "source": "juraj-google-style"}
795{"code": "def git_branch_rename(new_name):\n curr_name = git.current_branch(refresh=True).name\n if (curr_name not in git.protected_branches()):\n log.info('Renaming branch from <33>{}<32> to <33>{}'.format(curr_name, new_name))\n shell.run('git branch -m {}'.format(new_name))", "docstring": "Rename the current branch\n\nArgs:\nnew_name (str):\nNew name for the current branch.", "source": "codesearchnet"}
796{"code": "def _format_field_value(self, field_name) -> str:\n field_name = self._normalize_field_name(field_name)\n field = self._get_model_field(field_name)\n return SQLInsertCompiler.prepare_value(self, field, getattr(self.query.objs[0], field.attname))", "docstring": "Formats a field's value for usage in SQL.\n\nArguments:\nfield_name:\nThe name of the field to format\nthe value of.\n\nReturns:\nThe field's value formatted for usage\nin SQL.", "source": "codesearchnet"}
797{"code": "def _merge_hdx_update(self, object_type, id_field_name, file_to_upload=None, **kwargs):\n \n \n merge_two_dictionaries(self.data, self.old_data)\n if 'batch_mode' in kwargs: \n self.data['batch_mode'] = kwargs['batch_mode']\n if 'skip_validation' in kwargs: \n self.data['skip_validation'] = kwargs['skip_validation']\n ignore_field = self.configuration['%s' % object_type].get('ignore_on_update')\n self.check_required_fields(ignore_fields=[ignore_field])\n operation = kwargs.get('operation', 'update')\n self._save_to_hdx(operation, id_field_name, file_to_upload)", "docstring": "Helper method to check if HDX object exists and update it\n\nArgs:\nobject_type (str): Description of HDX object type (for messages)\nid_field_name (str): Name of field containing HDX object identifier\nfile_to_upload (Optional[str]): File to upload to HDX\n**kwargs: See below\noperation (string): Operation to perform eg. patch. Defaults to update.\n\nReturns:\nNone", "source": "juraj-google-style"}
798{"code": "def html_serialize(self, attributes, max_length=None):\n \n doc = ET.Element('span')\n for chunk in self:\n if (chunk.has_cjk() and\n not (max_length and len(chunk.word) > max_length)):\n ele = ET.Element('span')\n ele.text = chunk.word\n for key, val in attributes.items():\n ele.attrib[key] = val\n doc.append(ele)\n else:\n \n \n if doc.getchildren():\n if doc.getchildren()[-1].tail is None:\n doc.getchildren()[-1].tail = chunk.word\n else:\n doc.getchildren()[-1].tail += chunk.word\n else:\n if doc.text is None:\n doc.text = chunk.word\n else:\n doc.text += chunk.word\n result = ET.tostring(doc, encoding='utf-8').decode('utf-8')\n result = html5lib.serialize(\n html5lib.parseFragment(result), sanitize=True,\n quote_attr_values='always')\n return result", "docstring": "Returns concatenated HTML code with SPAN tag.\n\nArgs:\nattributes (dict): A map of name-value pairs for attributes of output\nSPAN tags.\nmax_length (:obj:`int`, optional): Maximum length of span enclosed chunk.\n\nReturns:\nThe organized HTML code. (str)", "source": "juraj-google-style"}
799{"code": "async def send_files_preconf(filepaths, config_path=CONFIG_PATH):\n config = read_config(config_path)\n subject = 'PDF files from pdfebc'\n message = ''\n (await send_with_attachments(subject, message, filepaths, config))", "docstring": "Send files using the config.ini settings.\n\nArgs:\nfilepaths (list(str)): A list of filepaths.", "source": "codesearchnet"}
800{"code": "def extend_args(function_signature, args, kwargs):\n arg_names = function_signature.arg_names\n arg_defaults = function_signature.arg_defaults\n arg_is_positionals = function_signature.arg_is_positionals\n keyword_names = function_signature.keyword_names\n function_name = function_signature.function_name\n args = list(args)\n for keyword_name in kwargs:\n if (keyword_name not in keyword_names):\n raise Exception(\"The name '{}' is not a valid keyword argument for the function '{}'.\".format(keyword_name, function_name))\n for skipped_name in arg_names[0:len(args)]:\n if (skipped_name in kwargs):\n raise Exception(\"Positional and keyword value provided for the argument '{}' for the function '{}'\".format(keyword_name, function_name))\n zipped_info = zip(arg_names, arg_defaults, arg_is_positionals)\n zipped_info = list(zipped_info)[len(args):]\n for (keyword_name, default_value, is_positional) in zipped_info:\n if (keyword_name in kwargs):\n args.append(kwargs[keyword_name])\n elif (default_value != funcsigs._empty):\n args.append(default_value)\n elif (not is_positional):\n raise Exception(\"No value was provided for the argument '{}' for the function '{}'.\".format(keyword_name, function_name))\n no_positionals = ((len(arg_is_positionals) == 0) or (not arg_is_positionals[(- 1)]))\n too_many_arguments = ((len(args) > len(arg_names)) and no_positionals)\n if too_many_arguments:\n raise Exception(\"Too many arguments were passed to the function '{}'\".format(function_name))\n return args", "docstring": "Extend the arguments that were passed into a function.\n\nThis extends the arguments that were passed into a function with the\ndefault arguments provided in the function definition.\n\nArgs:\nfunction_signature: The function signature of the function being\ncalled.\nargs: The non-keyword arguments passed into the function.\nkwargs: The keyword arguments passed into the function.\n\nReturns:\nAn extended list of arguments to pass into the function.\n\nRaises:\nException: An exception may be raised if the function cannot be called\nwith these arguments.", "source": "codesearchnet"}
801{"code": "def decode(self, token_ids: Union[int, List[int], 'np.ndarray', 'torch.Tensor', 'tf.Tensor'], skip_special_tokens: bool=False, clean_up_tokenization_spaces: Optional[bool]=None, **kwargs) -> str:\n token_ids = to_py_obj(token_ids)\n return self._decode(token_ids=token_ids, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs)", "docstring": "Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special\ntokens and clean up tokenization spaces.\n\nSimilar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\nArgs:\ntoken_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):\nList of tokenized input ids. Can be obtained using the `__call__` method.\nskip_special_tokens (`bool`, *optional*, defaults to `False`):\nWhether or not to remove special tokens in the decoding.\nclean_up_tokenization_spaces (`bool`, *optional*):\nWhether or not to clean up the tokenization spaces. If `None`, will default to\n`self.clean_up_tokenization_spaces`.\nkwargs (additional keyword arguments, *optional*):\nWill be passed to the underlying model specific decode method.\n\nReturns:\n`str`: The decoded sentence.", "source": "github-repos"}
802{"code": "def create(self, *args, **kwargs):\n data = self.get_data('floating_ips/', type=POST, params={'droplet_id': self.droplet_id})\n if data:\n self.ip = data['floating_ip']['ip']\n self.region = data['floating_ip']['region']\n return self", "docstring": "Creates a FloatingIP and assigns it to a Droplet.\n\nNote: Every argument and parameter given to this method will be\nassigned to the object.\n\nArgs:\ndroplet_id: int - droplet id", "source": "codesearchnet"}
803{"code": "def fit(self, sents, **kwargs):\n \n tokens = list(itertools.chain.from_iterable(sents))\n counter = Counter(tokens)\n self.vocab = self.build_vocab(counter, **kwargs)", "docstring": "Builds a vocabulary object based on the tokens in the input.\n\nArgs:\nsents: A list of lists of tokens (representing sentences)\n\nVocab kwargs include:\nmax_size\nmin_freq\nspecials\nunk_init", "source": "juraj-google-style"}
804{"code": "def _MergeScalarField(self, tokenizer, message, field):\n \n _ = self.allow_unknown_extension\n value = None\n\n if field.type in (descriptor.FieldDescriptor.TYPE_INT32,\n descriptor.FieldDescriptor.TYPE_SINT32,\n descriptor.FieldDescriptor.TYPE_SFIXED32):\n value = _ConsumeInt32(tokenizer)\n elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,\n descriptor.FieldDescriptor.TYPE_SINT64,\n descriptor.FieldDescriptor.TYPE_SFIXED64):\n value = _ConsumeInt64(tokenizer)\n elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,\n descriptor.FieldDescriptor.TYPE_FIXED32):\n value = _ConsumeUint32(tokenizer)\n elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,\n descriptor.FieldDescriptor.TYPE_FIXED64):\n value = _ConsumeUint64(tokenizer)\n elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,\n descriptor.FieldDescriptor.TYPE_DOUBLE):\n value = tokenizer.ConsumeFloat()\n elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:\n value = tokenizer.ConsumeBool()\n elif field.type == descriptor.FieldDescriptor.TYPE_STRING:\n value = tokenizer.ConsumeString()\n elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:\n value = tokenizer.ConsumeByteString()\n elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:\n value = tokenizer.ConsumeEnum(field)\n else:\n raise RuntimeError('Unknown field type %d' % field.type)\n\n if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:\n if field.is_extension:\n message.Extensions[field].append(value)\n else:\n getattr(message, field.name).append(value)\n else:\n if field.is_extension:\n if not self._allow_multiple_scalars and message.HasExtension(field):\n raise tokenizer.ParseErrorPreviousToken(\n 'Message type \"%s\" should not have multiple \"%s\" extensions.' %\n (message.DESCRIPTOR.full_name, field.full_name))\n else:\n message.Extensions[field] = value\n else:\n if not self._allow_multiple_scalars and message.HasField(field.name):\n raise tokenizer.ParseErrorPreviousToken(\n 'Message type \"%s\" should not have multiple \"%s\" fields.' %\n (message.DESCRIPTOR.full_name, field.name))\n else:\n setattr(message, field.name, value)", "docstring": "Merges a single scalar field into a message.\n\nArgs:\ntokenizer: A tokenizer to parse the field value.\nmessage: A protocol message to record the data.\nfield: The descriptor of the field to be merged.\n\nRaises:\nParseError: In case of text parsing problems.\nRuntimeError: On runtime errors.", "source": "juraj-google-style"}
805{"code": "def GetPresetsForOperatingSystem(cls, operating_system, operating_system_product, operating_system_version):\n operating_system = artifacts.OperatingSystemArtifact(family=operating_system, product=operating_system_product, version=operating_system_version)\n return cls._presets.GetPresetsByOperatingSystem(operating_system)", "docstring": "Determines the presets for a specific operating system.\n\nArgs:\noperating_system (str): operating system for example \"Windows\". This\nshould be one of the values in definitions.OPERATING_SYSTEM_FAMILIES.\noperating_system_product (str): operating system product for\nexample \"Windows XP\" as determined by preprocessing.\noperating_system_version (str): operating system version for\nexample \"5.1\" as determined by preprocessing.\n\nReturns:\nlist[PresetDefinition]: preset definitions, where an empty list\nrepresents all parsers and parser plugins (no preset).", "source": "codesearchnet"}
806{"code": "def predict(self, X_feat, X_seq):\n \n\n \n X_seq = np.expand_dims(X_seq, axis=1)\n\n return self._get_other_var(X_feat, X_seq, variable=\"y_pred\")", "docstring": "Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`).\n\nArgs:\nX_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train`\nX_seq: Sequenc design matrix. Same format as :py:attr:`X_seq` in :py:meth:`train`", "source": "juraj-google-style"}
807{"code": "def select_if(df, fun):\n \n\n def _filter_f(col):\n try:\n return fun(df[col])\n except:\n return False\n\n cols = list(filter(_filter_f, df.columns))\n return df[cols]", "docstring": "Selects columns where fun(ction) is true\nArgs:\nfun: a function that will be applied to columns", "source": "juraj-google-style"}
808{"code": "def validate(self, handler):\n \n\n \n test_method = self.plugin_test_validation(handler)\n if not test_method:\n return None\n\n \n \n for name, plugin_class in inspect.getmembers(handler, inspect.isclass):\n if self.plugin_class_validation(plugin_class):\n return {'class':plugin_class, 'test':test_method}\n\n \n print 'Failure for plugin: %s' % (handler.__name__)\n print 'Validation Error: Worker class is required to have a dependencies list and an execute method'\n return None", "docstring": "Validate the plugin, each plugin must have the following:\n1) The worker class must have an execute method: execute(self, input_data).\n2) The worker class must have a dependencies list (even if it's empty).\n3) The file must have a top level test() method.\n\nArgs:\nhandler: the loaded plugin.", "source": "juraj-google-style"}
809{"code": "def FlagCxx14Features(filename, clean_lines, linenum, error):\n \n line = clean_lines.elided[linenum]\n\n include = Match(r'\\s*\n\n \n if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):\n error(filename, linenum, 'build/c++14', 5,\n ('<%s> is an unapproved C++14 header.') % include.group(1))", "docstring": "Flag those C++14 features that we restrict.\n\nArgs:\nfilename: The name of the current file.\nclean_lines: A CleansedLines instance containing the file.\nlinenum: The number of the line to check.\nerror: The function to call with any errors found.", "source": "juraj-google-style"}
810{"code": "def apply(self, inputs, *args, **kwargs):\n warnings.warn('`layer.apply` is deprecated and will be removed in a future version. Please use `layer.__call__` method instead.')\n return self.__call__(inputs, *args, **kwargs)", "docstring": "Deprecated, do NOT use!\n\nThis is an alias of `self.__call__`.\n\nArgs:\ninputs: Input tensor(s).\n*args: additional positional arguments to be passed to `self.call`.\n**kwargs: additional keyword arguments to be passed to `self.call`.\n\nReturns:\nOutput tensor(s).", "source": "github-repos"}
811{"code": "def register_filters(self, filters, force=False):\n \n for filter_name, filter_ref in filters.items():\n self.register_filter(filter_name, filter_ref, force)", "docstring": "Add/register filters.\n\nArgs:\nfilters (dict): Dictionary of Python functions to use as :program:`Jinja2` filters.\nforce (bool): If set to ``True``, forces the registration of a filter no matter if it already exists or not.", "source": "juraj-google-style"}
812{"code": "def from_object(cls, obj):\n return cls(obj.get('sessionId', None), obj.get('status', 0), obj.get('value', None))", "docstring": "The factory method to create WebDriverResult from JSON Object.\n\nArgs:\nobj(dict): The JSON Object returned by server.", "source": "codesearchnet"}
813{"code": "def create_server(self, server_name, *args, **kwargs):\n \n server = ServerConnection(name=server_name, reactor=self)\n\n if args or kwargs:\n server.set_connect_info(*args, **kwargs)\n\n \n for verb, infos in self._event_handlers.items():\n for info in infos:\n server.register_event(info['direction'], verb, info['handler'],\n priority=info['priority'])\n\n self.servers[server_name] = server\n\n return server", "docstring": "Create an IRC server connection slot.\n\nThe server will actually be connected to when\n:meth:`girc.client.ServerConnection.connect` is called later.\n\nArgs:\nserver_name (str): Name of the server, to be used for functions and accessing the\nserver later through the reactor.\n\nReturns:\nserver (girc.client.ServerConnection): A not-yet-connected server.", "source": "juraj-google-style"}
814{"code": "def list_marts(self):\n\n def _row_gen(attributes):\n for attr in attributes.values():\n (yield (attr.name, attr.display_name))\n return pd.DataFrame.from_records(_row_gen(self.marts), columns=['name', 'display_name'])", "docstring": "Lists available marts in a readable DataFrame format.\n\nReturns:\npd.DataFrame: Frame listing available marts.", "source": "codesearchnet"}
815{"code": "def print_table(col_tuple, row_tuples):\n \n col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples)\n for col in range(len(col_tuple))]\n format_str = ' '.join('{{:<{}}}'.format(col_width)\n for col_width in col_widths)\n header_border = ' '.join('=' * col_width for col_width in col_widths)\n print(header_border)\n print(format_str.format(*col_tuple))\n print(header_border)\n for row_tuple in row_tuples:\n print(format_str.format(*row_tuple))\n print(header_border)\n print()", "docstring": "Print column headers and rows as a reStructuredText table.\n\nArgs:\ncol_tuple: Tuple of column name strings.\nrow_tuples: List of tuples containing row data.", "source": "juraj-google-style"}
816{"code": "def _log_every_n_to_logger(n, logger, level, message, *args): \n \n logger = logger or logging.getLogger()\n def _gen(): \n while True:\n for _ in range(n):\n yield False\n logger.log(level, message, *args)\n yield True\n gen = _gen()\n return lambda: six.next(gen)", "docstring": "Logs the given message every n calls to a logger.\n\nArgs:\nn: Number of calls before logging.\nlogger: The logger to which to log.\nlevel: The logging level (e.g. logging.INFO).\nmessage: A message to log\n*args: Any format args for the message.\nReturns:\nA method that logs and returns True every n calls.", "source": "juraj-google-style"}
817{"code": "def remove_regex(urls, regex):\n if (not regex):\n return urls\n if (not isinstance(urls, (list, set, tuple))):\n urls = [urls]\n try:\n non_matching_urls = [url for url in urls if (not re.search(regex, url))]\n except TypeError:\n return []\n return non_matching_urls", "docstring": "Parse a list for non-matches to a regex.\n\nArgs:\nurls: iterable of urls\nregex: string regex to be parsed for\n\nReturns:\nlist of strings not matching regex", "source": "codesearchnet"}
818{"code": "def is_leap_year(years):\n years = tf.convert_to_tensor(years, tf.int32)\n\n def divides_by(n):\n return tf.math.equal(years % n, 0)\n return tf.math.logical_and(divides_by(4), tf.math.logical_or(~divides_by(100), divides_by(400)))", "docstring": "Calculates whether years are leap years.\n\nArgs:\nyears: Tensor of int32 type. Elements should be positive.\n\nReturns:\nTensor of bool type.", "source": "github-repos"}
819{"code": "def _finish_operation_action(self, action):\n success = action.data['success']\n conn_key = action.data['id']\n if (self._get_connection_state(conn_key) != self.InProgress):\n self._logger.error('Invalid finish_operation action on a connection whose state is not InProgress, conn_key=%s', str(conn_key))\n return\n data = self._get_connection(conn_key)\n callback = data['callback']\n conn_id = data['conn_id']\n args = action.data['callback_args']\n data['state'] = self.Idle\n data['microstate'] = None\n callback(conn_id, self.id, success, *args)", "docstring": "Finish an attempted operation.\n\nArgs:\naction (ConnectionAction): the action object describing the result\nof the operation that we are finishing", "source": "codesearchnet"}
820{"code": "def markers(self, values):\n if (not isinstance(values, list)):\n raise TypeError('Markers must be a list of objects')\n self.options['markers'] = values", "docstring": "Set the markers.\n\nArgs:\nvalues (list): list of marker objects.\n\nRaises:\nValueError: Markers must be a list of objects.", "source": "codesearchnet"}
821{"code": "def GetSubkeyByIndex(self, index):\n \n subkeys = list(self._subkeys.values())\n\n if index < 0 or index >= len(subkeys):\n raise IndexError('Index out of bounds.')\n\n return subkeys[index]", "docstring": "Retrieves a subkey by index.\n\nArgs:\nindex (int): index of the subkey.\n\nReturns:\nWinRegistryKey: Windows Registry subkey or None if not found.\n\nRaises:\nIndexError: if the index is out of bounds.", "source": "juraj-google-style"}
822{"code": "def CreateSubdivision(self, parent=None, value=None):\n \n division = {\n 'xsi_type': 'ProductPartition',\n 'partitionType': 'SUBDIVISION',\n 'id': str(self.next_id)\n }\n\n \n if parent is not None:\n division['parentCriterionId'] = parent['id']\n division['caseValue'] = value\n\n adgroup_criterion = {\n 'xsi_type': 'BiddableAdGroupCriterion',\n 'adGroupId': self.adgroup_id,\n 'criterion': division\n }\n\n self.CreateAddOperation(adgroup_criterion)\n self.next_id -= 1\n\n return division", "docstring": "Creates a subdivision node.\n\nArgs:\nparent: The node that should be this node's parent.\nvalue: The value being partitioned on.\nReturns:\nA new subdivision node.", "source": "juraj-google-style"}
823{"code": "def _ValidateFractionalMaxPoolResult(self, input_tensor, pooling_ratio, pseudo_random, overlapping):\n with self.cached_session():\n p, r, c = nn_ops.fractional_max_pool_v2(input_tensor, pooling_ratio, pseudo_random, overlapping, seed=self._SEED)\n actual, row_seq, col_seq = self.evaluate([p, r, c])\n expected = self._GetExpectedFractionalMaxPoolResult(input_tensor, row_seq, col_seq, overlapping)\n self.assertShapeEqual(expected, p)\n self.assertAllClose(expected, actual)", "docstring": "Validate FractionalMaxPool's result against expected.\n\nExpected result is computed given input_tensor, and pooling region defined\nby row_seq and col_seq.\n\nArgs:\ninput_tensor: A tensor or numpy ndarray.\npooling_ratio: A list or tuple of length 4, first and last element be 1.\npseudo_random: Use pseudo random method to generate pooling sequence.\noverlapping: Use overlapping when pooling.\n\nReturns:\nNone", "source": "github-repos"}
824{"code": "def dnd_setSnooze(self, *, num_minutes: int, **kwargs) -> SlackResponse:\n self._validate_xoxp_token()\n kwargs.update({'num_minutes': num_minutes})\n return self.api_call('dnd.setSnooze', http_verb='GET', params=kwargs)", "docstring": "Turns on Do Not Disturb mode for the current user, or changes its duration.\n\nArgs:\nnum_minutes (int): The snooze duration. e.g. 60", "source": "codesearchnet"}
825{"code": "def MakeSuiteFromCdf(cdf, name=None):\n if (name is None):\n name = cdf.name\n suite = Suite(name=name)\n prev = 0.0\n for (val, prob) in cdf.Items():\n suite.Incr(val, (prob - prev))\n prev = prob\n return suite", "docstring": "Makes a normalized Suite from a Cdf object.\n\nArgs:\ncdf: Cdf object\nname: string name for the new Suite\n\nReturns:\nSuite object", "source": "codesearchnet"}
826{"code": "def get_max_capvol(self, remove=True, insert=True, volume=None):\n \n\n vol = volume if volume else self.struc_oxid.volume\n return self._get_max_cap_ah(remove, insert) * 1000 * 1E24 / (vol * const.N_A)", "docstring": "Give max capacity in mAh/cc for inserting and removing a charged cation into base structure.\n\nArgs:\nremove: (bool) whether to allow cation removal\ninsert: (bool) whether to allow cation insertion\nvolume: (float) volume to use for normalization (default=volume of initial structure)\n\nReturns:\nmax vol capacity in mAh/cc", "source": "juraj-google-style"}
827{"code": "def _ParseJournalEntry(self, file_object, file_offset):\n entry_object = self._ParseEntryObject(file_object, file_offset)\n entry_item_map = self._GetDataTypeMap('systemd_journal_entry_item')\n file_offset += 64\n data_end_offset = ((file_offset + entry_object.data_size) - 64)\n fields = {'real_time': entry_object.real_time}\n while (file_offset < data_end_offset):\n try:\n (entry_item, entry_item_data_size) = self._ReadStructureFromFileObject(file_object, file_offset, entry_item_map)\n except (ValueError, errors.ParseError) as exception:\n raise errors.ParseError('Unable to parse entry item at offset: 0x{0:08x} with error: {1!s}'.format(file_offset, exception))\n file_offset += entry_item_data_size\n if (entry_item.object_offset < self._maximum_journal_file_offset):\n raise errors.ParseError('object offset should be after hash tables ({0:d} < {1:d})'.format(entry_item.object_offset, self._maximum_journal_file_offset))\n event_data = self._ParseDataObject(file_object, entry_item.object_offset)\n event_string = event_data.decode('utf-8')\n (key, value) = event_string.split('=', 1)\n fields[key] = value\n return fields", "docstring": "Parses a journal entry.\n\nThis method will generate an event per ENTRY object.\n\nArgs:\nfile_object (dfvfs.FileIO): a file-like object.\nfile_offset (int): offset of the entry object relative to the start\nof the file-like object.\n\nReturns:\ndict[str, objects]: entry items per key.\n\nRaises:\nParseError: when an object offset is out of bounds.", "source": "codesearchnet"}
828{"code": "def create_snapshot(self, volume_id_or_uri, snapshot, timeout=(- 1)):\n uri = self.__build_volume_snapshot_uri(volume_id_or_uri)\n return self._client.create(snapshot, uri=uri, timeout=timeout, default_values=self.DEFAULT_VALUES_SNAPSHOT)", "docstring": "Creates a snapshot for the specified volume.\n\nArgs:\nvolume_id_or_uri:\nCan be either the volume ID or the volume URI.\nsnapshot (dict):\nObject to create.\ntimeout:\nTimeout in seconds. Wait for task completion by default. The timeout does not abort the operation in\nOneView, just stops waiting for its completion.\n\nReturns:\ndict: Storage volume.", "source": "codesearchnet"}
829{"code": "def movie_credits(self, **kwargs):\n \n path = self._get_id_path('movie_credits')\n\n response = self._GET(path, kwargs)\n self._set_attrs_to_values(response)\n return response", "docstring": "Get the movie credits for a specific person id.\n\nArgs:\nlanguage: (optional) ISO 639-1 code.\nappend_to_response: (optional) Comma separated, any person method.\n\nReturns:\nA dict respresentation of the JSON returned from the API.", "source": "juraj-google-style"}
830{"code": "def delete_knowledge_base(project_id, knowledge_base_id):\n \n import dialogflow_v2beta1 as dialogflow\n client = dialogflow.KnowledgeBasesClient()\n knowledge_base_path = client.knowledge_base_path(\n project_id, knowledge_base_id)\n\n response = client.delete_knowledge_base(knowledge_base_path)\n\n print('Knowledge Base deleted.'.format(response))", "docstring": "Deletes a specific Knowledge base.\n\nArgs:\nproject_id: The GCP project linked with the agent.\nknowledge_base_id: Id of the Knowledge base.", "source": "juraj-google-style"}
831{"code": "def relative_tokens_ids_to_notes(self, tokens: np.ndarray, start_idx: float, cutoff_time_idx: Optional[float]=None):\n words = [self._convert_id_to_token(token) for token in tokens]\n current_idx = start_idx\n current_velocity = 0\n note_onsets_ready = [None for i in range(sum([k.endswith('NOTE') for k in self.encoder.keys()]) + 1)]\n notes = []\n for token_type, number in words:\n if token_type == 'TOKEN_SPECIAL':\n if number == 1:\n break\n elif token_type == 'TOKEN_TIME':\n current_idx = token_time_to_note(number=number, cutoff_time_idx=cutoff_time_idx, current_idx=current_idx)\n elif token_type == 'TOKEN_VELOCITY':\n current_velocity = number\n elif token_type == 'TOKEN_NOTE':\n notes = token_note_to_note(number=number, current_velocity=current_velocity, default_velocity=self.default_velocity, note_onsets_ready=note_onsets_ready, current_idx=current_idx, notes=notes)\n else:\n raise ValueError('Token type not understood!')\n for pitch, note_onset in enumerate(note_onsets_ready):\n if note_onset is not None:\n if cutoff_time_idx is None:\n cutoff = note_onset + 1\n else:\n cutoff = max(cutoff_time_idx, note_onset + 1)\n offset_idx = max(current_idx, cutoff)\n notes.append([note_onset, offset_idx, pitch, self.default_velocity])\n if len(notes) == 0:\n return []\n else:\n notes = np.array(notes)\n note_order = notes[:, 0] * 128 + notes[:, 1]\n notes = notes[note_order.argsort()]\n return notes", "docstring": "Converts relative tokens to notes which will then be used to create Pretty Midi objects.\n\nArgs:\ntokens (`numpy.ndarray`):\nRelative Tokens which will be converted to notes.\nstart_idx (`float`):\nA parameter which denotes the starting index.\ncutoff_time_idx (`float`, *optional*):\nA parameter used while converting tokens to notes.", "source": "github-repos"}
832{"code": "def __init__(self, parent=None, **kwargs):\n \n if not parent:\n raise ValueError('Missing parent value.')\n\n super(VMDKPathSpec, self).__init__(parent=parent, **kwargs)", "docstring": "Initializes a path specification.\n\nNote that the VMDK file path specification must have a parent.\n\nArgs:\nparent (Optional[PathSpec]): parent path specification.\n\nRaises:\nValueError: when parent is not set.", "source": "juraj-google-style"}
833{"code": "def unpack(packet):\n validate_packet(packet)\n version = packet[0]\n try:\n pyof_lib = PYOF_VERSION_LIBS[version]\n except KeyError:\n raise UnpackException('Version not supported')\n try:\n message = pyof_lib.common.utils.unpack_message(packet)\n return message\n except (UnpackException, ValueError) as exception:\n raise UnpackException(exception)", "docstring": "Unpack the OpenFlow Packet and returns a message.\n\nArgs:\npacket: buffer with the openflow packet.\n\nReturns:\nGenericMessage: Message unpacked based on openflow packet.\n\nRaises:\nUnpackException: if the packet can't be unpacked.", "source": "codesearchnet"}
834{"code": "def _parse_pem_data(pem_data):\n \n sep = '-----BEGIN CERTIFICATE-----'\n cert_chain = [six.b(sep + s) for s in pem_data.split(sep)[1:]]\n certs = []\n load_cert = x509.load_pem_x509_certificate\n for cert in cert_chain:\n try:\n certs.append(load_cert(cert, default_backend()))\n except ValueError:\n warnings.warn('Certificate is invalid.')\n return False\n\n return certs", "docstring": "Parse PEM-encoded X.509 certificate chain.\n\nArgs:\npem_data: str. PEM file retrieved from SignatureCertChainUrl.\n\nReturns:\nlist or bool: If url is valid, returns the certificate chain as a list\nof cryptography.hazmat.backends.openssl.x509._Certificate\ncertificates where certs[0] is the first certificate in the file; if\nurl is invalid, returns False.", "source": "juraj-google-style"}
835{"code": "def LogUpdate(self, data):\n \n for hypo in self.Values():\n like = self.LogLikelihood(data, hypo)\n self.Incr(hypo, like)", "docstring": "Updates a suite of hypotheses based on new data.\n\nModifies the suite directly; if you want to keep the original, make\na copy.\n\nNote: unlike Update, LogUpdate does not normalize.\n\nArgs:\ndata: any representation of the data", "source": "juraj-google-style"}
836{"code": "def NHWCToNCHW(input_tensor: Union[tensor_lib.Tensor, list[int]]) -> Union[tensor_lib.Tensor, list[int]]:\n new_axes = {3: [0, 2, 1], 4: [0, 3, 1, 2], 5: [0, 4, 1, 2, 3]}\n if isinstance(input_tensor, tensor_lib.Tensor):\n ndims = input_tensor.shape.ndims\n return array_ops.transpose(input_tensor, new_axes[ndims])\n else:\n ndims = len(input_tensor)\n return [input_tensor[a] for a in new_axes[ndims]]", "docstring": "Converts the input from the NHWC format to NCHW.\n\nArgs:\ninput_tensor: a 3-, 4-, or 5-D tensor, or an array representing shape\n\nReturns:\nconverted tensor or shape array", "source": "github-repos"}
837{"code": "def add_children(self, children):\n self._children += [c for c in children if (c not in self._children)]", "docstring": "Adds new children nodes after filtering for duplicates\n\nArgs:\nchildren (list): list of OmniTree nodes to add as children", "source": "codesearchnet"}
838{"code": "def unauthorized(cls, errors=None):\n \n if cls.expose_status: \n cls.response.content_type = 'application/json'\n cls.response._status_line = '401 Unauthorized'\n\n return cls(401, errors=errors).to_json", "docstring": "Shortcut API for HTTP 401 `Unauthorized` response.\n\nArgs:\nerrors (list): Response key/value data.\n\nReturns:\nWSResponse Instance.", "source": "juraj-google-style"}
839{"code": "def cgmlst_subspecies_call(df_relatives):\n closest_distance = df_relatives['distance'].min()\n if (closest_distance > CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD):\n logging.warning('Min cgMLST distance (%s) above subspeciation distance threshold (%s)', closest_distance, CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD)\n return None\n else:\n df_relatives = df_relatives.loc[((df_relatives.distance <= CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD), :)]\n df_relatives = df_relatives.sort_values('distance', ascending=True)\n logging.debug('df_relatives by cgmlst %s', df_relatives.head())\n genome_spp = genomes_to_subspecies()\n subspecies_below_threshold = [(genome_spp[member_genome] if (member_genome in genome_spp) else None) for member_genome in df_relatives.index]\n subspecies_below_threshold = filter(None, subspecies_below_threshold)\n subspecies_counter = Counter(subspecies_below_threshold)\n logging.debug('Subspecies counter: %s', subspecies_counter)\n return (subspecies_counter.most_common(1)[0][0], closest_distance, dict(subspecies_counter))", "docstring": "Call Salmonella subspecies based on cgMLST results\n\nThis method attempts to find the majority subspecies type within curated\npublic genomes above a cgMLST allelic profile distance threshold.\n\nNote:\n``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cgMLST distance\nthreshold used to determine the subspecies by cgMLST. It is set at a\ndistance of 0.9 which translates to a cgMLST allelic similarity of 10%.\nA threshold of 0.9 is generous and reasonable given the congruence\nbetween subspecies designations and 10% cgMLST clusters by Adjusted\nRand (~0.850) and Adjusted Wallace metrics (~0.850 both ways).\n\nArgs:\ndf_relatives (pandas.DataFrame): Table of genomes related by cgMLST to input genome\n\nReturns:\nNone: if no curated public genomes found to have a cgMLST profile similarity of 10% or greater\n(string, float, dict): most common subspecies, closest related public genome distance, subspecies frequencies", "source": "codesearchnet"}
840{"code": "def cwise(tf_fn, xs, output_dtype=None, grad_function=None, name=None):\n return slicewise(tf_fn, xs, output_dtype=output_dtype, splittable_dims=xs[0].shape.dims, grad_function=grad_function, name=(name or 'cwise'))", "docstring": "Component-wise operation with no broadcasting.\n\nArgs:\ntf_fn: a component-wise function taking n tf.Tensor inputs and producing\na tf.Tensor output\nxs: n Tensors\noutput_dtype: an optional dtype\ngrad_function: an optional python function\nname: an optional string\n\nReturns:\na Tensor", "source": "codesearchnet"}
841{"code": "def dependencies(self, user=None, napp=None):\n napps = self._get_napp_key('napp_dependencies', user, napp)\n return [tuple(napp.split('/')) for napp in napps]", "docstring": "Get napp_dependencies from install NApp.\n\nArgs:\nuser(string) A Username.\nnapp(string): A NApp name.\nReturns:\nnapps(list): List with tuples with Username and NApp name.\ne.g. [('kytos'/'of_core'), ('kytos/of_l2ls')]", "source": "codesearchnet"}
842{"code": "def remove_all_lambda_permissions(app_name='', env='', region='us-east-1'):\n \n session = boto3.Session(profile_name=env, region_name=region)\n lambda_client = session.client('lambda')\n legacy_prefix = app_name + \"_\"\n\n lambda_arn = get_lambda_arn(app_name, env, region)\n lambda_alias_arn = get_lambda_alias_arn(app_name, env, region)\n arns = (lambda_arn, lambda_alias_arn)\n\n for arn in arns:\n try:\n response = lambda_client.get_policy(FunctionName=arn)\n except boto3.exceptions.botocore.exceptions.ClientError as error:\n LOG.info(\"No policy exists for function %s, skipping deletion\", arn)\n LOG.debug(error)\n continue\n\n policy_json = json.loads(response['Policy'])\n LOG.debug(\"Found Policy: %s\", response)\n for perm in policy_json['Statement']:\n if perm['Sid'].startswith(FOREMAST_PREFIX) or perm['Sid'].startswith(legacy_prefix):\n lambda_client.remove_permission(FunctionName=arn, StatementId=perm['Sid'])\n LOG.info('removed permission: %s', perm['Sid'])\n else:\n LOG.info('Skipping deleting permission %s - Not managed by Foremast', perm['Sid'])", "docstring": "Remove all foremast-* permissions from lambda.\n\nArgs:\napp_name (str): Application name\nenv (str): AWS environment\nregion (str): AWS region", "source": "juraj-google-style"}
843{"code": "def _encode_fhir_path_builder_constraint(self, builder: expressions.Builder, top_level_constraint: Optional[expressions.Builder]) -> Optional[_BuilderSql]:\n if not top_level_constraint or isinstance(top_level_constraint.node, _evaluation.RootMessageNode):\n fhir_path_expression_sql, sql_expression = self._translate_fhir_path_expression(builder)\n if sql_expression and fhir_path_expression_sql:\n return _BuilderSql(f'(SELECT IFNULL(LOGICAL_AND(result_), TRUE)\\nFROM UNNEST({sql_expression}) AS result_)', fhir_path_expression_sql, builder)\n return None\n root_sql_expression = self._encode_fhir_path_builder(top_level_constraint)\n relative_builder = expressions.Builder.replace_with_operand(builder, old_path=top_level_constraint.fhir_path, replacement_node=_evaluation.StructureBaseNode(self._context, top_level_constraint.return_type))\n fhir_path_expression_sql, sql_expression = self._translate_fhir_path_expression(relative_builder)\n if not sql_expression or not root_sql_expression or (not fhir_path_expression_sql):\n return None\n return _BuilderSql(f'(SELECT IFNULL(LOGICAL_AND(result_), TRUE)\\nFROM (SELECT {sql_expression} AS subquery_\\nFROM (SELECT AS VALUE ctx_element_\\nFROM UNNEST({root_sql_expression}) AS ctx_element_)),\\nUNNEST(subquery_) AS result_)', fhir_path_expression_sql, relative_builder)", "docstring": "Returns a Standard SQL translation of the constraint `fhir_path_expression` relative to its top-level constraint.\n\nArgs:\nbuilder: Builder containing the information to be encoded to Standard SQL.\ntop_level_constraint: Builder containing the constraint that the input\nbuilder is tied to.\n\nReturns:\nA Standard SQL encoding of the constraint `fhir_path_expression` upon\nsuccessful completion. The SQL will evaluate to a single boolean\nindicating whether the constraint is satisfied and the builder that\ncreated it. May be different from the input builder(s).", "source": "github-repos"}
844{"code": "def prepend(self, node):\n \n if not isinstance(node, grammar.STATEMENTS):\n raise ValueError\n self.to_prepend[-1].appendleft(node)", "docstring": "Prepend a statement to the current statement.\n\nNote that multiple calls to prepend will result in the last statement to be\nprepended to end up at the top.\n\nArgs:\nnode: The statement to prepend.\n\nRaises:\nValueError: If the given node is not a statement.", "source": "juraj-google-style"}
845{"code": "def attach(self, engine, log_handler, event_name):\n if (event_name not in State.event_to_attr):\n raise RuntimeError(\"Unknown event name '{}'\".format(event_name))\n engine.add_event_handler(event_name, log_handler, self, event_name)", "docstring": "Attach the logger to the engine and execute `log_handler` function at `event_name` events.\n\nArgs:\nengine (Engine): engine object.\nlog_handler (callable): a logging handler to execute\nevent_name: event to attach the logging handler to. Valid events are from :class:`~ignite.engine.Events`\nor any `event_name` added by :meth:`~ignite.engine.Engine.register_events`.", "source": "codesearchnet"}
846{"code": "def connect(self, slot):\n \n self._ensure_slot_args(slot)\n if not self.is_connected(slot):\n self.slots.append(slot)", "docstring": "Connect ``slot`` to this singal.\n\nArgs:\nslot (callable): Callable object wich accepts keyword arguments.\n\nRaises:\nInvalidSlot: If ``slot`` doesn't accept keyword arguments.", "source": "juraj-google-style"}
847{"code": "def InspectZipFile(self, parser_mediator, zip_file):\n try:\n xml_data = zip_file.read('_rels/.rels')\n property_files = self._ParseRelationshipsXMLFile(xml_data)\n except (IndexError, IOError, KeyError, OverflowError, ValueError, zipfile.BadZipfile) as exception:\n parser_mediator.ProduceExtractionWarning('Unable to parse relationships XML file: _rels/.rels with error: {0!s}'.format(exception))\n return\n metadata = {}\n for path in property_files:\n try:\n xml_data = zip_file.read(path)\n properties = self._ParsePropertiesXMLFile(xml_data)\n except (IndexError, IOError, KeyError, OverflowError, ValueError, zipfile.BadZipfile) as exception:\n parser_mediator.ProduceExtractionWarning('Unable to parse properties XML file: {0:s} with error: {1!s}'.format(path, exception))\n continue\n metadata.update(properties)\n event_data = OpenXMLEventData()\n event_data.app_version = self._GetPropertyValue(parser_mediator, metadata, 'app_version')\n event_data.app_version = self._GetPropertyValue(parser_mediator, metadata, 'app_version')\n event_data.author = self._GetPropertyValue(parser_mediator, metadata, 'author')\n event_data.creating_app = self._GetPropertyValue(parser_mediator, metadata, 'creating_app')\n event_data.doc_security = self._GetPropertyValue(parser_mediator, metadata, 'doc_security')\n event_data.hyperlinks_changed = self._GetPropertyValue(parser_mediator, metadata, 'hyperlinks_changed')\n event_data.i4 = self._GetPropertyValue(parser_mediator, metadata, 'i4')\n event_data.last_saved_by = self._GetPropertyValue(parser_mediator, metadata, 'last_saved_by')\n event_data.links_up_to_date = self._GetPropertyValue(parser_mediator, metadata, 'links_up_to_date')\n event_data.number_of_characters = self._GetPropertyValue(parser_mediator, metadata, 'number_of_characters')\n event_data.number_of_characters_with_spaces = self._GetPropertyValue(parser_mediator, metadata, 'number_of_characters_with_spaces')\n event_data.number_of_lines = self._GetPropertyValue(parser_mediator, metadata, 'number_of_lines')\n event_data.number_of_pages = self._GetPropertyValue(parser_mediator, metadata, 'number_of_pages')\n event_data.number_of_paragraphs = self._GetPropertyValue(parser_mediator, metadata, 'number_of_paragraphs')\n event_data.number_of_words = self._GetPropertyValue(parser_mediator, metadata, 'number_of_words')\n event_data.revision_number = self._GetPropertyValue(parser_mediator, metadata, 'revision_number')\n event_data.scale_crop = self._GetPropertyValue(parser_mediator, metadata, 'scale_crop')\n event_data.shared_doc = self._GetPropertyValue(parser_mediator, metadata, 'shared_doc')\n event_data.template = self._GetPropertyValue(parser_mediator, metadata, 'template')\n event_data.total_time = self._GetPropertyValue(parser_mediator, metadata, 'total_time')\n self._ProduceEvent(parser_mediator, event_data, metadata, 'created', definitions.TIME_DESCRIPTION_CREATION, 'creation time')\n self._ProduceEvent(parser_mediator, event_data, metadata, 'modified', definitions.TIME_DESCRIPTION_MODIFICATION, 'modification time')\n self._ProduceEvent(parser_mediator, event_data, metadata, 'last_printed', definitions.TIME_DESCRIPTION_LAST_PRINTED, 'last printed time')", "docstring": "Parses an OXML file-like object.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nzip_file (zipfile.ZipFile): the zip file containing OXML content. It is\nnot be closed in this method, but will be closed by the parser logic\nin czip.py.\n\nRaises:\nUnableToParseFile: when the file cannot be parsed.", "source": "codesearchnet"}
848{"code": "def _fit(self, dataset):\n \n sc = SparkContext.getOrCreate()\n\n logging.info(\"===== 1. train args: {0}\".format(self.args))\n logging.info(\"===== 2. train params: {0}\".format(self._paramMap))\n local_args = self.merge_args_params()\n logging.info(\"===== 3. train args + params: {0}\".format(local_args))\n\n if local_args.input_mode == TFCluster.InputMode.TENSORFLOW:\n if dfutil.isLoadedDF(dataset):\n \n logging.info(\"Loaded DataFrame of TFRecord.\")\n local_args.tfrecord_dir = dfutil.loadedDF[dataset]\n else:\n \n assert local_args.tfrecord_dir, \"Please specify --tfrecord_dir to export DataFrame to TFRecord.\"\n if self.getInputMapping():\n \n dataset = dataset.select(list(self.getInputMapping()))\n logging.info(\"Exporting DataFrame {} as TFRecord to: {}\".format(dataset.dtypes, local_args.tfrecord_dir))\n dfutil.saveAsTFRecords(dataset, local_args.tfrecord_dir)\n logging.info(\"Done saving\")\n\n tf_args = self.args.argv if self.args.argv else local_args\n cluster = TFCluster.run(sc, self.train_fn, tf_args, local_args.cluster_size, local_args.num_ps,\n local_args.tensorboard, local_args.input_mode, driver_ps_nodes=local_args.driver_ps_nodes)\n if local_args.input_mode == TFCluster.InputMode.SPARK:\n \n input_cols = sorted(self.getInputMapping())\n cluster.train(dataset.select(input_cols).rdd, local_args.epochs)\n cluster.shutdown(grace_secs=30)\n\n \n if self.export_fn:\n assert local_args.export_dir, \"Export function requires --export_dir to be set\"\n logging.info(\"Exporting saved_model (via export_fn) to: {}\".format(local_args.export_dir))\n\n def _export(iterator, fn, args):\n single_node_env(args)\n fn(args)\n\n \n sc.parallelize([1], 1).foreachPartition(lambda it: _export(it, self.export_fn, tf_args))\n\n return self._copyValues(TFModel(self.args))", "docstring": "Trains a TensorFlow model and returns a TFModel instance with the same args/params pointing to a checkpoint or saved_model on disk.\n\nArgs:\n:dataset: A Spark DataFrame with columns that will be mapped to TensorFlow tensors.\n\nReturns:\nA TFModel representing the trained model, backed on disk by a TensorFlow checkpoint or saved_model.", "source": "juraj-google-style"}
849{"code": "def VerifyStructure(self, parser_mediator, line):\n \n try:\n structure = self._DPKG_LOG_LINE.parseString(line)\n except pyparsing.ParseException as exception:\n logger.debug(\n 'Unable to parse Debian dpkg.log file with error: {0!s}'.format(\n exception))\n return False\n\n return 'date_time' in structure and 'body' in structure", "docstring": "Verifies if a line from a text file is in the expected format.\n\nArgs:\nparser_mediator (ParserMediator): parser mediator.\nline (str): line from a text file.\n\nReturns:\nbool: True if the line is in the expected format, False if not.", "source": "juraj-google-style"}
850{"code": "def set_hostname(hostname=None, deploy=False):\n if (not hostname):\n raise CommandExecutionError('Hostname option must not be none.')\n ret = {}\n query = {'type': 'config', 'action': 'set', 'xpath': \"/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system\", 'element': '<hostname>{0}</hostname>'.format(hostname)}\n ret.update(__proxy__['panos.call'](query))\n if (deploy is True):\n ret.update(commit())\n return ret", "docstring": "Set the hostname of the Palo Alto proxy minion. A commit will be required before this is processed.\n\nCLI Example:\n\nArgs:\nhostname (str): The hostname to set\n\ndeploy (bool): If true then commit the full candidate configuration, if false only set pending change.\n\n.. code-block:: bash\n\nsalt '*' panos.set_hostname newhostname\nsalt '*' panos.set_hostname newhostname deploy=True", "source": "codesearchnet"}
851{"code": "def clear(self, keep_attrs=False):\n \n if not keep_attrs:\n for a in (self.graph_attr, self.node_attr, self.edge_attr):\n a.clear()\n del self.body[:]", "docstring": "Reset content to an empty body, clear graph/node/egde_attr mappings.\n\nArgs:\nkeep_attrs (bool): preserve graph/node/egde_attr mappings", "source": "juraj-google-style"}
852{"code": "def get_server_group(self):\n api_url = '{0}/applications/{1}'.format(API_URL, self.app)\n response = requests.get(api_url, verify=GATE_CA_BUNDLE, cert=GATE_CLIENT_CERT)\n for server_group in response.json()['clusters'][self.env]:\n return server_group['serverGroups'][(- 1)]", "docstring": "Finds the most recently deployed server group for the application.\nThis is the server group that the scaling policy will be applied to.\n\nReturns:\nserver_group (str): Name of the newest server group", "source": "codesearchnet"}
853{"code": "def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:\n if token_ids_1 is None:\n return self.prefix_tokens + token_ids_0 + self.suffix_tokens\n return self.prefix_tokens + token_ids_0 + token_ids_1 + self.suffix_tokens", "docstring": "Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and\nadding special tokens. An NLLB sequence has the following format, where `X` represents the sequence:\n\n- `input_ids` (for encoder) `X [eos, src_lang_code]`\n- `decoder_input_ids`: (for decoder) `X [eos, tgt_lang_code]`\n\nBOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a\nseparator.\n\nArgs:\ntoken_ids_0 (`List[int]`):\nList of IDs to which the special tokens will be added.\ntoken_ids_1 (`List[int]`, *optional*):\nOptional second list of IDs for sequence pairs.\n\nReturns:\n`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.", "source": "github-repos"}
854{"code": "def run_step(context):\n logger.debug('started')\n assert context, f'context must have value for {__name__}'\n deprecated(context)\n context.assert_key_has_value('assert', __name__)\n assert_this = context['assert']['this']\n is_equals_there = ('equals' in context['assert'])\n if is_equals_there:\n assert_equals = context['assert']['equals']\n logger.debug(\"comparing assert['this'] to assert['equals'].\")\n assert_result = (context.get_formatted_iterable(assert_this) == context.get_formatted_iterable(assert_equals))\n else:\n logger.debug(\"evaluating assert['this'] as a boolean.\")\n assert_result = context.get_formatted_as_type(assert_this, out_type=bool)\n logger.info(f'assert evaluated to {assert_result}')\n if (not assert_result):\n if is_equals_there:\n type_this = type(context.get_formatted_iterable(assert_this)).__name__\n type_equals = type(context.get_formatted_iterable(assert_equals)).__name__\n error_text = f\"assert assert['this'] is of type {type_this} and does not equal assert['equals'] of type {type_equals}.\"\n else:\n error_text = f'assert {assert_this} evaluated to False.'\n raise ContextError(error_text)\n logger.debug('done')", "docstring": "Assert that something is True or equal to something else.\n\nArgs:\ncontext: dictionary-like pypyr.context.Context. context is mandatory.\nUses the following context keys in context:\n- assert\n- this. mandatory. Any type. If assert['equals'] not specified,\nevals as boolean.\n- equals. optional. Any type.\n\nIf assert['this'] evaluates to False raises error.\nIf assert['equals'] is specified, raises error if\nassert.this != assert.equals.\n\nassert['this'] & assert['equals'] both support string substitutions.\n\nReturns:\nNone\n\nRaises:\nContextError: if assert evaluates to False.", "source": "codesearchnet"}
855{"code": "def __setitem__(self, parameter, instr_params):\n \n\n for instruction, param_index in instr_params:\n assert isinstance(instruction, Instruction)\n assert isinstance(param_index, int)\n self._table[parameter] = instr_params", "docstring": "Sets list of Instructions that depend on Parameter.\n\nArgs:\nparameter (Parameter): the parameter to set\ninstr_params (list): List of (Instruction, int) tuples. Int is the\nparameter index at which the parameter appears in the instruction.", "source": "juraj-google-style"}
856{"code": "def __init__(self, dataset):\n self.dataset = dataset\n elem_spec = self.dataset.element_spec\n _check_table_initializer_element_spec(elem_spec)\n key_type = elem_spec[0].dtype\n value_type = elem_spec[1].dtype\n super(DatasetInitializer, self).__init__(key_type, value_type)", "docstring": "Creates a table initializer from a `tf.data.Dataset`.\n\nArgs:\ndataset: A `tf.data.Dataset` object that produces tuples of scalars. The\nfirst scalar is treated as a key and the second as value.\nRaises: ValueError if `dataset` doesn't conform to specifications.\nReturns: A `DatasetInitializer` object", "source": "github-repos"}
857{"code": "def load_ems(self, modules_paths: List[str]):\n \n all_em_lst = []\n if modules_paths:\n for modules_path in modules_paths:\n em_lst = []\n try:\n for file_name in os.listdir(modules_path):\n if file_name.startswith(\"em_\") and file_name.endswith(\".py\"):\n sys.path.append(modules_path) \n this_module = importlib.import_module(file_name[:-3])\n for em in self.classes_in_module(this_module):\n em_lst.append(em(self))\n except:\n self.log(\"Error when loading etk modules from \" + modules_path, \"error\")\n raise NotGetETKModuleError(\"Wrong file path for ETK modules\")\n all_em_lst += em_lst\n\n try:\n all_em_lst = self.topological_sort(all_em_lst)\n except Exception:\n self.log(\"Topological sort for ETK modules fails\", \"error\")\n raise NotGetETKModuleError(\"Topological sort for ETK modules fails\")\n\n \n \n \n return all_em_lst", "docstring": "Load all extraction modules from the path\n\nArgs:\nmodules_path: str\n\nReturns:", "source": "juraj-google-style"}
858{"code": "def install(path, restart=False):\n cmd = ['wusa.exe', path, '/quiet']\n if restart:\n cmd.append('/forcerestart')\n else:\n cmd.append('/norestart')\n ret_code = __salt__['cmd.retcode'](cmd, ignore_retcode=True)\n file_name = os.path.basename(path)\n errors = {2359302: '{0} is already installed'.format(file_name), 87: 'Unknown error'}\n if (ret_code in errors):\n raise CommandExecutionError(errors[ret_code])\n elif ret_code:\n raise CommandExecutionError('Unknown error: {0}'.format(ret_code))\n return True", "docstring": "Install a KB from a .msu file.\n\nArgs:\n\npath (str):\nThe full path to the msu file to install\n\nrestart (bool):\n``True`` to force a restart if required by the installation. Adds\nthe ``/forcerestart`` switch to the ``wusa.exe`` command. ``False``\nwill add the ``/norestart`` switch instead. Default is ``False``\n\nReturns:\nbool: ``True`` if successful, otherwise ``False``\n\nRaise:\nCommandExecutionError: If the package is already installed or an error\nis encountered\n\nCLI Example:\n\n.. code-block:: bash\n\nsalt '*' wusa.install C:/temp/KB123456.msu", "source": "codesearchnet"}
859{"code": "def random_mixed_density_matrix(num_qubits, num_mixtures=5):\n pre_probs = tf.random.uniform([num_mixtures], 1e-09)\n mixture_probabilities = pre_probs / tf.reduce_sum(pre_probs)\n random_unitary = random_unitary_matrix(num_qubits)\n dim = 2 ** num_qubits\n final_state = tf.zeros([dim, dim], tf.complex128)\n for i in range(num_mixtures):\n pure_state = tf.one_hot(i, dim, 1.0, 0.0, 0, tf.complex128)\n evolved_pure_state = tf.linalg.matvec(random_unitary, pure_state)\n adjoint_evolved_pure_state = tf.squeeze(tf.linalg.adjoint(tf.expand_dims(evolved_pure_state, 0)))\n final_state = final_state + tf.cast(mixture_probabilities[i], tf.complex128) * tf.einsum('i,j->ij', evolved_pure_state, adjoint_evolved_pure_state)\n return (final_state, mixture_probabilities)", "docstring": "Returns a random pure density matrix.\n\nApplies a common random unitary to `num_mixtures` orthogonal states, then\nmixes them with random weights.\n\nArgs:\nnum_qubits: Number of qubits on which the matrix acts.\nnum_mixtures: The number of orthogonal pure states to mix.\n\nReturns:\nfinal_state: The mixed density matrix.\nmixture_probabilities: The probability of each state in the mixture.", "source": "github-repos"}
860{"code": "def run(coro, loop=None):\n loop = (loop or asyncio.get_event_loop())\n return loop.run_until_complete(coro)", "docstring": "Convenient shortcut alias to ``loop.run_until_complete``.\n\nArguments:\ncoro (coroutine): coroutine object to schedule.\nloop (asyncio.BaseEventLoop): optional event loop to use.\nDefaults to: ``asyncio.get_event_loop()``.\n\nReturns:\nmixed: returned value by coroutine.\n\nUsage::\n\nasync def mul_2(num):\nreturn num * 2\n\npaco.run(mul_2(4))\n# => 8", "source": "codesearchnet"}
861{"code": "def user_agent_detail(self, **kwargs):\n \n path = '%s/%s/user_agent_detail' % (self.manager.path, self.get_id())\n return self.manager.gitlab.http_get(path, **kwargs)", "docstring": "Get the user agent detail.\n\nArgs:\n**kwargs: Extra options to send to the server (e.g. sudo)\n\nRaises:\nGitlabAuthenticationError: If authentication is not correct\nGitlabGetError: If the server cannot perform the request", "source": "juraj-google-style"}
862{"code": "def get_ip_address_info(ip_address, cache=None, nameservers=None, timeout=2.0, parallel=False):\n ip_address = ip_address.lower()\n if cache:\n info = cache.get(ip_address, None)\n if info:\n return info\n info = OrderedDict()\n info['ip_address'] = ip_address\n reverse_dns = get_reverse_dns(ip_address, nameservers=nameservers, timeout=timeout)\n country = get_ip_address_country(ip_address, parallel=parallel)\n info['country'] = country\n info['reverse_dns'] = reverse_dns\n info['base_domain'] = None\n if (reverse_dns is not None):\n base_domain = get_base_domain(reverse_dns)\n info['base_domain'] = base_domain\n return info", "docstring": "Returns reverse DNS and country information for the given IP address\n\nArgs:\nip_address (str): The IP address to check\ncache (ExpiringDict): Cache storage\nnameservers (list): A list of one or more nameservers to use\n(Cloudflare's public DNS resolvers by default)\ntimeout (float): Sets the DNS timeout in seconds\nparallel (bool): parallel processing\n\nReturns:\nOrderedDict: ``ip_address``, ``reverse_dns``", "source": "codesearchnet"}
863{"code": "def attention_image_summary(attn, image_shapes=None):\n attn = tf.cast(attn, tf.float32)\n num_heads = common_layers.shape_list(attn)[1]\n image = tf.transpose(attn, [0, 2, 3, 1])\n image = tf.pow(image, 0.2)\n image = tf.pad(image, [[0, 0], [0, 0], [0, 0], [0, tf.mod((- num_heads), 3)]])\n image = split_last_dimension(image, 3)\n image = tf.reduce_max(image, 4)\n if (image_shapes is not None):\n if (len(image_shapes) == 4):\n (q_rows, q_cols, m_rows, m_cols) = list(image_shapes)\n image = tf.reshape(image, [(- 1), q_rows, q_cols, m_rows, m_cols, 3])\n image = tf.transpose(image, [0, 1, 3, 2, 4, 5])\n image = tf.reshape(image, [(- 1), (q_rows * m_rows), (q_cols * m_cols), 3])\n else:\n assert (len(image_shapes) == 6)\n (q_rows, q_cols, q_channnels, m_rows, m_cols, m_channels) = list(image_shapes)\n image = tf.reshape(image, [(- 1), q_rows, q_cols, q_channnels, m_rows, m_cols, m_channels, 3])\n image = tf.transpose(image, [0, 1, 4, 3, 2, 5, 6, 7])\n image = tf.reshape(image, [(- 1), ((q_rows * m_rows) * q_channnels), ((q_cols * m_cols) * m_channels), 3])\n tf.summary.image('attention', image, max_outputs=1)", "docstring": "Compute color image summary.\n\nArgs:\nattn: a Tensor with shape [batch, num_heads, query_length, memory_length]\nimage_shapes: optional tuple of integer scalars.\nIf the query positions and memory positions represent the\npixels of flattened images, then pass in their dimensions:\n(query_rows, query_cols, memory_rows, memory_cols).\nIf the query positions and memory positions represent the\npixels x channels of flattened images, then pass in their dimensions:\n(query_rows, query_cols, query_channels,\nmemory_rows, memory_cols, memory_channels).", "source": "codesearchnet"}
864{"code": "def task(*args, **kwargs):\n func = None\n if ((len(args) == 1) and callable(args[0])):\n func = args[0]\n if (not kwargs):\n service = 'lambda'\n lambda_function_name_arg = None\n aws_region_arg = None\n else:\n service = kwargs.get('service', 'lambda')\n lambda_function_name_arg = kwargs.get('remote_aws_lambda_function_name')\n aws_region_arg = kwargs.get('remote_aws_region')\n capture_response = kwargs.get('capture_response', False)\n\n def func_wrapper(func):\n task_path = get_func_task_path(func)\n\n @wraps(func)\n def _run_async(*args, **kwargs):\n \"\\n This is the wrapping async function that replaces the function\\n that is decorated with @task.\\n Args:\\n These are just passed through to @task's func\\n\\n Assuming a valid service is passed to task() and it is run\\n inside a Lambda process (i.e. AWS_LAMBDA_FUNCTION_NAME exists),\\n it dispatches the function to be run through the service variable.\\n Otherwise, it runs the task synchronously.\\n\\n Returns:\\n In async mode, the object returned includes state of the dispatch.\\n For instance\\n\\n When outside of Lambda, the func passed to @task is run and we\\n return the actual value.\\n \"\n lambda_function_name = (lambda_function_name_arg or os.environ.get('AWS_LAMBDA_FUNCTION_NAME'))\n aws_region = (aws_region_arg or os.environ.get('AWS_REGION'))\n if ((service in ASYNC_CLASSES) and lambda_function_name):\n send_result = ASYNC_CLASSES[service](lambda_function_name=lambda_function_name, aws_region=aws_region, capture_response=capture_response).send(task_path, args, kwargs)\n return send_result\n else:\n return func(*args, **kwargs)\n update_wrapper(_run_async, func)\n _run_async.service = service\n _run_async.sync = func\n return _run_async\n return (func_wrapper(func) if func else func_wrapper)", "docstring": "Async task decorator so that running\n\nArgs:\nfunc (function): the function to be wrapped\nFurther requirements:\nfunc must be an independent top-level function.\ni.e. not a class method or an anonymous function\nservice (str): either 'lambda' or 'sns'\nremote_aws_lambda_function_name (str): the name of a remote lambda function to call with this task\nremote_aws_region (str): the name of a remote region to make lambda/sns calls against\n\nReturns:\nA replacement function that dispatches func() to\nrun asynchronously through the service in question", "source": "codesearchnet"}
865{"code": "def __init__(self, variant_tensor):\n self._variant_tensor_attr = variant_tensor\n self._graph_attr = ops.get_default_graph()\n self._options_attr = options_lib.Options()\n for input_dataset in self._inputs():\n input_options = None\n if isinstance(input_dataset, data_types.DatasetV1):\n if hasattr(input_dataset, '_dataset'):\n if not isinstance(input_dataset._dataset, data_types.DatasetV2):\n raise TypeError(f'Each input of dataset {type(self)} should be a subclass of `tf.data.Dataset` but encountered {type(input_dataset._dataset)}.')\n input_options = input_dataset._dataset._options_attr\n elif isinstance(input_dataset, data_types.DatasetV2):\n input_options = input_dataset._options_attr\n else:\n raise TypeError(f'Each input of dataset {type(self)} should be a subclass of `tf.data.Dataset` but encountered {type(input_dataset)}.')\n if input_options is not None:\n self._options_attr = self._options_attr.merge(input_options)\n self._options_attr._set_mutable(False)", "docstring": "Creates a DatasetV2 object.\n\nThis is a difference between DatasetV1 and DatasetV2. DatasetV1 does not\ntake anything in its constructor whereas in the DatasetV2, we expect\nsubclasses to create a variant_tensor and pass it in to the super() call.\n\nArgs:\nvariant_tensor: A DT_VARIANT tensor that represents the dataset.", "source": "github-repos"}
866{"code": "def chomp(text, max_len=280, split=None):\n split = (split or '—;,.')\n while (length(text) > max_len):\n try:\n text = re.split((('[' + split) + ']'), text[::(- 1)], 1)[1][::(- 1)]\n except IndexError:\n return text\n return text", "docstring": "Shorten a string so that it fits under max_len, splitting it at 'split'.\nNot guaranteed to return a string under max_len, as it may not be possible\n\nArgs:\ntext (str): String to shorten\nmax_len (int): maximum length. default 140\nsplit (str): strings to split on (default is common punctuation: \"-;,.\")", "source": "codesearchnet"}
867{"code": "def _player_step_tuple(self, envs_step_tuples):\n (ob_real, reward_real, _, _) = envs_step_tuples['real_env']\n (ob_sim, reward_sim, _, _) = envs_step_tuples['sim_env']\n ob_err = absolute_hinge_difference(ob_sim, ob_real)\n ob_real_aug = self._augment_observation(ob_real, reward_real, self.cumulative_real_reward)\n ob_sim_aug = self._augment_observation(ob_sim, reward_sim, self.cumulative_sim_reward)\n ob_err_aug = self._augment_observation(ob_err, (reward_sim - reward_real), (self.cumulative_sim_reward - self.cumulative_real_reward))\n ob = np.concatenate([ob_sim_aug, ob_real_aug, ob_err_aug], axis=1)\n (_, reward, done, info) = envs_step_tuples['real_env']\n return (ob, reward, done, info)", "docstring": "Construct observation, return usual step tuple.\n\nArgs:\nenvs_step_tuples: tuples.\n\nReturns:\nStep tuple: ob, reward, done, info\nob: concatenated images [simulated observation, real observation,\ndifference], with additional informations in header.\nreward: real environment reward\ndone: True iff. envs_step_tuples['real_env'][2] is True\ninfo: real environment info", "source": "codesearchnet"}
868{"code": "def GetLocalPath(self, inode, cache, database):\n \n local_path = cache.GetResults('local_path')\n if not local_path:\n results = database.Query(self.LOCAL_PATH_CACHE_QUERY)\n\n cache.CacheQueryResults(\n results, 'local_path', 'child_inode_number',\n ('parent_inode_number', 'filename'))\n local_path = cache.GetResults('local_path')\n\n parent, path = local_path.get(inode, [None, None])\n\n \n \n root_value = '%local_sync_root%/'\n\n if not path:\n return root_value\n\n paths = []\n while path:\n paths.append(path)\n parent, path = local_path.get(parent, [None, None])\n\n if not paths:\n return root_value\n\n \n \n paths.reverse()\n return root_value + '/'.join(paths)", "docstring": "Return local path for a given inode.\n\nArgs:\ninode (int): inode number for the file.\ncache (SQLiteCache): cache.\ndatabase (SQLiteDatabase): database.\n\nReturns:\nstr: full path, including the filename of the given inode value.", "source": "juraj-google-style"}
869{"code": "def default(self, o):\n \n if isinstance(o, datetime.datetime):\n return {\"@module\": \"datetime\", \"@class\": \"datetime\",\n \"string\": o.__str__()}\n if np is not None:\n if isinstance(o, np.ndarray):\n return {\"@module\": \"numpy\",\n \"@class\": \"array\",\n \"dtype\": o.dtype.__str__(),\n \"data\": o.tolist()}\n elif isinstance(o, np.generic):\n return o.item()\n if bson is not None:\n if isinstance(o, bson.objectid.ObjectId):\n return {\"@module\": \"bson.objectid\",\n \"@class\": \"ObjectId\",\n \"oid\": str(o)}\n\n try:\n d = o.as_dict()\n if \"@module\" not in d:\n d[\"@module\"] = u\"{}\".format(o.__class__.__module__)\n if \"@class\" not in d:\n d[\"@class\"] = u\"{}\".format(o.__class__.__name__)\n if \"@version\" not in d:\n try:\n parent_module = o.__class__.__module__.split('.')[0]\n module_version = import_module(parent_module).__version__\n d[\"@version\"] = u\"{}\".format(module_version)\n except AttributeError:\n d[\"@version\"] = None\n return d\n except AttributeError:\n return json.JSONEncoder.default(self, o)", "docstring": "Overriding default method for JSON encoding. This method does two\nthings: (a) If an object has a to_dict property, return the to_dict\noutput. (b) If the @module and @class keys are not in the to_dict,\nadd them to the output automatically. If the object has no to_dict\nproperty, the default Python json encoder default method is called.\n\nArgs:\no: Python object.\n\nReturn:\nPython dict representation.", "source": "juraj-google-style"}
870{"code": "def cleanup(self):\n current = self.join('current')\n if (not os.path.exists(current)):\n LOGGER.debug('found broken current symlink, removing: %s', current)\n os.unlink(self.join('current'))\n self.current = None\n try:\n self._update_current()\n except PrefixNotFound:\n if (not os.listdir(self.path)):\n LOGGER.debug('workdir is empty, removing %s', self.path)\n os.rmdir(self.path)\n else:\n raise MalformedWorkdir('Unable to find any prefixes in {0}, but the directory looks malformed. Try deleting it manually.'.format(self.path))", "docstring": "Attempt to set a new current symlink if it is broken. If no other\nprefixes exist and the workdir is empty, try to delete the entire\nworkdir.\n\nRaises:\n:exc:`~MalformedWorkdir`: if no prefixes were found, but the\nworkdir is not empty.", "source": "codesearchnet"}
871{"code": "def do_check_pep8(files, status):\n for file_name in files:\n args = ['flake8', '--max-line-length=120', '{0}'.format(file_name)]\n output = run(*args)\n if output:\n status.append('Python PEP8/Flake8: {0}: {1}'.format(file_name, output))\n return status", "docstring": "Run the python pep8 tool against the filst of supplied files.\nAppend any linting errors to the returned status list\n\nArgs:\nfiles (str): list of files to run pep8 against\nstatus (list): list of pre-receive check failures to eventually print\nto the user\n\nReturns:\nstatus list of current pre-redeive check failures. Might be an empty\nlist.", "source": "codesearchnet"}
872{"code": "def update_renames_v2(output_file_path):\n function_renames = collect_function_renames()\n constant_renames = collect_constant_renames()\n all_renames = function_renames.union(constant_renames)\n manual_renames = all_renames_v2.manual_symbol_renames\n rename_lines = [get_rename_line(name, canonical_name) for name, canonical_name in all_renames if 'tf.' + name not in manual_renames]\n renames_file_text = '%srenames = {\\n%s\\n}\\n' % (_FILE_HEADER, ',\\n'.join(sorted(rename_lines)))\n file_io.write_string_to_file(output_file_path, renames_file_text)", "docstring": "Writes a Python dictionary mapping deprecated to canonical API names.\n\nArgs:\noutput_file_path: File path to write output to. Any existing contents\nwould be replaced.", "source": "github-repos"}
873{"code": "def wait_for_postgres(database, host, port, username, password):\n connecting_string = 'Checking for PostgreSQL...'\n if (port is not None):\n port = int(port)\n while True:\n try:\n logger.info(connecting_string)\n connection = psycopg2.connect(database=database, host=host, port=port, user=username, password=password, connect_timeout=3)\n connection.close()\n logger.info('PostgreSQL is running!')\n break\n except psycopg2.OperationalError:\n time.sleep(1)", "docstring": "Waits for PostgreSQL database to be up\n\nArgs:\ndatabase (Optional[str]): Database name\nhost (Optional[str]): Host where database is located\nport (Union[int, str, None]): Database port\nusername (Optional[str]): Username to log into database\npassword (Optional[str]): Password to log into database\n\nReturns:\nNone", "source": "codesearchnet"}
874{"code": "def power(self, n):\n \n if n > 0:\n return super().power(n)\n return Stinespring(SuperOp(self).power(n))", "docstring": "The matrix power of the channel.\n\nArgs:\nn (int): compute the matrix power of the superoperator matrix.\n\nReturns:\nStinespring: the matrix power of the SuperOp converted to a\nStinespring channel.\n\nRaises:\nQiskitError: if the input and output dimensions of the\nQuantumChannel are not equal, or the power is not an integer.", "source": "juraj-google-style"}
875{"code": "def cubic_lattice( a, b, c, spacing ):\n \n grid = np.array( list( range( 1, a * b * c + 1 ) ) ).reshape( a, b, c, order='F' )\n it = np.nditer( grid, flags=[ 'multi_index' ] )\n sites = []\n while not it.finished:\n x, y, z = it.multi_index\n r = np.array( [ x, y, z ] ) * spacing\n neighbours = [ np.roll( grid, +1, axis=0 )[x,y,z],\n np.roll( grid, -1, axis=0 )[x,y,z],\n np.roll( grid, +1, axis=1 )[x,y,z],\n np.roll( grid, -1, axis=1 )[x,y,z],\n np.roll( grid, +1, axis=2 )[x,y,z],\n np.roll( grid, -1, axis=2 )[x,y,z] ]\n sites.append( lattice_site.Site( int( it[0] ), r, neighbours, 0.0, 'L' ) )\n it.iternext()\n return lattice.Lattice( sites, cell_lengths = np.array( [ a, b, c ] ) * spacing )", "docstring": "Generate a cubic lattice.\n\nArgs:\na (Int): Number of lattice repeat units along x.\nb (Int): Number of lattice repeat units along y.\nc (Int): Number of lattice repeat units along z.\nspacing (Float): Distance between lattice sites.\n\nReturns:\n(Lattice): The new lattice", "source": "juraj-google-style"}
876{"code": "def get_ituz(self, callsign, timestamp=timestamp_now):\n return self.get_all(callsign, timestamp)[const.ITUZ]", "docstring": "Returns ITU Zone of a callsign\n\nArgs:\ncallsign (str): Amateur Radio callsign\ntimestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)\n\nReturns:\nint: containing the callsign's CQ Zone\n\nRaises:\nKeyError: No ITU Zone found for callsign\n\nNote:\nCurrently, only Country-files.com lookup database contains ITU Zones", "source": "codesearchnet"}
877{"code": "def stop_gradient(variable):\n if any_symbolic_tensors((variable,)):\n return StopGradient().symbolic_call(variable)\n return backend.core.stop_gradient(variable)", "docstring": "Stops gradient computation.\n\nArgs:\nvariable: A tensor variable for which the gradient\ncomputation is to be disabled.\n\nReturns:\nThe variable with gradient computation disabled.\n\nExamples:\n\n>>> var = keras.backend.convert_to_tensor(\n... [1., 2., 3.],\n... dtype=\"float32\"\n... )\n>>> var = keras.ops.stop_gradient(var)", "source": "github-repos"}
878{"code": "def _update_from_body(self, destination, source):\n for (key, value) in source.iteritems():\n destination_value = destination.get(key)\n if (isinstance(value, dict) and isinstance(destination_value, dict)):\n self._update_from_body(destination_value, value)\n else:\n destination[key] = value", "docstring": "Updates the dictionary for an API payload with the request body.\n\nThe values from the body should override those already in the payload, but\nfor nested fields (message objects) the values can be combined\nrecursively.\n\nArgs:\ndestination: A dictionary containing an API payload parsed from the\npath and query parameters in a request.\nsource: A dictionary parsed from the body of the request.", "source": "codesearchnet"}
879{"code": "def parseTree(self, root, state: ParseState) -> List[Dict]:\n if (root.tag in self.AST_TAG_HANDLERS):\n return self.AST_TAG_HANDLERS[root.tag](root, state)\n elif (root.tag in self.libRtns):\n return self.process_libRtn(root, state)\n else:\n prog = []\n for node in root:\n prog += self.parseTree(node, state)\n return prog", "docstring": "Parses the XML ast tree recursively to generate a JSON AST\nwhich can be ingested by other scripts to generate Python\nscripts.\n\nArgs:\nroot: The current root of the tree.\nstate: The current state of the tree defined by an object of the\nParseState class.\n\nReturns:\nast: A JSON ast that defines the structure of the Fortran file.", "source": "codesearchnet"}
880{"code": "def register_symbolic_tensor_type(cls):\n global _user_convertible_tensor_types\n if cls not in _user_convertible_tensor_types:\n keras_tensor.register_keras_tensor_specialization(cls, keras_tensor.UserRegisteredTypeKerasTensor)\n _user_convertible_tensor_types.add(cls)", "docstring": "Allows users to specify types regarded as symbolic `Tensor`s.\n\nUsed in conjunction with `tf.register_tensor_conversion_function`, calling\n`tf.keras.__internal__.utils.register_symbolic_tensor_type(cls)`\nallows non-`Tensor` objects to be plumbed through Keras layers.\n\nExample:\n\n```python\n# One-time setup.\nclass Foo(object):\ndef __init__(self, input_):\nself._input = input_\ndef value(self):\nreturn tf.constant(42.)\n\ntf.register_tensor_conversion_function(\nFoo, lambda x, *args, **kwargs: x.value())\n\ntf.keras.__internal__.utils.register_symbolic_tensor_type(Foo)\n\n# User-land.\nlayer = tf.keras.layers.Lambda(lambda input_: Foo(input_))\n```\n\nArgs:\ncls: A `class` type which shall be regarded as a symbolic `Tensor`.", "source": "github-repos"}
881{"code": "def run_ops(state, serial=False, no_wait=False):\n state.deploying = True\n if serial:\n _run_serial_ops(state)\n elif no_wait:\n _run_no_wait_ops(state)\n for op_hash in state.get_op_order():\n _run_single_op(state, op_hash)", "docstring": "Runs all operations across all servers in a configurable manner.\n\nArgs:\nstate (``pyinfra.api.State`` obj): the deploy state to execute\nserial (boolean): whether to run operations host by host\nno_wait (boolean): whether to wait for all hosts between operations", "source": "codesearchnet"}
882{"code": "def _stop_trial(self, trial, error=False, error_msg=None, stop_logger=True):\n if stop_logger:\n trial.close_logger()\n if error:\n self.set_status(trial, Trial.ERROR)\n else:\n self.set_status(trial, Trial.TERMINATED)\n try:\n trial.write_error_log(error_msg)\n if (hasattr(trial, 'runner') and trial.runner):\n if ((not error) and self._reuse_actors and (self._cached_actor is None)):\n logger.debug('Reusing actor for {}'.format(trial.runner))\n self._cached_actor = trial.runner\n else:\n logger.info('Destroying actor for trial {}. If your trainable is slow to initialize, consider setting reuse_actors=True to reduce actor creation overheads.'.format(trial))\n trial.runner.stop.remote()\n trial.runner.__ray_terminate__.remote()\n except Exception:\n logger.exception('Error stopping runner for Trial %s', str(trial))\n self.set_status(trial, Trial.ERROR)\n finally:\n trial.runner = None", "docstring": "Stops this trial.\n\nStops this trial, releasing all allocating resources. If stopping the\ntrial fails, the run will be marked as terminated in error, but no\nexception will be thrown.\n\nArgs:\nerror (bool): Whether to mark this trial as terminated in error.\nerror_msg (str): Optional error message.\nstop_logger (bool): Whether to shut down the trial logger.", "source": "codesearchnet"}
883{"code": "def count_up_to(self, limit):\n return state_ops.count_up_to(self._variable, limit=limit)", "docstring": "Increments this variable until it reaches `limit`.\n\nWhen that Op is run it tries to increment the variable by `1`. If\nincrementing the variable would bring it above `limit` then the Op raises\nthe exception `OutOfRangeError`.\n\nIf no error is raised, the Op outputs the value of the variable before\nthe increment.\n\nThis is essentially a shortcut for `count_up_to(self, limit)`.\n\nArgs:\nlimit: value at which incrementing the variable raises an error.\n\nReturns:\nA `Tensor` that will hold the variable value before the increment. If no\nother Op modifies this variable, the values produced will all be\ndistinct.", "source": "github-repos"}
884{"code": "def _ParseShellItem(self, parser_mediator, shell_item):\n \n path_segment = self._ParseShellItemPathSegment(shell_item)\n self._path_segments.append(path_segment)\n\n event_data = shell_item_events.ShellItemFileEntryEventData()\n event_data.origin = self._origin\n event_data.shell_item_path = self.CopyToPath()\n\n if isinstance(shell_item, pyfwsi.file_entry):\n event_data.name = shell_item.name\n\n for extension_block in shell_item.extension_blocks:\n if isinstance(extension_block, pyfwsi.file_entry_extension):\n long_name = extension_block.long_name\n localized_name = extension_block.localized_name\n file_reference = extension_block.file_reference\n if file_reference:\n file_reference = '{0:d}-{1:d}'.format(\n file_reference & 0xffffffffffff, file_reference >> 48)\n\n event_data.file_reference = file_reference\n event_data.localized_name = localized_name\n event_data.long_name = long_name\n\n fat_date_time = extension_block.get_creation_time_as_integer()\n if fat_date_time != 0:\n date_time = dfdatetime_fat_date_time.FATDateTime(\n fat_date_time=fat_date_time)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n fat_date_time = extension_block.get_access_time_as_integer()\n if fat_date_time != 0:\n date_time = dfdatetime_fat_date_time.FATDateTime(\n fat_date_time=fat_date_time)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n fat_date_time = shell_item.get_modification_time_as_integer()\n if fat_date_time != 0:\n date_time = dfdatetime_fat_date_time.FATDateTime(\n fat_date_time=fat_date_time)\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)", "docstring": "Parses a shell item.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nshell_item (pyfwsi.item): shell item.", "source": "juraj-google-style"}
885{"code": "def get_max_bond_lengths(structure, el_radius_updates=None):\n \n \n jmnn = JmolNN(el_radius_updates=el_radius_updates)\n\n bonds_lens = {}\n els = sorted(structure.composition.elements, key=lambda x: x.Z)\n\n for i1 in range(len(els)):\n for i2 in range(len(els) - i1):\n bonds_lens[els[i1], els[i1 + i2]] = jmnn.get_max_bond_distance(\n els[i1].symbol, els[i1 + i2].symbol)\n\n return bonds_lens", "docstring": "Provides max bond length estimates for a structure based on the JMol\ntable and algorithms.\n\nArgs:\nstructure: (structure)\nel_radius_updates: (dict) symbol->float to update atomic radii\n\nReturns: (dict) - (Element1, Element2) -> float. The two elements are\nordered by Z.", "source": "juraj-google-style"}
886{"code": "def get_dataset_end_date_as_datetime(self):\n dataset_date = self.data.get('dataset_date', None)\n if dataset_date:\n if ('-' in dataset_date):\n dataset_date = dataset_date.split('-')[1]\n return datetime.strptime(dataset_date, '%m/%d/%Y')\n return None", "docstring": "Get dataset end date as datetime.datetime object.\n\nReturns:\nOptional[datetime.datetime]: Dataset date in datetime object or None if no date is set", "source": "codesearchnet"}
887{"code": "def __init__(self, comma_compat=False):\n \n self._comma_compat = comma_compat\n name = 'whitespace or comma' if self._comma_compat else 'whitespace'\n super(WhitespaceSeparatedListParser, self).__init__(None, name)", "docstring": "Initializer.\n\nArgs:\ncomma_compat: bool, whether to support comma as an additional separator.\nIf False then only whitespace is supported. This is intended only for\nbackwards compatibility with flags that used to be comma-separated.", "source": "juraj-google-style"}
888{"code": "def remove_user(self, group, username):\n \n try:\n self.lookup_id(group)\n except ldap_tools.exceptions.InvalidResult as err: \n raise err from None\n\n operation = {'memberUid': [(ldap3.MODIFY_DELETE, [username])]}\n self.client.modify(self.__distinguished_name(group), operation)", "docstring": "Remove a user from the specified LDAP group.\n\nArgs:\ngroup: Name of group to update\nusername: Username of user to remove\n\nRaises:\nldap_tools.exceptions.InvalidResult:\nResults of the query were invalid. The actual exception raised\ninherits from InvalidResult. See #lookup_id for more info.", "source": "juraj-google-style"}
889{"code": "def get_status_tree(root_pipeline_id):\n \n root_pipeline_key = db.Key.from_path(_PipelineRecord.kind(), root_pipeline_id)\n root_pipeline_record = db.get(root_pipeline_key)\n if root_pipeline_record is None:\n raise PipelineStatusError(\n 'Could not find pipeline ID \"%s\"' % root_pipeline_id)\n\n \n \n actual_root_key = _PipelineRecord.root_pipeline.get_value_for_datastore(\n root_pipeline_record)\n if actual_root_key != root_pipeline_key:\n root_pipeline_key = actual_root_key\n root_pipeline_id = root_pipeline_key.id_or_name()\n root_pipeline_record = db.get(root_pipeline_key)\n if not root_pipeline_record:\n raise PipelineStatusError(\n 'Could not find pipeline ID \"%s\"' % root_pipeline_id)\n\n \n queries = {}\n for model in (_PipelineRecord, _SlotRecord, _BarrierRecord, _StatusRecord):\n queries[model] = model.all().filter(\n 'root_pipeline =', root_pipeline_key).run(batch_size=1000)\n\n found_pipeline_dict = dict(\n (stage.key(), stage) for stage in queries[_PipelineRecord])\n found_slot_dict = dict(\n (slot.key(), slot) for slot in queries[_SlotRecord])\n found_barrier_dict = dict(\n (barrier.key(), barrier) for barrier in queries[_BarrierRecord])\n found_status_dict = dict(\n (status.key(), status) for status in queries[_StatusRecord])\n\n \n \n valid_pipeline_keys = set([root_pipeline_key])\n slot_filler_dict = {} \n expand_stack = [root_pipeline_record]\n while expand_stack:\n old_stack = expand_stack\n expand_stack = []\n for pipeline_record in old_stack:\n for child_pipeline_key in pipeline_record.fanned_out:\n \n \n child_pipeline_record = found_pipeline_dict.get(child_pipeline_key)\n if child_pipeline_record is None:\n raise PipelineStatusError(\n 'Pipeline ID \"%s\" points to child ID \"%s\" which does not exist.'\n % (pipeline_record.key().name(), child_pipeline_key.name()))\n expand_stack.append(child_pipeline_record)\n valid_pipeline_keys.add(child_pipeline_key)\n\n \n \n \n child_outputs = child_pipeline_record.params['output_slots']\n for output_slot_key in child_outputs.itervalues():\n slot_filler_dict[db.Key(output_slot_key)] = child_pipeline_key\n\n output = {\n 'rootPipelineId': root_pipeline_id,\n 'slots': {},\n 'pipelines': {},\n }\n\n for pipeline_key in found_pipeline_dict.keys():\n if pipeline_key not in valid_pipeline_keys:\n continue\n output['pipelines'][pipeline_key.name()] = _get_internal_status(\n pipeline_key=pipeline_key,\n pipeline_dict=found_pipeline_dict,\n slot_dict=found_slot_dict,\n barrier_dict=found_barrier_dict,\n status_dict=found_status_dict)\n\n for slot_key, filler_pipeline_key in slot_filler_dict.iteritems():\n output['slots'][str(slot_key)] = _get_internal_slot(\n slot_key=slot_key,\n filler_pipeline_key=filler_pipeline_key,\n slot_dict=found_slot_dict)\n\n return output", "docstring": "Gets the full status tree of a pipeline.\n\nArgs:\nroot_pipeline_id: The pipeline ID to get status for.\n\nReturns:\nDictionary with the keys:\nrootPipelineId: The ID of the root pipeline.\nslots: Mapping of slot IDs to result of from _get_internal_slot.\npipelines: Mapping of pipeline IDs to result of _get_internal_status.\n\nRaises:\nPipelineStatusError if any input is bad.", "source": "juraj-google-style"}
890{"code": "def _prefix_from_ip_string(self, ip_str):\n \n \n try:\n ip_int = self._ip_int_from_string(ip_str)\n except AddressValueError:\n self._report_invalid_netmask(ip_str)\n\n \n \n \n try:\n return self._prefix_from_ip_int(ip_int)\n except ValueError:\n pass\n\n \n ip_int ^= self._ALL_ONES\n try:\n return self._prefix_from_ip_int(ip_int)\n except ValueError:\n self._report_invalid_netmask(ip_str)", "docstring": "Turn a netmask/hostmask string into a prefix length\n\nArgs:\nip_str: The netmask/hostmask to be converted\n\nReturns:\nAn integer, the prefix length.\n\nRaises:\nNetmaskValueError: If the input is not a valid netmask/hostmask", "source": "juraj-google-style"}
891{"code": "def set_servo_position(self, goalposition, goaltime, led):\n goalposition_msb = (int(goalposition) >> 8)\n goalposition_lsb = (int(goalposition) & 255)\n data = []\n data.append(12)\n data.append(self.servoid)\n data.append(I_JOG_REQ)\n data.append(goalposition_lsb)\n data.append(goalposition_msb)\n data.append(led)\n data.append(self.servoid)\n data.append(goaltime)\n send_data(data)", "docstring": "Set the position of Herkulex\n\nEnable torque using torque_on function before calling this\n\nArgs:\n\ngoalposition (int): The desired position, min-0 & max-1023\ngoaltime (int): the time taken to move from present\nposition to goalposition\nled (int): the LED color\n0x00 LED off\n0x04 GREEN\n0x08 BLUE\n0x10 RED", "source": "codesearchnet"}
892{"code": "def aggregate_repo(repo, args, sem, err_queue):\n try:\n logger.debug(('%s' % repo))\n dirmatch = args.dirmatch\n if (not match_dir(repo.cwd, dirmatch)):\n logger.info('Skip %s', repo.cwd)\n return\n if (args.command == 'aggregate'):\n repo.aggregate()\n if args.do_push:\n repo.push()\n elif (args.command == 'show-closed-prs'):\n repo.show_closed_prs()\n elif (args.command == 'show-all-prs'):\n repo.show_all_prs()\n except Exception:\n err_queue.put_nowait(sys.exc_info())\n finally:\n sem.release()", "docstring": "Aggregate one repo according to the args.\n\nArgs:\nrepo (Repo): The repository to aggregate.\nargs (argparse.Namespace): CLI arguments.", "source": "codesearchnet"}
893{"code": "def send(self, value):\n if ((not self.block) and (self._stdin is not None)):\n self.writer.write('{}\\n'.format(value))\n return self\n else:\n raise TypeError(NON_BLOCKING_ERROR_MESSAGE)", "docstring": "Send text to stdin. Can only be used on non blocking commands\n\nArgs:\nvalue (str): the text to write on stdin\nRaises:\nTypeError: If command is blocking\nReturns:\nShellCommand: return this ShellCommand instance for chaining", "source": "codesearchnet"}
894{"code": "def add_argument_to(self, parser):\n from devassistant.cli.devassistant_argparse import DefaultIffUsedActionFactory\n if isinstance(self.kwargs.get('action', ''), list):\n if (self.kwargs['action'][0] == 'default_iff_used'):\n self.kwargs['action'] = DefaultIffUsedActionFactory.generate_action(self.kwargs['action'][1])\n self.kwargs.pop('preserved', None)\n try:\n parser.add_argument(*self.flags, **self.kwargs)\n except Exception as ex:\n problem = \"Error while adding argument '{name}': {error}\".format(name=self.name, error=repr(ex))\n raise exceptions.ExecutionException(problem)", "docstring": "Used by cli to add this as an argument to argparse parser.\n\nArgs:\nparser: parser to add this argument to", "source": "codesearchnet"}
895{"code": "def convert_sum(\n params, w_name, scope_name, inputs, layers, weights, names\n):\n \n print('Converting Sum ...')\n\n def target_layer(x):\n import keras.backend as K\n return K.sum(x)\n\n lambda_layer = keras.layers.Lambda(target_layer)\n layers[scope_name] = lambda_layer(layers[inputs[0]])", "docstring": "Convert sum.\n\nArgs:\nparams: dictionary with layer parameters\nw_name: name prefix in state_dict\nscope_name: pytorch scope name\ninputs: pytorch node inputs\nlayers: dictionary with keras tensors\nweights: pytorch state_dict\nnames: use short names for keras layers", "source": "juraj-google-style"}
896{"code": "def __init__(self, transitions):\n \n self._transitions = {}\n self._order = []\n for trdef in transitions:\n self._transitions[trdef.name] = trdef\n self._order.append(trdef.name)", "docstring": "Create a TransitionList.\n\nArgs:\ntransitions (list of (name, source, target) tuple): the transitions\nto include.", "source": "juraj-google-style"}
897{"code": "def tan(cls, x: 'TensorFluent') -> 'TensorFluent':\n \n return cls._unary_op(x, tf.tan, tf.float32)", "docstring": "Returns a TensorFluent for the tan function.\n\nArgs:\nx: The input fluent.\n\nReturns:\nA TensorFluent wrapping the tan function.", "source": "juraj-google-style"}
898{"code": "def WatchMetadata(self, handler, metadata_key='', recursive=True, timeout=None):\n while True:\n response = self._HandleMetadataUpdate(metadata_key=metadata_key, recursive=recursive, wait=True, timeout=timeout)\n try:\n handler(response)\n except Exception as e:\n self.logger.exception('Exception calling the response handler. %s.', e)", "docstring": "Watch for changes to the contents of the metadata server.\n\nArgs:\nhandler: callable, a function to call with the updated metadata contents.\nmetadata_key: string, the metadata key to watch for changes.\nrecursive: bool, True if we should recursively watch for metadata changes.\ntimeout: int, timeout in seconds for returning metadata output.", "source": "codesearchnet"}
899{"code": "def get_special_tokens_mask(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None, already_has_special_tokens: bool=False) -> List[int]:\n if already_has_special_tokens:\n return super().get_special_tokens_mask(token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True)\n if token_ids_1 is None:\n return [1] + [0] * len(token_ids_0) + [1]\n return [1] + [0] * len(token_ids_0) + [1, 1] + [0] * len(token_ids_1) + [1]", "docstring": "Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding\nspecial tokens using the tokenizer `prepare_for_model` method.\n\nArgs:\ntoken_ids_0 (`List[int]`):\nList of IDs.\ntoken_ids_1 (`List[int]`, *optional*):\nOptional second list of IDs for sequence pairs.\nalready_has_special_tokens (`bool`, *optional*, defaults to `False`):\nWhether or not the token list is already formatted with special tokens for the model.\n\nReturns:\n`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.", "source": "github-repos"}
900{"code": "def _upload_code(s3_conn, bucket, prefix, name, contents, content_hash, payload_acl):\n logger.debug('lambda: ZIP hash: %s', content_hash)\n key = '{}lambda-{}-{}.zip'.format(prefix, name, content_hash)\n if _head_object(s3_conn, bucket, key):\n logger.info('lambda: object %s already exists, not uploading', key)\n else:\n logger.info('lambda: uploading object %s', key)\n s3_conn.put_object(Bucket=bucket, Key=key, Body=contents, ContentType='application/zip', ACL=payload_acl)\n return Code(S3Bucket=bucket, S3Key=key)", "docstring": "Upload a ZIP file to S3 for use by Lambda.\n\nThe key used for the upload will be unique based on the checksum of the\ncontents. No changes will be made if the contents in S3 already match the\nexpected contents.\n\nArgs:\ns3_conn (botocore.client.S3): S3 connection to use for operations.\nbucket (str): name of the bucket to create.\nprefix (str): S3 prefix to prepend to the constructed key name for\nthe uploaded file\nname (str): desired name of the Lambda function. Will be used to\nconstruct a key name for the uploaded file.\ncontents (str): byte string with the content of the file upload.\ncontent_hash (str): md5 hash of the contents to be uploaded.\npayload_acl (str): The canned S3 object ACL to be applied to the\nuploaded payload\n\nReturns:\ntroposphere.awslambda.Code: CloudFormation Lambda Code object,\npointing to the uploaded payload in S3.\n\nRaises:\nbotocore.exceptions.ClientError: any error from boto3 is passed\nthrough.", "source": "codesearchnet"}
901{"code": "def GreaterThanOrEqualTo(self, value):\n \n self._awql = self._CreateSingleValueCondition(value, '>=')\n return self._query_builder", "docstring": "Sets the type of the WHERE clause as \"greater than or equal to\".\n\nArgs:\nvalue: The value to be used in the WHERE condition.\n\nReturns:\nThe query builder that this WHERE builder links to.", "source": "juraj-google-style"}
902{"code": "def assert_no_legacy_layers(layers):\n legacy_layers = [l for l in layers if getattr(l, '_is_legacy_layer', None)]\n if legacy_layers:\n layer_str = '\\n'.join((' ' + str(l) for l in legacy_layers))\n raise TypeError('The following are legacy tf.layers.Layers:\\n{}\\nTo use keras as a framework (for instance using the Network, Model, or Sequential classes), please use the tf.keras.layers implementation instead. (Or, if writing custom layers, subclass from tf.keras.layers rather than tf.layers)'.format(layer_str))", "docstring": "Prevent tf.layers.Layers from being used with Keras.\n\nCertain legacy layers inherit from their keras analogs; however they are\nnot supported with keras and can lead to subtle and hard to diagnose bugs.\n\nArgs:\nlayers: A list of layers to check\n\nRaises:\nTypeError: If any elements of layers are tf.layers.Layers", "source": "github-repos"}
903{"code": "def get_path(self, temp_ver):\n \n if temp_ver not in self:\n raise RuntimeError(\n 'Template: {} not present'.format(temp_ver.name)\n )\n return self._prefixed(temp_ver.name)", "docstring": "Get the path of the given version in this store\n\nArgs:\ntemp_ver TemplateVersion: version to look for\n\nReturns:\nstr: The path to the template version inside the store\n\nRaises:\nRuntimeError: if the template is not in the store", "source": "juraj-google-style"}
904{"code": "def _check_full_tensor_value(self, tensor_value, wall_time, op_type, output_slot, execution_index=None, graph_execution_trace_index=None):\n size = np.size(tensor_value)\n if not size or not np.issubdtype(tensor_value.dtype, np.floating):\n return\n is_inf = np.isinf(tensor_value)\n num_neg_inf = np.count_nonzero(np.logical_and(is_inf, np.less(tensor_value, 0.0)))\n num_pos_inf = np.count_nonzero(np.logical_and(is_inf, np.greater(tensor_value, 0.0)))\n num_nan = np.count_nonzero(np.isnan(tensor_value))\n if num_neg_inf or num_pos_inf or num_nan:\n self._alerts.append(InfNanAlert(wall_time, op_type, output_slot, size=size, num_neg_inf=num_neg_inf, num_pos_inf=num_pos_inf, num_nan=num_nan, execution_index=execution_index, graph_execution_trace_index=graph_execution_trace_index))", "docstring": "Check a full tensor value.\n\nAppends to the list of alerts if any inf or nan is found in the full tensor\nvalue.\n\nArgs:\ntensor_value: The full tensor value as a `np.ndarray`.\nwall_time: Wall timestamp for the execution event that generated the\ntensor value.\nop_type: Op type executed.\noutput_slot: The output slot of the op.\nexecution_index: Index to the top-level execution event.\ngraph_execution_trace_index: Index to the intra-graph execution trace\n(if applicable.)", "source": "github-repos"}
905{"code": "def power(self, n):\n if (not isinstance(n, (int, np.integer))):\n raise QiskitError('Can only power with integer powers.')\n if (self._input_dim != self._output_dim):\n raise QiskitError('Can only power with input_dim = output_dim.')\n return SuperOp(np.linalg.matrix_power(self._data, n), self.input_dims(), self.output_dims())", "docstring": "Return the compose of a QuantumChannel with itself n times.\n\nArgs:\nn (int): compute the matrix power of the superoperator matrix.\n\nReturns:\nSuperOp: the n-times composition channel as a SuperOp object.\n\nRaises:\nQiskitError: if the input and output dimensions of the\nQuantumChannel are not equal, or the power is not an integer.", "source": "codesearchnet"}
906{"code": "def _check_consistent_returns(self, node):\n \n \n explicit_returns = [\n _node for _node in self._return_nodes[node.name] if _node.value is not None\n ]\n if not explicit_returns:\n return\n if len(explicit_returns) == len(\n self._return_nodes[node.name]\n ) and self._is_node_return_ended(node):\n return\n self.add_message(\"inconsistent-return-statements\", node=node)", "docstring": "Check that all return statements inside a function are consistent.\n\nReturn statements are consistent if:\n- all returns are explicit and if there is no implicit return;\n- all returns are empty and if there is, possibly, an implicit return.\n\nArgs:\nnode (astroid.FunctionDef): the function holding the return statements.", "source": "juraj-google-style"}
907{"code": "def skip_if(condition: Union[Callable[[], bool], bool]) -> Callable[[_F], _F]:\n\n def real_skip_if(fn: _F) -> _F:\n\n def wrapper(*args, **kwargs):\n if callable(condition):\n skip = condition()\n else:\n skip = condition\n if not skip:\n return fn(*args, **kwargs)\n return wrapper\n return real_skip_if", "docstring": "Skips the decorated function if condition is or evaluates to True.\n\nArgs:\ncondition: Either an expression that can be used in \"if not condition\"\nstatement, or a callable whose result should be a boolean.\n\nReturns:\nThe wrapped function", "source": "github-repos"}
908{"code": "def mesh_axis_to_tensor_axis(self, mesh_ndims):\n ta2ma = self._tensor_axis_to_mesh_axis\n return tuple([(ta2ma.index(mesh_axis) if (mesh_axis in ta2ma) else None) for mesh_axis in xrange(mesh_ndims)])", "docstring": "For each mesh axis, which Tensor axis maps to it.\n\nArgs:\nmesh_ndims: int.\n\nReturns:\nTuple of optional integers, with length mesh_ndims.", "source": "codesearchnet"}
909{"code": "def add_maps(self, parent, root_path=\"\"):\n \n for mapsource in self.map_folders[root_path]['maps']:\n parent.append(self.get_network_link(mapsource))\n for folder in self.map_folders[root_path]['folders']:\n kml_folder_obj = kml_folder(folder)\n parent.append(kml_folder_obj)\n self.add_maps(parent=kml_folder_obj, root_path=F_SEP.join((root_path, folder)))", "docstring": "Recursively add maps in a folder hierarchy.\n\nArgs:\nparent (KMLElement): KMLElement to which we want to append child folders or maps respectively\nroot_path (str): path of 'parent'", "source": "juraj-google-style"}
910{"code": "def get_soap_structure(obj, alp, bet, rCut=5.0, nMax=5, Lmax=5, crossOver=True, all_atomtypes=None, eta=1.0):\n Hpos = obj.get_positions()\n arrsoap = get_soap_locals(obj, Hpos, alp, bet, rCut, nMax, Lmax, crossOver, all_atomtypes=all_atomtypes, eta=eta)\n return arrsoap", "docstring": "Get the RBF basis SOAP output for atoms in a finite structure.\n\nArgs:\nobj(ase.Atoms): Atomic structure for which the SOAP output is\ncalculated.\nalp: Alphas\nbet: Betas\nrCut: Radial cutoff.\nnMax: Maximum nmber of radial basis functions\nLmax: Maximum spherical harmonics degree\ncrossOver:\nall_atomtypes: Can be used to specify the atomic elements for which to\ncalculate the output. If given the output is calculated only for the\ngiven species.\neta: The gaussian smearing width.\n\nReturns:\nnp.ndarray: SOAP output for the given structure.", "source": "codesearchnet"}
911{"code": "def match_main(self, text, pattern, loc):\n if ((text == None) or (pattern == None)):\n raise ValueError('Null inputs. (match_main)')\n loc = max(0, min(loc, len(text)))\n if (text == pattern):\n return 0\n elif (not text):\n return (- 1)\n elif (text[loc:(loc + len(pattern))] == pattern):\n return loc\n else:\n match = self.match_bitap(text, pattern, loc)\n return match", "docstring": "Locate the best instance of 'pattern' in 'text' near 'loc'.\n\nArgs:\ntext: The text to search.\npattern: The pattern to search for.\nloc: The location to search around.\n\nReturns:\nBest match index or -1.", "source": "codesearchnet"}
912{"code": "def get_num_bytes(self, batch: Sequence[numpy.ndarray]) -> int:\n return sum((sys.getsizeof(element) for element in batch))", "docstring": "Returns:\nThe number of bytes of data for a batch.", "source": "github-repos"}
913{"code": "def __init__(self, config_files, mask_surface=True, mask_quality=True, **kwargs):\n \n self.pressure_dataset_names = defaultdict(list)\n super(NUCAPSReader, self).__init__(config_files,\n **kwargs)\n self.mask_surface = self.info.get('mask_surface', mask_surface)\n self.mask_quality = self.info.get('mask_quality', mask_quality)", "docstring": "Configure reader behavior.\n\nArgs:\nmask_surface (boolean): mask anything below the surface pressure\nmask_quality (boolean): mask anything where the `Quality_Flag` metadata is ``!= 1``.", "source": "juraj-google-style"}
914{"code": "def List(self, request, global_params=None):\n config = self.GetMethodConfig('List')\n return self._RunMethod(config, request, global_params=global_params)", "docstring": "Lists existing `BuildTrigger`s. This API is experimental.\n\nArgs:\nrequest: (CloudbuildProjectsTriggersListRequest) input message\nglobal_params: (StandardQueryParameters, default: None) global arguments\nReturns:\n(ListBuildTriggersResponse) The response message.", "source": "github-repos"}
915{"code": "def in_cross_replica_context():\n return _get_per_thread_mode().cross_replica_context is not None", "docstring": "Returns `True` if in a cross-replica context.\n\nSee `tf.distribute.get_replica_context` for details.\n\n```\nassert not tf.distribute.in_cross_replica_context()\nwith strategy.scope():\nassert tf.distribute.in_cross_replica_context()\n\ndef f():\nassert not tf.distribute.in_cross_replica_context()\n\nstrategy.run(f)\n```\n\nReturns:\n`True` if in a cross-replica context (`get_replica_context()` returns\n`None`), or `False` if in a replica context (`get_replica_context()` returns\nnon-`None`).", "source": "github-repos"}
916{"code": "def categorical_case(pmf, fns, rand=None):\n \n rand = tf.random_uniform([]) if rand is None else rand\n cmf = tf.pad(tf.cumsum(pmf), [(1, 0)])\n cmf = [cmf[i] for i in range(len(fns) + 1)]\n preds = [(rand >= a) & (rand < b) for a, b in zip(cmf[:-1], cmf[1:])]\n return tf.case(list(zip(preds, fns)), exclusive=True)", "docstring": "Returns the outputs of fns[i] with probability pmf[i].\n\nArgs:\npmf: A 1-D tensor of probabilities, the probability mass function.\nfns: A list of callables that return tensors, same length as pmf.\nrand: An optional scalar between 0.0 and 1.0, the output of an RNG.\n\nReturns:\nA tensor, the output of fns[i] with probability pmf[i].", "source": "juraj-google-style"}
917{"code": "def label_total_duration(self, label_list_ids=None):\n duration = collections.defaultdict(float)\n for label_list in self.label_lists.values():\n if ((label_list_ids is None) or (label_list.idx in label_list_ids)):\n for (label_value, label_duration) in label_list.label_total_duration().items():\n duration[label_value] += label_duration\n return duration", "docstring": "Return a dictionary containing the number of seconds,\nevery label-value is occurring in this utterance.\n\nArgs:\nlabel_list_ids (list): If not None, only labels from label-lists\nwith an id contained in this\nlist are considered.\n\nReturns:\ndict: A dictionary containing the number of seconds\nwith the label-value as key.", "source": "codesearchnet"}
918{"code": "def Normal(cls,\n mean: 'TensorFluent', variance: 'TensorFluent',\n batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:\n \n if mean.scope != variance.scope:\n raise ValueError('Normal distribution: parameters must have same scope!')\n loc = mean.tensor\n scale = tf.sqrt(variance.tensor)\n dist = tf.distributions.Normal(loc, scale)\n batch = mean.batch or variance.batch\n if not batch and batch_size is not None:\n t = dist.sample(batch_size)\n batch = True\n else:\n t = dist.sample()\n scope = mean.scope.as_list()\n return (dist, TensorFluent(t, scope, batch=batch))", "docstring": "Returns a TensorFluent for the Normal sampling op with given mean and variance.\n\nArgs:\nmean: The mean parameter of the Normal distribution.\nvariance: The variance parameter of the Normal distribution.\nbatch_size: The size of the batch (optional).\n\nReturns:\nThe Normal distribution and a TensorFluent sample drawn from the distribution.\n\nRaises:\nValueError: If parameters do not have the same scope.", "source": "juraj-google-style"}
919{"code": "def get_policy(self, name):\n \n\n address = _create_policy_address(name)\n policy_list_bytes = None\n\n try:\n policy_list_bytes = self._state_view.get(address=address)\n except KeyError:\n return None\n\n if policy_list_bytes is not None:\n policy_list = _create_from_bytes(policy_list_bytes,\n identity_pb2.PolicyList)\n for policy in policy_list.policies:\n if policy.name == name:\n return policy\n return None", "docstring": "Get a single Policy by name.\n\nArgs:\nname (str): The name of the Policy.\n\nReturns:\n(:obj:`Policy`) The Policy that matches the name.", "source": "juraj-google-style"}
920{"code": "def _maybe_set_tnp_casting(xnp: numpy_utils.NpModule) -> None:\n if not numpy_utils.lazy.has_tf or xnp is not numpy_utils.lazy.tnp:\n return\n if not numpy_utils.lazy.is_tnp_enabled:\n from tensorflow.python.ops.numpy_ops import np_dtypes\n if not np_dtypes.is_prefer_float32():\n np_dtypes.set_prefer_float32(True)\n msg = epy.dedent('\\n WARNING: Using array types for TF but without numpy mode enabled. It\\n is recommended to activate numpy mode as:\\n\\n import tensorflow.experimental.numpy as tnp\\n tnp.experimental_enable_numpy_behavior(prefer_float32=True)\\n ')\n print(msg)", "docstring": "If TF numpy mode is not set, make sure `tnp.asarray(1.)` is `tf.float32`.\n\nIf user uses TF without numpy mode, it will create casting issues (for\nexample: `tf.float64 + tf.float32` will raise an error).\nTo limit the errors encountered, we set `tnp.asarray(1.)` to `tf.float32`\ninstead of `tf.float64`.\n\nIf numpy mode is already activated, then no need to do anything, as\n`tf.float64 + tf.float32` will support auto-casting, like Jax and Numpy.\n\nArgs:\nxnp: numpy module.", "source": "github-repos"}
921{"code": "def GetNetworkAddressWithTime(self):\n if ((self.port is not None) and (self.host is not None) and (self.Version is not None)):\n return NetworkAddressWithTime(self.host, self.port, self.Version.Services)\n return None", "docstring": "Get a network address object.\n\nReturns:\nNetworkAddressWithTime: if we have a connection to a node.\nNone: otherwise.", "source": "codesearchnet"}
922{"code": "def write(self, obj: (BioCDocument or BioCPassage or BioCSentence)):\n if ((self.level == DOCUMENT) and (not isinstance(obj, BioCDocument))):\n raise ValueError\n if ((self.level == PASSAGE) and (not isinstance(obj, BioCPassage))):\n raise ValueError\n if ((self.level == SENTENCE) and (not isinstance(obj, BioCSentence))):\n raise ValueError\n self.writer.write(BioCJSONEncoder().default(obj))", "docstring": "Encode and write a single object.\n\nArgs:\nobj: an instance of BioCDocument, BioCPassage, or BioCSentence\n\nReturns:", "source": "codesearchnet"}
923{"code": "def get_metrics(weights: Array, dataset: Dataset) -> Metrics:\n pred = dataset.X.dot(weights) > 0\n actual = dataset.Y\n tp: int = jnp.sum(jnp.logical_and(pred == 1, actual == 1))\n tn: int = jnp.sum(jnp.logical_and(pred == 0, actual == 0))\n fp: int = jnp.sum(jnp.logical_and(pred == 1, actual == 0))\n fn: int = jnp.sum(jnp.logical_and(pred == 0, actual == 1))\n loss: float = cross_entropy_loss(weights, dataset.X, dataset.Y)\n accuracy = (tp + tn) / (tp + tn + fp + fn)\n precision = tp / (tp + fp + EPSILON)\n recall = tp / (tp + fn + EPSILON)\n fscore = 2 * precision * recall / (precision + recall + EPSILON)\n return Metrics(tp=tp, tn=tn, fp=fp, fn=fn, accuracy=accuracy, precision=precision, recall=recall, fscore=fscore, loss=loss)", "docstring": "Gets evaluation metrics from the learned weight vector and the dataset.\n\nArgs:\nweights: A weight vector.\ndataset: A dataset.\n\nReturns:\nresult (Metrics): The metrics over the given weights and the dataset.", "source": "github-repos"}
924{"code": "def __call__(self, argv, known_only=False):\n \n if not argv:\n \n \n self.MarkAsParsed()\n self._AssertAllValidators()\n return []\n\n \n program_name = argv[0]\n args = self.ReadFlagsFromFiles(argv[1:], force_gnu=False)\n\n \n unknown_flags, unparsed_args, undefok = self._ParseArgs(args, known_only)\n\n \n \n for name, value in unknown_flags:\n if name in undefok:\n continue\n\n suggestions = _helpers.GetFlagSuggestions(\n name, self.RegisteredFlags())\n raise exceptions.UnrecognizedFlagError(\n name, value, suggestions=suggestions)\n\n self.MarkAsParsed()\n self._AssertAllValidators()\n return [program_name] + unparsed_args", "docstring": "Parses flags from argv; stores parsed flags into this FlagValues object.\n\nAll unparsed arguments are returned.\n\nArgs:\nargv: argument list. Can be of any type that may be converted to a list.\nknown_only: parse and remove known flags, return rest untouched.\n\nReturns:\nThe list of arguments not parsed as options, including argv[0].\n\nRaises:\nError: on any parsing error.\nValueError: on flag value parsing error.", "source": "juraj-google-style"}
925{"code": "def get_utt_regions(self):\n regions = []\n current_offset = 0\n for utt_idx in sorted(self.utt_ids):\n offset = current_offset\n num_frames = []\n refs = []\n for cnt in self.containers:\n num_frames.append(cnt.get(utt_idx).shape[0])\n refs.append(cnt.get(utt_idx, mem_map=True))\n if (len(set(num_frames)) != 1):\n raise ValueError('Utterance {} has not the same number of frames in all containers!'.format(utt_idx))\n num_chunks = math.ceil((num_frames[0] / float(self.frames_per_chunk)))\n region = (offset, num_chunks, refs)\n regions.append(region)\n current_offset += num_chunks\n return regions", "docstring": "Return the regions of all utterances, assuming all utterances are concatenated.\nIt is assumed that the utterances are sorted in ascending order for concatenation.\n\nA region is defined by offset (in chunks), length (num-chunks) and\na list of references to the utterance datasets in the containers.\n\nReturns:\nlist: List of with a tuple for every utterances containing the region info.", "source": "codesearchnet"}
926{"code": "def _desired_sdk_filename_in_staging_location(sdk_location) -> str:\n if sdk_location.endswith('.whl'):\n _, wheel_filename = FileSystems.split(sdk_location)\n if wheel_filename.startswith('apache_beam'):\n return wheel_filename\n else:\n raise RuntimeError('Unrecognized SDK wheel file: %s' % sdk_location)\n else:\n return names.STAGED_SDK_SOURCES_FILENAME", "docstring": "Returns the name that SDK file should have in the staging location.\nArgs:\nsdk_location: Full path to SDK file.", "source": "github-repos"}
927{"code": "def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color='gray'):\n return field(field_name, CategoricalColorMapper(palette=palette, factors=factors, start=start, end=end, nan_color=nan_color))", "docstring": "Create a ``DataSpec`` dict that applies a client-side\n``CategoricalColorMapper`` transformation to a ``ColumnDataSource``\ncolumn.\n\nArgs:\nfield_name (str) : a field name to configure ``DataSpec`` with\n\npalette (seq[color]) : a list of colors to use for colormapping\n\nfactors (seq) : a sequences of categorical factors corresponding to\nthe palette\n\nstart (int, optional) : a start slice index to apply when the column\ndata has factors with multiple levels. (default: 0)\n\nend (int, optional) : an end slice index to apply when the column\ndata has factors with multiple levels. (default: None)\n\nnan_color (color, optional) : a default color to use when mapping data\nfrom a column does not succeed (default: \"gray\")\n\nReturns:\ndict", "source": "codesearchnet"}
928{"code": "def simple_generate(cls, create, **kwargs):\n \n strategy = enums.CREATE_STRATEGY if create else enums.BUILD_STRATEGY\n return cls.generate(strategy, **kwargs)", "docstring": "Generate a new instance.\n\nThe instance will be either 'built' or 'created'.\n\nArgs:\ncreate (bool): whether to 'build' or 'create' the instance.\n\nReturns:\nobject: the generated instance", "source": "juraj-google-style"}
929{"code": "def setup(self, universe):\n \n \n \n try:\n prices = universe[self.name]\n except KeyError:\n prices = None\n\n \n if prices is not None:\n self._prices = prices\n self.data = pd.DataFrame(index=universe.index,\n columns=['value', 'position'],\n data=0.0)\n self._prices_set = True\n else:\n self.data = pd.DataFrame(index=universe.index,\n columns=['price', 'value', 'position'])\n self._prices = self.data['price']\n self._prices_set = False\n\n self._values = self.data['value']\n self._positions = self.data['position']\n\n \n self.data['outlay'] = 0.\n self._outlays = self.data['outlay']", "docstring": "Setup Security with universe. Speeds up future runs.\n\nArgs:\n* universe (DataFrame): DataFrame of prices with security's name as\none of the columns.", "source": "juraj-google-style"}
930{"code": "def match_tracks(self, model_tracks, obs_tracks, unique_matches=True, closest_matches=False):\n \n if unique_matches:\n pairings = self.track_matcher.match_tracks(model_tracks, obs_tracks, closest_matches=closest_matches)\n else:\n pairings = self.track_matcher.neighbor_matches(model_tracks, obs_tracks)\n return pairings", "docstring": "Match forecast and observed tracks.\n\nArgs:\nmodel_tracks:\nobs_tracks:\nunique_matches:\nclosest_matches:\n\nReturns:", "source": "juraj-google-style"}
931{"code": "def load_model(model_cls_path, model_cls_name, model_load_args):\n \n spec = importlib.util.spec_from_file_location('active_model',\n model_cls_path)\n model_module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(model_module)\n model_cls = getattr(model_module, model_cls_name)\n model = model_cls()\n if not isinstance(model, BaseModel):\n warnings.warn(\"Loaded model '%s' at '%s' is not an instance of %r\"\n % (model_cls_name, model_cls_path, BaseModel))\n model.load(**model_load_args)\n return model", "docstring": "Get an instance of the described model.\n\nArgs:\nmodel_cls_path: Path to the module in which the model class\nis defined.\nmodel_cls_name: Name of the model class.\nmodel_load_args: Dictionary of args to pass to the `load` method\nof the model instance.\n\nReturns:\nAn instance of :class:`.models.model.BaseModel` or subclass", "source": "juraj-google-style"}
932{"code": "def merge(self, other_roc):\n \n if other_roc.thresholds.size == self.thresholds.size and np.all(other_roc.thresholds == self.thresholds):\n self.contingency_tables += other_roc.contingency_tables\n else:\n print(\"Input table thresholds do not match.\")", "docstring": "Ingest the values of another DistributedROC object into this one and update the statistics inplace.\n\nArgs:\nother_roc: another DistributedROC object.", "source": "juraj-google-style"}
933{"code": "def _scope_vals(self, vals):\n if isinstance(vals, (list, tuple)):\n return vals\n elif isinstance(vals, dict):\n return vals.values()\n else:\n return [vals]", "docstring": "Return a list of values to pass to `name_scope()`.\n\nArgs:\nvals: A tensor, a list or tuple of tensors, or a dictionary.\n\nReturns:\nThe values in vals as a list.", "source": "github-repos"}
934{"code": "def __init__(self, instance_id: str = None):\n \n self.instance_id = instance_id\n if instance_id:\n self.channel_id += \"", "docstring": "Initialize the channel.\nInherited initializer must call the \"super init\" method\nat the beginning.\n\nArgs:\ninstance_id: Instance ID of the channel.", "source": "juraj-google-style"}
935{"code": "def is_same_vectors(self, vec_set1, vec_set2):\n \n if (np.absolute(rel_strain(vec_set1[0], vec_set2[0])) >\n self.max_length_tol):\n return False\n elif (np.absolute(rel_strain(vec_set1[1], vec_set2[1])) >\n self.max_length_tol):\n return False\n elif (np.absolute(rel_angle(vec_set1, vec_set2)) >\n self.max_angle_tol):\n return False\n else:\n return True", "docstring": "Determine if two sets of vectors are the same within length and angle\ntolerances\n\nArgs:\nvec_set1(array[array]): an array of two vectors\nvec_set2(array[array]): second array of two vectors", "source": "juraj-google-style"}
936{"code": "def watermark_text(image, text, corner=2):\n FONT_PATH = ''\n if resource_exists(__name__, 'resources/fonts/SourceSansPro-Regular.ttf'):\n FONT_PATH = resource_filename(__name__, 'resources/fonts/SourceSansPro-Regular.ttf')\n padding = 5\n was_P = (image.mode == 'P')\n was_L = (image.mode == 'L')\n if (image.mode not in ['RGB', 'RGBA']):\n if (image.format in ['JPG', 'JPEG']):\n image = image.convert('RGB')\n else:\n image = image.convert('RGBA')\n img_draw = ImageDraw.Draw(image)\n fontsize = 1\n img_fraction = 0.05\n try:\n font = ImageFont.truetype(font=FONT_PATH, size=fontsize)\n was_over = False\n inc = 2\n while True:\n if (font.getsize(text)[1] > (img_fraction * image.height)):\n if (not was_over):\n was_over = True\n inc = (- 1)\n elif was_over:\n break\n fontsize += inc\n font = ImageFont.truetype(font=FONT_PATH, size=fontsize)\n fontsize -= 1\n font = ImageFont.truetype(font=FONT_PATH, size=fontsize)\n except:\n print('Failed to load Aperture font. Using default font instead.')\n font = ImageFont.load_default()\n pos = get_pos(corner, image.size, font.getsize(text), padding)\n img_draw.text(((pos[0] - 1), pos[1]), text, font=font, fill='black')\n img_draw.text(((pos[0] + 1), pos[1]), text, font=font, fill='black')\n img_draw.text((pos[0], (pos[1] - 1)), text, font=font, fill='black')\n img_draw.text((pos[0], (pos[1] + 1)), text, font=font, fill='black')\n img_draw.text(pos, text, font=font, fill='white')\n cleanup_resources()\n del img_draw\n if was_P:\n image = image.convert('P', palette=Image.ADAPTIVE, colors=256)\n elif was_L:\n image = image.convert('L')\n return image", "docstring": "Adds a text watermark to an instance of a PIL Image.\n\nThe text will be sized so that the height of the text is\nroughly 1/20th the height of the base image. The text will\nbe white with a thin black outline.\n\nArgs:\nimage: An instance of a PIL Image. This is the base image.\ntext: Text to use as a watermark.\ncorner: An integer between 0 and 3 representing the corner\nwhere the watermark image should be placed on top of the\nbase image. 0 is top left, 1 is top right, 2 is bottom\nright and 3 is bottom left. NOTE: Right now, this is\npermanently set to 2 (bottom right) but this can be\nchanged in the future by either creating a new cmd-line\nflag or putting this in the config file.\n\nReturns: The watermarked image", "source": "codesearchnet"}
937{"code": "def orbit2frame(name, ref_orbit, orientation=None, center=None, bypass=False):\n if (orientation is None):\n orientation = ref_orbit.frame.orientation\n elif (orientation.upper() in ('RSW', 'LVLH')):\n orientation = 'QSW'\n elif (orientation.upper() not in ('QSW', 'TNW')):\n raise ValueError((\"Unknown orientation '%s'\" % orientation))\n if (center is None):\n center = Earth\n\n def _to_parent_frame(self):\n 'Conversion from orbit frame to parent frame\\n '\n offset = ref_orbit.propagate(self.date).base.copy()\n if (orientation.upper() in ('QSW', 'TNW')):\n orb = ref_orbit.propagate(self.date)\n m = (to_qsw(orb) if (orientation.upper() == 'QSW') else to_tnw(orb))\n rotation = Frame._convert(m, m).T\n else:\n rotation = np.identity(6)\n return (rotation, offset)\n mtd = ('_to_%s' % ref_orbit.frame.__name__)\n dct = {mtd: _to_parent_frame, 'orientation': orientation, 'center': center, 'bypass': bypass}\n cls = _MetaFrame(name, (Frame,), dct)\n (cls + ref_orbit.frame)\n return cls", "docstring": "Create a frame based on a Orbit or Ephem object.\n\nArgs:\nname (str): Name to give the created frame\nref_orbit (Orbit or Ephem):\norientation (str): Orientation of the created frame\nbypass (bool): By-pass the warning when creating a frame with an already\ntaken name\nReturn:\nFrame:\n\nIf orientation is ``None``, the new frame will keep the orientation of the\nreference frame of the Orbit and move along with the orbit.\nOther acceptable values are ``\"QSW\"`` (and its aliases \"LVLH\" and \"RSW\") or ``\"TNW\"``.\n\nSee :py:func:`~beyond.frames.local.to_qsw` and :py:func:`~beyond.frames.local.to_tnw`\nfor informations regarding these orientations.", "source": "codesearchnet"}
938{"code": "def _use_tables(objs):\n \n from ..models.widgets import TableWidget\n return _any(objs, lambda obj: isinstance(obj, TableWidget))", "docstring": "Whether a collection of Bokeh objects contains a TableWidget\n\nArgs:\nobjs (seq[Model or Document]) :\n\nReturns:\nbool", "source": "juraj-google-style"}
939{"code": "def assert_sequential_execution(order, operations):\n operations = sorted(operations, key=lambda op: order[op])\n for i in range(len(operations) - 1):\n if not _exists_dependency(operations[i], operations[i + 1]):\n print(operations[i].graph.as_graph_def())\n raise AssertionError('No dependency between {} and {}. Graph is dumped to stdout.'.format(operations[i].name, operations[i + 1].name))", "docstring": "Asserts there's a deterministic execution order between the operations.\n\nArgs:\norder: a map from a tf.Operation to its topological order.\noperations: a list of operations that should be executed sequentially. It\ncan be given in any order.", "source": "github-repos"}
940{"code": "def distribution(namespace: Union[Type, str], name: str) -> 'Metrics.DelegatingDistribution':\n namespace = Metrics.get_namespace(namespace)\n return Metrics.DelegatingDistribution(MetricName(namespace, name))", "docstring": "Obtains or creates a Distribution metric.\n\nDistribution metrics are restricted to integer-only distributions.\n\nArgs:\nnamespace: A class or string that gives the namespace to a metric\nname: A string that gives a unique name to a metric\n\nReturns:\nA Distribution object.", "source": "github-repos"}
941{"code": "def _sync_to_uri(self, uri):\n cmd_cp = 'aws s3 cp {} {} --recursive --profile {}'.format(self.s3_version_uri, uri, self.env)\n cmd_sync = 'aws s3 sync {} {} --delete --exact-timestamps --profile {}'.format(self.s3_version_uri, uri, self.env)\n cp_result = subprocess.run(cmd_cp, check=True, shell=True, stdout=subprocess.PIPE)\n LOG.debug('Copy to %s before sync output: %s', uri, cp_result.stdout)\n LOG.info('Copied version %s to %s', self.version, uri)\n sync_result = subprocess.run(cmd_sync, check=True, shell=True, stdout=subprocess.PIPE)\n LOG.debug('Sync to %s command output: %s', uri, sync_result.stdout)\n LOG.info('Synced version %s to %s', self.version, uri)", "docstring": "Copy and sync versioned directory to uri in S3.\n\nArgs:\nuri (str): S3 URI to sync version to.", "source": "codesearchnet"}
942{"code": "def _send_offset_requests(self, timestamps):\n \n timestamps_by_node = collections.defaultdict(dict)\n for partition, timestamp in six.iteritems(timestamps):\n node_id = self._client.cluster.leader_for_partition(partition)\n if node_id is None:\n self._client.add_topic(partition.topic)\n log.debug(\"Partition %s is unknown for fetching offset,\"\n \" wait for metadata refresh\", partition)\n return Future().failure(Errors.StaleMetadata(partition))\n elif node_id == -1:\n log.debug(\"Leader for partition %s unavailable for fetching \"\n \"offset, wait for metadata refresh\", partition)\n return Future().failure(\n Errors.LeaderNotAvailableError(partition))\n else:\n timestamps_by_node[node_id][partition] = timestamp\n\n \n list_offsets_future = Future()\n responses = []\n node_count = len(timestamps_by_node)\n\n def on_success(value):\n responses.append(value)\n if len(responses) == node_count:\n offsets = {}\n for r in responses:\n offsets.update(r)\n list_offsets_future.success(offsets)\n\n def on_fail(err):\n if not list_offsets_future.is_done:\n list_offsets_future.failure(err)\n\n for node_id, timestamps in six.iteritems(timestamps_by_node):\n _f = self._send_offset_request(node_id, timestamps)\n _f.add_callback(on_success)\n _f.add_errback(on_fail)\n return list_offsets_future", "docstring": "Fetch offsets for each partition in timestamps dict. This may send\nrequest to multiple nodes, based on who is Leader for partition.\n\nArguments:\ntimestamps (dict): {TopicPartition: int} mapping of fetching\ntimestamps.\n\nReturns:\nFuture: resolves to a mapping of retrieved offsets", "source": "juraj-google-style"}
943{"code": "def set_attribute(self, node: cfg.CFGNode, obj: abstract.BaseValue, name: str, value: cfg.Variable) -> cfg.CFGNode:\n if not self._check_writable(obj, name):\n return node\n if self.ctx.vm.frame is not None and obj is self.ctx.vm.frame.f_globals:\n for v in value.data:\n v.update_official_name(name)\n if isinstance(obj, abstract.Empty):\n return node\n elif isinstance(obj, abstract.Module):\n log.warning('Ignoring overwrite of %s.%s', obj.name, name)\n return node\n elif isinstance(obj, (abstract.StaticMethod, abstract.ClassMethod)):\n return self.set_attribute(node, obj.method, name, value)\n elif isinstance(obj, abstract.SimpleValue):\n return self._set_member(node, obj, name, value)\n elif isinstance(obj, abstract.BoundFunction):\n return self.set_attribute(node, obj.underlying, name, value)\n elif isinstance(obj, abstract.Unsolvable):\n return node\n elif isinstance(obj, abstract.Unknown):\n if name in obj.members:\n obj.members[name].PasteVariable(value, node)\n else:\n obj.members[name] = value.AssignToNewVariable(node)\n return node\n elif isinstance(obj, abstract.TypeParameterInstance):\n nodes = []\n for v in obj.instance.get_instance_type_parameter(obj.name).data:\n nodes.append(self.set_attribute(node, v, name, value))\n return self.ctx.join_cfg_nodes(nodes) if nodes else node\n elif isinstance(obj, abstract.Union):\n for option in obj.options:\n node = self.set_attribute(node, option, name, value)\n return node\n else:\n raise NotImplementedError(obj.__class__.__name__)", "docstring": "Set an attribute on an object.\n\nThe attribute might already have a Variable in it and in that case we cannot\noverwrite it and instead need to add the elements of the new variable to the\nold variable.\n\nArgs:\nnode: The current CFG node.\nobj: The object.\nname: The name of the attribute to set.\nvalue: The Variable to store in it.\n\nReturns:\nA (possibly changed) CFG node.\nRaises:\nAttributeError: If the attribute cannot be set.\nNotImplementedError: If attribute setting is not implemented for obj.", "source": "github-repos"}
944{"code": "def svd(x, full_matrices=True, compute_uv=True):\n if any_symbolic_tensors((x,)):\n return SVD(full_matrices, compute_uv).symbolic_call(x)\n return _svd(x, full_matrices, compute_uv)", "docstring": "Computes the singular value decomposition of a matrix.\n\nArgs:\nx: Input tensor of shape `(..., M, N)`.\n\nReturns:\nA tuple of three tensors: a tensor of shape `(..., M, M)` containing the\nleft singular vectors, a tensor of shape `(..., M, N)` containing the\nsingular values and a tensor of shape `(..., N, N)` containing the\nright singular vectors.", "source": "github-repos"}
945{"code": "async def is_change_done(self, zone, change_id):\n zone_id = self.get_managed_zone(zone)\n url = f'{self._base_url}/managedZones/{zone_id}/changes/{change_id}'\n resp = (await self.get_json(url))\n return (resp['status'] == self.DNS_CHANGES_DONE)", "docstring": "Check if a DNS change has completed.\n\nArgs:\nzone (str): DNS zone of the change.\nchange_id (str): Identifier of the change.\nReturns:\nBoolean", "source": "codesearchnet"}
946{"code": "def __lt__(self, other):\n \n if not isinstance(other, interface.DateTimeValues):\n raise ValueError('Other not an instance of DateTimeValues')\n\n if not isinstance(other, SemanticTime):\n return True\n\n return self._SORT_ORDER < other._SORT_ORDER", "docstring": "Determines if the date time values are less than other.\n\nArgs:\nother (DateTimeValues): date time values to compare against.\n\nReturns:\nbool: True if the date time values are less than other.\n\nRaises:\nValueError: if other is not an instance of DateTimeValues.", "source": "juraj-google-style"}
947{"code": "def get_nets_lacnic(self, response):\n nets = []\n for match in re.finditer('^(inetnum|inet6num|route):[^\\\\S\\\\n]+(.+?,[^\\\\S\\\\n].+|.+)$', response, re.MULTILINE):\n try:\n net = copy.deepcopy(BASE_NET)\n net_range = match.group(2).strip()\n try:\n net['range'] = net['range'] = ('{0} - {1}'.format(ip_network(net_range)[0].__str__(), ip_network(net_range)[(- 1)].__str__()) if ('/' in net_range) else net_range)\n except ValueError:\n net['range'] = net_range\n temp = []\n for addr in net_range.split(', '):\n count = addr.count('.')\n if ((count is not 0) and (count < 4)):\n addr_split = addr.strip().split('/')\n for i in range((count + 1), 4):\n addr_split[0] += '.0'\n addr = '/'.join(addr_split)\n temp.append(ip_network(addr.strip()).__str__())\n net['cidr'] = ', '.join(temp)\n net['start'] = match.start()\n net['end'] = match.end()\n nets.append(net)\n except ValueError:\n pass\n return nets", "docstring": "The function for parsing network blocks from LACNIC whois data.\n\nArgs:\nresponse (:obj:`str`): The response from the LACNIC whois server.\n\nReturns:\nlist of dict: Mapping of networks with start and end positions.\n\n::\n\n[{\n'cidr' (str) - The network routing block\n'start' (int) - The starting point of the network\n'end' (int) - The endpoint point of the network\n}]", "source": "codesearchnet"}
948{"code": "def add_update(self, updates, inputs=None):\n if inputs is not None:\n tf_logging.warning('`add_update` `inputs` kwarg has been deprecated. You no longer need to pass a value to `inputs` as it is being automatically inferred.')\n call_context = base_layer_utils.call_context()\n if call_context.in_keras_graph:\n return\n if not call_context.frozen:\n for update in nest.flatten(updates):\n if callable(update):\n update()", "docstring": "Add update op(s), potentially dependent on layer inputs.\n\nWeight updates (for instance, the updates of the moving mean and variance\nin a BatchNormalization layer) may be dependent on the inputs passed\nwhen calling a layer. Hence, when reusing the same layer on\ndifferent inputs `a` and `b`, some entries in `layer.updates` may be\ndependent on `a` and some on `b`. This method automatically keeps track\nof dependencies.\n\nThis call is ignored when eager execution is enabled (in that case, variable\nupdates are run on the fly and thus do not need to be tracked for later\nexecution).\n\nArgs:\nupdates: Update op, or list/tuple of update ops, or zero-arg callable\nthat returns an update op. A zero-arg callable should be passed in\norder to disable running the updates by setting `trainable=False`\non this Layer, when executing in Eager mode.\ninputs: Deprecated, will be automatically inferred.", "source": "github-repos"}
949{"code": "def _GetArgsAndFlagsString(spec, metadata):\n args_with_no_defaults = spec.args[:len(spec.args) - len(spec.defaults)]\n args_with_defaults = spec.args[len(spec.args) - len(spec.defaults):]\n accepts_positional_args = metadata.get(decorators.ACCEPTS_POSITIONAL_ARGS)\n arg_and_flag_strings = []\n if args_with_no_defaults:\n if accepts_positional_args:\n arg_strings = [formatting.Underline(arg.upper()) for arg in args_with_no_defaults]\n else:\n arg_strings = [f'--{arg}={formatting.Underline(arg.upper())}' for arg in args_with_no_defaults]\n arg_and_flag_strings.extend(arg_strings)\n if args_with_defaults or spec.kwonlyargs or spec.varkw:\n arg_and_flag_strings.append('<flags>')\n if spec.varargs:\n varargs_underlined = formatting.Underline(spec.varargs.upper())\n varargs_string = f'[{varargs_underlined}]...'\n arg_and_flag_strings.append(varargs_string)\n return ' '.join(arg_and_flag_strings)", "docstring": "The args and flags string for showing how to call a function.\n\nIf positional arguments are accepted, the args will be shown as positional.\nE.g. \"ARG1 ARG2 [--flag=FLAG]\"\n\nIf positional arguments are disallowed, the args will be shown with flags\nsyntax.\nE.g. \"--arg1=ARG1 [--flag=FLAG]\"\n\nArgs:\nspec: The full arg spec for the component to construct the args and flags\nstring for.\nmetadata: Metadata for the component, including whether it accepts\npositional arguments.\n\nReturns:\nThe constructed args and flags string.", "source": "github-repos"}
950{"code": "def parse_document_id(chrom, pos, ref, alt, variant_type, case_id):\n \n return generate_md5_key([chrom, pos, ref, alt, variant_type, case_id])", "docstring": "Parse the unique document id for a variant.\n\nThis will always be unique in the database.\n\nArgs:\nchrom(str)\npos(str)\nref(str)\nalt(str)\nvariant_type(str): 'clinical' or 'research'\ncase_id(str): unqiue family id\n\nReturns:\ndocument_id(str): The unique document id in an md5 string", "source": "juraj-google-style"}
951{"code": "def classes_file(flag_leaf=False):\n \n if __flag_first:\n __setup()\n\n if not flag_leaf:\n return _classes_file\n\n return [cls for cls in _classes_file if cls not in _classes_file_superclass]", "docstring": "All known File* classes\n\nArgs:\nflag_leaf: returns only classes that do not have subclasses\n(\"leaf\" nodes as in a class tree graph)", "source": "juraj-google-style"}
952{"code": "def _alt_inner_shape(self, new_inner_rank):\n if new_inner_rank == 0:\n raise ValueError('new_inner_rank cannot be zero')\n elif self.inner_rank == 0:\n raise ValueError('old inner_rank cannot be zero')\n elif new_inner_rank == self.inner_rank:\n return self.inner_shape\n elif new_inner_rank < self.inner_rank:\n if self._static_inner_shape.is_fully_defined():\n return _alt_inner_shape_from_tensor_shape(self._static_inner_shape, self.dtype, new_inner_rank)\n first_dimension = self._num_slices_in_dimension(-new_inner_rank)\n if new_inner_rank == 1:\n return array_ops.expand_dims(first_dimension, 0)\n remaining_dimensions = self.inner_shape[1 - new_inner_rank:]\n return array_ops.concat([array_ops.expand_dims(first_dimension, 0), remaining_dimensions], axis=0)\n else:\n assert new_inner_rank > self.inner_rank\n new_dimensions = new_inner_rank - self.inner_rank\n if any([not x.is_uniform() for x in self.row_partitions[-new_dimensions:]]):\n raise ValueError('Cannot get an inner shape over a ragged dimension')\n first_dimension = self._num_slices_in_dimension(-new_inner_rank)\n new_dimensions = new_inner_rank - self.inner_rank\n new_dims = [first_dimension] + [x.uniform_row_length() for x in self.row_partitions[-new_dimensions:]]\n return array_ops.concat([array_ops_stack.stack(new_dims), self.inner_shape[1:]], axis=0)", "docstring": "Get an alternative inner shape with higher or lower rank.\n\nFor the rank of the inner shape to be be higher, the last few ragged\ndimensions must have uniform_row_length.\n\nArgs:\nnew_inner_rank: the new rank of the inner_shape\n\nReturns:\nA new inner_shape of rank new_inner_rank.", "source": "github-repos"}
953{"code": "def QueueQueryTasks(self, queue, limit=1):\n \n prefix = DataStore.QUEUE_TASK_PREDICATE_PREFIX\n all_tasks = []\n\n for _, serialized, ts in self.ResolvePrefix(\n queue, prefix, timestamp=DataStore.ALL_TIMESTAMPS):\n task = rdf_flows.GrrMessage.FromSerializedString(serialized)\n task.leased_until = ts\n all_tasks.append(task)\n\n return all_tasks[:limit]", "docstring": "Retrieves tasks from a queue without leasing them.\n\nThis is good for a read only snapshot of the tasks.\n\nArgs:\nqueue: The task queue that this task belongs to, usually client.Queue()\nwhere client is the ClientURN object you want to schedule msgs on.\nlimit: Number of values to fetch.\n\nReturns:\nA list of Task() objects.", "source": "juraj-google-style"}
954{"code": "def _GetAction(self, action, text):\n if ('airportdProcessDLILEvent' in action):\n interface = text.split()[0]\n return 'Interface {0:s} turn up.'.format(interface)\n if ('doAutoJoin' in action):\n match = self._CONNECTED_RE.match(text)\n if match:\n ssid = match.group(1)[1:(- 1)]\n else:\n ssid = 'Unknown'\n return 'Wifi connected to SSID {0:s}'.format(ssid)\n if ('processSystemPSKAssoc' in action):\n wifi_parameters = self._WIFI_PARAMETERS_RE.search(text)\n if wifi_parameters:\n ssid = wifi_parameters.group(1)\n bssid = wifi_parameters.group(2)\n security = wifi_parameters.group(3)\n if (not ssid):\n ssid = 'Unknown'\n if (not bssid):\n bssid = 'Unknown'\n if (not security):\n security = 'Unknown'\n return 'New wifi configured. BSSID: {0:s}, SSID: {1:s}, Security: {2:s}.'.format(bssid, ssid, security)\n return text", "docstring": "Parse the well known actions for easy reading.\n\nArgs:\naction (str): the function or action called by the agent.\ntext (str): mac Wifi log text.\n\nReturns:\nstr: a formatted string representing the known (or common) action.\nIf the action is not known the original log text is returned.", "source": "codesearchnet"}
955{"code": "def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs):\n \n input_ = deepcopy(input_)\n message = sha3_256(message.encode())\n if input_.fulfills:\n message.update('{}{}'.format(\n input_.fulfills.txid, input_.fulfills.output).encode())\n\n for owner_before in set(input_.owners_before):\n \n \n\n \n \n \n\n \n \n ccffill = input_.fulfillment\n subffills = ccffill.get_subcondition_from_vk(\n base58.b58decode(owner_before))\n if not subffills:\n raise KeypairMismatchException('Public key {} cannot be found '\n 'in the fulfillment'\n .format(owner_before))\n try:\n private_key = key_pairs[owner_before]\n except KeyError:\n raise KeypairMismatchException('Public key {} is not a pair '\n 'to any of the private keys'\n .format(owner_before))\n\n \n \n for subffill in subffills:\n subffill.sign(\n message.digest(), base58.b58decode(private_key.encode()))\n return input_", "docstring": "Signs a ThresholdSha256.\n\nArgs:\ninput_ (:class:`~bigchaindb.common.transaction.\nInput`) The Input to be signed.\nmessage (str): The message to be signed\nkey_pairs (dict): The keys to sign the Transaction with.", "source": "juraj-google-style"}
956{"code": "def find_common_root(elements):\n \n if not elements:\n raise UserWarning(\"Can't find common root - no elements suplied.\")\n\n root_path = el_to_path_vector(elements.pop())\n\n for el in elements:\n el_path = el_to_path_vector(el)\n\n root_path = common_vector_root(root_path, el_path)\n\n if not root_path:\n raise UserWarning(\n \"Vectors without common root:\\n%s\" % str(el_path)\n )\n\n return root_path", "docstring": "Find root which is common for all `elements`.\n\nArgs:\nelements (list): List of double-linked HTMLElement objects.\n\nReturns:\nlist: Vector of HTMLElement containing path to common root.", "source": "juraj-google-style"}
957{"code": "def assert_equal_flattened(self, expected_results, actual_results):\n self.assertEqual(len(expected_results), len(actual_results))\n for i, expected_result in enumerate(expected_results):\n final_result = []\n actual_result = actual_results[i]\n for val in actual_result:\n final_result.extend(val.numpy())\n self.assertAllEqual(expected_result, final_result)", "docstring": "Asserts that flattened results are equal.\n\nDue to the number of replicas in the strategy, the output may have a\ndifferent structure and needs to be flattened for comparison.\n\nArgs:\nexpected_results: The results expected as a result of a computation.\nactual_results: The actual results of a computation.", "source": "github-repos"}
958{"code": "def set_file_to_upload(self, file_to_upload):\n \n \n if 'url' in self.data:\n del self.data['url']\n self.file_to_upload = file_to_upload", "docstring": "Delete any existing url and set the file uploaded to the local path provided\n\nArgs:\nfile_to_upload (str): Local path to file to upload\n\nReturns:\nNone", "source": "juraj-google-style"}
959{"code": "def single_gate_matrix(gate, params=None):\n (theta, phi, lam) = map(float, single_gate_params(gate, params))\n return np.array([[np.cos((theta / 2)), ((- np.exp((1j * lam))) * np.sin((theta / 2)))], [(np.exp((1j * phi)) * np.sin((theta / 2))), (np.exp(((1j * phi) + (1j * lam))) * np.cos((theta / 2)))]])", "docstring": "Get the matrix for a single qubit.\n\nArgs:\ngate(str): the single qubit gate name\nparams(list): the operation parameters op['params']\nReturns:\narray: A numpy array representing the matrix", "source": "codesearchnet"}
960{"code": "def _prepare_host_call_fn(self, processed_t_fetches, op_fetches, graph, graph_summary_tag):\n if self._parameters.trace_dir is None:\n raise ValueError('Provide a trace_dir for tensor tracer in summary mode. --trace_dir=/model/dir')\n\n def _write_cache(step, event_file_suffix=None, **kwargs):\n \n file_suffix = _TT_EVENT_FILE_SUFFIX\n if event_file_suffix is not None:\n file_suffix = string_ops.string_join([file_suffix, event_file_suffix], separator='.')\n summary_write_ops = []\n summary_writer = summary.create_file_writer_v2(self._parameters.trace_dir, filename_suffix=file_suffix, max_queue=_TT_SUMMARY_MAX_QUEUE)\n graph.add_to_collection(TENSOR_TRACER_SUMMARY_COLLECTION, summary_writer)\n step_value = step[0]\n dt = step_value.dtype\n if dt.__ne__(dtypes.int64) and dt.__ne__(dtypes.uint64) and dt.__ne__(dtypes.float64):\n step_value = math_ops.cast(step_value, dtypes.int64)\n with summary_writer.as_default():\n summary_metadata = summary_pb2.SummaryMetadata(plugin_data=summary_pb2.SummaryMetadata.PluginData(plugin_name=_TT_TENSORBOARD_PLUGIN_NAME))\n for key, value in kwargs.items():\n if not self._parameters.collect_summary_per_core:\n if key == _TT_SUMMARY_TAG and value.shape.as_list()[0] != 1:\n value = self.aggregate_global_cache(value)\n with ops.control_dependencies([summary_writer.init()]):\n summary_write_ops.append(summary.write(_TT_SUMMARY_TAG + '/' + key + '.' + graph_summary_tag, value, metadata=summary_metadata, step=step_value))\n return control_flow_ops.group(summary_write_ops)\n global_step = training_util.get_or_create_global_step()\n step = array_ops.reshape(global_step, [1])\n self._host_call_fn = {}\n host_call_deps = op_fetches + [tensor.op for tensor in processed_t_fetches]\n caches_to_write = {}\n with ops.control_dependencies(host_call_deps):\n all_caches = self._cache_variable_for_graph(graph)\n for cache_name, cache_variable in all_caches.items():\n new_cache_shape = [1]\n new_cache_shape.extend(cache_variable.shape.as_list())\n cache = array_ops.reshape(cache_variable, new_cache_shape)\n caches_to_write[cache_name] = cache\n caches_to_write['step'] = step\n self._host_call_fn[_TT_HOSTCALL_KEY] = (_write_cache, caches_to_write)", "docstring": "Creates a host call function that will write the cache as tb summary.\n\nArgs:\nprocessed_t_fetches: List of tensor provided to session.run.\nop_fetches: List of operations provided to session.run.\ngraph: TensorFlow graph.\ngraph_summary_tag: the summary_tag name for the given graph.\nRaises:\nValueError if trace_dir is not set.", "source": "github-repos"}
961{"code": "def warn_once(self, msg, msg_name=None):\n assert isinstance(msg, str)\n msg_name = (msg_name if msg_name else msg)\n if (msg_name not in warnings_given):\n warnings.warn(msg)\n warnings_given.add(msg_name)", "docstring": "Prints a warning statement just once\n\nArgs:\nmsg: The warning message\nmsg_name: [optional] The name of the warning. If None, the msg_name\nwill be the msg itself.", "source": "codesearchnet"}
962{"code": "def from_lasio(cls, l, remap=None, funcs=None):\n params = {}\n funcs = (funcs or {})\n funcs['location'] = str\n for (field, (sect, code)) in las_fields['location'].items():\n params[field] = utils.lasio_get(l, sect, code, remap=remap, funcs=funcs)\n return cls(params)", "docstring": "Make a Location object from a lasio object. Assumes we're starting\nwith a lasio object, l.\n\nArgs:\nl (lasio).\nremap (dict): Optional. A dict of 'old': 'new' LAS field names.\nfuncs (dict): Optional. A dict of 'las field': function() for\nimplementing a transform before loading. Can be a lambda.\n\nReturns:\nLocation. An instance of this class.", "source": "codesearchnet"}
963{"code": "def get_port(self, id_or_uri, port_id_or_uri):\n uri = self._client.build_subresource_uri(id_or_uri, port_id_or_uri, 'ports')\n return self._client.get(uri)", "docstring": "Gets an interconnect port.\n\nArgs:\nid_or_uri: Can be either the interconnect id or uri.\nport_id_or_uri: The interconnect port id or uri.\n\nReturns:\ndict: The interconnect port.", "source": "codesearchnet"}
964{"code": "def _offset(value):\n \n o = int(value)\n if o == 0:\n return 0\n a = abs(o)\n s = a*36+(a%100)*24\n return (o", "docstring": "Parse timezone to offset in seconds.\n\nArgs:\nvalue: A timezone in the '+0000' format. An integer would also work.\n\nReturns:\nThe timezone offset from GMT in seconds as an integer.", "source": "juraj-google-style"}
965{"code": "def _is_trivial(node):\n trivial_node_types = (gast.Name, bool, str, gast.Add, gast.Sub, gast.Mult, gast.Div, gast.Mod, gast.Pow, gast.LShift, gast.RShift, gast.BitOr, gast.BitXor, gast.BitAnd, gast.FloorDiv, gast.Invert, gast.Not, gast.UAdd, gast.USub, gast.Eq, gast.NotEq, gast.Lt, gast.LtE, gast.Gt, gast.GtE, gast.Is, gast.IsNot, gast.In, gast.NotIn, gast.expr_context)\n if isinstance(node, trivial_node_types) and (not _is_py2_name_constant(node)):\n return True\n if gast_util.is_ellipsis(node):\n return True\n return False", "docstring": "Returns whether to consider the given node 'trivial'.\n\nThe definition of 'trivial' is a node that can't meaningfully be pulled out\ninto its own assignment statement.\n\nThis is surprisingly difficult to do robustly across versions of Python and\ngast, as the parsing of constants has changed, if I may, constantly.\n\nArgs:\nnode: An AST node to check for triviality\n\nReturns:\ntrivial: A Python `bool` indicating whether the node is trivial.", "source": "github-repos"}
966{"code": "def _process_image(filename, coder):\n with tf.gfile.FastGFile(filename, 'r') as f:\n image_data = f.read()\n if _is_png(filename):\n print(('Converting PNG to JPEG for %s' % filename))\n image_data = coder.png_to_jpeg(image_data)\n elif _is_cmyk(filename):\n print(('Converting CMYK to RGB for %s' % filename))\n image_data = coder.cmyk_to_rgb(image_data)\n image = coder.decode_jpeg(image_data)\n assert (len(image.shape) == 3)\n height = image.shape[0]\n width = image.shape[1]\n assert (image.shape[2] == 3)\n return (image_data, height, width)", "docstring": "Process a single image file.\n\nArgs:\nfilename: string, path to an image file e.g., '/path/to/example.JPG'.\ncoder: instance of ImageCoder to provide TensorFlow image coding utils.\nReturns:\nimage_buffer: string, JPEG encoding of RGB image.\nheight: integer, image height in pixels.\nwidth: integer, image width in pixels.", "source": "codesearchnet"}
967{"code": "def with_dependencies(self, checks):\n pass", "docstring": "Add dependencies to a _LayerBroadcaster.\n\nArgs:\nchecks: a list of ops that need to be run before any tensors from the\nBroadcaster are used.\n\nReturns:\na copy of this _LayerBroadcaster with dependencies added.", "source": "github-repos"}
968{"code": "def catch(func, *args, **kwargs):\n \n try:\n func(*args, **kwargs)\n except Exception as e:\n return e", "docstring": "Call the supplied function with the supplied arguments,\ncatching and returning any exception that it throws.\n\nArguments:\nfunc: the function to run.\n*args: positional arguments to pass into the function.\n**kwargs: keyword arguments to pass into the function.\nReturns:\nIf the function throws an exception, return the exception.\nIf the function does not throw an exception, return None.", "source": "juraj-google-style"}
969{"code": "def uses_star_args_or_kwargs_in_call(node):\n return uses_star_args_in_call(node) or uses_star_kwargs_in_call(node)", "docstring": "Check if an ast.Call node uses arbitrary-length *args or **kwargs.\n\nThis function works with the AST call node format of Python3.5+\nas well as the different AST format of earlier versions of Python.\n\nArgs:\nnode: The ast.Call node to check arg values for.\n\nReturns:\nTrue if the node uses starred variadic positional args or keyword args.\nFalse if it does not.", "source": "github-repos"}
970{"code": "def _get_userprofile_from_registry(user, sid):\n \n profile_dir = __utils__['reg.read_value'](\n 'HKEY_LOCAL_MACHINE',\n 'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\ProfileList\\\\{0}'.format(sid),\n 'ProfileImagePath'\n )['vdata']\n log.debug(\n 'user %s with sid=%s profile is located at \"%s\"',\n user, sid, profile_dir\n )\n return profile_dir", "docstring": "In case net user doesn't return the userprofile we can get it from the\nregistry\n\nArgs:\nuser (str): The user name, used in debug message\n\nsid (str): The sid to lookup in the registry\n\nReturns:\nstr: Profile directory", "source": "juraj-google-style"}
971{"code": "def _ReadRecordSchemaInformation(self, tables, file_object, record_offset):\n \n _ = self._ReadRecordHeader(file_object, record_offset)\n\n attribute_value_offsets = self._ReadRecordAttributeValueOffset(\n file_object, record_offset + 24, 2)\n\n if attribute_value_offsets != (0x21, 0x25):\n raise errors.ParseError('Unsupported record attribute value offsets')\n\n file_offset = file_object.tell()\n data_type_map = self._GetDataTypeMap('keychain_record_schema_information')\n\n record_values, _ = self._ReadStructureFromFileObject(\n file_object, file_offset, data_type_map)\n\n relation_name = record_values.relation_name.decode('ascii')\n\n table = KeychainDatabaseTable()\n table.relation_identifier = record_values.relation_identifier\n table.relation_name = relation_name\n\n tables[table.relation_identifier] = table\n\n table = tables.get(self._RECORD_TYPE_CSSM_DL_DB_SCHEMA_INFO, None)\n if not table:\n raise errors.ParseError('Missing CSSM_DL_DB_SCHEMA_INFO table.')\n\n record = collections.OrderedDict({\n 'RelationID': record_values.relation_identifier,\n 'RelationName': relation_name})\n\n table.records.append(record)", "docstring": "Reads a schema information (CSSM_DL_DB_SCHEMA_INFO) record.\n\nArgs:\ntables (dict[int, KeychainDatabaseTable]): tables per identifier.\nfile_object (file): file-like object.\nrecord_offset (int): offset of the record relative to the start of\nthe file.\n\nRaises:\nParseError: if the record cannot be read.", "source": "juraj-google-style"}
972{"code": "def submit_data(self, batch_id, halt_on_error=True):\n \n \n if self.halt_on_batch_error is not None:\n halt_on_error = self.halt_on_batch_error\n\n content = self.data\n \n self._batch_data_count = len(content.get('group')) + len(content.get('indicator'))\n self.tcex.log.info('Batch Size: {:,}'.format(self._batch_data_count))\n if content.get('group') or content.get('indicator'):\n headers = {'Content-Type': 'application/octet-stream'}\n try:\n r = self.tcex.session.post(\n '/v2/batch/{}'.format(batch_id), headers=headers, json=content\n )\n except Exception as e:\n self.tcex.handle_error(10520, [e], halt_on_error)\n if not r.ok or 'application/json' not in r.headers.get('content-type', ''):\n self.tcex.handle_error(10525, [r.status_code, r.text], halt_on_error)\n return r.json()\n return {}", "docstring": "Submit Batch request to ThreatConnect API.\nArgs:\nbatch_id (string): The batch id of the current job.", "source": "juraj-google-style"}
973{"code": "def get_snippet_client(self, name):\n if name in self._snippet_clients:\n return self._snippet_clients[name]", "docstring": "Gets the snippet client managed under a given name.\n\nArgs:\nname: string, the name of the snippet client under management.\n\nReturns:\nSnippetClient.", "source": "github-repos"}
974{"code": "def replace_method_name(self, signature_key, method_name, tags=None):\n if not signature_key:\n raise ValueError('`signature_key` must be defined.')\n if not method_name:\n raise ValueError('`method_name` must be defined.')\n if tags is not None and (not isinstance(tags, list)):\n tags = [tags]\n found_match = False\n for meta_graph_def in self._saved_model.meta_graphs:\n if tags is None or set(tags) == set(meta_graph_def.meta_info_def.tags):\n if signature_key not in meta_graph_def.signature_def:\n raise ValueError(f\"MetaGraphDef associated with tags {tags} does not have a signature_def with key: '{signature_key}'. This means either you specified the wrong signature key or forgot to put the signature_def with the corresponding key in your SavedModel.\")\n meta_graph_def.signature_def[signature_key].method_name = method_name\n found_match = True\n if not found_match:\n raise ValueError(f'MetaGraphDef associated with tags {tags} could not be found in SavedModel. This means either you specified invalid tags or your SavedModel does not have a MetaGraphDef with the specified tags.')", "docstring": "Replaces the method_name in the specified signature_def.\n\nThis will match and replace multiple sig defs iff tags is None (i.e when\nmultiple `MetaGraph`s have a signature_def with the same key).\nIf tags is not None, this will only replace a single signature_def in the\n`MetaGraph` with matching tags.\n\nArgs:\nsignature_key: Key of the signature_def to be updated.\nmethod_name: new method_name to replace the existing one.\ntags: A tag or sequence of tags identifying the `MetaGraph` to update. If\nNone, all meta graphs will be updated.\nRaises:\nValueError: if signature_key or method_name are not defined or\nif no metagraphs were found with the associated tags or\nif no meta graph has a signature_def that matches signature_key.", "source": "github-repos"}
975{"code": "def retry_handler(retries=0, delay=timedelta(), conditions=[]):\n \n delay_in_seconds = delay.total_seconds()\n return partial(retry_loop, retries, delay_in_seconds, conditions)", "docstring": "A simple wrapper function that creates a handler function by using\non the retry_loop function.\n\nArgs:\nretries (Integral): The number of times to retry if a failure occurs.\ndelay (timedelta, optional, 0 seconds): A timedelta representing\nthe amount time to delay between retries.\nconditions (list): A list of retry conditions.\nReturns:\nfunction: The retry_loop function partialed.", "source": "juraj-google-style"}
976{"code": "def _batch_rp_spec(rp_spec: RowPartitionSpec, batch_size: Optional[int]) -> RowPartitionSpec:\n if batch_size is None:\n return RowPartitionSpec(uniform_row_length=rp_spec.uniform_row_length, dtype=rp_spec.dtype)\n nrows = None if rp_spec.nrows is None else rp_spec.nrows * batch_size\n nvals = None if rp_spec.nvals is None else rp_spec.nvals * batch_size\n return RowPartitionSpec(nrows=nrows, nvals=nvals, uniform_row_length=rp_spec.uniform_row_length, dtype=rp_spec.dtype)", "docstring": "Batches a RowPartitionSpec.\n\nGiven a RowPartitionSpec and a batch_size, create a RowPartitionSpec that\nwill be the spec for the concatenation of batch_size RowPartitions.\n\nA RowPartition can be considered a transformation from a list of a given\nlength to a list of lists. Assume rp_a is a map from list_a to nlist_a,\nAnd rp_b is a map from list_b to nlist_b. concat(rp_a, rp_b) is a\ntransform of concat(list_a, list_b) to concat(nlist_a, nlist_b).\n\nIf batch_size is None, then have the spec be able to handle an arbitrary\nnumber of RowPartitions.\n\nArgs:\nrp_spec: a RowPartitionSpec for all the RowPartitions to be concatenated.\nbatch_size: the number of rp_specs to be concatenated.\n\nReturns:\na batched RowPartitionSpec.", "source": "github-repos"}
977{"code": "def exhaustive_iri_check(self, ontology: pd.DataFrame, iri_predicate: str, diff: bool=True) -> Tuple[list]:\n (inside, outside) = ([], [])\n header = (['Index'] + list(ontology.columns))\n for row in ontology.itertuples():\n row = {header[i]: val for (i, val) in enumerate(row)}\n entity_iri = row[iri_predicate]\n if isinstance(entity_iri, list):\n if (len(entity_iri) != 0):\n exit('Need to have only 1 iri in the cell from the onotology.')\n else:\n entity_iri = entity_iri[0]\n ilx_row = self.iri2row.get(entity_iri)\n if ilx_row:\n inside.append({'external_ontology_row': row, 'ilx_rows': [ilx_row]})\n else:\n outside.append(row)\n if diff:\n diff = self.__exhaustive_diff(inside)\n return (inside, outside, diff)\n return (inside, outside)", "docstring": "All entities with conflicting iris gets a full diff to see if they belong\n\nArgs:\nontology: pandas DataFrame created from an ontology where the colnames are predicates\nand if classes exist it is also thrown into a the colnames.\niri_predicate: usually in qname form and is the colname of the DataFrame for iri\nDefault is \"iri\" for graph2pandas module\ndiff: complete exhaustive diff if between curie matches... will take FOREVER if there are a lot -> n^2\nReturns:\ninside: entities that are inside of InterLex\noutside: entities NOT in InterLex\ndiff (optional): List[List[dict]]... so complicated but usefull diff between matches only", "source": "codesearchnet"}
978{"code": "def detect_language(index_page):\n dom = dhtmlparser.parseString(index_page)\n clean_content = dhtmlparser.removeTags(dom)\n lang = None\n try:\n lang = langdetect.detect(clean_content)\n except UnicodeDecodeError:\n lang = langdetect.detect(clean_content.decode('utf-8'))\n return SourceString(lang, source='langdetect')", "docstring": "Detect `languages` using `langdetect` library.\n\nArgs:\nindex_page (str): HTML content of the page you wish to analyze.\n\nReturns:\nobj: One :class:`.SourceString` object.", "source": "codesearchnet"}
979{"code": "def check_integrity(sakefile, settings):\n \n sprint = settings[\"sprint\"]\n error = settings[\"error\"]\n sprint(\"Call to check_integrity issued\", level=\"verbose\")\n if not sakefile:\n error(\"Sakefile is empty\")\n return False\n \n if len(sakefile.keys()) != len(set(sakefile.keys())):\n error(\"Sakefile contains duplicate targets\")\n return False\n for target in sakefile:\n if target == \"all\":\n if not check_target_integrity(target, sakefile[\"all\"], all=True):\n error(\"Failed to accept target 'all'\")\n return False\n continue\n if \"formula\" not in sakefile[target]:\n if not check_target_integrity(target, sakefile[target],\n meta=True):\n errmes = \"Failed to accept meta-target '{}'\".format(target)\n error(errmes)\n return False\n for atom_target in sakefile[target]:\n if atom_target == \"help\":\n continue\n if not check_target_integrity(atom_target,\n sakefile[target][atom_target],\n parent=target):\n errmes = \"Failed to accept target '{}'\\n\".format(\n atom_target)\n error(errmes)\n return False\n continue\n if not check_target_integrity(target, sakefile[target]):\n errmes = \"Failed to accept target '{}'\\n\".format(target)\n error(errmes)\n return False\n return True", "docstring": "Checks the format of the sakefile dictionary\nto ensure it conforms to specification\n\nArgs:\nA dictionary that is the parsed Sakefile (from sake.py)\nThe setting dictionary (for print functions)\nReturns:\nTrue if the Sakefile is conformant\nFalse if not", "source": "juraj-google-style"}
980{"code": "class AriaSharedExpertsMLP(nn.Module):\n\n def __init__(self, config: AriaTextConfig):\n super().__init__()\n self.config = config\n self.hidden_size = config.hidden_size\n self.intermediate_size = config.intermediate_size * config.moe_num_shared_experts\n self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)\n self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)\n self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)\n self.act_fn = ACT2FN[config.hidden_act]\n\n def forward(self, x):\n down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))\n return down_proj", "docstring": "Shared Expert MLP for shared experts.\n\nUnlike routed experts, shared experts process all tokens without routing.\nThis class reconfigures the intermediate size in comparison to the LlamaMLP.\n\nArgs:\nconfig (`AriaTextConfig`): Configuration object for the Aria language model.", "source": "github-repos"}
981{"code": "def notify_rollover(self, stream):\n \n\n self.offset -= 1\n\n if not self.matches(stream):\n return\n\n if self._count == 0:\n raise InternalError(\"BufferedStreamWalker out of sync with storage engine, count was wrong.\")\n\n self._count -= 1", "docstring": "Notify that a reading in the given stream was overwritten.\n\nArgs:\nstream (DataStream): The stream that had overwritten data.", "source": "juraj-google-style"}
982{"code": "def get_dihedral(self, i: int, j: int, k: int, l: int) -> float:\n \n v1 = self[k].coords - self[l].coords\n v2 = self[j].coords - self[k].coords\n v3 = self[i].coords - self[j].coords\n v23 = np.cross(v2, v3)\n v12 = np.cross(v1, v2)\n return math.degrees(math.atan2(np.linalg.norm(v2) * np.dot(v1, v23),\n np.dot(v12, v23)))", "docstring": "Returns dihedral angle specified by four sites.\n\nArgs:\ni: Index of first site\nj: Index of second site\nk: Index of third site\nl: Index of fourth site\n\nReturns:\nDihedral angle in degrees.", "source": "juraj-google-style"}
983{"code": "def _extend_object(parent, n, o, otype, fqdn):\n from inspect import ismodule, isclass\n pmodule = (parent if (ismodule(parent) or isclass(parent)) else None)\n try:\n if (otype == 'methods'):\n setattr(o.__func__, '__acornext__', None)\n else:\n setattr(o, '__acornext__', None)\n fqdn = _fqdn(o, recheck=True, pmodule=pmodule)\n return o\n except (TypeError, AttributeError):\n okey = id(o)\n if (okey not in _extended_objs):\n xobj = _create_extension(o, otype, fqdn, pmodule)\n fqdn = _fqdn(xobj, recheck=True, pmodule=pmodule)\n if (xobj is not None):\n _extended_objs[okey] = xobj\n try:\n setattr(parent, n, _extended_objs[okey])\n return _extended_objs[okey]\n except KeyError:\n msg.warn('Object extension failed: {} ({}).'.format(o, otype))", "docstring": "Extends the specified object if it needs to be extended. The method\nattempts to add an attribute to the object; if it fails, a new object is\ncreated that inherits all of `o` attributes, but is now a regular object\nthat can have attributes set.\n\nArgs:\nparent: has `n` in its `__dict__` attribute.\nn (str): object name attribute.\no (list): object instances to be extended.\notype (str): object types; one of [\"classes\", \"functions\", \"methods\",\n\"modules\"].\nfqdn (str): fully qualified name of the package that the object belongs\nto.", "source": "codesearchnet"}
984{"code": "def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):\n super(Nonce, self).read(input_stream, kmip_version=kmip_version)\n local_stream = BytearrayStream(input_stream.read(self.length))\n if self.is_tag_next(enums.Tags.NONCE_ID, local_stream):\n self._nonce_id = primitives.ByteString(tag=enums.Tags.NONCE_ID)\n self._nonce_id.read(local_stream, kmip_version=kmip_version)\n else:\n raise ValueError('Nonce encoding missing the nonce ID.')\n if self.is_tag_next(enums.Tags.NONCE_VALUE, local_stream):\n self._nonce_value = primitives.ByteString(tag=enums.Tags.NONCE_VALUE)\n self._nonce_value.read(local_stream, kmip_version=kmip_version)\n else:\n raise ValueError('Nonce encoding missing the nonce value.')\n self.is_oversized(local_stream)", "docstring": "Read the data encoding the Nonce struct and decode it into its\nconstituent parts.\n\nArgs:\ninput_stream (stream): A data stream containing encoded object\ndata, supporting a read method; usually a BytearrayStream\nobject.\nkmip_version (KMIPVersion): An enumeration defining the KMIP\nversion with which the object will be decoded. Optional,\ndefaults to KMIP 1.0.\n\nRaises:\nValueError: Raised if the nonce ID or nonce value is missing from\nthe encoding.", "source": "codesearchnet"}
985{"code": "def layer_statistics_dump(self, file: IO[str]) -> None:\n fields = ['op_name', 'tensor_idx'] + list(self._layer_debug_metrics.keys())\n if self._debug_options.layer_direct_compare_metrics is not None:\n fields += list(self._debug_options.layer_direct_compare_metrics.keys())\n fields += ['scale', 'zero_point', 'tensor_name']\n writer = csv.DictWriter(file, fields)\n writer.writeheader()\n if self.layer_statistics:\n for name, metrics in self.layer_statistics.items():\n data = metrics.copy()\n data['tensor_name'], _ = self._get_operand_name_and_index(name)\n data['tensor_idx'] = self._numeric_verify_op_details[name]['inputs'][0]\n data['op_name'] = self._quant_interpreter._get_op_details(self._defining_op[data['tensor_idx']])['op_name']\n details = self._quant_interpreter._get_tensor_details(data['tensor_idx'], subgraph_index=0)\n data['scale'], data['zero_point'] = (details['quantization_parameters']['scales'][0], details['quantization_parameters']['zero_points'][0])\n writer.writerow(data)", "docstring": "Dumps layer statistics into file, in csv format.\n\nArgs:\nfile: file, or file-like object to write.", "source": "github-repos"}
986{"code": "def parse_procheck(quality_directory):\n procheck_summaries = glob.glob(os.path.join(quality_directory, '*.sum'))\n if (len(procheck_summaries) == 0):\n return pd.DataFrame()\n all_procheck = {}\n for summ in procheck_summaries:\n structure_id = os.path.basename(summ).split('.sum')[0]\n procheck_dict = {}\n with open(summ) as f_in:\n lines = (line.rstrip() for line in f_in)\n lines = (line for line in lines if line)\n for line in lines:\n if (len(line.split()) > 1):\n if (line.split()[1] == 'Ramachandran'):\n procheck_dict['procheck_rama_favored'] = percentage_to_float(line.split()[3])\n procheck_dict['procheck_rama_allowed'] = percentage_to_float(line.split()[5])\n procheck_dict['procheck_rama_allowed_plus'] = percentage_to_float(line.split()[7])\n procheck_dict['procheck_rama_disallowed'] = percentage_to_float(line.split()[9])\n if (line.split()[1] == 'G-factors'):\n procheck_dict['procheck_gfac_dihedrals'] = line.split()[3]\n procheck_dict['procheck_gfac_covalent'] = line.split()[5]\n procheck_dict['procheck_gfac_overall'] = line.split()[7]\n all_procheck[structure_id] = procheck_dict\n DF_PROCHECK = pd.DataFrame.from_dict(all_procheck, orient='index')\n return DF_PROCHECK", "docstring": "Parses all PROCHECK files in a directory and returns a Pandas DataFrame of the results\n\nArgs:\nquality_directory: path to directory with PROCHECK output (.sum files)\n\nReturns:\nPandas DataFrame: Summary of PROCHECK results", "source": "codesearchnet"}
987{"code": "def parse_config_file(config_file, skip_unknown=False):\n for (reader, existence_check) in _FILE_READERS:\n if existence_check(config_file):\n with reader(config_file) as f:\n parse_config(f, skip_unknown=skip_unknown)\n return\n raise IOError('Unable to open file: {}'.format(config_file))", "docstring": "Parse a Gin config file.\n\nArgs:\nconfig_file: The path to a Gin config file.\nskip_unknown: A boolean indicating whether unknown configurables and imports\nshould be skipped instead of causing errors (alternatively a list of\nconfigurable names to skip if unknown). See `parse_config` for additional\ndetails.\n\nRaises:\nIOError: If `config_file` cannot be read using any register file reader.", "source": "codesearchnet"}
988{"code": "def user_activity_stats(self, username, format=None):\n request_url = '{}/api/0/user/{}/activity/stats'.format(self.instance, username)\n payload = {}\n if (username is not None):\n payload['username'] = username\n if (format is not None):\n payload['format'] = format\n return_value = self._call_api(request_url, params=payload)\n return return_value", "docstring": "Retrieve the activity stats about a specific user over the last year.\n\nParams:\nusername (string): filters the username of the user whose activity you are interested in.\nformat (string): Allows changing the of the date/time returned from iso format\nto unix timestamp Can be: timestamp or isoformat\nReturns:\ndict: A dictionary of activities done by a given user for all the projects\nfor a given Pagure instance.", "source": "codesearchnet"}
989{"code": "def transform(self, column):\n self.check_data_type()\n return pd.DataFrame({self.col_name: np.exp(column[self.col_name])})", "docstring": "Applies an exponential to values to turn them positive numbers.\n\nArgs:\ncolumn (pandas.DataFrame): Data to transform.\n\nReturns:\npd.DataFrame", "source": "codesearchnet"}
990{"code": "def create(self, master_course_id, coach_email, max_students_allowed, title, modules=None):\n \n payload = {\n 'master_course_id': master_course_id,\n 'coach_email': coach_email,\n 'max_students_allowed': max_students_allowed,\n 'display_name': title,\n }\n\n if modules is not None:\n payload['course_modules'] = modules\n\n resp = self.requester.post(\n parse.urljoin(self.base_url, '/api/ccx/v0/ccx/'),\n json=payload\n )\n\n try:\n resp.raise_for_status()\n except:\n log.error(resp.json())\n raise\n\n return resp.json()['ccx_course_id']", "docstring": "Creates a CCX\n\nArgs:\nmaster_course_id (str): edx course id of the master course\ncoach_email (str): email of the user to make a coach. This user must exist on edx.\nmax_students_allowed (int): Maximum number of students to allow in this ccx.\ntitle (str): Title of the CCX to be created\nmodules (optional list): A list of locator_ids (str) for the modules to enable.\n\nReturns:\nccx_id (str): The ID of the ccx.", "source": "juraj-google-style"}
991{"code": "def pylint_check(files):\n files = fs.wrap_paths(files)\n cfg_path = conf.get_path('lint.pylint_cfg', 'ops/tools/pylint.ini')\n pylint_cmd = 'pylint --rcfile {} {}'.format(cfg_path, files)\n return shell.run(pylint_cmd, exit_on_error=False).return_code", "docstring": "Run code checks using pylint.\n\nArgs:\nfiles (list[str]):\nA list of files to check\n\nReturns:\nbool: **True** if all files passed the checks, **False** otherwise.", "source": "codesearchnet"}
992{"code": "def simplify(self, eps, max_dist_error, max_speed_error, topology_only=False):\n if topology_only:\n self.points = drp(self.points, eps)\n else:\n self.points = spt(self.points, max_dist_error, max_speed_error)\n return self", "docstring": "In-place segment simplification\n\nSee `drp` and `compression` modules\n\nArgs:\neps (float): Distance threshold for the `drp` function\nmax_dist_error (float): Max distance error, in meters\nmax_speed_error (float): Max speed error, in km/h\ntopology_only (bool, optional): True to only keep topology, not considering\ntimes when simplifying. Defaults to False.\nReturns:\n:obj:`Segment`", "source": "codesearchnet"}
993{"code": "def _ReadString(\n self, file_object, file_offset, data_type_map, description):\n \n \n element_data_size = (\n data_type_map._element_data_type_definition.GetByteSize())\n elements_terminator = (\n data_type_map._data_type_definition.elements_terminator)\n\n byte_stream = []\n\n element_data = file_object.read(element_data_size)\n byte_stream.append(element_data)\n while element_data and element_data != elements_terminator:\n element_data = file_object.read(element_data_size)\n byte_stream.append(element_data)\n\n byte_stream = b''.join(byte_stream)\n\n return self._ReadStructureFromByteStream(\n byte_stream, file_offset, data_type_map, description)", "docstring": "Reads a string.\n\nArgs:\nfile_object (FileIO): file-like object.\nfile_offset (int): offset of the data relative from the start of\nthe file-like object.\ndata_type_map (dtfabric.DataTypeMap): data type map of the string.\ndescription (str): description of the string.\n\nReturns:\nobject: structure values object.\n\nRaises:\nFileFormatError: if the string cannot be read.\nValueError: if file-like object or date type map are invalid.", "source": "juraj-google-style"}
994{"code": "def check_causatives(self, case_obj=None, institute_obj=None):\n \n institute_id = case_obj['owner'] if case_obj else institute_obj['_id']\n institute_causative_variant_ids = self.get_causatives(institute_id)\n if len(institute_causative_variant_ids) == 0:\n return []\n\n if case_obj:\n \n case_causative_ids = set(case_obj.get('causatives', []))\n institute_causative_variant_ids = list(\n set(institute_causative_variant_ids).difference(case_causative_ids)\n )\n\n \n query = self.variant_collection.find(\n {'_id': {'$in': institute_causative_variant_ids}},\n {'variant_id': 1}\n )\n positional_variant_ids = [item['variant_id'] for item in query]\n\n filters = {'variant_id': {'$in': positional_variant_ids}}\n if case_obj:\n filters['case_id'] = case_obj['_id']\n else:\n filters['institute'] = institute_obj['_id']\n return self.variant_collection.find(filters)", "docstring": "Check if there are any variants that are previously marked causative\n\nLoop through all variants that are marked 'causative' for an\ninstitute and check if any of the variants are present in the\ncurrent case.\n\nArgs:\ncase_obj (dict): A Case object\ninstitute_obj (dict): check across the whole institute\n\nReturns:\ncausatives(iterable(Variant))", "source": "juraj-google-style"}
995{"code": "def move_bulk(self, from_statuses, to_status):\n \n\n for status in from_statuses:\n from_status_items = self.__get_var(\"items_\" + status)\n self.__set_var(\"items_\" + status, OrderedDict())\n\n to_status_items = self.__get_var(\"items_\" + to_status)\n to_status_items.update(from_status_items)", "docstring": "Move a bulk of request/response pairs to another status\n\nArgs:\nfrom_statuses list(str): The statuses to move from\nto_status (str): The status to move to", "source": "juraj-google-style"}
996{"code": "def get_by(self, field, value):\n firmwares = self.get_all()\n matches = []\n for item in firmwares:\n if (item.get(field) == value):\n matches.append(item)\n return matches", "docstring": "Gets the list of firmware baseline resources managed by the appliance. Optional parameters can be used to\nfilter the list of resources returned.\n\nThe search is case-insensitive.\n\nArgs:\nfield: Field name to filter.\nvalue: Value to filter.\n\nReturns:\nlist: List of firmware baseline resources.", "source": "codesearchnet"}
997{"code": "def cuda(self) -> Rotation:\n if self._rot_mats is not None:\n return Rotation(rot_mats=self._rot_mats.cuda(), quats=None)\n elif self._quats is not None:\n return Rotation(rot_mats=None, quats=self._quats.cuda(), normalize_quats=False)\n else:\n raise ValueError('Both rotations are None')", "docstring": "Analogous to the cuda() method of torch Tensors\n\nReturns:\nA copy of the Rotation in CUDA memory", "source": "github-repos"}
998{"code": "def entry_verifier(entries, regex, delimiter):\n cregex = re.compile(regex)\n python_version = int(sys.version.split('.')[0])\n decoder = ('unicode-escape' if (python_version == 3) else 'string-escape')\n dedelimiter = codecs.decode(delimiter, decoder)\n for entry in entries:\n match = re.match(cregex, entry)\n if (not match):\n split_regex = regex.split(delimiter)\n split_entry = entry.split(dedelimiter)\n part = 0\n for (regex_segment, entry_segment) in zip(split_regex, split_entry):\n if (not (regex_segment[0] == '^')):\n regex_segment = ('^' + regex_segment)\n if (not (regex_segment[(- 1)] == '$')):\n regex_segment += '$'\n if (not re.match(regex_segment, entry_segment)):\n raise FormatError(template=regex_segment, subject=entry_segment, part=part)\n part += 1", "docstring": "Checks each entry against regex for validity,\n\nIf an entry does not match the regex, the entry and regex\nare broken down by the delimiter and each segment is analyzed\nto produce an accurate error message.\n\nArgs:\nentries (list): List of entries to check with regex\n\nregex (str): Regular expression to compare entries with\n\ndelimiter (str): Character to split entry and regex by, used to check\nparts of entry and regex to narrow in on the error\n\nRaises:\nFormatError: Class containing regex match error data\n\nExample:\n>>> regex = r'^>.+\\\\n[ACGTU]+\\\\n$'\n>>> entry = [r'>entry1\\\\nAGGGACTA\\\\n']\n>>> entry_verifier(entry, regex, '\\\\n')", "source": "codesearchnet"}
999{"code": "def rebuild_ragged_tensor_with_value_rowids(rt, feed_dict=None, sess=None):\n if isinstance(rt, ragged_tensor.RaggedTensor):\n values = rebuild_ragged_tensor_with_value_rowids(rt.values, feed_dict, sess)\n rowids = rt.value_rowids()\n nrows = rt.nrows()\n if feed_dict is not None:\n rowids_ph = make_placeholder(rowids)\n nrows_ph = make_placeholder(nrows)\n feed_dict[rowids_ph] = sess.run(rowids)\n feed_dict[nrows_ph] = sess.run(nrows)\n rowids, nrows = (rowids_ph, nrows_ph)\n return ragged_tensor.RaggedTensor.from_value_rowids(values, rowids, nrows)\n else:\n if feed_dict is not None:\n rt_ph = make_placeholder(rt)\n feed_dict[rt_ph] = sess.run(rt)\n rt = rt_ph\n return rt", "docstring": "Returns a copy of `rt`, built using `from_value_rowids`.\n\nThis ensures that RaggedTensor._cached_value_rowids is populated, which\ntriggers a different code-path for converting ragged tensors to tensors.\n\nIf `feed_dict` and `sess` are specified, then build the new `RaggedTensor`\nusing placeholder tensors, and populate a feed dictionary that can be used\nto feed the placeholders.\n\nArgs:\nrt: The RaggedTensor to copy.\nfeed_dict: If specified, then build the new `RaggedTensor` using\nplaceholders, and populate this dict with entries to feed those\nplaceholders.\nsess: A session used to evaluate tensors; required if feed_dict is\nspecified.\n\nReturns:\nA copy of `rt`, built using `from_value_rowids`.", "source": "github-repos"}
1000{"code": "def find_and_replace_userids(self, text):\n match = True\n pattern = re.compile('<@([A-Z0-9]{9})>')\n while match:\n match = pattern.search(text)\n if match:\n name = self.get_user_display_name(match.group(1))\n text = re.sub(re.compile(match.group(0)), ('@' + name), text)\n return text", "docstring": "Finds occurrences of Slack userids and attempts to replace them with\ndisplay names.\n\nArgs:\ntext (string): The message text\nReturns:\nstring: The message text with userids replaced.", "source": "codesearchnet"}
1001{"code": "def _ws_on_close(self, ws: websocket.WebSocketApp):\n \n self.connected = False\n self.logger.error('Websocket closed')\n self._reconnect_websocket()", "docstring": "Callback for closing the websocket connection\n\nArgs:\nws: websocket connection (now closed)", "source": "juraj-google-style"}
1002{"code": "def usergroups_users_list(self, *, usergroup: str, **kwargs) -> SlackResponse:\n self._validate_xoxp_token()\n kwargs.update({'usergroup': usergroup})\n return self.api_call('usergroups.users.list', http_verb='GET', params=kwargs)", "docstring": "List all users in a User Group\n\nArgs:\nusergroup (str): The encoded ID of the User Group to update.\ne.g. 'S0604QSJC'", "source": "codesearchnet"}
1003{"code": "def object_graph_key_mapping(checkpoint_path):\n reader = py_checkpoint_reader.NewCheckpointReader(checkpoint_path)\n object_graph_string = reader.get_tensor(trackable.OBJECT_GRAPH_PROTO_KEY)\n object_graph_proto = trackable_object_graph_pb2.TrackableObjectGraph()\n object_graph_proto.ParseFromString(object_graph_string)\n names_to_keys = {}\n for node in object_graph_proto.nodes:\n for attribute in node.attributes:\n names_to_keys[attribute.full_name] = attribute.checkpoint_key\n return names_to_keys", "docstring": "Return name to key mappings from the checkpoint.\n\nArgs:\ncheckpoint_path: string, path to object-based checkpoint\n\nReturns:\nDictionary mapping tensor names to checkpoint keys.", "source": "github-repos"}
1004{"code": "def _VerifyValues(self, tensor_in_sizes, depthwise_filter_in_sizes, pointwise_filter_in_sizes, stride, padding, expected, data_format='NHWC'):\n with self.cached_session():\n t1 = self._InitValues(tensor_in_sizes)\n f1 = self._InitValues(depthwise_filter_in_sizes)\n f1.set_shape(depthwise_filter_in_sizes)\n f2 = self._InitValues(pointwise_filter_in_sizes)\n real_t1 = t1\n strides = [1, stride, stride, 1]\n if data_format == 'NCHW':\n real_t1 = array_ops.transpose(t1, [0, 3, 1, 2])\n strides = [1, 1, stride, stride]\n if isinstance(padding, list):\n padding = [padding[0], padding[3], padding[1], padding[2]]\n conv = nn_impl.separable_conv2d(real_t1, f1, f2, strides=strides, padding=padding, data_format=data_format)\n if data_format == 'NCHW':\n conv = array_ops.transpose(conv, [0, 2, 3, 1])\n value = self.evaluate(conv)\n tf_logging.debug('value = %s', value)\n self.assertArrayNear(expected, np.ravel(value), 0.002)\n self.assertShapeEqual(value, conv)", "docstring": "Verifies the output values of the separable convolution function.\n\nArgs:\ntensor_in_sizes: Input tensor dimensions.\ndepthwise_filter_in_sizes: Depthwise filter tensor dimensions.\npointwise_filter_in_sizes: Pointwise filter tensor dimensions.\nstride: Stride.\npadding: Padding type.\nexpected: An array containing the expected operation outputs.\ndata_format: string data format for input tensor.", "source": "github-repos"}
1005{"code": "def _letter_map(word):\n \n\n lmap = {}\n for letter in word:\n try:\n lmap[letter] += 1\n except KeyError:\n lmap[letter] = 1\n return lmap", "docstring": "Creates a map of letter use in a word.\n\nArgs:\nword: a string to create a letter map from\n\nReturns:\na dictionary of {letter: integer count of letter in word}", "source": "juraj-google-style"}
1006{"code": "def __findFirstMissing(self, array, start, end):\n if (start > end):\n return (end + 1)\n if (start != array[start]):\n return start\n mid = int(((start + end) / 2))\n if (array[mid] == mid):\n return self.__findFirstMissing(array, (mid + 1), end)\n return self.__findFirstMissing(array, start, mid)", "docstring": "Find the smallest elements missing in a sorted array.\n\nReturns:\nint: The smallest element missing.", "source": "codesearchnet"}
1007{"code": "def write_file(\n task: Task,\n filename: str,\n content: str,\n append: bool = False,\n dry_run: Optional[bool] = None,\n) -> Result:\n \n diff = _generate_diff(filename, content, append)\n\n if not task.is_dry_run(dry_run):\n mode = \"a+\" if append else \"w+\"\n with open(filename, mode=mode) as f:\n f.write(content)\n\n return Result(host=task.host, diff=diff, changed=bool(diff))", "docstring": "Write contents to a file (locally)\n\nArguments:\ndry_run: Whether to apply changes or not\nfilename: file you want to write into\ncontent: content you want to write\nappend: whether you want to replace the contents or append to it\n\nReturns:\nResult object with the following attributes set:\n* changed (``bool``):\n* diff (``str``): unified diff", "source": "juraj-google-style"}
1008{"code": "def get_instances(serials):\n objs = []\n for s in serials:\n objs.append(Monsoon(serial=s))\n return objs", "docstring": "Create Monsoon instances from a list of serials.\n\nArgs:\nserials: A list of Monsoon (integer) serials.\n\nReturns:\nA list of Monsoon objects.", "source": "codesearchnet"}
1009{"code": "def with_eager_op_as_function(cls: Optional[type[_T]]=None, only_as_function: bool=False) -> Union[Callable[[type[_T]], type[_T]], type[_T]]:\n\n def decorator(cls: type[_T]) -> type[_T]:\n return cls\n if cls is not None:\n return decorator(cls)\n return decorator", "docstring": "Returns the same class. This will be removed once all usages are removed.\n\nArgs:\ncls: class to decorate.\nonly_as_function: unused argument.\n\nReturns:\ncls", "source": "github-repos"}
1010{"code": "def send_messages(cls, http_request, message_requests):\n deduplicated_messages = set(message_requests)\n for (msg_type, text) in deduplicated_messages:\n message_function = getattr(messages, msg_type)\n message_function(http_request, text)", "docstring": "Deduplicate any outgoing message requests, and send the remainder.\n\nArgs:\nhttp_request: The HTTP request in whose response we want to embed the messages\nmessage_requests: A list of undeduplicated messages in the form of tuples of message type\nand text- for example, ('error', 'Something went wrong')", "source": "codesearchnet"}
1011{"code": "def __setitem__(self, keyword, clean_name=None):\n \n status = False\n if not clean_name and keyword:\n clean_name = keyword\n\n if keyword and clean_name:\n if not self.case_sensitive:\n keyword = keyword.lower()\n current_dict = self.keyword_trie_dict\n for letter in keyword:\n current_dict = current_dict.setdefault(letter, {})\n if self._keyword not in current_dict:\n status = True\n self._terms_in_trie += 1\n current_dict[self._keyword] = clean_name\n return status", "docstring": "To add keyword to the dictionary\npass the keyword and the clean name it maps to.\n\nArgs:\nkeyword : string\nkeyword that you want to identify\n\nclean_name : string\nclean term for that keyword that you would want to get back in return or replace\nif not provided, keyword will be used as the clean name also.\n\nExamples:\n>>> keyword_processor['Big Apple'] = 'New York'", "source": "juraj-google-style"}
1012{"code": "def _ParseItem(self, parser_mediator, olecf_item):\n result = False\n event_data = OLECFItemEventData()\n event_data.name = olecf_item.name\n event_data.offset = 0\n event_data.size = olecf_item.size\n (creation_time, modification_time) = self._GetTimestamps(olecf_item)\n if creation_time:\n date_time = dfdatetime_filetime.Filetime(timestamp=creation_time)\n event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_CREATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n result = True\n if modification_time:\n date_time = dfdatetime_filetime.Filetime(timestamp=modification_time)\n event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n result = True\n for sub_item in olecf_item.sub_items:\n if self._ParseItem(parser_mediator, sub_item):\n result = True\n return result", "docstring": "Parses an OLECF item.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nolecf_item (pyolecf.item): OLECF item.\n\nReturns:\nbool: True if an event was produced.", "source": "codesearchnet"}
1013{"code": "def calculate_columns(sequence):\n columns = {}\n for row in sequence:\n for key in row.keys():\n if (key not in columns):\n columns[key] = len(key)\n value_length = len(str(row[key]))\n if (value_length > columns[key]):\n columns[key] = value_length\n return columns", "docstring": "Find all row names and the maximum column widths.\n\nArgs:\ncolumns (dict): the keys are the column name and the value the max length.\n\nReturns:\ndict: column names (key) and widths (value).", "source": "codesearchnet"}
1014{"code": "def path_get_destination(p: tcod.path.AStar) -> Tuple[int, int]:\n \n x = ffi.new(\"int *\")\n y = ffi.new(\"int *\")\n lib.TCOD_path_get_destination(p._path_c, x, y)\n return x[0], y[0]", "docstring": "Get the current destination position.\n\nArgs:\np (AStar): An AStar instance.\nReturns:\nTuple[int, int]: An (x, y) point.", "source": "juraj-google-style"}
1015{"code": "def IsTensorFlowEventsFile(path):\n if (not path):\n raise ValueError('Path must be a nonempty string')\n return ('tfevents' in tf.compat.as_str_any(os.path.basename(path)))", "docstring": "Check the path name to see if it is probably a TF Events file.\n\nArgs:\npath: A file path to check if it is an event file.\n\nRaises:\nValueError: If the path is an empty string.\n\nReturns:\nIf path is formatted like a TensorFlowEventsFile.", "source": "codesearchnet"}
1016{"code": "def calculate_positions(self, first_bee_val, second_bee_val, value_range):\n \n\n value = first_bee_val + np.random.uniform(-1, 1) \\\n * (first_bee_val - second_bee_val)\n if value_range[0] == 'int':\n value = int(value)\n if value > value_range[1][1]:\n value = value_range[1][1]\n if value < value_range[1][0]:\n value = value_range[1][0]\n\n return value", "docstring": "Calculate the new value/position for two given bee values\n\nArgs:\nfirst_bee_val (int or float): value from the first bee\nsecond_bee_val (int or float): value from the second bee\nvalue_ranges (tuple): \"(value type, (min_val, max_val))\" for the\ngiven value\n\nReturns:\nint or float: new value", "source": "juraj-google-style"}
1017{"code": "def has_no_fat_ends(neuron, multiple_of_mean=2.0, final_point_count=5):\n bad_ids = []\n for leaf in _nf.iter_sections(neuron.neurites, iterator_type=Tree.ileaf):\n mean_radius = np.mean(leaf.points[1:][((- final_point_count):, COLS.R)])\n if ((mean_radius * multiple_of_mean) <= leaf.points[((- 1), COLS.R)]):\n bad_ids.append((leaf.id, leaf.points[(- 1):]))\n return CheckResult((len(bad_ids) == 0), bad_ids)", "docstring": "Check if leaf points are too large\n\nArguments:\nneuron(Neuron): The neuron object to test\nmultiple_of_mean(float): how many times larger the final radius\nhas to be compared to the mean of the final points\nfinal_point_count(int): how many points to include in the mean\n\nReturns:\nCheckResult with result list of ids of bad sections\n\nNote:\nA fat end is defined as a leaf segment whose last point is larger\nby a factor of `multiple_of_mean` than the mean of the points in\n`final_point_count`", "source": "codesearchnet"}
1018{"code": "def unwrap_or_else(self, op: Callable[[E], U]) -> Union[T, U]:\n \n return cast(T, self._val) if self._is_ok else op(cast(E, self._val))", "docstring": "Returns the sucess value in the :class:`Result` or computes a default\nfrom the error value.\n\nArgs:\nop: The function to computes default with.\n\nReturns:\nThe success value in the :class:`Result` if it is\na :meth:`Result.Ok` value, otherwise ``op(E)``.\n\nExamples:\n>>> Ok(1).unwrap_or_else(lambda e: e * 10)\n1\n>>> Err(1).unwrap_or_else(lambda e: e * 10)\n10", "source": "juraj-google-style"}
1019{"code": "def get_record(self, name, record_id):\n \n if name in self._cache:\n if record_id in self._cache[name]:\n return self._cache[name][record_id]", "docstring": "Retrieve a record with a given type name and record id.\n\nArgs:\nname (string): The name which the record is stored under.\nrecord_id (int): The id of the record requested.\n\nReturns:\n:class:`cinder_data.model.CinderModel`: The cached model.", "source": "juraj-google-style"}
1020{"code": "def _make_tensor_slice_spec(slice_spec, use_constant=True):\n\n def make_piece_scalar(piece):\n if isinstance(piece, int):\n scalar = constant_op.constant(piece)\n if use_constant:\n return scalar\n else:\n return array_ops.placeholder_with_default(scalar, [])\n elif isinstance(piece, slice):\n return slice(make_piece_scalar(piece.start), make_piece_scalar(piece.stop), make_piece_scalar(piece.step))\n else:\n return piece\n if isinstance(slice_spec, tuple):\n return tuple((make_piece_scalar(piece) for piece in slice_spec))\n else:\n return make_piece_scalar(slice_spec)", "docstring": "Wraps all integers in an extended slice spec w/ a tensor.\n\nThis function is used to help test slicing when the slice spec contains\ntensors, rather than integers.\n\nArgs:\nslice_spec: The extended slice spec.\nuse_constant: If true, then wrap each integer with a tf.constant. If false,\nthen wrap each integer with a tf.placeholder.\n\nReturns:\nA copy of slice_spec, but with each integer i replaced with tf.constant(i).", "source": "github-repos"}
1021{"code": "def list_folder(cls, session, mailbox, folder):\n \n return cls(\n '/mailboxes/%d/folders/%s/conversations.json' % (\n mailbox.id, folder.id,\n ),\n session=session,\n )", "docstring": "Return conversations in a specific folder of a mailbox.\n\nArgs:\nsession (requests.sessions.Session): Authenticated session.\nmailbox (helpscout.models.Mailbox): Mailbox that folder is in.\nfolder (helpscout.models.Folder): Folder to list.\n\nReturns:\nRequestPaginator(output_type=helpscout.models.Conversation):\nConversations iterator.", "source": "juraj-google-style"}
1022{"code": "def leapfrog_step(leapfrog_step_state: LeapFrogStepState, step_size: FloatTensor, target_log_prob_fn: PotentialFn, kinetic_energy_fn: PotentialFn) -> Tuple[(LeapFrogStepState, LeapFrogStepExtras)]:\n state = leapfrog_step_state.state\n state_grads = leapfrog_step_state.state_grads\n momentum = leapfrog_step_state.momentum\n step_size = maybe_broadcast_structure(step_size, state)\n state = tf.nest.map_structure(tf.convert_to_tensor, state)\n momentum = tf.nest.map_structure(tf.convert_to_tensor, momentum)\n state = tf.nest.map_structure(tf.convert_to_tensor, state)\n if (state_grads is None):\n (_, _, state_grads) = call_and_grads(target_log_prob_fn, state)\n else:\n state_grads = tf.nest.map_structure(tf.convert_to_tensor, state_grads)\n momentum = tf.nest.map_structure((lambda m, sg, s: (m + ((0.5 * sg) * s))), momentum, state_grads, step_size)\n (kinetic_energy, kinetic_energy_extra, momentum_grads) = call_and_grads(kinetic_energy_fn, momentum)\n state = tf.nest.map_structure((lambda x, mg, s: (x + (mg * s))), state, momentum_grads, step_size)\n (target_log_prob, state_extra, state_grads) = call_and_grads(target_log_prob_fn, state)\n momentum = tf.nest.map_structure((lambda m, sg, s: (m + ((0.5 * sg) * s))), momentum, state_grads, step_size)\n return (LeapFrogStepState(state, state_grads, momentum), LeapFrogStepExtras(target_log_prob, state_extra, kinetic_energy, kinetic_energy_extra))", "docstring": "Leapfrog `TransitionOperator`.\n\nArgs:\nleapfrog_step_state: LeapFrogStepState.\nstep_size: Step size, structure broadcastable to the `target_log_prob_fn`\nstate.\ntarget_log_prob_fn: Target log prob fn.\nkinetic_energy_fn: Kinetic energy fn.\n\nReturns:\nleapfrog_step_state: LeapFrogStepState.\nleapfrog_step_extras: LeapFrogStepExtras.", "source": "codesearchnet"}
1023{"code": "def remove_team_member(self, account_id=None, email_address=None):\n return self._add_remove_team_member(self.TEAM_REMOVE_MEMBER_URL, email_address, account_id)", "docstring": "Remove a user from your Team\n\nArgs:\n\naccount_id (str): The id of the account of the user to remove from your team.\n\nemail_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided.\n\nReturns:\nA Team object", "source": "codesearchnet"}
1024{"code": "def find_function(self, context, funname):\n \n\n if funname in self.builtins:\n return self.builtins[funname]\n\n func = None\n if isinstance(context, dict):\n if funname in context:\n func = context[funname]\n\n \n if isinstance(func, str):\n func = self._deferred_add(func)\n context[funname] = func\n elif hasattr(context, funname):\n func = getattr(context, funname)\n\n if func is None:\n raise NotFoundError(\"Function not found\", function=funname)\n\n return func", "docstring": "Find a function in the given context by name.\n\nThis function will first search the list of builtins and if the\ndesired function is not a builtin, it will continue to search\nthe given context.\n\nArgs:\ncontext (object): A dict or class that is a typedargs context\nfunname (str): The name of the function to find\n\nReturns:\ncallable: The found function.", "source": "juraj-google-style"}
1025{"code": "def __init__(self, source_shape, target_shape, layer_broadcasters, dtype=None):\n if not isinstance(source_shape, DynamicRaggedShape):\n raise TypeError('source_shape is not a DynamicRaggedShape')\n if not isinstance(target_shape, DynamicRaggedShape):\n raise TypeError('target_shape is not a DynamicRaggedShape')\n if not isinstance(layer_broadcasters, list):\n raise TypeError('layer_broadcasters not a list: ' + str(layer_broadcasters))\n for bc in layer_broadcasters:\n if not isinstance(bc, _LayerBroadcaster):\n raise TypeError('Not a LayerBroadcaster: ' + str(bc))\n dtype = _find_dtype(source_shape, dtype)\n dtype = _find_dtype(target_shape, dtype)\n dtype = _find_dtype_iterable(layer_broadcasters, dtype)\n dtype = _find_dtype(dtypes.int64, dtype)\n self._source_shape = source_shape.with_dtype(dtype)\n self._target_shape = target_shape.with_dtype(dtype)\n self._layer_broadcasters = [x.with_dtype(dtype) for x in layer_broadcasters]", "docstring": "Create a broadcaster.\n\nDo not call directly.\nThe source_shape, target_shape, and layer_broadcasters are converted\nto have the same dtype.\n\nNote: source_shape.rank and target_shape.rank must be known.\nArgs:\nsource_shape: the source DynamicRaggedShape\ntarget_shape: the target DynamicRaggedShape\nlayer_broadcasters: List[_LayerBroadcaster] of length source_shape.rank.\ndtype: the preferred dtype of the broadcaster.\n\nRaises:\nTypeError: if the input types don't match.", "source": "github-repos"}
1026{"code": "def input_list_parser(infile_list):\n \n\n final_list_of_files = []\n\n for x in infile_list:\n\n \n if op.isdir(x):\n os.chdir(x)\n final_list_of_files.extend(glob.glob('*'))\n\n \n if op.isfile(x):\n final_list_of_files.append(x)\n\n return final_list_of_files", "docstring": "Always return a list of files with varying input.\n\n>>> input_list_parser(['/path/to/folder/'])\n['/path/to/folder/file1.txt', '/path/to/folder/file2.txt', '/path/to/folder/file3.txt']\n\n>>> input_list_parser(['/path/to/file.txt'])\n['/path/to/file.txt']\n\n>>> input_list_parser(['file1.txt'])\n['file1.txt']\n\nArgs:\ninfile_list: List of arguments\n\nReturns:\nlist: Standardized list of files", "source": "juraj-google-style"}
1027{"code": "def add_listener_policy(self, json_data):\n env = boto3.session.Session(profile_name=self.env, region_name=self.region)\n elbclient = env.client('elb')\n stickiness = {}\n elb_settings = self.properties['elb']\n if elb_settings.get('ports'):\n ports = elb_settings['ports']\n for listener in ports:\n if listener.get('stickiness'):\n stickiness = self.add_stickiness()\n LOG.info('Stickiness Found: %s', stickiness)\n break\n for job in json.loads(json_data)['job']:\n for listener in job['listeners']:\n policies = []\n ext_port = listener['externalPort']\n if listener['listenerPolicies']:\n policies.extend(listener['listenerPolicies'])\n if stickiness.get(ext_port):\n policies.append(stickiness.get(ext_port))\n if policies:\n LOG.info('Adding listener policies: %s', policies)\n elbclient.set_load_balancer_policies_of_listener(LoadBalancerName=self.app, LoadBalancerPort=ext_port, PolicyNames=policies)", "docstring": "Attaches listerner policies to an ELB\n\nArgs:\njson_data (json): return data from ELB upsert", "source": "codesearchnet"}
1028{"code": "def make_body(self, resp, params, meta, content):\n response = {'meta': meta, 'content': content}\n resp.content_type = 'application/json'\n resp.body = json.dumps(response, indent=((params['indent'] or None) if ('indent' in params) else None))", "docstring": "Construct response body in ``resp`` object using JSON serialization.\n\nArgs:\nresp (falcon.Response): response object where to include\nserialized body\nparams (dict): dictionary of parsed parameters\nmeta (dict): dictionary of metadata to be included in 'meta'\nsection of response\ncontent (dict): dictionary of response content (resource\nrepresentation) to be included in 'content' section of response\n\nReturns:\nNone", "source": "codesearchnet"}
1029{"code": "def get(self, key, **ctx_options):\n options = _make_ctx_options(ctx_options)\n use_cache = self._use_cache(key, options)\n if use_cache:\n self._load_from_cache_if_available(key)\n use_datastore = self._use_datastore(key, options)\n if (use_datastore and isinstance(self._conn, datastore_rpc.TransactionalConnection)):\n use_memcache = False\n else:\n use_memcache = self._use_memcache(key, options)\n ns = key.namespace()\n memcache_deadline = None\n if use_memcache:\n mkey = (self._memcache_prefix + key.urlsafe())\n memcache_deadline = self._get_memcache_deadline(options)\n mvalue = (yield self.memcache_get(mkey, for_cas=use_datastore, namespace=ns, use_cache=True, deadline=memcache_deadline))\n if use_cache:\n self._load_from_cache_if_available(key)\n if (mvalue not in (_LOCKED, None)):\n cls = model.Model._lookup_model(key.kind(), self._conn.adapter.default_model)\n pb = entity_pb.EntityProto()\n try:\n pb.MergePartialFromString(mvalue)\n except ProtocolBuffer.ProtocolBufferDecodeError:\n logging.warning(('Corrupt memcache entry found with key %s and namespace %s' % (mkey, ns)))\n mvalue = None\n else:\n entity = cls._from_pb(pb)\n entity._key = key\n if use_cache:\n self._cache[key] = entity\n raise tasklets.Return(entity)\n if ((mvalue is None) and use_datastore):\n (yield self.memcache_set(mkey, _LOCKED, time=_LOCK_TIME, namespace=ns, use_cache=True, deadline=memcache_deadline))\n (yield self.memcache_gets(mkey, namespace=ns, use_cache=True, deadline=memcache_deadline))\n if (not use_datastore):\n raise tasklets.Return(None)\n if use_cache:\n entity = (yield self._get_batcher.add_once(key, options))\n else:\n entity = (yield self._get_batcher.add(key, options))\n if (entity is not None):\n if (use_memcache and (mvalue != _LOCKED)):\n pbs = entity._to_pb(set_key=False).SerializePartialToString()\n if (len(pbs) <= memcache.MAX_VALUE_SIZE):\n timeout = self._get_memcache_timeout(key, options)\n (yield self.memcache_cas(mkey, pbs, time=timeout, namespace=ns, deadline=memcache_deadline))\n if use_cache:\n self._cache[key] = entity\n raise tasklets.Return(entity)", "docstring": "Return a Model instance given the entity key.\n\nIt will use the context cache if the cache policy for the given\nkey is enabled.\n\nArgs:\nkey: Key instance.\n**ctx_options: Context options.\n\nReturns:\nA Model instance if the key exists in the datastore; None otherwise.", "source": "codesearchnet"}
1030{"code": "def from_epsg_code(code):\n \n \n code = str(code)\n proj4 = utils.crscode_to_string(\"epsg\", code, \"proj4\")\n crs = from_proj4(proj4)\n return crs", "docstring": "Load crs object from epsg code, via spatialreference.org.\nParses based on the proj4 representation.\n\nArguments:\n\n- *code*: The EPSG code as an integer.\n\nReturns:\n\n- A CS instance of the indicated type.", "source": "juraj-google-style"}
1031{"code": "def from_value(value: Any, context: trace.TracingContext=None) -> trace.TraceType:\n if context is None:\n context = InternalTracingContext()\n if context.is_legacy_signature and isinstance(value, trace.TraceType):\n return value\n elif isinstance(value, trace.SupportsTracingProtocol):\n generated_type = value.__tf_tracing_type__(context)\n if not isinstance(generated_type, trace.TraceType):\n raise TypeError('Expected an instance of TraceType for Tracing Protocol call to ' + str(value) + ' but got ' + str(generated_type))\n return generated_type\n if isinstance(value, weakref.ref):\n raise TypeError(f'weakref input {value} not supported for tf.function.')\n if hasattr(value, '__wrapped__'):\n return from_value(value.__wrapped__, context)\n if isinstance(value, list):\n return default_types.List(*(from_value(c, context) for c in value))\n if isinstance(value, tuple):\n if util.is_namedtuple(value):\n named_tuple_type = type(value)\n return default_types.NamedTuple.from_type_and_attributes(named_tuple_type, tuple((from_value(c, context) for c in value)))\n else:\n return default_types.Tuple(*(from_value(c, context) for c in value))\n if isinstance(value, collections.abc.Mapping):\n mapping_type = type(value)\n return default_types.Dict({k: from_value(value[k], context) for k in value}, mapping_type)\n if util.is_attrs(value):\n return default_types.Attrs.from_type_and_attributes(type(value), tuple((from_value(getattr(value, a.name), context) for a in value.__attrs_attrs__)))\n if util.is_np_ndarray(value):\n ndarray = value.__array__()\n return default_types.TENSOR(ndarray.shape, ndarray.dtype)\n if isinstance(value, custom_nest_protocol.CustomNestProtocol):\n metadata, components = value.__tf_flatten__()\n return custom_nest_trace_type.CustomNestTraceType(type(value), metadata, tuple((from_value(c, context) for c in components)))\n try:\n ref = weakref.ref(value)\n if ref is None:\n raise TypeError(f'Deleted objects are not valid tf.function arguments, Got {value!r}')\n else:\n return default_types.Weakref(ref)\n except TypeError:\n try:\n return default_types.Literal(value)\n except:\n raise TypeError(f'Could not generate a generic TraceType for {value!r}.Please verify that it is immutable/hashable. Otherwise, consider implementing the Tracing Protocol for it.')", "docstring": "Returns a TraceType corresponding to the value based on the context.\n\nArgs:\nvalue: The value to generate a TraceType for.\ncontext: The TracingContext to be shared during protocol calls.\n\nReturns:\nA TraceType object representing the given value.", "source": "github-repos"}
1032{"code": "def get_input_params(distribution_strategy, num_samples, steps, batch_size, mode=None):\n use_per_replica_batch = not dist_utils.global_batch_size_supported(distribution_strategy)\n if context.executing_eagerly():\n allow_partial_batch = mode != ModeKeys.TRAIN or not backend.is_tpu_strategy(distribution_strategy)\n else:\n allow_partial_batch = mode == ModeKeys.TRAIN or ((mode == ModeKeys.PREDICT or mode == ModeKeys.TEST) and backend.is_tpu_strategy(distribution_strategy))\n if steps is None:\n if batch_size is None:\n global_batch_size = min(num_samples, 32)\n else:\n global_batch_size = batch_size\n if use_per_replica_batch:\n global_batch_size *= distribution_strategy.num_replicas_in_sync\n if allow_partial_batch:\n steps = np.ceil(num_samples / global_batch_size).astype(int)\n else:\n if num_samples % global_batch_size:\n raise ValueError('The number of samples %s is not divisible by batch size %s.' % (num_samples, global_batch_size))\n steps = num_samples \n elif batch_size is None:\n if num_samples % steps:\n raise ValueError('The number of samples %s is not divisible by steps %s. Please change the number of steps to a value that can consume all the samples' % (num_samples, steps))\n global_batch_size = num_samples \n else:\n global_batch_size = batch_size\n if use_per_replica_batch:\n global_batch_size *= distribution_strategy.num_replicas_in_sync\n min_num_samples = global_batch_size * steps\n if allow_partial_batch:\n min_num_samples = global_batch_size * (steps - 1) + 1 if steps > 1 else 0\n if num_samples < min_num_samples:\n raise ValueError('Number of samples %s is less than samples required for specified batch_size %s and steps %s' % (num_samples, global_batch_size, steps))\n if use_per_replica_batch:\n if global_batch_size % distribution_strategy.num_replicas_in_sync:\n raise ValueError('The batch size (%s) could not be sharded evenly across the sync replicas (%s) in the distribution strategy.' % (global_batch_size, distribution_strategy.num_replicas_in_sync))\n batch_size = global_batch_size \n else:\n batch_size = global_batch_size\n return (steps, batch_size)", "docstring": "Calculate the number of batches and steps/steps_per_epoch.\n\nArgs:\ndistribution_strategy: The DistributionStrategy used to compile the model.\nnum_samples: The number of samples from which we determine the batch size\nand steps.\nsteps: The specified number of steps.\nbatch_size: The specified batch_size.\nmode: ModeKey representing whether input will be used for training,\nevaluation, or prediction. This is used to relax the constraints on\nconsuming all the training samples to keep compatibility till we support\npartial batches. If none, then partial batches are not allowed.\n\nReturns:\nsteps: The steps or steps_per_epoch argument depending on if a user is\ncalling `fit`, `evaluate` or `predict`. If the is_training flag is set\nwe don't require the number of samples to be used completely.\nbatch_size: The batch size to be used in model iterations.\n\nRaises:\nValueError: If the number of batches or steps evaluates to 0.", "source": "github-repos"}
1033{"code": "def aliased_as(self, name):\n stream = copy.copy(self)\n stream._alias = name\n return stream", "docstring": "Create an alias of this stream.\n\nReturns an alias of this stream with name `name`.\nWhen invocation of an SPL operator requires an\n:py:class:`~streamsx.spl.op.Expression` against\nan input port this can be used to ensure expression\nmatches the input port alias regardless of the name\nof the actual stream.\n\nExample use where the filter expression for a ``Filter`` SPL operator\nuses ``IN`` to access input tuple attribute ``seq``::\n\ns = ...\ns = s.aliased_as('IN')\n\nparams = {'filter': op.Expression.expression('IN.seq % 4ul == 0ul')}\nf = op.Map('spl.relational::Filter', stream, params = params)\n\nArgs:\nname(str): Name for returned stream.\n\nReturns:\nStream: Alias of this stream with ``name`` equal to `name`.\n\n.. versionadded:: 1.9", "source": "codesearchnet"}
1034{"code": "def clip_by_value(x, min, max):\n from .function_bases import maximum2 as maximum2_base\n from .function_bases import minimum2 as minimum2_base\n return minimum2_base(maximum2_base(x, min), max)", "docstring": "r\"\"\"Clip inputs by values.\n\n.. math::\n\ny = \\begin{cases}\nmax & (x > max) \\\\\nx & (otherwise) \\\\\nmin & (x < min)\n\\end{cases}.\n\nArgs:\nx (Variable): An input variable.\nmin (Variable): A min variable by which `x` is clipped. Note that the shape of `min` must be the same as `x`'s.\nmax (Variable): A max variable by which `x` is clipped. Note that the shape of `max` must be the same as `x`'s\n\nReturns:\n~nnabla.Variable: N-D array.", "source": "codesearchnet"}
1035{"code": "def read_uint32(self, little_endian=True):\n \n if little_endian:\n endian = \"<\"\n else:\n endian = \">\"\n return self.unpack('%sI' % endian, 4)", "docstring": "Read 4 bytes as an unsigned integer value from the stream.\n\nArgs:\nlittle_endian (bool): specify the endianness. (Default) Little endian.\n\nReturns:\nint:", "source": "juraj-google-style"}
1036{"code": "def StringEscape(self, string, match, **_):\n \n precondition.AssertType(string, Text)\n\n \n \n \n if self.current_expression.operator == \"regexp\":\n self.string += compatibility.UnescapeString(string)\n elif match.group(1) in \"\\\\'\\\"rnbt\":\n self.string += compatibility.UnescapeString(string)\n else:\n raise ParseError(\"Invalid escape character %s.\" % string)", "docstring": "Escape backslashes found inside a string quote.\n\nBackslashes followed by anything other than [\\'\"rnbt] will raise an Error.\n\nArgs:\nstring: The string that matched.\nmatch: The match object (m.group(1) is the escaped code)\n\nRaises:\nParseError: For strings other than those used to define a regexp, raise an\nerror if the escaped string is not one of [\\'\"rnbt].", "source": "juraj-google-style"}
1037{"code": "def _self_suppression(iou, _, iou_sum, iou_threshold):\n batch_size = array_ops.shape(iou)[0]\n can_suppress_others = math_ops.cast(array_ops.reshape(math_ops.reduce_max(iou, 1) < iou_threshold, [batch_size, -1, 1]), iou.dtype)\n iou_after_suppression = array_ops.reshape(math_ops.cast(math_ops.reduce_max(can_suppress_others * iou, 1) < iou_threshold, iou.dtype), [batch_size, -1, 1]) * iou\n iou_sum_new = math_ops.reduce_sum(iou_after_suppression, [1, 2])\n return [iou_after_suppression, math_ops.reduce_any(iou_sum - iou_sum_new > iou_threshold), iou_sum_new, iou_threshold]", "docstring": "Suppress boxes in the same tile.\n\nCompute boxes that cannot be suppressed by others (i.e.,\ncan_suppress_others), and then use them to suppress boxes in the same tile.\n\nArgs:\niou: a tensor of shape [batch_size, num_boxes_with_padding] representing\nintersection over union.\niou_sum: a scalar tensor.\niou_threshold: a scalar tensor.\n\nReturns:\niou_suppressed: a tensor of shape [batch_size, num_boxes_with_padding].\niou_diff: a scalar tensor representing whether any box is supressed in\nthis step.\niou_sum_new: a scalar tensor of shape [batch_size] that represents\nthe iou sum after suppression.\niou_threshold: a scalar tensor.", "source": "github-repos"}
1038{"code": "def path2route(path: SchemaPath) -> SchemaRoute:\n \n if path == \"/\" or path == \"\":\n return []\n nlist = path.split(\"/\")\n prevns = None\n res = []\n for n in (nlist[1:] if path[0] == \"/\" else nlist):\n p, s, loc = n.partition(\":\")\n if s:\n if p == prevns:\n raise InvalidSchemaPath(path)\n res.append((loc, p))\n prevns = p\n elif prevns:\n res.append((p, prevns))\n else:\n raise InvalidSchemaPath(path)\n return res", "docstring": "Translate a schema/data path to a schema/data route.\n\nArgs:\npath: Schema path.\n\nRaises:\nInvalidSchemaPath: Invalid path.", "source": "juraj-google-style"}
1039{"code": "def __init__(self, description=None, default=None, required=False):\n \n self.__doc__ = description\n self._default = default\n self._value = default\n self._required = bool(required)", "docstring": "Initialize the option with some basic metadata.\n\nArgs:\ndescription (str, optional): A human readable description of what\nthe option represents.\ndefault (optional): The default value to use if unset.\nrequired (bool, optional): Whether or not the value must be set.", "source": "juraj-google-style"}
1040{"code": "def raiseError(cls, message):\n \n error_message = \"[error] %s\" % message\n if cls.__raise_exception__:\n raise Exception(error_message)\n\n cls.colorprint(error_message, Fore.RED)\n sys.exit(1)", "docstring": "Print an error message\n\nArgs:\nmessage: the message to print", "source": "juraj-google-style"}
1041{"code": "def setup_remoteckan(self, remoteckan=None, **kwargs):\n if (remoteckan is None):\n self._remoteckan = self.create_remoteckan(self.get_hdx_site_url(), full_agent=self.get_user_agent(), **kwargs)\n else:\n self._remoteckan = remoteckan", "docstring": "Set up remote CKAN from provided CKAN or by creating from configuration\n\nArgs:\nremoteckan (Optional[ckanapi.RemoteCKAN]): CKAN instance. Defaults to setting one up from configuration.\n\nReturns:\nNone", "source": "codesearchnet"}
1042{"code": "def get_create_batch_env_fun(batch_env_fn, time_limit):\n \n\n def create_env_fun(game_name=None, sticky_actions=None):\n del game_name, sticky_actions\n batch_env = batch_env_fn(in_graph=False)\n batch_env = ResizeBatchObservation(batch_env) \n batch_env = DopamineBatchEnv(batch_env, max_episode_steps=time_limit)\n return batch_env\n\n return create_env_fun", "docstring": "Factory for dopamine environment initialization function.\n\nArgs:\nbatch_env_fn: function(in_graph: bool) -> batch environment.\ntime_limit: time steps limit for environment.\n\nReturns:\nfunction (with optional, unused parameters) initializing environment.", "source": "juraj-google-style"}
1043{"code": "async def send(self, metric):\n \n message = json.dumps(metric).encode('utf-8')\n await self.loop.create_datagram_endpoint(\n lambda: UDPClientProtocol(message),\n remote_addr=(self.ip, self.port))", "docstring": "Transform metric to JSON bytestring and send to server.\n\nArgs:\nmetric (dict): Complete metric to send as JSON.", "source": "juraj-google-style"}
1044{"code": "def ExpandUsersVariablePath(cls, path, path_separator, user_accounts):\n \n path_segments = path.split(path_separator)\n return cls._ExpandUsersVariablePathSegments(\n path_segments, path_separator, user_accounts)", "docstring": "Expands a path with a users variable, e.g. %%users.homedir%%.\n\nArgs:\npath (str): path with users variable.\npath_separator (str): path segment separator.\nuser_accounts (list[UserAccountArtifact]): user accounts.\n\nReturns:\nlist[str]: paths for which the users variables have been expanded.", "source": "juraj-google-style"}
1045{"code": "def decompose_space(H, A):\n \n return OperatorTrace.create(\n OperatorTrace.create(A, over_space=H.operands[-1]),\n over_space=ProductSpace.create(*H.operands[:-1]))", "docstring": "Simplifies OperatorTrace expressions over tensor-product spaces by\nturning it into iterated partial traces.\n\nArgs:\nH (ProductSpace): The full space.\nA (Operator):\n\nReturns:\nOperator: Iterative partial trace expression", "source": "juraj-google-style"}
1046{"code": "def selection_error_control(self, form_info):\n (keys, names) = self.return_selected_form_items(form_info['ChannelList'])\n chosen_channels_number = len(keys)\n if (form_info['new_channel'] and (chosen_channels_number < 2)):\n return (False, _(u'You should choose at least two channel to merge operation at a new channel.'))\n elif (form_info['existing_channel'] and (chosen_channels_number == 0)):\n return (False, _(u'You should choose at least one channel to merge operation with existing channel.'))\n elif (form_info['find_chosen_channel'] and (chosen_channels_number != 1)):\n return (False, _(u'You should choose one channel for split operation.'))\n return (True, None)", "docstring": "It controls the selection from the form according\nto the operations, and returns an error message\nif it does not comply with the rules.\n\nArgs:\nform_info: Channel or subscriber form from the user\n\nReturns: True or False\nerror message", "source": "codesearchnet"}
1047{"code": "def require(self, entity_type, attribute_name=None):\n if (not attribute_name):\n attribute_name = entity_type\n self.requires += [(entity_type, attribute_name)]\n return self", "docstring": "The intent parser should require an entity of the provided type.\n\nArgs:\nentity_type(str): an entity type\nattribute_name(str): the name of the attribute on the parsed intent. Defaults to match entity_type.\n\nReturns:\nself: to continue modifications.", "source": "codesearchnet"}
1048{"code": "def get_ilo_sso_url(self, ip=None):\n \n uri = \"{}/iloSsoUrl\".format(self.data[\"uri\"])\n\n if ip:\n uri = \"{}?ip={}\".format(uri, ip)\n\n return self._helper.do_get(uri)", "docstring": "Retrieves the URL to launch a Single Sign-On (SSO) session for the iLO web interface. If the server hardware is\nunsupported, the resulting URL will not use SSO and the iLO web interface will prompt for credentials.\nThis is not supported on G7/iLO3 or earlier servers.\n\nArgs:\nip: IP address or host name of the server's iLO management processor\n\nReturns:\nURL", "source": "juraj-google-style"}
1049{"code": "def get_members(cls, session, team_or_id):\n \n if isinstance(team_or_id, Person):\n team_or_id = team_or_id.id\n return cls(\n '/teams/%d/members.json' % team_or_id,\n session=session,\n out_type=User,\n )", "docstring": "List the members for the team.\n\nArgs:\nteam_or_id (helpscout.models.Person or int): Team or the ID of\nthe team to get the folders for.\n\nReturns:\nRequestPaginator(output_type=helpscout.models.Users): Users\niterator.", "source": "juraj-google-style"}
1050{"code": "def from_prev_calc(cls, prev_calc_dir, mode='gap', reciprocal_density=50, copy_chgcar=True, **kwargs):\n (vasprun, outcar) = get_vasprun_outcar(prev_calc_dir)\n prev_structure = get_structure_from_prev_run(vasprun, outcar, sym_prec=0)\n added_kpoints = []\n if (mode.lower() == 'gap'):\n bs = vasprun.get_band_structure()\n (vbm, cbm) = (bs.get_vbm()['kpoint'], bs.get_cbm()['kpoint'])\n if vbm:\n added_kpoints.append(vbm.frac_coords)\n if cbm:\n added_kpoints.append(cbm.frac_coords)\n files_to_transfer = {}\n if copy_chgcar:\n chgcars = sorted(glob.glob(str((Path(prev_calc_dir) / 'CHGCAR*'))))\n if chgcars:\n files_to_transfer['CHGCAR'] = str(chgcars[(- 1)])\n return cls(structure=prev_structure, added_kpoints=added_kpoints, reciprocal_density=reciprocal_density, mode=mode, files_to_transfer=files_to_transfer, **kwargs)", "docstring": "Generate a set of Vasp input files for HSE calculations from a\ndirectory of previous Vasp run. if mode==\"gap\", it explicitly adds VBM\nand CBM of the prev run to the k-point list of this run.\n\nArgs:\nprev_calc_dir (str): Directory containing the outputs\n(vasprun.xml and OUTCAR) of previous vasp run.\nmode (str): Either \"uniform\", \"gap\" or \"line\"\nreciprocal_density (int): density of k-mesh\ncopy_chgcar (bool): whether to copy CHGCAR of previous run\n\\\\*\\\\*kwargs: All kwargs supported by MPHSEBSStaticSet,\nother than prev_structure which is determined from the previous\ncalc dir.", "source": "codesearchnet"}
1051{"code": "def _HashBlock(self, block, start, end):\n for finger in self.fingers:\n expected_range = finger.CurrentRange()\n if (expected_range is None):\n continue\n if ((start > expected_range.start) or ((start == expected_range.start) and (end > expected_range.end)) or ((start < expected_range.start) and (end > expected_range.start))):\n raise RuntimeError('Cutting across fingers.')\n if (start == expected_range.start):\n finger.HashBlock(block)", "docstring": "_HashBlock feeds data blocks into the hashers of fingers.\n\nThis function must be called before adjusting fingers for next\ninterval, otherwise the lack of remaining ranges will cause the\nblock not to be hashed for a specific finger.\n\nStart and end are used to validate the expected ranges, to catch\nunexpected use of that logic.\n\nArgs:\nblock: The data block.\nstart: Beginning offset of this block.\nend: Offset of the next byte after the block.\n\nRaises:\nRuntimeError: If the provided and expected ranges don't match.", "source": "codesearchnet"}
1052{"code": "def testConcreteFunctionFlatSignatureError(self, conc_args=(), conc_kwargs=None, call_args=(), call_kwargs=None, error='.*', exception=TypeError):\n conc_args = conc_args() if callable(conc_args) else conc_args\n conc_kwargs = conc_kwargs() if callable(conc_kwargs) else conc_kwargs or {}\n call_args = call_args() if callable(call_args) else call_args\n call_kwargs = call_kwargs() if callable(call_kwargs) else call_kwargs or {}\n self.assertIsInstance(conc_args, tuple)\n self.assertIsInstance(call_args, tuple)\n self.assertIsInstance(conc_kwargs, dict)\n self.assertIsInstance(call_kwargs, dict)\n\n @polymorphic_function.function\n def func(x, y=5, *varargs, **kwargs):\n del y, varargs, kwargs\n return x\n conc = func.get_concrete_function(*conc_args, **conc_kwargs)\n with self.assertRaisesRegex(exception, error):\n self.evaluate(conc._call_with_flat_signature(call_args, call_kwargs))", "docstring": "Tests for errors in the flat signature.\n\nArgs:\nconc_args: Positional arguments used for get_concrete_function.\nconc_kwargs: Keyword arguments used for get_concrete_function.\ncall_args: Positional arguments used to call the function.\ncall_kwargs: Keyword arguments used to call the function.\nerror: Expected exception message.\nexception: Expected exception type.", "source": "github-repos"}
1053{"code": "def replace_with_vptq_linear(model, quantization_config=None, modules_to_not_convert=None, current_key_name=None, has_been_replaced=False):\n modules_to_not_convert = ['lm_head'] if not modules_to_not_convert else modules_to_not_convert\n for name, module in model.named_children():\n if current_key_name is None:\n current_key_name = []\n current_key_name.append(name)\n layer_name = '.'.join(current_key_name)\n shared_layer_config = quantization_config.shared_layer_config\n config_for_layers = quantization_config.config_for_layers\n if isinstance(module, nn.Linear) and layer_name not in modules_to_not_convert and (layer_name in config_for_layers or current_key_name[-1] in shared_layer_config):\n layer_params = config_for_layers.get(layer_name, None) or shared_layer_config.get(current_key_name[-1], None)\n with init_empty_weights():\n in_features = module.in_features\n out_features = module.out_features\n model._modules[name] = VQuantLinear(in_features, out_features, vector_lens=layer_params['vector_lens'], num_centroids=layer_params['num_centroids'], num_res_centroids=layer_params['num_res_centroids'], group_num=layer_params['group_num'], group_size=layer_params['group_size'], outlier_size=layer_params['outlier_size'], indices_as_float=layer_params['indices_as_float'], enable_norm=layer_params['enable_norm'], enable_perm=layer_params['enable_perm'], is_indice_packed=True, enable_proxy_error=False, bias=module.bias is not None)\n has_been_replaced = True\n model._modules[name].requires_grad_(False)\n if len(list(module.children())) > 0:\n _, has_been_replaced = replace_with_vptq_linear(module, quantization_config=quantization_config, modules_to_not_convert=modules_to_not_convert, current_key_name=current_key_name, has_been_replaced=has_been_replaced)\n current_key_name.pop(-1)\n return (model, has_been_replaced)", "docstring": "Public method that recursively replaces the Linear layers of the given model with VPTQ quantized layers.\n`accelerate` is needed to use this method. Returns the converted model and a boolean that indicates if the\nconversion has been successful or not.\n\nArgs:\nmodel (`torch.nn.Module`):\nThe model to convert, can be any `torch.nn.Module` instance.\nquantization_config (`VptqConfig`):\nThe quantization config object that contains the quantization parameters.\nmodules_to_not_convert (`List[`str`]`, *optional*, defaults to `[\"lm_head\"]`):\nNames of the modules to not convert in `VQuantLinear`. In practice we keep the `lm_head` in full precision\nfor numerical stability reasons.\ncurrent_key_name (`list`, *optional*):\nA list that contains the current key name. This is used for recursion and should not be passed by the user.\nhas_been_replaced (`bool`, *optional*):\nA boolean that indicates if the conversion has been successful or not. This is used for recursion and\nshould not be passed by the user.", "source": "github-repos"}
1054{"code": "def get_object(cls, api_token, droplet_id):\n droplet = cls(token=api_token, id=droplet_id)\n droplet.load()\n return droplet", "docstring": "Class method that will return a Droplet object by ID.\n\nArgs:\napi_token (str): token\ndroplet_id (int): droplet id", "source": "codesearchnet"}
1055{"code": "def is_connected(self):\n if (self._client is not None):\n try:\n self._client.server_info()\n except ConnectionFailure:\n return False\n return True\n else:\n return False", "docstring": "Returns the connection status of the data store.\n\nReturns:\nbool: ``True`` if the data store is connected to the MongoDB server.", "source": "codesearchnet"}
1056{"code": "def call_for_each_tower(\n towers, func, devices=None, use_vs=None):\n \n\n ret = []\n if devices is not None:\n assert len(devices) == len(towers)\n if use_vs is not None:\n assert len(use_vs) == len(towers)\n\n tower_names = ['tower{}'.format(idx) for idx in range(len(towers))]\n\n for idx, t in enumerate(towers):\n device = devices[idx] if devices is not None else '/gpu:{}'.format(t)\n usevs = use_vs[idx] if use_vs is not None else False\n reuse = not usevs and idx > 0\n with tfv1.device(device), _maybe_reuse_vs(reuse), TrainTowerContext(\n tower_names[idx],\n vs_name=tower_names[idx] if usevs else '',\n index=idx, total=len(towers)):\n if len(str(device)) < 10: \n logger.info(\"Building graph for training tower {} on device {} ...\".format(idx, device))\n else:\n logger.info(\"Building graph for training tower {} ...\".format(idx))\n\n \n \n with override_to_local_variable(enable=usevs):\n ret.append(func())\n return ret", "docstring": "Run `func` on all GPUs (towers) and return the results.\n\nArgs:\ntowers (list[int]): a list of GPU id.\nfunc: a lambda to be called inside each tower\ndevices: a list of devices to be used. By default will use '/gpu:{tower}'\nuse_vs (list[bool]): list of use_vs to passed to TowerContext\n\nReturns:\nList of outputs of ``func``, evaluated on each tower.", "source": "juraj-google-style"}
1057{"code": "def __init__(self, layers=None, name=None):\n super(functional.Functional, self).__init__(name=name, autocast=False)\n self.supports_masking = True\n self._compute_output_and_mask_jointly = True\n self._auto_track_sub_layers = False\n self._inferred_input_shape = None\n self._has_explicit_input_shape = False\n self._input_dtype = None\n self._layer_call_argspecs = {}\n self._created_nodes = set()\n self._graph_initialized = False\n self._use_legacy_deferred_behavior = False\n if layers:\n if not isinstance(layers, (list, tuple)):\n layers = [layers]\n for layer in layers:\n self.add(layer)", "docstring": "Creates a `Sequential` model instance.\n\nArgs:\nlayers: Optional list of layers to add to the model.\nname: Optional name for the model.", "source": "github-repos"}
1058{"code": "def has_neigh(tag_name, params=None, content=None, left=True):\n\n def has_neigh_closure(element):\n if ((not element.parent) or (not (element.isTag() and (not element.isEndTag())))):\n return False\n childs = element.parent.childs\n childs = filter((lambda x: ((x.isTag() and (not x.isEndTag())) or x.getContent().strip() or (x is element))), childs)\n if (len(childs) <= 1):\n return False\n ioe = childs.index(element)\n if (left and (ioe > 0)):\n return is_equal_tag(childs[(ioe - 1)], tag_name, params, content)\n if ((not left) and ((ioe + 1) < len(childs))):\n return is_equal_tag(childs[(ioe + 1)], tag_name, params, content)\n return False\n return has_neigh_closure", "docstring": "This function generates functions, which matches all tags with neighbours\ndefined by parameters.\n\nArgs:\ntag_name (str): Tag has to have neighbour with this tagname.\nparams (dict): Tag has to have neighbour with this parameters.\nparams (str): Tag has to have neighbour with this content.\nleft (bool, default True): Tag has to have neigbour on the left, or\nright (set to ``False``).\n\nReturns:\nbool: True for every matching tag.\n\nNote:\nThis function can be used as parameter for ``.find()`` method in\nHTMLElement.", "source": "codesearchnet"}
1059{"code": "def inverse_stft_window_fn(frame_step, forward_window_fn=window_ops.hann_window, name=None):\n\n def inverse_stft_window_fn_inner(frame_length, dtype):\n \n with ops.name_scope(name, 'inverse_stft_window_fn', [forward_window_fn]):\n frame_step_ = ops.convert_to_tensor(frame_step, name='frame_step')\n frame_step_.shape.assert_has_rank(0)\n frame_length = ops.convert_to_tensor(frame_length, name='frame_length')\n frame_length.shape.assert_has_rank(0)\n forward_window = forward_window_fn(frame_length, dtype=dtype)\n denom = math_ops.square(forward_window)\n overlaps = -(-frame_length \n denom = array_ops.pad(denom, [(0, overlaps * frame_step_ - frame_length)])\n denom = array_ops.reshape(denom, [overlaps, frame_step_])\n denom = math_ops.reduce_sum(denom, 0, keepdims=True)\n denom = array_ops.tile(denom, [overlaps, 1])\n denom = array_ops.reshape(denom, [overlaps * frame_step_])\n return forward_window / denom[:frame_length]\n return inverse_stft_window_fn_inner", "docstring": "Generates a window function that can be used in `inverse_stft`.\n\nConstructs a window that is equal to the forward window with a further\npointwise amplitude correction. `inverse_stft_window_fn` is equivalent to\n`forward_window_fn` in the case where it would produce an exact inverse.\n\nSee examples in `inverse_stft` documentation for usage.\n\nArgs:\nframe_step: An integer scalar `Tensor`. The number of samples to step.\nforward_window_fn: window_fn used in the forward transform, `stft`.\nname: An optional name for the operation.\n\nReturns:\nA callable that takes a window length and a `dtype` keyword argument and\nreturns a `[window_length]` `Tensor` of samples in the provided datatype.\nThe returned window is suitable for reconstructing original waveform in\ninverse_stft.", "source": "github-repos"}
1060{"code": "def _get_max_page(dom):\n div = dom.find('div', {'class': 'razeniKnihListovani'})\n if (not div):\n return 1\n links = div[0].find('a')\n max_page = filter((lambda x: (('href' in x.params) and ('pageindex=' in x.params['href']))), links)\n max_page = map((lambda x: x.params['href'].split('pageindex=')[(- 1)]), max_page)\n max_page = filter((lambda x: x.isdigit()), max_page)\n max_page = map((lambda x: int(x)), max_page)\n if (not max_page):\n return 1\n return max(max_page)", "docstring": "Try to guess how much pages are in book listing.\n\nArgs:\ndom (obj): HTMLElement container of the page with book list.\n\nReturns:\nint: Number of pages for given category.", "source": "codesearchnet"}
1061{"code": "def mark_backward(output_tensor, used_node_names):\n \n op = output_tensor.op\n if op.name in used_node_names:\n return\n used_node_names.add(op.name)\n for input_tensor in op.inputs:\n mark_backward(input_tensor, used_node_names)\n for control_input_op in op.control_inputs:\n used_node_names.add(control_input_op.name)\n for input_tensor in control_input_op.inputs:\n mark_backward(input_tensor, used_node_names)", "docstring": "Function to propagate backwards in the graph and mark nodes as used.\n\nTraverses recursively through the graph from the end tensor, through the op\nthat generates the tensor, and then to the input tensors that feed the op.\nNodes encountered are stored in used_node_names.\n\nArgs:\noutput_tensor: A Tensor which we start the propagation.\nused_node_names: A list of strings, stores the name of nodes we've marked as\nvisited.", "source": "juraj-google-style"}
1062{"code": "def get_plugin(self, identifier, cls=None):\n \n if ((cls is None or cls == 'provider')\n and identifier in self.available_providers):\n return self.available_providers[identifier]\n elif ((cls is None or cls == 'checker')\n and identifier in self.available_checkers):\n return self.available_checkers[identifier]\n return Config.load_local_plugin(identifier)", "docstring": "Return the plugin corresponding to the given identifier and type.\n\nArgs:\nidentifier (str): identifier of the plugin.\ncls (str): one of checker / provider.\n\nReturns:\nChecker/Provider: plugin class.", "source": "juraj-google-style"}
1063{"code": "def _write_credentials_file(credentials_file, credentials):\n \n data = {'file_version': 2, 'credentials': {}}\n\n for key, credential in iteritems(credentials):\n credential_json = credential.to_json()\n encoded_credential = _helpers._from_bytes(base64.b64encode(\n _helpers._to_bytes(credential_json)))\n data['credentials'][key] = encoded_credential\n\n credentials_file.seek(0)\n json.dump(data, credentials_file)\n credentials_file.truncate()", "docstring": "Writes credentials to a file.\n\nRefer to :func:`_load_credentials_file` for the format.\n\nArgs:\ncredentials_file: An open file handle, must be read/write.\ncredentials: A dictionary mapping user-defined keys to an instance of\n:class:`oauth2client.client.Credentials`.", "source": "juraj-google-style"}
1064{"code": "def __init__(self, primals, tangents):\n self._accumulator = pywrap_tfe.TFE_Py_ForwardAccumulatorNew(False)\n self._recording = False\n primal_ids = set()\n for primal in nest.flatten(primals):\n if id(primal) in primal_ids:\n raise ValueError('Tensor {} was specified as a primal multiple times. This may indicate an error. If it was intended, please sum the corresponding tangents.')\n primal_ids.add(id(primal))\n self._watch(primals, tangents)", "docstring": "Specify tensors to watch and their Jacobian-vector products.\n\nMathematically, `tangents` is a vector right-multiplying the Jacobian matrix\n(a Jacobian-vector product) for the function computed while this accumulator\nis active. Since JVPs are computed in forward mode as the computation\nhappens, this vector must be supplied in advance.\n\nListing a single tensor multiple times in `primals` raises an\nexception. Excluding a tensor from `primals` is equivalent to watching it\nwith a tangent tensor of zeros.\n\nArgs:\nprimals: A tensor or nested structure of tensors to watch.\ntangents: A tensor or nested structure of tensors, with the same nesting\nstructure as `primals`, with each element being a vector with the same\nsize as the corresponding primal element.\n\nRaises:\nValueError: If the same tensor or variable is specified multiple times in\n`primals`.", "source": "github-repos"}
1065{"code": "def pull(self, device_filename, dest_file=None, timeout_ms=None):\n \n should_return_data = dest_file is None\n if isinstance(dest_file, six.string_types):\n dest_file = open(dest_file, 'w')\n elif dest_file is None:\n dest_file = six.StringIO()\n self.filesync_service.recv(device_filename, dest_file,\n timeouts.PolledTimeout.from_millis(timeout_ms))\n if should_return_data:\n return dest_file.getvalue()", "docstring": "Pull file from device.\n\nArguments:\ndevice_filename: The filename on the device to pull.\ndest_file: If set, a filename or writable file-like object.\ntimeout_ms: Expected timeout for the pull.\n\nReturns:\nThe file data if dest_file is not set, None otherwise.", "source": "juraj-google-style"}
1066{"code": "def load_fasta_file_as_dict_of_seqs(filename):\n \n\n results = {}\n records = load_fasta_file(filename)\n for r in records:\n results[r.id] = str(r.seq)\n\n return results", "docstring": "Load a FASTA file and return the sequences as a dict of {ID: sequence string}\n\nArgs:\nfilename (str): Path to the FASTA file to load\n\nReturns:\ndict: Dictionary of IDs to their sequence strings", "source": "juraj-google-style"}
1067{"code": "def check(self, version):\n \n\n for disjunct in self._disjuncts:\n if self._check_insersection(version, disjunct):\n return True\n\n return False", "docstring": "Check that a version is inside this SemanticVersionRange\n\nArgs:\nversion (SemanticVersion): The version to check\n\nReturns:\nbool: True if the version is included in the range, False if not", "source": "juraj-google-style"}
1068{"code": "def _clean_isbn(isbn):\n if isinstance(isbn, basestring):\n isbn = list(isbn.lower())\n isbn = filter((lambda x: (x.isdigit() or (x == 'x'))), isbn)\n return map((lambda x: (10 if (x == 'x') else int(x))), isbn)", "docstring": "Remove all non-digit and non \"x\" characters from given string.\n\nArgs:\nisbn (str): isbn string, which will be cleaned.\n\nReturns:\nlist: array of numbers (if \"x\" is found, it is converted to 10).", "source": "codesearchnet"}
1069{"code": "def _register_callback(self, cb):\n \n if isinstance(cb, (list, tuple)):\n for x in cb:\n self._register_callback(x)\n return\n assert isinstance(cb, Callback), cb\n assert not isinstance(self._callbacks, Callbacks), \\\n \"Cannot register more callbacks after trainer was setup!\"\n if not self.is_chief and cb.chief_only:\n logger.warn(\"Callback {} is chief-only, skipped.\".format(str(cb)))\n return False\n else:\n self._callbacks.append(cb)\n return True", "docstring": "Register callbacks to the trainer.\nIt can only be called before :meth:`Trainer.train()`.\n\nArgs:\ncb (Callback or [Callback]): a callback or a list of callbacks\n\nReturns:\nsucceed or not", "source": "juraj-google-style"}
1070{"code": "async def subscriptions(self, request):\n if (not self._accepting):\n return web.Response(status=503)\n web_sock = web.WebSocketResponse()\n (await web_sock.prepare(request))\n async for msg in web_sock:\n if (msg.type == aiohttp.WSMsgType.TEXT):\n (await self._handle_message(web_sock, msg.data))\n elif (msg.type == aiohttp.WSMsgType.ERROR):\n LOGGER.warning('Web socket connection closed with exception %s', web_sock.exception())\n (await web_sock.close())\n (await self._handle_unsubscribe(web_sock))\n return web_sock", "docstring": "Handles requests for new subscription websockets.\n\nArgs:\nrequest (aiohttp.Request): the incoming request\n\nReturns:\naiohttp.web.WebSocketResponse: the websocket response, when the\nresulting websocket is closed", "source": "codesearchnet"}
1071{"code": "def create_d1_dn_subject(common_name_str):\n return cryptography.x509.Name([cryptography.x509.NameAttribute(cryptography.x509.oid.NameOID.COUNTRY_NAME, 'US'), cryptography.x509.NameAttribute(cryptography.x509.oid.NameOID.STATE_OR_PROVINCE_NAME, 'California'), cryptography.x509.NameAttribute(cryptography.x509.oid.NameOID.LOCALITY_NAME, 'San Francisco'), cryptography.x509.NameAttribute(cryptography.x509.oid.NameOID.ORGANIZATION_NAME, 'Root CA'), cryptography.x509.NameAttribute(cryptography.x509.oid.NameOID.COMMON_NAME, 'ca.ca.com')])", "docstring": "Create the DN Subject for certificate that will be used in a DataONE environment.\n\nThe DN is formatted into a DataONE subject, which is used in authentication,\nauthorization and event tracking.\n\nArgs:\ncommon_name_str: str\nDataONE uses simple DNs without physical location information, so only the\n``common_name_str`` (``CommonName``) needs to be specified.\n\nFor Member Node Client Side certificates or CSRs, ``common_name_str`` is the\n``node_id``, e.g., ``urn:node:ABCD`` for production, or\n``urn:node:mnTestABCD`` for the test environments.\n\nFor a local CA, something like ``localCA`` may be used.\n\nFor a locally trusted client side certificate, something like\n``localClient`` may be used.", "source": "codesearchnet"}
1072{"code": "def define_both_methods(class_name, class_dict, old_name, new_name):\n assert ((old_name not in class_dict) or (new_name not in class_dict)), 'Class \"{}\" cannot define both \"{}\" and \"{}\" methods.'.format(class_name, old_name, new_name)\n if (old_name in class_dict):\n class_dict[new_name] = class_dict[old_name]\n elif (new_name in class_dict):\n class_dict[old_name] = class_dict[new_name]", "docstring": "Function to help CamelCase to PEP8 style class methods migration.\n\nFor any class definition:\n1. Assert it does not define both old and new methods,\notherwise it does not work.\n2. If it defines the old method, create the same new method.\n3. If it defines the new method, create the same old method.\n\nArgs:\nclass_name: the class name.\nclass_dict: the class dictionary.\nold_name: old method's name.\nnew_name: new method's name.\n\nRaises:\nAssertionError: raised when the class defines both the old_name and\nnew_name.", "source": "codesearchnet"}
1073{"code": "def _GetNextLogCountPerToken(token):\n global _log_counter_per_token\n _log_counter_per_token[token] = 1 + _log_counter_per_token.get(token, -1)\n return _log_counter_per_token[token]", "docstring": "Wrapper for _log_counter_per_token.\n\nArgs:\ntoken: The token for which to look up the count.\n\nReturns:\nThe number of times this function has been called with\n*token* as an argument (starting at 0)", "source": "github-repos"}
1074{"code": "def requires_grad(self) -> bool:\n if self._rot_mats is not None:\n return self._rot_mats.requires_grad\n elif self._quats is not None:\n return self._quats.requires_grad\n else:\n raise ValueError('Both rotations are None')", "docstring": "Returns the requires_grad property of the underlying rotation\n\nReturns:\nThe requires_grad property of the underlying tensor", "source": "github-repos"}
1075{"code": "def copy2(src, dst, metadata=None, retry_params=None):\n common.validate_file_path(src)\n common.validate_file_path(dst)\n if (metadata is None):\n metadata = {}\n copy_meta = 'COPY'\n else:\n copy_meta = 'REPLACE'\n metadata.update({'x-goog-copy-source': src, 'x-goog-metadata-directive': copy_meta})\n api = storage_api._get_storage_api(retry_params=retry_params)\n (status, resp_headers, content) = api.put_object(api_utils._quote_filename(dst), headers=metadata)\n errors.check_status(status, [200], src, metadata, resp_headers, body=content)", "docstring": "Copy the file content from src to dst.\n\nArgs:\nsrc: /bucket/filename\ndst: /bucket/filename\nmetadata: a dict of metadata for this copy. If None, old metadata is copied.\nFor example, {'x-goog-meta-foo': 'bar'}.\nretry_params: An api_utils.RetryParams for this call to GCS. If None,\nthe default one is used.\n\nRaises:\nerrors.AuthorizationError: if authorization failed.\nerrors.NotFoundError: if an object that's expected to exist doesn't.", "source": "codesearchnet"}
1076{"code": "def __init__(self, dataframe, map_info):\n \n self.df = dataframe\n self.map_info = map_info", "docstring": "Reads genotypes from a pandas DataFrame.\n\nArgs:\ndataframe (pandas.DataFrame): The data.\nmap_info (pandas.DataFrame): The mapping information.\n\nNote\n====\nThe index of the dataframe should be the sample IDs. The index of\nthe map_info should be the variant name, and there should be\ncolumns named chrom and pos.", "source": "juraj-google-style"}
1077{"code": "def prepare_for_send(self, full_url=False):\n \n assert self.url\n assert self.method\n assert self.version\n\n url_info = self.url_info\n\n if 'Host' not in self.fields:\n self.fields['Host'] = url_info.hostname_with_port\n\n if not full_url:\n if url_info.query:\n self.resource_path = '{0}?{1}'.format(url_info.path, url_info.query)\n else:\n self.resource_path = url_info.path\n else:\n self.resource_path = url_info.url", "docstring": "Modify the request to be suitable for HTTP server.\n\nArgs:\nfull_url (bool): Use full URL as the URI. By default, only\nthe path of the URL is given to the server.", "source": "juraj-google-style"}
1078{"code": "def open_required(func):\n \n @functools.wraps(func)\n def wrapper(self, *args, **kwargs):\n \n if not self.opened():\n raise errors.JLinkException('J-Link DLL is not open.')\n elif not self.connected():\n raise errors.JLinkException('J-Link connection has been lost.')\n return func(self, *args, **kwargs)\n return wrapper", "docstring": "Decorator to specify that the J-Link DLL must be opened, and a\nJ-Link connection must be established.\n\nArgs:\nfunc (function): function being decorated\n\nReturns:\nThe wrapper function.", "source": "juraj-google-style"}
1079{"code": "def create_database_view(self, view: views.View, view_name: str) -> None:\n dataset = f'{self._view_dataset.project}.{self._view_dataset.dataset_id}'\n view_sql = f'CREATE OR REPLACE VIEW `{dataset}.{view_name}` AS\\n{self.to_sql(view)}'\n self._client.query(view_sql).result()", "docstring": "Creates a BigQuery view with the given name in the runner's view_dataset.\n\nArgs:\nview: the FHIR view that creates\nview_name: the view name passed to the CREATE OR REPLACE VIEW statement.\n\nRaises:\ngoogle.cloud.exceptions.GoogleAPICallError if the job failed.", "source": "github-repos"}
1080{"code": "def save(self, *, auto_commit=False):\n \n try:\n db.session.add(self.resource)\n if auto_commit:\n db.session.commit()\n except SQLAlchemyError as ex:\n self.log.exception('Failed updating resource: {}'.format(ex))\n db.session.rollback()", "docstring": "Save the resource to the database\n\nArgs:\nauto_commit (bool): Automatically commit the transaction. Default: `False`\n\nReturns:\n`None`", "source": "juraj-google-style"}
1081{"code": "def check_denotation(target_values, predicted_values):\n \n \n if len(target_values) != len(predicted_values):\n return False\n \n for target in target_values:\n if not any(target.match(pred) for pred in predicted_values):\n return False\n return True", "docstring": "Return True if the predicted denotation is correct.\n\nArgs:\ntarget_values (list[Value])\npredicted_values (list[Value])\nReturns:\nbool", "source": "juraj-google-style"}
1082{"code": "def get_list_index(lst, index_or_name):\n \n if isinstance(index_or_name, six.integer_types):\n return index_or_name\n\n return lst.index(index_or_name)", "docstring": "Return the index of an element in the list.\n\nArgs:\nlst (list): The list.\nindex_or_name (int or str): The value of the reference element, or directly its numeric index.\n\nReturns:\n(int) The index of the element in the list.", "source": "juraj-google-style"}
1083{"code": "def _text_io_wrapper(stream, mode, encoding, errors, newline):\n \n \n \n if \"t\" in mode and not hasattr(stream, 'encoding'):\n text_stream = TextIOWrapper(\n stream, encoding=encoding, errors=errors, newline=newline)\n yield text_stream\n text_stream.flush()\n\n \n else:\n yield stream", "docstring": "Wrap a binary stream to Text stream.\n\nArgs:\nstream (file-like object): binary stream.\nmode (str): Open mode.\nencoding (str): Stream encoding.\nerrors (str): Decoding error handling.\nnewline (str): Universal newlines", "source": "juraj-google-style"}
1084{"code": "async def inspect(self, name: str) -> Mapping:\n response = (await self.docker._query_json('images/{name}/json'.format(name=name)))\n return response", "docstring": "Return low-level information about an image\n\nArgs:\nname: name of the image", "source": "codesearchnet"}
1085{"code": "def name_from_base(base, max_length=63, short=False):\n timestamp = (sagemaker_short_timestamp() if short else sagemaker_timestamp())\n trimmed_base = base[:((max_length - len(timestamp)) - 1)]\n return '{}-{}'.format(trimmed_base, timestamp)", "docstring": "Append a timestamp to the provided string.\n\nThis function assures that the total length of the resulting string is not\nlonger than the specified max length, trimming the input parameter if necessary.\n\nArgs:\nbase (str): String used as prefix to generate the unique name.\nmax_length (int): Maximum length for the resulting string.\nshort (bool): Whether or not to use a truncated timestamp.\n\nReturns:\nstr: Input parameter with appended timestamp.", "source": "codesearchnet"}
1086{"code": "def setup_suite(self, config):\n pass", "docstring": "Function used to add test classes, has to be implemented by child class.\n\nArgs:\nconfig: config_parser.TestRunConfig, the config provided by google3 infra.\n\nRaises:\nError: when setup_suite is not implemented by child class.", "source": "github-repos"}
1087{"code": "def load_orthologs(fo: IO, metadata: dict):\n version = metadata['metadata']['version']\n with timy.Timer('Load Orthologs') as timer:\n arango_client = arangodb.get_client()\n belns_db = arangodb.get_belns_handle(arango_client)\n arangodb.batch_load_docs(belns_db, orthologs_iterator(fo, version), on_duplicate='update')\n log.info('Load orthologs', elapsed=timer.elapsed, source=metadata['metadata']['source'])\n remove_old_ortholog_edges = f\n remove_old_ortholog_nodes = f\n arangodb.aql_query(belns_db, remove_old_ortholog_edges)\n arangodb.aql_query(belns_db, remove_old_ortholog_nodes)\n metadata['_key'] = f\"Orthologs_{metadata['metadata']['source']}\"\n try:\n belns_db.collection(arangodb.belns_metadata_name).insert(metadata)\n except ArangoError as ae:\n belns_db.collection(arangodb.belns_metadata_name).replace(metadata)", "docstring": "Load orthologs into ArangoDB\n\nArgs:\nfo: file obj - orthologs file\nmetadata: dict containing the metadata for orthologs", "source": "codesearchnet"}
1088{"code": "def EWFGlobPathSpec(file_system, path_spec):\n if (not path_spec.HasParent()):\n raise errors.PathSpecError('Unsupported path specification without parent.')\n parent_path_spec = path_spec.parent\n parent_location = getattr(parent_path_spec, 'location', None)\n if (not parent_location):\n raise errors.PathSpecError('Unsupported parent path specification without location.')\n (parent_location, _, segment_extension) = parent_location.rpartition('.')\n segment_extension_start = segment_extension[0]\n segment_extension_length = len(segment_extension)\n if ((segment_extension_length not in [3, 4]) or (not segment_extension.endswith('01')) or ((segment_extension_length == 3) and (segment_extension_start not in ['E', 'e', 's'])) or ((segment_extension_length == 4) and (not segment_extension.startswith('Ex')))):\n raise errors.PathSpecError('Unsupported parent path specification invalid segment file extension: {0:s}'.format(segment_extension))\n segment_number = 1\n segment_files = []\n while True:\n segment_location = '{0:s}.{1:s}'.format(parent_location, segment_extension)\n kwargs = path_spec_factory.Factory.GetProperties(parent_path_spec)\n kwargs['location'] = segment_location\n if (parent_path_spec.parent is not None):\n kwargs['parent'] = parent_path_spec.parent\n segment_path_spec = path_spec_factory.Factory.NewPathSpec(parent_path_spec.type_indicator, **kwargs)\n if (not file_system.FileEntryExistsByPathSpec(segment_path_spec)):\n break\n segment_files.append(segment_path_spec)\n segment_number += 1\n if (segment_number <= 99):\n if (segment_extension_length == 3):\n segment_extension = '{0:s}{1:02d}'.format(segment_extension_start, segment_number)\n elif (segment_extension_length == 4):\n segment_extension = '{0:s}x{1:02d}'.format(segment_extension_start, segment_number)\n else:\n segment_index = (segment_number - 100)\n if (segment_extension_start in ['e', 's']):\n letter_offset = ord('a')\n else:\n letter_offset = ord('A')\n (segment_index, remainder) = divmod(segment_index, 26)\n third_letter = chr((letter_offset + remainder))\n (segment_index, remainder) = divmod(segment_index, 26)\n second_letter = chr((letter_offset + remainder))\n first_letter = chr((ord(segment_extension_start) + segment_index))\n if (first_letter in ['[', '{']):\n raise RuntimeError('Unsupported number of segment files.')\n if (segment_extension_length == 3):\n segment_extension = '{0:s}{1:s}{2:s}'.format(first_letter, second_letter, third_letter)\n elif (segment_extension_length == 4):\n segment_extension = '{0:s}x{1:s}{2:s}'.format(first_letter, second_letter, third_letter)\n return segment_files", "docstring": "Globs for path specifications according to the EWF naming schema.\n\nArgs:\nfile_system (FileSystem): file system.\npath_spec (PathSpec): path specification.\n\nReturns:\nlist[PathSpec]: path specifications that match the glob.\n\nRaises:\nPathSpecError: if the path specification is invalid.\nRuntimeError: if the maximum number of supported segment files is\nreached.", "source": "codesearchnet"}
1089{"code": "def unwrap(self, value):\n return self._extended._local_results(value)", "docstring": "Returns the list of all local per-replica values contained in `value`.\n\nDEPRECATED: Please use `experimental_local_results` instead.\n\nNote: This only returns values on the workers initiated by this client.\nWhen using a `tf.distribute.Strategy` like\n`tf.distribute.experimental.MultiWorkerMirroredStrategy`, each worker\nwill be its own client, and this function will only return values\ncomputed on that worker.\n\nArgs:\nvalue: A value returned by `experimental_run()`,\n`extended.call_for_each_replica()`, or a variable created in `scope`.\n\nReturns:\nA tuple of values contained in `value`. If `value` represents a single\nvalue, this returns `(value,).`", "source": "github-repos"}
1090{"code": "def _ShardTestEmbeddings(self, weights, biases, num_shards):\n with ops.Graph().as_default() as g:\n sharded_weights = variable_scope.get_variable('w', partitioner=partitioned_variables.fixed_size_partitioner(num_shards), initializer=constant_op.constant(weights))\n sharded_biases = variable_scope.get_variable('b', partitioner=partitioned_variables.fixed_size_partitioner(num_shards), initializer=constant_op.constant(biases))\n with self.session(graph=g) as sess:\n self.evaluate(variables.global_variables_initializer())\n return self.evaluate([list(sharded_weights), list(sharded_biases)])", "docstring": "Shards the weights and biases returned by _GenerateTestData.\n\nArgs:\nweights: The weights returned by _GenerateTestData.\nbiases: The biases returned by _GenerateTestData.\nnum_shards: The number of shards to create.\n\nReturns:\nsharded_weights: A list of size `num_shards` containing all the weights.\nsharded_biases: A list of size `num_shards` containing all the biases.", "source": "github-repos"}
1091{"code": "def read_model_from_bytearray(model_bytearray):\n model = convert_bytearray_to_object(model_bytearray)\n if sys.byteorder == 'big':\n byte_swap_tflite_model_obj(model, 'little', 'big')\n for buffer in model.buffers:\n if buffer.offset:\n buffer.data = model_bytearray[buffer.offset:buffer.offset + buffer.size]\n buffer.offset = 0\n buffer.size = 0\n for subgraph in model.subgraphs:\n for op in subgraph.operators:\n if op.largeCustomOptionsOffset:\n op.customOptions = model_bytearray[op.largeCustomOptionsOffset:op.largeCustomOptionsOffset + op.largeCustomOptionsSize]\n op.largeCustomOptionsOffset = 0\n op.largeCustomOptionsSize = 0\n return model", "docstring": "Reads a tflite model as a python object.\n\nArgs:\nmodel_bytearray: TFLite model in bytearray format.\n\nReturns:\nA python object corresponding to the input tflite file.", "source": "github-repos"}
1092{"code": "def ParseFloat(text):\n \n try:\n \n return float(text)\n except ValueError:\n \n if _FLOAT_INFINITY.match(text):\n if text[0] == '-':\n return float('-inf')\n else:\n return float('inf')\n elif _FLOAT_NAN.match(text):\n return float('nan')\n else:\n \n try:\n return float(text.rstrip('f'))\n except ValueError:\n raise ValueError('Couldn\\'t parse float: %s' % text)", "docstring": "Parse a floating point number.\n\nArgs:\ntext: Text to parse.\n\nReturns:\nThe number parsed.\n\nRaises:\nValueError: If a floating point number couldn't be parsed.", "source": "juraj-google-style"}
1093{"code": "def get_branch(profile, name):\n \n ref = \"heads/\" + name\n data = refs.get_ref(profile, ref)\n return data", "docstring": "Fetch a branch.\n\nArgs:\n\nprofile\nA profile generated from ``simplygithub.authentication.profile``.\nSuch profiles tell this module (i) the ``repo`` to connect to,\nand (ii) the ``token`` to connect with.\n\nname\nThe name of the branch to fetch.\n\nReturns:\nA dict with data baout the branch.", "source": "juraj-google-style"}
1094{"code": "def __init__(self, file_entry):\n \n super(LVMVolume, self).__init__(file_entry.name)\n self._file_entry = file_entry", "docstring": "Initializes a LVM volume.\n\nArgs:\nfile_entry (LVMFileEntry): a LVM file entry.", "source": "juraj-google-style"}
1095{"code": "def SmartUnicode(string):\n \n if isinstance(string, Text):\n return string\n\n if isinstance(string, bytes):\n return string.decode(\"utf-8\", \"ignore\")\n\n \n \n if compatibility.PY2:\n return str(string).__native__()\n else:\n return str(string)", "docstring": "Returns a unicode object.\n\nThis function will always return a unicode object. It should be used to\nguarantee that something is always a unicode object.\n\nArgs:\nstring: The string to convert.\n\nReturns:\na unicode object.", "source": "juraj-google-style"}
1096{"code": "def find_mapreduce_yaml(status_file=__file__):\n \n checked = set()\n yaml = _find_mapreduce_yaml(os.path.dirname(status_file), checked)\n if not yaml:\n yaml = _find_mapreduce_yaml(os.getcwd(), checked)\n return yaml", "docstring": "Traverse directory trees to find mapreduce.yaml file.\n\nBegins with the location of status.py and then moves on to check the working\ndirectory.\n\nArgs:\nstatus_file: location of status.py, overridable for testing purposes.\n\nReturns:\nthe path of mapreduce.yaml file or None if not found.", "source": "juraj-google-style"}
1097{"code": "def __eq__(self, other):\n \n if type(self) is type(other) and \\\n self._name == other._name and \\\n self._params == other._params:\n return True\n return False", "docstring": "Two measurement options are the same if they are of the same type\nand have the same name and params.\n\nArgs:\nother (MeasOpts): Other Discriminator/Kernel.\n\nReturns:\nbool: are self and other equal.", "source": "juraj-google-style"}
1098{"code": "def separated(self):\n separated_lls = collections.defaultdict(LabelList)\n for label in self.labels:\n separated_lls[label.value].add(label)\n for ll in separated_lls.values():\n ll.idx = self.idx\n return separated_lls", "docstring": "Create a separate Label-List for every distinct label-value.\n\nReturns:\ndict: A dictionary with distinct label-values as keys.\nEvery value is a LabelList containing only labels with the same value.\n\nExample:\n>>> ll = LabelList(idx='some', labels=[\n>>> Label('a', start=0, end=4),\n>>> Label('b', start=3.95, end=6.0),\n>>> Label('a', start=7.0, end=10.2),\n>>> Label('b', start=10.3, end=14.0)\n>>> ])\n>>> s = ll.separate()\n>>> s['a'].labels\n[Label('a', start=0, end=4), Label('a', start=7.0, end=10.2)]\n>>> s['b'].labels\n[Label('b', start=3.95, end=6.0), Label('b', start=10.3, end=14.0)]", "source": "codesearchnet"}
1099{"code": "def _build_predicate_for_coding_in_value_set(expanded_value_set: value_set_pb2.ValueSet, coding_column: Optional[_sql_data_types.Identifier]=None) -> _sql_data_types.StandardSqlExpression:\n codes_per_system = {}\n for concept in expanded_value_set.expansion.contains:\n codes_per_system.setdefault(concept.system.value, []).append(concept.code.value)\n codes_per_system = list(codes_per_system.items())\n codes_per_system.sort(key=operator.itemgetter(0))\n for _, codes in codes_per_system:\n codes.sort()\n if coding_column is None:\n code_col = _sql_data_types.Identifier('code', _sql_data_types.String)\n system_col = _sql_data_types.Identifier('system', _sql_data_types.String)\n else:\n code_col = coding_column.dot('code', _sql_data_types.String)\n system_col = coding_column.dot('system', _sql_data_types.String)\n code_system_predicates = []\n for system, codes in codes_per_system:\n system = _sql_data_types.RawExpression('\"%s\"' % system, _sql_data_types.String)\n codes = [_sql_data_types.RawExpression('\"%s\"' % code, _sql_data_types.String) for code in codes]\n code_system_predicates.append(system_col.eq_(system).and_(code_col.in_(codes)))\n return functools.reduce(lambda acc, pred: acc.or_(pred), code_system_predicates)", "docstring": "Builds a predicate asserting the coding column is bound to the value_set.\n\nEnsures that the codings contained in `coding_column` are codings found in\n`expanded_value_set`.\nProduces SQL like:\n(`coding_column`.system = system1 AND `coding_column`.code IN (\ncode1, code2)) OR\n(`coding_column`.system = system2 AND `coding_column`.code IN (\ncode3, code4))\n\nArgs:\nexpanded_value_set: The expanded value set containing the coding values to\nassert membership against.\ncoding_column: The column containing the coding values. If given, columns\n`coding_column`.system and `coding_column`.code will be referenced in\nthe predicate. If not given, columns 'system' and 'code' will be\nreferenced.\n\nReturns:\nThe SQL for the value set binding predicate.", "source": "github-repos"}
1100{"code": "def _build_dict(my_dict, keys, values):\n temp = my_dict\n for (depth, key) in enumerate(keys):\n if (depth < (len(keys) - 1)):\n if (key not in temp):\n temp[key] = dict()\n temp = temp[key]\n elif (key not in temp):\n temp[key] = values\n else:\n temp[key] = {**temp[key], **values}\n return my_dict", "docstring": "Build a dictionary from a set of redis hashes.\n\nkeys = ['a', 'b', 'c']\nvalues = {'value': 'foo'}\nmy_dict = {'a': {'b': {'c': {'value': 'foo'}}}}\n\nArgs:\nmy_dict (dict): Dictionary to add to\nkeys (list[str]): List of keys used to define hierarchy in my_dict\nvalues (dict): Values to add at to the dictionary at the key\nspecified by keys\n\nReturns:\ndict, new dictionary with values added at keys", "source": "codesearchnet"}
1101{"code": "def _GetPropertyValue(self, parser_mediator, properties, property_name):\n property_value = properties.get(property_name, None)\n if isinstance(property_value, py2to3.BYTES_TYPE):\n try:\n property_value = property_value.decode('utf-8')\n except UnicodeDecodeError:\n parser_mediator.ProduceExtractionWarning('unable to decode property: {0:s}'.format(property_name))\n return property_value", "docstring": "Retrieves a property value.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nproperties (dict[str, object]): properties.\nproperty_name (str): name of the property.\n\nReturns:\nstr: property value.", "source": "codesearchnet"}
1102{"code": "def run_inference(examples, serving_bundle):\n \n batch_size = 64\n if serving_bundle.estimator and serving_bundle.feature_spec:\n \n preds = serving_bundle.estimator.predict(\n lambda: tf.data.Dataset.from_tensor_slices(\n tf.parse_example([ex.SerializeToString() for ex in examples],\n serving_bundle.feature_spec)).batch(batch_size))\n\n if serving_bundle.use_predict:\n preds_key = serving_bundle.predict_output_tensor\n elif serving_bundle.model_type == 'regression':\n preds_key = 'predictions'\n else:\n preds_key = 'probabilities'\n\n values = []\n for pred in preds:\n values.append(pred[preds_key])\n return common_utils.convert_prediction_values(values, serving_bundle)\n elif serving_bundle.custom_predict_fn:\n \n \n values = serving_bundle.custom_predict_fn(examples)\n return common_utils.convert_prediction_values(values, serving_bundle)\n else:\n return platform_utils.call_servo(examples, serving_bundle)", "docstring": "Run inference on examples given model information\n\nArgs:\nexamples: A list of examples that matches the model spec.\nserving_bundle: A `ServingBundle` object that contains the information to\nmake the inference request.\n\nReturns:\nA ClassificationResponse or RegressionResponse proto.", "source": "juraj-google-style"}
1103{"code": "def reciprocal_no_nan(x, name=None):\n with ops.name_scope(name, 'reciprocal_no_nan', [x]) as scope:\n x = ops.convert_to_tensor(x, name='x')\n one = constant_op.constant(1, dtype=x.dtype.base_dtype, name='one')\n return gen_math_ops.div_no_nan(one, x, name=scope)", "docstring": "Performs a safe reciprocal operation, element wise.\n\nIf a particular element is zero, the reciprocal for that element is\nalso set to zero.\n\nFor example:\n```python\nx = tf.constant([2.0, 0.5, 0, 1], dtype=tf.float32)\ntf.math.reciprocal_no_nan(x) # [ 0.5, 2, 0.0, 1.0 ]\n```\n\nArgs:\nx: A `Tensor` of type `float16`, `float32`, `float64` `complex64` or\n`complex128`.\nname: A name for the operation (optional).\n\nReturns:\nA `Tensor` of same shape and type as `x`.\n\nRaises:\nTypeError: x must be of a valid dtype.", "source": "github-repos"}
1104{"code": "def _minimize_peak_memory_list(graph):\n schedule = []\n bytes_freed = {}\n users_of = collections.defaultdict(set)\n in_degree = collections.defaultdict(int)\n operation_id = {}\n priority_queue = []\n for (i, operation_name) in enumerate(graph.get_all_operation_names()):\n operation_id[operation_name] = i\n for input_name in graph.get_operation_input_names(operation_name):\n if (operation_name in users_of[input_name]):\n continue\n users_of[input_name].add(operation_name)\n in_degree[operation_name] += 1\n for operation_name in graph.get_all_operation_names():\n bytes_freed[operation_name] = 0\n for input_name in graph.get_operation_input_names(operation_name):\n if ((len(users_of[input_name]) == 1) and (not graph.is_tensor_final(input_name))):\n bytes_freed[operation_name] += graph.get_tensor_size(input_name)\n for output_name in graph.get_operation_output_names(operation_name):\n if (users_of[output_name] or graph.is_tensor_final(output_name)):\n bytes_freed[operation_name] -= graph.get_tensor_size(output_name)\n for operation_name in graph.get_all_operation_names():\n if (in_degree[operation_name] == 0):\n heapq.heappush(priority_queue, ((- bytes_freed[operation_name]), operation_name))\n while priority_queue:\n (neg_bytes_freed, operation_name) = heapq.heappop(priority_queue)\n if (bytes_freed[operation_name] != (- neg_bytes_freed)):\n continue\n schedule.append(operation_id[operation_name])\n bytes_freed[operation_name] = None\n for output_name in graph.get_operation_output_names(operation_name):\n for other_operation_name in users_of[output_name]:\n in_degree[other_operation_name] -= 1\n if (in_degree[other_operation_name] == 0):\n heapq.heappush(priority_queue, ((- bytes_freed[other_operation_name]), other_operation_name))\n for input_name in graph.get_operation_input_names(operation_name):\n if (operation_name not in users_of[input_name]):\n continue\n users_of[input_name].remove(operation_name)\n if ((len(users_of[input_name]) != 1) or graph.is_tensor_final(output_name)):\n continue\n (other_operation_name,) = users_of[input_name]\n bytes_freed[other_operation_name] += graph.get_tensor_size(input_name)\n if (in_degree[other_operation_name] > 0):\n continue\n heapq.heappush(priority_queue, ((- bytes_freed[other_operation_name]), other_operation_name))\n return schedule", "docstring": "Computes schedule according to the greedy list heuristic.\n\nGreedy list heuristic: schedule the operation which results in the most bytes\nof memory being (immediately) freed.\nTODO(joshuawang): Experiment with tiebreaking by preferring more successors.\n\nArgs:\ngraph: an mtf.auto_mtf.graph_interface.GraphInterface.\n\nReturns:\nan iterable of integers representing the schedule.", "source": "codesearchnet"}
1105{"code": "def GetPluginObjects(cls, plugin_names):\n \n plugin_objects = {}\n for plugin_name, plugin_class in iter(cls._plugin_classes.items()):\n if plugin_name not in plugin_names:\n continue\n\n plugin_objects[plugin_name] = plugin_class()\n\n return plugin_objects", "docstring": "Retrieves the plugin objects.\n\nArgs:\nplugin_names (list[str]): names of plugins that should be retrieved.\n\nReturns:\ndict[str, AnalysisPlugin]: analysis plugins per name.", "source": "juraj-google-style"}
1106{"code": "def _create_key_value_cache_tensors(self, shape: Tuple[int, ...], device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:\n is_cpu_device = device == torch.device('cpu')\n key_cache = torch.zeros(shape, dtype=self._dtype, device=device, pin_memory=is_cpu_device)\n value_cache = torch.zeros(shape, dtype=self._dtype, device=device, pin_memory=is_cpu_device)\n torch._dynamo.mark_static_address(key_cache)\n torch._dynamo.mark_static_address(value_cache)\n return (key_cache, value_cache)", "docstring": "Creates K/V cache tensors on a device. Pins memory for CPU tensors. Marks them as static\naddresses for non-CPU tensors.\n\nArgs:\nshape (`Tuple[int, ...]`): Shape.\ndevice (`torch.device`): Device.\n\nReturns:\nKey and value cache tensors as a tuple.", "source": "github-repos"}
1107{"code": "def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):\n vision_data = {}\n if image_sizes is not None:\n images_kwargs = Idefics3ProcessorKwargs._defaults.get('images_kwargs', {})\n images_kwargs.update(kwargs)\n num_image_patches = [self.image_processor.get_number_of_image_patches(*image_size, images_kwargs) for image_size in image_sizes]\n base_image_length = self.image_seq_len + 3\n col_length = self.image_seq_len + 2\n num_image_tokens = []\n for num_patches in num_image_patches:\n num_cols = num_rows = int(math.sqrt(num_patches - 1))\n row_length = col_length * num_cols + 1\n num_image_tokens.append(base_image_length + row_length * num_rows)\n vision_data.update({'num_image_tokens': num_image_tokens, 'num_image_patches': num_image_patches})\n return MultiModalData(**vision_data)", "docstring": "Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.\n\nArgs:\nimage_sizes (`List[List[int]]`, *optional*):\nThe input sizes formatted as (height, width) per each image.\n\nReturns:\n`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided\ninput modalities, along with other useful data.", "source": "github-repos"}
1108{"code": "def wbmax(self, value=None):\n \n if value is not None:\n try:\n value = float(value)\n except ValueError:\n raise ValueError('value {} need to be of type float '\n 'for field `wbmax`'.format(value))\n\n self._wbmax = value", "docstring": "Corresponds to IDD Field `wbmax`\nExtreme maximum wet-bulb temperature\n\nArgs:\nvalue (float): value for IDD Field `wbmax`\nUnit: C\nif `value` is None it will not be checked against the\nspecification and is assumed to be a missing value\n\nRaises:\nValueError: if `value` is not a valid value", "source": "juraj-google-style"}
1109{"code": "def Print(self, output_writer):\n \n if self._names:\n output_writer.Write('\\tnames: {0:s}\\n'.format(\n ', '.join(self._names)))", "docstring": "Prints a human readable version of the filter.\n\nArgs:\noutput_writer (CLIOutputWriter): output writer.", "source": "juraj-google-style"}
1110{"code": "def _set_class_parser(self, init_parser, methods_to_parse, cls):\n \n top_level_parents = [init_parser] if init_parser else []\n description = self._description or cls.__doc__\n top_level_parser = argparse.ArgumentParser(description=description,\n parents=top_level_parents,\n add_help=False,\n conflict_handler=\"resolve\")\n top_level_parser.add_argument(\"-h\", \"--help\", action=FullHelpAction,\n help=\"Display this help message\")\n parser_to_method = self._add_sub_parsers(top_level_parser,\n methods_to_parse,\n cls.__name__)\n \n \n if init_parser:\n parser_to_method[\"__init__\"] = \"__init__\"\n top_level_parser.call = self._get_parser_call_method(parser_to_method)\n cls.parser = top_level_parser", "docstring": "Creates the complete argument parser for the decorated class.\n\nArgs:\ninit_parser: argument parser for the __init__ method or None\nmethods_to_parse: dict of method name pointing to their associated\nargument parser\ncls: the class we are decorating\n\nReturns:\nThe decorated class with an added attribute 'parser'", "source": "juraj-google-style"}
1111{"code": "def parse_branch_ref(filename):\n data = open(filename).read().strip()\n items = data.split(' ')\n if len(items) == 1:\n return None\n elif len(items) == 2 and items[0] == 'ref:':\n return items[1].strip()\n else:\n raise RuntimeError('Git directory has unparseable HEAD')", "docstring": "Given a filename of a .git/HEAD file return ref path.\n\nIn particular, if git is in detached head state, this will\nreturn None. If git is in attached head, it will return\nthe branch reference. E.g. if on 'master', the HEAD will\ncontain 'ref: refs/heads/master' so 'refs/heads/master'\nwill be returned.\n\nExample: parse_branch_ref(\".git/HEAD\")\nArgs:\nfilename: file to treat as a git HEAD file\nReturns:\nNone if detached head, otherwise ref subpath\nRaises:\nRuntimeError: if the HEAD file is unparseable.", "source": "github-repos"}
1112{"code": "def get_categorical_feature_names(example):\n \n features = get_example_features(example)\n return sorted([\n feature_name for feature_name in features\n if features[feature_name].WhichOneof('kind') == 'bytes_list'\n ])", "docstring": "Returns a list of feature names for byte type features.\n\nArgs:\nexample: An example.\n\nReturns:\nA list of categorical feature names (e.g. ['education', 'marital_status'] )", "source": "juraj-google-style"}
1113{"code": "def process_action(resource, action, action_issuer='unknown'):\n \n from cinq_collector_aws import AWSRegionCollector\n\n func_action = action_mapper[resource.resource_type][action]\n extra_info = {}\n action_status = ActionStatus.UNKNOWN\n\n if func_action:\n if action_mapper[resource.resource_type]['service_name'] == 'lambda':\n client = get_aws_session(\n AWSAccount.get(dbconfig.get('rds_collector_account', AWSRegionCollector.ns, ''))\n ).client(\n 'lambda',\n dbconfig.get('rds_collector_region', AWSRegionCollector.ns, '')\n )\n else:\n client = get_aws_session(AWSAccount(resource.account)).client(\n action_mapper[resource.resource_type]['service_name'],\n region_name=resource.location\n )\n try:\n logger.info(f'Trying to {action} resource {resource.id} for account {resource.account.account_name} / region {resource.location}')\n action_status, extra_info = func_action(client, resource)\n Enforcement.create(resource.account.account_id, resource.id, action, datetime.now(), extra_info)\n except Exception as ex:\n action_status = ActionStatus.FAILED\n logger.exception('Failed to apply action {} to {}: {}'.format(action, resource.id, ex))\n finally:\n auditlog(\n event='{}.{}.{}.{}'.format(action_issuer, resource.resource_type, action, action_status),\n actor=action_issuer,\n data={\n 'resource_id': resource.id,\n 'account_name': resource.account.account_name,\n 'location': resource.location,\n 'info': extra_info\n }\n )\n return action_status\n else:\n logger.error('Failed to apply action {} to {}: Not supported'.format(action, resource.id))\n return ActionStatus.FAILED", "docstring": "Process an audit action for a resource, if possible\n\nArgs:\nresource (:obj:`Resource`): A resource object to perform the action on\naction (`str`): Type of action to perform (`kill` or `stop`)\naction_issuer (`str`): The issuer of the action\nReturns:\n`ActionStatus`", "source": "juraj-google-style"}
1114{"code": "def as_dict(self, verbosity: int=0) -> Dict:\n d = {'@module': self.__class__.__module__, '@class': self.__class__.__name__, 'matrix': self._matrix.tolist()}\n ((a, b, c), (alpha, beta, gamma)) = self.lengths_and_angles\n if (verbosity > 0):\n d.update({'a': a, 'b': b, 'c': c, 'alpha': alpha, 'beta': beta, 'gamma': gamma, 'volume': self.volume})\n return d", "docstring": "Json-serialization dict representation of the Lattice.\n\nArgs:\nverbosity (int): Verbosity level. Default of 0 only includes the\nmatrix representation. Set to 1 for more details.", "source": "codesearchnet"}
1115{"code": "def from_millis(cls, timeout_ms):\n if hasattr(timeout_ms, 'has_expired'):\n return timeout_ms\n if (timeout_ms is None):\n return cls(None)\n return cls((timeout_ms / 1000.0))", "docstring": "Create a new PolledTimeout if needed.\n\nIf timeout_ms is already a PolledTimeout, just return it, otherwise create a\nnew PolledTimeout with the given timeout in milliseconds.\n\nArgs:\ntimeout_ms: PolledTimeout object, or number of milliseconds to use for\ncreating a new one.\n\nReturns:\nA PolledTimeout object that will expire in timeout_ms milliseconds, which\nmay be timeout_ms itself, or a newly allocated PolledTimeout.", "source": "codesearchnet"}
1116{"code": "def _request(self, domain, type_name, search_command, db_method, body=None):\n headers = {'Content-Type': 'application/json', 'DB-Method': db_method}\n search_command = self._clean_datastore_path(search_command)\n url = '/v2/exchange/db/{}/{}/{}'.format(domain, type_name, search_command)\n r = self.tcex.session.post(url, data=body, headers=headers, params=self._params)\n data = []\n status = 'Failed'\n if ((not r.ok) or ('application/json' not in r.headers.get('content-type', ''))):\n self.tcex.handle_error(350, [r.status_code, r.text])\n data = r.json()\n status = 'Success'\n return {'data': data, 'response': r, 'status': status}", "docstring": "Make the API request for a Data Store CRUD operation\n\nArgs:\ndomain (string): One of 'local', 'organization', or 'system'.\ntype_name (string): This is a free form index type name. The ThreatConnect API will use\nthis resource verbatim.\nsearch_command (string): Search command to pass to ES.\ndb_method (string): The DB method 'DELETE', 'GET', 'POST', or 'PUT'\nbody (dict): JSON body", "source": "codesearchnet"}
1117{"code": "def update_power_state(self, id_or_uri, power_state):\n uri = (self._client.build_uri(id_or_uri) + '/powerState')\n return self._client.update(power_state, uri)", "docstring": "Sets the power state of the specified power delivery device. The device must be an HP Intelligent Outlet.\n\nArgs:\nid_or_uri:\nCan be either the power device id or the uri\npower_state:\n{\"powerState\":\"On|Off\"}\n\nReturns:\nstr: The power state", "source": "codesearchnet"}
1118{"code": "def has_unchecked_field(self, locator, **kwargs):\n \n\n kwargs[\"checked\"] = False\n return self.has_selector(\"field\", locator, **kwargs)", "docstring": "Checks if the page or current node has a radio button or checkbox with the given label,\nvalue, or id, that is currently unchecked.\n\nArgs:\nlocator (str): The label, name, or id of an unchecked field.\n**kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.\n\nReturns:\nbool: Whether it exists.", "source": "juraj-google-style"}
1119{"code": "def get_student_by_email(self, email, students=None):\n if (students is None):\n students = self.get_students()\n email = email.lower()\n for student in students:\n if (student['accountEmail'].lower() == email):\n return (student['studentId'], student)\n return (None, None)", "docstring": "Get a student based on an email address.\n\nCalls ``self.get_students()`` to get list of all students,\nif not passed as the ``students`` parameter.\n\nArgs:\nemail (str): student email\nstudents (list): dictionary of students to search, default: None\nWhen ``students`` is unspecified, all students in gradebook\nare retrieved.\n\nRaises:\nrequests.RequestException: Exception connection error\nValueError: Unable to decode response content\n\nReturns:\ntuple: tuple of student id and student dictionary.", "source": "codesearchnet"}
1120{"code": "def _expand_terms(self, terms):\n \n ret = {\n 'keywords': list(),\n 'doc': list(),\n 'from': None,\n 'to': None}\n\n if not isinstance(terms, dict):\n stp = SearchTermParser()\n terms = stp.parse(terms, term_join=self.backend._and_join)\n\n if 'about' in terms:\n ret['doc'].append(terms['about'])\n\n if 'with' in terms:\n ret['doc'].append(terms['with'])\n\n if 'in' in terms:\n place_vids = self._expand_place_ids(terms['in'])\n ret['keywords'].append(place_vids)\n\n if 'by' in terms:\n ret['keywords'].append(terms['by'])\n ret['from'] = terms.get('from', None)\n ret['to'] = terms.get('to', None)\n return ret", "docstring": "Expands partition terms to the appropriate fields.\n\nArgs:\nterms (dict or str):\n\nReturns:\ndict: keys are field names, values are query strings", "source": "juraj-google-style"}
1121{"code": "def _get_args_to_parse(args, sys_argv):\n \n arguments = args if args is not None else sys_argv[1:]\n _LOG.debug(\"Parsing arguments: %s\", arguments)\n return arguments", "docstring": "Return the given arguments if it is not None else sys.argv if it contains\nsomething, an empty list otherwise.\n\nArgs:\nargs: argument to be parsed\nsys_argv: arguments of the command line i.e. sys.argv", "source": "juraj-google-style"}
1122{"code": "def get_args(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', required=True, help='Input file to process.')\n parser.add_argument('--output', required=True, help='Output file to write results to.')\n return parser.parse_known_args(argv)", "docstring": "Determines user specified arguments from the given list of arguments.\n\nArgs:\nargv: all arguments.\n\nReturns:\nA pair of argument lists containing known and remaining arguments.", "source": "github-repos"}
1123{"code": "def WriteSessionStart(self):\n self._RaiseIfNotWritable()\n if (self._storage_type != definitions.STORAGE_TYPE_SESSION):\n raise IOError('Unsupported storage type.')\n session_start = self._session.CreateSessionStart()\n self._storage_file.WriteSessionStart(session_start)", "docstring": "Writes session start information.\n\nRaises:\nIOError: if the storage type is not supported or\nwhen the storage writer is closed.\nOSError: if the storage type is not supported or\nwhen the storage writer is closed.", "source": "codesearchnet"}
1124{"code": "def convert_tiktoken_to_fast(encoding: Any, output_dir: str):\n output_dir = Path(output_dir)\n output_dir.mkdir(exist_ok=True)\n save_file = output_dir / 'tiktoken' / TIKTOKEN_VOCAB_FILE\n tokenizer_file = output_dir / TOKENIZER_FILE\n save_file_absolute = str(save_file.absolute())\n output_file_absolute = str(tokenizer_file.absolute())\n try:\n from tiktoken import get_encoding\n from tiktoken.load import dump_tiktoken_bpe\n if isinstance(encoding, str):\n encoding = get_encoding(encoding)\n dump_tiktoken_bpe(encoding._mergeable_ranks, save_file_absolute)\n except ImportError:\n raise ValueError('`tiktoken` is required to save a `tiktoken` file. Install it with `pip install tiktoken`.')\n tokenizer = TikTokenConverter(vocab_file=save_file_absolute, pattern=encoding._pat_str, additional_special_tokens=encoding._special_tokens).converted()\n tokenizer.save(output_file_absolute)", "docstring": "Converts given `tiktoken` encoding to `PretrainedTokenizerFast` and saves the configuration of converted tokenizer\non disk.\n\nArgs:\nencoding (`str` or `tiktoken.Encoding`):\nTokenizer from `tiktoken` library. If `encoding` is `str`, the tokenizer will be loaded with\n`tiktoken.get_encoding(encoding)`.\noutput_dir (`str`):\nSave path for converted tokenizer configuration file.", "source": "github-repos"}
1125{"code": "def _contains_tensor(sample: repr_dataset.RepresentativeSample) -> bool:\n return any(map(lambda value: isinstance(value, core.Tensor), sample.values()))", "docstring": "Determines whether `sample` contains any tf.Tensors.\n\nArgs:\nsample: A `RepresentativeSample`.\n\nReturns:\nTrue iff `sample` contains at least tf.Tensors.", "source": "github-repos"}
1126{"code": "def get_room(self, id):\n if (id not in self._rooms):\n self._rooms[id] = Room(self, id)\n return self._rooms[id]", "docstring": "Get room.\n\nReturns:\n:class:`Room`. Room", "source": "codesearchnet"}
1127{"code": "class WarmUp(schedules.LearningRateSchedule):\n\n def __init__(self, initial_learning_rate: float, decay_schedule_fn: Callable, warmup_steps: int, power: float=1.0, name: Optional[str]=None):\n super().__init__()\n self.initial_learning_rate = initial_learning_rate\n self.warmup_steps = warmup_steps\n self.power = power\n self.decay_schedule_fn = decay_schedule_fn\n self.name = name\n\n def __call__(self, step):\n with tf.name_scope(self.name or 'WarmUp') as name:\n global_step_float = tf.cast(step, tf.float32)\n warmup_steps_float = tf.cast(self.warmup_steps, tf.float32)\n warmup_percent_done = global_step_float / warmup_steps_float\n warmup_learning_rate = self.initial_learning_rate * tf.math.pow(warmup_percent_done, self.power)\n return tf.cond(global_step_float < warmup_steps_float, lambda: warmup_learning_rate, lambda: self.decay_schedule_fn(step - self.warmup_steps), name=name)\n\n def get_config(self):\n return {'initial_learning_rate': self.initial_learning_rate, 'decay_schedule_fn': self.decay_schedule_fn, 'warmup_steps': self.warmup_steps, 'power': self.power, 'name': self.name}", "docstring": "Applies a warmup schedule on a given learning rate decay schedule.\n\nArgs:\ninitial_learning_rate (`float`):\nThe initial learning rate for the schedule after the warmup (so this will be the learning rate at the end\nof the warmup).\ndecay_schedule_fn (`Callable`):\nThe schedule function to apply after the warmup for the rest of training.\nwarmup_steps (`int`):\nThe number of steps for the warmup part of training.\npower (`float`, *optional*, defaults to 1.0):\nThe power to use for the polynomial warmup (defaults is a linear warmup).\nname (`str`, *optional*):\nOptional name prefix for the returned tensors during the schedule.", "source": "github-repos"}
1128{"code": "def set_status_code(self, status_code_line):\n self._empty = False\n self.status_code = self._remove_structure_prefix(_InstrumentationStructurePrefixes.STATUS_CODE, status_code_line)\n if self.status_code == _InstrumentationStatusCodes.START:\n self.begin_time = utils.get_current_epoch_time()", "docstring": "Sets the status code for the instrumentation test method, used in\ndetermining the test result.\n\nArgs:\nstatus_code_line: string, the raw instrumentation output line that\ncontains the status code of the instrumentation block.", "source": "github-repos"}
1129{"code": "def get_pair(self, term1, term2):\n key = self.key(term1, term2)\n return self.pairs.get(key, None)", "docstring": "Get the value for a pair of terms.\n\nArgs:\nterm1 (str)\nterm2 (str)\n\nReturns:\nThe stored value.", "source": "codesearchnet"}
1130{"code": "def __init__(self, olecf_item):\n \n super(OLECFPropertySetStream, self).__init__()\n self._properties = {}\n self.date_time_properties = {}\n\n self._ReadPropertySet(olecf_item.set)", "docstring": "Initialize an OLECF property set stream.\n\nArgs:\nolecf_item (pyolecf.property_set_stream): OLECF item.", "source": "juraj-google-style"}
1131{"code": "def true_num_genes(model, custom_spont_id=None):\n true_num = 0\n for gene in model.genes:\n if (not is_spontaneous(gene, custom_id=custom_spont_id)):\n true_num += 1\n return true_num", "docstring": "Return the number of genes in a model ignoring spontaneously labeled genes.\n\nArgs:\nmodel (Model):\ncustom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``\n\nReturns:\nint: Number of genes excluding spontaneous genes", "source": "codesearchnet"}
1132{"code": "def _prepare_4d_causal_attention_mask_with_cache_position(attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, cache_position: torch.Tensor, batch_size: int, **kwargs):\n if attention_mask is not None and attention_mask.dim() == 4:\n causal_mask = attention_mask\n else:\n min_dtype = torch.finfo(dtype).min\n causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device)\n if sequence_length != 1:\n causal_mask = torch.triu(causal_mask, diagonal=1)\n causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)\n causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)\n if attention_mask is not None:\n causal_mask = causal_mask.clone()\n mask_length = attention_mask.shape[-1]\n padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)\n padding_mask = padding_mask == 0\n causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(padding_mask, min_dtype)\n return causal_mask", "docstring": "Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape\n`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.\n\nArgs:\nattention_mask (`torch.Tensor`):\nA 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape\n`(batch_size, 1, query_length, key_value_length)`.\nsequence_length (`int`):\nThe sequence length being processed.\ntarget_length (`int`):\nThe target length: when generating with static cache, the mask should be as long as the static cache,\nto account for the 0 padding, the part of the cache that is not filled yet.\ndtype (`torch.dtype`):\nThe dtype to use for the 4D attention mask.\ncache_position (`torch.Tensor`):\nIndices depicting the position of the input sequence tokens in the sequence.\nbatch_size (`torch.Tensor`):\nBatch size.", "source": "github-repos"}
1133{"code": "def forward(self, outputs, targets):\n outputs_without_aux = {k: v for k, v in outputs.items() if k != 'auxiliary_outputs'}\n indices = self.matcher(outputs_without_aux, targets)\n num_boxes = sum((len(t['class_labels']) for t in targets))\n num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)\n world_size = 1\n if is_accelerate_available():\n if PartialState._shared_state != {}:\n num_boxes = reduce(num_boxes)\n world_size = PartialState().num_processes\n num_boxes = torch.clamp(num_boxes / world_size, min=1).item()\n losses = {}\n for loss in self.losses:\n losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))\n if 'auxiliary_outputs' in outputs:\n for i, auxiliary_outputs in enumerate(outputs['auxiliary_outputs']):\n indices = self.matcher(auxiliary_outputs, targets)\n for loss in self.losses:\n if loss == 'masks':\n continue\n l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes)\n l_dict = {k + f'_{i}': v for k, v in l_dict.items()}\n losses.update(l_dict)\n return losses", "docstring": "This performs the loss computation.\n\nArgs:\noutputs (`dict`, *optional*):\nDictionary of tensors, see the output specification of the model for the format.\ntargets (`List[dict]`, *optional*):\nList of dicts, such that `len(targets) == batch_size`. The expected keys in each dict depends on the\nlosses applied, see each loss' doc.", "source": "github-repos"}
1134{"code": "def _ReadEncryptedData(self, read_size):\n encrypted_data = self._file_object.read(read_size)\n read_count = len(encrypted_data)\n self._encrypted_data = b''.join([self._encrypted_data, encrypted_data])\n (self._decrypted_data, self._encrypted_data) = self._decrypter.Decrypt(self._encrypted_data)\n self._decrypted_data_size = len(self._decrypted_data)\n return read_count", "docstring": "Reads encrypted data from the file-like object.\n\nArgs:\nread_size (int): number of bytes of encrypted data to read.\n\nReturns:\nint: number of bytes of encrypted data read.", "source": "codesearchnet"}
1135{"code": "def egg_info_writer(cmd, basename, filename):\n setupcfg = next((f for f in setuptools.findall() if (os.path.basename(f) == 'setup.cfg')), None)\n if (not setupcfg):\n return\n parser = six.moves.configparser.ConfigParser()\n parser.read(setupcfg)\n if ((not parser.has_section('rcli')) or (not parser.items('rcli'))):\n return\n config = dict(parser.items('rcli'))\n for (k, v) in six.iteritems(config):\n if (v.lower() in ('y', 'yes', 'true')):\n config[k] = True\n elif (v.lower() in ('n', 'no', 'false')):\n config[k] = False\n else:\n try:\n config[k] = json.loads(v)\n except ValueError:\n pass\n cmd.write_file(basename, filename, json.dumps(config))", "docstring": "Read rcli configuration and write it out to the egg info.\n\nArgs:\ncmd: An egg info command instance to use for writing.\nbasename: The basename of the file to write.\nfilename: The full path of the file to write into the egg info.", "source": "codesearchnet"}
1136{"code": "def ExamineEvent(self, mediator, event):\n \n if self._tagging_rules is None:\n if self._autodetect_tag_file_attempt:\n \n \n return\n\n if not self._AttemptAutoDetectTagFile(mediator):\n logger.info(\n 'No tag definition file specified, and plaso was not able to '\n 'autoselect a tagging file. As no definitions were specified, '\n 'no events will be tagged.')\n return\n\n matched_label_names = []\n for label_name, filter_objects in iter(self._tagging_rules.items()):\n for filter_object in filter_objects:\n if filter_object.Match(event):\n matched_label_names.append(label_name)\n break\n\n if matched_label_names:\n event_tag = self._CreateEventTag(\n event, self._EVENT_TAG_COMMENT, matched_label_names)\n\n mediator.ProduceEventTag(event_tag)\n self._number_of_event_tags += 1", "docstring": "Analyzes an EventObject and tags it according to rules in the tag file.\n\nArgs:\nmediator (AnalysisMediator): mediates interactions between analysis\nplugins and other components, such as storage and dfvfs.\nevent (EventObject): event to examine.", "source": "juraj-google-style"}
1137{"code": "def eval_adiabatic_limit(YABFGN, Ytilde, P0):\n \n Y, A, B, F, G, N = YABFGN\n\n Klim = (P0 * (B - A * Ytilde * A) * P0).expand().simplify_scalar()\n Hlim = ((Klim - Klim.dag())/2/I).expand().simplify_scalar()\n\n Ldlim = (P0 * (G - A * Ytilde * F) * P0).expand().simplify_scalar()\n\n dN = identity_matrix(N.shape[0]) + F.H * Ytilde * F\n Nlim = (P0 * N * dN * P0).expand().simplify_scalar()\n\n return SLH(Nlim.dag(), Ldlim.dag(), Hlim.dag())", "docstring": "Compute the limiting SLH model for the adiabatic approximation\n\nArgs:\nYABFGN: The tuple (Y, A, B, F, G, N)\nas returned by prepare_adiabatic_limit.\nYtilde: The pseudo-inverse of Y, satisfying Y * Ytilde = P0.\nP0: The projector onto the null-space of Y.\n\nReturns:\nSLH: Limiting SLH model", "source": "juraj-google-style"}
1138{"code": "def cond(self, name='cond'):\n with self._name_scope(name):\n return self._cond()", "docstring": "Returns the condition number of this linear operator.\n\nArgs:\nname: A name for this `Op`.\n\nReturns:\nShape `[B1,...,Bb]` `Tensor` of same `dtype` as `self`.", "source": "github-repos"}
1139{"code": "def end_run_group(group, session):\n from datetime import datetime\n group.end = datetime.now()\n group.status = 'completed'\n session.commit()", "docstring": "End the run_group successfully.\n\nArgs:\ngroup: The run_group we want to complete.\nsession: The database transaction we will finish.", "source": "codesearchnet"}
1140{"code": "def delete(self, key):\n dct = self\n keys = key.split('.')\n last_key = keys[(- 1)]\n for k in keys:\n if (k == last_key):\n del dct[k]\n break\n if isinstance(dct, DotDict):\n dct = super(DotDict, dct).__getitem__(k)\n else:\n dct = dct.__getitem__(k)\n if (not isinstance(dct, (DotDict, dict))):\n raise KeyError('Subkey \"{}\" in \"{}\" invalid for deletion'.format(k, key))", "docstring": "Remove a value from the `DotDict`.\n\nThe `key` parameter can either be a regular string key,\ne.g. \"foo\", or it can be a string key with dot notation,\ne.g. \"foo.bar.baz\", to signify a nested element.\n\nIf the key does not exist in the `DotDict`, it will continue\nsilently.\n\nArgs:\nkey (str): The key to remove.", "source": "codesearchnet"}
1141{"code": "def _mini_batch_training_op(self, inputs, cluster_idx_list, cluster_centers, total_counts):\n update_ops = []\n for inp, cluster_idx in zip(inputs, cluster_idx_list):\n with ops.colocate_with(inp, ignore_existing=True):\n assert total_counts is not None\n cluster_idx = array_ops.reshape(cluster_idx, [-1])\n unique_ids, unique_idx = array_ops.unique(cluster_idx)\n num_unique_cluster_idx = array_ops.size(unique_ids)\n with ops.colocate_with(total_counts, ignore_existing=True):\n old_counts = array_ops.gather(total_counts, unique_ids)\n with ops.colocate_with(cluster_centers, ignore_existing=True):\n old_cluster_centers = array_ops.gather(cluster_centers, unique_ids)\n count_updates = math_ops.unsorted_segment_sum(array_ops.ones_like(unique_idx, dtype=total_counts.dtype), unique_idx, num_unique_cluster_idx)\n cluster_center_updates = math_ops.unsorted_segment_sum(inp, unique_idx, num_unique_cluster_idx)\n broadcast_shape = array_ops.concat([array_ops.reshape(num_unique_cluster_idx, [1]), array_ops.ones(array_ops.reshape(array_ops.rank(inp) - 1, [1]), dtype=dtypes.int32)], 0)\n cluster_center_updates -= math_ops.cast(array_ops.reshape(count_updates, broadcast_shape), inp.dtype) * old_cluster_centers\n learning_rate = math_ops.reciprocal(math_ops.cast(old_counts + count_updates, inp.dtype))\n learning_rate = array_ops.reshape(learning_rate, broadcast_shape)\n cluster_center_updates *= learning_rate\n update_counts = state_ops.scatter_add(total_counts, unique_ids, count_updates)\n update_cluster_centers = state_ops.scatter_add(cluster_centers, unique_ids, cluster_center_updates)\n update_ops.extend([update_counts, update_cluster_centers])\n return control_flow_ops.group(*update_ops)", "docstring": "Creates an op for training for mini batch case.\n\nArgs:\ninputs: list of input Tensors.\ncluster_idx_list: A vector (or list of vectors). Each element in the\nvector corresponds to an input row in 'inp' and specifies the cluster id\ncorresponding to the input.\ncluster_centers: Tensor Ref of cluster centers.\ntotal_counts: Tensor Ref of cluster counts.\n\nReturns:\nAn op for doing an update of mini-batch k-means.", "source": "github-repos"}
1142{"code": "def execute_command(self, args, parent_environ=None, **subprocess_kwargs):\n if (parent_environ in (None, os.environ)):\n target_environ = {}\n else:\n target_environ = parent_environ.copy()\n interpreter = Python(target_environ=target_environ)\n executor = self._create_executor(interpreter, parent_environ)\n self._execute(executor)\n return interpreter.subprocess(args, **subprocess_kwargs)", "docstring": "Run a command within a resolved context.\n\nThis applies the context to a python environ dict, then runs a\nsubprocess in that namespace. This is not a fully configured subshell -\nshell-specific commands such as aliases will not be applied. To execute\na command within a subshell instead, use execute_shell().\n\nWarning:\nThis runs a command in a configured environ dict only, not in a true\nshell. To do that, call `execute_shell` using the `command` keyword\nargument.\n\nArgs:\nargs: Command arguments, can be a string.\nparent_environ: Environment to interpret the context within,\ndefaults to os.environ if None.\nsubprocess_kwargs: Args to pass to subprocess.Popen.\n\nReturns:\nA subprocess.Popen object.\n\nNote:\nThis does not alter the current python session.", "source": "codesearchnet"}
1143{"code": "def _AddHeader(self, fp):\n \n text = textwrap.wrap(\n textwrap.dedent(self.config_header), break_on_hyphens=False)\n fp.write('\\n'.join(['\n fp.write('\\n\\n')", "docstring": "Create a file header in the config.\n\nArgs:\nfp: int, a file pointer for writing the header.", "source": "juraj-google-style"}
1144{"code": "def extract_numerics_alert(event):\n value = event.summary.value[0]\n debugger_plugin_metadata_content = None\n if value.HasField('metadata'):\n plugin_data = value.metadata.plugin_data\n if (plugin_data.plugin_name == constants.DEBUGGER_PLUGIN_NAME):\n debugger_plugin_metadata_content = plugin_data.content\n if (not debugger_plugin_metadata_content):\n raise ValueError('Event proto input lacks debugger plugin SummaryMetadata.')\n debugger_plugin_metadata_content = tf.compat.as_text(debugger_plugin_metadata_content)\n try:\n content_object = json.loads(debugger_plugin_metadata_content)\n device_name = content_object['device']\n except (KeyError, ValueError) as e:\n raise ValueError(('Could not determine device from JSON string %r, %r' % (debugger_plugin_metadata_content, e)))\n debug_op_suffix = ':DebugNumericSummary'\n if (not value.node_name.endswith(debug_op_suffix)):\n raise ValueError(('Event proto input does not have the expected debug op suffix %s' % debug_op_suffix))\n tensor_name = value.node_name[:(- len(debug_op_suffix))]\n elements = tf_debug.load_tensor_from_event(event)\n nan_count = elements[constants.NAN_NUMERIC_SUMMARY_OP_INDEX]\n neg_inf_count = elements[constants.NEG_INF_NUMERIC_SUMMARY_OP_INDEX]\n pos_inf_count = elements[constants.POS_INF_NUMERIC_SUMMARY_OP_INDEX]\n if ((nan_count > 0) or (neg_inf_count > 0) or (pos_inf_count > 0)):\n return NumericsAlert(device_name, tensor_name, event.wall_time, nan_count, neg_inf_count, pos_inf_count)\n return None", "docstring": "Determines whether a health pill event contains bad values.\n\nA bad value is one of NaN, -Inf, or +Inf.\n\nArgs:\nevent: (`Event`) A `tensorflow.Event` proto from `DebugNumericSummary`\nops.\n\nReturns:\nAn instance of `NumericsAlert`, if bad values are found.\n`None`, if no bad values are found.\n\nRaises:\nValueError: if the event does not have the expected tag prefix or the\ndebug op name is not the expected debug op name suffix.", "source": "codesearchnet"}
1145{"code": "def limitReal(x, max_denominator=1000000):\n f = Fraction(x).limit_denominator(max_denominator)\n return Real((f.numerator, f.denominator))", "docstring": "Creates an pysmt Real constant from x.\n\nArgs:\nx (number): A number to be cast to a pysmt constant.\nmax_denominator (int, optional): The maximum size of the denominator.\nDefault 1000000.\n\nReturns:\nA Real constant with the given value and the denominator limited.", "source": "codesearchnet"}
1146{"code": "def __call__(self, text, toLang, fromLang=None):\n \n return self.skype.conn(\"GET\", \"{0}/skype/translate\".format(SkypeConnection.API_TRANSLATE),\n params={\"from\": fromLang or \"\", \"to\": toLang, \"text\": text},\n auth=SkypeConnection.Auth.SkypeToken).json()", "docstring": "Attempt translation of a string. Supports automatic language detection if ``fromLang`` is not specified.\n\nArgs:\ntext (str): input text to be translated\ntoLang (str): country code of output language\nfromLang (str): country code of input language", "source": "juraj-google-style"}
1147{"code": "def forward(self, hidden_states: torch.Tensor, level_index: Optional[int]=None, attention_mask: Optional[torch.Tensor]=None, position_embeddings: Optional[torch.Tensor]=None, query_position_embeddings: Optional[torch.Tensor]=None, encoder_hidden_states: Optional[torch.Tensor]=None, encoder_attention_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=False):\n if self.pre_norm:\n outputs = self.forward_pre(hidden_states=hidden_states, level_index=level_index, position_embeddings=position_embeddings, query_position_embeddings=query_position_embeddings, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions)\n else:\n outputs = self.forward_post(hidden_states=hidden_states, level_index=level_index, position_embeddings=position_embeddings, query_position_embeddings=query_position_embeddings, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions)\n return outputs", "docstring": "Args:\nhidden_states (`torch.FloatTensor`):\nInput to the layer of shape `(seq_len, batch, embed_dim)`.\nattention_mask (`torch.FloatTensor`):\nAttention mask of shape `(1, seq_len, tgt_len, src_len)`.\nposition_embeddings (`torch.FloatTensor`, *optional*):\nPosition embeddings that are added to the keys in the masked-attention layer.\nquery_position_embeddings (`torch.FloatTensor`, *optional*):\nPosition embeddings that are added to the queries and keys in the self-attention layer.\nencoder_hidden_states (`torch.FloatTensor`):\nCross attention input to the layer of shape `(seq_len, batch, embed_dim)`.\nencoder_attention_mask (`torch.FloatTensor`):\nEncoder attention mask of size`(1, seq_len, tgt_len, src_len)`.\noutput_attentions (`bool`, *optional*):\nWhether or not to return the attentions tensors of all attention layers. See `attentions` under\nreturned tensors for more detail.", "source": "github-repos"}
1148{"code": "def enable_encryption(self):\n try:\n self.send_state_event('m.room.encryption', {'algorithm': 'm.megolm.v1.aes-sha2'})\n self.encrypted = True\n return True\n except MatrixRequestError:\n return False", "docstring": "Enables encryption in the room.\n\nNOTE: Once enabled, encryption cannot be disabled.\n\nReturns:\nTrue if successful, False if not", "source": "codesearchnet"}
1149{"code": "def _download_items(db, last_id):\n \n MAX_RETRY = 20 \n MAX_DOC_ID = 10000000 \n\n not_found_cnt = 0 \n for doc_id in xrange(last_id, MAX_DOC_ID):\n doc_id += 1\n print \"Downloading %d..\" % (doc_id)\n\n if not_found_cnt >= MAX_RETRY:\n print \"It looks like this is an end:\", doc_id - MAX_RETRY\n break\n\n try:\n record = _download(doc_id)\n except (DocumentNotFoundException, InvalidAlephBaseException):\n print \"\\tnot found, skipping\"\n not_found_cnt += 1\n continue\n\n not_found_cnt = 0\n db[\"item_%d\" % doc_id] = record\n db[\"last_id\"] = doc_id - MAX_RETRY if doc_id > MAX_RETRY else 1\n\n if doc_id % 100 == 0:\n db.commit()", "docstring": "Download items from the aleph and store them in `db`. Start from `last_id`\nif specified.\n\nArgs:\ndb (obj): Dictionary-like object used as DB.\nlast_id (int): Start from this id.", "source": "juraj-google-style"}
1150{"code": "def create_token_type_ids_from_sequences(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:\n sep = [self.sep_token_id]\n cls = [self.cls_token_id]\n if token_ids_1 is None:\n return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0]\n return len(cls) * [self.cls_token_type_id] + len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]", "docstring": "Create a mask from the two sequences passed to be used in a sequence-pair classification task. A Funnel\nTransformer sequence pair mask has the following format:\n\n```\n2 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1\n| first sequence | second sequence |\n```\n\nIf `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).\n\nArgs:\ntoken_ids_0 (`List[int]`):\nList of IDs.\ntoken_ids_1 (`List[int]`, *optional*):\nOptional second list of IDs for sequence pairs.\n\nReturns:\n`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).", "source": "github-repos"}
1151{"code": "def occurrence(self, file_name=None, path=None, date=None):\n if (self._indicator_data.get('type') != 'File'):\n return None\n occurrence_obj = FileOccurrence(file_name, path, date)\n self._occurrences.append(occurrence_obj)\n return occurrence_obj", "docstring": "Add a file Occurrence.\n\nArgs:\nfile_name (str, optional): The file name for this occurrence.\npath (str, optional): The file path for this occurrence.\ndate (str, optional): The datetime expression for this occurrence.\n\nReturns:\nobj: An instance of Occurrence.", "source": "codesearchnet"}
1152{"code": "def add_tasks_r(addon_module, package_module, package_name):\n module_dict = package_module.__dict__\n for (attr_name, attr_val) in module_dict.items():\n if isinstance(attr_val, fabric.tasks.WrappedCallableTask):\n addon_module.__dict__[attr_name] = attr_val\n elif ((attr_name != package_name) and isinstance(attr_val, types.ModuleType) and attr_val.__name__.startswith('fabsetup_') and (attr_name.split('.')[(- 1)] != package_name)):\n submodule_name = flo('{addon_module.__name__}.{attr_name}')\n submodule = get_or_create_module_r(submodule_name)\n package_module = attr_val\n add_tasks_r(submodule, package_module, package_name)\n addon_module.__dict__[attr_name] = submodule", "docstring": "Recursively iterate through 'package_module' and add every fabric task\nto the 'addon_module' keeping the task hierarchy.\n\nArgs:\naddon_module(types.ModuleType)\npackage_module(types.ModuleType)\npackage_name(str): Required, to avoid redundant addition of tasks\n\nReturn: None", "source": "codesearchnet"}
1153{"code": "def copy(self, source_file_names, destination_file_names):\n if not len(source_file_names) == len(destination_file_names):\n message = 'Unable to copy unequal number of sources and destinations.'\n raise BeamIOError(message)\n src_dest_pairs = list(zip(source_file_names, destination_file_names))\n return self._blobstorageIO().copy_paths(src_dest_pairs)", "docstring": "Recursively copy the file tree from the source to the destination\n\nArgs:\nsource_file_names: list of source file objects that needs to be copied\ndestination_file_names: list of destination of the new object\n\nRaises:\n``BeamIOError``: if any of the copy operations fail", "source": "github-repos"}
1154{"code": "def undetoured_new(cls, *args, **kwargs) -> Any:\n new_method = _global_detour_context.get_original_new(cls)\n if new_method is object.__new__:\n instance = new_method(cls)\n else:\n instance = new_method(cls, *args, **kwargs)\n instance.__init__(*args, **kwargs)\n return instance", "docstring": "Create a new instance of cls without detouring.\n\nIf cls.__init__ creates sub-objects, creation of sub-objects\nmaybe detoured based on current context. For example::\n\nclass A:\n\ndef __init__(self, x):\nif x < 0:\nself.child = A(x)\nelse:\nself.x = x\n\nwith pg.detour([A, B]):\na = A(-1)\nassert isinstance(a, A)\nassert isinstance(a.child, B)\n\nArgs:\ncls: The class whose instance will be created.\n*args: Positional arguments to be passed to class __init__ method.\n**kwargs: Keyword arguments to be passed to class __init__ method.\n\nReturns:\nA instance of `cls`.", "source": "github-repos"}
1155{"code": "def GetAPFSFileEntryByPathSpec(self, path_spec):\n location = getattr(path_spec, 'location', None)\n identifier = getattr(path_spec, 'identifier', None)\n if (identifier is not None):\n fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_identifier(identifier)\n elif (location is not None):\n fsapfs_file_entry = self._fsapfs_volume.get_file_entry_by_path(location)\n else:\n raise errors.PathSpecError('Path specification missing location and identifier.')\n return fsapfs_file_entry", "docstring": "Retrieves the APFS file entry for a path specification.\n\nArgs:\npath_spec (PathSpec): a path specification.\n\nReturns:\npyfsapfs.file_entry: file entry.\n\nRaises:\nPathSpecError: if the path specification is missing location and\nidentifier.", "source": "codesearchnet"}
1156{"code": "def create_team(self, name):\n \n request = self._get_request()\n return request.post(self.TEAM_CREATE_URL, {\"name\": name})", "docstring": "Creates a new Team\n\nCreates a new Team and makes you a member. You must not currently belong to a team to invoke.\n\nArgs:\n\nname (str): The name of your team\n\nReturns:\nA Team object", "source": "juraj-google-style"}
1157{"code": "def _createBitpattern(functioncode, value):\n \n _checkFunctioncode(functioncode, [5, 15])\n _checkInt(value, minvalue=0, maxvalue=1, description='inputvalue')\n\n if functioncode == 5:\n if value == 0:\n return '\\x00\\x00'\n else:\n return '\\xff\\x00'\n\n elif functioncode == 15:\n if value == 0:\n return '\\x00'\n else:\n return '\\x01'", "docstring": "Create the bit pattern that is used for writing single bits.\n\nThis is basically a storage of numerical constants.\n\nArgs:\n* functioncode (int): can be 5 or 15\n* value (int): can be 0 or 1\n\nReturns:\nThe bit pattern (string).\n\nRaises:\nTypeError, ValueError", "source": "juraj-google-style"}
1158{"code": "def _ProcessPathSpec(self, extraction_worker, parser_mediator, path_spec):\n \n self._current_display_name = parser_mediator.GetDisplayNameForPathSpec(\n path_spec)\n\n try:\n extraction_worker.ProcessPathSpec(parser_mediator, path_spec)\n\n except KeyboardInterrupt:\n self._abort = True\n\n self._processing_status.aborted = True\n if self._status_update_callback:\n self._status_update_callback(self._processing_status)\n\n \n \n except dfvfs_errors.CacheFullError:\n \n self._abort = True\n logger.error((\n 'ABORT: detected cache full error while processing '\n 'path spec: {0:s}').format(self._current_display_name))\n\n \n \n except Exception as exception: \n parser_mediator.ProduceExtractionWarning((\n 'unable to process path specification with error: '\n '{0!s}').format(exception), path_spec=path_spec)\n\n if getattr(self._processing_configuration, 'debug_output', False):\n logger.warning(\n 'Unhandled exception while processing path spec: {0:s}.'.format(\n self._current_display_name))\n logger.exception(exception)\n\n pdb.post_mortem()", "docstring": "Processes a path specification.\n\nArgs:\nextraction_worker (worker.ExtractionWorker): extraction worker.\nparser_mediator (ParserMediator): parser mediator.\npath_spec (dfvfs.PathSpec): path specification.", "source": "juraj-google-style"}
1159{"code": "def _call_method(self, method, req, resp_class):\n payload = req.SerializeToString()\n headers = {'Content-Type': 'application/x-protobuf', 'Content-Length': str(len(payload)), 'X-Goog-Api-Format-Version': '2'}\n (response, content) = self._http.request(('%s:%s' % (self._url, method)), method='POST', body=payload, headers=headers)\n if (response.status != 200):\n raise _make_rpc_error(method, response, content)\n resp = resp_class()\n resp.ParseFromString(content)\n return resp", "docstring": "_call_method call the given RPC method over HTTP.\n\nIt uses the given protobuf message request as the payload and\nreturns the deserialized protobuf message response.\n\nArgs:\nmethod: RPC method name to be called.\nreq: protobuf message for the RPC request.\nresp_class: protobuf message class for the RPC response.\n\nReturns:\nDeserialized resp_class protobuf message instance.\n\nRaises:\nRPCError: The rpc method call failed.", "source": "codesearchnet"}
1160{"code": "def __init__(self, tlv_type=127, value=None):\n \n super().__init__()\n self.tlv_type = tlv_type\n self._value = BinaryData() if value is None else value", "docstring": "Create an instance and set its attributes.\n\nArgs:\ntlv_type (int): Type used by this class. Defaults to 127.\nvalue (:class:`~pyof.foundation.basic_types.BinaryData`):\nValue stored by GenericTLV.", "source": "juraj-google-style"}
1161{"code": "def search(self, term):\n return self._result(self._get(self._url('/images/search'), params={'term': term}), True)", "docstring": "Search for images on Docker Hub. Similar to the ``docker search``\ncommand.\n\nArgs:\nterm (str): A term to search for.\n\nReturns:\n(list of dicts): The response of the search.\n\nRaises:\n:py:class:`docker.errors.APIError`\nIf the server returns an error.", "source": "codesearchnet"}
1162{"code": "def _fill_from_default(self, default_job_config):\n \n if self._job_type != default_job_config._job_type:\n raise TypeError(\n \"attempted to merge two incompatible job types: \"\n + repr(self._job_type)\n + \", \"\n + repr(default_job_config._job_type)\n )\n\n new_job_config = self.__class__()\n\n default_job_properties = copy.deepcopy(default_job_config._properties)\n for key in self._properties:\n if key != self._job_type:\n default_job_properties[key] = self._properties[key]\n\n default_job_properties[self._job_type].update(self._properties[self._job_type])\n new_job_config._properties = default_job_properties\n\n return new_job_config", "docstring": "Merge this job config with a default job config.\n\nThe keys in this object take precedence over the keys in the default\nconfig. The merge is done at the top-level as well as for keys one\nlevel below the job type.\n\nArguments:\ndefault_job_config (google.cloud.bigquery.job._JobConfig):\nThe default job config that will be used to fill in self.\n\nReturns:\ngoogle.cloud.bigquery.job._JobConfig A new (merged) job config.", "source": "juraj-google-style"}
1163{"code": "def method(self, method):\n \n self._request.method = method\n self.add_matcher(matcher('MethodMatcher', method))", "docstring": "Defines the HTTP method to match.\nUse ``*`` to match any method.\n\nArguments:\nmethod (str): method value to match. E.g: ``GET``.\n\nReturns:\nself: current Mock instance.", "source": "juraj-google-style"}
1164{"code": "def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None):\n with tf.variable_scope('sigmoid_cross_entropy_one_hot', values=[logits, labels]):\n del weights_fn\n cross_entropy = tf.losses.sigmoid_cross_entropy(multi_class_labels=labels, logits=logits)\n return (cross_entropy, tf.constant(1.0))", "docstring": "Calculate sigmoid cross entropy for one-hot lanels and logits.\n\nArgs:\nlogits: Tensor of size [batch-size, o=1, p=1, num-classes]\nlabels: Tensor of size [batch-size, o=1, p=1, num-classes]\nweights_fn: Function that takes in labels and weighs examples (unused)\nReturns:\ncross_entropy (scalar), weights", "source": "codesearchnet"}
1165{"code": "def exit(self, code=None, msg=None):\n \n \n if msg is not None:\n if code in [0, 3] or (code is None and self.exit_code in [0, 3]):\n self.log.info(msg)\n else:\n self.log.error(msg)\n self.message_tc(msg)\n\n if code is None:\n code = self.exit_code\n elif code in [0, 1, 3]:\n pass\n else:\n self.log.error(u'Invalid exit code')\n code = 1\n\n if self.default_args.tc_aot_enabled:\n \n self.playbook.aot_rpush(code)\n\n self.log.info(u'Exit Code: {}'.format(code))\n sys.exit(code)", "docstring": "Application exit method with proper exit code\n\nThe method will run the Python standard sys.exit() with the exit code\npreviously defined via :py:meth:`~tcex.tcex.TcEx.exit_code` or provided\nduring the call of this method.\n\nArgs:\ncode (Optional [integer]): The exit code value for the app.\nmsg (Optional [string]): A message to log and add to message tc output.", "source": "juraj-google-style"}
1166{"code": "def num_employers(self, num_employers):\n \n\n if num_employers < 2:\n self._logger.log(\n 'warn',\n 'Two employers are needed: setting to two'\n )\n num_employers = 2\n self._num_employers = num_employers\n self._logger.log('debug', 'Number of employers set to {}'.format(\n num_employers\n ))\n self._limit = num_employers * len(self._value_ranges)\n self._logger.log('debug', 'Limit set to {}'.format(self._limit))", "docstring": "Sets the number of employer bees; at least two are required\n\nArgs:\nnum_employers (int): number of employer bees", "source": "juraj-google-style"}
1167{"code": "def get_apod(cls, date=None, hd=False):\n instance = cls('planetary/apod')\n filters = {'date': date, 'hd': hd}\n return instance.get_resource(**filters)", "docstring": "Returns Astronomy Picture of the Day\n\nArgs:\ndate: date instance (default = today)\n\nhd: bool if high resolution should be included\n\nReturns:\njson", "source": "codesearchnet"}
1168{"code": "def _set_route(self, ip_dest, next_hop, **kwargs):\n commands = self._build_commands(ip_dest, next_hop, **kwargs)\n delete = kwargs.get('delete', False)\n default = kwargs.get('default', False)\n if delete:\n commands = ('no ' + commands)\n elif default:\n commands = ('default ' + commands)\n return self.configure(commands)", "docstring": "Configure a static route\n\nArgs:\nip_dest (string): The ip address of the destination in the\nform of A.B.C.D/E\nnext_hop (string): The next hop interface or ip address\n**kwargs['next_hop_ip'] (string): The next hop address on\ndestination interface\n**kwargs['distance'] (string): Administrative distance for this\nroute\n**kwargs['tag'] (string): Route tag\n**kwargs['route_name'] (string): Route name\n**kwargs['delete'] (boolean): If true, deletes the specified route\ninstead of creating or setting values for the route\n**kwargs['default'] (boolean): If true, defaults the specified\nroute instead of creating or setting values for the route\n\nReturns:\nTrue if the operation succeeds, otherwise False.", "source": "codesearchnet"}
1169{"code": "def advth(step):\n \n rbot, rtop = misc.get_rbounds(step)\n rmean = 0.5 * (rbot + rtop)\n rad = step.rprof['r'].values + rbot\n radio = step.timeinfo['H_int']\n if rbot != 0: \n th_adv = -(rtop**3 - rad**3) / rmean**2 / 3\n else:\n th_adv = rad - rtop\n th_adv *= radio\n th_adv += step.timeinfo['Nutop']\n return th_adv, None", "docstring": "Theoretical advection.\n\nThis compute the theoretical profile of total advection as function of\nradius.\n\nArgs:\nstep (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData\ninstance.\nReturns:\ntuple of :class:`numpy.array` and None: the theoretical advection.\nThe second element of the tuple is None.", "source": "juraj-google-style"}
1170{"code": "def _ProcessZipFileWithPlugins(self, parser_mediator, zip_file):\n archive_members = zip_file.namelist()\n for plugin in self._plugins:\n try:\n plugin.UpdateChainAndProcess(parser_mediator, zip_file=zip_file, archive_members=archive_members)\n except errors.WrongCompoundZIPPlugin as exception:\n logger.debug('[{0:s}] wrong plugin: {1!s}'.format(self.NAME, exception))", "docstring": "Processes a zip file using all compound zip files.\n\nArgs:\nparser_mediator (ParserMediator): mediates interactions between parsers\nand other components, such as storage and dfvfs.\nzip_file (zipfile.ZipFile): the zip file. It should not be closed in\nthis method, but will be closed in ParseFileObject().", "source": "codesearchnet"}
1171{"code": "def _popitem(self, indices=None, name=None):\n if name is None:\n name = '%s_get_nokey' % self._name\n indices, dtypes = self._get_indices_and_dtypes(indices)\n with ops.colocate_with(self._coloc_op):\n key, result = self._popitem_fn(shared_name=self._name, indices=indices, dtypes=dtypes, name=name, capacity=self._capacity, memory_limit=self._memory_limit)\n key = self._create_device_transfers(key)[0]\n result = self._get_return_value(result, indices)\n return (key, result)", "docstring": "If the staging area is ordered, the (key, value) with the smallest key will be returned.\n\nOtherwise, a random (key, value) will be returned.\nIf the staging area is empty when this operation executes,\nit will block until there is an element to dequeue.\n\nArgs:\nkey: Key associated with the required data\nindices: Partial list of tensors to retrieve (optional).\nA list of integer or string indices.\nString indices are only valid if the Staging Area\nhas names associated with it.\nname: A name for the operation (optional)\n\nReturns:\nThe created op", "source": "github-repos"}
1172{"code": "def match_any(patterns, name):\n \n \n if not patterns:\n return True\n return any(match(pattern, name) for pattern in patterns)", "docstring": "Test if a name matches any of a list of patterns.\n\nWill return `True` if ``patterns`` is an empty list.\n\nArguments:\npatterns (list): A list of wildcard pattern, e.g ``[\"*.py\",\n\"*.pyc\"]``\nname (str): A filename.\n\nReturns:\nbool: `True` if the name matches at least one of the patterns.", "source": "juraj-google-style"}
1173{"code": "def apply_range_set(self, hist: Hist) -> None:\n \n \n axis = self.axis(hist)\n \n \n assert not isinstance(self.min_val, float)\n assert not isinstance(self.max_val, float)\n \n min_val = self.min_val(axis)\n max_val = self.max_val(axis)\n \n \n \n self.axis(hist).SetRange(min_val, max_val)", "docstring": "Apply the associated range set to the axis of a given hist.\n\nNote:\nThe min and max values should be bins, not user ranges! For more, see the binning\nexplanation in ``apply_func_to_find_bin(...)``.\n\nArgs:\nhist: Histogram to which the axis range restriction should be applied.\nReturns:\nNone. The range is set on the axis.", "source": "juraj-google-style"}
1174{"code": "def ShapeEquals(tensor_proto, shape):\n if not isinstance(tensor_proto, tensor_pb2.TensorProto):\n raise TypeError(f'`tensor_proto` must be a tensor_pb2.TensorProto object, but got type {type(tensor_proto)}.')\n if isinstance(shape, tensor_shape_pb2.TensorShapeProto):\n shape = [d.size for d in shape.dim]\n elif not isinstance(shape, (list, tuple)):\n raise TypeError(f'`shape` must be a list or tuple, but got type {type(shape)}.')\n tensor_shape_list = [d.size for d in tensor_proto.tensor_shape.dim]\n return all((x == y for x, y in zip(tensor_shape_list, shape)))", "docstring": "Returns True if \"tensor_proto\" has the given \"shape\".\n\nArgs:\ntensor_proto: A TensorProto.\nshape: A tensor shape, expressed as a TensorShape, list, or tuple.\n\nReturns:\nTrue if \"tensor_proto\" has the given \"shape\", otherwise False.\n\nRaises:\nTypeError: If \"tensor_proto\" is not a TensorProto, or shape is not a\nTensorShape, list, or tuple.", "source": "github-repos"}
1175{"code": "def compute_batch_indices(batch_size, beam_size):\n \n batch_pos = tf.range(batch_size * beam_size) \n batch_pos = tf.reshape(batch_pos, [batch_size, beam_size])\n return batch_pos", "docstring": "Computes the i'th coordinate that contains the batch index for gathers.\n\nBatch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which\nbatch the beam item is in. This will create the i of the i,j coordinate\nneeded for the gather.\n\nArgs:\nbatch_size: Batch size\nbeam_size: Size of the beam.\nReturns:\nbatch_pos: [batch_size, beam_size] tensor of ids", "source": "juraj-google-style"}
1176{"code": "def check(self):\n for info in self.get_info():\n if (info.free < info.limit):\n return info", "docstring": "Check resource levels.\n\nReturns:\nNone, ResourceInfo: If None is provided, no levels are exceeded.\nOtherwise, the first ResourceInfo exceeding limits is returned.", "source": "codesearchnet"}
1177{"code": "def get_bel_versions() -> List[str]:\n spec_dir = config['bel']['lang']['specifications']\n fn = f'{spec_dir}/versions.json'\n with open(fn, 'r') as f:\n versions = json.load(f)\n return versions", "docstring": "Get BEL Language versions supported\n\nGet the list of all BEL Language versions supported. The file this depends\non is generated by belspec_yaml2json and is kept up to date using\n`make update_ebnf` or `make update_parsers`. You can also run `belspec_yaml2json`\ndirectly as it's added as a command by pip install.\n\nReturns:\nList[str]: list of versions", "source": "codesearchnet"}
1178{"code": "def parse_tensor_name_with_slicing(in_str):\n if in_str.count('[') == 1 and in_str.endswith(']'):\n tensor_name = in_str[:in_str.index('[')]\n tensor_slicing = in_str[in_str.index('['):]\n else:\n tensor_name = in_str\n tensor_slicing = ''\n return (tensor_name, tensor_slicing)", "docstring": "Parse tensor name, potentially suffixed by slicing string.\n\nArgs:\nin_str: (str) Input name of the tensor, potentially followed by a slicing\nstring. E.g.: Without slicing string: \"hidden/weights/Variable:0\", with\nslicing string: \"hidden/weights/Variable:0[1, :]\"\n\nReturns:\n(str) name of the tensor\n(str) slicing string, if any. If no slicing string is present, return \"\".", "source": "github-repos"}
1179{"code": "def prepare_framework(estimator, s3_operations):\n \n if estimator.code_location is not None:\n bucket, key = fw_utils.parse_s3_url(estimator.code_location)\n key = os.path.join(key, estimator._current_job_name, 'source', 'sourcedir.tar.gz')\n else:\n bucket = estimator.sagemaker_session._default_bucket\n key = os.path.join(estimator._current_job_name, 'source', 'sourcedir.tar.gz')\n script = os.path.basename(estimator.entry_point)\n if estimator.source_dir and estimator.source_dir.lower().startswith('s3:\n code_dir = estimator.source_dir\n estimator.uploaded_code = fw_utils.UploadedCode(s3_prefix=code_dir, script_name=script)\n else:\n code_dir = 's3:\n estimator.uploaded_code = fw_utils.UploadedCode(s3_prefix=code_dir, script_name=script)\n s3_operations['S3Upload'] = [{\n 'Path': estimator.source_dir or script,\n 'Bucket': bucket,\n 'Key': key,\n 'Tar': True\n }]\n estimator._hyperparameters[sagemaker.model.DIR_PARAM_NAME] = code_dir\n estimator._hyperparameters[sagemaker.model.SCRIPT_PARAM_NAME] = script\n estimator._hyperparameters[sagemaker.model.CLOUDWATCH_METRICS_PARAM_NAME] = \\\n estimator.enable_cloudwatch_metrics\n estimator._hyperparameters[sagemaker.model.CONTAINER_LOG_LEVEL_PARAM_NAME] = estimator.container_log_level\n estimator._hyperparameters[sagemaker.model.JOB_NAME_PARAM_NAME] = estimator._current_job_name\n estimator._hyperparameters[sagemaker.model.SAGEMAKER_REGION_PARAM_NAME] = \\\n estimator.sagemaker_session.boto_region_name", "docstring": "Prepare S3 operations (specify where to upload `source_dir`) and environment variables\nrelated to framework.\n\nArgs:\nestimator (sagemaker.estimator.Estimator): The framework estimator to get information from and update.\ns3_operations (dict): The dict to specify s3 operations (upload `source_dir`).", "source": "juraj-google-style"}
1180{"code": "def get_connection_count(self, id=None, endpoint=None):\n \n return self._call_endpoint(GET_CONNECTION_COUNT, id=id, endpoint=endpoint)", "docstring": "Gets the number of nodes connected to the endpoint\nArgs:\nid: (int, optional) id to use for response tracking\nendpoint: (RPCEndpoint, optional) endpoint to specify to use\nReturns:\njson object of the result or the error encountered in the RPC call", "source": "juraj-google-style"}
1181{"code": "def ge(self, other, axis=\"columns\", level=None):\n \n return self._binary_op(\"ge\", other, axis=axis, level=level)", "docstring": "Checks element-wise that this is greater than or equal to other.\n\nArgs:\nother: A DataFrame or Series or scalar to compare to.\naxis: The axis to perform the gt over.\nlevel: The Multilevel index level to apply gt over.\n\nReturns:\nA new DataFrame filled with Booleans.", "source": "juraj-google-style"}
1182{"code": "def get_country_info_from_iso3(cls, iso3, use_live=True, exception=None):\n countriesdata = cls.countriesdata(use_live=use_live)\n country = countriesdata['countries'].get(iso3.upper())\n if (country is not None):\n return country\n if (exception is not None):\n raise exception\n return None", "docstring": "Get country information from ISO3 code\n\nArgs:\niso3 (str): ISO3 code for which to get country information\nuse_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.\nexception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.\n\nReturns:\nOptional[Dict[str]]: country information", "source": "codesearchnet"}
1183{"code": "def tag_versions(repo_path):\n repo = dulwich.repo.Repo(repo_path)\n tags = get_tags(repo)\n maj_version = 0\n feat_version = 0\n fix_version = 0\n last_maj_version = 0\n last_feat_version = 0\n result = []\n for (commit_sha, children) in reversed(get_children_per_first_parent(repo_path).items()):\n commit = get_repo_object(repo, commit_sha)\n (maj_version, feat_version, fix_version) = get_version(commit=commit, tags=tags, maj_version=maj_version, feat_version=feat_version, fix_version=fix_version, children=children)\n if ((last_maj_version != maj_version) or (last_feat_version != feat_version)):\n last_maj_version = maj_version\n last_feat_version = feat_version\n tag_name = ('refs/tags/v%d.%d' % (maj_version, feat_version))\n if ON_PYTHON3:\n repo[str.encode(tag_name)] = commit\n else:\n repo[tag_name] = commit\n result.append(('v%d.%d -> %s' % (maj_version, feat_version, commit_sha)))\n return '\\n'.join(result)", "docstring": "Given a repo will add a tag for each major version.\n\nArgs:\nrepo_path(str): path to the git repository to tag.", "source": "codesearchnet"}
1184{"code": "def get_tool_context(self, tool_alias):\n \n tools_dict = self.get_tools()\n data = tools_dict.get(tool_alias)\n if data:\n return data[\"context_name\"]\n return None", "docstring": "Given a visible tool alias, return the name of the context it\nbelongs to.\n\nArgs:\ntool_alias (str): Tool alias to search for.\n\nReturns:\n(str): Name of the context that exposes a visible instance of this\ntool alias, or None if the alias is not available.", "source": "juraj-google-style"}
1185{"code": "def stop(self, timeout_s=None):\n \n self._stopping.set()\n with self._current_phase_thread_lock:\n phase_thread = self._current_phase_thread\n if not phase_thread:\n return\n\n if phase_thread.is_alive():\n phase_thread.kill()\n\n _LOG.debug('Waiting for cancelled phase to exit: %s', phase_thread)\n timeout = timeouts.PolledTimeout.from_seconds(timeout_s)\n while phase_thread.is_alive() and not timeout.has_expired():\n time.sleep(0.1)\n _LOG.debug('Cancelled phase %s exit',\n \"didn't\" if phase_thread.is_alive() else 'did')\n \n self.test_state.stop_running_phase()", "docstring": "Stops execution of the current phase, if any.\n\nIt will raise a ThreadTerminationError, which will cause the test to stop\nexecuting and terminate with an ERROR state.\n\nArgs:\ntimeout_s: int or None, timeout in seconds to wait for the phase to stop.", "source": "juraj-google-style"}
1186{"code": "def do_conneg(accept, supported):\n \n for result in parse_accept_header(accept):\n mime_type = result[0]\n if (mime_type in supported):\n return mime_type\n return None", "docstring": "Parse accept header and look for preferred type in supported list.\n\nArguments:\naccept - HTTP Accept header\nsupported - list of MIME type supported by the server\n\nReturns:\nsupported MIME type with highest q value in request, else None.\n\nFIXME - Should replace this with negotiator2", "source": "juraj-google-style"}
1187{"code": "def merge(self, dataset):\n \n def merge_data(source, dest):\n for key, value in source.items():\n if isinstance(value, dict):\n merge_data(value, dest.setdefault(key, {}))\n else:\n dest[key] = value\n return dest\n\n merge_data(dataset.data, self._data)\n\n for h in dataset.task_history:\n if h not in self._task_history:\n self._task_history.append(h)", "docstring": "Merge the specified dataset on top of the existing data.\n\nThis replaces all values in the existing dataset with the values from the\ngiven dataset.\n\nArgs:\ndataset (TaskData): A reference to the TaskData object that should be merged\non top of the existing object.", "source": "juraj-google-style"}
1188{"code": "def write_wav(path, samples, sr=16000):\n max_value = np.abs(np.iinfo(np.int16).min)\n data = (samples * max_value).astype(np.int16)\n scipy.io.wavfile.write(path, sr, data)", "docstring": "Write to given samples to a wav file.\nThe samples are expected to be floating point numbers\nin the range of -1.0 to 1.0.\n\nArgs:\npath (str): The path to write the wav to.\nsamples (np.array): A float array .\nsr (int): The sampling rate.", "source": "codesearchnet"}
1189{"code": "def pose_inv(pose):\n \n\n \n \n\n \n \n \n \n \n \n\n pose_inv = np.zeros((4, 4))\n pose_inv[:3, :3] = pose[:3, :3].T\n pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose[:3, 3])\n pose_inv[3, 3] = 1.0\n return pose_inv", "docstring": "Computes the inverse of a homogenous matrix corresponding to the pose of some\nframe B in frame A. The inverse is the pose of frame A in frame B.\n\nArgs:\npose: numpy array of shape (4,4) for the pose to inverse\n\nReturns:\nnumpy array of shape (4,4) for the inverse pose", "source": "juraj-google-style"}
1190{"code": "def pad(x, paddings, dim_name, name=None):\n \n return PadOperation(\n x, paddings, dim_name, name=name).outputs[0]", "docstring": "Slice operation.\n\nArgs:\nx: a list of Tensors\npaddings: list of integers of size 2, padding size before and after for dim.\ndim_name: string, name for the padding dim\nname: an optional string\nReturns:\na Tensor with shape extended by output_shape for the last axis.", "source": "juraj-google-style"}
1191{"code": "def ParsePathItem(item, opts=None):\n \n if item == os.path.curdir:\n return CurrentComponent()\n\n if item == os.path.pardir:\n return ParentComponent()\n\n recursion = PATH_RECURSION_REGEX.search(item)\n if recursion is None:\n return GlobComponent(item, opts)\n\n start, end = recursion.span()\n if not (start == 0 and end == len(item)):\n raise ValueError(\"malformed recursive component\")\n\n if recursion.group(\"max_depth\"):\n max_depth = int(recursion.group(\"max_depth\"))\n else:\n max_depth = None\n\n return RecursiveComponent(max_depth=max_depth, opts=opts)", "docstring": "Parses string path component to an `PathComponent` instance.\n\nArgs:\nitem: A path component string to be parsed.\nopts: A `PathOpts` object.\n\nReturns:\n`PathComponent` instance corresponding to given path fragment.\n\nRaises:\nValueError: If the path item contains a recursive component fragment but\ncannot be parsed as such.", "source": "juraj-google-style"}
1192{"code": "def _CountClientStatisticByLabel(self, day_buckets, extract_statistic_fn):\n counts = collections.defaultdict(int)\n now = rdfvalue.RDFDatetime.Now()\n for info in self.IterateAllClientsFullInfo(batch_size=db.MAX_COUNT):\n if (not info.metadata.ping):\n continue\n statistic_value = extract_statistic_fn(info)\n for client_label in info.GetLabelsNames(owner='GRR'):\n for day_bucket in day_buckets:\n time_boundary = (now - rdfvalue.Duration.FromDays(day_bucket))\n if (info.metadata.ping > time_boundary):\n counts[(statistic_value, client_label, day_bucket)] += 1\n return dict(counts)", "docstring": "Returns client-activity metrics for a particular statistic.\n\nArgs:\nday_buckets: A set of n-day-active buckets.\nextract_statistic_fn: A function that extracts the statistic's value from\na ClientFullInfo object.", "source": "codesearchnet"}
1193{"code": "def translate(self, start=None, end=None, arch_mode=None):\n \n start_addr = start if start else self.binary.ea_start\n end_addr = end if end else self.binary.ea_end\n\n self.ir_translator.reset()\n\n for addr, asm, _ in self.disassemble(start=start_addr, end=end_addr, arch_mode=arch_mode):\n yield addr, asm, self.ir_translator.translate(asm)", "docstring": "Translate to REIL instructions.\n\nArgs:\nstart (int): Start address.\nend (int): End address.\narch_mode (int): Architecture mode.\n\nReturns:\n(int, Instruction, list): A tuple of the form (address, assembler instruction, REIL instructions).", "source": "juraj-google-style"}
1194{"code": "def _handle_missing_parameters(parameter_values, all_params, required_params, existing_stack=None):\n missing_params = list((set(all_params) - set(parameter_values.keys())))\n if (existing_stack and ('Parameters' in existing_stack)):\n stack_parameters = [p['ParameterKey'] for p in existing_stack['Parameters']]\n for p in missing_params:\n if (p in stack_parameters):\n logger.debug('Using previous value for parameter %s from existing stack', p)\n parameter_values[p] = UsePreviousParameterValue\n final_missing = list((set(required_params) - set(parameter_values.keys())))\n if final_missing:\n raise MissingParameterException(final_missing)\n return list(parameter_values.items())", "docstring": "Handles any missing parameters.\n\nIf an existing_stack is provided, look up missing parameters there.\n\nArgs:\nparameter_values (dict): key/value dictionary of stack definition\nparameters\nall_params (list): A list of all the parameters used by the\ntemplate/blueprint.\nrequired_params (list): A list of all the parameters required by the\ntemplate/blueprint.\nexisting_stack (dict): A dict representation of the stack. If\nprovided, will be searched for any missing parameters.\n\nReturns:\nlist of tuples: The final list of key/value pairs returned as a\nlist of tuples.\n\nRaises:\nMissingParameterException: Raised if a required parameter is\nstill missing.", "source": "codesearchnet"}
1195{"code": "def diff_prettyHtml(self, diffs):\n html = []\n for (op, data) in diffs:\n text = data.replace('&', '&').replace('<', '<').replace('>', '>').replace('\\n', '¶<br>')\n if (op == self.DIFF_INSERT):\n html.append(('<ins style=\"background:\n elif (op == self.DIFF_DELETE):\n html.append(('<del style=\"background:\n elif (op == self.DIFF_EQUAL):\n html.append(('<span>%s</span>' % text))\n return ''.join(html)", "docstring": "Convert a diff array into a pretty HTML report.\n\nArgs:\ndiffs: Array of diff tuples.\n\nReturns:\nHTML representation.", "source": "codesearchnet"}
1196{"code": "def restrict_condition(node, var, condition):\n dnf = []\n restricted = False\n for b in var.bindings:\n match_result = _match_condition(b.data, condition)\n if match_result:\n dnf.append([b])\n else:\n restricted = True\n if not dnf:\n _restrict_counter.inc('unsatisfiable')\n return UNSATISFIABLE\n elif restricted:\n _restrict_counter.inc('restricted')\n return Condition(node, dnf)\n else:\n _restrict_counter.inc('unrestricted')\n return None", "docstring": "Return a restricted condition based on filtered bindings.\n\nArgs:\nnode: The CFGNode.\nvar: A variable.\ncondition: A value that we will check each binding for compatibility with.\n\nReturns:\nA Condition or None. Each binding of the variable is checked for\ncompatibility with the condition. If either no bindings match, or all\nbindings match, then None is returned. Otherwise a new Condition is built\nfrom the specified, compatible, bindings.", "source": "github-repos"}
1197{"code": "def get_fba_flux(self, objective):\n \n flux_result = self.solve_fba(objective)\n fba_fluxes = {}\n\n \n for key in self._model.reactions:\n fba_fluxes[key] = flux_result.get_value(self._v_wt[key])\n return fba_fluxes", "docstring": "Return a dictionary of all the fluxes solved by FBA.\n\nDictionary of fluxes is used in :meth:`.lin_moma` and :meth:`.moma`\nto minimize changes in the flux distributions following model\nperturbation.\n\nArgs:\nobjective: The objective reaction that is maximized.\n\nReturns:\nDictionary of fluxes for each reaction in the model.", "source": "juraj-google-style"}
1198{"code": "def get_variable_scope_name(value):\n \n \n value = getattr(value, \"variable_scope\", value)\n if isinstance(value, tf.VariableScope):\n return value.name\n elif isinstance(value, six.string_types):\n return value\n else:\n raise ValueError(\"Not a variable scope: {}\".format(value))", "docstring": "Returns the name of the variable scope indicated by the given value.\n\nArgs:\nvalue: String, variable scope, or object with `variable_scope` attribute\n(e.g., Sonnet module).\n\nReturns:\nThe name (a string) of the corresponding variable scope.\n\nRaises:\nValueError: If `value` does not identify a variable scope.", "source": "juraj-google-style"}
1199{"code": "def _constrain_L2_grad(op, grad):\n \n inp = op.inputs[0]\n inp_norm = tf.norm(inp)\n unit_inp = inp / inp_norm\n\n grad_projection = dot(unit_inp, grad)\n parallel_grad = unit_inp * grad_projection\n\n is_in_ball = tf.less_equal(inp_norm, 1)\n is_pointed_inward = tf.less(grad_projection, 0)\n allow_grad = tf.logical_or(is_in_ball, is_pointed_inward)\n clip_grad = tf.logical_not(allow_grad)\n\n clipped_grad = tf.cond(clip_grad, lambda: grad - parallel_grad, lambda: grad)\n\n return clipped_grad", "docstring": "Gradient for constrained optimization on an L2 unit ball.\n\nThis function projects the gradient onto the ball if you are on the boundary\n(or outside!), but leaves it untouched if you are inside the ball.\n\nArgs:\nop: the tensorflow op we're computing the gradient for.\ngrad: gradient we need to backprop\n\nReturns:\n(projected if necessary) gradient.", "source": "juraj-google-style"}
1200{"code": "def GetFileSystem(self, path_spec):\n \n identifier = self._GetFileSystemCacheIdentifier(path_spec)\n return self._file_system_cache.GetObject(identifier)", "docstring": "Retrieves a file system object defined by path specification.\n\nArgs:\npath_spec (PathSpec): path specification.\n\nReturns:\nFileSystem: a file system object or None if not cached.", "source": "juraj-google-style"}
