language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def timescales(self): r"""Implied timescales of the TICA transformation For each :math:`i`-th eigenvalue, this returns .. math:: t_i = -\frac{\tau}{\log(|\lambda_i|)} where :math:`\tau` is the :py:obj:`lag` of the TICA object and :math:`\lambda_i` is the `i`-th :p...
java
public void reConnect() throws IOException { try { if (client != null && client.isConnected()) client.disconnect(); } catch (IOException ioe) {} connect(); }
java
public void writeIntern (String value) throws IOException { // if the value to be written is null, simply write a zero if (value == null) { writeShort(0); return; } // create our intern map if necessary if (_internmap == null) { _i...
java
public synchronized OServerAdmin dropDatabase() throws IOException { storage.checkConnection(); boolean retry = true; while (retry) try { final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_DROP); try { network.writeString(st...
python
def load_file(self, app, pathname, relpath, pypath): """Loads a file and creates a View from it. Files are split between a YAML front-matter and the content (unless it is a .yml file). """ try: view_class = self.get_file_view_cls(relpath) return create_view_from_f...
python
def run_steps(args: argparse.Namespace): """Run all steps required to complete task. Called directly from main.""" logging.basicConfig(level=logging.INFO, format="sockeye.autopilot: %(message)s") # (1) Establish task logging.info("=== Start Autopilot ===") # Listed task if args.task: ...
java
public MultiRuntimeDefinitionBuilder addRuntime(final Configuration config, final String runtimeName){ Validate.notNull(config, "runtime configuration module should not be null"); Validate.isTrue(StringUtils.isNotBlank(runtimeName), "runtimeName should be non empty and non blank string"); final ...
java
public Map<String, Object> getExtra() { if (extra == null) { // `extra` *should* never be null, but there are scenarios such as // when an application is run through ProGuard which may cause deserialization // code to be removed (and thus silently not run). In this case, our ...
python
def _write_value(self, field_type, value): """ Writes an item of an array :param field_type: Value type :param value: The value itself """ if len(field_type) > 1: # We don't need details for arrays and objects field_type = field_type[0] i...
python
def cli(env, origin_volume_id, origin_snapshot_id, duplicate_size, duplicate_iops, duplicate_tier, duplicate_snapshot_size, billing): """Order a duplicate file storage volume.""" file_manager = SoftLayer.FileStorageManager(env.client) hourly_billing_flag = False if billing.lower() == "hourly": ...
java
private void addQueryParams(final Request request) { if (startDate != null) { request.addQueryParam("StartDate", DateConverter.dateStringFromLocalDate(startDate)); } if (endDate != null) { request.addQueryParam("EndDate", DateConverter.dateStringFromLocalDate(endDate)); ...
java
public HtmlTree getStyleSheetProperties() { String stylesheetfile = configuration.stylesheetfile; DocPath stylesheet; if (stylesheetfile.isEmpty()) { stylesheet = DocPaths.STYLESHEET; } else { DocFile file = DocFile.createFileForInput(configuration, stylesheetfile...
java
private boolean readyToRestore(T object, boolean valid) { try { boolean ready = false; try { ready = valid && poolObjectFactory.readyToRestore(object); } finally { if (!ready) { poolObjectFactory.destroy(object); ...
python
def insertInto(self, tableName, overwrite=False): """Inserts the content of the :class:`DataFrame` to the specified table. It requires that the schema of the class:`DataFrame` is the same as the schema of the table. Optionally overwriting any existing data. """ self._jw...
java
@SafeVarargs public static <A> EnumGene<A> of( final int alleleIndex, final A... validAlleles ) { return new EnumGene<>(alleleIndex, ISeq.of(validAlleles)); }
java
public void doStatementCleanup(PreparedStatement stmt) throws SQLException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (setCursorNameSupported) { try{ stmt.setCursorName(null); } catch (SQLFeatureNotSupportedException s...
python
def check_css_selectors(webdriver, *selectors): """Returns true if all CSS selectors passed in is found. This can be used to quickly validate a page. Args: webdriver (Webdriver) : Selenium Webdriver instance selectors (str) : N number of CSS selectors strings to match ...
java
public void index(DigitalObject object, Payload payload) throws IndexerException { String oid = object.getId(); String pid = payload.getId(); // Don't proccess annotations through this function if (pid.startsWith("anotar.")) { annotate(object, payload); return; } // log.info("Indexing OID:'{}', PID: ...
python
def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613 ''' Lists all packages available for update. When run in global zone, it reports only upgradable packages for the global zone. When run in non-global zone, it can report more upgradable packages than ``pkg update -vn``, becaus...
java
@Nullable public static CascadingStyleSheet readFromFile (@Nonnull final File aFile, @Nonnull final CSSReaderSettings aSettings) { return readFromStream (new FileSystemResource (aFile), aSettings); }
java
public Lockable write_lock( Key job_key ) { Log.debug(Log.Tag.Sys.LOCKS,"write-lock "+_key+" by job "+job_key); return ((PriorWriteLock)new PriorWriteLock(job_key).invoke(_key))._old; }
java
private static void initializeSupportedEntities() { defaultSupportedEntities = new ArrayList<String>(2); defaultSupportedEntities.add(Service.DO_PERSON_ACCOUNT); defaultSupportedEntities.add(Service.DO_GROUP); }
python
def render(self, data, mimetype): """ Serializes a Python object into a byte array containing a JSON document. :param data: A Python object. :param mimetype: The mimetype to render the data. :return: A byte array containing a JSON document. """ indent = self.__ge...
java
@DefinedBy(Api.COMPILER) public Diagnostic.Kind getKind() { switch (diagnosticInfo.type) { case NOTE: return Diagnostic.Kind.NOTE; case WARNING: return flags.contains(DiagnosticFlag.MANDATORY) ? Diagnostic.Kind.MANDATORY_WARNING ...
java
private void processService(Service service) throws Exception { getLog().info(" Service: " + service.getServiceName()); Document iddDoc = parseIddFile(service.getServiceName()); // 1. validate if (!isOffline()) { getLog().debug("Validating XML.."); new XmlVali...
python
def issue_date(self, value): """ The date on which the asset is issued :param value: :return: """ self._issue_date = parse(value).date() if isinstance(value, type_check) else value
java
public static boolean isEqualsMethod(Method method) { if (method == null || false == method.getName().equals("equals")) { return false; } final Class<?>[] paramTypes = method.getParameterTypes(); return (1 == paramTypes.length && paramTypes[0] == Object.class); }
java
public CompiledScript compile(String scriptSource) throws ScriptException { try { return new GroovyCompiledScript(this, getScriptClass(scriptSource)); } catch (CompilationFailedException ee) { throw new ScriptException(ee); } }
python
def _cleanstarlog(file_in): """ cleaning history.data or star.log file, e.g. to take care of repetitive restarts. private, should not be called by user directly Parameters ---------- file_in : string Typically the filename of the mesa output history.data or star.log file, c...
java
@Override protected void postInit(Connection connection) throws SQLException { super.postInit(connection); Statement stmt = null; ResultSet rs = null; try { if (containerConfig.useSequenceForOrderNumber) { String select = "select * from JC...
java
public int compareSourceLines(BugCollection lhsCollection, BugCollection rhsCollection, SourceLineAnnotation lhs, SourceLineAnnotation rhs) { if (lhs == null || rhs == null) { return compareNullElements(lhs, rhs); } // Classes must match fuzzily. int cmp = compar...
java
public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { final Resource resource = createResource(context, operation); populateModel(context, operation, resource); recordCapabilitiesAndRequirements(context, operation, resource); //v...
java
protected void copyDataOutBound(int sourceTaskId, boolean isLocalSpout, TopologyAPI.StreamId streamId, HeronTuples.HeronDataTuple tuple, List<Integer> outTasks) { boolean firstIter...
python
def json_safe(string, content_type='application/octet-stream'): """Returns JSON-safe version of `string`. If `string` is a Unicode string or a valid UTF-8, it is returned unmodified, as it can safely be encoded to JSON string. If `string` contains raw/binary data, it is Base64-encoded, formatted and ...
python
def validate_items(self): """ Validates the items in the backing array, including performing type validation. Sets the _typed property and clears the dirty flag as a side effect Returns: The typed array """ logger.debug(fmt("Validating {}", self)) fr...
java
public T tag(Object tag) { if (view != null) { view.setTag(tag); } return self(); }
java
public void fireHttpSessionUpdated(final HttpSession session) { if (View.isInitialised() && !EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { fireHttpSessionUpdated(session); } }); return; } int index = sessions.indexOf(session); ...
python
def write_info(dirs, parallel, config): """Write cluster or local filesystem resources, spinning up cluster if not present. """ if parallel["type"] in ["ipython"] and not parallel.get("run_local"): out_file = _get_cache_file(dirs, parallel) if not utils.file_exists(out_file): sys...
python
def single_load(input_, ac_parser=None, ac_template=False, ac_context=None, **options): r""" Load single configuration file. .. note:: :func:`load` is a preferable alternative and this API should be used only if there is a need to emphasize given input 'input\_' is single ...
java
@Override public void visit(int version, int access, String classResourceName, String signature, String superClassResourceName, String interfaceResourceNames[]) { Object[] logParms; if (tc....
python
def send_game(self, *args, **kwargs): """See :func:`send_game`""" return send_game(*args, **self._merge_overrides(**kwargs)).run()
java
public static double d(int[] x, int[] y) { if (x.length != y.length) throw new IllegalArgumentException(String.format("Arrays have different length: x[%d], y[%d]", x.length, y.length)); double dist = 0.0; for (int i = 0; i < x.length; i++) { double d = Math.abs(x[i] - y[...
java
public static Method findSetter(String methodName, Object instance, Class<?> valueClass) throws NoSuchMethodException { return findMethod(methodName, instance, valueClass, true); }
java
@Override protected int deleteValueData(String cid) throws SQLException, InvalidItemStateException, RepositoryException { if (deleteValue == null) { deleteValue = dbConnection.prepareStatement(DELETE_VALUE); } else { deleteValue.clearParameters(); } del...
python
def merged(self, other): """Returns the merged result of two requirements. Two requirements can be in conflict and if so, this function returns None. For example, requests for "foo-4" and "foo-6" are in conflict, since both cannot be satisfied with a single version of foo. Some...
java
public int refreshNamenodes(String[] argv, int i) throws IOException { ClientDatanodeProtocol datanode = null; String dnAddr = (argv.length == 2) ? argv[i] : null; try { datanode = getClientDatanodeProtocol(dnAddr); if (datanode != null) { datanode.refreshNamenodes(); retu...
python
def get_lldp_neighbors(self): """IOS implementation of get_lldp_neighbors.""" lldp = {} neighbors_detail = self.get_lldp_neighbors_detail() for intf_name, entries in neighbors_detail.items(): lldp[intf_name] = [] for lldp_entry in entries: hostname...
java
public int[] toIntArray() { final int[] result = new int[this.size()]; this.forEachWithIndex(new IntIntProcedure() { public void value(int each, int index) { result[index] = each; } }); return result; }
java
public Alignment<S> invert(S sequence2) { return new Alignment<>(sequence2, getRelativeMutations().invert().move(sequence2Range.getFrom()), sequence2Range, sequence1Range, score); }
python
def impute_knn(df, k=3): """ Nearest neighbour imputations which weights samples using the mean squared difference on features for which two rows both have observed data. :param df: The input dataframe that contains missing values :param k: The number of neighbours :return: the ...
java
public boolean setVetoPolicy(TimeVetoPolicy vetoPolicy) { if (parent == null) { throw new RuntimeException("TimePickerSettings.setVetoPolicy(), " + "A veto policy can only be set after constructing the TimePicker."); } this.vetoPolicy = vetoPolicy; return ...
python
def _on_model_delete(sender, **kwargs): """Remove documents from search indexes post_delete.""" instance = kwargs.pop("instance") for index in instance.search_indexes: try: _delete_from_search_index(instance=instance, index=index) except Exception: logger.exception("E...
java
@Override public Service getService(ThriftClient thriftClient, String serviceName) throws IkasoaException { if (thriftClient == null) throw new IllegalArgumentException("'thriftClient' is null !"); return StringUtil.isEmpty(serviceName) ? new ServiceClientImpl(thriftClient.getProtocol(thriftClient.getT...
java
public static X509Certificate readCertificate(final Resource resource) { try (val in = resource.getInputStream()) { return CertUtil.readCertificate(in); } catch (final Exception e) { throw new IllegalArgumentException("Error reading certificate " + resource, e); } }
python
def _get_phi(self, C, mag): """ Returns the magnitude dependent intra-event standard deviation (phi) (equation 15) """ if mag < 5.5: return C["phi1"] elif mag < 5.75: return C["phi1"] + (C["phi2"] - C["phi1"]) * ((mag - 5.5) / 0.25) else: ...
java
@Override public boolean containsValue(Object value) { // Overridden to take advantage of faster iterator if (value == null) { for (Entry e = header.after; e != header; e = e.after) if (e.value == null) return true; } else { for (Entry e = header.after; e != header; e = e.after) if (value.equals(e...
python
def serve_file(load, fnd): ''' Return a chunk from a file based on the data received ''' if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') ret = {'data': '', 'dest': ''} if 'path' not in load or 'loc' not in load or 'saltenv' not in load: ...
python
def fill(h1: Histogram1D, ax: Axes, **kwargs): """Fill plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) # show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulative", False) kwargs["label"] = kwargs.get("label", ...
java
public IfcServiceLifeFactorTypeEnum createIfcServiceLifeFactorTypeEnumFromString(EDataType eDataType, String initialValue) { IfcServiceLifeFactorTypeEnum result = IfcServiceLifeFactorTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue + "'...
python
def requirement_spec(package_name, *args): """Identifier used when specifying a requirement to pip or setuptools.""" if not args or args == (None,): return package_name version_specs = [] for version_spec in args: if isinstance(version_spec, (list, tuple)): operator, v...
python
def get_scan_parameters_index(scan_parameter): '''Takes the scan parameter array and creates a scan parameter index labeling the unique scan parameter combinations. Parameters ---------- scan_parameter : numpy.ndarray The table with the scan parameters. Returns ------- numpy.Histogr...
python
def condition_indices(df): ''' Returns a pandas Series with condition indices of the df columns. Args: df: pandas DataFrame with columns to run diagnostics on ''' eigvals = eigenvalues(df) cond_idx = np.sqrt(eigvals.max() / eigvals) return pd.Series(cond_idx, df.columns, name='Condi...
python
def expand_file_arguments(): """ Any argument starting with "@" gets replaced with all values read from a text file. Text file arguments can be split by newline or by space. Values are added "as-is", as if they were specified in this order on the command line. """ new_args = [] expanded = False ...
python
def send_simple(self, address, timestamp, value): """Queue a simple datapoint (ie. a 64-bit word), return True/False for success. Arguments: address -- uint64_t representing a unique metric. timestamp -- uint64_t representing number of nanoseconds (10^-9) since epoch. value -- u...
python
def convert_to_cached_wcs(self, hpx_in, sum_ebins=False, normalize=True): """ Make a WCS object and convert HEALPix data into WCS projection Parameters ---------- hpx_in : `~numpy.ndarray` HEALPix input data sum_ebins : bool sum energy bins over energy...
python
def locate_run(output, target, no_newline): """ Print location of RASH related file. """ from .config import ConfigStore cfstore = ConfigStore() path = getattr(cfstore, "{0}_path".format(target)) output.write(path) if not no_newline: output.write("\n")
java
public void setBytes(long memoryOffset, byte[] buffer, int bufferOffset, int count) { if (buffer == null) throw new NullPointerException(); else if (bufferOffset < 0 || count < 0 || bufferOffset + count > buffer.length) throw new IndexOutOfBo...
java
public boolean printToolbarControl(boolean bFieldsFound, PrintWriter out, int iHtmlAttributes) { out.println(Utility.startTag("toolbars")); int iNumCols = ((ToolScreen)this.getScreenField()).getSFieldCount(); for (int iIndex = 0; iIndex < iNumCols; iIndex++) { ScreenField...
java
public static double pdf(double val, double loc, double scale) { val = Math.abs((val - loc) / scale); double e = FastMath.exp(-val); double f = 1.0 + e; return e / (scale * f * f); }
python
def van_image_enc_2d(x, first_depth, reuse=False, hparams=None): """The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf). Args: x: The image to encode. first_depth: The depth of the first layer. Depth is increased in subseq...
java
private void setBooleanQueryMaxClauseCount() { if (!maxBooleanClausesWasSet) { maxBooleanClausesWasSet = true; String maxClauseCountProp = SecurityActions.getSystemProperty(MAX_BOOLEAN_CLAUSES_SYS_PROP); if (maxClauseCountProp != null) { int maxClauseCount; try {...
java
public static synchronized void after(String url, HttpConsumer<Exchange> consumer) { checkStarted(); instance().interceptors.add(new Interceptor(Interceptor.Type.AFTER, HandlerUtil.parseUrl(url), consumer)); }
python
def router_added_to_hosting_device(self, context, router): """Notify cfg agent about router added to hosting device.""" self._notification(context, 'router_added_to_hosting_device', [router], operation=None, shuffle_agents=False)
python
def list(self, search_opts=None, limit=None, marker=None, sort_by=None, reverse=None): """Get a list of Jobs.""" query = base.get_query_string(search_opts, limit=limit, marker=marker, sort_by=sort_by, reverse=reverse) url = "/jobs%s" % query ...
python
def _build_strain_specific_model(self, strain_id, ref_functional_genes, orth_matrix, force_rerun=False): """Create strain GEMPRO, set functional genes""" gp_noseqs_path = op.join(self.model_dir, '{}_gp.pckl'.format(strain_id)) if ssbio.utils.force_rerun(flag=force_rerun, outfile=gp_noseqs_path)...
python
def cmd_fw_list(self, args): '''cmd handler for list''' stuff = self.filtered_rows_from_args(args) if stuff is None: return (filtered, remainder) = stuff print("") print(" seq platform frame major.minor.patch releasetype latest git-sha format") for ...
python
def download_quads(name, bbox, rbox, quiet, dest, limit): '''Download quads from a mosaic''' bbox = bbox or rbox cl = clientv1() dl = downloader.create(cl, mosaic=True) output = downloader_output(dl, disable_ansi=quiet) output.start() try: mosaic, = cl.get_mosaic_by_name(name).items...
python
def _identify_eds_ing(first, second): """Find nodes connecting adjacent edges. Args: first(Edge): Edge object representing the first edge. second(Edge): Edge object representing the second edge. Returns: tuple[int, int, set[int]]: The first two values repres...
python
def generator_chain(initial_data: T, *factories: Callable[[T], Iterator[T]]) -> Iterator[T]: """Chain multiple generators together by passing results from one to the next. This helper function allows to create a chain of generator where each generator is constructed by a factory that gets the data yielded ...
python
def binary_tlv_to_python(binary_string, result=None): """Recursively decode a binary string and store output in result object :param binary_string: a bytearray object of tlv data :param result: result store for recursion :return: """ result = {} if result is None else result if not binary_...
python
def get_implementation(cls, force: bool = False) -> AxesHandler: """ Fetch and initialize configured handler implementation and memoize it to avoid reinitialization. This method is re-entrant and can be called multiple times from e.g. Django application loader. """ if force or ...
java
long expireAfterCreate(@Nullable K key, @Nullable V value, Expiry<K, V> expiry, long now) { if (expiresVariable() && (key != null) && (value != null)) { long duration = expiry.expireAfterCreate(key, value, now); return isAsync ? (now + duration) : (now + Math.min(duration, MAXIMUM_EXPIRY)); } re...
java
private static DelimiterBasedFrameDecoder wordDecoder() { return new DelimiterBasedFrameDecoder(256, IntStream.of('\r', '\n', ' ', '\t', '.', ',', ';', ':', '-') .mapToObj(delim -> wrappedBuffer(new byte[] { (byte) delim })) .toArray(ByteBuf[]::new)); }
python
def _get_hashing_context(self, app: FlaskUnchained) -> CryptContext: """ Get the token hashing (and verifying) context. """ return CryptContext(schemes=app.config.SECURITY_HASHING_SCHEMES, deprecated=app.config.SECURITY_DEPRECATED_HASHING_SCHEMES)
java
private void fireEvent(RecorderEventImpl event) { eventSender.event = event; scheduler.submit(eventSender, PriorityQueueScheduler.INPUT_QUEUE); }
java
@Deprecated public String toGMTString() { // d MMM yyyy HH:mm:ss 'GMT' long t = getTime(); BaseCalendar cal = getCalendarSystem(t); BaseCalendar.Date date = (BaseCalendar.Date) cal.getCalendarDate(getTime(), (TimeZone)null); StringBuilder sb = new StringBuilder(32...
python
def collect(context=None, style=None, palette=None, **kwargs): """Returns the merged rcParams dict of the specified context, style, and palette. Parameters ---------- context: str style: str palette: str kwargs: - Returns ------- rcParams: dict The merged paramet...
java
public Object visit(QueryRootNode node, Object data) throws RepositoryException { BooleanQuery root = new BooleanQuery(); Query wrapped = root; if (node.getLocationNode() != null) { wrapped = (Query)node.getLocationNode().accept(this, root); } return wrapped; }
java
public String getString(int index) { Object tmp = mArray.get(index); return tmp == null ? null : tmp.toString(); }
python
def records(credentials, url="https://freedns.afraid.org/api/"): """ Yield the dynamic DNS records associated with this account. :param credentials: an AfraidCredentials instance :param url: the service URL """ params = {"action": "getdyndns", "sha": credentials.sha} req = requests.get( ...
python
def main(params=None): """ Main function to launch phonefy. The function is created in this way so as to let other applications make use of the full configuration capabilities of the application. The parameters received are used as parsed by this modules `getParser()`. Args: ----- ...
python
def open(self, fname, mode='rb'): """ (Re-)opens a backup file """ self.close() self.fp = open(fname, mode) self.fname = fname
python
def mouseDoubleClickEvent(self, event): """Creates and shows editor for stimulus (test) selected""" if event.button() == QtCore.Qt.LeftButton: index = self.indexAt(event.pos()) if index.isValid(): selectedStimModel = self.model().data(index, QtCore.Qt.UserRole) ...
python
def pub_ret(self, load, skip_verify=False): ''' Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. ''' if not skip_verify and any(key not in load for key in ('jid', 'id')): return {} else: ...
java
public void configure(@Observes RestAssuredConfiguration restAssuredConfiguration) { CubeDockerConfiguration cubeDockerConfiguration = cubeDockerConfigurationInstance.get(); final RequestSpecBuilder requestSpecBuilder = new RequestSpecBuilder(); configureRequestSpecBuilder(restAssuredConfigura...
python
def find_linked_dynamic_libraries(): """ This function attempts to locate the required link libraries, and returns them as a list of absolute paths. """ with TaskContext("Find the required dynamic libraries") as log: llvm = get_llvm() libs = required_link_libraries() resolved...
java
@JsonIgnore public void addAttributeMapping(String key, Object value) { attributeMappings.put(key, value); }
python
def set_client_cmd(self, *args): """ Adds given cmd(s) to ``self.output['client_cmd']`` Args: *args: Client commands. """ self.client_cmd.update(args) self.output['client_cmd'] = list(self.client_cmd)
python
def display_exc(self): """Properly prints an exception in the exception context.""" errmsg = self.get_error() if errmsg is not None: if self.path is not None: errmsg_lines = ["in " + self.path + ":"] for line in errmsg.splitlines(): ...
python
def millerRabin(n, k): """ Miller Rabin pseudo-prime test return True means likely a prime, (how sure about that, depending on k) return False means definitely a composite. Raise assertion error when n, k are not positive integers and n is not 1 """ assert n >= 1 # ensure n is bigger...