language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected void fireLayerRemovedEvent(MapLayer layer, int oldChildIndex) { fireLayerHierarchyChangedEvent(new MapLayerHierarchyEvent( this, layer, Type.REMOVE_CHILD, oldChildIndex, layer.isTemporaryLayer())); }
python
def event_at(self, when, data_tuple): """ Schedule an event to be emitted at a certain time. :param when: an absolute timestamp :param data_tuple: a 2-tuple (flavor, data) :return: an event object, useful for cancelling. """ return self._base.event_at(when, self....
python
def fetch_attr_type(self, table_name): """ :return: Dictionary of attribute names and attribute types in the table. :rtype: dict :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.TableNotFoundError: ...
python
def validate(request_schema=None, response_schema=None): """ Decorate request handler to make it automagically validate it's request and response. """ def wrapper(func): # Validating the schemas itself. # Die with exception if they aren't valid if request_schema is not None: ...
python
def differences(scansion: str, candidate: str) -> List[int]: """ Given two strings, return a list of index positions where the contents differ. :param scansion: :param candidate: :return: >>> differences("abc", "abz") [2] """ before = scansion.replace(" ", "") after = candidate...
java
public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled) { if (!bInitCalled) ((DateUpdatedHandler)listener).init(null, m_iMainFilesFieldSeq, m_bMoveCurrentTime); return super.syncClonedListener(field, listener, true); }
java
private static long[] checkStringIndex(String term) { assert (term != null); // If second element is < 0, this is a dict key long[] result = {0L, 1L}; // Empty strings are not allowed. if ("".equals(term)) { //$NON-NLS-1$ throw EvaluationException.create(MSG_KEY_CANNOT_BE_EMPTY_STRING); } if ...
python
def update(self, device_json=None, info_json=None, settings_json=None, avatar_json=None): """Update the internal device json data.""" if device_json: UTILS.update(self._device_json, device_json) if avatar_json: UTILS.update(self._avatar_json, avatar_json) ...
python
def update_attribute(attr,**kwargs): """ Add a generic attribute, which can then be used in creating a resource attribute, and put into a type. .. code-block:: python (Attr){ id = 1020 name = "Test Attr" dimension_id = 123 } """ log.debug("...
python
def stopping_function(results, args=None, rstate=None, M=None, return_vals=False): """ The default stopping function utilized by :class:`DynamicSampler`. Zipped parameters are passed to the function via :data:`args`. Assigns the run a stopping value based on a weighted average of t...
python
def _construct_key(self, rule_id: str, spacy_rule_id:int) -> int: """ Use a mapping to store the information about rule_id for each matches, create the mapping key here Args: rule_id: str spacy_rule_id:int Returns: int """ hash_key = (rule_id, sp...
python
def compact_tables(self): """ Compact report items of type "table" with same results type. Report items of type "tables" in the same subreport is merged into one. The data are ordered by 1st column. """ items_to_del = set() for i in range(len(self.report_data)): ...
python
def set_debug_listener(stream): """Break into a debugger if receives the SIGUSR1 signal""" def debugger(sig, frame): launch_debugger(frame, stream) if hasattr(signal, 'SIGUSR1'): signal.signal(signal.SIGUSR1, debugger) else: logger.warn("Cannot set SIGUSR1 signal for debug mode...
java
public Config find(String morphlineId, Config config, String nameForErrorMsg) { List<? extends Config> morphlineConfigs = config.getConfigList("morphlines"); if (morphlineConfigs.size() == 0) { throw new MorphlineCompilationException( "Morphline file must contain at least one morphline: " + name...
java
public static void asJson(Writer writer, WxOutMsg msg) { NutMap map = new NutMap(); map.put("touser", msg.getToUserName()); map.put("msgtype", msg.getMsgType()); switch (WxMsgType.valueOf(msg.getMsgType())) { case text: map.put("text", new NutMap().setv("content", msg...
python
def _astype(self, dtype, **kwargs): """ these automatically copy, so copy=True has no effect raise on an except if raise == True """ dtype = pandas_dtype(dtype) # if we are passed a datetime64[ns, tz] if is_datetime64tz_dtype(dtype): values = self.val...
python
def CMS(data, format="PEM"): """ Factory function to create CMS objects from received messages. Parses CMS data and returns either SignedData or EnvelopedData object. format argument can be either "PEM" or "DER". It determines object type from the contents of received CMS structure. ""...
java
public static double Inverse(double y0) { if (y0 <= 0.0) { if (y0 == 0) return Double.NEGATIVE_INFINITY; try { throw new IllegalArgumentException("y0"); } catch (Exception e) { e.printStackTrace(); } } if (y0 >= 1.0)...
python
def do_GET(self): # pylint: disable=g-bad-name """Serve the server pem with GET requests.""" self._IncrementActiveCount() try: if self.path.startswith("/server.pem"): stats_collector_instance.Get().IncrementCounter( "frontend_http_requests", fields=["cert", "http"]) self.S...
java
public static String rowIndexListToString(final List<Integer> row) { if (row == null || row.isEmpty()) { return null; } StringBuffer index = new StringBuffer(); boolean addDelimiter = false; for (Integer lvl : row) { if (addDelimiter) { index.append(INDEX_DELIMITER); } index.append(lvl); ...
python
def _ensure_url_string(url): """Convert `url` to a string URL if it isn't one already.""" if isinstance(url, str): return url elif isinstance(url, (ParseResult, SplitResult)): return url.geturl() else: raise TypeError( "Could not convert %r to a string URL." % (url,))
java
@SuppressFBWarnings(value = "IM_BAD_CHECK_FOR_ODD", justification = "It's obvious that groupSize is not negative.") public CPSubsystemConfig setGroupSize(int groupSize) { checkTrue(groupSize == 0 || (groupSize >= MIN_GROUP_SIZE && groupSize <= MAX_GROUP_SIZE && (groupSize % 2 == 1)), "Group ...
python
def _convert_fastq(srafn, outdir, single=False): "convert sra to fastq" cmd = "fastq-dump --split-files --gzip {srafn}" cmd = "%s %s" % (utils.local_path_export(), cmd) sraid = os.path.basename(utils.splitext_plus(srafn)[0]) if not srafn: return None if not single: out_file = [os...
java
public void setConfigFile(final String config) { if (config == null) { throw (new IllegalArgumentException( "Configuration file parameter is null")); } File file = new File(config); if (file.exists()) { if (file.isDirectory()) { ...
python
def _spawn_fork_workers(self): """ 通过线程启动多个worker """ thread = Thread(target=self._fork_workers, args=()) thread.daemon = True thread.start()
java
protected void addDefaultPreferencesRules(Digester digester) { // creation of the default user settings digester.addObjectCreate("*/" + N_WORKPLACE + "/" + N_DEFAULTPREFERENCES, CmsDefaultUserSettings.class); digester.addSetNext("*/" + N_WORKPLACE + "/" + N_DEFAULTPREFERENCES, "setDefaultUserSe...
java
public static ExpectedCondition<Boolean> clickCanBeDoneWithoutAlertOnElementLocated(final By locator) { return new ExpectedCondition<Boolean>() { /** * {@inheritDoc} */ @Override public Boolean apply(@Nullable WebDriver driver) { try ...
python
def mask_raster(in_raster, mask, out_raster): """ Mask raster data. Args: in_raster: list or one raster mask: Mask raster data out_raster: list or one raster """ if is_string(in_raster) and is_string(out_raster): in_raster = [str(i...
python
def _joint_calling(items): """Determine if this call feeds downstream into joint calls. """ jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), items[0]) if jointcaller: assert len(items) == 1, "Can only do joint calling preparation with GATK with single samples" assert tz.ge...
java
public ZealotKhala andNotLikePattern(String field, String pattern) { return this.doLikePattern(ZealotConst.AND_PREFIX, field, pattern, true, false); }
python
def actuator_on(self, service_location_id, actuator_id, duration=None): """ Turn actuator on Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator ...
java
public boolean[] getSubjectUniqueID() { if (info == null) return null; try { UniqueIdentity id = (UniqueIdentity)info.get( X509CertInfo.SUBJECT_ID); if (id == null) return null; else return (...
python
def _record_values_for_fit_summary_and_statsmodels(self): """ Store the various estimation results that are used to describe how well the estimated model fits the given dataset, and record the values that are needed for the statsmodels estimation results table. All values are sto...
python
def preprocessor(accepts, exports, flag=None): """Decorator to add a new preprocessor""" def decorator(f): preprocessors.append((accepts, exports, flag, f)) return f return decorator
java
@Override public DeleteDomainResult deleteDomain(DeleteDomainRequest request) { request = beforeClientExecution(request); return executeDeleteDomain(request); }
python
def schema(self): """ Construct the schema definition for this index """ schema_data = super(GlobalIndex, self).schema(self.hash_key) schema_data['ProvisionedThroughput'] = self.throughput.schema() return schema_data
python
def list_queues(self, prefix=None, num_results=None, include_metadata=False, marker=None, timeout=None): ''' Returns a generator to list the queues. The generator will lazily follow the continuation tokens returned by the service and stop when all queues have been r...
python
def export(name, path, replace=False): ''' Export a zones configuration name : string name of the zone path : string path of file to export too. replace : boolean replace the file if it exists ''' ret = {'name': name, 'changes': {}, 'result': N...
java
@XmlElementDecl(namespace = "http://www.drugbank.ca", name = "allele", scope = SnpEffectType.class) public JAXBElement<String> createSnpEffectTypeAllele(String value) { return new JAXBElement<String>(_SnpAdverseDrugReactionTypeAllele_QNAME, String.class, SnpEffectType.class, value); }
python
def pagination_data(self, max_number_of_links=7): '''Returns a generator of tuples (string, page_number, clickable), where `string` is the text of the html link, `page_number` is the number of the page the link points to, and `clickable` is a boolean indicating whether the link is clicka...
java
public static ByteBuf wrappedBuffer(ByteBuf buffer) { if (buffer.isReadable()) { return buffer.slice(); } else { buffer.release(); return EMPTY_BUFFER; } }
java
public PageManager getPageManager() { if (pageManager != null) { return pageManager; } pageManager = (PageManager) ContainerManager.getComponent("pageManager"); return pageManager; }
python
def create_redditor(self, user_name, password, email=''): """Register a new user. :returns: The json response from the server. """ data = {'email': email, 'passwd': password, 'passwd2': password, 'user': user_name} return self.req...
python
def set(clear=False, **defaults): """ Set default parameters for :class:`lsqfit.nonlinear_fit`. Use to set default values for parameters: ``svdcut``, ``debug``, ``tol``, ``maxit``, and ``fitter``. Can also set parameters specific to the fitter specified by the ``fitter`` argumen...
python
def calculateDatasetItems(self, scene, datasets): """ Syncs the scene together with the given datasets to make sure we have the proper number of items, by removing non-existant datasets and adding new ones. :param scene | <XChartScene> ...
java
@Override public void configurationEvent(ConfigurationEvent event) { if (event.getType() == ConfigurationEvent.CM_UPDATED && pids.contains(event.getPid())) { populateDestinationPermissions(); runtimeSecurityService.modifyMessagingServices(this); } }
python
def create_table_from(self, name, src): """ Create a new table with same schema as the source. If the named table already exists, nothing happens. Arguments: name (str): The name of the table to create. src (str): The name of the source table to duplicate. ...
python
def create_new_document(self, base_name='New Document', extension='.txt', preferred_eol=0, autodetect_eol=True, **kwargs): """ Creates a new document. The document name will be ``base_name + count + extension`` :param base_name: B...
java
public <T> ReactiveSeq<T> getSummariesStream(ListObjectsRequest req, Function<S3ObjectSummary, T> processor) { return ReactiveSeq.fromIterator(new S3ObjectSummaryIterator( client, req)) .map(processor); }
python
def clause_texts(self): """The texts of ``clauses`` multilayer elements. Non-consequent spans are concatenated with space character by default. Use :py:meth:`~estnltk.text.Text.texts` method to supply custom separators. """ if not self.is_tagged(CLAUSES): self.tag_cla...
python
def viewport(self) -> Tuple[int, int, int, int]: ''' tuple: The viewport of the window. ''' return self.wnd.viewport
python
def update_meta_info(self): """Extract metadata from myself""" result = super(BaseStructuredCalibration, self).update_meta_info() result['instrument'] = self.instrument result['uuid'] = self.uuid result['tags'] = self.tags result['type'] = self.name() minfo = se...
java
public ReceiveMessageAction setValidators(List<MessageValidator<? extends ValidationContext>> validators) { this.validators.clear(); this.validators.addAll(validators); return this; }
java
@Override public final void run(final IAction action) { if (targetPart == null) { return; } try { if (!selection.isEmpty() && (selection instanceof IStructuredSelection)) { IStructuredSelection ssel = (IStructuredSelection) selection; O...
python
def __search_str(self, obj, item, parent): """Compare strings""" obj_text = obj if self.case_sensitive else obj.lower() if (self.match_string and item == obj_text) or (not self.match_string and item in obj_text): self.__report(report_key='matched_values', key=parent, value=obj)
python
def past_participle(self): """ Strong verbs I >>> verb = StrongOldNorseVerb() >>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"]) >>> verb.past_participle() [['litinn', 'litinn', 'litnum', 'litins', 'litnir', 'litna', 'litnum', 'litinna'], ['li...
python
def wait_socket(_socket, session, timeout=1): """Helper function for testing non-blocking mode. This function blocks the calling thread for <timeout> seconds - to be used only for testing purposes. Also available at `ssh2.utils.wait_socket` """ directions = session.block_directions() if di...
java
public Observable<ServiceResponse<TopicInner>> updateWithServiceResponseAsync(String resourceGroupName, String topicName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (...
java
public Topics getList(String groupId, int perPage, int page, boolean sign) throws JinxException { JinxUtils.validateParams(groupId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.groups.discuss.topics.getList"); params.put("group_id", groupId); if (perPage > 0) { p...
python
def get_reg_index_value_pairs(self, regIndexList): """ Returns a string like NN:MMMMMMMM;NN:MMMMMMMM;... for the T response string. NN is the index of the register to follow MMMMMMMM is the value of the register. """ str = b'' regList = self._context.read...
java
private String getText(@NotNull final ResourceBundle bundle, @NotNull final Annotation annotation, @NotNull final String defaultKey) { Contract.requireArgNotNull("bundle", bundle); Contract.requireArgNotNull("annotation", annotation); Contract.requireArgNotNull("defaultKey", defaultKey); ...
java
static Proxy parseProxySettings(String spec) { try { if (spec == null || spec.length() == 0) { return null; } return new Proxy(spec); } catch (URISyntaxException e) { return null; } }
python
def generate_keywords(additional_keywords=None): """Generates gettext keywords list :arg additional_keywords: dict of keyword -> value :returns: dict of keyword -> values for Babel extraction Here's what Babel has for DEFAULT_KEYWORDS:: DEFAULT_KEYWORDS = { '_': None, ...
python
def save(self, model, joining=None, touch=True): """ Save a new model and attach it to the parent model. :type model: eloquent.Model :type joining: dict :type touch: bool :rtype: eloquent.Model """ if joining is None: joining = {} mo...
java
public static String format(final String pattern, final Object... args) { return messageFormat(pattern).render(args); }
java
public void fireRelationReadEvent(Relation relation) { if (m_projectListeners != null) { for (ProjectListener listener : m_projectListeners) { listener.relationRead(relation); } } }
java
private static Optional<Expression> tryResolveMissingExpression(PlanBuilder subPlan, Expression expression) { Expression rewritten = subPlan.rewrite(expression); if (rewritten != expression) { return Optional.of(rewritten); } return Optional.empty(); }
java
public final Set<String> getPropertyNames() { Set<String> props = new TreeSet<>(); collectPropertyNames(props); return props; }
python
def get_camera_imageseries(self, number_of_imageseries=10, offset=0): """ Get smartcam image series Args: number_of_imageseries (int): number of image series to get offset (int): skip offset amount of image series """ response = None try: resp...
java
public List<Probe> sendProbe(Probe probe) throws ProbeSenderException { List<Probe> actualProbesToSend; try { actualProbesToSend = splitProbe(probe); } catch (MalformedURLException | JAXBException | UnsupportedPayloadType e) { throw new ProbeSenderException("Issue splitting the probe.", e); ...
python
def process_tessellate(elem, update_delta, delta, **kwargs): """ Tessellates surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param update_delta: flag to control evaluation delta updates :type update_delta: bool :param ...
java
@Weight(Weight.Unit.NORMAL) public static <T extends Closeable> T defer(@Nullable final T closeable) { if (closeable != null) { defer(new Deferred() { private static final long serialVersionUID = 2265124256013043847L; @Override public void executeDeferred() throws Exception { ...
python
def show_tree(self): """Populate the tree with profiler data and display it.""" self.initialize_view() # Clear before re-populating self.setItemsExpandable(True) self.setSortingEnabled(False) rootkey = self.find_root() # This root contains profiler overhead if root...
java
public SearchResult<WorkflowSummary> search( @Nullable Integer start, @Nullable Integer size, @Nullable String sort, @Nullable String freeText, @Nonnull String query) { Preconditions.checkNotNull(query, "query cannot be null"); SearchPb.Request.Builder request = SearchPb.Request...
java
public String[] getSynonyms(String string) { if (SYNONYM_MAP != null) { return SYNONYM_MAP.getSynonyms(string.toLowerCase()); } else { return new String[0]; } }
python
def merge_user_into_another_user_destination_user_id(self, id, destination_user_id): """ Merge user into another user. Merge a user into another user. To merge users, the caller must have permissions to manage both users. This should be considered irreversible. This will d...
python
def require(self, entity_type, attribute_name=None): """ The intent parser should require an entity of the provided type. Args: entity_type(str): an entity type attribute_name(str): the name of the attribute on the parsed intent. Defaults to match entity_type. R...
java
public ResourceBundle getBundle(final String bundleName) { LOG.info("Getting bundle: " + bundleName); return bundles.get(bundleName); }
java
@Override public synchronized void start(StartContext context) throws StartException { final RemoteDomainConnection connection; final ManagementChannelHandler handler; try { ScheduledExecutorService scheduledExecutorService = scheduledExecutorInjector.getValue(); thi...
python
def output_schema( self, what="", file_path=None, append=False, sort_keys=False ): """*Outputs JSON Schema to terminal or a file.* By default, the schema is output for the last request and response. The output can be limited further by: - The property of the last instance,...
java
private void checkTimeouts() { long waitTime = getMs(PropertyKey.MASTER_WORKER_CONNECT_WAIT_TIME); long retryInterval = getMs(PropertyKey.USER_RPC_RETRY_MAX_SLEEP_MS); if (waitTime < retryInterval) { LOG.warn("{}={}ms is smaller than {}={}ms. Workers might not have enough time to register. " ...
python
def _import_from_importer(network, importer, basename, skip_time=False): """ Import network data from importer. Parameters ---------- skip_time : bool Skip importing time """ attrs = importer.get_attributes() current_pypsa_version = [int(s) for s in network.pypsa_version.split...
java
public void close() { for (Entry<String, OResourcePool<String, DB>> pool : pools.entrySet()) { for (DB db : pool.getValue().getResources()) { pool.getValue().close(); try { OLogManager.instance().debug(this, "Closing pooled database '%s'...", db.getName()); ((ODatabas...
python
def _get_encrypted_credentials(self, context): """ [MS-CSSP] 3.1.5 Processing Events and Sequencing Rules - Step 5 https://msdn.microsoft.com/en-us/library/cc226791.aspx After the client has verified the server's authenticity, it encrypts the user's credentials with the authenti...
python
def make_table_parser() -> cmd2.argparse_completer.ACArgumentParser: """Create a unique instance of an argparse Argument parser for processing table arguments. NOTE: The two cmd2 argparse decorators require that each parser be unique, even if they are essentially a deep copy of each other. For cases like ...
python
def _set_trusted_option_if_needed(repostr, trusted): ''' Set trusted option to repo if needed ''' if trusted is True: repostr += ' [trusted=yes]' elif trusted is False: repostr += ' [trusted=no]' return repostr
java
public static ItemIdValue makeItemIdValue(String id, String siteIri) { return factory.getItemIdValue(id, siteIri); }
java
private void initIndex() throws Exception { // 0. Add the tasklog template GetIndexTemplatesResponse result = elasticSearchClient.admin() .indices() .prepareGetTemplates("tasklog_template") .execute() .actionGet(); if (result.getIndexTemplates()....
java
public static String combineToPath(List<String> pParts) { if (pParts != null && pParts.size() > 0) { StringBuilder buf = new StringBuilder(); Iterator<String> it = pParts.iterator(); while (it.hasNext()) { String part = it.next(); buf.append(es...
python
def ARPLimitExceeded_originator_switch_info_switchIdentifier(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ARPLimitExceeded = ET.SubElement(config, "ARPLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ...
python
def send_api_request(self, method, url, params={}, valid_parameters=[], needs_api_key=False): """ Sends the url with parameters to the requested url, validating them to make sure that they are what we expect to have passed to us :param method: a string, the request method you want to ma...
python
def for_json(self): """Return date ISO8601 string formats for datetime, date, and time values, milliseconds for intervals""" value = super(DatetimeField, self).for_json() # Order of instance checks matters for proper inheritance checks if isinstance(value, pendulum.Interval): ...
java
public static StreamShardHandle convertToStreamShardHandle(StreamShardMetadata streamShardMetadata) { Shard shard = new Shard(); shard.withShardId(streamShardMetadata.getShardId()); shard.withParentShardId(streamShardMetadata.getParentShardId()); shard.withAdjacentParentShardId(streamShardMetadata.getAdjacentPa...
java
public static final boolean collinear(final Point2D p1, final Point2D p2, final Point2D p3) { return Geometry.collinear(p1, p2, p3); }
java
public void drawOval(float x1, float y1, float width, float height, int segments) { drawArc(x1, y1, width, height, segments, 0, 360); }
java
public SparseDoubleVector generateContext(Queue<String> prevWords, Queue<String> nextWords) { SparseDoubleVector meaning = new CompactSparseVector(indexVectorLength); addContextTerms(meaning, prevWords, -1 * prevWords.size()); addContextTerms(meaning...
python
async def _raise_for_status(response): """Raise an appropriate error for a given response. Arguments: response (:py:class:`aiohttp.ClientResponse`): The API response. Raises: :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate error for the response's status. This fu...
python
def match(self, abstract_consonant: AbstractConsonant) -> bool: """ A real consonant matches an abstract consonant if and only if the required features of the abstract consonant are also features of the real consonant. :param abstract_consonant: AbstractConsonant :return: bool ...
python
def apply_effect_expression_filters( effects, gene_expression_dict, gene_expression_threshold, transcript_expression_dict, transcript_expression_threshold): """ Filter collection of varcode effects by given gene and transcript expression thresholds. Parameters ...
java
public Stream<Entry<MatchedName, MetricValue>> filter(Context t) { return t.getTSData().getCurrentCollection().get(this::match, x -> true).stream() .flatMap(this::filterMetricsInTsv); }