language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def add_with_properties(self, model, name=None, update_dict=None, bulk=True, **kwargs): """ Add a part and update its properties in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method....
python
def resourcetypes(rid, model): ''' Return a list of Versa types for a resource ''' types = [] for o, r, t, a in model.match(rid, VTYPE_REL): types.append(t) return types
java
public void open() throws IOException { mConnection.connect(); mContentType = mConnection.getContentType(); mResponseCode = mConnection.getResponseCode(); mContentEncoding = mConnection.getContentEncoding(); }
java
public void putLongField(HttpHeader name, long value) { String v = Long.toString(value); put(name, v); }
python
def _UpdateChildIndex(self, urn, mutation_pool): """Update the child indexes. This function maintains the index for direct child relations. When we set an AFF4 path, we always add an attribute like index:dir/%(childname)s to its parent. This is written asynchronously to its parent. In order to...
python
def set_grant_type(self, grant_type = 'client_credentials', api_key=None, api_secret=None, scope=None, info=None): """ Grant types: - token: An authorization is requested to the end-user by redirecting it to an authorization page hosted on Dailymotion. Once authorized, ...
python
def create_key(self, name, convergent_encryption=False, derived=False, exportable=False, allow_plaintext_backup=False, key_type="aes256-gcm96", mount_point=DEFAULT_MOUNT_POINT): """Create a new named encryption key of the specified type. The values set here cannot be changed after ke...
java
private int utf8Position(int charPosition) { int pos = offset; for (int i = 0; i < charPosition; i++) { int byteValue = data[pos] & 0xff; if (byteValue < 0x80) { pos += 1; } else if (byteValue < 0xC2) { throw new UncheckedIOException("invalid UTF8", new CharacterCodingException...
java
public static CPDefinitionInventory fetchByUuid_Last(String uuid, OrderByComparator<CPDefinitionInventory> orderByComparator) { return getPersistence().fetchByUuid_Last(uuid, orderByComparator); }
python
def saveSettings(self): """ Saves the persistent settings. Only saves the profile. """ try: self.saveProfile() except Exception as ex: # Continue, even if saving the settings fails. logger.warn(ex) if DEBUGGING: raise ...
python
def handle_404(request, exception): '''Handle 404 Not Found This handler should be used to handle error http 404 not found for all endpoints or if resource not available. ''' error = format_error(title='Resource not found', detail=str(exception)) return json(return_an_error(error), status=HTTPSt...
java
@XmlElementDecl(namespace = "urn:switchyard-quickstart-demo:library:1.0", name = "loanResponse") public JAXBElement<LoanResponse> createLoanResponse(LoanResponse value) { return new JAXBElement<LoanResponse>(LOAN_RESPONSE_QNAME, LoanResponse.class, null, value); }
java
public static <T> List<T> deserializeContainer(Response response, Class<T> type) throws IOException, StreamException { return deserializeContainer(response, "results", type); }
java
public void setActionConfigurationProperties(java.util.Collection<ActionConfigurationProperty> actionConfigurationProperties) { if (actionConfigurationProperties == null) { this.actionConfigurationProperties = null; return; } this.actionConfigurationProperties = new java...
python
def dont_cache(): """ Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0. """ def decorate_func(func): @wraps(func) def decorate_func_call(*a, **kw): callback = SetCacheControlHeadersForNoCachingCal...
java
private void addPriorityInfo(BannerComponents bannerComponents, int index) { Integer abbreviationPriority = bannerComponents.abbreviationPriority(); if (abbreviations.get(abbreviationPriority) == null) { abbreviations.put(abbreviationPriority, new ArrayList<Integer>()); } abbreviations.get(abbrevi...
java
public static void registerExceptionHandler(RegisterableExceptionHandler exceptionHandlerDelegate) { AwtExceptionHandlerAdapterHack.exceptionHandlerDelegate = exceptionHandlerDelegate; // Registers this class with the system properties so Sun's JDK can pick it up. Always sets even if previously set. ...
java
void computeSyndromes( GrowQueue_I8 input , GrowQueue_I8 ecc , GrowQueue_I8 syndromes) { syndromes.resize(syndromeLength()); for (int i = 0; i < syndromes.size; i++) { int val = math.power(2,i); syndromes.data[i] = (byte)math.polyEval(input,val); syndromes.data[i] = (byte)math.polyEvalCo...
java
public void setPerformance(int evaluation, double value) { if ((m_Metrics != null) && !m_Metrics.check(evaluation)) return; m_MetricValues.put(evaluation, value); }
python
def normalize(self): """ Normalize the path. Turn /file/title/../author to /file/author :return: <self> """ if str(self): normalized = normpath(str(self)) + ('/' * self.is_dir) if normalized.startswith('//'): # http://bugs.python.org/636648 ...
python
def restrict_to_polygon(feed: "Feed", polygon: Polygon) -> "Feed": """ Build a new feed by restricting this one to only the trips that have at least one stop intersecting the given Shapely polygon, then restricting stops, routes, stop times, etc. to those associated with that subset of trips. Re...
python
def get_frequency_list(lang, wordlist='best', match_cutoff=30): """ Read the raw data from a wordlist file, returning it as a list of lists. (See `read_cBpack` for what this represents.) Because we use the `langcodes` module, we can handle slight variations in language codes. For example, looking f...
java
public Enumeration<String> getElements() { AttributeNameEnumeration elements = new AttributeNameEnumeration(); elements.addElement(PERMITTED_SUBTREES); elements.addElement(EXCLUDED_SUBTREES); return (elements.elements()); }
java
public static final Duration getDuration(InputStream is) throws IOException { double durationInSeconds = getInt(is); durationInSeconds /= (60 * 60); return Duration.getInstance(durationInSeconds, TimeUnit.HOURS); }
python
def subjects_list(self, limit=-1, offset=-1): """Retrieve list of all subjects in the data store. Parameters ---------- limit : int Limit number of results in returned object listing offset : int Set offset in list (order as defined by object store) ...
java
public void run() { this.serverSocket = null; try { Log(Level.INFO, "Attempting to create SocketServer..."); // If requrestedPortNumber is 0 and we have a range of ports specified, then attempt to allocate a port dynamically from that range. if (this.reque...
java
public void createApplication(String nic, String password) throws IOException { String url = "https://eu.api.ovh.com/createApp/"; Document doc = Jsoup.connect(url) .data("nic", nic) .data("password", password) .data("applicationName", "One Shoot Token") .data("applicationDescription", "One Shoot Tok...
python
def mode(self, mode): """Set Arlo camera mode. :param mode: arm, disarm """ modes = self.available_modes if (not modes) or (mode not in modes): return self.publish( action='set', resource='modes' if mode != 'schedule' else 'schedule', ...
python
def create_cloud(self): """ Create instances for the cloud providers """ instances = [] for i in range(self.settings['NUMBER_NODES']): new_instance = Instance.new(settings=self.settings, cluster=self) instances.append(new_instance) create_nodes = ...
java
public BatchListObjectPoliciesResponse withAttachedPolicyIds(String... attachedPolicyIds) { if (this.attachedPolicyIds == null) { setAttachedPolicyIds(new java.util.ArrayList<String>(attachedPolicyIds.length)); } for (String ele : attachedPolicyIds) { this.attachedPolicyI...
java
String makeInList(final String cell) { if (cell.startsWith("(")) { return cell; } String result = ""; Iterator<String> iterator = Arrays.asList(ListSplitter.split("\"", true, ...
java
public DataSetBuilder random(String column, Timestamp min, Timestamp max) { ensureValidRange(min, max); final long a = min.getTime() * NANO_PER_MSEC + min.getNanos(); final long n = max.getTime() * NANO_PER_MSEC + max.getNanos() - a + 1; return set(column, () -> { long v = a + rng....
python
def leave_room(room, sid=None, namespace=None): """Leave a room. This function removes the user from a room, under the current namespace. The user and the namespace are obtained from the event context. Example:: @socketio.on('leave') def on_leave(data): username = session['user...
java
public int countDifferencesBetweenIgnoreWhitespaceAnd(String first, String second) { String cleanFirst = allWhitespaceToSingleSpace(first); String cleanSecond = allWhitespaceToSingleSpace(second); return countDifferencesBetweenAnd(cleanFirst, cleanSecond); }
python
def connect_vpc(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.vpc.VPCConnectio...
java
public static <T> Predicate<T> memoizePredicate(final Predicate<T> p, final Cacheable<Boolean> cache) { final Function<T, Boolean> memoised = memoizeFunction((Function<T, Boolean>) t -> p.test(t), cache); LazyImmutable<Boolean> nullR = LazyImmutable.def(); return (t) -> t==null? nullR.computeIfA...
java
@Override public void handleServerEvent(ISFSEvent event) throws SFSException { Zone sfsZone = (Zone) event.getParameter(SFSEventParam.ZONE); User sfsUser = (User) event.getParameter(SFSEventParam.USER); User recipient = (User)event.getParameter(SFSEventParam.RECIPIENT); String messag...
java
public void marshall(TrainingSpecification trainingSpecification, ProtocolMarshaller protocolMarshaller) { if (trainingSpecification == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(trainingSpecific...
java
public static int toIntWithDefault(String value, int defaultValue) { int result = defaultValue; try { result = Integer.parseInt(value); } catch (@SuppressWarnings("unused") Exception e) { // Do nothing, return default. } return result; }
python
def reviewed_badge(user, talk): """Returns a badge for the user's reviews of the talk""" context = { 'reviewed': False, } review = None if user and not user.is_anonymous(): review = talk.reviews.filter(reviewer=user).first() if review: context['reviewed'] = True ...
java
static boolean isAdapterType(Element element, Elements elements, Types types) { TypeMirror typeAdapterType = types.getDeclaredType( elements.getTypeElement(TYPE_ADAPTER_CLASS_NAME), types.getWildcardType(null, null)); return types.isAssignable(element.asType(), typeAdapterType); }
java
public static List<CommercePriceEntry> toModels( CommercePriceEntrySoap[] soapModels) { if (soapModels == null) { return null; } List<CommercePriceEntry> models = new ArrayList<CommercePriceEntry>(soapModels.length); for (CommercePriceEntrySoap soapModel : soapModels) { models.add(toModel(soapModel));...
python
def get_impact_report_as_string(analysis_dir): """Retrieve an html string of table report (impact-report-output.html). :param analysis_dir: Directory of where the report located. :type analysis_dir: str :return: HTML string of the report. :rtype: str """ html_report_products = [ 'i...
java
public java.util.List<String> getVpcIds() { if (vpcIds == null) { vpcIds = new com.amazonaws.internal.SdkInternalList<String>(); } return vpcIds; }
python
def _copy_interfaces_info(interfaces): ''' Return a dictionary with a copy of each interface attributes in ATTRS ''' ret = {} for interface in interfaces: _interface_attrs_cpy = set() for attr in ATTRS: if attr in interfaces[interface]: attr_dict = Hashab...
python
def intr_write(self, dev_handle, ep, intf, data, timeout): r"""Perform an interrupt write. dev_handle is the value returned by the open_device() method. The ep parameter is the bEndpointAddress field whose endpoint the data will be sent to. intf is the bInterfaceNumber field of ...
java
public final void mDOUBLE_PIPE() throws RecognitionException { try { int _type = DOUBLE_PIPE; int _channel = DEFAULT_TOKEN_CHANNEL; // src/main/resources/org/drools/compiler/lang/DRL6Lexer.g:275:5: ( '||' ) // src/main/resources/org/drools/compiler/lang/DRL6Lexer.g:275:7: '||' { match("||"); if (sta...
python
def dumps(x, float_bits=DEFAULT_FLOAT_BITS): """ Dump data structure to str. Here float_bits is either 32 or 64. """ with lock: if float_bits == 32: encode_func[float] = encode_float32 elif float_bits == 64: encode_func[float] = encode_float64 else: ...
java
private void refillEntry(int baseHash) { K key = _keys[baseHash]; V value = _values[baseHash]; _keys[baseHash] = null; _values[baseHash] = null; int hash = key.hashCode() & _mask; for (int count = _size; count >= 0; count--) { if (_values[hash] == null) { _keys[hash] = key; ...
python
def format_help(self): """Sets up all sub-parsers when help is requested.""" if self._subparsers: for action in self._subparsers._actions: if isinstance(action, LazySubParsersAction): for parser_name, parser in action._name_parser_map.iteritems(): ...
java
public synchronized void updateNextBuildNumber(int next) throws IOException { RunT lb = getLastBuild(); if (lb!=null ? next>lb.getNumber() : next>0) { this.nextBuildNumber = next; saveNextBuildNumber(); } }
python
def _close_connection(self): """Close the connection to the easyfire unit.""" if (self._mode == PROP_MODE_SERIAL): self._serial.close() elif (self._mode == PROP_MODE_TCP): self._socket.close() elif (self._mode == PROP_MODE_FILE): self._file.close()
python
def _process_orthologs(self, raw, limit=None): """ This method maps orthologs for a species to the KEGG orthology classes. Triples created: <gene_id> is a class <orthology_class_id> is a class <assoc_id> has subject <gene_id> <assoc_id> has object <orthology_cla...
java
private static boolean isOrderByNodeRequired(AbstractParsedStmt parsedStmt, AbstractPlanNode root) { // Only sort when the statement has an ORDER BY. if ( ! parsedStmt.hasOrderByColumns()) { return false; } // Skip the explicit ORDER BY plan step if an IndexScan is already p...
java
public Token[] tokenize(String input) { List tokens = new ArrayList(); int cursor = 0; while (cursor<input.length()) { char ch = input.charAt(cursor); if (Character.isWhitespace(ch)) { cursor++; } else if (Character.isLetter(ch)) { StringBuffer...
python
def update(self, story, params={}, **options): """Updates the story and returns the full record for the updated story. Only comment stories can have their text updated, and only comment stories and attachment stories can be pinned. Only one of `text` and `html_text` can be specified. P...
java
@Override public void setVersion(int version) { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) { StringBuffer sb = new StringBuffer(newValueString).append(version).append(oldValueString).append(_version).append(appNameAndIdStri...
java
@Override public int getDiscardedResultsCount() { if (queryResults instanceof DiscardingBlockingQueue) { DiscardingBlockingQueue discardingBlockingQueue = (DiscardingBlockingQueue) queryResults; return discardingBlockingQueue.getDiscardedElementCount(); } else { r...
java
public InputStream get(String remoteFile, FileTransferProgress progress) throws SshException, ChannelOpenException { ScpEngineIO scp = new ScpEngineIO("scp " + "-f " /* + (verbose ? "-v " : "") */ + remoteFile, ssh.openSessionChannel()); try { return scp.readStreamFromRemote(remoteFile, progress); } ca...
python
def simple_cnn(actns:Collection[int], kernel_szs:Collection[int]=None, strides:Collection[int]=None, bn=False) -> nn.Sequential: "CNN with `conv_layer` defined by `actns`, `kernel_szs` and `strides`, plus batchnorm if `bn`." nl = len(actns)-1 kernel_szs = ifnone(kernel_szs, [3]*nl) stride...
python
def makePrintReturner(pre="", post="" ,out=None): r"""Creates functions that print out their argument, (between optional `pre` and `post` strings) and return it unmodified. This is usefull for debugging e.g. parts of expressions, without having to modify the behavior of the program. Example: >...
java
public static byte[] messageDigest(String value) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); md5.update(value.getBytes("UTF-8")); return md5.digest(); } catch (NoSuchAlgorithmException e) { throw new SofaRpcRuntimeException("...
java
public static void addToMap(final Map<String, VerbatimSerializer> serializerMap) { PlantUmlVerbatimSerializer serializer = new PlantUmlVerbatimSerializer(); for (Type type : Type.values()) { String name = type.getName(); serializerMap.put(name, serializer); } }
python
def object2code(key, code): """Returns code for widget from dict object""" if key in ["xscale", "yscale"]: if code == "log": code = True else: code = False else: code = unicode(code) return code
java
protected void validate(String operationType) throws Exception { super.validate(operationType); MPSInt polling_interval_validator = new MPSInt(); polling_interval_validator.setConstraintMinValue(MPSConstants.GENERIC_CONSTRAINT, 1); polling_interval_validator.setConstraintMaxValue(MPSConstants.GENERIC_CO...
python
def id(opts): ''' Return a unique ID for this proxy minion. This ID MUST NOT CHANGE. If it changes while the proxy is running the salt-master will get really confused and may stop talking to this minion ''' r = salt.utils.http.query(opts['proxy']['url']+'id', decode_type='json', decode=True) ...
python
def op(cls,text,*args,**kwargs): """ This method must be overriden in derived classes """ return cls.fn(text,*args,**kwargs)
java
public JBBPTextWriter SetTabSpaces(final int numberOfSpacesPerTab) { if (numberOfSpacesPerTab <= 0) { throw new IllegalArgumentException("Tab must contains positive number of space chars [" + numberOfSpacesPerTab + ']'); } final int currentIdentSteps = this.indent / this.spacesInTab; this.spacesIn...
python
def compose_post(apikey, resize, rotation, noexif): """ composes basic post requests """ check_rotation(rotation) check_resize(resize) post_data = { 'formatliste': ('', 'og'), 'userdrehung': ('', rotation), 'apikey': ('', apikey) } if resize ...
java
@Override public void dump(DumperContext dumpContext) throws DumpException { ensureInitialized(); List<String> args = dumpContext.getArgsAsList(); PrintStream writer = dumpContext.getStdout(); String cmd = args.isEmpty() ? null : args.get(0); List<String> rest = args.isEmpty() ? new ArrayList<Str...
java
@Override public ListCreateAccountStatusResult listCreateAccountStatus(ListCreateAccountStatusRequest request) { request = beforeClientExecution(request); return executeListCreateAccountStatus(request); }
java
private void encodeBytesBody(StringBuffer result, JsJmsBytesMessage msg) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "encodeBytesBody"); byte[] body = msg.getBytes(); if (body != null) { result.append('~'); HexString.binToHex(body, 0, body.length, result); ...
java
public final void fireEvent(CalendarEvent evt) { if (fireEvents && !batchUpdates) { if (MODEL.isLoggable(FINER)) { MODEL.finer(getName() + ": fireing event: " + evt); //$NON-NLS-1$ } requireNonNull(evt); Event.fireEvent(this, evt); } }
java
public CmsResource readResource(String resourcename, CmsResourceFilter filter) throws CmsException { CmsResource res = null; // iterate through all wrappers and call "readResource" till one does not return null List<I_CmsResourceWrapper> wrappers = getWrappers(); Iterator<I_CmsResource...
java
public SequenceGenerator.SequenceBlock allocateBlock(int blockSize) { final long l = this.last; SequenceGenerator.SequenceBlock block = new SequenceGenerator.SequenceBlock(l + 1, l + blockSize); this.last = l + blockSize; return block; }
python
def _build_authorization_request_url( self, response_type, state=None ): """Form URL to request an auth code or access token. Parameters response_type (str) Only 'code' (Authorization Code Grant) supported at this time state (str) ...
python
def _call(self, x): """Return ``self(x)``.""" result = self.sess.run(self.output_tensor, feed_dict={self.input_tensor: np.asarray(x)}) return result
java
public static boolean isVarValue( Object val) { return val == null || !val.getClass().equals( String.class) || varValueRegex_.matcher( val.toString()).matches(); }
java
@Override protected int doSendReceiveFragment ( byte[] buf, int off, int length, byte[] inB ) throws IOException { if ( this.handle.isStale() ) { throw new IOException("DCERPC pipe is no longer open"); } int have = this.handle.sendrecv(buf, off, length, inB, getMaxRecv()); ...
python
def tear_down_instances(self): """Tear down all instances """ self.info_log('Tearing down all instances...') for instance in self.alive_instances: instance.tear_down() self.info_log('[Done]Tearing down all instances')
java
public static byte hashByteArray(byte[] array, int startInclusive, int endExclusive) { if (array == null) { return 0; } int range = endExclusive - startInclusive; if (range < 0) { throw new IllegalArgumentException(startInclusive + " > " + endExclusive); ...
java
private static boolean isDateHeader(final Buffer name) { try { return name.getByte(0) == 'D' && name.getByte(1) == 'a' && name.getByte(2) == 't' && name.getByte(3) == 'e'; } catch (final IOException e) { return false; } }
python
def _is_really_comment(tokens, index): """Return true if the token at index is really a comment.""" if tokens[index].type == TokenType.Comment: return True # Really a comment in disguise! try: if tokens[index].content.lstrip()[0] == "#": return True except IndexError: ...
python
def percentile_ranks(self, affinities, allele=None, alleles=None, throw=True): """ Return percentile ranks for the given ic50 affinities and alleles. The 'allele' and 'alleles' argument are as in the `predict` method. Specify one of these. Parameters ---------- ...
java
protected boolean isClassLoaded(String className, Instrumentation instrumentation) { if (instrumentation == null || className == null) { throw new IllegalArgumentException("instrumentation and className must not be null"); } Class<?>[] classes = instrumentation.getAllLoadedClasses();...
java
public void setAttribute(String name, String value) { this.myAttrs.put(name.toLowerCase(), value); }
java
@Override public void write(final OutputStream output) throws IOException { initialize(); if (content == null) { content = new byte[0]; } output.write(content, 0, content.length); output.flush(); }
java
@Override public <X> void body(Class<X> type, Result<X> result) { delegate().body(type, result); }
java
public ServiceFuture<List<LongTermRetentionBackupInner>> listByServerAsync(final String locationName, final String longTermRetentionServerName, final Boolean onlyLatestPerDatabase, final LongTermRetentionDatabaseState databaseState, final ListOperationCallback<LongTermRetentionBackupInner> serviceCallback) { re...
java
@Nonnull public static ESuccess writeToStream (@Nonnull final IMicroNode aNode, @Nonnull @WillClose final OutputStream aOS) { return writeToStream (aNode, aOS, XMLWriterSettings.DEFAULT_XML_SETTINGS); }
java
public MethodMember getMethod(String name, String descriptor) { for (MethodMember method : typedescriptor.getMethods()) { if (method.getName().equals(name) && method.getDescriptor().equals(descriptor)) { return method; } } throw new IllegalStateException("Unable to find member '" + name + descriptor + "...
java
public static void multAddOuter( double alpha , DMatrix5x5 A , double beta , DMatrix5 u , DMatrix5 v , DMatrix5x5 C ) { C.a11 = alpha*A.a11 + beta*u.a1*v.a1; C.a12 = alpha*A.a12 + beta*u.a1*v.a2; C.a13 = alpha*A.a13 + beta*u.a1*v.a3; C.a14 = alpha*A.a14 + beta*u.a1*v.a4; C.a15 = ...
java
public SMethod findMethod(String methodName) { for (SService sService : servicesByName.values()) { SMethod method = sService.getSMethod(methodName); if (method != null) { return method; } } return null; }
java
public void waitForPendingFutures() { // Wait inbox to become empty: Log.v(Log.TAG_BATCHER, "%s: waitForPendingFutures is called ...", this); while (true) { ScheduledFuture future; synchronized (mutex) { while (!inbox.isEmpty()) { try ...
java
public static DeviceType getDevice(final Request request) { if (request instanceof ServletRequest) { return getDevice(((ServletRequest) request).getBackingRequest()); } return DeviceType.NORMAL; }
python
def seed_aws_organization(ctx, owner): """Seeds SWAG from an AWS organziation.""" swag = create_swag_from_ctx(ctx) accounts = swag.get_all() _ids = [result.get('id') for result in accounts] client = boto3.client('organizations') paginator = client.get_paginator('list_accounts') response_ite...
python
def bios_image(self, bios_image): """ Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path """ self._bios_image = self.manager.get_abs_image_path(bios_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU bios image path to {bios_image}'.form...
java
@Override @Deprecated public StringBuffer format(CurrencyAmount currAmt, StringBuffer toAppendTo, FieldPosition pos) { return format(currAmt.getNumber().doubleValue(), currAmt.getCurrency(), toAppendTo, pos); }
python
def unsubscribe_url(self): """Return the absolute URL to visit to delete me.""" server_relative = ('%s?s=%s' % (reverse('tidings.unsubscribe', args=[self.pk]), self.secret)) return 'https://%s%s' % (Site.obje...
python
def subtract_timedelta(self, delta): """ Remove timedelta duration from the instance. :param delta: The timedelta instance :type delta: datetime.timedelta :rtype: Time """ if delta.days: raise TypeError("Cannot subtract timedelta with days to Time.")...