language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Nonnull public static Matcher getMatcher (@Nonnull @RegEx final String sRegEx, @Nonnull final String sValue) { ValueEnforcer.notNull (sValue, "Value"); return RegExCache.getPattern (sRegEx).matcher (sValue); }
java
public SecurityProvider getSecurityProvider() { checkState(InitializedState.INITIALIZED, InitializedState.INITIALIZED); List<SecurityProvider> securityProviders = aggregatedModule.getSecurityProviders(); return new AggregatedSecurityProvider(securityProviders); }
java
public EList<XAnnotationElementValuePair> getElementValuePairs() { if (elementValuePairs == null) { elementValuePairs = new EObjectContainmentEList<XAnnotationElementValuePair>(XAnnotationElementValuePair.class, this, XAnnotationsPackage.XANNOTATION__ELEMENT_VALUE_PAIRS); } return elementValuePairs; }
java
public PactDslJsonArray date() { String pattern = DateFormatUtils.ISO_DATE_FORMAT.getPattern(); body.put(DateFormatUtils.ISO_DATE_FORMAT.format(new Date(DATE_2000))); generators.addGenerator(Category.BODY, rootPath + appendArrayIndex(0), new DateGenerator(pattern)); matchers.addRule(rootPath + a...
python
def load(self): """ We load the data from the key itself instead of fetching from some external data store. Opposite of _get_session_key(), raises BadSignature if signature fails. $ echo '_json_formatted_' | openssl aes-256-cbc -a -k _passphrase_ -p salt=... ...
java
public boolean getParameterAsBoolean(String name, Boolean defaultValue) { return defaultValue(stringToBoolean(getParameter(name)), defaultValue); }
python
def pull(self): """Print out summary information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('%s -' % item['timestamp'], end='') # Transp...
python
def check_stops(pfeed, *, as_df=False, include_warnings=False): """ Analog of :func:`check_frequencies` for ``pfeed.stops`` """ # Use gtfstk's stop validator if pfeed.stops is not None: stop_times = pd.DataFrame(columns=['stop_id']) feed = gt.Feed(stops=pfeed.stops, stop_times=stop_t...
python
def d_grade_ipix(ipix, nside_in, nside_out, nest=False): """ Return the indices of the super-pixels which contain each of the sub-pixels (nside_in > nside_out). Parameters: ----------- ipix : index of the input subpixels nside_in : nside of the input subpix nside_out : nside of th...
java
public static channel_binding get(nitro_service service, String id) throws Exception{ channel_binding obj = new channel_binding(); obj.set_id(id); channel_binding response = (channel_binding) obj.get_resource(service); return response; }
python
def send(instructions, printer_identifier=None, backend_identifier=None, blocking=True): """ Send instruction bytes to a printer. :param bytes instructions: The instructions to be sent to the printer. :param str printer_identifier: Identifier for the printer. :param str backend_identifier: Can enfo...
python
def is_zipfile(filename): """Quickly see if a file is a ZIP file by checking the magic number. The filename argument may be a file or file-like object too. """ result = False try: if hasattr(filename, "read"): result = _check_zipfile(fp=filename) else: with o...
python
def get_kwargs(self, **kwargs): """ Creates a full URL to request based on arguments. :Parametes: - `kwargs`: All keyword arguments to build a kubernetes API endpoint """ version = kwargs.pop("version", "v1") if version == "v1": base = kwargs.pop("...
python
def detect_Massimini2004(dat_orig, s_freq, time, opts): """Slow wave detection based on Massimini et al., 2004. Parameters ---------- dat_orig : ndarray (dtype='float') vector with the data for one channel s_freq : float sampling frequency time : ndarray (dtype='float') ...
java
public static byte[] ensureCapacity(byte array[], int capacity){ if(capacity<=0 || capacity-array.length<=0) return array; int newCapacity = array.length*2; if(newCapacity-capacity< 0) newCapacity = capacity; if(newCapacity<0){ if(capacity<0) // overf...
python
def add_samples(self, samples, reverse=False): """ Concatenate the given new samples to the current audio data. This function initializes the memory if no audio data is present already. If ``reverse`` is ``True``, the new samples will be reversed and then concatenated. ...
python
def get_blocks(self, chrom, start, end): """ Get any blocks in this alignment that overlap the given location. :return: the alignment blocks that overlap a given genomic interval; potentially none, in which case the empty list is returned. """ if chrom not in self.block_trees: re...
java
public final FunctionType getBindReturnType(int argsToBind) { Builder builder = builder(registry) .withReturnType(getReturnType()) .withTemplateKeys(getTemplateTypeMap().getTemplateKeys()); if (argsToBind >= 0) { Node origParams = getParametersNode(); if (origParams !...
java
public void removeExtension(Resource rootResource, String moduleName, ManagementResourceRegistration rootRegistration) throws IllegalStateException { final ManagementResourceRegistration profileReg; if (rootRegistration.getPathAddress().size() == 0) { //domain or server extension ...
python
def setall(self, key, values): """Delete frames of the given type and add frames in 'values'. Args: key (text): key for frames to delete values (list[Frame]): frames to add """ self.delall(key) for tag in values: self[tag.HashKey] = tag
python
def do_size(self, w, h): """Apply size scaling.""" # simeon@ice ~>cat m1.pnm | pnmscale -width 50 > m2.pnm infile = self.tmpfile outfile = self.basename + '.siz' if (w is None): # print "size: no scaling" self.tmpfile = infile else: # p...
java
private final static void usage(final String msg) { System.err.println(msg); System.err.println("Usage: java Base64 -e|-d inputfile outputfile"); }
python
def _build_path(self): ''' Constructs the actual request URL with accompanying query if any. Returns: None: But does modify self.path, which contains the final request path sent to the server. ''' if not self.path: self.path = '/' ...
python
def _get_example_csv(self): """For dimension parsing """ station_key = self.json["station"][0]["key"] period = "corrected-archive" url = self.url\ .replace(".json", "/station/{}/period/{}/data.csv"\ .format(station_key, period)) r = re...
python
def handle_worker_messages(self, timeout): """ Read messages that are placed in self.incoming_mailbox, and then update the job states corresponding to each message. Args: timeout: How long to wait for an incoming message, if the mailbox is empty right now. Returns: ...
python
def request(self, host, handler, request_body, verbose): '''Send xml-rpc request using proxy''' #We get a traceback if we don't have this attribute: self.verbose = verbose url = 'http://' + host + handler request = urllib2.Request(url) request.add_data(request_body) ...
python
def _assign_IDS_to_datafiles(datafiles, parser, measurement_class=None, **kwargs): """ Assign measurement IDS to datafiles using specified parser. Parameters ---------- datafiles : iterable of str Path to datafiles. An ID will be assigned to each. Note that this function does not ch...
java
public static boolean canProduceEmptyMatches(final Pattern<?, ?> pattern) { NFAFactoryCompiler<?> compiler = new NFAFactoryCompiler<>(checkNotNull(pattern)); compiler.compileFactory(); State<?> startState = compiler.getStates().stream().filter(State::isStart).findFirst().orElseThrow( () -> new IllegalStateExce...
java
public static Properties readPropertiesFromFile(File file) throws IOException { try (FileInputStream fis = new FileInputStream(file)) { Properties prop = new Properties(); prop.load(fis); return prop; } }
python
def callLater(self, when, what, *a, **kw): """ Copied from twisted.internet.task.Clock, r20480. Fixes the bug where the wrong DelayedCall would sometimes be returned. """ dc = base.DelayedCall(self.seconds() + when, what, a, kw, self.calls.remo...
python
def discover(service, timeout=5, retries=5): ''' Discovers services on a network using the SSDP Protocol. ''' group = ('239.255.255.250', 1900) message = '\r\n'.join([ 'M-SEARCH * HTTP/1.1', 'HOST: {0}:{1}', 'MAN: "ssdp:discover"', 'ST: {st}', 'MX: 3', '', '']) so...
python
def sort(self, *args, **kwargs): ''' http://www.elasticsearch.org/guide/reference/api/search/sort.html Allows to add one or more sort on specific fields. Each sort can be reversed as well. The sort is defined on a per field level, with special field name for _score to sort by score. sta...
java
private static URI createBare(final URI link) { final URI uri; if (link.getRawQuery() == null && link.getRawFragment() == null) { uri = link; } else { final String href = link.toString(); final int idx; if (link.getRawQuery() == null) { ...
python
def get_tools(whitelist, known_plugins): """ Filter all known plugins by a whitelist specified. If the whitelist is empty, default to all plugins. """ def getpath(c): return "%s:%s" % (c.__module__, c.__class__.__name__) tools = [x for x in known_plugins if getpath(x) in whitelist] ...
python
def emit_only(self, event: str, func_names: Union[str, List[str]], *args, **kwargs) -> None: """ Specifically only emits certain subscribed events. :param event: Name of the event. :type event: str :param func_names: Function(s) to emit. :type func_names: Unio...
java
public static String toJson(Object value) { if (value instanceof String) { return '"' + (String) value + '"'; } else if (value instanceof Collection) { return "[" + toJsonCollection((Collection) value) + "]"; } else { throw new IllegalArgumentException("Unable...
java
public String convertObjectClassificationStrucFlgsToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public com.google.api.ads.adwords.axis.v201809.cm.Location getLocation() { return location; }
python
def new_digraph(self, name, data=None, **attr): """Return a new instance of type DiGraph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state """ self._init_graph(name, 'DiGr...
python
def has_child_bins(self, bin_id): """Tests if a bin has any children. arg: bin_id (osid.id.Id): the ``Id`` of a bin return: (boolean) - ``true`` if the ``bin_id`` has children, ``false`` otherwise raise: NotFound - ``bin_id`` not found raise: NullArgument - ...
java
public PackedDecimal movePointLeft(int n) { BigDecimal result = toBigDecimal().movePointLeft(n); return PackedDecimal.valueOf(result); }
java
private void abortActiveConnections(final ExecutorService assassinExecutor) { for (PoolEntry poolEntry : connectionBag.values(STATE_IN_USE)) { Connection connection = poolEntry.close(); try { connection.abort(assassinExecutor); } catch (Throwable e) { ...
python
def set_vars(self, *args, **kwargs): """ Optic does not use `get` or `ird` variables hence we should never try to change the input when we connect this task """ kwargs.update(dict(*args)) self.history.info("OpticTask intercepted set_vars with args %s" % kwargs) i...
java
@Override public <B> Identity<B> flatMap(Function<? super A, ? extends Monad<B, Identity<?>>> f) { return f.apply(runIdentity()).coerce(); }
java
public void marshall(StorageGatewayError storageGatewayError, ProtocolMarshaller protocolMarshaller) { if (storageGatewayError == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(storageGatewayError.ge...
java
private static TestConstructor[] findAll(Class<?> cls) { final Constructor<?>[] constructors = cls.getConstructors(); final Field[] fields = getBurstableFields(cls); final List<TestConstructor> filteredConstructors = new ArrayList<>(); for (Constructor<?> constructor : constructors) { if (constru...
python
def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL', prog='.', excs=(Exception,), reraise=True): """ Context manager for handling interactive prog indication This context manager streamlines presenting banners and prog indicators. To start the prog, pass ``...
python
def post_order(self): """Return a post-order iterator for the tree.""" for child in self.children: for node in child.post_order(): yield node yield self
java
private static int parseInt(String value, int defaultValue) { if (value == null) { return defaultValue; } try { return Integer.parseInt(value); } catch (Throwable ignore) {} return defaultValue; }
java
public CollectionAssert hasFlattenedSizeLessThanOrEqualTo(int size) { isNotNull(); int flattenedSize = flattenedSize(0, this.actual); if (!(flattenedSize <= size)) { failWithMessage("The flattened size <%s> is not less or equal to <%s>", flattenedSize, size); } return this; }
python
def search_by_user(self, screen_name, count=100): """Search tweets by user. Args: screen_name: screen name count: the number of tweets Returns: list: tweet list """ results = self._api.user_timeline(screen_name=screen_name, count=count) ...
python
def get_crash_signature(error_line): """Try to get a crash signature from the given error_line string.""" search_term = None match = CRASH_RE.match(error_line) if match and is_helpful_search_term(match.group(1)): search_term = match.group(1) return search_term
python
def expect(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError. ...
java
public BoxRequestsComment.AddReplyComment getAddCommentReplyRequest(String commentId, String message) { BoxRequestsComment.AddReplyComment request = new BoxRequestsComment.AddReplyComment(commentId, message, getCommentsUrl(), mSession); return request; }
java
public static final void main(final String[] args) { Injector injector = init("gl-register-alleles", args); File glstringFile = injector.getInstance(Key.get(File.class, GlstringFile.class)); File identifierFile = injector.getInstance(Key.get(File.class, IdentifierFile.class)); GlClient c...
java
public MailMessage findMessage(final String accountReservationKey, final Predicate<MailMessage> condition, final long timeoutSeconds, final long sleepMillis) { MailAccount mailAccount = checkNotNull(mailAccountManager.lookupUsedMailAccountForCurrentThread(accountReservationKey), "No mail account reserved for c...
python
def generate_certificate(self, common_name, public_key_algorithm='rsa', signature_algorithm='rsa_sha_512', key_length=2048, signing_ca=None): """ Generate an internal gateway certificate used for VPN on this engine. Certificate request should be an instance of VPNCertific...
java
protected void closePopupDefault() { if (m_previewHandlerRegistration != null) { m_previewHandlerRegistration.removeHandler(); } m_previewHandlerRegistration = null; if (checkvalue(m_textboxColorValue.getText())) { m_popup.hide(); } }
python
def get_key(self): """ Check for a key without waiting. This method is deprecated. Use :py:meth:`.get_event` instead. """ event = self.get_event() if event and isinstance(event, KeyboardEvent): return event.key_code return None
java
@Override public void restore(final List<DataSlice> dataSlices) throws SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "restore", dataSlices); restoreInternal(dataSlices, true); if (Tra...
python
def update(self, items): """ Updates the dependencies in the inverse relationship format, i.e. from an iterable or dict that is structured as `(item, dependent_items)`. Note that this implementation is only valid for 1:1 relationships, i.e. that each node has also exactly one dependent. ...
python
def detect_build(snps): """ Detect build of SNPs. Use the coordinates of common SNPs to identify the build / assembly of a genotype file that is being loaded. Notes ----- rs3094315 : plus strand in 36, 37, and 38 rs11928389 : plus strand in 36, minus strand in 37 and 38 rs2500347 : plu...
java
@Override public Set<KamEdge> getEdges(KamNode sourceNode, KamNode targetNode) { return getEdges(sourceNode, targetNode, null); }
java
protected Properties loadConfig (String configPath) throws IOException { Properties config = new Properties(); try { config.load(new FileInputStream(new File(_rdir, configPath))); } catch (Exception e) { String errmsg = "Unable to load resource manager config ...
python
def standardize_by_allele_count(score, aac, bins=None, n_bins=None, diagnostics=True): """Standardize `score` within allele frequency bins. Parameters ---------- score : array_like, float The score to be standardized, e.g., IHS or NSL. aac : array_like, int ...
java
public Area findBasicAreas() { AreaImpl rootarea = new AreaImpl(0, 0, 0, 0); setRoot(rootarea); rootarea.setAreaTree(this); rootarea.setPage(page); for (int i = 0; i < page.getRoot().getChildCount(); i++) { Box cbox = page.getRoot().getChildAt(i); ...
java
public void setNetworkSourceDomain(java.util.Collection<StringFilter> networkSourceDomain) { if (networkSourceDomain == null) { this.networkSourceDomain = null; return; } this.networkSourceDomain = new java.util.ArrayList<StringFilter>(networkSourceDomain); }
python
def read_route_spec_config(fname): """ Read, parse and sanity check the route spec config file. The config file needs to be in this format: { "<CIDR-1>" : [ "host-1-ip", "host-2-ip", "host-3-ip" ], "<CIDR-2>" : [ "host-4-ip", "host-5-ip" ], "<CIDR-3>" : [ "host-6-ip", "host-7-i...
python
def get_info(brain_or_object, endpoint=None, complete=False): """Extract the data from the catalog brain or object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param endpoint: The named URL endpoint for the root...
java
@Override public ResultSet getResultSet() throws SQLException { final ResultSet resultSet = delegate.getResultSet(); if (resultSet != null) { if (proxyResultSet == null || ((ProxyResultSet) proxyResultSet).delegate != resultSet) { proxyResultSet = ProxyFactory.getProxyResultSet(conne...
python
def _get(self, uri, options): """ Quick and dirty wrapper around the requests object to do some simple data catching :params uri: a string, the uri you want to request :params options: a dict, the list of parameters you want to use """ url = "http://%s/%s" % (sel...
python
def list_issues(context, id, sort, limit, where): """list_issues(context, id) List all job attached issues. >>> dcictl job-list-issue [OPTIONS] :param string id: ID of the job to retrieve issues from [required] :param string sort: Field to apply sort :param integer limit: Max number of rows t...
python
def warning(self, message, *args, **kwargs): """Alias to warn """ self._log(logging.WARNING, message, *args, **kwargs)
python
def from_bundle(cls, b, component, compute=None, mesh_init_phi=0.0, datasets=[], **kwargs): """ Build a star from the :class:`phoebe.frontend.bundle.Bundle` and its hierarchy. Usually it makes more sense to call :meth:`System.from_bundle` directly. :paramete...
java
private Set<Resource> extractRelationshipField(List<Resource> sourceResources, ResourceField relationshipField, QueryAdapter queryAdapter, Map<ResourceIdentifier, Resource> resourceMap, Map<ResourceIdentifier, Object> entityMap, boolean lookUp) { Set<Resource> loadedEntities = new HashSet<>(); for (Resource sour...
java
public void marshall(WorkspaceImage workspaceImage, ProtocolMarshaller protocolMarshaller) { if (workspaceImage == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(workspaceImage.getImageId(), IMAGEID_...
python
def find_and_fire_hook(event_name, instance, user_override=None): """ Look up Hooks that apply """ try: from django.contrib.auth import get_user_model User = get_user_model() except ImportError: from django.contrib.auth.models import User from rest_hooks.models import HOO...
python
def betting_market_rules_create(self, names, descriptions, account=None, **kwargs): """ Create betting market rules :param list names: Internationalized names, e.g. ``[['de', 'Foo'], ['en', 'bar']]`` :param list descriptions: Internationalized descriptions, e.g. ...
java
public String getCaption() { return caption != null && caption.toLowerCase().startsWith("label:") ? StrUtil.getLabel(caption.substring(6)) : caption; }
java
public byte read(int offset) throws IOException { if (ensureBuffer(offset, 1) > 0) { this.pos = offset + 1; return this.buffer[offset]; } throw new EOFException(); }
java
public boolean hasAnyScopeMatching(String... scopesRegex) { boolean result = OAuth2ExpressionUtils.hasAnyScopeMatching(authentication, scopesRegex); if (!result) { missingScopes.addAll(Arrays.asList(scopesRegex)); } return result; }
java
public static void shredInputStream(final INodeWriteTrx wtx, final InputStream value, final EShredderInsert child) { final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLEventReader parser; try { pa...
java
public FunctionInner update(String resourceGroupName, String jobName, String functionName, FunctionInner function) { return updateWithServiceResponseAsync(resourceGroupName, jobName, functionName, function).toBlocking().single().body(); }
python
def uncompressed_size(filename): """Return the uncompressed size for a file by executing commands Note: due to a limitation in gzip format, uncompressed files greather than 4GiB will have a wrong value. """ quoted_filename = shlex.quote(filename) # TODO: get filetype from file-magic, if avail...
java
public List<IstioResource> deployIstioResources(final Path directory) throws IOException { final List<IstioResource> istioResources = new ArrayList<>(); if (Files.isDirectory(directory)) { Files.list(directory) .filter(ResourceFilter::filterKubernetesResource) ...
python
def _euler_step(self, dt): """ Performs a single step in the euler integration, updating stateful components Parameters ---------- dt : float This is the amount to increase time by this step """ self.state = self.state + self.ddt() * dt
python
def open(self, autocommit=False): """Call-through to data_access.open.""" self.data_access.open(autocommit=autocommit) return self
python
def getProjectArea(self, projectarea_name, archived=False, returned_properties=None): """Get :class:`rtcclient.project_area.ProjectArea` object by its name :param projectarea_name: the project area name :param archived: (default is False) whether the project area ...
python
def _coerce_to_ndarray(self): """ coerce to an ndarary of object dtype """ # TODO(jreback) make this better data = self._data.astype(object) data[self._mask] = self._na_value return data
python
def get( self, instance, **kwargs ): """Return an attribute from an object using the Ref path. instance The object instance to traverse. """ target = instance for attr in self._path: target = getattr( target, attr ) return target
python
def data_to_binary(self): """ :return: bytes """ return bytes([ COMMAND_CODE, self.channels_to_byte(self.led_on), self.channels_to_byte(self.led_slow_blinking), self.channels_to_byte(self.led_fast_blinking) ])
python
def wrap(self, data, many): """Wrap response in envelope.""" if not many: return data else: data = {'contents': data} bucket = self.context.get('bucket') if bucket: data.update(BucketSchema().dump(bucket).data) return da...
java
@JsonIgnore public void setPoints(int[] points) { this.points = new ArrayList<>(); for (int i = 0; i < points.length; i++) { this.points.add(points[i]); } }
python
def _check_signatures(lines, **kwargs): """Check that the signatures are valid. There should be at least three signatures. If not, one of them should be a trusted developer/reviewer. Formatting supported being: [signature] full name <email@address> :param lines: lines (lineno, content) to verify....
python
def option_hook(self, function): """ Decorator for adding an option hook function. An option hook is a function that is called right before a run is created. It receives (and potentially modifies) the options dictionary. That is, the dictionary of commandline options used for ...
python
def filter_single_grain(self): ''' This subroutine is to filter out single grains. It is kind of useless if you have tons of data still in the list. To work on there, you have other filters (filter_desc and filter_data) available! This filter gives an index to every grain, plots...
python
def get_current_instruction(self) -> Dict: """Gets the current instruction for this GlobalState. :return: """ instructions = self.environment.code.instruction_list return instructions[self.mstate.pc]
python
def store(self, transient_file, persistent_file): '''Makes PersistentFile from TransientFile''' #for i in range(5): # persistent_file = PersistentFile(self.persistent_root, # persistent_name, self) # if not os.path.exists(persistent_file....
python
def merge_graphs(self, other_docgraph, verbose=False): """ Merges another document graph into the current one, thereby adding all the necessary nodes and edges (with attributes, layers etc.). NOTE: This will only work if both graphs have exactly the same tokenization. ""...
java
public String getWithDefault(String code, String defaultMessage, Object... arguments) { try { return getMessage(code, null, arguments); } catch (NoSuchMessageException ex) { return defaultMessage; } }