Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
357,800
def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False): indices = [] for x in range(first_index, second_index + 1): if tiles_34[x] > 0: indices.extend([x] * tiles_34[x]) if not indices: return [] ...
Find and return all valid set combinations in given suit :param tiles_34: :param first_index: :param second_index: :param hand_not_completed: in that mode we can return just possible shi\pon sets :return: list of valid combinations
357,801
def get_data_for_model(self, args, kwargs): kwargs_from_invocation = self.get_raw_data() args_from_invocation = deque(self.path_args) defaults = kwargs values = args + list(kwargs.keys()) output = {} raw = False for i, field in enumerate(values): ...
In comes args and kwargs expected for the model. Out comes the data from this invocation that will go to the model. In other words, this function does the "data negotiation" between the controller and the model.
357,802
def convert_docx_to_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str: if True: text = with get_filelikeobject(filename, blob) as fp: for xml in gen_xml_files_from_docx(fp): text += docx_text_from...
Converts a DOCX file to text. Pass either a filename or a binary object. Args: filename: filename to process blob: binary ``bytes`` object to process config: :class:`TextProcessingConfig` control object Returns: text contents Notes: - Old ``docx`` (https://pypi.py...
357,803
def _parse_block(self, parser, allow_pluralize): referenced = [] buf = [] while 1: if parser.stream.current.type == : buf.append(parser.stream.current.value.replace(, )) next(parser.stream) elif parser.stream.current.type == : ...
Parse until the next block tag with a given name.
357,804
def _load_paths(self, paths, depth=0): if depth > self.MAX_DEPTH: return for path in paths: try: if not path: continue if depth == 0: path = os.path.expanduser(pa...
Goes recursevly through the given list of paths in order to find and pass all preset files to ```_load_preset()```
357,805
def within_ipv4_range(self, field, values): v = [ % part for iprange in values for part in iprange.split()] self.update_filter(.format(field, .join(v)))
Add an IP range network filter for relevant address fields. Range (between) filters allow only one range be provided. :param str field: name of field to filter on. Taken from 'Show Filter Expression' within SMC. :param list values: IP range values. Values would be a list of ...
357,806
def search(self, word, d, allow_spaces=True, return_cost=True): if not all((c in self.alphabet or (c == " " and self.allow_spaces)) for c in word): return [] return self._trie_search( word, d, allow_spaces=allow_spaces, return_cost=return...
Finds all dictionary words in d-window from word
357,807
def make_response(self, content, code=200, headers=None): if headers: for header in headers: self.headers[header] = headers[header] return make_response(content, code, self.headers)
Wrapper around Flask.make_response which also adds any local headers.
357,808
def replace(key, value, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN): * if not isinstance(time, six.integer_types): raise SaltInvocationError(time\) if not isinstance(min_compress_len, ...
Replace a key on the memcached server. This only succeeds if the key already exists. This is the opposite of :mod:`memcached.add <salt.modules.memcached.add>` CLI Example: .. code-block:: bash salt '*' memcached.replace <key> <value>
357,809
def addModlist(entry: dict, ignore_attr_types: Optional[List[str]] = None) -> Dict[str, List[bytes]]: ignore_attr_types = _list_dict(map(str.lower, (ignore_attr_types or []))) modlist: Dict[str, List[bytes]] = {} for attrtype in entry.keys(): if attrtype.lower() in ignore_attr_types: ...
Build modify list for call of method LDAPObject.add()
357,810
def create_dataset(self, dataset_id, friendly_name=None, description=None, access=None, location=None, project_id=None): project_id = self._get_project_id(project_id) try: datasets = self.bigquery.datasets() dataset_data = self.dataset...
Create a new BigQuery dataset. Parameters ---------- dataset_id : str Unique ``str`` identifying the dataset with the project (the referenceID of the dataset, not the integer id of the dataset) friendly_name: str, optional A human readable nam...
357,811
def show_items(self, cursor, items): if not items : return self.cancel_completion() strng = text.columnize(items) self._console_widget._fill_temporary_buffer(cursor, strng, html=False)
Shows the completion widget with 'items' at the position specified by 'cursor'.
357,812
def follower_num(self): href = re_collection_url_split.match(self.url).group(1) return int(self.soup.find(, href=href + ).text)
获取关注此收藏夹的人数. :return: 关注此收藏夹的人数 :rtype: int
357,813
def splits(cls, fields, root=".data", train="train.txt", test="test.txt", validation_frac=0.1, **kwargs): train, test = super(CoNLL2000Chunking, cls).splits( fields=fields, root=root, train=train, test=test, separator=, **kwargs) sort_key = trai...
Downloads and loads the CoNLL 2000 Chunking dataset. NOTE: There is only a train and test dataset so we use 10% of the train set as validation
357,814
def createDataFromFile(self, filePath, inputEncoding = None, defaultFps = None): file_ = File(filePath) if inputEncoding is None: inputEncoding = file_.detectEncoding() inputEncoding = inputEncoding.lower() videoInfo = VideoInfo(defaultFps) if defaultFps is not Non...
Fetch a given filePath and parse its contents. May raise the following exceptions: * RuntimeError - generic exception telling that parsing was unsuccessfull * IOError - failed to open a file at given filePath @return SubtitleData filled with non-empty, default datafields. Client should...
357,815
def Flash(self, partition, timeout_ms=0, info_cb=DEFAULT_MESSAGE_CALLBACK): return self._SimpleCommand(b, arg=partition, info_cb=info_cb, timeout_ms=timeout_ms)
Flashes the last downloaded file to the given partition. Args: partition: Partition to overwrite with the new image. timeout_ms: Optional timeout in milliseconds to wait for it to finish. info_cb: See Download. Usually no messages. Returns: Response to a downloa...
357,816
def remove(self, i): if i < 1 or i > self.rally_count(): print("Invalid rally point number %u" % i) self.rally_points.pop(i-1) self.reindex()
remove a rally point
357,817
def create_dict_subelement(root, subelement, content, **kwargs): attribs = kwargs.get(, None) namespace = kwargs.get(, None) key = subelement for degree_order_key in DEGREE_ORDER: for descriptor, value in content.items(): if descriptor == degree_order_key: ...
Create a XML subelement from a Python dictionary.
357,818
def _grab_crl(user_agent, url, timeout): request = Request(url) request.add_header(, ) request.add_header(, user_agent) response = urlopen(request, None, timeout) data = response.read() if pem.detect(data): _, _, data = pem.unarmor(data) return crl.CertificateList.load(data)
Fetches a CRL and parses it :param user_agent: A unicode string of the user agent to use when fetching the URL :param url: A unicode string of the URL to fetch the CRL from :param timeout: The number of seconds after which an HTTP request should timeout :return: An as...
357,819
def iter(self): upperCase = self._upperCase for _file in self._files: with asHandle(_file) as fp: records = SeqIO.parse(fp, ) while True: try: record = next(records) except StopIteration:...
Iterate over the sequences in self.file_, yielding each as an instance of the desired read class. @raise ValueError: If the input file has an odd number of records or if any sequence has a different length than its predicted secondary structure.
357,820
def _idle_register_view(self, view): assert(self.view is None) self.view = view if self.handlers == "class": for name in dir(self): when, _, what = partition(name, ) widget, _, signal = partition(what, ) if when == "on": ...
Internal method that calls register_view
357,821
def deleted(self, base: pathlib.PurePath = pathlib.PurePath(), include_children: bool = True, include_directories: bool = True) -> Iterator[str]: if self.is_deleted: yield str(base / self.left.name)
Find the paths of entities deleted between the left and right entities in this comparison. :param base: The base directory to recursively append to entities. :param include_children: Whether to recursively include children of deleted directories. These are thems...
357,822
def command_canonize(string, vargs): try: ipa_string = IPAString( unicode_string=string, ignore=vargs["ignore"], single_char_parsing=vargs["single_char_parsing"] ) print(vargs["separator"].join([(u"%s" % c) for c in ipa_string])) except ValueError...
Print the canonical representation of the given string. It will replace non-canonical compound characters with their canonical synonym. :param str string: the string to act upon :param dict vargs: the command line arguments
357,823
def get_organisation_information(self, query_params=None): return self.fetch_json( uri_path=self.base_uri, query_params=query_params or {} )
Get information fot this organisation. Returns a dictionary of values.
357,824
def delay(self, methodname, *args, **kwargs): ID = str(uuid.uuid4()) self.send_query(ID, methodname, False, *args, **kwargs) return ID
调用但不要求返回结果,而是通过系统方法getresult来获取. Parameters: methodname (str): - 要调用的方法名 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数
357,825
def export_as_tfhub_module(model_name, hparams, decode_hparams, problem, checkpoint_path, export_dir): def hub_module_fn(): model_fn = t2t_model.T2TModel.make_estimator_m...
Exports the last checkpoint from the directory as tfhub module. It creates the Module spec and signature (based on T2T problem information), which is later used to create and export the hub module. Module will be saved inside the ckpt_dir. Args: model_name: name of the model to be exported. hparams: T...
357,826
def updateResultsForJob(self, forceUpdate=True): updateInterval = time.time() - self._lastUpdateAttemptTime if updateInterval < self._MIN_UPDATE_INTERVAL and not forceUpdate: return self.logger.info("Attempting model selection for jobID=%d: time=%f"\ " lastUpdate=%f"%(self....
Chooses the best model for a given job. Parameters ----------------------------------------------------------------------- forceUpdate: (True/False). If True, the update will ignore all the restrictions on the minimum time to update and the minimum number of records to ...
357,827
def name(self): return ffi.string(lib.EnvGetInstanceName(self._env, self._ist)).decode()
Instance name.
357,828
def search_patients(self, search_criteria, include_picture=, organization_id=None): include_picture = include_picture or organization_id = organization_id or magic = self._magic_json(action=TouchWorksMagicConstants.ACTION_SEARCH_PATIENTS, ...
invokes TouchWorksMagicConstants.ACTION_SEARCH_PATIENTS action :return: JSON response
357,829
def prepare(self, node): super(Reorder, self).prepare(node) candidates = self.type_dependencies.successors( TypeDependencies.NoDeps) ...
Format type dependencies information to use if for reordering.
357,830
def set_game_score(self, user_id, score, force=False, disable_edit_message=False, chat_id=None, message_id=None, inline_message_id=None): assert_type_or_raise(user_id, int, parameter_name="user_id") assert_type_or_raise(score, int, parameter_name="score") assert_type_or_raise(force, N...
Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False. https://core.tele...
357,831
def make_fileitem_peinfo_type(petype, condition=, negate=False, preserve_case=False): document = search = content_type = content = petype ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate,...
Create a node for FileItem/PEInfo/Type :return: A IndicatorItem represented as an Element node
357,832
def get_event_teams(self, id, **data): return self.get("/events/{0}/teams/".format(id), data=data)
GET /events/:id/teams/ Returns a list of :format:`teams` for the event.
357,833
def listFileParents(self, logical_file_name="", block_id=0, block_name=""): if not logical_file_name and not block_name and not block_id: dbsExceptionHandler(, \ "Logical_file_name, block_id or block_name is required for fileparents api", self.logger.exception ) ...
required parameter: logical_file_name or block_name returns: this_logical_file_name, parent_logical_file_name, parent_file_id
357,834
def write(filename, f): import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], points[:, 0]) vals = f(polar, azimuthal) meshio.write(filename, points, {"triangle": cells}, point_data={"f": vals}...
Write a function `f` defined in terms of spherical coordinates to a file.
357,835
def poll(self): task = self.task n_jobs = len(self.submission_data) n_poll_fails = 0 if task.walltime == NO_FLOAT: max_polls = sys.maxsize else: max_polls = int(math.ceil((task.walltime * 3600.) / (task.poll_interval * 60.))) ...
Initiates the job status polling loop.
357,836
def choices(klass): _choices = [] for attr in user_attributes(klass.Meta): val = getattr(klass.Meta, attr) setattr(klass, attr, val[0]) _choices.append((val[0], val[1])) setattr(klass, , tuple(_choices)) return klass
Decorator to set `CHOICES` and other attributes
357,837
def Navigate(self, direction: int) -> : ele = self.pattern.Navigate(direction) return Control.CreateControlFromElement(ele)
Call IUIAutomationCustomNavigationPattern::Navigate. Get the next control in the specified direction within the logical UI tree. direction: int, a value in class `NavigateDirection`. Return `Control` subclass or None. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomatio...
357,838
def _distance_between_coords(self, lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) r = 6371 d_hav = 2 * r * asin(sqrt((sin((lat1 - lat2) / 2))**2 + \ cos(lat1) * cos(lat2) * (sin((lon1 - lon2) / 2)**2 ...
Calculate the great circle distance between two points on the earth (specified in decimal degrees). Haversine formula states that: d = 2 * r * arcsin(sqrt(sin^2((lat1 - lat2) / 2 + cos(lat1)cos(lat2)sin^2((lon1 - lon2) / 2)))) where r is the radius of the sphere. This assumes t...
357,839
def to_json(self): participant = self.side prop_dict = { participant: { MODIFIER: self.modifier } } if self.modifier == LOCATION: prop_dict[participant] = { LOCATION: self.effect.to_json() ...
Create a property dict that is used to recreate an edge dictionary for a :class:`BELGraph`. :return: Property dictionary of an edge that is participant (sub/obj) related. :rtype: dict
357,840
def EvalAdjustingSchedule(history, constant=0.1, steps_to_decrease=20, improvement_margin=0.001, decrease_rate=1.5, history_mode="eval", metric="metrics/accuracy"):...
Learning rate that decreases when eval metric stalls. If the chosen metric does not improve by improvement_margin for as many as steps_to_decrease steps, then the constant gets decreased by decrease rate. Finally, the MultifactorSchedule gets called with the adjusted constant. Args: history: trax.history....
357,841
def add_node(self, id, radius=8, style=style.DEFAULT, category="", label=None, root=False, properties={}): if self.has_key(id): return self[id] if not isinstance(style, str) and style.__dict__.has_key["name"]: style = styl...
Add node from id and return the node object.
357,842
def voip(self): if self._voip is None: self._voip = VoipList( self._version, account_sid=self._solution[], country_code=self._solution[], ) return self._voip
Access the voip :returns: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList :rtype: twilio.rest.api.v2010.account.available_phone_number.voip.VoipList
357,843
def list_sets(family=): * cmd = .format(_ipset_cmd()) out = __salt__[](cmd, python_shell=False) _tmp = out.split() count = 0 sets = [] sets.append({}) for item in _tmp: if not item: count = count + 1 sets.append({}) continue key, valu...
.. versionadded:: 2014.7.0 List all ipset sets. CLI Example: .. code-block:: bash salt '*' ipset.list_sets
357,844
def _nest_payload(self, keys, payload): if len(keys) == 0: return payload return {keys[0]: self._nest_payload(keys[1:], payload)}
Nest a payload in a dict under the keys contained in `keys`
357,845
def _deduplicate_indexed_slices(values, indices): unique_indices, new_index_positions = tf.unique(indices) summed_values = tf.unsorted_segment_sum(values, new_index_positions, tf.shape(unique_indices)[0]) return (su...
Sums `values` associated with any non-unique `indices`. Args: values: A `Tensor` with rank >= 1. indices: A one-dimensional integer `Tensor`, indexing into the first dimension of `values` (as in an IndexedSlices object). Returns: A tuple of (`summed_values`, `unique_indices`) where `uniq...
357,846
def bulk_create(self, *records): if not records: raise TypeError() if any(not isinstance(r, dict) for r in records): raise TypeError() new_records = [] for record_data in records: record = record_factory(self._app, record_data) ...
Create and validate multiple records in associated app Args: *records (dict): One or more dicts of new record field names and values Notes: Requires Swimlane 2.15+ Validates like :meth:`create`, but only sends a single request to create all provided fields, and doe...
357,847
def save(self, filename=None): if filename is None: filename = "morse_smale_complex.json" with open(filename, "w") as fp: fp.write(self.to_json())
Saves a constructed Morse-Smale Complex in json file @ In, filename, a filename for storing the hierarchical merging of features and the base level partitions of the data
357,848
def date_elem(ind_days, ind_minutes): def inner(seq): return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000) return inner
Create a function to parse a datetime from the product-specific blocks.
357,849
def _convert_verbal_form( analysis ): assert FORM in analysis, +FORM+ for form, replacement in _verb_conversion_rules: if analysis[FORM] == form: assert analysis[POSTAG] == , \ +str(analysis[POSTAG])+ analysis[FORM] = replacement elif a...
Converts ordinary verbal categories of the input analysis. Performs one-to-one conversions.
357,850
def spec(self): pspec = {} pspec[] = self.NAME pspec[] = self.VERSION pspec[] = self.DESCRIPTION components = [sys.argv[0], self.NAME] if self.USE_ARGUMENTS: components.append() pspec[] = self.COMMAND or .join(components) pspec[] = [ inp...
Generate spec for the processor as a Python dictionary. A spec is a standard way to describe a MountainLab processor in a way that is easy to process, yet still understandable by humans. This method generates a Python dictionary that complies with a spec definition.
357,851
def try_to_create_directory(directory_path): logger = logging.getLogger("ray") directory_path = os.path.expanduser(directory_path) if not os.path.exists(directory_path): try: os.makedirs(directory_path) except OSError as e: if e.errno != errno.EEXIST: ...
Attempt to create a directory that is globally readable/writable. Args: directory_path: The path of the directory to create.
357,852
def find_package_dirs(root_path): package_sdirs = set() for entry in os.listdir(root_path): fname = entry if root_path == else pjoin(root_path, entry) if isdir(fname) and exists(pjoin(fname, )): package_sdirs.add(fname) return package_sdirs
Find python package directories in directory `root_path` Parameters ---------- root_path : str Directory to search for package subdirectories Returns ------- package_sdirs : set Set of strings where each is a subdirectory of `root_path`, containing an ``__init__.py`` fi...
357,853
def asdate(self): return datetime.date(self.year, self.month, self.day)
Return this datetime_tz as a date object. Returns: This datetime_tz as a date object.
357,854
def discover(self): % startup_file) self.ssl_pymongo_options = self._get_ssl_pymongo_options( self.loaded_args) self.cluster_tree = {} self.cluster_tags = defaultdict(list) self.cluster_running = {} ...
Fetch state for each processes. Build the self.cluster_tree, self.cluster_tags, self.cluster_running data structures, needed for sub-commands start, stop, list.
357,855
def peeklist(self, fmt, **kwargs): pos = self._pos return_values = self.readlist(fmt, **kwargs) self._pos = pos return return_values
Interpret next bits according to format string(s) and return list. fmt -- One or more strings with comma separated tokens describing how to interpret the next bits in the bitstring. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string w...
357,856
def _phi2deriv(self,R,z,phi=0.,t=0.): raise AttributeError return self._scf.phi2deriv(R,z,phi=phi,use_physical=False)
NAME: _phi2deriv PURPOSE: evaluate the second azimuthal derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the second azimuthal derivative ...
357,857
def check_basename_conflicts(self, targets): basename_seen = {} for target in targets: if target.basename in basename_seen: raise self.BasenameConflictError( "the same basename: {}'\n\t{} and \n\t{}" .format(ta...
Apps' basenames are used as bundle directory names. Ensure they are all unique.
357,858
def ned2geodetic(n: float, e: float, d: float, lat0: float, lon0: float, h0: float, ell: Ellipsoid = None, deg: bool = True) -> Tuple[float, float, float]: x, y, z = enu2ecef(e, n, -d, lat0, lon0, h0, ell, deg=deg) return ecef2geodetic(x, y, z, ell, deg=deg)
Converts North, East, Down to target latitude, longitude, altitude Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float East NED coordinate (meters) d : float or numpy.ndarray of float Down NED coordinat...
357,859
def model_stats(self): stats = self.model.default_stats return blob_data_to_dict(stats, self._sampler.blobs)
A dict mapping the model's ``default_stats`` to arrays of values. The returned array has shape ``nwalkers x niterations``.
357,860
def get_instance(self, payload): return AuthTypesInstance( self._version, payload, account_sid=self._solution[], domain_sid=self._solution[], )
Build an instance of AuthTypesInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesInstance
357,861
def get_object(self, *args, **kwargs): self.category_instance = get_object_or_404(Category, slug=self.kwargs[]) return get_object_or_404(Post, thread__id=self.kwargs[], thread__category=self.category_instance, pk=self.kwargs[])
Should memoize the object to avoid multiple query if get_object is used many times in the view
357,862
def prefixed_collapsible_map(m, prefix): if m == values.unset: return {} def flatten_dict(d, result={}, prv_keys=[]): for k, v in d.items(): if isinstance(v, dict): flatten_dict(v, result, prv_keys + [k]) else: result[.join(prv_keys +...
Return a dict of params corresponding to those in m with the added prefix
357,863
def remove_known_hosts(overcloud_ip): known_hosts = os.path.expanduser("~/.ssh/known_hosts") if os.path.exists(known_hosts): command = [, , overcloud_ip, , known_hosts] subprocess.check_call(command)
For a given IP address remove SSH keys from the known_hosts file
357,864
def create(self, attributes=values.unset, twilio_address=values.unset, date_created=values.unset, date_updated=values.unset, identity=values.unset, user_address=values.unset): data = values.of({ : identity, : user_address, : attributes, ...
Create a new ParticipantInstance :param unicode attributes: An optional string metadata field you can use to store any data you wish. :param unicode twilio_address: The address of the Twilio phone number that the participant is in contact with. :param datetime date_created: The date that this r...
357,865
def save(self): kwargs = dict( (field, getattr(self, field)) for field in self.updateable_fields if hasattr(self, field) ) self.cloud_manager.modify_server(self.uuid, **kwargs) self._reset(kwargs)
Sync local changes in server's attributes to the API. Note: DOES NOT sync IPAddresses and storage_devices, use add_ip, add_storage, remove_ip, remove_storage instead.
357,866
def _clean_inheritance_tokens(self): c = self._copy() x = c._data x.pop(, None) x.pop(, None) x.pop(, None) return c
create a new copy of this :class:`.Context`. with tokens related to inheritance state removed.
357,867
def serial_udb_extra_f13_encode(self, sue_week_no, sue_lat_origin, sue_lon_origin, sue_alt_origin): return MAVLink_serial_udb_extra_f13_message(sue_week_no, sue_lat_origin, sue_lon_origin, sue_alt_origin)
Backwards compatible version of SERIAL_UDB_EXTRA F13: format sue_week_no : Serial UDB Extra GPS Week Number (int16_t) sue_lat_origin : Serial UDB Extra MP Origin Latitude (int32_t) sue_lon_origin : Serial UDB Extra MP Origin Longitude ...
357,868
def vehicle_type_string(self, hb): if hb.type == mavutil.mavlink.MAV_TYPE_FIXED_WING: return if hb.type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER: return if hb.type == mavutil.mavlink.MAV_TYPE_SURFACE_BOAT: return if hb.type == mavutil.mavli...
return vehicle type string from a heartbeat
357,869
def replace(self, key, value): self._find_lt(key) node = self._path[0][2] if node is self._tail or key < node[0]: node = self._create_node(key, value) self._insert(node) else: node[1] = value
Replace the value of the first key-value pair with key *key*. If the key was not found, the pair is inserted.
357,870
def update_instance(self, data): for key, val in iteritems(data): if not hasattr(self, key): raise AttributeError( "No field named {key} for model {model}".format( key=key, model=self.__class__.__name__ ...
Update a single record by id with the provided data. Args: data (dict): The new data to update the record with. Returns: self: This is an instance of itself with the updated data. Raises: AttributeError: This is raised if a key in the ``data`` isn't ...
357,871
def get_proficiencies(self): collection = JSONClientValidated(, collection=, runtime=self._runtime) result = collection.find(self._view_filter()).sort(, DESCENDING) return object...
Gets all ``Proficiencies``. return: (osid.learning.ProficiencyList) - a list of ``Proficiencies`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*
357,872
def comment(self, message): message = str(message) sw_repr = { : , : self._record._swimlane.user.as_usergroup_selection(), : pendulum.now().to_rfc3339_string(), : message } comment = Comment(self._swimlane, sw_repr) self....
Add new comment to record comment field
357,873
def get_table_names(self, connection, schema=None, **kw): return self._get_table_or_view_names(, connection, schema, **kw)
Return a list of table names for `schema`. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.get_table_names`.
357,874
def TakeIf(self: dict, f): if is_to_destruct(f): f = destruct_func(f) return (e for e in self.items() if f(e))
[ { 'self': [1, 2, 3], 'f': lambda e: e%2, 'assert': lambda ret: list(ret) == [1, 3] } ]
357,875
def structs2records(structs): try: n = len(structs) except TypeError: yield struct2dict(structs) return for i in range(n): struct = structs[i] yield struct2dict(struct)
convert one or more structs and generate dictionaries
357,876
def set_harakiri_params(self, timeout=None, verbose=None, disable_for_arh=None): self._set(, timeout) self._set(, verbose, cast=bool) self._set(, disable_for_arh, cast=bool) return self._section
Sets workers harakiri parameters. :param int timeout: Harakiri timeout in seconds. Every request that will take longer than the seconds specified in the harakiri timeout will be dropped and the corresponding worker is thereafter recycled. :param bool verbose: Haraki...
357,877
def getChecks(self, **parameters): for key in parameters: if key not in [, , ]: sys.stderr.write( % key) response = self.request(, , parameters) return [PingdomCheck(self, x) for x in response.json()[]]
Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offset for listing (requires limit.) ...
357,878
def video_mode_supported(self, width, height, bpp): if not isinstance(width, baseinteger): raise TypeError("width can only be an instance of type baseinteger") if not isinstance(height, baseinteger): raise TypeError("height can only be an instance of type baseinteger") ...
Returns whether the frame buffer implementation is willing to support a given video mode. In case it is not able to render the video mode (or for some reason not willing), it should return @c false. Usually this method is called when the guest asks the VMM device whether a given video mo...
357,879
def version_info(self): package = pkg.get_distribution() local_version_str = package.version local_version = package.parsed_version print( + colored( + local_version_str, )) if not self.settings[]: return print(, end=...
Tell, what version we're running at and if it's up to date.
357,880
def show_current_metadata(self): LOGGER.debug( + self.layer.name()) keywords = KeywordIO(self.layer) content_html = keywords.to_message().to_html() full_html = html_header() + content_html + html_footer() self.metadata_preview_web_view.setHtml(full_html)
Show metadata of the current selected layer.
357,881
def close(self): if self._S is not None: self._S.close() self._evt.wait() self._S = None
Close subscription.
357,882
def _check_shape(shape): if isinstance(shape, tuple): for dim in shape: if (isinstance(dim, tuple) and len(dim) == 2 and isinstance(dim[0], int) and isinstance(dim[1], int)): if dim[0] < 0: raise ValueError("expected low dimension to b...
Verify that a shape has the right format.
357,883
def send_request(self, kind, url_components, **kwargs): return self.api.send_request(kind, self.resource_path, url_components, **kwargs)
Send a request for this resource to the API Parameters ---------- kind: str, {'get', 'delete', 'put', 'post', 'head'}
357,884
def _to_relative_path(cls, parent_repo, path): path = to_native_path_linux(path) if path.endswith(): path = path[:-1] if osp.isabs(path): working_tree_linux = to_native_path_linux(parent_repo.working_tree_dir) if not path.startswith(working_...
:return: a path guaranteed to be relative to the given parent-repository :raise ValueError: if path is not contained in the parent repository's working tree
357,885
async def on_raw_317(self, message): target, nickname, idle_time = message.params[:3] info = { : int(idle_time), } if nickname in self._pending[]: self._whois_info[nickname].update(info)
WHOIS idle time.
357,886
def render_target(self): render_target = lib.SDL_GetRenderTarget(self._ptr) if render_target == ffi.NULL: return None else: return Texture._from_ptr(render_target)
Texture: The current render target, or None if using the default render target.
357,887
def make_palette_chunks(palette): p = bytearray() t = bytearray() for x in palette: p.extend(x[0:3]) if len(x) > 3: t.append(x[3]) if t: return p, t return p, None
Create the byte sequences for a ``PLTE`` and if necessary a ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be ``None`` if no ``tRNS`` chunk is necessary.
357,888
def parse_TKIP_hdr(pkt): assert pkt.FCfield.protected tkip_layer = pkt[Dot11TKIP] payload = tkip_layer.data if not tkip_layer.ext_iv: raise ValueError("Extended IV must be set for TKIP") TSC0 = tkip_layer.TSC0 TSC1 = tkip_layer.TSC1 WEPseed = tkip_layer...
Extract TSCs, TA and encoded-data from a packet @pkt
357,889
def place(self, x, y, svg, layer_id): content = xmltodict.parse(svg) self.place_svg_dict(x, y, content, layer_id)
Place the :paramref:`svg` content at ``(x, y)`` position in the SVG, in a layer with the id :paramref:`layer_id`. :param float x: the x position of the svg :param float y: the y position of the svg :param str svg: the SVG to place at ``(x, y)`` :param str layer_id: the id of the...
357,890
def _evaluate(self,R,phi=0.,t=0.): if not self._tform is None: if t < self._tform: smooth= 0. elif t < self._tsteady: deltat= t-self._tform xi= 2.*deltat/(self._tsteady-self._tform)-1. smooth= (3./16.*xi**5.-5./8*xi...
NAME: _evaluate PURPOSE: evaluate the potential at R,phi,t INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: Phi(R,phi,t) HISTORY: 2011-03-27 - Started - Bovy (NYU)
357,891
def remove_post_process(self, name): self._pprocesses = [post_process for post_process in self._pprocesses if post_process.name != name]
remove a post-process Parameters ---------- name : str name of the post-process to remove.
357,892
def read_channel_list_file(*source): config = configparser.ConfigParser(dict_type=OrderedDict) source = file_list(source) success_ = config.read(*source) if len(success_) != len(source): raise IOError("Failed to read one or more CLF files") out = ChannelList() out.source =...
Read a `~gwpy.detector.ChannelList` from a Channel List File
357,893
def changed(self): if not self.parents: return [] return ChangedFileNodesGenerator([n for n in self._get_paths_for_status()], self)
Returns list of modified ``FileNode`` objects.
357,894
def open(self, url): protocol, location = self.__split(url) content = self.__find(location) if protocol == and content is None: raise Exception, % location return content
Open a document at the specified URL. The document URL's needs not contain a protocol identifier, and if it does, that protocol identifier is ignored when looking up the store content. Missing documents referenced using the internal 'suds' protocol are reported by raising an ex...
357,895
def is_end_node(node): return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Name) and node.value.id == )
Checks if a node is the "end" keyword. Args: node: AST node. Returns: True if the node is the "end" keyword, otherwise False.
357,896
def CreateStorageWriter(cls, storage_format, session, path): if storage_format == definitions.STORAGE_FORMAT_SQLITE: return sqlite_writer.SQLiteStorageFileWriter(session, path) return None
Creates a storage writer. Args: session (Session): session the storage changes are part of. path (str): path to the storage file. storage_format (str): storage format. Returns: StorageWriter: a storage writer or None if the storage file cannot be opened or the storage format ...
357,897
def set_default_interface(etree): global types, ET, modules t = _get_etree_type(etree) _types = set(types or []) _types.update([t]) types = tuple(_types) modules[t] = etree old, ET = ET, etree return old
Sets the default interface that PyAMF will use to deal with XML entities (both objects and blobs).
357,898
def slow_reduction_transfer(ii, j, idx, count, x, u, v, c): for i in ii: j1 = x[i] jj = j[idx[i]:(idx[i]+count[i])] uu = np.min((c[idx[i]:(idx[i]+count[i])] - v[jj])[jj != j1]) v[j1] = v[j1] - uu + u[i] u[i] = uu
Perform the reduction transfer step from the Jonker-Volgenant algorithm The data is input in a ragged array in terms of "i" structured as a vector of values for each i,j combination where: ii - the i to be reduced j - the j-index of every entry idx - the index of the first entry for each i...
357,899
def json_success_response(data, response): response.body = json.dumps(data) response.status_code = 200 response.add_header("Content-Type", "application/json") response.add_header("Cache-Control", "no-store") response.add_header("Pragma", "no-cache")
Formats the response of a successful token request as JSON. Also adds default headers and status code.