language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def add(self, *resources): """ Apply the tag to one or more resources :param resources: one or more `Resource` objects to which tags can be applied :return: `None` :raises DOAPIError: if the API endpoint replies with an error """ self.doapi_manager.re...
java
public ServiceFuture<VirtualMachineImageInner> getAsync(String location, String publisherName, String offer, String skus, String version, final ServiceCallback<VirtualMachineImageInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(location, publisherName, offer, skus, version...
java
private static Type resolveType(Class<?> rootClass, Type[] parameters, Class<?> targetClass) { // Look at super interfaces for (Type interfaceType : rootClass.getGenericInterfaces()) { Type type = resolveType(interfaceType, rootClass, parameters, targetClass); if (type != nul...
java
public void encode(MultimediaObject multimediaObject, File target, EncodingAttributes attributes) throws IllegalArgumentException, InputFormatException, EncoderException { encode(multimediaObject, target, attributes, null); }
java
@SuppressWarnings("unchecked") public static <T> T getObjectInstance(String className) { try { Class clazz = Class.forName(className); return (T) clazz.newInstance(); } catch (Exception e) { throw new Error(e); } }
python
def allowed_transitions(constraint_type: str, labels: Dict[int, str]) -> List[Tuple[int, int]]: """ Given labels and a constraint type, returns the allowed transitions. It will additionally include transitions for the start and end states, which are used by the conditional random field. Parameters ...
java
public ParcelFileDescriptor executeForBlobFileDescriptor(String sql, Object[] bindArgs, CancellationSignal cancellationSignal) { if (sql == null) { throw new IllegalArgumentException("sql must not be null."); } final int cookie = mRecentOperations.beginOperation("execute...
python
def import_plugin(self, plugin): ''' Import plugin by given name, looking at :attr:`namespaces`. :param plugin: plugin module name :type plugin: str :raises PluginNotFoundError: if not found on any namespace ''' names = [ '%s%s%s' % (namespace, '' if ...
java
private static List<Object> createEqualityKey(Node node) { List<Object> values = new ArrayList<Object>(); values.add(node.getNodeType()); values.add(node.getNodeName()); values.add(node.getLocalName()); values.add(node.getNamespaceURI()); values.add(node.getPrefix()); ...
python
def _subcommand_arguments(args): """ Return (subcommand, (possibly adjusted) arguments for that subcommand) Returns (None, args) when no subcommand is found Parsing our arguments is hard. Each subcommand has its own docopt validation, and some subcommands (paster and shell) have positional opt...
java
public static void w(String tag, String msg, Object... args) { if (sLevel > LEVEL_WARNING) { return; } if (args.length > 0) { msg = String.format(msg, args); } Log.w(tag, msg); }
java
public CSSClass addClass(CSSClass clss) throws CSSNamingConflict { CSSClass existing = store.get(clss.getName()); if (existing != null && existing.getOwner() != null && existing.getOwner() != clss.getOwner()) { throw new CSSNamingConflict("CSS class naming conflict between "+clss.getOwner().toString()+" a...
python
def style_classpath(self, products, scheduler): """Returns classpath as paths for scalastyle.""" classpath_entries = self._tool_classpath('scalastyle', products, scheduler) return [classpath_entry.path for classpath_entry in classpath_entries]
python
def parse_symbol(self, symbol, providers): '''Parse a symbol to obtain information regarding ticker, field and provider. Must return an instance of :attr:`symboldata`. :keyword symbol: string associated with market data to load. :keyword providers: dictionary of :class:`dynts.data....
python
def get_game_high_scores(user_id, chat_id=None, message_id=None, inline_message_id=None, **kwargs): """ Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns...
python
def build_model(self): '''Find out the type of model configured and dispatch the request to the appropriate method''' if self.model_config['model-type']: return self.build_red() elif self.model_config['model-type']: return self.buidl_hred() else: raise...
java
public void finished() { if (tc.isEntryEnabled()) SibTr.entry(tc, "finished"); browserIterator = null; if (tc.isEntryEnabled()) SibTr.exit(tc, "finished"); }
java
@Deprecated public BlockMeta moveBlockMeta(BlockMeta blockMeta, BlockStoreLocation newLocation) throws BlockDoesNotExistException, BlockAlreadyExistsException, WorkerOutOfSpaceException { // If existing location belongs to the target location, simply return the current block meta. BlockStor...
java
protected boolean intersectsX (IRay3 ray, float x) { IVector3 origin = ray.origin(), dir = ray.direction(); float t = (x - origin.x()) / dir.x(); if (t < 0f) { return false; } float iy = origin.y() + t*dir.y(), iz = origin.z() + t*dir.z(); return iy >= _minExt...
python
def interpolate_nearest(self, lons, lats, data): """ Interpolate using nearest-neighbour approximation Returns the same as interpolate(lons,lats,data,order=0) """ return self.interpolate(lons, lats, data, order=0)
java
static private void populateCache() { if (cacheIsPopulated) { return; } cacheIsPopulated = true; /* Schema: * * units{ * duration{ * day{ * one{"{0} ден"} * other{"{0} дена"} * } ...
java
public static DatabaseLiaison getLiaison (String url) { if (url == null) throw new NullPointerException("URL must not be null"); // see if we already have a liaison mapped for this connection DatabaseLiaison liaison = _mappings.get(url); if (liaison == null) { // scan the...
java
private boolean endingMultiLineComment( String content, int startOffset, int endOffset ) throws BadLocationException { int index = indexOf(content, getEndDelimiter(), startOffset); if ((index < 0) || (index > endOffset)) return false; else { setMultiLineComment(false); ...
python
def roleDeleted(self, *args, **kwargs): """ Role Deleted Messages Message that a new role has been deleted. This exchange outputs: ``v1/role-message.json#``This exchange takes the following keys: * reserved: Space reserved for future routing-key entries, you should always mat...
java
private <I, D> void writeInternal(ObservationTable<I, D> table, Function<? super Word<? extends I>, ? extends String> wordToString, Function<? super D, ? extends String> outputToString, Appendable out) throws ...
python
def subject(self): """ Return a string to be used as the email subject line. """ if self.application_name and self.application_version: return 'Crash Report - {name} (v{version})'.format(name=self.application_name, ...
java
private void indexFile(FileAbstractModel fileAbstractModel, ScanStatistic stats, String dirname, InputStream inputStream, long filesize) throws Exception { final String filename = fileAbstractModel.getName(); final LocalDateTime created = fileAbstractModel.getCreationDate(); ...
java
void verifySignature(JsonNode messageJson) { if (!signatureChecker.verifySignature(toMap(messageJson), fetchPublicKey(messageJson))) { throw new SdkClientException("Signature in SNS message was invalid"); } }
python
def setup_standalone_signals(instance): """Called when prefs dialog is running in standalone mode. It makes the delete event of dialog and click on close button finish the application. """ window = instance.get_widget('config-window') window.connect('delete-event', Gtk.main_quit) # We need ...
python
def get_query_params(request, *args): """ Allows to change one of the URL get parameter while keeping all the others. Usage:: {% load libs_tags %} {% get_query_params request "page" page_obj.next_page_number as query %} <a href="?{{ query }}">Next</a> You can also pass in several pa...
java
public OvhCallsGenerated billingAccount_line_serviceName_automaticCall_identifier_GET(String billingAccount, String serviceName, String identifier) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/automaticCall/{identifier}"; StringBuilder sb = path(qPath, billingAccount, serviceN...
python
def shutdown(cluster_info, queues=['input']): """Stops all TensorFlow nodes by feeding ``None`` into the multiprocessing.Queues. Args: :cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc). :queues: *INTERNAL_USE* Returns: A nodeRDD.mapPartitions() fun...
java
private void linearScanBatchKNN(ArrayDBIDs ids, List<KNNHeap> heaps) { final DistanceQuery<O> dq = distanceQuery; // The distance is computed on database IDs for(DBIDIter iter = getRelation().getDBIDs().iter(); iter.valid(); iter.advance()) { int index = 0; for(DBIDIter iter2 = ids.iter(); iter2...
java
public ByteBuffer readToByteBuffer(int max) throws IOException { Validate.isTrue(max >= 0, "maxSize must be 0 (unlimited) or larger"); final boolean localCapped = max > 0; // still possibly capped in total stream final int bufferSize = localCapped && max < DefaultSize ? max : DefaultSize; ...
java
public void recordNewEvent() { // Remove old events from record final double thresholdTime = System.currentTimeMillis() - (timeslotInMilliseconds * 2.0); events.removeIf(e -> e < thresholdTime); // Record new event events.add(System.currentTimeMillis()); }
python
def write(self, path=None): """ Write all of the HostsEntry instances back to the hosts file :param path: override the write path :return: Dictionary containing counts """ written_count = 0 comments_written = 0 blanks_written = 0 ipv4_entries_writt...
python
def require_instance(obj, types=None, name=None, type_name=None, truncate_at=80): """ Raise an exception if obj is not an instance of one of the specified types. Similarly to isinstance, 'types' may be either a single type or a tuple of types. If name or type_name is provided, it is used in the ex...
python
def split_into_batches(input_list, batch_size, batch_storage_dir, checkpoint=False): """ Break the input data into smaller batches, optionally saving each one to disk. Args: input_list: An input object that has a list-like interface (indexing and slicing). batch_size: The maximum number of ...
java
public static Connector createDefault(Map<String, String> properties) { Connector.Builder builder = Connector.Builder.create() .rawProperties(properties) .secureEnabled(Boolean.parseBoolean(properties.get("ssl.enabled"))) .sslProtocol(properties.get("ssl.protocol"...
java
private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); compEnc[0] = (byte)(yBit ? 0x03 : 0x02); return CURVE.getCurve().decodePoint(compEnc); ...
python
def write_forward_run(self): """ write the forward run script forward_run.py """ with open(os.path.join(self.m.model_ws,self.forward_run_file),'w') as f: f.write("import os\nimport numpy as np\nimport pandas as pd\nimport flopy\n") f.write("import pyemu\n") f...
java
public com.google.api.ads.admanager.axis.v201902.DateTime getSubmissionTime() { return submissionTime; }
java
public void open(OutputStream wrappedStream) throws IOException { if(isOpen()) { // error; should not be opening/wrapping in an unclosed // stream remains open throw new IOException("ROS already open for " +Thread.currentThread().getName()); } ...
java
public void fireCalendarWrittenEvent(ProjectCalendar calendar) { if (m_projectListeners != null) { for (ProjectListener listener : m_projectListeners) { listener.calendarWritten(calendar); } } }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TypesPackage.JVM_TYPE_PARAMETER_DECLARATOR__TYPE_PARAMETERS: return getTypeParameters(); } return super.eGet(featureID, resolve, coreType); }
python
def create_single_token(self, *, payer_id, name, identification_number, payment_method, number, expiration_date): """ Using this feature you can register a customer’s credit card data and get a token sequential number. Args: payer_id: name: identification_num...
python
def process_gps_position(self, helper, sess): """ just print the current GPS position """ gps_position = helper.get_snmp_value(sess, helper, self.oids['oid_gps_position']) if gps_position: helper.add_summary(gps_position) else: helper.add_summary...
java
public <M> Graph<K, VV, EV> runVertexCentricIteration( ComputeFunction<K, VV, EV, M> computeFunction, MessageCombiner<K, M> combiner, int maximumNumberOfIterations) { return this.runVertexCentricIteration(computeFunction, combiner, maximumNumberOfIterations, null); }
java
@Deprecated public static String toPlainText(String text, int offset, int capacity) { PlainTextState state = PlainTextState.TEXT; StringBuilder plainText = new StringBuilder(); for(int i = offset; i < text.length() && plainText.length() <= capacity; ++i) { int c = text.charAt(i); ...
java
public void close() { if (connected) { try { terminal.deactivate(); } catch (Exception ex) { logger.debug("Exception occurred while closing UDPMasterConnection", ex); } connected = false; } }
python
def GetClassesByArtifact(cls, artifact_name): """Get the classes that support parsing a given artifact.""" return [ cls.classes[c] for c in cls.classes if artifact_name in cls.classes[c].supported_artifacts ]
python
def get_path_uid(path): # type: (str) -> int """ Return path's uid. Does not follow symlinks: https://github.com/pypa/pip/pull/935#discussion_r5307003 Placed this function in compat due to differences on AIX and Jython, that should eventually go away. :raises OSError: When path is...
java
@Deprecated public static EchoOutput adapt(final Appendable appendable) { return new EchoOutput() { @Override public void onReceive(int input, String string) throws IOException { appendable.append(string); } @Override public void o...
java
private PrintStream createOutputStream() { if (outputLogFilename != null) { try { FileOutputStream fout = new FileOutputStream(outputLogFilename, false); BufferedOutputStream bos = new BufferedOutputStream(fout, 4096); // We are using a PrintStream for...
python
def loads(serialized_messages): """ Deserialize messages from a JSON formatted str Args: serialized_messages (JSON str): Returns: list: Deserialized message objects. Raises: ValidationError: If deserialized message validation failed. KeyError: If serialized_message...
java
@Override public GetSubscriptionDefinitionResult getSubscriptionDefinition(GetSubscriptionDefinitionRequest request) { request = beforeClientExecution(request); return executeGetSubscriptionDefinition(request); }
python
def intersection(L1, L2): """Intersects two line segments Args: L1 ([float, float]): x and y coordinates L2 ([float, float]): x and y coordinates Returns: bool: if they intersect (float, float): x and y of intersection, if they do """ D = L1[0] * L2[1] - L1[1] * L2[0...
java
public LocalDate plusDays(int days) { if (days == 0) { return this; } long instant = getChronology().days().add(getLocalMillis(), days); return withLocalMillis(instant); }
java
public static AbstractMethodArrangement getMethodArrangement(final List<BenchmarkElement> elements, final KindOfArrangement kind) { AbstractMethodArrangement arrang = null; switch (kind) { case NoArrangement: arrang = new NoMethodArrangement(elements); break; ...
python
def liftover(self, intersecting_region): """ Lift a region that overlaps the genomic occurrence of the retrotransposon to consensus sequence co-ordinates. This method will behave differently depending on whether this retrotransposon occurrance contains a full alignment or not. If it does, the alignm...
java
private Point getPopupLocation() { Dimension popupSize = comboBox.getSize(); Insets insets = getInsets(); // reduce the width of the scrollpane by the insets so that the popup // is the same width as the combo box. popupSize.setSize(popupSize.width - (insets.right + insets...
java
@SuppressWarnings({"unused", "WeakerAccess"}) public void pushProfile(final Map<String, Object> profile) { if (profile == null || profile.isEmpty()) return; postAsyncSafely("profilePush", new Runnable() { @Override public void run() { _push(profil...
java
public boolean intersects(long minimum, long supremum) { MutableRoaringBitmap.rangeSanityCheck(minimum, supremum); short minKey = highbits(minimum); short supKey = highbits(supremum); int len = highLowContainer.size(); // seek to start int pos = 0; while (pos < len && compareUnsi...
java
boolean doFileNames(Stream<String> filenames) throws IOException { return doClassNames( filenames.filter(name -> name.endsWith(".class")) .filter(name -> !name.endsWith("package-info.class")) .filter(name -> !name.endsWith("module-info.class")) ...
java
public OvhVirtualMacManagement serviceName_virtualMac_macAddress_virtualAddress_ipAddress_GET(String serviceName, String macAddress, String ipAddress) throws IOException { String qPath = "/dedicated/server/{serviceName}/virtualMac/{macAddress}/virtualAddress/{ipAddress}"; StringBuilder sb = path(qPath, serviceName,...
java
public Collection<BoxGroupMembership.Info> getMemberships() { final BoxAPIConnection api = this.getAPI(); final String groupID = this.getID(); Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() { public Iterator<BoxGroupMembership.Info> iterator() { ...
java
public Array listToArray() throws PageException { if (this.query instanceof QueryImpl) return ListUtil.listToArray(((QueryImpl) this.query).getColumnlist(false), ","); throw new ApplicationException("Query is not of type QueryImpl. Use instead Query.columnArray() or Query.columnList().listToArray()."); }
java
@Override int findKey(final byte[] key) { final long[] hash = MurmurHash3.hash(key, SEED); int entryIndex = getIndex(hash[0], tableEntries_); int firstDeletedIndex = -1; final int loopIndex = entryIndex; do { if (isBitClear(stateArr_, entryIndex)) { return firstDeletedIndex == -1 ? ~...
java
public static List<String> getDataTypeWithAllPrecisionVariants(final Column column) { final ArrayList<String> list = new ArrayList<>(3); list.add(String.format("%s(%d,%d)", column.getColumnDataType().getName(), column.getSize(), column.getDecimalDigits())); list.add(String.format("%s(%d)", colum...
python
def create_bulk_device_enrollment(self, enrollment_identities, **kwargs): # noqa: E501 """Bulk upload # noqa: E501 With bulk upload, you can upload a `CSV` file containing a number of enrollment IDs. **Example usage:** ``` curl -X POST \\ -H 'Authorization: Bearer <valid access token>' \\ -F 'enroll...
python
def calc_erc_weights(returns, initial_weights=None, risk_weights=None, covar_method='ledoit-wolf', risk_parity_method='ccd', maximum_iterations=100, tolerance=1E-8): """ Calculates the e...
python
async def write_and_drain(self, data: bytes, timeout: NumType = None) -> None: """ Format a command and send it to the server. """ if self._stream_writer is None: raise SMTPServerDisconnected("Client not connected") self._stream_writer.write(data) async with...
python
def SetPercentage(self, percent, total): """Set whether to display percentage values (and total for doing so)""" self.percentageView = percent self.total = total
java
public static CompletableFuture<Void> from(ChannelFuture future) { LettuceAssert.notNull(future, "ChannelFuture must not be null"); CompletableFuture<Void> result = new CompletableFuture<>(); adapt(future, result); return result; }
java
public GetFeedbackResponse getFeedback(SesRequest request) { InternalRequest internalRequest = this.createRequest("feedback", request, HttpMethodName.GET); return this.invokeHttpClient(internalRequest, GetFeedbackResponse.class); }
python
def bcesboot_backup(y1,y1err,y2,y2err,cerr,nsim=10000): """ Does the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param nsim: n...
java
public void execute() throws MojoExecutionException { getLog().debug("starting packaging"); AbstractConfiguration[] configurations= (AbstractConfiguration[]) getPluginContext().get(ConfiguratorMojo.GENERATED_CONFIGURATIONS_KEY); try { for(AbstractConfiguration confi...
python
def ExceptionHook(exctype, value, tb): ''' A custom exception handler that logs errors to file. ''' for line in traceback.format_exception_only(exctype, value): log.error(line.replace('\n', '')) for line in traceback.format_tb(tb): log.error(line.replace('\n', '')) sys.__except...
python
def hmsStrToDeg(ra): """Convert a string representation of RA into a float in degrees.""" hour, min, sec = ra.split(':') ra_deg = hmsToDeg(int(hour), int(min), float(sec)) return ra_deg
java
public List<RemoveFromList> repairCommand(final RemoveFromList toRepair, final RemoveFromList repairAgainst) { if (toRepair.getStartPosition() + toRepair.getRemoveCount() <= repairAgainst.getStartPosition()) { return asList(toRepair); } if (toRepair.getStartPosition() >= repairAgains...
java
private void fireMouseClicked(int button, int x, int y, int clickCount) { consumed = false; for (int i=0;i<mouseListeners.size();i++) { MouseListener listener = (MouseListener) mouseListeners.get(i); if (listener.isAcceptingInput()) { listener.mouseClicked(button, x, y, clickCount); if (consumed...
python
def _gql(query_string, query_class=Query): """Parse a GQL query string (internal version). Args: query_string: Full GQL query, e.g. 'SELECT * FROM Kind WHERE prop = 1'. query_class: Optional class to use, default Query. Returns: An instance of query_class. """ from .google_imports import gql # ...
java
private void startThreads(Configuration conf, String traceIn, Path ioPath, Path scratchDir, CountDownLatch startFlag) throws IOException { monitor = createJobMonitor(); submitter = createJobSubmitter(monitor, conf.getInt(GRIDMIX_SUB_THR, Runtime.getRuntime().availableProcessors() + 1), ...
java
static boolean isMixedExpression(String expression) { if (null == expression) { return false; } // if it doesn't start and end with delimiters return (!(expression.startsWith("#{") && expression.endsWith("}"))) && isExpression(expression); }
python
def on_bar(self, event): ''' 策略事件 :param event: :return: ''' 'while updating the market data' print( "on_bar account {} ".format(self.account_cookie), event.market_data.data ) print(event.send_order) try: ...
python
def download_profile(self, profile_name: Union[str, Profile], profile_pic: bool = True, profile_pic_only: bool = False, fast_update: bool = False, download_stories: bool = False, download_stories_only: bool = False, down...
java
private void addSlaveJulLogRecords(Container result, List<java.util.concurrent.Callable<List<FileContent>>> tasks, final Node node, final SmartLogFetcher logFetcher) { final FilePath rootPath = node.getRootPath(); if (rootPath != null) { // rotated log files stored on the disk ta...
java
public ConsumedCapacity withLocalSecondaryIndexes(java.util.Map<String, Capacity> localSecondaryIndexes) { setLocalSecondaryIndexes(localSecondaryIndexes); return this; }
python
def obfuscate_class(tokens, index, replace, replacement, *args): """ If the token string (a class) inside *tokens[index]* matches *replace*, return *replacement*. """ def return_replacement(replacement): CLASS_REPLACEMENTS[replacement] = replace return replacement tok = tokens[in...
java
public TempFileNameScheme getTempFileNameScheme() { final TempFileNameScheme tempFileNameScheme; try { final String cls = Optional .ofNullable(getProperty("temp-file-name-scheme")) .orElse(configuration.get("temp-file-name-scheme")); tempFi...
java
public Object getLobFromGFSEntity(GridFS gfs, EntityMetadata m, Object entity, KunderaMetadata kunderaMetadata) { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(m.getPersistenceUnit()); EntityType entityType = metaModel.entity(m.getEn...
java
@Override @Transactional(value = MillJpaRepoConfig.TRANSACTION_MANAGER_BEAN, propagation = Propagation.REQUIRES_NEW) public boolean flagAsDeleted(String account, String storeId, String spaceId, String contentId, ...
java
public SegmentIndexBuffer openSegmentIndexBuffer(int segId) { SegmentIndexBuffer sib = _sibLookup.get(segId); if(sib == null) { sib = new SegmentIndexBuffer(); sib.setSegmentId(segId); _sibLookup.put(segId, sib); } return sib; }
java
public boolean isClassUnmarkedForRemoval(String className) { for (ControlEntry controlEntry : controlList) { if (controlEntry.pattern.matcher(className).matches() && controlEntry.controlMode == ControlMode.KEEP) { return true; } } return false; }
java
public static ConnectionInformation fromDriver(Driver driver) { final ConnectionInformation connectionInformation = new ConnectionInformation(); connectionInformation.driver = driver; return connectionInformation; }
java
public final EObject entryRuleXUnaryOperation() throws RecognitionException { EObject current = null; EObject iv_ruleXUnaryOperation = null; try { // InternalSARL.g:8973:56: (iv_ruleXUnaryOperation= ruleXUnaryOperation EOF ) // InternalSARL.g:8974:2: iv_ruleXUnaryOpera...
python
def set_index(self, index): """Display the data of the given index :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ item = index.internalPointer() self.actionunit = item.internal_data()...
python
def restrict_access(scope, mod=None, login=None, oauth_only=False, generator_called=False): """Restrict function access unless the user has the necessary permissions. Raises one of the following exceptions when appropriate: * LoginRequired * LoginOrOAuthRequired * the sc...
python
def write_eof(self): """Shut down the write direction of the transport.""" self._check_status() if not self._writable: raise TransportError('transport is not writable') if self._closing: raise TransportError('transport is closing') try: self._h...
java
public void setReadTimeout(int timeout) { Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value"); this.socketTimeout = timeout; setLegacySocketTimeout(getHttpClient(), timeout); }