language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def StatFS(self, path=None): """Call os.statvfs for a given list of rdf_paths. OS X and Linux only. Note that a statvfs call for a network filesystem (e.g. NFS) that is unavailable, e.g. due to no network, will result in the call blocking. Args: path: a Unicode string containing the path or...
python
def to_pandas(self): """Return a Pandas dataframe of the minimum spanning tree. Each row is an edge in the tree; the columns are `from`, `to`, and `distance` giving the two vertices of the edge which are indices into the dataset, and the distance between those datapoints. ...
java
@Override public void acquire(HLock lock) { acquire(lock, Long.MAX_VALUE - System.currentTimeMillis() - 10000); }
python
def unreduce_array(array, shape, axis, keepdims): """Reverse summing over a dimension, NumPy implementation. Args: array: The array that was reduced. shape: The original shape of the array before reduction. axis: The axis or axes that were summed. keepdims: Whether these axes were kept as singleton...
java
public static ByteBuffer toSerializedEvent(AbstractEvent event) throws IOException { final Class<?> eventClass = event.getClass(); if (eventClass == EndOfPartitionEvent.class) { return ByteBuffer.wrap(new byte[] { 0, 0, 0, END_OF_PARTITION_EVENT }); } else if (eventClass == CheckpointBarrier.class) { retu...
java
public static <R> Function<Object,Set<R>> setOf(final Type<R> resultType, final String methodName, final Object... optionalParameters) { return methodForSetOf(resultType, methodName, optionalParameters); }
python
def log_spewer(self, gconfig, fd): '''Child process to manage logging. This reads pairs of lines from `fd`, which are alternating priority (Python integer) and message (unformatted string). ''' setproctitle('rejester fork_worker log task') yakonfig.set_default_config([y...
java
private void appendExcludesListToExcludesFile(Plugin plugin, List<String> nonAffectedClasses) throws MojoExecutionException { String excludesFileName = extractParamValue(plugin, EXCLUDES_FILE_PARAM_NAME); File excludesFileFile = new File(excludesFileName); // First restore file in case it has b...
java
protected void transcode(File file, Transcoder transcoder) throws IOException, TranscoderException { // Disable validation, performance is more important here (thumbnails!) transcoder.addTranscodingHint(XMLAbstractTranscoder.KEY_XML_PARSER_VALIDATING, Boolean.FALSE); SVGDocument doc = cloneDocument(); T...
java
public boolean addFriendByName(String name, FriendGroup friendGroup) { if (getRiotApi() != null) { try { final StringBuilder buf = new StringBuilder(); buf.append("sum"); buf.append(getRiotApi().getSummonerId(name)); buf.append("@pvp.net"); addFriendById(buf.toString(), name, friendGroup); ...
python
def cli(env, identifier, count): """Get details for a ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') env.fout(ticket.get_ticket_results(mgr, ticket_id, update_count=count))
python
def epcr_parse(self): """ Parse the ePCR outputs """ logging.info('Parsing ePCR outputs') for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': # Create a set to store all the unique results toxin_set = set() ...
java
public static String collectReplacements(String orig, @ClosureParams(value=SimpleType.class, options="char") Closure<String> transform) { if (orig == null) return orig; StringBuilder sb = null; // lazy create for edge-case efficiency for (int i = 0, len = orig.length(); i < len; i++) { ...
python
def trigger(self, event, *args): """Trigger event by name.""" for handler in self._event_handlers[event]: handler(*args)
java
public static boolean overlaps(TermOccurrence o1, TermOccurrence o2) { return o1.getSourceDocument().equals(o2.getSourceDocument()) && o1.getBegin() < o2.getEnd() && o2.getBegin()< o1.getEnd(); }
java
public void init(HttpInboundConnection conn, RequestMessage req) { this.request = req; this.response = conn.getResponse(); this.connection = conn; this.outStream = new ResponseBody(this.response.getBody()); this.locale = Locale.getDefault(); }
java
protected void writeResultEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { sb.append("Success:"); sb.append(execInfo.isSuccess() ? "True" : "False"); sb.append(", "); }
java
public void trace( Object messagePattern, Object arg ) { if( m_delegate.isTraceEnabled() && messagePattern != null ) { String msgStr = (String) messagePattern; msgStr = MessageFormatter.format( msgStr, arg ); m_delegate.trace( msgStr, null ); } }
python
def chdir(path): """Change the working directory to `path` for the duration of this context manager. :param str path: The path to change to """ cur_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(cur_cwd)
java
private int initializePatternPCETable() { long[] pcetable = new long[INITIAL_ARRAY_SIZE_]; int pcetablesize = pcetable.length; int patternlength = pattern_.text_.length(); CollationElementIterator coleiter = utilIter_; if (coleiter == null) { coleiter = new Collation...
java
public Map<String, String> getListsDirectory() throws RottenTomatoesException { properties.clear(); properties.put(ApiBuilder.PROPERTY_URL, URL_LISTS_DIRECTORY); WrapperLists wrapper = response.getResponse(WrapperLists.class, properties); if (wrapper != null && wrapper.getLinks() != nul...
python
def describeTopics(self, maxTermsPerTopic=None): """Return the topics described by weighted terms. WARNING: If vocabSize and k are large, this can return a large object! :param maxTermsPerTopic: Maximum number of terms to collect for each topic. (default: vocabulary size) ...
python
def last(self, n=1): """ Get the last element of an array. Passing **n** will return the last N values in the array. The **guard** check allows it to work with `_.map`. """ res = self.obj[-n:] if len(res) is 1: res = res[0] return self._wrap(re...
java
@Override protected void setProfile(List<Step> sx, List<Step> sy) { profile = pair = new SimpleProfilePair<S, C>(getQuery(), getTarget(), sx, sy); }
python
def _get_boll(cls, df): """ Get Bollinger bands. boll_ub means the upper band of the Bollinger bands boll_lb means the lower band of the Bollinger bands boll_ub = MA + Kσ boll_lb = MA − Kσ M = BOLL_PERIOD K = BOLL_STD_TIMES :param df: data ...
python
def paths_from_version(version): """Get the EnergyPlus install directory and executable path. Parameters ---------- version : str, optional EnergyPlus version in the format "X-X-X", e.g. "8-7-0". Returns ------- eplus_exe : str Full path to the EnergyPlus executable. ep...
python
def item_id(response): """ Parse the item ids, will be available as ``item_0_name``, ``item_1_name``, ``item_2_name`` and so on """ dict_keys = ['item_0', 'item_1', 'item_2', 'item_3', 'item_4', 'item_5'] new_keys = ['item_0_name', 'item_1_name', 'item_2_name', '...
java
public final SelectableChannel configureBlocking(boolean block) throws IOException { synchronized (regLock) { if (!isOpen()) throw new ClosedChannelException(); if (blocking == block) return this; if (block && haveValidKeys()) ...
java
public static void glBindTexture(int target, int textureID) { checkContextCompatibility(); nglBindTexture(target, WebGLObjectMap.get().toTexture(textureID)); }
java
public void rebuildAllIndexes() throws Exception { I_CmsReport report = new CmsShellReport(m_cms.getRequestContext().getLocale()); OpenCms.getSearchManager().rebuildAllIndexes(report); }
java
public String formatAsString(final ObjectCell<?> cell, final Locale locale) { return format(cell, locale).getText(); }
java
public Observable<ServiceResponse<Page<IdentifierInner>>> listSiteIdentifiersAssignedToHostNameNextWithServiceResponseAsync(final String nextPageLink) { return listSiteIdentifiersAssignedToHostNameNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<IdentifierInner>>, Observab...
java
protected void closeInputs() throws IOException{ while(true){ if(in instanceof Transport) return; in.close(); in = in.detachInput(); } }
java
public static <S extends Iterator<? extends T>, T> Iterator<T> iteratorOverIterators(Iterable<S> iteratorsIterable) { Objects.requireNonNull(iteratorsIterable, "The iteratorsIterable is null"); return new CombiningIterator<T>(iteratorsIterable.iterator()); }
python
def parse_url(request, url): """Parse url URL parameter.""" try: validate = URLValidator() validate(url) except ValidationError: if url.startswith('/'): host = request.get_host() scheme = 'https' if request.is_secure() else 'http' url = '{scheme}:/...
python
def native(self): """ The native Python datatype representation of this value :return: An integer or None """ if self.contents is None: return None if self._native is None: self._native = self.__int__() if self._map is no...
java
@Override public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
java
@Override public ByteBuffer serialize(Character object) { ByteBuffer byteBuffer = ByteBuffer.allocate(2); byteBuffer.putChar(object).flip(); return byteBuffer; }
python
def add_target_with_env(self, environment, name=None): """Add an SCons target to this nest, with an SCons Environment The function decorated will be immediately called with three arguments: * ``environment``: A clone of the SCons environment, with variables populated for all values i...
python
def handle_m2m_field(self, obj, field): """ while easymode follows inverse relations for foreign keys, for manytomayfields it follows the forward relation. While easymode excludes all relations to "self" you could still create a loop if you add one extra level of indirec...
python
def to_string(address, dns_format=False): """ Convert address to string :param address: WIPV4Address to convert :param dns_format: whether to use arpa-format or not :return: """ if isinstance(address, WIPV4Address) is False: raise TypeError('Invalid address type') address = [str(int(x)) for x in addr...
python
def add(self, num): """ Adds num to the current value """ try: val = self.value() + num except: val = num self.set(min(self.fmax, max(self.fmin, val)))
java
public boolean previous() { // see if it is back to the start already if( state == 0 ) return false; else state = 1; for( int i = c; i >= 0; i-- ) { bins[i]--; if( i == 0 ) { if( bins[0] < 0 ) { state = 0; // put it back into its first combination for( int j = 0; j < bins.lengt...
java
private String compressImage(String imagePath, File destDirectory) { Bitmap scaledBitmap = null; BitmapFactory.Options options = new BitmapFactory.Options(); // by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If // you try th...
python
def _generate_object(cls, soup, game, players): """ get box_score data :param soup: Beautifulsoup object :param game: MLBAM Game object :param players: MLBAM Players object :return: pitchpx.box_score.box_score.BoxScore object """ def get_batter(soup, team...
python
def write_context_error_report(self,file,context_type): """Write a context error report relative to the target or query into the specified filename :param file: The name of a file to write the report to :param context_type: They type of profile, target or query based :type file: string :type contex...
java
public LambdaDslObject eachKeyLike(String exampleKey, PactDslJsonRootValue value) { object.eachKeyLike(exampleKey, value); return this; }
python
def transformWith(self, func, other, keepSerializer=False): """ Return a new DStream in which each RDD is generated by applying a function on each RDD of this DStream and 'other' DStream. `func` can have two arguments of (`rdd_a`, `rdd_b`) or have three arguments of (`time`, `rd...
python
def rnormal(mu, tau, size=None): """ Random normal variates. """ return np.random.normal(mu, 1. / np.sqrt(tau), size)
java
private String getElementURI() { String uri = null; // At this point in processing we have received all the // namespace mappings // As we still don't know the elements namespace, // we now figure it out. String prefix = getPrefixPart(m_elemContext.m_elementName); ...
python
def updateLayoutParameters(self, algorithmName, body, verbose=None): """ Updates the Layout parameters for the Layout algorithm specified by the `algorithmName` parameter. :param algorithmName: Name of the layout algorithm :param body: A list of Layout Parameters with Values. :p...
java
public static <K, V, V2> Lens.Simple<Map<K, V>, Map<K, V2>> mappingValues(Iso<V, V, V2, V2> iso) { return simpleLens(m -> toMap(HashMap::new, map(t -> t.biMapR(view(iso)), map(Tuple2::fromEntry, m.entrySet()))), (s, b) -> view(mappingValues(iso.mirror()), b)); }
python
def extract_lookups_from_string(value): """Extract any lookups within a string. Args: value (str): string value we're extracting lookups from Returns: list: list of :class:`stacker.lookups.Lookup` if any """ lookups = set() for match in LOOKUP_REGEX.finditer(value): gr...
java
public final T parse(String value, Path configFilePath) { if (value == null) { throw new RuntimeException(ErrorMessage.UNAVAILABLE_PROPERTY.getMessage(name(), configFilePath)); } return parser().read(value); }
java
static void reportError(final String errorMessage) { if (MetricsManager.instance != null) { MetricsManager.rootMetricsLogger.incCounter(METRIC_ERRORS, 1); } LOG.error(errorMessage); }
java
protected void setNonDeferrableScheduledExecutor(ServiceReference<ScheduledExecutorService> ref) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "setNonDeferrableScheduledExecutor", ref); nonDeferrableSchedXSvcRef.setReference(ref); }
java
void formatTimeZone_X(StringBuilder b, ZonedDateTime d, int width, char ch) { int[] tz = getTzComponents(d); // Emit a 'Z' by itself for X if time is exactly GMT if (ch == 'X' && tz[TZOFFSET] == 0) { b.append('Z'); return; } switch (width) { case 5: case 4: case 3...
java
protected final void scan(Package tree) { Set<Class<?>> classes = Classes.matching(annotatedWith(Entity.class)).in(tree); for (Class<?> clazz : classes) { addPersistent(clazz); } }
java
private static String escapeString(String value) { Map<String, String> substitutions = new HashMap<String, String>(); substitutions.put("\n", "\\n"); substitutions.put("\t", "\\t"); substitutions.put("\r", "\\r"); return CmsStringUtil.substitute(value, substitutions); }
java
@SafeVarargs public static<T> Filter<T> and(final Filter<T>... f) { return new Filter<T>() { @Override public boolean apply(final T x) { for (final Filter<T> filter: f) if (! filter.apply(x)) return false; return true; } @Override public String toString() { return "(" + StringUtils.join(f...
python
def _get_udev_rules(self, channel_read, channel_write, channel_data): """construct udev rules info.""" sub_str = '%(read)s %%k %(read)s %(write)s %(data)s qeth' % { 'read': channel_read, 'read': channel_read, ...
python
def _collapse_to_cwl_record_single(data, want_attrs, input_files): """Convert a single sample into a CWL record. """ out = {} for key in want_attrs: key_parts = key.split("__") out[key] = _to_cwl(tz.get_in(key_parts, data), input_files) return out
java
public static <T> T fromJson(String json, Class<T> clazz) { Objects.requireNonNull(json, Required.JSON.toString()); Objects.requireNonNull(clazz, Required.CLASS.toString()); T object = null; try { object = mapper.readValue(json, clazz); } catch (IOException e...
python
def get_texts_and_labels(sentence_chunk): """Given a sentence chunk, extract original texts and labels.""" words = sentence_chunk.split('\n') texts = [] labels = [] for word in words: word = word.strip() if len(word) > 0: toks = word.split('\t') texts.append(t...
python
def remover(self, id_tipo_acesso, id_equipamento): """Removes relationship between equipment and access type. :param id_equipamento: Equipment identifier. :param id_tipo_acesso: Access type identifier. :return: None :raise EquipamentoNaoExisteError: Equipment doesn't exist. ...
java
public static boolean isNCName(CharSequence s) { if (isNullOrEmpty(s)) { return false; } int firstCodePoint = Character.codePointAt(s, 0); if (!isNCNameStartChar(firstCodePoint)) { return false; } for (int i = Character.charCount(firstCodePoint); i...
java
public void write(File file, Map<String, String> outputProperties) throws TransformerException, IOException { Writer writer = new Utf8Writer(file); try { write(writer, outputProperties); } finally { writer.close(); } }
python
def from_file(filename, password='', keytype=None): """ Returns a new PrivateKey instance with the given attributes. If keytype is None, we attempt to automatically detect the type. :type filename: string :param filename: The key file name. :type password: string ...
python
def load_cli(subparsers): """Given a parser, load the CLI subcommands""" for command_name in available_commands(): module = '{}.{}'.format(__package__, command_name) loader, description = _import_loader(module) parser = subparsers.add_parser(command_name, ...
java
public T peek() { if (nextToken == null) { nextToken = getNext(); } if (nextToken == null) { throw new NoSuchElementException(); } return nextToken; }
java
public ItemRequest<CustomField> findById(String customField) { String path = String.format("/custom_fields/%s", customField); return new ItemRequest<CustomField>(this, CustomField.class, path, "GET"); }
java
protected void gotoEOR(ArchiveRecord record) throws IOException { if (getIn().available() <= 0) { return; } // Remove any trailing LINE_SEPARATOR int c = -1; while (getIn().available() > 0) { if (getIn().markSupported()) { getIn()....
java
public static Document unmarshalHelper(InputSource source, EntityResolver resolver) throws CmsXmlException { return unmarshalHelper(source, resolver, false); }
python
def triplify_object(binding): """ Create bi-directional bindings for object relationships. """ triples = [] if binding.uri: triples.append((binding.subject, RDF.type, binding.uri)) if binding.parent is not None: parent = binding.parent.subject if binding.parent.is_array: ...
java
private String periodToString(Period period) { String retVal; if (period.getYears() > 0) { int weeks = Math.abs(period.getYears()) * 52; if (period.getYears() < 0) { weeks = -weeks; } retVal = String.format("P%dW", weeks); } else if...
java
@Override public ServiceRefAmp bind(ServiceRefAmp service, String address) { if (log.isLoggable(Level.FINEST)) { log.finest(L.l("bind {0} for {1} in {2}", address, service.api().getType(), this)); } address = toCanonical(address); registry().bind(address, service); ...
java
boolean onHeartbeatStop() { SocketPool clusterSocketPool; if (isExternal()) { clusterSocketPool = _clusterSocketPool.getAndSet(null); } else { clusterSocketPool = _clusterSocketPool.get(); } if (clusterSocketPool != null) { clusterSocketPool.getFactory().notifyHeartbeat...
python
def list_variables(self, page_size=None, page_token=None, client=None): """API call: list variables for this config. This only lists variable names, not the values. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables/l...
java
public void destroy() { CmsXmlContentUgcApi.SERVICE.destroySession(m_content.getSessionId(), new AsyncCallback<Void>() { public void onFailure(Throwable caught) { throw new RuntimeException(caught); } public void onSuccess(Void result) { ...
python
def ring2nest(nside, ipix): """Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`.""" ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return ring_to_nested(ipix, nside)
python
def add(cls, pid, connection): """Add a new connection and session to a pool. :param str pid: The pool id :type connection: psycopg2.extensions.connection :param connection: The connection to add to the pool """ with cls._lock: cls._ensure_pool_exists(pid) ...
python
def create_subfield_layer(aspect, ip): '''Reads the SUBFIELD.pgn file and creates the subfield layer.''' layer = [] if 'PANTS' in aspect: layer = pgnreader.parse_pagan_file(FILE_SUBFIELD, ip, invert=False, sym=True) else: layer = pgnreader.parse_pagan_file(FILE_MIN_SUBFIELD, ip, inve...
python
def _parse_field_list(fieldnames, include_parents=False): """ Parse a list of field names, possibly including dot-separated subform fields, into an internal ParsedFieldList object representing the base fields and subform listed. :param fieldnames: a list of field names as strings. dot-separated nam...
java
public StrBuilder insert(int index, CharSequence csq, int start, int end) { if (csq == null) { csq = "null"; } final int csqLen = csq.length(); if (start > csqLen) { return this; } if (start < 0) { start = 0; } if (end > csqLen) { end = csqLen; } if (start >= end) { return this; } ...
python
def logfile_generator(self): """Yield each line of the file, or the next line if several files.""" if not self.args['exclude']: # ask all filters for a start_limit and fast-forward to the maximum start_limits = [f.start_limit for f in self.filters if h...
python
def setup(cls, opts=type('opts', (), { 'background': None, 'logdir': None, 'logging_conf_file': None, 'log_level': 'DEBUG' })): """Setup logging via CLI params and config.""" logger = logging.getLogger('l...
python
def update(self, τ: float = 1.0, update_indicators=True, dampen=False): """ Advance the model by one time step. """ for n in self.nodes(data=True): n[1]["next_state"] = n[1]["update_function"](n) for n in self.nodes(data=True): n[1]["rv"].dataset = n[1]["next_state"] ...
java
@Deprecated public boolean delete(String src) throws IOException { checkOpen(); clearFileStatusCache(); return namenode.delete(src, true); }
python
def set_base_prompt( self, pri_prompt_terminator=">", alt_prompt_terminator="]", delay_factor=1 ): """ Sets self.base_prompt Used as delimiter for stripping of trailing prompt in output. Should be set to something that is general and applies in multiple contexts. For Comwar...
java
public ReplicationClientFactory usingApiKey(String apiKey) { if (Objects.equal(_apiKey, apiKey)) { return this; } return new ReplicationClientFactory(_jerseyClient, apiKey); }
java
private void buildReplacementNodesFromTranslation(MsgNode msg, SoyMsg translation) { currReplacementNodes = Lists.newArrayList(); for (SoyMsgPart msgPart : translation.getParts()) { if (msgPart instanceof SoyMsgRawTextPart) { // Append a new RawTextNode to the currReplacementNodes list. ...
python
def argsort(self, axis=-1, kind="quicksort", order=None): """ Returns the indices that would sort the array. See the documentation of ndarray.argsort for details about the keyword arguments. Example ------- >>> from unyt import km >>> data = [3, 8, 7]*km...
java
boolean reportSubtaskStats(JobVertexID jobVertexId, SubtaskStateStats subtask) { TaskStateStats taskStateStats = taskStats.get(jobVertexId); if (taskStateStats != null && taskStateStats.reportSubtaskStats(subtask)) { currentNumAcknowledgedSubtasks++; latestAcknowledgedSubtask = subtask; currentStateSize ...
java
@Override public T decode(byte[] bytes) throws IOException { if (bytes == null) { throw new IOException("byte array is null."); } CodedInputStream input = CodedInputStream.newInstance(bytes, 0, bytes.length); return readFrom(input); }
python
def guess(system): """ input format guess function. First guess by extension, then test by lines """ files = system.files maybe = [] if files.input_format: maybe.append(files.input_format) # first, guess by extension for key, val in input_formats.items(): if type(val) == ...
python
def coalescence_waiting_times(self, backward=True): '''Generator over the waiting times of successive coalescence events Args: ``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False`` ''' if not isinstance(backward, bool): ...
python
def group_membership_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/group_memberships#delete-membership" api_path = "/api/v2/group_memberships/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
python
def job_status_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/job_statuses#show-job-status" api_path = "/api/v2/job_statuses/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
python
def cleanup(self): """ This function is called when the service has finished running regardless of intentionally or not. """ # if an event broker has been created for this service if self.event_broker: # stop the event broker self.event_br...
python
def _set_intf_isis(self, v, load=False): """ Setter method for intf_isis, mapped from YANG variable /routing_system/interface/ve/intf_isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_intf_isis is considered as a private method. Backends looking to pop...