language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public TrailingHeaders addHeader(CharSequence name, Iterable<Object> values) { lastHttpContent.trailingHeaders().add(name, values); return this; }
python
def endclip(self): """End the current clip region. When clip calls are nested, it ends the most recently created crip region.""" self.__clip_box = self.__clip_stack[-1] del self.__clip_stack[-1] self.grestore()
java
protected void disableStop() { EventTarget targ = svgp.getDocument().getRootElement(); targ.removeEventListener(SVGConstants.SVG_EVENT_MOUSEMOVE, this, false); targ.removeEventListener(SVGConstants.SVG_EVENT_MOUSEUP, this, false); // FIXME: listen on the background object! targ.removeEventListener(S...
java
public static String replaceFirst(CharSequence self, Pattern pattern, CharSequence replacement) { return pattern.matcher(self).replaceFirst(replacement.toString()); }
python
def generate_clickable_map(self): # type: () -> unicode """Generate clickable map tags if clickable item exists. If not exists, this only returns empty string. """ if self.clickable: return '\n'.join([self.content[0]] + self.clickable + [self.content[-1]]) el...
python
def count(self, with_limit_and_skip=False): """**DEPRECATED** - Get the size of the results set for this query. The :meth:`count` method is deprecated and **not** supported in a transaction. Please use :meth:`~pymongo.collection.Collection.count_documents` instead. Returns the ...
java
public final Dataset getDataset(String name) { GetDatasetRequest request = GetDatasetRequest.newBuilder().setName(name).build(); return getDataset(request); }
java
public Attribute export(JavaClass cl, JavaClass target) { target.getConstantPool().addUTF8(getName()); OpaqueAttribute attr = new OpaqueAttribute(getName()); byte []value = new byte[_value.length]; System.arraycopy(_value, 0, value, 0, _value.length); attr.setValue(value); return...
java
public void preInvoke( InterceptorContext context, InterceptorChain chain ) throws InterceptorException { preAction( ( ActionInterceptorContext ) context, chain ); }
python
def update_box_field(self, box_key, field): '''Upates box field as specified Args: box_key key for pipeline where the fields lives field StreakField object with fresh data returns (status code, updated field dict) ''' #does not work self._raise_unimplemented_error() uri = '/'.join([self....
java
private RandomVariable getValueUnderlyingNumeraireRelative(LIBORModelMonteCarloSimulationModel model, Schedule legSchedule, boolean paysFloat, double swaprate, double notional) throws CalculationException { RandomVariable value = model.getRandomVariableForConstant(0.0); for(int periodIndex = legSchedule.getNumb...
java
private boolean notifyOnGroupClicked(@NonNull final View view, final int groupIndex, final long id) { return groupClickListener != null && groupClickListener.onGroupClick(this, view, groupIndex, id); }
python
def escape_email_quoted_text(text, indent_txt='>>', linebreak_txt='\n'): """ Escape text using an email-like indenting rule. As an example, this text:: >>Brave Sir Robin ran away... <img src="malicious_script />*No!* >>bravely ran away away... I didn't!*<script>malicious code...
java
private String getString(String valueKey) { String realKey = m_entity.getTypeName() + "/" + valueKey; CmsEntityAttribute attr = m_entity.getAttribute(realKey); if (attr == null) { return ""; } else { return attr.getSimpleValue(); } }
java
@SuppressWarnings("unchecked") public static <T> Class<T> getClass(T obj) { return ((null == obj) ? null : (Class<T>) obj.getClass()); }
python
def _sanitize(recipe): """Clean up a recipe that may have been stored as serialized json string. Convert any numerical pointers that are stored as strings to integers.""" recipe = recipe.copy() for k in list(recipe): if k not in ("start", "error") and int(k) and k != int(k): ...
java
public static List<String> availableDomains(IDBAccess dbAccess) { List<GrNode> resultList = loadAllDomainInfoNodes(dbAccess); List<String> domains = new ArrayList<String>(); for (GrNode rNode : resultList) { domains.add(rNode.getProperty(DomainInfoNameProperty).getValue().toString()); } return domain...
python
def oqi(ql, qs, ns=None, rc=None, ot=None, coe=None, moc=None): """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.OpenQueryInstances`. Open an enumeration session to execute a query in a namespace and to retrieve the instances representing the query result. Use the :func:`~wbemc...
python
def load_json(filename, to='auto'): ''' load_json(filename) yields the object represented by the json file or stream object filename. The optional argument to may be set to None to indicate that the JSON data should be returned verbatim rather than parsed by neuropythy's denormalize system. '''...
java
public void setReplicaGlobalSecondaryIndexSettings(java.util.Collection<ReplicaGlobalSecondaryIndexSettingsDescription> replicaGlobalSecondaryIndexSettings) { if (replicaGlobalSecondaryIndexSettings == null) { this.replicaGlobalSecondaryIndexSettings = null; return; } th...
python
def get_program_weight(self): """! @brief Get time to program a page including the data transfer.""" return self.program_weight + \ float(len(self.data)) / float(DATA_TRANSFER_B_PER_S)
python
def get_network_create_endpoint_kwargs(self, action, endpoint_config, kwargs=None): """ Generates keyword arguments for Docker's ``create_endpoint_config`` utility / ``EndpointConfig`` type as well as for ``connect_container_to_network``. :param action: Action configuration. :ty...
python
def _set_packages(self, node): ''' Set packages and collections. :param node: :return: ''' pkgs = etree.SubElement(node, 'packages') for pkg_name, pkg_version in sorted(self._data.software.get('packages', {}).items()): pkg = etree.SubElement(pkgs, 'pa...
java
public static MethodInvocation newMethodInvocation(Object target, String methodName, Object... args) { Assert.notNull(target, "Target object cannot be null"); return new MethodInvocation(target, ClassUtils.findMethod(target.getClass(), methodName, args), args); }
python
def sanity_check(self, sender, to, subject, plain=None, html=None, cc=None, bcc=None): """ Sanity check the message. If we have PLAIN and HTML versions, send a multipart alternative MIME message, else send whichever we do have. If we have neither, raise NoContentError ...
java
public static InputStream inputStream(File file) { // workaround http://stackoverflow.com/questions/36880692/java-file-does-not-exists-but-file-getabsolutefile-exists if (!file.exists()) { file = file.getAbsoluteFile(); } if (!file.exists()) { throw E.ioException(...
java
public V get(final int key) { final int index = (key & 0x7FFFFFFF) % elementData.length; IntEntry<V> m = elementData[index]; while (m != null) { if (key == m.key) { return m.value; } m = m.nextInSlot; } return null; }
java
public void setResult(Result result) throws IllegalArgumentException { if(null == result) throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_NULL, null)); //"Result should not be null"); m_result = result; }
java
public final hqlParser.whenClause_return whenClause() throws RecognitionException { hqlParser.whenClause_return retval = new hqlParser.whenClause_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token WHEN216=null; Token THEN218=null; ParserRuleReturnScope logicalExpression217 =null; Pars...
java
public void shutdown() { if (this.shuttingDown.getAndSet(true)) { // Already being shut down LOG.warn("DataNode.shutdown() was called while shutting down."); return; } if (infoServer != null) { try { infoServer.stop(); } catch (Exception e) { LOG.warn("Exception...
java
static void constructAvgTransactionGraph(Map.Entry<String, LrProjectScenarioResults> scenarioResults, JSONObject scenarioGraphData) { Map<Integer, TreeMap<String, AvgTransactionResponseTime>> avgTransactionResponseTimeResults = scenarioResults.getValu...
java
public static String extractDate(HttpServletRequest request) { if (request == null) { return ""; } String date = request.getHeader("X-Amz-Date"); if (StringUtils.isBlank(date)) { return request.getParameter("X-Amz-Date"); } else { return date; } }
java
public static String getSystemProperty(String propName) { final String temp = propName; try { String prop = AccessController.doPrivileged( new PrivilegedAction<String>() { @Ove...
python
def list_contacts(self, **kwargs): """ List all contacts, optionally filtered by a query. Specify filters as query keyword argument, such as: email=abc@xyz.com, mobile=1234567890, phone=1234567890, contacts can be filtered by state and company_id such as: ...
python
def assess_differences(image_file1, image_file2, levels=None, version=None, size_heuristic=False, guts1=None, guts2=None): '''assess_differences will compare two images on each ...
java
public PagedList<UsageInner> listWebWorkerUsagesNext(final String nextPageLink) { ServiceResponse<Page<UsageInner>> response = listWebWorkerUsagesNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<UsageInner>(response.body()) { @Override public Page<Usa...
java
@Override public PersistableDownload pause() throws PauseException { boolean forceCancel = true; TransferState currentState = getState(); this.monitor.getFuture().cancel(true); if (persistableDownload == null) { throw new PauseException(TransferManagerUtils.determinePaus...
python
def decompose_atom_list(atom_list): """ Return elements and/or atom ids and coordinates from an `atom list`. Depending on input type of an atom list (version 1 or 2) 1. [[element, coordinates (x, y, z)], ...] 2. [[element, atom key, coordinates (x, y, z)], ...] the function reverses w...
java
private void handleUpdate(final TrackMetadataUpdate update) { boolean foundInCache = false; if (update.metadata == null || update.metadata.trackType != CdjStatus.TrackType.REKORDBOX) { clearDeck(update); } else { // We can offer waveform information for this device; chec...
python
def reference_creators_citation(self, ref_id): """Return for citation the creator surnames (locally defined) and the publication year.""" # FIXME Delayed refactoring. Use an index instead of an ID. index = self.reference_index(ref_id) creators = self.reference_creator_surnames(index) ...
java
public void setKappa(double kappa) { if(kappa < 0.5 || kappa > 1.0 || Double.isNaN(kappa)) throw new IllegalArgumentException("Kapp must be in [0.5, 1], not " + kappa); this.kappa = kappa; }
java
public List<SequenceLabel> getNumericNames() { final List<SequenceLabel> result = new ArrayList<SequenceLabel>(); while (hasNextToken()) { result.add(getNextToken()); } return result; }
java
public File writeMap(Map<?, ?> map, LineSeparator lineSeparator, String kvSeparator, boolean isAppend) throws IORuntimeException { if(null == kvSeparator) { kvSeparator = " = "; } try(PrintWriter writer = getPrintWriter(isAppend)) { for (Entry<?, ?> entry : map.entrySet()) { if (null != entry) { ...
python
def _mean_prediction(self, mu, Y, h, t_z): """ Creates a h-step ahead mean prediction Parameters ---------- mu : np.ndarray The past predicted values Y : np.ndarray The past data h : int How many steps ahead for the prediction ...
python
def get_dimension_from_db_by_name(dimension_name): """ Gets a dimension from the DB table. """ try: dimension = db.DBSession.query(Dimension).filter(Dimension.name==dimension_name).one() return JSONObject(dimension) except NoResultFound: raise ResourceNotFoundError("Dimen...
python
def check(self, radl): """Check the features in this application.""" SIMPLE_FEATURES = { "name": (str, lambda x, _: bool(x.value)), "path": (str, lambda x, _: bool(x.value)), "version": (str, is_version), "preinstalled": (str, ["YES", "NO"]) } ...
python
def threshold_image(img, bkground_thresh, bkground_value=0.0): """ Thresholds a given image at a value or percentile. Replacement value can be specified too. Parameters ----------- image_in : ndarray Input image bkground_thresh : float a threshold value to identify the ba...
java
private String getProcessName(ProcessTextProvider textProvider) { if (!quotedString('"',textProvider)) { return "P"+(textProvider.incrementProcessCount()); } if (textProvider.getLastToken().contains("_")) { throw new ParserException("Process names nust not include underbar: "+textProvider.g...
python
def _dstationarystate(self, k, param): """Returns the dstationarystate .""" if self._distributionmodel: return self.model.dstationarystate(k, param) else: return self.model.dstationarystate(param)
java
public IterableOfProtosFluentAssertion<M> ignoringFieldDescriptors( FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return ignoringFieldDescriptors(asList(firstFieldDescriptor, rest)); }
python
def delete_scheduling_block(block_id): """Delete Scheduling Block with the specified ID""" DB.delete('scheduling_block/{}'.format(block_id)) # Add a event to the scheduling block event list to notify # of a deleting a scheduling block from the db DB.rpush('scheduling_block_events', jso...
java
public Cell createTitleCell(String str, double width) { int cellCnt = this.getCellCnt(); Cell cell = this.getLastRow().createCell(cellCnt); cell.setCellValue(str); cell.setCellType(CellType.STRING); cell.setCellStyle(this.style.getStringCs()); sheet.setColumnWidth(cell...
java
public static LinkedHashMap<String, ProteinSequence> readFastaProteinSequence( File file) throws IOException { FileInputStream inStream = new FileInputStream(file); LinkedHashMap<String, ProteinSequence> proteinSequences = readFastaProteinSequence(inStream); inStream.close(); return proteinSequences; }
python
def _interpolate_v(p, r, v): """ interpolates v based on the values in the A table for the scalar value of r and th """ # interpolate v (p should be in table) # ordinate: y**2 # abcissa: 1./v # find the 3 closest v values # only p >= .9 have table values for 1 degree of freedom. ...
java
public static <R> LongFunction<R> longFunction(CheckedLongFunction<R> function, Consumer<Throwable> handler) { return t -> { try { return function.apply(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStateExcep...
python
def rectwidth(self): """Calculate :ref:`pysynphot-formula-rectw`. Returns ------- ans : float Bandpass rectangular width. """ mywaveunits = self.waveunits.name self.convert('angstroms') wave = self.wave thru = self.throughput ...
python
def _force(self,z,t=0.): """ NAME: _force PURPOSE: evaluate the force INPUT: z t OUTPUT: F_z(z,t;R) HISTORY: 2010-07-13 - Written - Bovy (NYU) """ return self._Pot.zforce(self._R,z,phi=self._...
java
public Observable<RestApiResponse> execute() { return deferAndWatch(new Func1<Subscriber, Observable<? extends RestApiResponse>>() { @Override public Observable<? extends RestApiResponse> call(Subscriber subscriber) { RestApiRequest apiRequest = asRequest(); ...
java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!httpAuth.isAllowed(req, resp)) { return; } // post du formulaire d'ajout d'application à monitorer I18N.bindLocale(req.getLocale()); try { addCollectorApplication(...
java
public void format(PatriciaTrie<V> trie, File file, boolean formatBitString) throws FileNotFoundException { PrintWriter writer = new PrintWriter(new FileOutputStream(file)); writer.println(format(trie, formatBitString)); writer.close(); }
java
@Override public CommerceDiscountRel findByCommerceDiscountId_Last( long commerceDiscountId, OrderByComparator<CommerceDiscountRel> orderByComparator) throws NoSuchDiscountRelException { CommerceDiscountRel commerceDiscountRel = fetchByCommerceDiscountId_Last(commerceDiscountId, orderByComparator); if (...
python
def get_open_trackers_from_remote(): """Returns open trackers announce URLs list from remote repo.""" url_base = 'https://raw.githubusercontent.com/idlesign/torrentool/master/torrentool/repo' url = '%s/%s' % (url_base, OPEN_TRACKERS_FILENAME) try: import requests response = requests.g...
java
public ApiResponse<Void> unsubscribeWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = unsubscribeValidateBeforeCall(null, null); return apiClient.execute(call); }
python
def parse(system): """ Parse input file with the given format in system.files.input_format """ t, _ = elapsed() input_format = system.files.input_format add_format = system.files.add_format # exit when no input format is given if not input_format: logger.error( 'No ...
java
@Deprecated public Writable[] call(Writable[] params, InetSocketAddress[] addresses) throws IOException { return call(params, addresses, null, null); }
java
public void marshall(ErrorInformation errorInformation, ProtocolMarshaller protocolMarshaller) { if (errorInformation == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(errorInformation.getCode(), COD...
java
public static ClassFileTransformer installTransformer(Instrumentation instrumentation) { final TypeDescription runReflectiveCall = TypePool.Default.ofSystemLoader().describe("com.nordstrom.automation.junit.RunReflectiveCall").resolve(); final TypeDescription finished = TypePool.Default.ofSystemLoader(...
python
def load_from_conf(self): """Load settings from configuration file""" for checkbox, (option, default) in list(self.checkboxes.items()): checkbox.setChecked(self.get_option(option, default)) # QAbstractButton works differently for PySide and PyQt if not API == 'py...
python
def add_review(self, reviewer, product, review, date=None): """Add a new review from a given reviewer to a given product. Args: reviewer: an instance of Reviewer. product: an instance of Product. review: a float value. date: date the review issued. Retur...
python
async def substr(self, name, start, end=-1): """ Return a substring of the string at key ``name``. ``start`` and ``end`` are 0-based integers specifying the portion of the string to return. """ return await self.execute_command('SUBSTR', name, start, end)
python
def early_stop(stopping_rounds, maximize=False, verbose=True): """Create a callback that activates early stoppping. Validation error needs to decrease at least every **stopping_rounds** round(s) to continue training. Requires at least one item in **evals**. If there's more than one, will use the la...
java
public KeyStore getKeyStore(String name, String type, String provider, String fileName, String password, boolean create, SSLConfig sslConfig) throws Exception { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "getKeyStore", new Object[] { name, type, provider, fileName,...
python
def abort(http_status_code, exc=None, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. From Flask-Restful. See NOTICE file for license information. """ try: sanic.exceptions.abort(http_status_code, exc) ...
java
public UnsafeSorterIterator getIterator(int startIndex) throws IOException { if (spillWriters.isEmpty()) { assert(inMemSorter != null); UnsafeSorterIterator iter = inMemSorter.getSortedIterator(); moveOver(iter, startIndex); return iter; } else { LinkedList<UnsafeSorterIterator> qu...
java
public void onCloseRemote(CloseInfo closeInfo) { if (LOG.isDebugEnabled()) LOG.debug("onCloseRemote({})", closeInfo); ConnectionState event = null; synchronized (this) { if (this.state == ConnectionState.CLOSED) { // already closed return; ...
java
public static XClass getXClass(ClassDescriptor c) throws CheckedAnalysisException { return Global.getAnalysisCache().getClassAnalysis(XClass.class, c); }
python
def _to_binpoly(x): '''Convert a Galois Field's number into a nice polynomial''' if x <= 0: return "0" b = 1 # init to 2^0 = 1 c = [] # stores the degrees of each term of the polynomials i = 0 # counter for b = 2^i while x > 0: b = (1 << i) # generate a number...
python
def transform_series(series, force_list=False, buffers=None): ''' Transforms a Pandas series into serialized form Args: series (pd.Series) : the Pandas series to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes usi...
python
def load_and_process_igor_model(self, marginals_file_name): """Set attributes by reading a generative model from IGoR marginal file. Sets attributes PVJ, PdelV_given_V, PdelJ_given_J, PinsVJ, and Rvj. Parameters ---------- marginals_file_name : str F...
python
def _read_v3_10x_h5(filename): """ Read hdf5 file from Cell Ranger v3 or later versions. """ with tables.open_file(str(filename), 'r') as f: try: dsets = {} for node in f.walk_nodes('/matrix', 'Array'): dsets[node.name] = node.read() from scipy...
java
public static List<UITaskMetric> getTaskMetrics(MetricInfo info, String component, int window) { TreeMap<Integer, UITaskMetric> taskData = new TreeMap<>(); if (info != null) { for (Map.Entry<String, Map<Integer, MetricSnapshot>> metric : info.get_metrics().entrySet()) { Strin...
python
def auto_track_url(track): """ Automatically sets the bigDataUrl for `track`. Requirements: * the track must be fully connected, such that its root is a Hub object * the root Hub object must have the Hub.url attribute set * the track must have the `source` attribute set """ ...
python
def safe_get(data, key_list): ''' Safely access dictionary keys when plugin may have failed ''' for key in key_list: data = data.get(key, {}) return data if data else 'plugin_failed'
python
def get_data(model, instance_id, kind=''): """Get instance data by id. :param model: a string, model name in rio.models :param id: an integer, instance id. :param kind: a string specified which kind of dict tranformer should be called. :return: data. """ instance = get_instance(model, insta...
python
def _run_check(self): """Execute a check command. Returns: True if the exit code of the command is 0 otherwise False. """ cmd = shlex.split(self.config['check_cmd']) self.log.info("running %s", ' '.join(cmd)) proc = subprocess.Popen(cmd, stdout=subprocess.PI...
java
@Override public IDocumentQuery<T> orderByDistance(String fieldName, String shapeWkt) { _orderByDistance(fieldName, shapeWkt); return this; }
python
def create(key_name: str, sections: List[str]): # -> NoParserFoundForObject: """ Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests https://github.com/nose-devs/nose/issues/725 :param key_name: :param sections: :r...
java
private void sleepIfRequired(int bytesUp) throws ConnectException { snifferSocket.lastWriteThreadId = Thread.currentThread().getId(); if (snifferSocket.lastReadThreadId == snifferSocket.lastWriteThreadId) { snifferSocket.potentiallyBufferedInputBytes = 0; } if (0 == sniffe...
java
private void installModuleMBeanServer() { try { Method method = ModuleLoader.class.getDeclaredMethod("installMBeanServer"); method.setAccessible(true); method.invoke(null); } catch (Exception e) { throw new ContainerException("Could not install Module...
python
def fasta(self): """Generates sequence data for the protein in FASTA format.""" max_line_length = 79 fasta_str = '>{0}:{1}|PDBID|CHAIN|SEQUENCE\n'.format( self.parent.id.upper(), self.id) seq = self.sequence split_seq = [seq[i: i + max_line_length] ...
java
public boolean isFeature(String feature) { Boolean result = features.get(feature); return (result != null) ? result : false; }
java
public void setType(DBFDataType type) { if (!type.isWriteSupported()) { throw new IllegalArgumentException("No support for writting " + type); } this.type = type; if (type.getDefaultSize() > 0) { this.length = type.getDefaultSize(); } }
java
@Override public void encode(OutputStream output, Indenter indenter) { encode(output, indenter, null); }
java
public synchronized ActionForward handleException( Throwable ex, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException ...
python
def _cleanup(path: str) -> None: """Cleanup temporary directory.""" if os.path.isdir(path): shutil.rmtree(path)
python
def send(self, request, ordered=False): """ This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def ...
java
@Override public String getClassNameForTable(final Table table) { this.wasUsedBefore = true; for (final NameProvider provider : providers) { final String name = provider.getClassNameForTable(table); if (Objects.nonNull(name)) { return name; ...
java
private ListPartsResult listObjectParts(String bucketName, String objectName, String uploadId, int partNumberMarker) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseExceptio...
python
def get(tag: {str, 'Language'}, normalize=True) -> 'Language': """ Create a Language object from a language tag string. If normalize=True, non-standard or overlong tags will be replaced as they're interpreted. This is recommended. Here are several examples of language codes, wh...
java
public static boolean setEquals(List<String> a, List<String> b) { if (a == null) { a = new ArrayList<>(); } if (b == null) { b = new ArrayList<>(); } if (a.size() != b.size()) { return false; } Collections.sort(a); Coll...