code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, layer, connected = False, admin_on = True, power_on = True, fault = False, is_switch = True): <NEW_LINE> <INDENT> self.layer = layer <NEW_LINE> super(StructuredNode, self).__init__(is_switch=is_switch)
Init. @param layer layer within topo (int) @param connected actively connected to controller @param admin_on administratively on or off @param power_on powered on or off @param fault fault seen on node @param is_switch switch or host
625941f0d7e4931a7ee9e4b1
def init_eval_model(flags, base_model_type): <NEW_LINE> <INDENT> model = init_model_and_weights(flags, base_model_type) <NEW_LINE> model.eval() <NEW_LINE> return model
Initializes model and loads weights for evaluation Args: flags - configuration parameters base_model_type - type of base network model Returns: model - network model
625941f096565a6dacc8fc5a
def SetStateChangeHandler(self, handler:callable): <NEW_LINE> <INDENT> self.state_change_handler = handler
Setzt einen Handler der bei jeder Statusänderung des Boards gerufen wird. :param callable handler: Ein Callable das ein Dictionary wie in :meth:`GetState` als einzigen Parameter entgegennimmt. Kann auch ``None`` sein, das entspricht einem Entfernen des Handlers. .. seealso:: :meth:`tools.InstallStateChang...
625941f0f9cc0f698b140b87
def test_3090_correctlyOrdered( self ): <NEW_LINE> <INDENT> self.assertTrue( self.bbos.correctlyOrdered('GEN','EXO') ) <NEW_LINE> self.assertTrue( self.bbos.correctlyOrdered('GEN','LEV') ) <NEW_LINE> self.assertTrue( self.bbos.correctlyOrdered('GEN','REV') ) <NEW_LINE> self.assertTrue( self.bbos.correctlyOrdered('MAL',...
Test the correctlyOrdered function.
625941f056b00c62f0f14bee
def __iter__(self): <NEW_LINE> <INDENT> return zip(self.__slots__, self._to_tuple())
Yield pairs of (attribute_name, value). This allows using `dict(my_struct)`.
625941f091f36d47f21aca8a
@translator_api_blueprint.route("/apps/bundles/<language>/<target>/checkModifications", methods=["GET"]) <NEW_LINE> @requires_golab_api_login <NEW_LINE> @cross_origin() <NEW_LINE> @api <NEW_LINE> def check_modifications(language, target): <NEW_LINE> <INDENT> app_url = request.values.get('app_url') <NEW_LINE> update_use...
Retrieves the last modification date and the active users.
625941f0442bda511e8be9a1
def create_connection(db_file): <NEW_LINE> <INDENT> conn = None <NEW_LINE> try: <NEW_LINE> <INDENT> conn = sqlite3.connect(db_file) <NEW_LINE> return conn <NEW_LINE> <DEDENT> except Error as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> return conn
create a database connection to a SQLite database :param db_file: :return:
625941f07cff6e4e81117f17
def soft_iou(pred_tensor, labels, average=True, device=torch.device("cpu"), classes=21, ignore_index=255, ignore_background=True): <NEW_LINE> <INDENT> gt = labels.long().unsqueeze(1).to(device) <NEW_LINE> valid = gt != ignore_index <NEW_LINE> gt[gt == ignore_index] = 0 <NEW_LINE> valid = valid.float().to(device) <NEW_L...
Soft IoU score for semantic segmentation, based on 10.1109/ICCV.2017.372
625941f050485f2cf553d32d
@utils.arg('hostnameorid', metavar='<hostname or id>', help="Name or ID of host") <NEW_LINE> @utils.arg('ifnameoruuid', metavar='<interface name or uuid>', help="Name or UUID of interface") <NEW_LINE> def do_host_if_delete(cc, args): <NEW_LINE> <INDENT> ihost = ihost_utils._find_ihost(cc, args.hostnameorid) <NEW_LINE> ...
Delete an interface.
625941f044b2445a33932623
def __matmul__(self, other) -> 'Array': <NEW_LINE> <INDENT> current = self[:] <NEW_LINE> axes = self.axes <NEW_LINE> if not isinstance(other, (Array, np.ndarray)): <NEW_LINE> <INDENT> raise NotImplementedError(f"matrix multiplication not implemented for {type(other)}") <NEW_LINE> <DEDENT> if isinstance(other, np.ndarra...
Overrides operator @ for matrix multiplication. Notes ----- Only available with Python >= 3.5 Examples -------- >>> arr1d = ndtest(3) >>> arr1d a a0 a1 a2 0 1 2 >>> arr2d = ndtest((3, 3)) >>> arr2d a\b b0 b1 b2 a0 0 1 2 a1 3 4 5 a2 6 7 8 >>> arr1d @ arr1d # doctest: +SKIP 5 >>> arr1...
625941f0925a0f43d254a40e
def get_source_entity_hash(key, context): <NEW_LINE> <INDENT> if isinstance(context, list): <NEW_LINE> <INDENT> if context: <NEW_LINE> <INDENT> keys = [key] + context <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> keys = [key, ''] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if context: <NEW_LINE> <INDENT> key...
Term access url is the MD5 of 'key:context'
625941f091af0d3eaac9bfaf
def is_due(self, last_run_at): <NEW_LINE> <INDENT> return self.run_every.is_due(last_run_at)
Returns tuple of two items ``(is_due, next_time_to_run)``, where next time to run is in seconds. e.g. * ``(True, 20)``, means the Job should be run now, and the next time to run is in 20 seconds. * ``(False, 12)``, means the Job should be run in 12 seconds. You can override this to decide the interval at runtime...
625941f04a966d76dd5515a7
def __init__(self): <NEW_LINE> <INDENT> this = _DataModel.new_EMomentTensorMethodNames() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this
__init__(Seiscomp::DataModel::EMomentTensorMethodNames self) -> EMomentTensorMethodNames
625941f0009cb60464c6393e
def compare_cards(card1, card2): <NEW_LINE> <INDENT> val1 = card1 % 13 <NEW_LINE> val2 = card2 % 13 <NEW_LINE> if val1 > val2: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif val2 > val1: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
TODO: Given an integer card representation, return -1 for card1 < card2, 0 for card1 = card2, and 1 for card1 > card2
625941f0009cb60464c6393f
def test_squeeze_with_dim(self): <NEW_LINE> <INDENT> def test_f(a): <NEW_LINE> <INDENT> return torch.squeeze(a + a, 2) <NEW_LINE> <DEDENT> x = torch.randn(1, 3, 1, 2, 5, 1) <NEW_LINE> jitVsGlow(test_f, x, expected_fused_ops={"aten::squeeze"})
Test of the PyTorch aten::squeeze Node on Glow.
625941f0435de62698dfe1de
def prepare_network_operation(vca_client, operation): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> gateway = get_gateway( vca_client, ctx.target.node.properties['nat']['edge_gateway']) <NEW_LINE> public_ip = _obtain_public_ip(vca_client, ctx, gateway, operation) <NEW_LINE> private_ip = _create_ip_range(vca_client, gate...
create nat rules by rules from network node
625941f0d164cc61757832e1
def process_server_app_data_records(self,checkFinished=False): <NEW_LINE> <INDENT> bad_record_mac = 0 <NEW_LINE> if checkFinished: <NEW_LINE> <INDENT> check_mac = self.build_record_mac(True,self.decrypted_server_finished[0],hs) <NEW_LINE> if self.decrypted_server_finished[1] != check_mac: <NEW_LINE> <INDENT> print ("Wa...
Using the encrypted records in self.server_response_ciphertexts, containing the response from the server to a GET or POST request (the *first* request after the handshake), this function will process the response one record at a time. Each of these records is decrypted and reassembled into the plaintext form of the re...
625941f0004d5f362079a8c0
def bulk_delete(self, names, container=None, response_dict=None): <NEW_LINE> <INDENT> return self._retry(None, bulk_delete, names=names, container=container, response_dict=response_dict)
Wrapper for :func:`bulk_delete`
625941f01b99ca400220b045
@receiver(post_save, sender=Rma) <NEW_LINE> def rma_post_save_handler(sender, **kwargs): <NEW_LINE> <INDENT> from xml_helpers.lib import load_customer_to_redis <NEW_LINE> r = redis.StrictRedis(host='localhost', port=6379, db=settings.REDIS_DB) <NEW_LINE> customers = Customer.objects.all() <NEW_LINE> for c in customers:...
update ALL customers in redis database upon save. cannot just update single customer because old customer moved from will not update. can surgically update 2 customers (source and dest) but source is lost. :param sender: :param kwargs: :return:
625941f06e29344779a62ba2
def write_text_file_PatSet(olist:list, fname:str) -> bool: <NEW_LINE> <INDENT> rValue = False <NEW_LINE> try: <NEW_LINE> <INDENT> with open(fname, 'w+') as f: <NEW_LINE> <INDENT> f.write(PATSET_1_ROW + TAB + PATSET_TITLE + NL) <NEW_LINE> f.write(NL) <NEW_LINE> f.write(PATSET_3_ROW) <NEW_LINE> for row in range(len(olist...
write PatSet text file which is used to import into IGXL based test program
625941f0435de62698dfe1df
def neumannFunction(self, x, y): <NEW_LINE> <INDENT> alpha = -(numpy.sum(x) - numpy.dot(x.T, y))/numpy.dot(x**2, y) <NEW_LINE> f = 1/(1- alpha * x) <NEW_LINE> return f
Compute the Neumann kernel for a vector.
625941f010dbd63aa1bd3134
def __init__(self, part1, part1_position, part1_basis, part2, part2_position, part2_basis, name='LimitedBallLinkage'): <NEW_LINE> <INDENT> def part1_basis_f(q): <NEW_LINE> <INDENT> return part1_basis.Rotation(part1_basis.u, q[0], copy=True) .Rotation(part1_basis.v, q[1], copy=True) <NEW_LIN...
Allowed movements are: - a rotation around part1 basis u - a rotation around part1 basis v
625941f0de87d2750b86032b
def setArrayData(self, data, perspective=0): <NEW_LINE> <INDENT> if qt.qVersion() > "4.6": <NEW_LINE> <INDENT> self.beginResetModel() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.reset() <NEW_LINE> <DEDENT> self._array = data <NEW_LINE> self.assignDataFunction(perspective) <NEW_LINE> if len(data.shape) > 3: <NEW_...
setStackData(self, data, perspective=0) data is a 3D array dimension is the array dimension acting as index of images
625941f04f6381625f114fcc
def distance_features(x,a,i, max_mention_distance=5, max_token_distance=10): <NEW_LINE> <INDENT> f = defaultdict(float) <NEW_LINE> if a != i: <NEW_LINE> <INDENT> mention_distance = min(i - a, max_mention_distance) <NEW_LINE> token_distance = min(x[i].start_token - x[a].end_token, max_token_distance) <NEW_LINE> f['menti...
compute a set of distance features for antecedent a and mention i :param x: markable list for document :param a: antecedent index :param i: mention index :param max_mention_distance: upper limit on mention distance :param max_token_distance: upper limit on token distance :returns: dict of features :rtype: defaultdict
625941f015baa723493c450c
def from_json(self, s): <NEW_LINE> <INDENT> raise NotImplementedError()
de-serialize
625941f024f1403a926010f3
def test_amenity_dict(self): <NEW_LINE> <INDENT> amenity_dict = self.amenty.to_dict() <NEW_LINE> self.assertIn(amenity_dict, self.objects.values())
Test whjether new Amenity objects dict get added to objects
625941f04e696a04525c99df
def test_docker_services_unused_port(): <NEW_LINE> <INDENT> with mock.patch("subprocess.check_output") as check_output: <NEW_LINE> <INDENT> check_output.side_effect = [b"", b"", b""] <NEW_LINE> check_output.returncode = 0 <NEW_LINE> assert check_output.call_count == 0 <NEW_LINE> with get_docker_services( "docker-compos...
Complain loudly when the requested port is not used by the service.
625941f04e4d5625662d4961
def balanced_delimiter(string): <NEW_LINE> <INDENT> st = stackClass.Stack() <NEW_LINE> opener_dict = {")": "(", "]": "[", "}": "{"} <NEW_LINE> for char in string: <NEW_LINE> <INDENT> if char in "([{": <NEW_LINE> <INDENT> st.put(char) <NEW_LINE> <DEDENT> elif char in ")]}" and st.isEmpty() == False: <NEW_LINE> <INDENT> ...
>>> balanced_delimiter("hell(o)") True >>> balanced_delimiter("he[l]l{(o)}") True >>> balanced_delimiter("hell(o}") False >>> balanced_delimiter("hell(o})") False >>> balanced_delimiter("hell(o})(") False >>> balanced_delimiter("hell{(o})") False >>> balanced_delimiter("{}(hello!") False :param string: str :return: bo...
625941f0dc8b845886cb5ac9
def distLInf (a, b): <NEW_LINE> <INDENT> return max (abs (a[0] - b[0]), abs (a[1] - b[1]))
Utility method to compute the L-infinity distance between the given two coordinates.
625941f021a7993f00bc828c
def getHyphenation(self, word, **kwargs): <NEW_LINE> <INDENT> allParams = ['word', 'sourceDictionary', 'useCanonical', 'limit'] <NEW_LINE> params = locals() <NEW_LINE> for (key, val) in params['kwargs'].iteritems(): <NEW_LINE> <INDENT> if key not in allParams: <NEW_LINE> <INDENT> raise TypeError("Got an unexpected keyw...
Returns syllable information for a word Args: word, str: Word to get syllables for (required) sourceDictionary, str: Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. (optional) useCanonical, str: If true will try to return a correct word root ('cats' -&gt; 'cat')...
625941f0f9cc0f698b140b88
def evaluate_model(crf, X_dev, y_dev): <NEW_LINE> <INDENT> labels = list(crf.classes_) <NEW_LINE> labels.remove('O') <NEW_LINE> print("Predicting labels") <NEW_LINE> y_pred = crf.predict(X_dev) <NEW_LINE> print("Displaying accuracy") <NEW_LINE> metrics.flat_f1_score(y_dev, y_pred, average='weighted', labels=labels) <NE...
Evaluate the model Inputs: crf: trained CRF model X_dev: list of feature dicts for dev set y_dev: list of labels for dev set Returns: None (prints metrics)
625941f0bd1bec0571d90bc1
def getSignalHeader(self, chn): <NEW_LINE> <INDENT> return {'label': self.getLabel(chn), 'dimension': self.getPhysicalDimension(chn), 'sample_rate': self.getSampleFrequency(chn), 'physical_max':self.getPhysicalMaximum(chn), 'physical_min': self.getPhysicalMinimum(chn), 'digital_max': self.getDigitalMaximum(chn), 'digit...
Returns the header of one signal as dicts
625941f06fb2d068a760f638
def interval_validator(*, min_value=None, max_value=None, min_incl=True, max_incl=True): <NEW_LINE> <INDENT> if (min_value is not None and max_value is not None and not (min_value <= max_value)): <NEW_LINE> <INDENT> raise ValueError('min_value is greater than max_value' f' ({min_value} > {max_value})') <NEW_LINE> <DEDE...
Create a function that checks whether a value is in an interval. The type of the checked values must at least support the operators ``<`` (for ``*_incl=False``) or ``<=`` (for ``*_incl=True``). :param min_value: minimum value (``None`` means no limit) :param max_value: maximum value (``None`` means no limit) :param b...
625941f01d351010ab8560ac
def _get_date_only(self): <NEW_LINE> <INDENT> obj = self.timestamp.date() <NEW_LINE> return obj
Provides the date (without time). Used for agenda.
625941f07d43ff24873a3237
@shared_task() <NEW_LINE> def subscribe_user_to_basket(instance_id, newsletters=[]): <NEW_LINE> <INDENT> from mozillians.users.models import UserProfile <NEW_LINE> try: <NEW_LINE> <INDENT> instance = UserProfile.objects.get(pk=instance_id) <NEW_LINE> <DEDENT> except UserProfile.DoesNotExist: <NEW_LINE> <INDENT> instanc...
Subscribe a user to Basket. This task subscribes a user to Basket, if not already subscribed and then updates his data on the Phonebook DataExtension. The task retries on failure at most BASKET_TASK_MAX_RETRIES times and if it finally doesn't complete successfully, it emails the settings.BASKET_MANAGERS with details.
625941f0ec188e330fd5ad25
def predict(self, x_test, k=5, wt='distance'): <NEW_LINE> <INDENT> target = self.data_raw.shape[1]-1 <NEW_LINE> x_train = self.codebook.matrix[:, :target] <NEW_LINE> y_train = self.codebook.matrix[:, target] <NEW_LINE> clf = neighbors.KNeighborsRegressor(k, weights=wt) <NEW_LINE> clf.fit(x_train, y_train) <NEW_LINE> x_...
Similar to SKlearn we assume that we have X_tr, Y_tr and X_test. Here it is assumed that target is the last column in the codebook and data has dim-1 columns :param x_test: input vector :param k: number of neighbors to use :param wt: method to use for the weights (more detail in KNeighborsRegressor docs) :returns:...
625941f031939e2706e4d3f4
def checkio(data): <NEW_LINE> <INDENT> mini = False <NEW_LINE> may = False <NEW_LINE> num = False <NEW_LINE> res = False <NEW_LINE> if(len(data) >= 10): <NEW_LINE> <INDENT> for x in data: <NEW_LINE> <INDENT> if(x.islower()): <NEW_LINE> <INDENT> mini = True <NEW_LINE> <DEDENT> if(x.isupper()): <NEW_LINE> <INDENT> may = ...
Check string input for password uses
625941f0c432627299f051dc
def valid_processor_options(processors=None): <NEW_LINE> <INDENT> if processors is None: <NEW_LINE> <INDENT> processors = [ dynamic_import(p) for p in tuple(settings.THUMBNAIL_PROCESSORS) + tuple(settings.THUMBNAIL_SOURCE_GENERATORS)] <NEW_LINE> <DEDENT> valid_options = set(['size', 'quality', 'subsampling']) <NEW_LINE...
Return a list of unique valid options for a list of image processors (and/or source generators)
625941f0cc0a2c11143dd423
def set_image(self, url): <NEW_LINE> <INDENT> self.image = {'url': url} <NEW_LINE> return self
Sets the image of the embed
625941f099cbb53fe6793176
def __getattr__(self, attr): <NEW_LINE> <INDENT> fixed_attr = "%s_%s" % (self.resource_name, attr) <NEW_LINE> actual_callable_op = getattr(self.actual_resource, fixed_attr) <NEW_LINE> param_name = attr.replace("Get", "").replace("Set", "")[0].lower() <NEW_LINE> return WrappedCallableOp(actual_callable_op, param_name)
Convert XxxxYyyy to Resource_XxxxYyyy, e.g. GetBrightness --> State_GetBrightness. The former is easier to use.
625941f06e29344779a62ba3
def store(self, val, ptr): <NEW_LINE> <INDENT> pointee = ptr.type[:-1] <NEW_LINE> val = self.cast(val, pointee) <NEW_LINE> op = Store(val, ptr) <NEW_LINE> self.basic_block.operations.append(op) <NEW_LINE> return op
Store val to ptr
625941f073bcbd0ca4b2c607
def test_request(self): <NEW_LINE> <INDENT> self.assertEqual(self.__message.request({'type': 'get_post_count'}), self.__post.getCount()) <NEW_LINE> self.assertEqual(self.__message.request({'type': 'get_all_post'}), self.__post.getAll()) <NEW_LINE> self.assertEqual(self.__message.request({'type': 'get_post_by_id'}), sel...
测试message.Message.request()
625941f0cad5886f8bd2756a
def test_description_max_length(self): <NEW_LINE> <INDENT> project = Project.objects.get(id=1) <NEW_LINE> max_length = project._meta.get_field("description").max_length <NEW_LINE> self.assertEqual(max_length,255)
测试pname的最大长度
625941f0a05bb46b383ecdae
@app.route('/DeleteArea', methods=['DELETE']) <NEW_LINE> def CallDeleteArea(): <NEW_LINE> <INDENT> interface = { "AreaName" : str, "WellList" : list } <NEW_LINE> pkg, success, msg = InitializePayload(request, interface) <NEW_LINE> if success: <NEW_LINE> <INDENT> AreaName = pkg['AreaName'] <NEW_LINE> WellList = pkg['Wel...
Interface Package Description
625941f0fff4ab517eb2f9d2
def test_event_filter_no_title(self): <NEW_LINE> <INDENT> self.event_creation() <NEW_LINE> res = self.client().get( '/api/events/all?title=Hiking Mt Kenya&location=Naivasha' ) <NEW_LINE> self.assertEqual(res.status_code, 404) <NEW_LINE> self.assertIn('No events found', str(res.data))
Test API can filter an event by location and title with wrong title (GET request).
625941f09b70327d1c4e136a
def test_top__invalid_value(self): <NEW_LINE> <INDENT> r = Rect(0, 0, 1, 1) <NEW_LINE> for value in (None, [], "1", (1,), [1, 2, 3]): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> r.top = value
Ensures the top attribute handles invalid values correctly.
625941f0283ffb24f3c55e8d
def get_country_code(addr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return geoip.country(addr).country.iso_code <NEW_LINE> <DEDENT> except (TypeError, NameError): <NEW_LINE> <INDENT> return None
Get the ISO country code from a client IP address.
625941f0e5267d203edce228
def link_queue_to_worker(self): <NEW_LINE> <INDENT> self.pika_connector.declare_permanent_queues(self.accepted_keys, self.exchange_name, self.get_queue_name, self.process_order) <NEW_LINE> return
Declare queues in system and makes the worker listen to message coming from these queues. Queues are durable, meaning they survive through crashes of RabbitMQ server and of Worker
625941f0a8ecb033257d365d
def __delitem__(self, key, dict_delitem=dict.__delitem__, reindex=True): <NEW_LINE> <INDENT> key = self._keychecker(key, mode=1) <NEW_LINE> value = self[key] <NEW_LINE> self.changed.pop(key, None) <NEW_LINE> self.names[value.name].remove(value.id) <NEW_LINE> if not self.names[value.name]: <NEW_LINE> <INDENT> del self.n...
si[key] -> si[key*] -> value
625941f07047854f462a1995
def characterizeAttributes(self, rawData): <NEW_LINE> <INDENT> print("DataManagement: Characterizing Attributes...") <NEW_LINE> attributeID = 0 <NEW_LINE> for att in range(len(rawData[0])): <NEW_LINE> <INDENT> if att != self.instanceIDRef and att != self.phenotypeRef: <NEW_LINE> <INDENT> for inst in range(len(rawData))...
Determine range (if continuous) or states (if discrete) for each attribute and saves this information
625941f0925a0f43d254a40f
def initFilesVisit(self, obj): <NEW_LINE> <INDENT> if self.__config.get("serialize", "XMLDefaultFileName") == "True": <NEW_LINE> <INDENT> namespace = "".join(obj.get_namespace().split("::")) <NEW_LINE> filename = ( namespace + obj.get_name() + self.__config.get("serialize", "SerializableH") ) <NEW_LINE> PRINT.info( "Ge...
Defined to generate files for generated code products. @param obj: the instance of the concrete element to operation on.
625941f0b5575c28eb68e598
def set_factors(self): <NEW_LINE> <INDENT> weight_list = [] <NEW_LINE> factor_list = [] <NEW_LINE> probability_list = [] <NEW_LINE> for facet in self.facet_list: <NEW_LINE> <INDENT> if len(facet) == 1: <NEW_LINE> <INDENT> weight_list.append(-1) <NEW_LINE> probability_list.append(self.set_probabilities_2x1()) <NEW_LINE>...
Iterates through self.facet_list and sets a factor to each facet and coefficients for the factor. The coefficients for each factors are determined randomly using set_probabilities_2x2 and set_probabilities_2x2x2. TODO : Incomplete. So far it can only manage facets of size 2 to 3 inclusively. :return: None. This functio...
625941f03eb6a72ae02eca80
def get_user_parameters(job): <NEW_LINE> <INDENT> return json.loads( job["data"]["actionConfiguration"]["configuration"]["UserParameters"] )
Returns the user parameters that were defined in CodePipeline.
625941f0d10714528d60027d
def AddUsersToOrganization(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
625941f0851cf427c661aa9c
@when('apache-bigtop-plugin.hdfs.installed') <NEW_LINE> @when('hadoop-plugin.joined', 'namenode.joined') <NEW_LINE> @when_not('namenode.ready') <NEW_LINE> def send_nn_spec(principal, namenode): <NEW_LINE> <INDENT> bigtop = Bigtop() <NEW_LINE> namenode.set_local_spec(bigtop.spec())
Send our plugin spec so the namenode can become ready.
625941f0091ae356686674e7
def add_node(cfg, id_node, id_process = None, req_host_cfg = None, functionality = None, py_module = None, state_type = None, config = None): <NEW_LINE> <INDENT> cfg_node = dict() <NEW_LINE> if id_process is not None: <NEW_LINE> <INDENT> cfg_node['process'] = id_process <NEW_LINE> <DEDENT> else: <NEW_...
Mutate the config structure to add a new node.
625941f0236d856c2ad44d75
def getRepresentationForCollection(self): <NEW_LINE> <INDENT> feat_data = self.getOptionQueryValues() <NEW_LINE> feat_data['feature'] = self.name <NEW_LINE> return feat_data
Creates a dict representation of the FeatureManager's composition.
625941f063b5f9789fde7678
def _encode(self, value): <NEW_LINE> <INDENT> sign_int = int(value) <NEW_LINE> unsign_int = sign_int + 8192 <NEW_LINE> lower_byte = unsign_int & 0x007F <NEW_LINE> higher_byte = ((unsign_int & 0x3F80) << 1) <NEW_LINE> self.enc_byte = hex(lower_byte + higher_byte)
Gets a signed integer and return a 4 character string, such that after the encoding is complete, the most significant bit of each byte has been cleared. Argument: value {string} -- integer input value to be encoded. Returns: Encoded 2-byte string.
625941f0596a89723608a04b
def insert(self, item): <NEW_LINE> <INDENT> if self._modCount != self._backingStore.getModCount(): <NEW_LINE> <INDENT> raise AttributeError("List has been modified illegally.") <NEW_LINE> <DEDENT> if self._lastItemPos is None: <NEW_LINE> <INDENT> self._backingStore.add(item) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Preconditions: The list has not been modified except by this iterator's mutators. Adds item to the end if the current position is undefined, or inserts it at that position.
625941f0dd821e528d63b737
@contextmanager <NEW_LINE> def transmit_learner_data_context(command_kwargs=None, certificate=None, self_paced=False, end_date=None, passed=False): <NEW_LINE> <INDENT> if command_kwargs is None: <NEW_LINE> <INDENT> command_kwargs = {} <NEW_LINE> <DEDENT> testcase = TestTransmitLearnerData(methodName='setUp') <NEW_LINE>...
Sets up all the data and context wrappers required to run the transmit_learner_data management command.
625941f0cb5e8a47e48b8033
def custom_sorting(self, word): <NEW_LINE> <INDENT> word = word.replace(u'é', u'e') <NEW_LINE> word = word.replace(u'è', u'e') <NEW_LINE> word = word.replace(u'ê', u'e') <NEW_LINE> word = word.replace(u'ë', u'e') <NEW_LINE> word = word.replace(u'à', u'a') <NEW_LINE> word = word.replace(u'â', u'a') <NEW_LINE> word = wor...
idea taken from http://code.activestate.com/recipes/576507-sort-strings-containing-german-umlauts-in-correct-/ It's a workaround for OSX
625941f016aa5153ce362a0b
def get_clean_exclusions(self, sb): <NEW_LINE> <INDENT> return CleanExclusions()
This is the default exclusion object which will be passed to the clean method for all builders except for the CMake builder.
625941f0d4950a0f3b08c8d9
def test_multi_dim_sm_gets_phys_and_log(): <NEW_LINE> <INDENT> ie_dc_dict = [{'dc:title': 'Test deposit'}] <NEW_LINE> mets = mdf.build_mets( ie_dmd_dict=ie_dc_dict, pres_master_dir=os.path.join(CURRENT_DIR, 'data', 'test_batch_5'), input_dir=os.path.join(CURRENT_DIR, 'data', 'test_batch_5'), digital_original=True, stru...
Multi-level structmaps get both SM types when "BOTH" is selected
625941f016aa5153ce362a0c
def remove_message(self, path): <NEW_LINE> <INDENT> self.open(rw=True).remove_message(path)
Remove the given message from the notmuch index. :param path: path to the message :type path: str
625941f04428ac0f6e5bad8a
def edit_timezone(self): <NEW_LINE> <INDENT> button = self.find_element(*self._edit_timezone_button_locator) <NEW_LINE> Utility.click_option(self.driver, element=button) <NEW_LINE> sleep(0.25) <NEW_LINE> modal_root = self.driver.execute_script(GET_ROOT.format('dialog')) <NEW_LINE> return ChangeCourseTimezone(self.page,...
Click on the edit icon nex to the course timezone. :return: the change course timezone modal :rtype: :py:class:`ChangeCourseTimezone`
625941f08c3a873295158955
def __new__(cls, value): <NEW_LINE> <INDENT> if isinstance(value, type_str): <NEW_LINE> <INDENT> return type_str.__new__(cls, value) <NEW_LINE> <DEDENT> return type_str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
Create a new NavigableString. When unpickling a NavigableString, this method is called with the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be passed in to the superclass's __new__ or the superclass won't know how to handle non-ASCII characters.
625941f0460517430c394708
def merge_rules(rules_dict_list, default_installers): <NEW_LINE> <INDENT> combined_rules = {} <NEW_LINE> for rules in reversed(rules_dict_list): <NEW_LINE> <INDENT> for xylem_key, new_os_dict in rules.items(): <NEW_LINE> <INDENT> if xylem_key not in combined_rules: <NEW_LINE> <INDENT> combined_os_dict = copy_os_dict( n...
Merge list of rules dicts into one. The rules dicts are merged such that the entries in the front of ``rules_dict_list`` take precedence. It is assumed that all rules dicts are fully expanded and have valid structure. The rules dicts are deep copied up to the installer rules, which are themselves not deep copied. The...
625941f0d486a94d0b98e6d9
def help(self, command): <NEW_LINE> <INDENT> raise NotImplementedError
EXAMPLES:: sage: lisp.help('setq') Traceback (most recent call last): ... NotImplementedError
625941f045492302aab5e85c
def decision_function(self,X,y=None): <NEW_LINE> <INDENT> ss = (1.0/(self.anomaly_score(X,y)+1e-10) - self.threshold_) <NEW_LINE> return ss
Returns a measure of anomaly (the log probability of the data) from smallest (most anomalous) to high (least anomalous). :param X: an numpy array :param y: an numpy array or None :return: numpy array
625941f0be383301e01b5a0d
def download(url, dst): <NEW_LINE> <INDENT> if os.path.isfile(dst): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> os.makedirs(os.path.dirname(dst), exist_ok=True) <NEW_LINE> with open(dst, 'wb') as f: <NEW_LINE> <INDENT> LOGGER.info('Downloading %s to %s' % (url, dst)) <NEW_LINE> response = requests.get(url, stream=Tr...
Downloads a file from a url to the given destination with % finished bar. :param url: The url. :param dst: The destination.
625941f0462c4b4f79d1dc62
def dar_elapsed_total( self ): <NEW_LINE> <INDENT> start = min( self.as_list( 'DAR', 'START', formatter=int ), default=0 ) <NEW_LINE> end = max (self.as_list( 'DAR', 'END', formatter=int ), default=0 ) <NEW_LINE> if end < 1 or start < 1: <NEW_LINE> <INDENT> raise UserWarning( 'insufficient time data' ) <NEW_LINE> <DEDE...
Total runtime for all dars to complete Returns: namedtuple( total_runtime )
625941f03c8af77a43ae3d3a
def __init__(self, instanceName): <NEW_LINE> <INDENT> self.instanceName = instanceName <NEW_LINE> self.connection = []
instanceName is the Name of the node. No check is made here that the name is not already in use.
625941f0d164cc61757832e2
def _ensure_can_send(thing): <NEW_LINE> <INDENT> if isinstance(thing, str): <NEW_LINE> <INDENT> raise ValueError('Cannot send type str. ' 'Maybe you left out a ".encode()" somewhere?')
It's easy to accidentally pass in a str instead of bytes when send()ing. This gives a more informative message if a ``str`` was accidentally passed to a send method.
625941f0566aa707497f4af3
def tickSize(self, req_id: int, field: int, size: int): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> request = self._requests.get(req_id) <NEW_LINE> if request is None: <NEW_LINE> <INDENT> logging.warning("tickSize[req_id= %d] with no associated request - ignored." % req_id) <NEW_LINE> return <NEW_LINE> <DE...
tickSize(EWrapper self, TickerId tickerId, TickType field, int size)
625941f099fddb7c1c9de921
def _find_already_built_wheel(metadata_directory): <NEW_LINE> <INDENT> if not metadata_directory: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> metadata_parent = os.path.dirname(metadata_directory) <NEW_LINE> if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)): <NEW_LINE> <INDENT> return None <NEW_L...
Check for a wheel already built during the get_wheel_metadata hook.
625941f030c21e258bdfaa37
def hailstone(n): <NEW_LINE> <INDENT> count = 1 <NEW_LINE> print(n) <NEW_LINE> if n == 1: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif n % 2 == 0: <NEW_LINE> <INDENT> count += hailstone(n // 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count += hailstone(n*3+1) <NEW_LINE> <DEDENT> return count
Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7
625941f0d8ef3951e3243ad1
def splitSpace(file_list): <NEW_LINE> <INDENT> word="" <NEW_LINE> list1=[] <NEW_LINE> list2=[] <NEW_LINE> for index in range(len(file_list)): <NEW_LINE> <INDENT> for item in range(len(file_list[index])): <NEW_LINE> <INDENT> if file_list[index][item] != ' ': <NEW_LINE> <INDENT> word += file_list[index][item] <NEW_LINE> ...
This function splits whitespace between characters and puts them into a list. Time complexity: Best: O(NM) Worst: O(NM) Space complexity: Best: O(NM) Worst: O(NM) Error handle: None Return: A list with lists of the items in the row from data in the database. Parameter: file_list, ...
625941f0293b9510aa2c3823
def __init__(self, initial=None, universe=None): <NEW_LINE> <INDENT> super(intspanlist, self).__init__() <NEW_LINE> if initial: <NEW_LINE> <INDENT> self.extend(initial) <NEW_LINE> <DEDENT> if universe is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> restIndex = self.index(TheRest) <NEW_LINE> remaining = sorted...
Construct a new ``intspanlist`` :param iterable|str initial: Optional initial list of items. :returns: the intspanlist :rtype: intspanlist
625941f00a366e3fb873edb3
def get_tokenizing_function(self, wordtable_type): <NEW_LINE> <INDENT> if wordtable_type == CFG_BIBINDEX_INDEX_TABLE_TYPE["Words"]: <NEW_LINE> <INDENT> return self.tokenize_for_words <NEW_LINE> <DEDENT> elif wordtable_type == CFG_BIBINDEX_INDEX_TABLE_TYPE["Pairs"]: <NEW_LINE> <INDENT> return self.tokenize_for_pairs <NE...
Picks correct tokenize_for_xxx function depending on type of tokenization (wordtable_type)
625941f0d7e4931a7ee9e4b3
def get_game_expand_parameters(expand_str): <NEW_LINE> <INDENT> if not expand_str: <NEW_LINE> <INDENT> return (0, 0) <NEW_LINE> <DEDENT> expand = expand_str.split(',') <NEW_LINE> scores = 0 <NEW_LINE> similars = 0 <NEW_LINE> for e in expand: <NEW_LINE> <INDENT> if scores == 0: <NEW_LINE> <INDENT> m = re.match(r'^highsc...
Finds the parameters of the expand query string option. Args: expand_str: the value of the expand option (e.g. 'sales,highscores(10),similars(5)') Returns: a 2 dimensional tuple containing [0]: highscores parameter 0..INT_MAX [1]: similars parameter 0..INT_MAX
625941f082261d6c526aba3b
def rotate(self, matrix): <NEW_LINE> <INDENT> if not len(matrix): <NEW_LINE> <INDENT> return matrix <NEW_LINE> <DEDENT> n = len(matrix) <NEW_LINE> for i in range(n//2): <NEW_LINE> <INDENT> for j in range(i,n-i-1): <NEW_LINE> <INDENT> prev = matrix[i][j] <NEW_LINE> matrix[i][j] = matrix[n -j -1][i] <NEW_LINE> matrix[n-1...
Do not return anything, modify matrix in-place instead.
625941f063d6d428bbe44a84
def makeDict(categories): <NEW_LINE> <INDENT> d={} <NEW_LINE> index=0 <NEW_LINE> for cat in categories: <NEW_LINE> <INDENT> d[cat]=index <NEW_LINE> index+=1 <NEW_LINE> <DEDENT> return d
:param categories: list of possible categories in a categorical variable :return: returns a dictionary which maps a string into a unique integer
625941f07c178a314d6ef9fc
def test_fields_exclude_fields(self): <NEW_LINE> <INDENT> converter = DocumentFieldConverter( self.document_class, exclude=['body', 'author'] ) <NEW_LINE> converter.convert = self.convert <NEW_LINE> self.assertEqual({ 'title': 'title-value', 'timestamp': 'timestamp-value', }, converter.fields)
Test :py:meth:`.DocumentFieldConverter.fields` with excluded fields.
625941f0851cf427c661aa9d
def forward(self, src, tgt, lengths, dec_state=None): <NEW_LINE> <INDENT> tgt = tgt[:-1] <NEW_LINE> enc_hidden, context = self.encoder(src, lengths) <NEW_LINE> enc_state = self.decoder.init_decoder_state(src, context, enc_hidden) <NEW_LINE> out, dec_state, attns = self.decoder(tgt, context, enc_state if dec_state is No...
Forward propagate a `src` and `tgt` pair for training. Possible initialized with a beginning decoder state. Args: src (:obj:`Tensor`): a source sequence passed to encoder. typically for inputs this will be a padded :obj:`LongTensor` of size `[len x batch x features]`. however, may be an ...
625941f0d4950a0f3b08c8da
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') <NEW_LINE> parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) <NEW_LINE> parser.add_argument('--cfg', dest='cfg_file', help='optional config file', defa...
Parse input arguments
625941f04c3428357757c8b7
def get_aux(url): <NEW_LINE> <INDENT> from requests import get <NEW_LINE> from scrapy.selector import Selector <NEW_LINE> return Selector(text=get(url).text)
Get auxiliary page and return Selector
625941f0e8904600ed9f24ca
def writeOnlyActorsDirectors(filename, moviesDict, usersDict, ranking=None, actors=True, directors=True): <NEW_LINE> <INDENT> CSV_CHAR = ',' <NEW_LINE> try: <NEW_LINE> <INDENT> fh = open(filename, 'w') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> header = ['tid', 'pid'] <NEW_LINE> lin...
Write a transaction file ready to be process by R. The file will write
625941f050812a4eaa59c8af
def encode_test_case(test_case): <NEW_LINE> <INDENT> if test_case is not None: <NEW_LINE> <INDENT> return test_case.replace(',', ',,') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
Encode test case name to escape commas. Avoids that test case names including commas are interpreted as several test cases in the comma separated list of enabled test cases included in the runner_cfg string.
625941f024f1403a926010f4
def unhook(self): <NEW_LINE> <INDENT> if event.contains(Engine, "commit", self._commit): <NEW_LINE> <INDENT> event.remove(Engine, "commit", self._commit) <NEW_LINE> <DEDENT> if event.contains(Engine, "commit_twophase", self._commit): <NEW_LINE> <INDENT> event.remove(Engine, "commit_twophase", self._commit)
Unhooks commit events.
625941f085dfad0860c3b3f0
def social_tenure_bind_to_node(self, base_node): <NEW_LINE> <INDENT> str_data = self.entity_read.social_tenure_attributes() <NEW_LINE> if self.check_str_supports_multiple_entities(): <NEW_LINE> <INDENT> str_data['party'] = 'LOOKUP' <NEW_LINE> str_data['spatial_unit'] = 'LOOKUP' <NEW_LINE> <DEDENT> for str_node, str_dat...
Add social tenure parameters to the bind section :param base_node: string :return: QDomnode
625941f044b2445a33932625
def _use_global_cache(self, key, options=None): <NEW_LINE> <INDENT> if self.global_cache is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> flag = options.use_global_cache if options else None <NEW_LINE> if flag is None: <NEW_LINE> <INDENT> flag = self.global_cache_policy(key) <NEW_LINE> <DEDENT> if flag is ...
Return whether to use the global cache for this key.
625941f0be383301e01b5a0e
def get_enemy_img(): <NEW_LINE> <INDENT> img_enemies = [ img_bee, img_pheonix, img_gremlin, img_scorpion, img_catcher_g, img_catcher_b, img_mosquito, img_airplane, ] <NEW_LINE> return img_enemies[random.randint(0, len(img_enemies))-1]
randomly select enemy's sprite object
625941f03617ad0b5ed6848a
def version(self): <NEW_LINE> <INDENT> return self._version
Returns the received server version. :returns: server version (string)
625941f0ec188e330fd5ad26
def get_bandwidth(self): <NEW_LINE> <INDENT> return self.curr_amount/(self.end - self.start)
simulates bandwidth format :return: void
625941f0a79ad161976cc6d9
def followStroke(self, event): <NEW_LINE> <INDENT> if(self.lastPos == event.position): return <NEW_LINE> self.activePoints = self.activePoints+(event.position,) <NEW_LINE> self.drawTo(event.position)
Takes a mouseMove event and continues to draw the current stroke
625941f010dbd63aa1bd3135
def waveform_to_examples(data, sample_rate): <NEW_LINE> <INDENT> if len(data.shape) > 1: <NEW_LINE> <INDENT> data = np.mean(data, axis=1) <NEW_LINE> <DEDENT> if sample_rate != params.SAMPLE_RATE: <NEW_LINE> <INDENT> data = resampy.resample(data, sample_rate, params.SAMPLE_RATE) <NEW_LINE> <DEDENT> log_mel = mel_feature...
Converts audio waveform into an array of examples for VGGish. Args: data: np.array of either one dimension (mono) or two dimensions (multi-channel, with the outer dimension representing channels). Each sample is generally expected to lie in the range [-1.0, +1.0], although this is not required. sam...
625941f03c8af77a43ae3d3b
def request(self, path, request, body=None, **kwargs): <NEW_LINE> <INDENT> out_hdrs = dict.copy(self.headers) <NEW_LINE> if kwargs.get("accept"): <NEW_LINE> <INDENT> out_hdrs['accept'] = kwargs.get("accept") <NEW_LINE> <DEDENT> if body: <NEW_LINE> <INDENT> if isinstance(body, dict): <NEW_LINE> <INDENT> body = str(json....
Make an HTTP request and return the results :param path: Path used with the initialized URL to make a request :param request: HTTP request type (GET, POST, PUT, DELETE) :param body: HTTP body of request :key accept: Set HTTP 'Accept' header with this value :key base_path: Override the base_path for this request :key c...
625941f0d99f1b3c44c67b17
def isPersistent(self, key: str) -> bool: <NEW_LINE> <INDENT> return self.getFlags(key) & NT_PERSISTENT != 0
Returns whether the value is persistent through program restarts. :param key: the key name .. versionadded:: 2017.0.0
625941f0498bea3a759ba041
def show(request, number): <NEW_LINE> <INDENT> return HttpResponse(f'placeholder to display blog number {number}')
Displays the content of a blog. Parameters: request (django.shortcuts.HttpRequest): The request made when accessing the page number (int): The id of the blog to display Returns: A django.shortcuts.HttpResponse with the requested blog
625941f0d18da76e23532a71
def __init__(self, experimental_info_pickle): <NEW_LINE> <INDENT> self._exper_info = pickle.load(open(experimental_info_pickle))
:param experimental_info_pickle: str, name of the pickle file
625941f04e696a04525c99e1