language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SuppressWarnings("unchecked") public <T extends Serializable> T getParsedBody(Class<T> parseClass) throws FoxHttpResponseException { if (foxHttpClient.getFoxHttpResponseParser() == null) { throw new FoxHttpResponseException("getParsedBody needs a FoxHttpResponseParser to deserialize the body");...
java
public static X509CertificateHolder getX509CertificateHolder(CertifiedPublicKey cert) { if (cert instanceof BcX509CertifiedPublicKey) { return ((BcX509CertifiedPublicKey) cert).getX509CertificateHolder(); } else { try { return new X509CertificateHolder(cert.ge...
python
def _M2(Xvar, Yvar, mask_X=None, mask_Y=None, xsum=0, xconst=0, ysum=0, yconst=0, weights=None, diag_only=False): """ direct (nonsymmetric) second moment matrix. Decide if we need dense, sparse, const""" if mask_X is None and mask_Y is None: return _M2_dense(Xvar, Yvar, weights=weights, diag_only=diag_o...
python
def play(): """Open the matched movie with a media player.""" with sqlite3.connect(ARGS.database) as connection: connection.text_factory = str cursor = connection.cursor() if ARGS.pattern: if not ARGS.strict: ARGS.pattern = '%{0}%'.format(ARGS.pattern) ...
python
def ssh(self, *command): """Run an ssh command using the configured user/server values.""" if self.args.user: ssh_spec = '{0}@{1}'.format(self.args.user, self.args.server) else: ssh_spec = self.args.server return self.sh('ssh', ssh_spec, *command)
java
public List<CaseStageInstance> internalGetCaseStages(CaseDefinition caseDef, String caseId, boolean activeOnly, QueryContext queryContext) { CorrelationKey correlationKey = correlationKeyFactory.newCorrelationKey(caseId); Collection<org.jbpm.services.api.model.NodeInstanceDesc> nodes = runtimeD...
java
protected void print(List<? extends DocTree> list, String sep) throws IOException { if (list.isEmpty()) return; boolean first = true; for (DocTree t: list) { if (!first) print(sep); print(t); first = false; } }
python
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows ...
java
public boolean removeNode(String path, boolean removeChildren) throws ZooKeeperException { try { if (removeChildren) { curatorFramework.delete().deletingChildrenIfNeeded().forPath(path); } else { curatorFramework.delete().forPath(path); } ...
java
public Actions click() { if (isBuildingActions()) { action.addAction(new ClickAction(jsonMouse, null)); } return clickInTicks(LEFT); }
python
def new_query(): """Query the information of all the GPUs on local machine""" N.nvmlInit() def _decode(b): if isinstance(b, bytes): return b.decode() # for python3, to unicode return b def get_gpu_info(handle): """Get one GPU info...
java
@SafeVarargs public static <T, U, R> BiFunction<T, U, Optional<R>> maybeFirstMatch(BinaryClause<T, U, R>... clauses) { final List<Clause<Pair<T, U>, R>> unaryClauses = Sequences.of(clauses).map(BinaryClause::tupled).toList(); return Pairs.untupled(new MaybeFirstMatchStrategy<>(unaryClauses)); }
python
def get_observing_method_kwargs(self, prop_name, method): """ Returns the keyword arguments which were specified when declaring a notification method, either statically or dynamically with :meth:`Observer.observe`. Since patterns may be involved when declaring the notifi...
java
public CellFormatter createFormatter(final String formatPattern) { final CellFormatter formatter = customFormatterFactory.create(formatPattern); return formatter; }
python
def getTransitionActor(obj, action_id): """Returns the actor that performed a given transition. If transition has not been perormed, or current user has no privileges, returns None :return: the username of the user that performed the transition passed-in :type: string """ review_history = getRev...
python
def ari(reference_intervals, reference_labels, estimated_intervals, estimated_labels, frame_size=0.1): """Adjusted Rand Index (ARI) for frame clustering segmentation evaluation. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') ...
java
@Nullable public static MimeType safeParseMimeType (@Nullable final String sMimeType, @Nonnull final EMimeQuoting eQuotingAlgorithm) { try { return parseMimeType (sMimeType, eQuotingAlgorithm); } catch (final MimeTypeParserException ex) { r...
java
public String getWebhookUrl() throws PropertyException { String url = PropertyManager.getProperty("mdw.slack.webhook.url"); if (url == null) throw new PropertyException("Missing configuration: mdw.slack.webhook.url"); return url; }
python
def resetPassword(self, userId): ''' Changes a user's password to a system-generated value. ''' self._setHeaders('resetPassword') return self._sforce.service.resetPassword(userId)
java
public ServiceFuture<ImmutabilityPolicyInner> lockImmutabilityPolicyAsync(String resourceGroupName, String accountName, String containerName, String ifMatch, final ServiceCallback<ImmutabilityPolicyInner> serviceCallback) { return ServiceFuture.fromHeaderResponse(lockImmutabilityPolicyWithServiceResponseAsync(r...
java
final public void configureImpl(Object bean) // , ConfigType<?> type) throws ConfigException { Objects.requireNonNull(bean); //Objects.requireNonNull(type); try { //type.beforeConfigure(bean); // ioc/23e7 InjectContext env = InjectContextImpl.CONTEXT; injectTop(be...
java
private void reportException(Exception e) { logger.error("Failed to write JSON export: " + e.toString()); throw new RuntimeException(e.toString(), e); }
java
static SoyMsgBundle parseXliffTargetMsgs(String xliffContent) throws SAXException { // Get a SAX parser. SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); } catch (ParserConfigurationException pce) { ...
java
public final Tuple5<T2, T3, T4, T5, T6> skip1() { return new Tuple5<>(v2, v3, v4, v5, v6); }
java
public void purgeCounters(final long epochMinute) { for (Iterator<Map.Entry<String, MinuteCounter>> it = errorCounter.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String, MinuteCounter> entry = it.next(); if (entry.getValue().getEpochMinute() < epochMinute) { it.remove(); ...
java
private void addReferenceToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) { final String url = nextLine.substring("URL: ".length()); if (null != vulnerability) { final Reference ref = new Reference(); ref.setName(vulnerability.getName()); ...
java
public void align(Structure s1, Structure s2, StrucAligParameters params) throws StructureException { // step 1 convert the structures to Atom Arrays Atom[] ca1 = getAlignmentAtoms(s1); Atom[] ca2 = getAlignmentAtoms(s2); notifyStartingAlignment(s1.getName(), ca1, s2.getName(), ca2); align(ca1, ca2, para...
python
def getTempDirectory(rootDir=None): """ returns a temporary directory that must be manually deleted. rootDir will be created if it does not exist. """ if rootDir is None: return tempfile.mkdtemp() else: if not os.path.exists(rootDir): try: os.makedirs(...
python
def extract_tar(url, target_dir, additional_compression="", remove_common_prefix=False, overwrite=False): """ extract a targz and install to the target directory """ try: if not os.path.exists(target_dir): os.makedirs(target_dir) tf = tarfile.TarFile.open(fileobj=download_to_bytesio(...
java
public DetectorFactory getFactoryByFullName(final String fullName) { return findFirstMatchingFactory(factory -> factory.getFullName().equals(fullName)); }
python
def options(self, parser, env): """ Configure with command line option '--filetype'. """ Plugin.options(self, parser, env) parser.add_option('--filetype', action='append', help='Specify additional filetypes to monitor.')
python
def search_reference_sets( self, accession=None, md5checksum=None, assembly_id=None): """ Returns an iterator over the ReferenceSets fulfilling the specified conditions. :param str accession: If not null, return the reference sets for which the `accession` matche...
java
public List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units) { List<UnitValue> result = new ArrayList<>(); for (int i = 0; i < units.length; i++) { UnitFactor factor = resolve(units[i], base); if (factor != null) { BigDecimal n = factor.rational().compute(mode); resu...
java
public <T, S> Future<CallResults<T, S>> call(final InputHandler<T> inputHandler, final OutputHandler<S> outputHandler) throws SQLException { return executorService.submit(new Callable<CallResults<T, S>>() { /** * {@inheritDoc} */ public CallResults<T, S> call()...
java
@Override public synchronized Lock obtainWriteLock() { Set<File> readLocks = getReadLocks(); if (readLocks.isEmpty()) { final File writeLock = getWriteLock(); if (writeLock == null) { return createLock(true); } } return null; }
python
def _getUserCodeFunctionName(self): """ Get the name of the function 4 levels up the stack (above this function, our caller, and whatever Toil code delegated to the JobStore implementation). Returns a string usable in a filename, and returns a placeholder string if the function n...
python
def _before_initialize(self, location, **kwargs): """ Check if specific URL has not been provided, otherwise, use cls._URL""" url = kwargs.get('url', '') if url.lower() == 'localhost': self.url = 'http://localhost/nominatim/search' elif url: self.url = url
python
def _isnan(self): """ Return if each value is NaN. """ if self._can_hold_na: return isna(self) else: # shouldn't reach to this condition by checking hasnans beforehand values = np.empty(len(self), dtype=np.bool_) values.fill(False) ...
python
def include(self): """Return fields to include :return list: a list of include information """ include_param = self.qs.get('include', []) if current_app.config.get('MAX_INCLUDE_DEPTH') is not None: for include_path in include_param: if len(include_pa...
java
protected <T extends Controller> void redirect(Class<T> controllerClass){ redirect(controllerClass, new HashMap<String, String>(0)); }
java
public static double width_interpolate( double[][] data, double x, int nx, int ny ) { int rows = data.length; double xuno = 0, xdue = 0, yuno = 0, ydue = 0, y = 0; // if 0, interpolate between 0 and the first value of data if (x >= 0 && x < data[0][nx]) { xuno = 0; ...
java
private StatementResult addPerson( final Transaction tx, final String name ) { return tx.run( "CREATE (:Person {name: $name})", parameters( "name", name ) ); }
java
public void bind(Class<?> type, Class<? extends SARLSemanticModification> modification) { this.modificationTypes.put(type, modification); }
java
public void decode(ByteBuffer dst, int stride, int numMCURows, YUVDecoder decoder) throws IOException { if(decoder == null) { throw new NullPointerException("decoder"); } if(!insideSOS) { throw new IllegalStateException("decode not started"); } i...
java
public static String getDisplayName(TypeDeclaration type) { if (type == null || type.displayName() == null) { return null; } else { return type.displayName().value(); } }
python
def get_object_attrs(obj): """ Get the attributes of an object using dir. This filters protected attributes """ attrs = [k for k in dir(obj) if not k.startswith('__')] if not attrs: attrs = dir(obj) return attrs
python
def get_scipy_minimizer(**kwargs): """Get minimizer which uses `scipy.optimize.minimize`""" def minimizer(objective, n_params): params = [random.random() for _ in range(n_params)] result = scipy_minimizer(objective, params, **kwargs) return result.x return minimizer
java
@Override public void clearCache() { entityCache.clearCache(CPDAvailabilityEstimateImpl.class); finderCache.clearCache(FINDER_CLASS_NAME_ENTITY); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); }
python
def dens_in_meanmatterdens(vo,ro,H=70.,Om=0.3): """ NAME: dens_in_meanmatterdens PURPOSE: convert density to units of the mean matter density INPUT: vo - velocity unit in km/s ro - length unit in kpc H= (default: 70) Hubble constant in km/s/Mpc Om= (defa...
java
private int lastIndexOfNumericTag(String category) { if (category == null) { return -1; } int last = -1; for (int i = category.length() - 1; i >= 0; i--) { if (isLabelAnnotationIntroducingCharacter(category.charAt(i))) { boolean onlyDigitsFollow = false; for (int j = ...
java
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/oauth_approved_apps") @Description("Returns list of Oauth approved apps of argus for this user") public List<AuthenticatedOAuthAppDto> authenticatedApps(@Context HttpServletRequest req) { String userName=findUserByToken(req); int result ...
python
def delete(user_id): ''' Delele the user in the database by `user_id`. ''' try: del_count = TabMember.delete().where(TabMember.uid == user_id) del_count.execute() return True except: return False
java
public synchronized void stop() { running = false; pool.shutdown(); try { if (!pool.awaitTermination(60, TimeUnit.SECONDS)) pool.shutdownNow(); if (!serverSocket.isClosed()) this.serverSocket.close(); } catch (IOException e) { DBP.printerror("Error closing Socket."); DBP.printException(e); ...
python
def from_event(cls, event): """Create a message from an event :param event: the event that was received of type ``pubmsg`` or ``privmsg`` :type event: :class:`Event3` :returns: a message that resembles the event :rtype: :class:`Message3` :raises: None """ ...
java
private List<String> filterAttributeNames(MBeanServerExecutor pSeverManager,ObjectName pName, List<String> pNames) throws IOException, ReflectionException, MBeanException, AttributeNotFoundException, InstanceNotFoundException { Set<String> attrs = new HashSet<String>(getAllAttributesNames(pSeverMana...
python
def removevalues(self, key, values): """ Removes all <values> from the values of <key>. If <key> has no remaining values after removevalues(), the key is popped. Example: omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)]) omd.removevalues(1, [1, 111]) omd.al...
java
public void releaseTrailers(HttpTrailersImpl h) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "releaseTrailers: " + h); } this.hdrPool.put(h); }
java
protected boolean isEncodeable(final String location) { //accessing protected methods using reflection: //return httpServletResponse.isEncodeable(location); boolean result=false; try{ Method isEncodeable = HttpServletResponseImpl.class.getDeclaredMethod("isEncodeable", String...
java
public static String formatNodeName(RemedyIndexEventData eventData) { StringBuilder builder = new StringBuilder(); builder.append(eventData.getProcessId()).append(SPLIT).append(eventData.getStartTime()).append(SPLIT).append(eventData.getEndTime()); return builder.toString(); }
java
@SuppressWarnings("unchecked") public <M extends T> Set<M> findSet() { return (Set<M>) query().findSet(); }
java
@SuppressWarnings("ReferenceEquality") // unknownType is a singleton private FlowScope inferParameters(FlowScope entryFlowScope) { Node functionNode = containerScope.getRootNode(); if (!functionNode.isFunction()) { return entryFlowScope; // we're in the global scope } else if (NodeUtil.isBundledGoog...
python
def setHoverable(self, state): """ Sets whether or not this is a hoverable button. When in a hoverable state, the icon will only be visible when the button is hovered on. :param state | <bool> """ self._hoverable = state self._hoverIcon = self.icon(...
java
static boolean bodyMayHaveConditionalCode(Node n) { if (!n.isReturn() && !n.isExprResult()) { return true; } return mayHaveConditionalCode(n); }
python
def expand_default(self, scale, discrete=(0, 0.6, 0, 0.6), continuous=(0.05, 0, 0.05, 0)): """ Expand a single scale """ if is_waive(scale.expand): if isinstance(scale, scale_discrete): return discrete elif isinstance(scale, ...
java
private byte[] pbkdf2(final String password, final byte[] salt, int iterations) { try { Mac mac = Mac.getInstance(hmacAlgorithm); Key key; if (password == null || password.isEmpty()) { key = new EmptySecretKey(hmacAlgorithm); } else { ...
java
public static Span getValue(Context context) { @javax.annotation.Nullable Span span = CONTEXT_SPAN_KEY.get(Utils.checkNotNull(context, "context")); return span == null ? BlankSpan.INSTANCE : span; }
java
private BitMatrix sampleGrid(BitMatrix image, ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomRight, ResultPoint bottomLeft) throws NotFoundException { GridSampler sampler = Grid...
python
def wash_for_js(text): """ DEPRECATED: use htmlutils.escape_javascript_string() instead, and take note that returned value is no longer enclosed into quotes. """ from invenio_utils.html import escape_javascript_string if isinstance(text, six.string_types): return '"%s"' % escape_java...
java
public ResultSet getResultSet(int iType) { switch (iType) { case DBConstants.SQL_SEEK_TYPE: if (!SHARE_STATEMENTS) return m_seekResultSet; case DBConstants.SQL_SELECT_TYPE: case DBConstants.SQL_CREATE_TYPE: retur...
java
public <T> T convert(final Object result, final Class<T> targetType) { return convert(result, targetType, defaultResultConverter); }
java
public String startDirectEditEnabled(CmsDirectEditParams params, CmsDirectEditResourceInfo resourceInfo) throws JSONException { String editLocale = m_cms.getRequestContext().getLocale().toString(); String editId = getNextDirectEditId(); String editNewLink = CmsEncoder.encode(params.getLinkF...
python
def add_root_log_file(log_file): """ Add a log file to the root logger. Parameters ---------- log_file :obj:`str` The path to the log file. """ root_logger = logging.getLogger() # add a file handle to the root logger hdlr = logging.FileHandler(log_file) formatter = logg...
java
public List<DllCharacteristic> getDllCharacteristics() { long value = get(DLL_CHARACTERISTICS); List<DllCharacteristic> dllChs = DllCharacteristic.getAllFor(value); return dllChs; }
python
def reset(self): """Reset the simulation to its initial state.""" warnings.warn("This reset method is very crude. It should work for " "many simple simulations, but we make no guarantees. In " "particular, if you have components that manage their " ...
python
def transactional_async(func, args, kwds, **options): """The async version of @ndb.transaction.""" options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED) if args or kwds: return transaction_async(lambda: func(*args, **kwds), **options) return transaction_async(func, **options)
python
def ru_strftime(date, format="%d.%m.%Y", inflected_day=False, preposition=False): """ Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strfti...
python
def make_default_logger(name=INTERNAL_LOGGER_NAME, level=logging.INFO, fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s'): """Create a logger with the default configuration""" logger = logging.getLogger(name) logger.setLevel(level) if not logger.handlers: handler...
java
public void hover(final By by) { checkTopmostElement(by); WebElement element = findElement(by); new Actions(webDriver).moveToElement(element).perform(); }
java
@Override public void deselectAll() { if (!isMultiple()) { throw new UnsupportedOperationException( "You may only deselect all options of a multi-select"); } for (WebElement option : getOptions()) { setSelected(option, false); } }
python
def _apply_uncertainty_to_mfd(self, mfd, value): """ Modify ``mfd`` object with uncertainty value ``value``. """ if self.uncertainty_type == 'abGRAbsolute': a, b = value mfd.modify('set_ab', dict(a_val=a, b_val=b)) elif self.uncertainty_type == 'bGRRelati...
python
def at(self, step): """Return a TimeMachine for the same object at a different time. Takes an integer argument representing the id field of an Action. Returns the TimeMachine at the time of that Action. (Less ambiguously: at the time right after the Action. """ return T...
python
def __createLayout(self): """Creates the dialog layout""" self.resize(450, 150) self.setSizeGripEnabled(True) verticalLayout = QVBoxLayout(self) whereGroupbox = QGroupBox(self) whereGroupbox.setTitle("Garbage collector message destination") sizePolicy = QSizePol...
java
protected boolean waitForJobs() throws InterruptedException { final Pair<Long, Job> peekPair; try (Guard ignored = timeQueue.lock()) { peekPair = timeQueue.peekPair(); } if (peekPair == null) { awake.acquire(); return true; } final long...
python
def taskDefined(self, *args, **kwargs): """ Task Defined Messages When a task is created or just defined a message is posted to this exchange. This message exchange is mainly useful when tasks are scheduled by a scheduler that uses `defineTask` as this does not make the...
java
public void marshall(SymbolicLink symbolicLink, ProtocolMarshaller protocolMarshaller) { if (symbolicLink == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(symbolicLink.getBlobId(), BLOBID_BINDING); ...
python
def td_contents(self, item, attr_list): """Given an item and an attr, return the contents of the td. This method is a likely candidate to override when extending the Col class, which is done in LinkCol and ButtonCol. Override this method if you need to get some extra data from t...
python
def blockstart_tolineno(self): """The line on which the beginning of this block ends. :type: int """ if self.name: return self.name.tolineno if self.type: return self.type.tolineno return self.lineno
java
public void remove(int n) { assert this.inHeap(n); int kPos = this.indices.get(n); this.indices.set(n, -1); if (kPos < this.heap.size() - 1) { this.heap.set(kPos, this.heap.back()); this.indices.set(this.heap.get(kPos), kPos); this.heap.pop(); this.percolateDown(kPos); } else...
python
def to_string(self, shell=None): '''Use the command executor to retrieve the text of the scrim script compatible with the provided shell. If no shell is provided, use :attr:`scrim.shell`. Attributes: shell (str): Which shell should we return a script for cmd....
python
def update_grid(self): """Update grid according to info map.""" info_map = self.ms_game.get_info_map() for i in xrange(self.ms_game.board_height): for j in xrange(self.ms_game.board_width): self.grid_wgs[(i, j)].info_label(info_map[i, j]) self.ctrl_wg.move_co...
python
def augment_observation( observation, reward, cum_reward, frame_index, bar_color=None, header_height=27 ): """Augments an observation with debug info.""" img = PIL_Image().new( "RGB", (observation.shape[1], header_height,) ) draw = PIL_ImageDraw().Draw(img) draw.text( (1, 0), "c:{:3}, r:{:...
python
def cidr_broadcast(cidr): ''' Get the broadcast address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return six.text_type(ips.broadcast)
java
protected void validateCertificate(X509Certificate[] chain) throws com.ibm.wsspi.security.wim.exception.CertificateMapFailedException { // validate the certificate array if (chain == null || chain.length == 0) { throw new com.ibm.wsspi.security.wim.exception.CertificateMapFailedException(); ...
python
def _get_config(self, path=None): """ Get the config. :rtype: dict """ if not path and not self.option("config"): raise Exception("The --config|-c option is missing.") if not path: path = self.option("config") filename, ext = os.path.spl...
python
def normalise(self, string, line_num): """ Strips the whitespace and applies Unicode normalisation to the given string. The second arg is used as an ID of the string when reporting its lint errors (if such). """ stripped = string.strip() if stripped != string: self.strip_errors.append(line_num) nfc_...
java
public RestItem updateItem( HttpServletRequest request, String rawRepositoryName, String rawWorkspaceName, String path, String requestContent ) throws JSONException, RepositoryException { ...
python
def get_dataset(corpora): """ Return a dictionary of subjectID -> [path_to_resource]. """ # TODO: make filter methods for the files def make_posix_path(dirpath, filename): dirpath = posixpath.sep.join(dirpath.split(os.sep)) return posixpath.join(dirpath, filename) wav_files_in_...
python
def get_view(self, mo_ref, properties=None): """Get a view of a vSphere managed object. :param mo_ref: The MOR to get a view of :type mo_ref: ManagedObjectReference :param properties: A list of properties to retrieve from the \ server :type properties: list ...
python
def get_agent(msg): """ Handy hack to handle legacy messages where 'agent' was a list. """ agent = msg['msg']['agent'] if isinstance(agent, list): agent = agent[0] return agent
python
def reindex_to(self, x, attribute="Name"): """ Returns a copy that only has rows corresponding to feature names in x. Parameters ---------- x : str or pybedtools.BedTool BED, GFF, GTF, or VCF where the "Name" field (that is, the value returned by feature[...