language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def remnant_mass_ulim(eta, ns_g_mass, bh_spin_z, ns_sequence, max_ns_g_mass, shift): """ Function that determines the maximum remnant disk mass for an NS-BH system with given symmetric mass ratio, NS mass, and BH spin parameter component along the orbital angular momentum. This is a wrapper to ...
java
@Override public void visit(SQLiteDatabaseSchema schema, SQLiteEntity entity) throws Exception { int indexCounter = 0; // generate the class name that represents the table String classTableName = getTableClassName(entity.getSimpleName()); FindIndexesVisitor indexVisitor = new FindIndexesVisitor(); List<? e...
python
def _on_report(_loop, adapter, conn_id, report): """Callback when a report is received.""" conn_string = None if conn_id is not None: conn_string = adapter._get_property(conn_id, 'connection_string') if isinstance(report, BroadcastReport): adapter.notify_event_nowait(conn_string, 'broa...
java
protected void unsetJaasLoginContextEntry(ServiceReference<com.ibm.ws.security.jaas.common.JAASLoginContextEntry> svc) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "unsetJaasLoginContextEntry", svc); } jaasLoginContextEntryName = null; }
java
protected int computeBucket(K key, K minKey) { return 1 + Math.min(msd(key, minKey), buckets.length - 2); }
java
public static String findRouteOrRequestUriTransport(Request request) { RouteHeader route = (RouteHeader) request.getHeader(RouteHeader.NAME); if(route != null) { URI uri = route.getAddress().getURI(); return findURITransport(uri, request.getContentLength().getContentLength()); } URI ruri = request.getRequ...
java
@Override public <T> T getProperty(Object description, Class<T> c) { logger.debug("Getting property of description: ", description + " and type " + c.getSimpleName()); return super.getProperty(description, c); }
python
def K(self, X, X2, target): """Return covariance between X and X2.""" if (X2 is None) or (X2 is X): target[np.diag_indices_from(target)] += self._Kdiag(X)
java
public void addOutPutStreams(List<OutputStream> outputStreams) { checkNotNull(outputStreams, "outputStreams parameter is NULL!"); for (OutputStream stream : outputStreams) { addOutPutStream(stream); } }
java
public static String buildSelectSQL(BeanDescFactory beanDescFactory, EntityOperator entityOperator, Class<?> clazz, NameConverter nameConverter){ StringBuilder sb = new StringBuilder(); BeanDesc beanDesc = beanDescFactory.getBeanDesc(clazz); sb.append("SELECT * FROM "); sb.append(M...
java
public void engineReloaded(Object objectSent) { final JsMessagingEngine engine = (JsMessagingEngine)objectSent; final String methodName = "engineReloaded"; if (TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, engine); } RELOADING_MESSAGING_ENGINES.r...
python
def product_url(self, product): """ Return a human-friendly URL for this product. :param product: str, eg. "ceph" :returns: str, URL """ url = 'product/%s' % product return posixpath.join(self.url, url)
python
def _columns_for_table(table_name): """ Return all of the columns registered for a given table. Parameters ---------- table_name : str Returns ------- columns : dict of column wrappers Keys will be column names. """ return {cname: col for (tname, cname), co...
java
public Form createAnswerForm() { if (!isFormType()) { throw new IllegalStateException("Only forms of type \"form\" could be answered"); } // Create a new Form Form form = new Form(DataForm.Type.submit); for (FormField field : getFields()) { // Add to the n...
java
synchronized void asyncReconnect(final URI reconnectUri, String authKey, final ReconnectCallback callback) { if (getState() != State.OPEN) { return; } // Update the configuration with the new credentials final ProtocolConnectionConfiguration config = ProtocolConnectionConfigu...
python
def extractSubNetwork(network_file, out_subset_network_file, outlet_ids, river_id_field, next_down_id_field, river_magnitude_field, safe_mode=True): """ ...
python
def list_users(self, envs=[], query="/users/"): """ List users in specified environments """ juicer.utils.Log.log_debug( "List Users In: %s", ", ".join(envs)) for env in envs: juicer.utils.Log.log_info("%s:" % (env)) _r = self.connectors[en...
python
def prepare_filename_decorator(fn): """ A decorator of `prepare_filename` method 1. It automatically assign `settings.ROUGHPAGES_INDEX_FILENAME` if the `normalized_url` is ''. 2. It automatically assign file extensions to the output list. """ @wraps(fn) def inner(self, normalized_url...
java
@Override public ResourceSet<AuthRegistrationsCredentialListMapping> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
java
public @NotNull <T> T get(@NotNull String name, @NotNull T defaultValue) { @Nullable @SuppressWarnings("unchecked") T value = get(name, (Class<T>)defaultValue.getClass()); if (value != null) { return value; } else { return defaultValue; } }
java
public void marshall(GetGroupQueryRequest getGroupQueryRequest, ProtocolMarshaller protocolMarshaller) { if (getGroupQueryRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getGroupQueryReques...
java
private void enable(EJSContainer ejsContainer, BeanId id, BeanMetaData bmd) throws RemoteException { this.container = ejsContainer; this.ivEntityHelper = ejsContainer.ivEntityHelper; this.ivHomeId = id; this.beanMet...
java
@Deprecated public String getWithLocale(String code, Locale locale, Object... arguments) { return get(code, locale, arguments); }
python
def vm_disk_save(name, kwargs=None, call=None): ''' Sets the disk to be saved in the given image. .. versionadded:: 2016.3.0 name The name of the VM containing the disk to save. disk_id The ID of the disk to save. image_name The name of the new image where the disk wi...
python
def is_verified_or_verifiable(analysis): """Returns whether the analysis is verifiable or has already been verified """ if IVerified.providedBy(analysis): return True if wf.isTransitionAllowed(analysis, "verify"): return True if wf.isTransitionAllowed(analysis, "multi_verify"): ...
java
public void finishParsingAndReset() { if (queryRowObservable != null) { queryRowObservable.onCompleted(); } if (queryInfoObservable != null) { queryInfoObservable.onCompleted(); } if (queryErrorObservable != null) { queryErrorObservable.onCompl...
python
def _start_new_resumable_upload(self, key, headers=None): """ Starts a new resumable upload. Raises ResumableUploadException if any errors occur. """ conn = key.bucket.connection if conn.debug >= 1: print 'Starting new resumable upload.' self.server_h...
java
public static double toRadians(double x) { if (Double.isInfinite(x) || x == 0.0) { // Matches +/- 0.0; return correct sign return x; } // These are PI/180 split into high and low order bits final double facta = 0.01745329052209854; final double factb = 1.99784475...
python
def pull_all_repos(): """Pull origin updates for all repos with origins.""" repos = ClonedRepo.objects.all() for repo in repos: if repo.origin is not None: pull_repo.delay(repo_name=repo.name)
java
@Override public synchronized InputStream getInputStream() throws IOException { if (connected == false) { // Implicitly open the connection if it has not yet been done so. connect(); } Object token = ThreadIdentityManager.runAsServer(); try { if (...
java
public static <V, E> Graph<V, E> synchronize( final MutableGraph<V, E> graph ) { MutableGraph<V, E> checkedGraph = checkNotNull( graph, "Impossible to synchronize null Graph." ); return new SynchronizedMutableGraph<V, E>( checkedGraph ); }
python
def add_packages(self, packages): """ Adds an automatic resolution of urls into tasks. :param packages: The url will determine package/module and the class. :return: self """ # type: (List[str])->TaskNamespace assert isinstance(packages, list), "Packages must be l...
java
public void flush() throws IOException { ensureOpen(); // Finish decompressing and writing pending output data if (!inf.finished()) { try { while (!inf.finished() && !inf.needsInput()) { int n; // Decompress pending output d...
java
protected static String[] sortDescending(String[] s) { Arrays.sort(s, new Comparator<String>() { @Override public int compare(String o1, String o2) { if (o1.length() < o2.length()) return 1; if (o1.length() > o2.len...
python
def loads(astring): """Decompress and deserialize string into a Python object via pickle.""" try: return pickle.loads(lzma.decompress(astring)) except lzma.LZMAError as e: raise SerializerError( 'Cannot decompress object ("{}")'.format(str(e)) ...
java
BoxCreateAuthRequest createOAuth(String code, String clientId, String clientSecret) { BoxCreateAuthRequest request = new BoxCreateAuthRequest(mSession, getTokenUrl(), code, clientId, clientSecret); return request; }
java
public static JTextArea createStandardTextArea(String text) { JTextArea result = new JTextArea(text); return configureStandardTextArea(result); }
java
public DirectoryScanner scan() throws IllegalStateException { synchronized (scanLock) { if (scanning) { while (scanning) { try { scanLock.wait(); } catch (InterruptedException e) { continue; ...
python
def main(self): """Main beautifying function.""" error = False parser = argparse.ArgumentParser( description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False) parser.add_argument('--indent-size', '-i', nargs=1, type=int, default=4, ...
python
def windowed_weir_cockerham_fst(pos, g, subpops, size=None, start=None, stop=None, step=None, windows=None, fill=np.nan, max_allele=None): """Estimate average Fst in windows over a single chromosome/contig, following the method of Weir and Cockerha...
python
def _set_auto_recovery(self, v, load=False): """ Setter method for auto_recovery, mapped from YANG variable /mac_address_table/mac_move/auto_recovery (container) If this variable is read-only (config: false) in the source YANG file, then _set_auto_recovery is considered as a private method. Backends...
python
def _get_sync(self, url): """Internal method used for GET requests Args: url (str): URL to fetch Returns: Individual URL request's response Raises: HTTPError: If HTTP request failed. """ response = self.session.get(url) if resp...
java
public static String[] getStringArray(Properties props, String key) { String[] results = MetaClass.cast(props.getProperty(key), String [].class); if (results == null) { results =new String[] {}; } return results; }
java
@Override public Integer getPropertyInteger(String key, int aDefault) { return getPropertyInteger(key, Integer.valueOf(aDefault)); }
java
public boolean evaluate(final LoggingEvent event, Map matches) { String eventTimeStampString = RESOLVER.getValue(LoggingEventFieldResolver.TIMESTAMP_FIELD, event).toString(); long eventTimeStamp = Long.parseLong( eventTimeStampString) / 1000 * 1000; boolean result = false; long first = e...
python
def rst2markdown_github(path_to_rst, path_to_md, pandoc="pandoc"): """ Converts ``rst`` to **markdown_github**, using :program:`pandoc` **Input** * ``FILE.rst`` **Output** * ``FILE.md`` """ _proc = subprocess.Popen([pandoc, "-f", "rst", "-t", "m...
java
public static vm_device[] get(nitro_service client) throws Exception { vm_device resource = new vm_device(); resource.validate("get"); return (vm_device[]) resource.get_resources(client); }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "LocationString") public JAXBElement<StringOrRefType> createLocationString(StringOrRefType value) { return new JAXBElement<StringOrRefType>(_LocationString_QNAME, StringOrRefType.class, null, value); }
python
def ParseFileLNKFile( self, parser_mediator, file_object, display_name): """Parses a Windows Shortcut (LNK) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): fi...
python
def has_wrong_break(real_seg, pred_seg): """ Parameters ---------- real_seg : list of integers The segmentation as it should be. pred_seg : list of integers The predicted segmentation. Returns ------- bool : True, if strokes of one symbol were segmented to be in ...
java
public InputSecurityGroup withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def export_assets( self, parent, output_config, read_time=None, asset_types=None, content_type=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Exports a...
python
def add_exposure(self, layer): """Add an exposure layer in the analysis. :param layer: An exposure layer to be used for the analysis. :type layer: QgsMapLayer """ self._exposures.append(layer) self._is_ready = False
python
def kendall(x, axis=0): """Kendall' tau (Rank) Correlation Matrix (for ordinal data) Parameters ---------- x : ndarray data set axis : int, optional Variables as columns is the default (axis=0). If variables are in the rows use axis=1 Returns ------- r : ndarra...
java
public String getStatValueAsString(T metric, String interval) { if (metric.isRateMetric()) { return String.valueOf(getStatValueAsDouble(metric, interval)); } return getMonitoredStatValue(metric).getValueAsString(interval); }
python
def set_wv_parameters(filter_name, grism_name): """Set wavelength calibration parameters for rectified images. Parameters ---------- filter_name : str Filter name. grism_name : str Grism name. Returns ------- wv_parameters : dictionary Python dictionary containi...
python
def mtf_image_transformer_single(): """Small single parameters.""" hparams = mtf_image_transformer_tiny() hparams.mesh_shape = "" hparams.layout = "" hparams.hidden_size = 32 hparams.filter_size = 32 hparams.batch_size = 1 hparams.num_encoder_layers = 1 hparams.num_decoder_layers = 1 hparams.num_hea...
java
static double getHipConfidenceUB(final int lgK, final long numCoupons, final double hipEstAccum, final int kappa) { if (numCoupons == 0) { return 0.0; } assert lgK >= 4; assert (kappa >= 1) && (kappa <= 3); double x = hipErrorConstant; if (lgK <= 14) { x = (hipLowSideData[(3 * (lgK - 4)) + (ka...
python
def _extract(param_names: List[str], params: Dict[str, mx.nd.NDArray], ext_params: Dict[str, np.ndarray]) -> List[str]: """ Extract specific parameters from a given base. :param param_names: Names of parameters to be extracted. :param params: Mapping from parameter names to th...
java
public void setZValues(double[][] zValues, double low, double high) { this.zValues = zValues; this.lowValue = low; this.highValue = high; }
python
def update(self, campaign_id, area, nick=None): '''xxxxx.xxxxx.campaign.area.update =================================== 更新一个推广计划的投放地域''' request = TOPRequest('xxxxx.xxxxx.campaign.area.update') request['campaign_id'] = campaign_id request['area'] = area if nick!=N...
python
def actually_mount(self, client): """Actually mount something in Vault""" a_obj = self.config.copy() if 'description' in a_obj: del a_obj['description'] try: m_fun = getattr(client, self.mount_fun) if self.description and a_obj: m_fun(...
python
def console_delete(con: tcod.console.Console) -> None: """Closes the window if `con` is the root console. libtcod objects are automatically garbage collected once they go out of scope. This function exists for backwards compatibility. .. deprecated:: 9.3 This function is not needed for no...
java
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (!(msg instanceof HttpMessage || msg instanceof HttpContent)) { ctx.write(msg, promise); return; } boolean release = true; SimpleChannelPromiseAggregator promiseA...
python
def getSensors(self): """ Returns the currently visible state of the world as a numpy array of doubles. """ Pd = array([b.p_demand for b in self.case.buses if b.type == PQ]) logger.info("State: %s" % list(Pd)) return Pd
java
protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { if (interfaces.length == 0) { throw new ClassNotFoundException("zero-length interfaces array"); } Class nonPublicClass = null; Class[] classes = new Class[interfaces.length]; for (int i = 0; i < interfa...
python
def successors(self, state, successor_func=None, **run_args): """ Don't use this function manually - it is meant to interface with exploration techniques. """ if successor_func is not None: return successor_func(state, **run_args) return self._project.factory.successo...
python
def update(self, currentTemp, targetTemp): """Calculate PID output value for given reference input and feedback.""" # in this implementation, ki includes the dt multiplier term, # and kd includes the dt divisor term. This is typical practice in # industry. self.targetTemp = targ...
java
@Override public T remove(int index) { if (displacement != null) { return super.get(index - displacement); } return super.remove(index); }
java
public static double I0(double x) { double ans; double ax = Math.abs(x); if (ax < 3.75) { double y = x / 3.75; y = y * y; ans = 1.0 + y * (3.5156229 + y * (3.0899424 + y * (1.2067492 + y * (0.2659732 + y * (0.360768e-1 + y * 0.4581...
python
def point_lm(self, context): """ Supply point source lm coordinates to montblanc """ # Shape (npsrc, 2) (ls, us), _ = context.array_extents(context.name) return np.asarray(lm_coords[ls:us], dtype=context.dtype)
java
private IMethodInfo getSingleMethodWithName( String methodName, IType typeToResolveAgainst, ITypeInfo typeInfo ) { MethodList methods; if( typeInfo instanceof IRelativeTypeInfo ) { methods = ((IRelativeTypeInfo)typeInfo).getMethods( typeToResolveAgainst ); } else { methods = typeIn...
java
public Trigger getTrigger() { try { String triggerStr = m_config.get(ATTR_TRIGGER); if (triggerStr == null) { return DEFAULT_TRIGGER; // trigger is optional, don't log an error } Trigger trigger = Trigger.valueOf(triggerStr); return tr...
python
def get_case(flags): """Parse flags for case sensitivity settings.""" if not bool(flags & CASE_FLAGS): case_sensitive = util.is_case_sensitive() elif flags & FORCECASE: case_sensitive = True else: case_sensitive = False return case_sensitive
java
private int getClassFromVotes(double votes[]){ double maxVote = -1; int maxVoteClass = -1; for (int i = 0; i < votes.length; i++){ if (votes[i] > maxVote){ maxVote = votes[i]; maxVoteClass = i; } } return maxVoteClass; }
java
public ClassDoc[] allClasses(PackageDoc pkgDoc) { return pkgDoc.isIncluded() ? pkgDoc.allClasses() : getArray(allClasses, Util.getPackageName(pkgDoc)); }
python
def get_configuration_dict(self, secret_attrs=False): """Overrides superclass method and renames some properties""" cd = super(TaxonomicAmendmentsShard, self).get_configuration_dict(secret_attrs=secret_attrs) # "rename" some keys in the dict provided cd['number of amendments'] = cd.pop('...
python
def _det_stat_freq(det_freq, data_freq_sq, data_freq, w, Nc, ulen, mplen): """ Compute detection statistic in the frequency domain :type det_freq: numpy.ndarray :param det_freq: detector in freq domain :type data_freq_sq: numpy.ndarray :param data_freq_sq: squared data in freq domain :type ...
java
public Builder addPredicates(int index, Predicate... predicates) { while (index >= this.predicates.size()) { this.predicates.add(new ArrayList<>()); } this.predicates.get(index).addAll(new ArrayList<>(Arrays.asList(predicates))); return self(); }
python
def check_version(): """Sanity check version information for corrupt virtualenv symlinks """ if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]: return sys.exit( ansi.error() + ' your virtual env points to the wrong python version. ' 'This is likely because you ...
java
@Override protected IIOMetadataNode getStandardTransparencyNode() { IIOMetadataNode transparency = new IIOMetadataNode("Transparency"); IIOMetadataNode alpha = new IIOMetadataNode("Alpha"); transparency.appendChild(alpha); if (extensions != null) { if (extensions.hasAlp...
java
public JSONObject asJSONObject() throws TwitterException { if (json == null) { try { json = new JSONObject(asString()); if (CONF.isPrettyDebugEnabled()) { logger.debug(json.toString(1)); } else { logger.debug(res...
java
public static boolean isUrl(String resourceLocation) { if (resourceLocation == null) { return false; } if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) { return true; } try { new URL(resourceLocation); return true; } c...
java
public void clearReferrerURLCookie(HttpServletRequest req, HttpServletResponse res, String cookieName) { String url = CookieHelper.getCookieValue(req.getCookies(), cookieName); if (url != null && url.length() > 0) { invalidateReferrerURLCookie(req, res, cookieName); } }
java
private boolean isInsideMappedRegion(int position, int startPoint, int endPoint) { boolean enclosed = (position < endPoint && position >= startPoint); boolean wrapAround = (startPoint > endPoint && (position >= startPo...
python
def delete_subject(self, subject): """ DELETE /subjects/(string: subject) Deletes the specified subject and its associated compatibility level if registered. It is recommended to use this API only when a topic needs to be recycled or in development environments. :param subject: s...
python
def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (tokens) ''' ret = [] for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts['token_dir']): for token in filenames: ret.append(token) ...
java
public static RoaringBitmap flip(RoaringBitmap bm, final long rangeStart, final long rangeEnd) { rangeSanityCheck(rangeStart, rangeEnd); if (rangeStart >= rangeEnd) { return bm.clone(); } RoaringBitmap answer = new RoaringBitmap(); final int hbStart = Util.toIntUnsigned(Util.highbits(rangeStar...
python
def needs_auth(self): """Whether this repository needs authentication.""" return self.username or self.password or (self.url and self.url.needs_auth)
java
public static boolean sendStaticContent( Request.In event, IOSubchannel channel, Function<String, URL> resolver, MaxAgeCalculator maxAgeCalculator) { if (sendStaticContent( event.httpRequest(), channel, resolver, maxAgeCalculator)) { event.setResult(true); ...
java
@Override public GBMModel createImpl() { GBMV3.GBMParametersV3 p = this.parameters; GBMModel.GBMParameters parms = p.createImpl(); return new GBMModel(model_id.key(), parms, new GBMModel.GBMOutput(null)); }
python
def expand_path(pathname): """ Expand the home directory in a pathname based on the effective user id. :param pathname: A pathname that may start with ``~/``, indicating the path should be interpreted as being relative to the home directory of the current (effectiv...
java
public ServiceFuture<CertificateBundle> getCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback<CertificateBundle> serviceCallback) { return getCertificateAsync(vaultBaseUrl, certificateName, "", serviceCallback); }
java
public static int fromModifierSet(Set<Modifier> set) { int modifiers = 0; if (set.contains(Modifier.PUBLIC)) { modifiers |= java.lang.reflect.Modifier.PUBLIC; } if (set.contains(Modifier.PRIVATE)) { modifiers |= java.lang.reflect.Modifier.PRIVATE; } if (set.contains(Modifier.PROTECTE...
java
@Override protected Byte decodeData(byte[] buffer) { final ByteBuffer bytebuf = allocate(size); // buffer is guaranteed non-null and proper length bytebuf.put(buffer); bytebuf.rewind(); return bytebuf.get(); }
python
def get_cf_files(path, queue): """Get rule files in a directory and put them in a queue""" for root, _, files in os.walk(os.path.abspath(path)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if os.path.isfile(fullname) a...
java
public void clear() { // TODO Should we clear `creationTime` also? In fact, it doesn't make sense // TODO Should we clear `ownedEntryCount` also? In fact, it doesn't make sense puts = 0; misses = 0; removals = 0; expiries = 0; hits = 0; evictions = 0; ...
python
def _dump(file_obj, options, out=sys.stdout): """Dump to fo with given options.""" # writer and keys are lazily loaded. We don't know the keys until we have # the first item. And we need the keys for the csv writer. total_count = 0 writer = None keys = None for row in DictReader(file_obj, op...
python
def uptodate(name, refresh=False, pkgs=None, **kwargs): ''' .. versionadded:: 2014.7.0 .. versionchanged:: 2018.3.0 Added support for the ``pkgin`` provider. Verify that the system is completely up to date. name The name has no functional value and is only used as a tracking ...
java
public SortedMultiMap<Double,String> getMostSimilar( final String word, final SemanticSpace sspace, int numberOfSimilarWords, Similarity.SimType similarityType) { Vector v = sspace.getVector(word); // if the semantic space did not have the word, then return null if (v =...