language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def clear_cache(self): """Removes all files from the songcache dir""" self.logger.debug("Clearing cache") if os.path.isdir(self.songcache_dir): for filename in os.listdir(self.songcache_dir): file_path = os.path.join(self.songcache_dir, filename) try: ...
python
def to_geodataframe(products): """Return the products from a query response as a GeoPandas GeoDataFrame with the values in their appropriate Python types. """ try: import geopandas as gpd import shapely.wkt except ImportError: raise ImportError...
python
def arithmetic_crossover(random, mom, dad, args): """Return the offspring of arithmetic crossover on the candidates. This function performs arithmetic crossover (AX), which is similar to a generalized weighted averaging of the candidate elements. The allele of each parent is weighted by the *ax_alpha*...
python
def code_to_sjis(code): u"""Convert character code(hex) to string""" if code and isinstance(code, basestring): clean_code = code.replace('>', '') if clean_code: _code_to_sjis_char = lambda c: ''.join([chr(int("%c%c"%(a, b), 16)) for a, b in izip(c[0::2], c[1::2])]) return...
python
def spline_backwards_hankel(ht, htarg, opt): r"""Check opt if deprecated 'spline' is used. Returns corrected htarg, opt. r""" # Ensure ht is all lowercase ht = ht.lower() # Only relevant for 'fht' and 'hqwe', not for 'quad' if ht in ['fht', 'qwe', 'hqwe']: # Get corresponding htar...
python
def get(self, ii, default=None, msg_if_none=None): """ Get an item from Container - a wrapper around Container.__getitem__() with defaults and custom error message. Parameters ---------- ii : int or str The index or name of the item. default : any, op...
python
def delete_mockdata_url(service_name, implementation_name, url, headers, dir_base=dirname(__file__)): """ :param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc. """ # Ht...
java
protected boolean getBoolean(I_CmsXmlContentLocation parent, String name) { I_CmsXmlContentValueLocation location = parent.getSubValue(name); if (location == null) { return false; } String value = location.getValue().getStringValue(m_cms); return Boolean.parseBoolean...
java
@Override public List<T> filter(final List<T> list) throws CouldNotPerformException { beforeFilter(); return ListFilter.super.filter(list); }
python
def run(self, data): """ Run the check method and format the result for analysis. Args: data (DSM/DMM/MDM): DSM/DMM/MDM instance to check. Returns: tuple (int, str): status constant from Checker class and messages. """ result_type = namedtuple('R...
python
def _get_subject_uri(self, guid=None): """ Returns the full path that uniquely identifies the subject endpoint. """ uri = self.uri + '/v1/subject' if guid: uri += '/' + urllib.quote_plus(guid) return uri
python
def mob_suite_targets(self, database_name='mob_suite'): """ Download MOB-suite databases :param database_name: name of current database """ logging.info('Download MOB-suite databases') # NOTE: This requires mob_suite >=1.4.9.1. Versions before that don't have the -d optio...
python
def add_igrf(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses International Geomagnetic Reference Field (IGRF) model to obtain geomagnetic field values. Uses pyglow module to run IGRF. Configured to use actual solar parameters to run ...
python
def _set_frequency_spacing(self, min_freq, max_freq): """ Frequency spacing to use, i.e. how to map the available frequency range to the discrete sheet rows. NOTE: We're calculating the spacing of a range between the highest and lowest frequencies, the actual segmentation and ...
python
def check_rez(self, strict=True): """ Checks to see if a Rez package is available in the current environment. If it is available, add it to the system path, exposing the Rez Python API :param strict: (bool) If True, raise an error if Rez is not available as a package. ...
java
@SafeVarargs public final Builder abortOn(Class<? extends Exception>... exceptions) { for (Class<? extends Exception> exception : exceptions) { nonRetriableExceptions.add(checkNotNull(exception)); } return this; }
python
def map2matrix(data_map, layout): r"""Map to Matrix This method transforms a 2D map to a 2D matrix Parameters ---------- data_map : np.ndarray Input data map, 2D array layout : tuple 2D layout of 2D images Returns ------- np.ndarray 2D matrix Raises ------...
python
def scms(self): """ Property for accessing :class:`SCMManager` instance, which is used to manage pluggable SCM materials. :rtype: yagocd.resources.scm.SCMManager """ if self._scm_manager is None: self._scm_manager = SCMManager(session=self._session) return se...
python
def report_final_result(metric): """Reports final result to tuner. metric: serializable object. """ assert _params is not None, 'nni.get_next_parameter() needs to be called before report_final_result' metric = json_tricks.dumps({ 'parameter_id': _params['parameter_id'], 'trial_job_id...
java
private void startPollingTask(Config config) { Future<?> future; PollingTask pollingTask = new PollingTask(config); future = scheduledExecutor.schedule(pollingTask, config.initialPollDelay, TimeUnit.MILLISECONDS); pollingFutureRef.getAndSet(future); }
java
public void importUser() { // create a new user id String userName = m_orgUnit.getName() + m_userName; try { if (m_throwable != null) { m_user = null; getReport().println(m_throwable); CmsMessageContainer message = Messages.get().cont...
python
def to_python(self, data): """ Convert a data to python format. """ if data is None: return u'' if isinstance(data, unicode): return data else: return unicode(data, DEFAULT_ENCODING)
python
def format_pattrs(pattrs: List['api.PrettyAttribute']) -> str: """Generates repr string given a list of pattrs.""" output = [] pattrs.sort( key=lambda x: ( _FORMATTER[x.display_group].display_index, x.display_group, x.name, ) ) for display_group, g...
java
@Override public void write(JsonWriterImpl out, byte []value) { StringBuilder sb = new StringBuilder(); Base64Util.encode(sb, value, 0, value.length); out.write(sb.toString()); }
java
public CmdLineAction onSwitch(Consumer<@NonNull String> action) { SwitchCmdLineAction switchAction = new SwitchCmdLineAction(action); this.switchActions.add(switchAction); return switchAction; }
python
def main(argv: Optional[Sequence[str]] = None, *, check: bool = True, **runargs) -> Optional[CompletedProcess]: """Run a builtin scanpy command or a scanpy-* subcommand. Uses :func:`subcommand.run` for the latter: ``~run(['scanpy', *argv], **runargs)`` """ parser = ArgumentParser(description="There are...
python
def load_installed_plugins(self): """ :rtype: list of Plugin """ result = [] plugin_dirs = [d for d in os.listdir(self.plugin_path) if os.path.isdir(os.path.join(self.plugin_path, d))] settings = constants.SETTINGS for d in plugin_dirs: if d == "__pycache__": ...
java
@Override public DeleteLoadBalancerResult deleteLoadBalancer(DeleteLoadBalancerRequest request) { request = beforeClientExecution(request); return executeDeleteLoadBalancer(request); }
java
private CloseableDataStore createDataStoreWithUrl(URI location, String apiKey, MetricRegistry metricRegistry) { // Reuse the same base classes as when using host discovery, ignoring unused fields as needed. String ignore = "ignore"; MultiThreadedServiceFactory<AuthDataStore> secureDataStoreFacto...
java
private void cacheLinkedObject(String owningObjID, String linkFieldName, DBObject linkedObject) { // Find or create map for the owning object. Map<String, Map<String, DBObject>> objMap = m_linkedObjectMap.get(owningObjID); ...
python
def create_from_taskfile(self, taskfile): """Create a new TaskFileInfo and return it for the given taskfile :param taskfile: the taskfile to represent :type taskfile: :class:`jukeboxcore.djadapter.models.TaskFile` :returns: a taskfileinfo :rtype: :class:`TaskFileInfo` :r...
python
def use_to_ned(tensor): ''' Converts a tensor in USE coordinate sytem to NED ''' return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE)
python
def match(self, path): '''Attempts to match a url to the given path. If successful, a tuple is returned. The first item is the matchd function and the second item is a dictionary containing items to be passed to the function parsed from the provided path. If the provided path do...
python
def allstats(self, approximate=False): """ Compute some basic raster statistics Parameters ---------- approximate: bool approximate statistics from overviews or a subset of all tiles? Returns ------- list of dicts a list with a di...
java
private static void sortEventsByTokenIndex(Row row) { Collections.sort(row.getEvents(), new Comparator<GridEvent>() { @Override public int compare(GridEvent o1, GridEvent o2) { if (o1 == o2) { return 0; } if (o1 == null) { return -1; } if (o2 =...
java
protected static Set<Tag> stringToTags(String data) { Set<Tag> tags = new HashSet<>(); String[] split = data.split("\r"); for (String s : split) { if (s.indexOf(Tag.KEY_VALUE_SEPARATOR) > -1) { String[] keyValue = s.split(String.valueOf(Tag.KEY_VALUE_SEPARATOR)); ...
python
def stop(self): """ Stop the monitoring thread of the plugin. The super-class will send the stop signal on the monitor-IP queue, which prompts the loop to stop. """ super(Tcp, self).stop() self.monitor_thread.join() logging.info("TCP health monitor plugi...
python
def get_github_hostname_user_repo_from_url(url): """Return hostname, user and repository to fork from. :param url: The URL to parse :return: hostname, user, repository """ parsed = parse.urlparse(url) if parsed.netloc == '': # Probably ssh host, sep, path = parsed.path.partition...
python
def find_existing_split_discordants(data): """Check for pre-calculated split reads and discordants done as part of alignment streaming. """ in_bam = dd.get_align_bam(data) sr_file = "%s-sr.bam" % os.path.splitext(in_bam)[0] disc_file = "%s-disc.bam" % os.path.splitext(in_bam)[0] if utils.file_ex...
java
@Override public void visitCode(Code obj) { stack.resetForMethodEntry(this); localLabels.clear(); super.visitCode(obj); for (SourceLineAnnotation sla : localLabels.values()) { BugInstance bug = new BugInstance(this, BugType.S508C_NO_SETLABELFOR.name(), NORMAL_PRIORITY).ad...
java
@Override public void closeAllClientTransports(DestroyHook destroyHook) { // 清空所有列表,不让再调了 Map<ProviderInfo, ClientTransport> all = clearProviders(); if (destroyHook != null) { try { destroyHook.preDestroy(); } catch (Exception e) { if (...
java
public ClassDoc overriddenClass() { com.sun.javadoc.Type t = overriddenType(); return (t != null) ? t.asClassDoc() : null; }
java
private static String unquote(String s) { while (s.startsWith("\"") || s.startsWith("'")) { s = s.substring(1); } while (s.endsWith("\"") || s.endsWith("'")) { s = s.substring(0, s.length() - 1); } return s; }
java
Document createDocument(Entity entity) { int maxIndexingDepth = entity.getEntityType().getIndexingDepth(); XContentBuilder contentBuilder; try { contentBuilder = XContentFactory.contentBuilder(JSON); XContentGenerator generator = contentBuilder.generator(); generator.writeStartObject(); ...
java
@Override public void close() { try { flush(); indexWriter.close(); } catch (MutationsRejectedException e) { throw new PrestoException(UNEXPECTED_ACCUMULO_ERROR, "Mutation was rejected by server on close", e); } }
python
def validate_method_arity(method, *needed_args): # type: (Callable, *str) -> None """ Tests if the decorated method has a sufficient number of parameters. :param method: The method to be tested :param needed_args: The name (for description only) of the needed arguments, with...
python
def update_process_died_status(self): """ Update the flag indicating whether any process exited and did not provide a result. """ # There is a result pending, the process is no longer alive, yet there is no result in the queue # This means the decoder process has not succesfully produced metric...
python
def add_transcript_file(self, transcript_file, language_type=None): """Adds a transcript file tagged as the given language. arg: transcript_file (displayText): the new transcript_file raise: InvalidArgument - ``transcript_file`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`...
python
def get(self): """ Resolves and returns the object value. Re-uses an existing previous evaluation, if applicable. :return: The result of evaluating the object. """ if not self._evaluated: self._val = self._func(*self._args, **self._kwargs) self._evaluated...
python
def radiance2tb(rad, wavelength): """ Get the Tb from the radiance using the Planck function rad: Radiance in SI units wavelength: Wavelength in SI units (meter) """ from pyspectral.blackbody import blackbody_rad2temp as rad2temp return rad2temp(wavelength, rad)
python
def _mock_request(self, **kwargs): """ A mocked out make_request call that bypasses all network calls and simply returns any mocked responses defined. """ model = kwargs.get('model') service = model.service_model.endpoint_prefix operation = model.name LOG....
python
def resample_time_series(self): """OHLC time series resampler. Resamples time series data to create Open-Hi-Lo-Close (OHLC) data, which can be useful for statistical tests, or simply for charting. Frequency abbreviations are taken from the pandas library. By default, t...
java
private static String standardizeUri(String uri) { return (uri == null) ? null : regexIDPattern.matcher( regexTaskIDPattern.matcher( regexParameterPattern.matcher( uri ).replaceFirst("") ).replaceAll("task_id:\\?") ).replaceAll("/\\?$1"); }
java
@Override public void configureMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException { // It may require to be configured from the DM => add the right marker parameters.getScopedInstance().data.put( Instance.READY_FOR_CFG_MARKER, "true" ); this.logger.fine( "Configuring machine...
python
def update_tile_extent_bounds(self): """ Updates the :attr:`tile_beg_min` and :attr:`tile_end_max` data members according to :attr:`tile_bounds_policy`. """ if self.tile_bounds_policy == NO_BOUNDS: self.tile_beg_min = self.array_start - self.halo[:, 0] se...
java
@Override public Response stopAll( String applicationName, String instancePath ) { this.logger.fine( "Request: stop instances in " + applicationName + ", from instance = " + instancePath + "." ); String lang = lang( this.manager ); Response response; try { ManagedApplication ma = this.manager.applicationMn...
java
private static long valuedt(TemporalAccessor datetime, ZoneId otherTimezoneOffset) { ZoneId alternativeTZ = Optional.ofNullable(otherTimezoneOffset).orElse(ZoneOffset.UTC); if (datetime instanceof LocalDateTime) { return ((LocalDateTime) datetime).atZone(alternativeTZ).toEpochSecond(); ...
python
def psychrometric_vapor_pressure_wet(dry_bulb_temperature, wet_bulb_temperature, pressure, psychrometer_coefficient=6.21e-4 / units.kelvin): r"""Calculate the vapor pressure with wet bulb and dry bulb temperatures. This uses a psychrometric relationship as outlined in [WMO8...
python
def to_csvf(self, fpath: str, fieldnames: Sequence[str], encoding: str='utf8', with_header: bool=False, crlf: bool=False, tsv: bool=False) -> str: """From instance to yaml file :param fpath: Csv file path :param fieldnames: Order of columns by property name :param encodi...
java
protected void setConfigurationService(ConfigurationService configService) { if (log.isLoggable(Level.FINER)) { log.finer("Set configuration service = " + configService); } configurationService = configService; if (configurationService != null) { initConfig(); ...
java
@SuppressWarnings("unchecked") private static void validateSelector(Map<String, Object> selector) throws QueryException { String topLevelOp = (String) selector.keySet().toArray()[0]; // top level op can only be $and or $or after normalisation if (topLevelOp.equals(AND) || topLevelOp.equals(...
python
def _parse_response(self, resp): """Gets the authentication information from the returned JSON.""" super(RaxIdentity, self)._parse_response(resp) user = resp["access"]["user"] defreg = user.get("RAX-AUTH:defaultRegion") if defreg: self._default_region = defreg
java
private static Map<FEATURE, Integer> tokenize(byte[] tlv) { HashMap<FEATURE, Integer> m = new HashMap<FEATURE, Integer>(); if (tlv.length % 6 != 0) { throw new IllegalArgumentException("Bad response length: " + tlv.length); } for (int i = 0; i < tlv.length; i += 6) { ...
java
public void appendFloat(float x) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(4); DataOutputStream bufout = new DataOutputStream(buffer); try { bufout.writeFloat(x); appendBytes(buffer.toByteArray(), 0, 4); } catch (IOException e) { throw...
python
def bigtable_users(self): """Access to bigtable.user role memebers For example: .. literalinclude:: snippets.py :start-after: [START bigtable_users_policy] :end-before: [END bigtable_users_policy] """ result = set() for member in self._bindings.g...
python
def file_add(self, ev, paths): """ Register for file change events. If there is a change to the file, all registered tasks will be notified with a call t.event(action). Note that as multiple tasks might register an event on the same path, each path is mapped to a dict of tasks ...
python
def init_UI(self): """ Builds User Interface for the interpretation Editor """ #set fonts FONT_WEIGHT=1 if sys.platform.startswith('win'): FONT_WEIGHT=-1 font1 = wx.Font(9+FONT_WEIGHT, wx.SWISS, wx.NORMAL, wx.NORMAL, False, self.font_type) font2 = wx.Font...
java
private TimeUnit getPollUnit() { String unit = mProperties.getProperty(CONSOLE_KEY_UNIT); if (unit == null) { unit = CONSOLE_DEFAULT_UNIT; } return TimeUnit.valueOf(unit.toUpperCase()); }
python
def add_text_memo(self, memo_text): """Set the memo for the transaction to a new :class:`TextMemo <stellar_base.memo.TextMemo>`. :param memo_text: The text for the memo to add. :type memo_text: str, bytes :return: This builder instance. """ memo_text = memo.Text...
java
@Override public CommerceDiscount removeByUUID_G(String uuid, long groupId) throws NoSuchDiscountException { CommerceDiscount commerceDiscount = findByUUID_G(uuid, groupId); return remove(commerceDiscount); }
java
public void setRegions(java.util.Collection<Region> regions) { if (regions == null) { this.regions = null; return; } this.regions = new com.amazonaws.internal.SdkInternalList<Region>(regions); }
java
public TableGenerator<Entity<T>> getOrCreateTableGenerator() { Node node = childNode.getOrCreate("table-generator"); TableGenerator<Entity<T>> tableGenerator = new TableGeneratorImpl<Entity<T>>(this, "table-generator", childNode, node); return tableGenerator; }
java
public <T extends Annotation> T getAnnotation(Class<T> type) { return member.getAnnotation(type); }
python
def metrics(self): """ Set of metrics for this model """ from vel.metrics.loss_metric import Loss from vel.metrics.accuracy import Accuracy return [Loss(), Accuracy()]
java
public void addMember(JSConsumerKey key) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "addMember", key); super.addMember(key); // superclass method does most of the work synchronized (criteriaLock) { if (allCriterias != nul...
java
protected DateFormat createFormatter(final Optional<XlsDateTimeConverter> converterAnno) { final boolean lenient = converterAnno.map(a -> a.lenient()).orElse(false); if(!converterAnno.isPresent()) { SimpleDateFormat formatter = new SimpleDateFormat(getDefaultJavaPattern()); ...
python
def config(env=DEFAULT_ENV, default=None): """Returns a dictionary with EMAIL_* settings from EMAIL_URL.""" conf = {} s = os.environ.get(env, default) if s: conf = parse(s) return conf
python
def should_store_best_checkpoint(self, epoch_idx, metrics) -> bool: """ Should we store current checkpoint as the best """ if not self.store_best: return False metric = metrics[self.metric] if better(self._current_best_metric_value, metric, self.metric_mode): se...
java
public GeneratedClassLoader createClassLoader(ClassLoader parent) { ContextFactory f = getFactory(); return f.createClassLoader(parent); }
java
void compareArrayTypes(Schema oldSchema, Schema newSchema, List<Message> messages, String name) { if(oldSchema == null || newSchema == null || oldSchema.getType() != Sc...
python
def _image_search_average(url_list, max_threads=2, **kwargs): """Takes a list of image urls and averages the images to get the average color. Designed to be implimented with many methods of url sourcing. Arguments url_list: list list of strings with the image urls to average max_threads:...
java
public InputSource resolveEntity(String publicId, String systemId) throws org.xml.sax.SAXException { return getCurrentProcessor().resolveEntity(this, publicId, systemId); }
java
public final void traverse(ZooPC pc) { try { traverseObject(pc); traverseWorkList(); } finally { workList.clear(); toBecomePersistent.clear(); //We have to clear the seenObjects here, see also issue #58. seenObjects.clear(); } }
python
def _update(self, layer=None): """ Update layers in model. """ meta = getattr(self, ModelBase._meta_attr) if not layer: layers = self.layers else: # convert non-sequence to tuple layers = _listify(layer) for layer in layers: ...
java
public String[] getQuarters(int context, int width) { String [] returnValue = null; switch (context) { case FORMAT : switch(width) { case WIDE : returnValue = quarters; break; case ABBREVIATED : ...
java
public static Role get(final String _name) throws CacheReloadException { final Cache<String, Role> cache = InfinispanCache.get().<String, Role>getCache(Role.NAMECACHE); if (!cache.containsKey(_name) && !Role.getRoleFromDB(Role.SQL_NAME, _name)) { cache.put(_name, Role.NULL, 100, ...
java
@Override public SyndCategory remove(final int index) { final DCSubject subject = subjects.remove(index); if (subject != null) { return new SyndCategoryImpl(subject); } else { return null; } }
python
def _get_auth(username, password): ''' Returns the HTTP auth header ''' if username and password: return requests.auth.HTTPBasicAuth(username, password) else: return None
java
@Override public ResourceSet<Field> read(final TwilioRestClient client) { return new ResourceSet<>(this, client, firstPage(client)); }
python
def getGyroData(self): """! Gets and returns the X, Y and Z values from the gyroscope @return a dictionary with the measurement results or Boolean. @retval {...} a dictionary data. @retval False means 'Unkown gyroscope range', that you need to check the "gyroscope range"...
java
public String dialogHead(String title) { String escapedTitle; if (title == null) { escapedTitle = ""; } else { escapedTitle = CmsEncoder.escapeHtml(title); } return "<div class=\"dialoghead\" unselectable=\"on\">" + escapedTitle + "</div>"; }
java
public static <T extends ImageGray<T>,Desc extends TupleDesc> StereoVisualOdometry<T> stereoQuadPnP( double inlierPixelTol , double epipolarPixelTol , double maxDistanceF2F, double maxAssociationError, int ransacIterations , int refineIterations , ...
python
def update(self, *args): """ Updates information about colors and their multiplicity in respective :class:`Multicolor` instance. By iterating over supplied arguments each of which should represent a color object, updates information about colors and their multiplicity in current :class:`Multicolor` ins...
python
def scheme_host_port_prefix(self, scheme='http', host='host', port=None, prefix=None): """Return URI composed of scheme, server, port, and prefix.""" uri = scheme + '://' + host if (port and not ((scheme == 'http' and port == 80) or (sche...
java
@Nullable @Override public synchronized Host getHost() { for (Integer priority : priorities) { IteratingHostProvider iteratingHostProvider = hosts.get(priority); if (iteratingHostProvider!=null) { //this could only be null if we had a synchronization problem or a bug. ...
java
public <T> T read(String input, Class<T> rootType) { JodaBeanUtils.notNull(input, "input"); return read(new StringReader(input), rootType); }
java
public static Matcher<Tree> parentNode(Matcher<? extends Tree> treeMatcher) { @SuppressWarnings("unchecked") // Safe contravariant cast Matcher<Tree> matcher = (Matcher<Tree>) treeMatcher; return new ParentNode(matcher); }
java
public static IDomainAccess createDomainAccess(IDBAccess dbAccess, String domainName) { return IDomainAccessFactory.INSTANCE.createDomainAccess(dbAccess, domainName); }
python
def background_knowledge(self): ''' Emits the background knowledge in prolog form for Aleph. ''' modeslist, getters = [self.mode(self.__target_predicate(), [('+', self.db.target_table)], head=True)], [] determinations, types = [], [] for (table, ref_table) in self.db.conn...
python
def client_to_screen(self, x, y): """ Translates window client coordinates to screen coordinates. @note: This is a simplified interface to some of the functionality of the L{win32.Point} class. @see: {win32.Point.client_to_screen} @type x: int @param x: Ho...