Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
382,500
def rotate(self, angle, center=(0, 0)): ca = numpy.cos(angle) sa = numpy.sin(angle) sa = numpy.array((-sa, sa)) c0 = numpy.array(center) self.polygons = [(points - c0) * ca + (points - c0)[:, ::-1] * sa + c0 for points in self.polygons] r...
Rotate this object. Parameters ---------- angle : number The angle of rotation (in *radians*). center : array-like[2] Center point for the rotation. Returns ------- out : ``PolygonSet`` This object.
382,501
def groups_leave(self, room_id, **kwargs): return self.__call_api_post(, roomId=room_id, kwargs=kwargs)
Causes the callee to be removed from the private group, if they’re part of it and are not the last owner.
382,502
def _recv_callback(self, msg): m2req = MongrelRequest.parse(msg[0]) MongrelConnection(m2req, self._sending_stream, self.request_callback, no_keep_alive=self.no_keep_alive, xheaders=self.xheaders)
Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String.
382,503
def add_positional_embedding(x, max_length, name=None, positions=None): with tf.name_scope("add_positional_embedding"): _, length, depth = common_layers.shape_list(x) var = tf.cast(tf.get_variable(name, [max_length, depth]), x.dtype) if positions is None: pad_length = tf.maximum(0, length - max_l...
Adds positional embedding. Args: x: Tensor with shape [batch, length, depth]. max_length: int representing static maximum size of any dimension. name: str representing name of the embedding tf.Variable. positions: Tensor with shape [batch, length]. Returns: Tensor of same shape as x.
382,504
def unusedoptions(self, sections): unused = set([]) for section in _list(sections): if not self.has_section(section): continue options = self.options(section) raw_values = [self.get(section, option, raw=True) for option in options] ...
Lists options that have not been used to format other values in their sections. Good for finding out if the user has misspelled any of the options.
382,505
def update(self, message=None, subject=None, days=None, downloads=None, notify=None): method, url = get_URL() payload = { : self.config.get(), : self.session.cookies.get(), : self.tr...
Update properties for a transfer. :param message: updated message to recipient(s) :param subject: updated subject for trasfer :param days: updated amount of days transfer is available :param downloads: update amount of downloads allowed for transfer :param notify: update whether...
382,506
def get_assets(self): if self.retrieved: raise errors.IllegalState() self.retrieved = True return objects.AssetList(self._results, runtime=self._runtime)
Gets the asset list resulting from a search. return: (osid.repository.AssetList) - the asset list raise: IllegalState - the list has already been retrieved *compliance: mandatory -- This method must be implemented.*
382,507
def find_motif_disruptions( position, ref, alt, genome_fasta, matrices, ): import subprocess import MOODS max_motif_length = max([x.shape[0] for x in matrices.values()]) chrom, coords = position.split() start,end = [int(x) for x in coords.split()] s = .format(ch...
Determine whether there is a difference between the ref and alt alleles for TF binding. Requires samtools in your path. Parameters ---------- position : str Zero based genomic coordinates of the reference allele of the form chrom:start-end (chr5:100-101 for a SNV for instance). The ...
382,508
def write_table(self, table, rows, append=False, gzip=False): _write_table(self.root, table, rows, self.table_relations(table), append=append, gzip=gzip, encoding=self.encoding)
Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existing data. gzip: If `True`, compress the resulting table ...
382,509
def modfacl(acl_type, acl_name=, perms=, *args, **kwargs): ****** recursive = kwargs.pop(, False) raise_err = kwargs.pop(, False) _raise_on_no_files(*args) cmd = if recursive: cmd += cmd += cmd = .format(cmd, _acl_prefix(acl_type), acl_name, perms) for dentry in arg...
Add or modify a FACL for the specified file(s) CLI Examples: .. code-block:: bash salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen salt '*' acl.modfacl ...
382,510
def _huffman_encode_char(cls, c): if isinstance(c, EOS): return cls.static_huffman_code[-1] else: assert(isinstance(c, int) or len(c) == 1) return cls.static_huffman_code[orb(c)]
huffman_encode_char assumes that the static_huffman_tree was previously initialized @param str|EOS c: a symbol to encode @return (int, int): the bitstring of the symbol and its bitlength @raise AssertionError
382,511
def get_proto(self): if self.proto_idx_value is None: self.proto_idx_value = self.CM.get_proto(self.proto_idx) return self.proto_idx_value
Return the prototype of the method :rtype: string
382,512
def open_channel(self): logger.debug() self._connection.channel(on_open_callback=self.on_channel_open)
Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika.
382,513
def fromBrdict(cls, master, brdict): cache = master.caches.get_cache("BuildRequests", cls._make_br) return cache.get(brdict[], brdict=brdict, master=master)
Construct a new L{BuildRequest} from a dictionary as returned by L{BuildRequestsConnectorComponent.getBuildRequest}. This method uses a cache, which may result in return of stale objects; for the most up-to-date information, use the database connector methods. @param master: cu...
382,514
def create(server_): try: if server_[] and config.is_profile_configured(__opts__, __active_provider_name__ or , server_[], ...
Create a single BareMetal server from a data dict.
382,515
def add_widgets_context(request, context): user = context["user"] if context["is_student"] or context["eighth_sponsor"]: num_blocks = 6 surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks) if context["is_student"]: schedule, no_signup_today = gen_schedule(u...
WIDGETS: * Eighth signup (STUDENT) * Eighth attendance (TEACHER or ADMIN) * Bell schedule (ALL) * Birthdays (ALL) * Administration (ADMIN) * Links (ALL) * Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise)
382,516
def ReadUnicodeTable(filename, nfields, doline): if nfields < 2: raise InputError("invalid number of fields %d" % (nfields,)) if type(filename) == str: if filename.startswith("http://"): fil = urllib2.urlopen(filename) else: fil = open(filename, "r") else: fil = filename first ...
Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-comment line in the table is expected to have the given ...
382,517
def x_rolls(self, number, count=0, func=sum): for x in range(number): yield self.roll(count, func)
Iterator of number dice rolls. :param count: [0] Return list of ``count`` sums :param func: [sum] Apply func to list of individual die rolls func([])
382,518
def visible_object_layers(self): return (layer for layer in self.tmx.visible_layers if isinstance(layer, pytmx.TiledObjectGroup))
This must return layer objects This is not required for custom data formats. :return: Sequence of pytmx object layers/groups
382,519
def chebyshev_distance(point1, point2): distance = 0.0 dimension = len(point1) for i in range(dimension): distance = max(distance, abs(point1[i] - point2[i])) return distance
! @brief Calculate Chebyshev distance between between two vectors. \f[ dist(a, b) = \max_{}i\left (\left | a_{i} - b_{i} \right |\right ); \f] @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @return (double) Chebyshev distance...
382,520
def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.populate_from is not None: kwargs[] = self.populate_from if self.unique_with != (): kwargs[] = self.unique_with kwargs.pop(, None) return name, path, args, kwar...
Deconstruct method.
382,521
async def create_cred( self, cred_offer_json, cred_req_json: str, cred_attrs: dict, rr_size: int = None) -> (str, str): LOGGER.debug( , cred_offer_json, cred_req_json, cred_attrs, rr...
Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier. Raise WalletState for closed wallet. If the credential definition supports...
382,522
def bookmarks_changed(self): bookmarks = self.editor.get_bookmarks() if self.editor.bookmarks != bookmarks: self.editor.bookmarks = bookmarks self.sig_save_bookmarks.emit(self.filename, repr(bookmarks))
Bookmarks list has changed.
382,523
def has_gradient(self): try: self.__model.gradient self.__model.predictions_and_gradient except AttributeError: return False else: return True
Returns true if _backward and _forward_backward can be called by an attack, False otherwise.
382,524
def ws_url(self): proto = self.request.protocol.replace(, ) host = self.application.ipython_app.websocket_host if host == : host = self.request.host return "%s://%s" % (proto, host)
websocket url matching the current request turns http[s]://host[:port] into ws[s]://host[:port]
382,525
def open(server=None, url=None, ip=None, port=None, name=None, https=None, auth=None, verify_ssl_certificates=True, proxy=None, cookies=None, verbose=True, _msgs=None): r if server is not None: assert_is_type(server, H2OLocalServer) assert_is_type(ip, None, "`ip` sho...
r""" Establish connection to an existing H2O server. The connection is not kept alive, so what this method actually does is it attempts to connect to the specified server, and checks that the server is healthy and responds to REST API requests. If the H2O server cannot be reached, an :c...
382,526
def extract_anomalies(y_true, smoothed_errors, window_size, batch_size, error_buffer): if len(y_true) <= batch_size * window_size: raise ValueError("Window size (%s) larger than y_true (len=%s)." % (batch_size, len(y_true))) num_windows = int((len(y_true) - (batch_size * w...
Extracts anomalies from the errors. Args: y_true (): smoothed_errors (): window_size (int): batch_size (int): error_buffer (int): Returns:
382,527
def _update_limits_from_api(self): try: self.connect() resp = self.conn.get_send_quota() except EndpointConnectionError as ex: logger.warning(, str(ex)) return except ClientError as ex: if ex.response[][] in [, ]: ...
Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information.
382,528
def _get_quantile_ratio(self, X, y): y_pred = self.predict(X) return (y_pred > y).mean()
find the expirical quantile of the model Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors, where n_samples is the number of samples and m_features is the number of features. y : array-like, shape (n_samples,) Target...
382,529
def top_priority_effect(effects): if len(effects) == 0: raise ValueError("List of effects cannot be empty") effects = map( select_between_exonic_splice_site_and_alternate_effect, effects) effects_grouped_by_gene = apply_groupby( effects, fn=gene_id_of_associated_transc...
Given a collection of variant transcript effects, return the top priority object. ExonicSpliceSite variants require special treatment since they actually represent two effects -- the splicing modification and whatever else would happen to the exonic sequence if nothing else gets changed. In cases where ...
382,530
def get_file(self, name, filename): stream, vname = self.get_stream(name) path, version = split_name(vname) dir_path = os.path.dirname(filename) if dir_path: mkdir(dir_path) with open(filename, ) as f: shutil.copyfileobj(stream, f) retu...
Saves the content of file named ``name`` to ``filename``. Works like :meth:`get_stream`, but ``filename`` is the name of a file which will be created (or overwritten). Returns the full versioned name of the retrieved file.
382,531
def apply_strategy(self): method_id = self.conf.strategy.replace(, ) if not hasattr(DuplicateSet, method_id): raise NotImplementedError( "DuplicateSet.{}() method.".format(method_id)) return getattr(self, method_id)()
Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it.
382,532
def do_create(marfile, files, compress, productversion=None, channel=None, signing_key=None, signing_algorithm=None): with open(marfile, ) as f: with MarWriter(f, productversion=productversion, channel=channel, signing_key=signing_key, signing...
Create a new MAR file.
382,533
def run(self, clf): rank = MPI.COMM_WORLD.Get_rank() if rank == 0: logger.info( ) self.sl.distribute([self.data], self.mask) self.sl.broadcast((self.labels, self.num_folds, clf)) if rank == 0: logger.info( ...
run activity-based voxel selection Sort the voxels based on the cross-validation accuracy of their activity vectors within the searchlight Parameters ---------- clf: classification function the classifier to be used in cross validation Returns -----...
382,534
def purge(self): self.channel.purge_stream(self.stream_id, remove_definition=False, sandbox=None)
Purge the stream. This removes all data and clears the calculated intervals :return: None
382,535
def check(self, feature): mapper = feature.as_dataframe_mapper() mapper.fit(self.X, y=self.y)
Check that fit can be called on reference data
382,536
def isempty(path): if op.isdir(path): return [] == os.listdir(path) elif op.isfile(path): return 0 == os.stat(path).st_size return None
Returns True if the given file or directory path is empty. **Examples**: :: auxly.filesys.isempty("foo.txt") # Works on files... auxly.filesys.isempty("bar") # ...or directories!
382,537
def get_scaled(self, factor): res = TimeUnit(self) res._factor = self._factor * factor res._unit = self._unit return res
Get a new time unit, scaled by the given factor
382,538
def load_essentiality(self, model): data = self.config.get("essentiality") if data is None: return experiments = data.get("experiments") if experiments is None or len(experiments) == 0: return path = self.get_path(data, ...
Load and validate all data files.
382,539
def _get_nop_length(cls, insns): nop_length = 0 if insns and cls._is_noop_insn(insns[0]): for insn in insns: if cls._is_noop_insn(insn): nop_length += insn.size else: break return nop_len...
Calculate the total size of leading nop instructions. :param insns: A list of capstone insn objects. :return: Number of bytes of leading nop instructions. :rtype: int
382,540
def convertDict2Attrs(self, *args, **kwargs): for n,a in enumerate(self.attrs): try: params = self.params except AttributeError as aerr: params = {} kwargs.update(params) try: task = self.mambut...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Task object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dictionaries) with a MambuTas...
382,541
def parse_deps(orig_doc, options={}): doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes()) if not doc.is_parsed: user_warning(Warnings.W005) if options.get("collapse_phrases", False): with doc.retokenize() as retokenizer: for np in list(doc.noun_chunks): ...
Generate dependency parse in {'words': [], 'arcs': []} format. doc (Doc): Document do parse. RETURNS (dict): Generated dependency parse keyed by words and arcs.
382,542
def post_async(self, url, data, callback=None, params=None, headers=None): params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, None) self._authenticate(params, headers) data = json.dumps(data, cls=JSONEncoder) process_pool.apply...
Asynchronous POST request with the process pool.
382,543
def supports_object_type(self, object_type=None): from .osid_errors import IllegalState, NullArgument if not object_type: raise NullArgument() if self._kwargs[] not in []: raise IllegalState() return object_type in self.get_object_types
Tests if the given object type is supported. arg: object_type (osid.type.Type): an object Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not an ``OBJECT`` raise: NullArgument - ``object_type`` is ``nul...
382,544
def mosh_args(conn): I, = conn.identities identity = I.identity_dict args = [] if in identity: args += [, identity[]] if in identity: args += [identity[]++identity[]] else: args += [identity[]] return args
Create SSH command for connecting specified server.
382,545
def allowance(self, filename): for line in self.rulelines: if line.applies_to(filename): return line.allowance return True
Preconditions: - our agent applies to this entry - filename is URL decoded
382,546
def bgseq(code): if isinstance(code, str): code = nametonum(code) if code == -1: return "" s = termcap.get(, code) or termcap.get(, code) return s
Returns the background color terminal escape sequence for the given color code number.
382,547
def consume_messages(self, max_next_messages): if self.__next_messages == 0: self.set_next_messages(min(1000, max_next_messages)) self.set_next_messages(min(self.__next_messages, max_next_messages)) mark = time.time() for record in self._get_messages_from_co...
Get messages batch from Kafka (list at output)
382,548
def _search_files(path): path = pathlib.Path(path) fifo = [] for fp in path.glob("*"): if fp.is_dir(): continue for fmt in formats: if not fmt.is_series and fmt.verify(fp): fifo.append((fp, fmt...
Search a folder for data files .. versionchanged:: 0.6.0 `path` is not searched recursively anymore
382,549
def semiyearly(date=datetime.date.today()): return datetime.date(date.year, 1 if date.month < 7 else 7, 1)
Twice a year.
382,550
def update(self, modelID, modelParams, modelParamsHash, metricResult, completed, completionReason, matured, numRecords): assert (modelParamsHash is not None) if completed: matured = True if metricResult is not None and matured and \ ...
Insert a new entry or update an existing one. If this is an update of an existing entry, then modelParams will be None Parameters: -------------------------------------------------------------------- modelID: globally unique modelID of this model modelParams: params dict for this model, or...
382,551
def aliases(*names): def wrapper(func): setattr(func, ATTR_ALIASES, names) return func return wrapper
Defines alternative command name(s) for given function (along with its original name). Usage:: @aliases('co', 'check') def checkout(args): ... The resulting command will be available as ``checkout``, ``check`` and ``co``. .. note:: This decorator only works with a rece...
382,552
def get_channelstate_by_token_network_and_partner( chain_state: ChainState, token_network_id: TokenNetworkID, partner_address: Address, ) -> Optional[NettingChannelState]: token_network = get_token_network_by_identifier( chain_state, token_network_id, ) channel_...
Return the NettingChannelState if it exists, None otherwise.
382,553
def dumps(obj, *args, **kwargs): return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **kwargs)
Typeless dump an object to json string
382,554
def consistency(self): result = self.total_duration.jd / (self.max_time - self.min_time).jd return result
Get a percentage of fill between the min and max time the moc is defined. A value near 0 shows a sparse temporal moc (i.e. the moc does not cover a lot of time and covers very distant times. A value near 1 means that the moc covers a lot of time without big pauses. Returns ----...
382,555
def _make_plan(plan_dict): operator_type = plan_dict["operatorType"] identifiers = plan_dict.get("identifiers", []) arguments = plan_dict.get("args", []) children = [_make_plan(child) for child in plan_dict.get("children", [])] if "dbHits" in plan_dict or "rows" in plan_dict: db_hits = ...
Construct a Plan or ProfiledPlan from a dictionary of metadata values. :param plan_dict: :return:
382,556
def GetParametro(self, clave, clave1=None, clave2=None, clave3=None, clave4=None): "Devuelve un parámetro de salida (establecido por llamada anterior)" valor = self.params_out.get(clave) for clave in (clave1, clave2, clave3, clave4): if clave is not None and valor i...
Devuelve un parámetro de salida (establecido por llamada anterior)
382,557
def build_job_configs(self, args): job_configs = {} components = Component.build_from_yamlfile(args[]) NAME_FACTORY.update_base_dict(args[]) ret_dict = make_diffuse_comp_info_dict(components=components, library=args[], ...
Hook to build job configurations
382,558
def delay_and_stop(duration, dll, device_number): xinput = getattr(ctypes.windll, dll) time.sleep(duration/1000) xinput_set_state = xinput.XInputSetState xinput_set_state.argtypes = [ ctypes.c_uint, ctypes.POINTER(XinputVibration)] xinput_set_state.restype = ctypes.c_uint vibration ...
Stop vibration aka force feedback aka rumble on Windows after duration miliseconds.
382,559
def verify_merkle_path(merkle_root_hex, serialized_path, leaf_hash_hex, hash_function=bin_double_sha256): merkle_root = hex_to_bin_reversed(merkle_root_hex) leaf_hash = hex_to_bin_reversed(leaf_hash_hex) path = MerkleTree.path_deserialize(serialized_path) path = [{: p[], : hex_to_bin_reversed...
Verify a merkle path. The given path is the path from two leaf nodes to the root itself. merkle_root_hex is a little-endian, hex-encoded hash. serialized_path is the serialized merkle path path_hex is a list of little-endian, hex-encoded hashes. Return True if the path is consistent with the merkle r...
382,560
def _get_job_results(query=None): if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__[](query) if in response and in response[]: jid = response[][] while get_job(jid)[][][] != : time.sleep(5) return g...
Executes a query that requires a job for completion. This function will wait for the job to complete and return the results.
382,561
def pace(self): secs_per_km = self.duration / (self.distance / 1000) return time.strftime(, time.gmtime(secs_per_km))
Average pace (mm:ss/km for the workout
382,562
def cauldron_extras(self): for extra in super(Dimension, self).cauldron_extras: yield extra if self.formatters: prop = self.id + else: prop = self.id_prop yield self.id + , lambda row: getattr(row, prop)
Yield extra tuples containing a field name and a callable that takes a row
382,563
def add_edges(self): for group, edgelist in self.edges.items(): for (u, v, d) in edgelist: self.draw_edge(u, v, d, group)
Draws all of the edges in the graph.
382,564
def _definition(self): headerReference = self._sectPr.get_headerReference(self._hdrftr_index) return self._document_part.header_part(headerReference.rId)
|HeaderPart| object containing content of this header.
382,565
def update_layers_esri_mapserver(service, greedy_opt=False): try: esri_service = ArcMapService(service.url) srs_code = esri_service.spatialReference.wkid srs, created = SpatialReferenceSystem.objects.get_...
Update layers for an ESRI REST MapServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json
382,566
def list_ec2(region, filter_by_kwargs): conn = boto.ec2.connect_to_region(region) instances = conn.get_only_instances() return lookup(instances, filter_by=filter_by_kwargs)
List running ec2 instances.
382,567
def callprop(self, prop, *args): if not isinstance(prop, basestring): prop = prop.to_string().value cand = self.get(prop) if not cand.is_callable(): raise MakeError(, % cand.typeof()) return cand.call(self, args)
Call a property prop as a method (this will be self). NOTE: dont pass this and arguments here, these will be added automatically!
382,568
def jens_transformation_beta(graph: BELGraph) -> DiGraph: result = DiGraph() for u, v, d in graph.edges(data=True): relation = d[RELATION] if relation == NEGATIVE_CORRELATION: result.add_edge(u, v) result.add_edge(v, u) elif relation in CAUSAL_INCREASE_REL...
Apply Jens' Transformation (Type 2) to the graph. 1. Induce a sub-graph over causal and correlative relations 2. Transform edges with the following rules: - increases => backwards decreases - decreases => decreases - positive correlation => delete - negative correlation => two w...
382,569
def readLiteralContextModes(self): print(.center(60, )) self.literalContextModes = [] for i in range(self.numberOfBlockTypes[L]): self.literalContextModes.append( self.verboseRead(LiteralContextMode(number=i)))
Read literal context modes. LSB6: lower 6 bits of last char MSB6: upper 6 bits of last char UTF8: rougly dependent on categories: upper 4 bits depend on category of last char: control/whitespace/space/ punctuation/quote/%/open/close/ comma/period/=/dig...
382,570
def get_missing_simulations(self, param_list, runs=None): params_to_simulate = [] if runs is not None: next_runs = self.db.get_next_rngruns() available_params = [r[] for r in self.db.get_results()] for param_comb in param_list: ...
Return a list of the simulations among the required ones that are not available in the database. Args: param_list (list): a list of dictionaries containing all the parameters combinations. runs (int): an integer representing how many repetitions are wanted ...
382,571
def nnz_obs_groups(self): og = [] obs = self.observation_data for g in self.obs_groups: if obs.loc[obs.obgnme==g,"weight"].sum() > 0.0: og.append(g) return og
get the observation groups that contain at least one non-zero weighted observation Returns ------- nnz_obs_groups : list a list of observation groups that contain at least one non-zero weighted observation
382,572
def put(self, key, value): value = self.serializedValue(value) self.child_datastore.put(key, value)
Stores the object `value` named by `key`. Serializes values on the way in, and stores the serialized data into the ``child_datastore``. Args: key: Key naming `value` value: the object to store.
382,573
def create_api_key(awsclient, api_name, api_key_name): _sleep() client_api = awsclient.get_client() print( % api_key_name) response = client_api.create_api_key( name=api_key_name, description= + api_name, enabled=True ) print(%s\ % response[]) return resp...
Create a new API key as reference for api.conf. :param api_name: :param api_key_name: :return: api_key
382,574
def _execute(self, method_function, method_name, resource, **params): resource_uri = "{api_host}{resource}".format(api_host=self.api_host, resource=resource) url_encoded_fields = self._encode_params(params) headers = RestClient.generate_telesign_headers(self.customer_id, ...
Generic TeleSign REST API request handler. :param method_function: The Requests HTTP request function to perform the request. :param method_name: The HTTP method name, as an upper case string. :param resource: The partial resource URI to perform the request against, as a string. :param ...
382,575
def set_weekly(self, interval, *, days_of_week, first_day_of_week, **kwargs): self.set_daily(interval, **kwargs) self.__days_of_week = set(days_of_week) self.__first_day_of_week = first_day_of_week
Set to repeat every week on specified days for every x no. of days :param int interval: no. of days to repeat at :param str first_day_of_week: starting day for a week :param list[str] days_of_week: list of days of the week to repeat :keyword date start: Start date of repetition (kwargs)...
382,576
def get_recover_position(gzfile, last_good_position): with closing(mmap.mmap(gzfile.fileno(), 0, access=mmap.ACCESS_READ)) as m: return m.find(GZIP_SIGNATURE, last_good_position + 1)
Return position of a next gzip stream in a GzipFile, or -1 if it is not found. XXX: caller must ensure that the same last_good_position is not used multiple times for the same gzfile.
382,577
def _parse(reactor, directory, pemdir, *args, **kwargs): def colon_join(items): return .join([item.replace(, ) for item in items]) sub = colon_join(list(args) + [.join(item) for item in kwargs.items()]) pem_path = FilePath(pemdir).asTextMode() acme_key = load_or_create_client_key(pem_path) ...
Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to use.
382,578
def closest_pixel_to_set(self, start, pixel_set, direction, w=13, t=0.5): y, x = np.meshgrid(np.arange(w) - w / 2, np.arange(w) - w / 2) cur_px_y = np.ravel(y + start[0]).astype(np.uint16) cur_px_x = np.ravel(x + start[1]).astype(np.uint16) cur_px = s...
Starting at pixel, moves start by direction * t until there is a pixel from pixel_set within a radius w of start. Then, returns start. Parameters ---------- start : :obj:`numpy.ndarray` of float The initial pixel location at which to start. pixel_set : set of 2-tupl...
382,579
def JoinKeyPath(path_segments): path_segments = [ segment.split(definitions.KEY_PATH_SEPARATOR) for segment in path_segments] path_segments = [ element for sublist in path_segments for element in sublist] path_segments = filter(None, path_segments) key_path = definitions....
Joins the path segments into key path. Args: path_segments (list[str]): Windows Registry key path segments. Returns: str: key path.
382,580
def segment_snrs(filters, stilde, psd, low_frequency_cutoff): snrs = [] norms = [] for bank_template in filters: snr, _, norm = matched_filter_core( bank_template, stilde, h_norm=bank_template.sigmasq(psd), psd=None, low_frequency_cutoff=low_frequency_c...
This functions calculates the snr of each bank veto template against the segment Parameters ---------- filters: list of FrequencySeries The list of bank veto templates filters. stilde: FrequencySeries The current segment of data. psd: FrequencySeries low_frequency_cutoff: fl...
382,581
def access_key(self, data): if data.startswith(b): new = binascii.unhexlify(data[2:]) else: new = data if len(new) == 6: self.access_code = new else: raise yubico_exception.InputError()
Set a new access code which will be required for future re-programmings of your YubiKey. Supply data as either a raw string, or a hexlified string prefixed by 'h:'. The result, after any hex decoding, must be 6 bytes.
382,582
def _to_dict(self): _dict = {} if hasattr(self, ) and self.section_titles is not None: _dict[] = [ x._to_dict() for x in self.section_titles ] if hasattr(self, ) and self.leading_sentences is not None: _dict[] = [ ...
Return a json dictionary representing this model.
382,583
def transliterate(self, target_language="en"): return WordList([w.transliterate(target_language) for w in self.words], language=target_language, parent=self)
Transliterate the string to the target language.
382,584
def SetSelected( self, node, point=None, propagate=True ): if node == self.selectedNode: return self.selectedNode = node self.UpdateDrawing() if node: wx.PostEvent( self, SquareSelectionEvent( node=node, point=point, map=self ) )
Set the given node selected in the square-map
382,585
def get_operator(self, operator): op = { : , : , : , : , : , : , : , }.get(operator) if op is not None: return op, False op = { : , : , : , ...
Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt' for '>' invert - boolean, True if this co...
382,586
def delete_contribution(self, url): try: result = self.api_request(url) if in result and in result: self.api_request(result[], method=) return True except: pass return False
Delete the contribution with this identifier :rtype: bool :returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist)
382,587
def assign(self, partitions): self._subscription.assign_from_user(partitions) self._client.set_topics([tp.topic for tp in partitions])
Manually assign a list of TopicPartitions to this consumer. Arguments: partitions (list of TopicPartition): Assignment for this instance. Raises: IllegalStateError: If consumer has already called :meth:`~kafka.KafkaConsumer.subscribe`. Warning: ...
382,588
def get_bound_form(self, noun, gender): syllables = self.syllabifier.syllabify(noun) stem = self.stemmer.get_stem(noun, gender) cv_pattern = self.cv_patterner.get_cv_pattern(stem) if [letter[0] for letter in cv_pattern[-2:]] == [, ] or stem in []: ...
Return bound form of nound, given its gender.
382,589
def datatype(dbtype, description, cursor): dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
Google AppEngine Helper to convert a data type into a string.
382,590
def cudaMemcpy_htod(dst, src, count): status = _libcudart.cudaMemcpy(dst, src, ctypes.c_size_t(count), cudaMemcpyHostToDevice) cudaCheckStatus(status)
Copy memory from host to device. Copy data from host memory to device memory. Parameters ---------- dst : ctypes pointer Device memory pointer. src : ctypes pointer Host memory pointer. count : int Number of bytes to copy.
382,591
def run(self, clock, generalLedger): for c in self.components: c.run(clock, generalLedger) for a in self.activities: a.run(clock, generalLedger)
Execute the component at the current clock cycle. :param clock: The clock containing the current execution time and period information. :param generalLedger: The general ledger into which to create the transactions.
382,592
def IPNetwork(address, version=None, strict=False): if version: if version == 4: return IPv4Network(address, strict) elif version == 6: return IPv6Network(address, strict) try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueEr...
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. version: An Integer, if set, don't try to automa...
382,593
def safe_getattr(brain_or_object, attr, default=_marker): try: value = getattr(brain_or_object, attr, _marker) if value is _marker: if default is not _marker: return default fail("Attribute not found.".format(attr)) if callable(value): ...
Return the attribute value :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param attr: Attribute name :type attr: str :returns: Attribute value :rtype: obj
382,594
def setval(self, varname, value): if varname in self: self[varname][] = value else: self[varname] = Variable(self.default_type, value=value)
Set the value of the variable with the given name.
382,595
def retrieve_pt(cls, request, service): try: pgt = cls.objects.get(user=request.user, session_key=request.session.session_key).pgt except cls.DoesNotExist: raise ProxyError( "INVALID_TICKET", "No proxy ticket found for this HttpRequest obj...
`request` should be the current HttpRequest object `service` a string representing the service for witch we want to retrieve a ticket. The function return a Proxy Ticket or raise `ProxyError`
382,596
def chunks(l:Collection, n:int)->Iterable: "Yield successive `n`-sized chunks from `l`." for i in range(0, len(l), n): yield l[i:i+n]
Yield successive `n`-sized chunks from `l`.
382,597
def handle(self, source, target, app=None, **options): translation.activate(settings.LANGUAGE_CODE) if app: unpack = app.split() if len(unpack) == 2: models = [get_model(unpack[0], unpack[1])] elif len(unpack) == 1: models = g...
command execution
382,598
def dollarfy(x): def _dollarfy(key, value, fmt, meta): if key == : return Str( + value[1] + ) return None return walk(x, _dollarfy, , {})
Replaces Math elements in element list 'x' with a $-enclosed string. stringify() passes through TeX math. Use dollarfy(x) first to replace Math elements with math strings set in dollars. 'x' should be a deep copy so that the underlying document is left untouched. Returns 'x'.
382,599
def _check_forest(self, sensors): if self in sensors: raise ValueError( % (self.name,)) sensors.add(self) for parent in self._parents: parent._check_forest(sensors)
Validate that this sensor doesn't end up referencing itself.