language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected final UtlInvLine<RS, PurchaseReturn, PurchaseReturnLine, PurchaseReturnTaxLine, PurchaseReturnGoodsTaxLine> lazyGetUtlPurRetGdLn( final Map<String, Object> pAddParam) throws Exception { UtlInvLine<RS, PurchaseReturn, PurchaseReturnLine, PurchaseReturnTaxLine, PurchaseReturnGoodsTaxLine> ut...
java
private static boolean compareOrderedCollection(Collection col1, Collection col2, Deque stack, Set visited) { // Same instance check already performed... if (col1.size() != col2.size()) { return false; } Iterator i1 = col1.iterator(); Iterator i2 = col2....
java
public static boolean samePredicate(PredicateNode p1, PredicateNode p2) { return sameResource((URIReference) p1, (URIReference) p2); }
java
@Override public boolean visit(final InjectionPlan<?> node) { if (node instanceof Constructor<?>) { return visit((Constructor<?>) node); } else if (node instanceof Subplan<?>) { return visit((Subplan<?>) node); } else if (node instanceof JavaInstance<?>) { return visit((JavaInstance<?>) ...
java
public LsQuestion getQuestion(int surveyId, int questionId) throws LimesurveyRCException { return getQuestions(surveyId).filter(question -> question.getId() == questionId) .findFirst().orElseThrow(() -> new LimesurveyRCException("No question found for id " + questionId + " in survey " + surveyId...
python
def unadvertise_endpoint(self, endpointid): """ Unadvertise a previously-advertised endpointid (string). :param endpointid. The string returned from ed.get_id() or the value of property endpoint.id. Should not be None :return True if removed, False if not removed (hasn't been...
python
def get_edxml_with_aws_urls(self): """stub""" edxml = self.get_edxml() soup = BeautifulSoup(edxml, 'xml') attrs = { 'draggable': 'icon', 'drag_and_drop_input': 'img', 'files': 'included_files', 'img': 'src' } # replace all ...
python
def _return_assoc_tuple(self, objects): """ Create the property tuple for _imethod return of references, referencenames, associators, and associatornames methods. This is different than the get/enum imethod return tuples. It creates an OBJECTPATH for each object in the return li...
python
def loxodrome_inverse(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, deg: bool = True): """ computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or ...
java
protected void updatePluginConfiguration(PluginConfiguration value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Cou...
java
public void setTrackStart(final double TRACK_START) { // check values if (Double.compare(TRACK_START, trackStop) == 0) { throw new IllegalArgumentException("Track start value cannot equal track stop value"); } trackStart = TRACK_START; validate(); fireStateCha...
python
def get_paths_goobjs(go_objs, go_top=None, go2obj=None): """Given a list of GO objects, return: paths, user GOs as ints, all GO terms paths.""" go_paths = [] # Collect all paths for go_objs go_all = set() # Collect all GO terms in all paths pathobj = GoPaths() for go_obj in go_objs: #print ...
java
public static SyncMapItemDeleter deleter(final String pathServiceSid, final String pathMapSid, final String pathKey) { return new SyncMapItemDeleter(pathServiceSid, pathMapSid, pathKey); }
python
def parse_pagination_dict(cls, response_obj): """ :type response_obj: dict :rtype: dict """ pagination_dict = {} cls.update_dict_id_field_from_response_field( pagination_dict, cls._FIELD_OLDER_ID, response_obj, cls._FIELD...
java
private static <T> void awaitSettle(final List<IPromise<T>> futures, final IPromise result) { PromiseLatch latch = new PromiseLatch(futures.size()); latch.getPromise().then( () -> result.complete(futures, null) ); futures.forEach( fut -> fut.then( () -> latch.countDown() ) ); }
python
def updateperms(self, action, groups): """ A method to update the permissions (group membership) of a bugzilla user. :arg action: add, remove, or set :arg groups: list of groups to be added to (i.e. ['fedora_contrib']) """ self.bugzilla.updateperms(self.name, act...
java
private Source register(Source source) { /** * As promised, the registrar simply abstracts away internal resolvers * by iterating over them during the registration process. */ for (Resolver resolver : resolvers) { resolver.register(source); } ...
java
@XmlElementDecl(namespace = "http://www.opengis.net/citygml/relief/2.0", name = "MassPointRelief", substitutionHeadNamespace = "http://www.opengis.net/citygml/relief/2.0", substitutionHeadName = "_ReliefComponent") public JAXBElement<MassPointReliefType> createMassPointRelief(MassPointReliefType value) { re...
java
protected void logJobProperties() { if (this.jobProps != null && this.jobProps.getBoolean(JOB_DUMP_PROPERTIES_IN_LOG, false)) { try { final Map<String, String> flattenedProps = this.jobProps.getFlattened(); this.info("****** Job properties ******"); this.info(String.format(...
java
public final void setDuration(int duration) { if (isComplete()) { this.getLogger() .warn( "{} is already closed, the new duration of {} will be ignored on: {}", this.getClass().getSimpleName(), du...
python
def add(self, observation, action, reward, terminal, *args): """Append artificial_done to *args and run parent method.""" # If this will be a problem for maintenance, we could probably override # DQNAgent.add() method instead. artificial_done = self._artificial_done and terminal args = list(args) ...
python
def gmove(pattern, destination): """Move all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise. """ for item ...
python
def get_page_objects_by_ext_type(context, object_type): """ **Arguments** ``object_type`` object type :return selected objects """ try: objects = context['page']['ext_content'][object_type] except KeyError: raise template.TemplateSyntaxError('wrong content type: {0:...
java
public OvhAsyncTask<OvhHubicDetailsResponse> packName_hubic_services_domain_details_GET(String packName, String domain) throws IOException { String qPath = "/pack/xdsl/{packName}/hubic/services/{domain}/details"; StringBuilder sb = path(qPath, packName, domain); String resp = exec(qPath, "GET", sb.toString(), nul...
python
def ip_shell_after_exception(frame): """ Launches an IPython embedded shell in the namespace where an exception occurred. :param frame: :return: """ # let the user know, where this shell is 'waking up' # construct frame list # this will be printed in the header frame_info_list = []...
java
@SuppressWarnings("unchecked") public void addExtensionFactory(ExtensionFactory factory) { synchronized (lock) { if (initialized) { if (null == extensionFactories) { extensionFactories = new ArrayList(); } if(!extensionFactories...
python
def _parse_attributes(self, element_name, package_class, namespace=''): """ Returns an instance of the package_class instantiated with a dictionary of the attributes from element_name in the specified namespace of the RSS feed. """ return package_class( self._...
python
def rouge_l_sentence_level(evaluated_sentences, reference_sentences): """ Computes ROUGE-L (sentence level) of two text collections of sentences. http://research.microsoft.com/en-us/um/people/cyl/download/papers/ rouge-working-note-v1.3.1.pdf Calculated according to: R_lcs = LCS(X,Y)/m P_lc...
python
def process_entities(self, tlo): """Processes all the found entities on the given TLObject, unless .enabled is False. Returns True if new input entities were added. """ if not self.save_entities: return rows = self._entities_to_rows(tlo) if not...
python
def on(self, day, strict=False): """Iterates (in chronological order) over all events that occurs on `day` Args: day (Arrow object) strict (bool): if True events will be returned only if they are\ strictly *included* in `day`. """ day_start, day_stop ...
python
def _fill_vao(self): """Put array location in VAO for shader in same order as arrays given to Mesh.""" with self.vao: self.vbos = [] for loc, verts in enumerate(self.arrays): vbo = VBO(verts) self.vbos.append(vbo) self.vao.assign_ve...
java
BackedSession getSession(String id, int versionId, boolean isSessionAccess, boolean retrieval) { //create local variable - JIT performance improvement final boolean isTraceOn = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled(); //id coming in does NOT have the Cache ID at the front. ...
java
public static void write(String text, String contentType) { setContentType(contentType); Writer writer = null; try { writer = getWriter(); writer.write(text); writer.flush(); } catch (IOException e) { throw new RenderException("Error when output to client!", e); } finally { IoUtil.clo...
java
public void validate(FacesContext context) { if (context == null) { throw new NullPointerException(); } // Submitted value == null means "the component was not submitted // at all". Object submittedValue = getSubmittedValue(); if (submittedValue == null) {...
java
public List<JavaResource> getProjectQualifiers(Project project) { final List<JavaResource> qualifiers = new ArrayList<>(); if (project != null) { project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaResourceVisitor() { @Override public void visi...
java
public static byte[] readToNull(InputStream is, int maxSize) throws IOException { byte[] bytes = new byte[maxSize]; int i = 0; while(i < maxSize) { int b = is.read(); if(b == -1) { throw new EOFException("NO NULL"); } bytes[i] = (byte) (b & 0xff); i++; if(b == 0) { return copy(bytes,0...
java
public void resetAutoLoadLastLoadTime(CacheKeyTO cacheKey) { if (null == autoLoadMap) { return; } AutoLoadTO autoLoadTO = autoLoadMap.get(cacheKey); if (null != autoLoadTO && !autoLoadTO.isLoading()) { autoLoadTO.setLastLoadTime(1L); } }
python
def watched(self, option): """ Set whether to filter by a user's watchlist. Options available are user.ONLY, user.NOT, and None; default is None. """ params = join_params(self.parameters, {"watched": option}) return self.__class__(**params)
java
public Block<S, L> getBlockForState(S origState) { State<S, L> state = stateStorage.get(origState); return state.getBlock(); }
python
def get_interesting_members(base_class, cls): """Returns a list of methods that can be routed to""" base_members = dir(base_class) predicate = inspect.ismethod if _py2 else inspect.isfunction all_members = inspect.getmembers(cls, predicate=predicate) return [member for member in all_members ...
python
def create_repo(self, name, description=github.GithubObject.NotSet, homepage=github.GithubObject.NotSet, private=github.GithubObject.NotSet, has_issues=github.GithubObject.NotSet, has_wiki=github.GithubObject.NotSet, has_downloads=github.GithubObject.NotSet, h...
java
@SuppressWarnings("unchecked") public <R> DynamoDBMapperFieldModel<T,R> rangeKey() { final DynamoDBMapperFieldModel<T,R> field = (DynamoDBMapperFieldModel<T,R>)keys.get(RANGE); if (field == null) { throw new DynamoDBMappingException( targetType.getSimpleName() + "; no map...
python
def unpack_scalar(cls, dataset, data): """ Given a dataset object and data in the appropriate format for the interface, return a simple scalar. """ if len(data) != 1: return data key = list(data.keys())[0] if len(data[key]) == 1 and key in dataset.vdi...
python
def export_data(filename_or_fobj, data, mode="w"): """Return the object ready to be exported or only data if filename_or_fobj is not passed.""" if filename_or_fobj is None: return data _, fobj = get_filename_and_fobj(filename_or_fobj, mode=mode) source = Source.from_file(filename_or_fobj, mode...
java
public void decrypt(KeyParameter aesKey) { checkNotNull(aesKey); BasicKeyChain newBasic = basic.toDecrypted(aesKey); if (chains != null) { List<DeterministicKeyChain> newChains = new ArrayList<>(chains.size()); for (DeterministicKeyChain chain : chains) n...
java
public static Color decodeColor(String s) { if (s == null) return null; s = s.toLowerCase().trim(); try { return WebColors.getRGBColor(s); } catch(IllegalArgumentException iae) { return null; } }
java
public static JarFile createJar() throws IOException, URISyntaxException { URL location = faspmanager2.class.getProtectionDomain().getCodeSource().getLocation(); return new JarFile(new File(location.toURI())); }
java
protected void applyHiddenRegionFormatting(List<ITextReplacer> replacers) { IHiddenRegionFormatting separator = findWhitespaceThatSeparatesSemanticRegions(replacers).getFormatting(); // 1. apply indentation Integer inc = formatting.getIndentationIncrease(); Integer dec = formatting.getIndentationDecrease(); ...
python
def _run_nb_cmd(self, cmd): ''' cmd iterator ''' try: proc = salt.utils.nb_popen.NonBlockingPopen( cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, ) while True: ...
java
public static void setInputWhereClauses(Configuration conf, String clauses) { if (clauses == null || clauses.isEmpty()) return; conf.set(INPUT_CQL_WHERE_CLAUSE_CONFIG, clauses); }
java
HdfsFileStatus[] getHdfsListing(String src) { // prepare components outside of readLock String srcs = normalizePath(src); byte[][] components = INodeDirectory.getPathComponents(srcs); readLock(); try { INode targetNode = rootDir.getNode(components); if (targetNode == null) ...
java
public static FuncN<Observable<Void>> toAsync(ActionN action) { return toAsync(action, Schedulers.computation()); }
java
private Response downloadArtifact(Node node) throws Exception { NodeRepresentation nodeRepresentation = nodeRepresentationService.getNodeRepresentation(node, null); if (node.canAddMixin("exo:mavencounter")) { node.addMixin("exo:mavencounter"); node.getSession().save(); } ...
java
@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "geq") public JAXBElement<RelationsType> createGeq(RelationsType value) { return new JAXBElement<RelationsType>(_Geq_QNAME, RelationsType.class, null, value); }
python
def ensure_dir(path): """Create all parent directories of path if they don't exist. Args: path. Path-like object. Create parent dirs to this path. Return: None. """ os.makedirs(os.path.abspath(os.path.dirname(path)), exist_ok=True)
python
def get_networks(base_file, ipaddr_file): """ Gather network and host information from ipplan export files. """ networks = [] base = open(base_file, 'r') csv_reader = csv.reader(base, delimiter='\t') buffer = "" for row in csv_reader: # Fixes quotation bug in ipplan exporter for base...
java
public void cancelAllReservations() { // Inform jobs which have reserved slots on this tasktracker if (jobForFallowMapSlot != null) { unreserveSlots(TaskType.MAP, jobForFallowMapSlot); } if (jobForFallowReduceSlot != null) { unreserveSlots(TaskType.REDUCE, jobForFallowReduceSlot); } }
python
def list_(package='', cyg_arch='x86_64'): ''' List locally installed packages. package : '' package name to check. else all cyg_arch : Cygwin architecture to use Options are x86 and x86_64 CLI Example: .. code-block:: bash salt '*' cyg.list ''' pkgs =...
python
def parse_options(): """ Parses command-line option """ try: opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx', ['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo', 'minimize', 'solver=', 'trim=', 'verbose']) except getopt.GetoptErro...
java
private static String factorizeFullness(long bitmapCardinality, long numRows) { if (bitmapCardinality == 0) { return "0"; } else if (bitmapCardinality == numRows) { return "1"; } else { double fullness = bitmapCardinality / (double) numRows; int index = Arrays.binarySearch(BITMAP_F...
python
def skip_item_key(self, item, key): """Add the key to the item's "skip" list """ if "skip" in item: item["skip"].append(key) else: item["skip"] = [key] return item
java
public String[] queryVsanObjectUuidsByFilter(String[] uuids, int limit, int version) throws VsanFault, RemoteException, RuntimeFault { return getVimService().queryVsanObjectUuidsByFilter(getMOR(), uuids, limit, version); }
java
@Override public Period until(ChronoLocalDate endDateExclusive) { LocalDate end = LocalDate.from(endDateExclusive); long totalMonths = end.getProlepticMonth() - this.getProlepticMonth(); // safe int days = end.day - this.day; if (totalMonths > 0 && days < 0) { totalMonth...
python
def insertDataset(self, blockcontent, otptIdList, migration=False): """ This method insert a datsset from a block object into dbs. """ dataset = blockcontent['dataset'] conn = self.dbi.connection() # First, check and see if the dataset exists. try: da...
python
def _proxy_connect(name, method_name, kwargs, econtext): """ Implements the target portion of Router._proxy_connect() by upgrading the local context to a parent if it was not already, then calling back into Router._connect() using the arguments passed to the parent's Router.connect(). :returns:...
java
public Response serve( String uri, String method, Properties header, Properties parms ) { myOut.println( method + " '" + uri + "' " ); Enumeration e = header.propertyNames(); while ( e.hasMoreElements()) { String value = (String)e.nextElement(); myOut.println( " HDR: '" + value + "' = '"...
java
public static void unsetCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker) throws PBFactoryException { HashMap map = (HashMap) currentBrokerMap.get(); WeakHashMap set = null; if(map != null) { set = (WeakHashMap) map.get(key); ...
python
def get_service_task( service_name, task_name, inactive=False, completed=False ): """ Get a dictionary describing a service task, or None :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str...
java
public ServiceBuilder withStreamSegmentStore(Function<ComponentSetup, StreamSegmentStore> streamSegmentStoreCreator) { Preconditions.checkNotNull(streamSegmentStoreCreator, "streamSegmentStoreCreator"); this.streamSegmentStoreCreator = streamSegmentStoreCreator; return this; }
python
def submit(self): """ Posts the form's data and returns the resulting Page Returns Page - The resulting page """ u = urlparse(self.url) if not self.action: self.action = self.url elif self.action == u.path: self.acti...
java
private void removeClientId(String clientId) { //Sometimes the client Id will be null. For instance in the case QueueConnectionFactory, there is no default client Id specified in metatype.xml. if (clientId == null) return; //do nothing ConcurrentHashMap<String, Integer> clientIdTab...
java
static int getMethodId(Method method, Method[] allMethods, int startIndex) { int numMethods = allMethods.length; for (int i = startIndex; i < numMethods; ++i) { if (methodsMatch(method, allMethods[i])) return i...
python
def _init_randgen(self): """ Initialise random generator to be used for picking elements. With the current implementation in tohu (where we pick elements from generators individually instead of in bulk), it is faster to `use random.Random` than `numpy.random.RandomState` (it is ...
python
def bot(app, debug): """Run the experiment bot.""" if debug is None: verify_id(None, None, app) (id, tmp) = setup_experiment(log) if debug: url = debug else: heroku_app = HerokuApp(dallinger_uid=app) worker = generate_random_id() hit = generate_random_id() ...
python
def lindex(self, key, index): """Emulate lindex.""" redis_list = self._get_list(key, 'LINDEX') if self._encode(key) not in self.redis: return None try: return redis_list[index] except (IndexError): # Redis returns nil if the index doesn't ex...
python
def _len_lcs(x, y): """ Returns the length of the Longest Common Subsequence between sequences x and y. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence :param x: sequence of words :param y: sequence of words :returns integer: Length of LCS between x and y """ ...
python
def __get_response_element_data(self, key1, key2): """ For each origin an elements object is created in the ouput. For each destination, an object is created inside elements object. For example, if there are 2 origins and 1 destination, 2 element objects with 1 object each are created. I...
python
def ps(self): """ View active queries with execution time. Record( pid=28023, source='pgbench', running_for=datetime.timedelta(0, 0, 288174), waiting=0, query='UPDATE pgbench_accounts SET abalance = abalance + 423;' ) ...
python
def load_state_dict(self, state_dict: Dict[str, Any]) -> None: """ Load the schedulers state. Parameters ---------- state_dict : ``Dict[str, Any]`` Scheduler state. Should be an object returned from a call to ``state_dict``. """ self.__dict__.update(s...
python
def annotations_class(cls): """Works like annotations, but is only applicable to classes. """ assert(isclass(cls)) # To play it safe we avoid to modify the dict while iterating over it, # so we previously cache keys. # For this we don't use keys() because of Python 3. # Todo: Better use insp...
python
def check_order(self): """ Performs the check and store the violations in self.violations. :return: boolean indicating the error state """ for feature, info in self.constraints.items(): self._check_feature(feature, info, 'before') self._check_feature(feat...
java
public boolean reverseTransformPacket(RawPacket pkt) { int seqNo = pkt.getSequenceNumber(); if (!seqNumSet) { seqNumSet = true; seqNum = seqNo; } // Guess the SRTP index (48 bit), see rFC 3711, 3.3.1 // Stores the guessed roc in this.guessedROC long guessedIndex = guessIndex(seqNo); // Replay c...
python
def append(self, val): """Appends the object to the end of the values list. Will also set the value to the first item in the values list :param val: Object to append :type val: primitive """ self.values.append(val) self.value = self.values[0]
java
public void remove(RowKey key) { currentState.put( key, new AssociationOperation( key, null, REMOVE ) ); }
python
async def approve(self, remark: str = '') -> None: """ Approve the request. :param remark: remark of friend (only works in friend request) """ try: await self.bot.call_action( action='.handle_quick_operation_async', self_id=self.ctx.ge...
python
def _group_by_area(self, datasets): """Group datasets by their area.""" def _area_id(area_def): return area_def.name + str(area_def.area_extent) + str(area_def.shape) # get all of the datasets stored by area area_datasets = {} for x in datasets: area_id =...
python
def __evaluation_error(self, result, condition, throw): """Helper-method for easy error-logging""" self.log.error("Result does not match condition, dropping item. " "Result %s; Condition: %s; Throw: %s", result, condition, throw) return False
python
def _on_axes_updated(self): """Method to run when axes are changed in any way. Propagates updated axes properly. """ # update attrs self.attrs["axes"] = [a.identity.encode() for a in self._axes] # remove old attributes while len(self._current_axis_identities_in_n...
python
def _map_arguments(self, args): """Map from the top-level arguments to the arguments provided to the indiviudal links """ data = args.get('data') comp = args.get('comp') library = args.get('library') dry_run = args.get('dry_run', False) self._set_link('sum-rings'...
java
public static long[] convertToArrayLongs(final Block[] blockArray) { long[] blocksAsLongs = new long[blockArray.length * LONGS_PER_BLOCK]; BlockListAsLongs bl = new BlockListAsLongs(blocksAsLongs); assert bl.getNumberOfBlocks() == blockArray.length; for (int i = 0; i < blockArray.length; i++) { ...
java
public synchronized void startup() throws IllegalStateException, RuntimeException { if (agiServer == null) { throw new IllegalStateException("Mandatory property agiServer is not set."); } if (thread != null) { throw new IllegalStateException("AgiServe...
python
def optimize_fn(model, optimizer=None, learning_rate_schedule=None, loss=None, metrics=None): """Compile the model in Keras.""" learning_rate_schedule = learning_rate_schedule or T2TLearningRateSchedule() if optimizer: optimizer = optimizer(learn...
python
def jplace_split(self, original_jplace, cluster_dict): ''' To make GraftM more efficient, reads are dereplicated and merged into one file prior to placement using pplacer. This function separates the single jplace file produced by this process into the separate jplace files, one ...
java
public Node chooseRandom(String scope) { netlock.readLock().lock(); try { if (scope.startsWith("~")) { return chooseRandom(NodeBase.ROOT, scope.substring(1)); } else { return chooseRandom(scope, null); } } finally { netlock.readLock().unlock(); } }
python
def aer2geodetic(az: float, el: float, srange: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool = True) -> Tuple[float, float, float]: """ gives geodetic coordinates of a point with az, el, range from an observer at lat0, lon0, h0 Parame...
python
def register_json_encoder(self, encoder_type: type, encoder: JSONEncoder): """ Register the given JSON encoder for use with the given object type. :param encoder_type: the type of object to encode :param encoder: the JSON encoder :return: this builder """ self._js...
python
def update(self, component_id, name=None, status=None, description=None, link=None, order=None, group_id=None, enabled=True): """Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the com...
java
@GET @Path("{id}/status") @Produces(APPLICATION_JSON) @Timed @ExceptionMetered public Optional<HostStatus> hostStatus( @PathParam("id") final String host, @QueryParam("status") @DefaultValue("") final String statusFilter) { final HostStatus status = model.getHostStatus(host); final Optiona...
python
def add_hypermedia(self, obj): ''' Adds HATEOAS links to the resource. Adds href link to self. Override in subclasses to include additional functionality ''' if hasattr(self, 'pk'): obj['_links'] = { 'self': { 'href': '{}{}/'.format...
python
def submit(self, stanza): """Adds keys to the current configuration stanza as a dictionary of key-value pairs. :param stanza: A dictionary of key-value pairs for the stanza. :type stanza: ``dict`` :return: The :class:`Stanza` object. """ body = _encode(**stanza) ...