language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_default_config(self): """ Returns the default collector settings """ config = super(RabbitMQCollector, self).get_default_config() config.update({ 'path': 'rabbitmq', 'host': 'localhost:55672', 'user': 'guest', 'password': 'g...
java
@Override public Request<DeleteVpcPeeringConnectionRequest> getDryRunRequest() { Request<DeleteVpcPeeringConnectionRequest> request = new DeleteVpcPeeringConnectionRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
java
public Double getAsDouble(String key) { Object value = mValues.get(key); try { return value != null ? ((Number) value).doubleValue() : null; } catch (ClassCastException e) { if (value instanceof CharSequence) { try { return Double.value...
python
def setColorAlpha(self, fixed=None, proportional=None): """ Change the alpha of the current :py:class:`Color`. :param fixed: Set the absolute 0-1 value of the alpha. :param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value...
java
@Override public void setStatusCode(StatusCodes code) { if (!code.equals(this.myStatusCode)) { this.myStatusCode = code; // no matter what, empty out the reason phrase information so that it // will default to match this new status code this.myReason = null; ...
python
def GetSize(cls): """Calculate the size of the struct.""" format_str = "".join([x[0] for x in cls._fields]) return struct.calcsize(format_str)
java
public SortedSet<ClassDoc> implementingclasses(ClassDoc cd) { SortedSet<ClassDoc> result = get(implementingclasses, cd); SortedSet<ClassDoc> intfcs = allSubs(cd, false); //If class x implements a subinterface of cd, then it follows //that class x implements cd. Iterator<ClassDoc...
java
public FessMessages addConstraintsNotNullMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_NotNull_MESSAGE)); return this; }
java
@Override public CreateClassifierResult createClassifier(CreateClassifierRequest request) { request = beforeClientExecution(request); return executeCreateClassifier(request); }
python
def setup(self, host, flow_id, reason, grr_server_url, grr_username, grr_password, approvers=None, verify=True): """Initializes a GRR flow collector. Args: host: hostname of machine. flow_id: ID of GRR flow to retrieve. reason: justification for GRR access....
python
def set_mlimits(self, row, column, min=None, max=None): """Set limits for the point meta (colormap). Point meta values outside this range will be clipped. :param min: value for start of the colormap. :param max: value for end of the colormap. """ subplot = self.get_sub...
java
private Control getControl(String name) { Control control = player.getControl(name); if (control == null) { throw new RuntimeException("Cannot find format control " + name); } return control; }
python
def find_missing_projections(label_list, projections): """ Finds all combinations of labels in `label_list` that are not covered by an entry in the dictionary of `projections`. Returns a list containing tuples of uncovered label combinations or en empty list if there are none. All uncovered label combin...
java
public static Days daysBetween(ReadableInstant start, ReadableInstant end) { int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.days()); return Days.days(amount); }
java
public synchronized void addBuffer(byte[] buf, int off, int len) { if (copyBuffers) { byte[] b = new byte[len]; System.arraycopy(buf, off, b, 0, len); buf = b; off = 0; } buffers.add(new Triple<>(buf, Integer.valueOf(off), Integer.valueOf(len))); totalSize += len; }
python
def _reduce_count(self): """Reduce size of cache by count. """ if self.max_count: while len(self.data) > self.max_count: self.data.popitem(last=False)
python
def get_name_preorder( self, name, sender_script_pubkey, register_addr, include_failed=False ): """ Get the current preorder for a name, given the name, the sender's script pubkey, and the registration address used to calculate the preorder hash. Return the preorder record on success. ...
python
def get_recipe_instances(self, badges=None, excluded=None): """ Returns all recipe instances or just those for the given badges. """ if badges: if not isinstance(badges, (list, tuple)): badges = [badges] if excluded: if not isinstance(excl...
python
def interactive(): """Create an interactive command line tool. Wrapper for an interactive session for manual commands to be entered. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--device', default='/dev/ttyUSB0', help='Path to PLM device') ...
java
public File append(byte[] data, int off, int len) throws IORuntimeException { return write(data, off, len, true); }
java
@Override public String encrypt(final String string) throws UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException { initialize(); final byte[] utf8 = str...
java
public void startDocument() throws SAXException { try { if (null == m_resultContentHandler) createResultContentHandler(m_result); } catch (TransformerException te) { throw new SAXException(te.getMessage(), te); } // Reset for multiple transforms with this transformer....
java
public void allowASCII(boolean allow) { this.allowASCII = allow; ISO9660NamingConventions.FORCE_ISO9660_CHARSET = !allow; if (allow) { System.out.println("Warning: Allowing the full ASCII character set breaks ISO 9660 conformance."); } }
python
def visit_rule(self, node, rule): """Assign a name to the Expression and return it.""" label, equals, expression = rule expression.name = label # Assign a name to the expr. return expression
java
public PagedResult<AlternateEmail> listAlternateEmails(long userId, PaginationParameters pagination) throws SmartsheetException { String path = "users/" + userId + "/alternateemails"; if (pagination != null) { path += pagination.toQueryString(); } return this.listResource...
python
def contains(self, val): """ Check if given value or range is present. Parameters ---------- val : int or tuple or list or range Range or integer being checked. Returns ------- retlen : int Length of overlapping with `val` subran...
java
public void logTaskUpdates(TaskID taskId, long finishTime) { if (disableHistory) { return; } JobID id = taskId.getJobID(); if (!this.jobId.equals(id)) { throw new RuntimeException("JobId from task: " + id + " does not match expected: " + jobId); } i...
java
public Options collectFrom(Class type) { final Options opts = new Options(); collectOptions(type, opts); return opts; }
python
def setup_recovery(working_dir): """ Set up the recovery metadata so we can fully recover secondary state, like subdomains. """ db = get_db_state(working_dir) bitcoind_session = get_bitcoind(new=True) assert bitcoind_session is not None _, current_block = virtualchain.get_index_range('b...
java
private String buildCsvValue(final Field field, final String fieldValue) { return (areTextValuesWrapped && field.getType().equals(String.class) || isValueWrappable.test(fieldValue)) ? wrapWithQuotes(fieldValue) : fieldValue; ...
java
public static MonthDay fromCalendarFields(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The calendar must not be null"); } return new MonthDay(calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)); }
java
public static void notNullOrEmpty(File parameter, String name) throws IllegalArgumentException { if (parameter == null || parameter.getPath().isEmpty()) { throw new IllegalArgumentException(name + " path is null or empty."); } }
java
private void configureAdditionalClasspath(final ClassRealm realm) { log.debug("Configuring additional classpath with scope: {}", classpathScope); List<File> classpath = Lists.newArrayList(); // add build output directory if scope includes 'compile' if (classpathScope.matches(compile)) { classpat...
python
def write_toc(self, args): """Write the table of contents.""" # FIXME: Can this logic be moved into the create_parser function? ordered = False if args.ordered_list_marker is not None: list_marker = args.ordered_list_marker ordered = True elif args.unorder...
python
def _connect(self): """ Connect to a RabbitMQ instance :returns: Boolean corresponding to success of connection :rtype: bool """ logger.info("Connecting to rabbit") for url in self._urls: try: self._connection = pika.BlockingConnectio...
python
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
java
public static StringBuffer sanitizePath(String input) { StringBuffer buf = new StringBuffer(); // Strip any surrounding quotation marks, that might have came with the file name from // any external source like the Windows environment variable. if (input.matches("^\".+\"$")) { input = input.substr...
java
public static void copyBufferedStream(BufferedInputStream sourceStream, BufferedOutputStream destinationStream, boolean closeStreams) throws IOException { byte[] buffer = new byte[8192]; int bytesRead = 0; try { while ((bytesRead = sourceStream.read(buffer)) != -1) { destinationStream.write(buffer, 0, ...
python
def XYZ_to_Luv(cobj, *args, **kwargs): """ Convert from XYZ to Luv """ temp_x = cobj.xyz_x temp_y = cobj.xyz_y temp_z = cobj.xyz_z denom = temp_x + (15.0 * temp_y) + (3.0 * temp_z) # avoid division by zero if denom == 0.0: luv_u = 0.0 luv_v = 0.0 else: luv...
python
def ploidy(args): """ %prog ploidy seqids karyotype.layout mcscan.out all.bed synteny.layout Build a figure that calls graphics.karyotype to illustrate the high ploidy of WGD history of pineapple genome. The script calls both graphics.karyotype and graphic.synteny. """ p = OptionParser(ploi...
java
public void divBP(VarTensor f) { VarTensor newFactor = applyBinOp(this, f, new AlgebraLambda.DivBP()); internalSet(newFactor); }
python
def to_percentage(number, rounding=2): """Creates a percentage string representation from the given `number`. The number is multiplied by 100 before adding a '%' character. Raises `ValueError` if `number` cannot be converted to a number. """ number = float(number) * 100 number_as_int = int(numb...
python
def getPlainText(self, identify=None): """ Convenience function for templates which want access to the raw text, without XML tags. """ frags = getattr(self, 'frags', None) if frags: plains = [] for frag in frags: if hasattr(frag, '...
python
def apply(self, func, args=(), kwds=dict()): """Equivalent of the apply() builtin function. It blocks till the result is ready.""" return self.apply_async(func, args, kwds).get()
python
def to_uint(self): """Convert vector to an unsigned integer, if possible. This is only useful for arrays filled with zero/one entries. """ num = 0 for i, f in enumerate(self._items): if f.is_zero(): pass elif f.is_one(): nu...
python
def upload_file(self, body, key=None, metadata=None, headers=None, access_key=None, secret_key=None, queue_derive=None, verbose=None, verify=None, ...
java
static void allocateHuffmanCodeLengths(final int[] array, final int maximumLength) { switch (array.length) { case 2: array[1] = 1; // fall through case 1: array[0] = 1; return; } /* Pass 1 : Set extended par...
java
private String getLabel(int i) { for (String label : labelMap.keySet()) { if (labelMap.get(label) == i) return label; } return null; }
python
def _get_changed_cfg_pkgs(self, data): ''' Filter out unchanged packages on the Debian or RPM systems. :param data: Structure {package-name -> [ file .. file1 ]} :return: Same structure as data, except only files that were changed. ''' f_data = dict() for pkg_nam...
python
def _handleFailedExecutor(self, agentID, executorID=None): """ Should be called when we find out an executor has failed. Gets the log from some container (since we are never handed a container ID) that ran on the given executor on the given agent, if the agent is still u...
java
@Override public Thoroughfare buildObject(String namespaceURI, String localName, String namespacePrefix) { return new ThoroughfareImpl(namespaceURI, localName, namespacePrefix); }
java
public void addRow(final String... cells){ final Row row = new Row((Object[]) cells); if(!rows.contains(row)){ rows.add(row); } }
python
def find_group_differences(groups1, groups2): r""" Returns a measure of how disimilar two groupings are Args: groups1 (list): true grouping of items groups2 (list): predicted grouping of items CommandLine: python -m utool.util_alg find_group_differences SeeAlso: vt...
python
def count_of_assigned_jobs(self): "Number of fields that have attrib['JobAssigned'] set to true." assigned = len([x.attrib['JobAssigned'] for x in self.fields if x.attrib['JobAssigned'] == 'true']) return assigned
python
def get_main_section(self, linesep=None): """ Serialize just the main section of the manifest and return it as bytes :return bytes """ linesep = linesep or self.linesep or os.linesep stream = BytesIO() ManifestSection.store(self, stream, linesep) return ...
python
def undo_sign_in(entry, session=None): """Delete a signed in entry. :param entry: `models.Entry` object. The entry to delete. :param session: (optional) SQLAlchemy session through which to access the database. """ # noqa if session is None: session = Session() else: session = se...
python
def changelist_view(self, request, extra_context=None): """ If we only have a single preference object redirect to it, otherwise display listing. """ model = self.model if model.objects.all().count() > 1: return super(PreferencesAdmin, self).changelist_view(re...
java
public WriteSegmentRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def fit(self, conver=DEFAULT_CONVERGENCE, minit=DEFAULT_MINIT, maxit=DEFAULT_MAXIT, fflag=DEFAULT_FFLAG, maxgerr=DEFAULT_MAXGERR, going_inwards=False): """ Perform just a simple 1-pixel extraction at the current (x0, y0) position using bilinear interpolation. The...
java
private Node getFirstChild(Node node) { if (node == null) return null; Node newNode = node.getFirstChild(); if (newNode == null) return null; int accept = acceptNode(newNode); if (accept == NodeFilter.FILTER_ACCEPT) return newNode; else if (accept == NodeFilter.FILTER_SKIP && newNode.hasChildNod...
java
public org.openprovenance.prov.model.Attribute unmarshal(Object value) { // System.out.println("AnyAdapter unmarshalling for " + value); if (value instanceof org.w3c.dom.Element) { org.w3c.dom.Element el = (org.w3c.dom.Element) value; return domProcessor.unmarshallAttribute(el,pF...
python
def calc_point_distance_vary(self, chi_coords, point_fupper, mus): """ Calculate distance between point and the bank allowing the metric to vary based on varying upper frequency cutoff. Slower than calc_point_distance, but more reliable when upper frequency cutoff can change a lo...
java
public void println(double d) throws IOException { String value = Double.toString(d); this.output.write(value.getBytes(), 0, value.length()); this.output.write(CRLF, 0, 2); }
python
def remove_item(self, item): """Remove item from model""" index = self.items.index(item) self.beginRemoveRows(QtCore.QModelIndex(), index, index) self.items.remove(item) self.endRemoveRows()
python
def find_assign_to_builtin(node): """Finds assigning to built-ins""" # The list of forbidden builtins is constant and not determined at # runtime anyomre. The reason behind this change is that certain # modules (like `gettext` for instance) would mess with the # builtins module making this practice...
python
def is_nsfw(): """A :func:`.check` that checks if the channel is a NSFW channel. This check raises a special exception, :exc:`.NSFWChannelRequired` that is derived from :exc:`.CheckFailure`. .. versionchanged:: 1.1.0 Raise :exc:`.NSFWChannelRequired instead of generic :exc:`.CheckFailure`. ...
python
def groupby(self, key_fn): """ Parameters ---------- key_fn : function Takes an effect or variant, returns a grouping key. """ result_dict = defaultdict(list) for x in self: result_dict[key_fn(x)].append(x) # convert result lists ...
python
def _jsmin(self): """Copy the input to the output, deleting the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed. """...
java
@Override public final int getInt(final String key) { Integer result = optInt(key); if (result == null) { throw new ObjectMissingException(this, key); } return result; }
python
def set_user(uid=None, username=None, password=None, priv=None, status=None): ''' Sets a CIMC user with specified configurations. .. versionadded:: 2019.2.0 Args: uid(int): The user ID slot to create the user account in. username(str): The name of the user. password(str): The...
python
def metainfo( self, mydict ): """This convenience function is only useful for html. It adds meta information via the <meta> element, the argument is a dictionary of the form { 'name':'content' }.""" if isinstance( mydict, dict ): for name, content in list( mydict.items( ) ):...
java
private boolean laterVersion(String newVersion, String oldVersion) { // Compare business versions, retur newVersion = newVersion.trim(); oldVersion = oldVersion.trim(); if (StringUtils.isNumeric(newVersion) && StringUtils.isNumeric(oldVersion)) return Double.parseDouble(newVersion) > Double.parseD...
java
public void addNum(double d) { if( isUUID() ) { addNA(); return; } if(_id == null || d != 0) { if(_ls != null)switch_to_doubles(); if( _ds == null || _sparseLen >= _ds.length ) { append2slowd(); // call addNum again since append2slow might have flipped to sparse addNum(d); ...
python
def createPushParser(SAX, chunk, size, URI): """Create a progressive XML parser context to build either an event flow if the SAX object is not None, or a DOM tree otherwise. """ ret = libxml2mod.xmlCreatePushParser(SAX, chunk, size, URI) if ret is None:raise parserError('xmlCreatePushParser() f...
python
def get_changeset(self, revision=None): """ Returns ``MercurialChangeset`` object representing repository's changeset at the given ``revision``. """ revision = self._get_revision(revision) changeset = MercurialChangeset(repository=self, revision=revision) return c...
python
def time_slices_to_layers(graphs, interslice_weight=1, slice_attr='slice', vertex_id_attr='id', edge_type_attr='type', weight_attr='weight'): """ Convert time slices to layer graphs. Ea...
python
def timemeter(msg=None): """Timer meter Use this annotation method can calculate the execute time. :param msg: custom message output :return: fn values """ def _time_meter(fn): @functools.wraps(fn) def _wrapper(*args, **kwargs): mark = timeit.default_timer() ...
java
public ApiResponse<UniverseIdsResponse> postUniverseIdsWithHttpInfo(List<String> requestBody, String acceptLanguage, String datasource, String language) throws ApiException { com.squareup.okhttp.Call call = postUniverseIdsValidateBeforeCall(requestBody, acceptLanguage, datasource, la...
java
String createCssContentString() { StringBuilder css = new StringBuilder(); css.append("<style>\n"); // html, body css.append("html, body {"); css.append("margin: 0;"); css.append("}\n"); // body css.append("body {"); css.append("background-color: ...
python
def filterStack(self, filters): """ Filter the ObjectGraph in-place by removing all edges to nodes that do not match every filter in the given filter list Returns a tuple containing the number of: (nodes_visited, nodes_removed, nodes_orphaned) """ visited, removes, orpha...
python
def update_certificate(self, cert_id, body, **kwargs): # noqa: E501 """Update trusted certificate. # noqa: E501 An endpoint for updating existing trusted certificates. **Example usage:** `curl -X PUT https://api.us-east-1.mbedcloud.com/v3/trusted-certificates/{cert-id} -d {\"description\": \"very i...
java
public static QueryAtomContainer create(IAtomContainer mol, Expr.Type... opts) { Set<Expr.Type> optset = EnumSet.noneOf(Expr.Type.class); optset.addAll(Arrays.asList(opts)); QueryAtomContainer query = new QueryAtomContainer(mol.getBuilder()); Map<IChemObject, IChemObject...
java
public static List<int[]> getNegativeRanges( double[] x ) { int firstNegative = -1; int lastNegative = -1; List<int[]> rangeList = new ArrayList<int[]>(); for( int i = 0; i < x.length; i++ ) { double xValue = x[i]; if (firstNegative == -1 && xValue < 0) { ...
python
def get_gradebook_column_mdata(): """Return default mdata map for GradebookColumn""" return { 'grade_system': { 'element_label': { 'text': 'grade system', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), ...
java
public static ListeningScheduledExecutorService listeningDecorator( ScheduledExecutorService delegate) { return (delegate instanceof ListeningScheduledExecutorService) ? (ListeningScheduledExecutorService) delegate : new ScheduledListeningDecorator(delegate); }
python
def quoted(s): """ quotes a string if necessary. """ # strip any existing quotes s = s.strip(u'"') # don't add quotes for minus or leading space if s[0] in (u'-', u' '): return s if u' ' in s or u'/' in s: return u'"%s"' % s else: return s
python
def complete_rules(rules, cmd): '''complete using a list of completion rules''' if not isinstance(rules, list): rules = [rules] ret = [] for r in rules: ret += complete_rule(r, cmd) return ret
python
def _get_serial_number(self): """ Retrieves the FTDI device serial number. :returns: string containing the device serial number """ return usb.util.get_string(self._device.usb_dev, 64, self._device.usb_dev.iSerialNumber)
java
public ServiceCall<BatchStatus> updateBatch(UpdateBatchOptions updateBatchOptions) { Validator.notNull(updateBatchOptions, "updateBatchOptions cannot be null"); String[] pathSegments = { "v1/batches" }; String[] pathParameters = { updateBatchOptions.batchId() }; RequestBuilder builder = RequestBuilder.p...
java
@Override public String get(String baseUrl, String uri) throws HttpServiceException, TechnicalException { return get(baseUrl + uri); }
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.GEAR__DATA: setDATA((byte[])newValue); return; } super.eSet(featureID, newValue); }
java
public static void replaceTokensInStream( final InputStream stream, final MultiDataContext<ContextView, DataContext> dataContext, final ScriptfileUtils.LineEndingStyle style, final File destination, final String nodeName ) throws IOException ...
java
private void getMoreEvents(Calendar day) { // Get more events if the month is changed. if (mEventRects == null) mEventRects = new ArrayList<EventRect>(); if (mWeekViewLoader == null && !isInEditMode()) throw new IllegalStateException("You must provide a MonthChangeListen...
python
def parse_reports(self): """ Find Picard RnaSeqMetrics reports and parse their data """ # Set up vars self.picard_RnaSeqMetrics_data = dict() self.picard_RnaSeqMetrics_histogram = dict() # Go through logs and find Metrics for f in self.find_log_files('picard/rnaseqmetrics', filehandles=True): ...
python
def _get_table_info(self): """Inspect the base to get field names""" self.fields = [] self.field_info = {} self.cursor.execute('PRAGMA table_info (%s)' %self.name) for field_info in self.cursor.fetchall(): fname = field_info[1].encode('utf-8') self....
java
@Override public UnicodeSet freeze() { if (!isFrozen()) { // Do most of what compact() does before freezing because // compact() will not work when the set is frozen. // Small modification: Don't shrink if the savings would be tiny (<=GROW_EXTRA). // Delete b...
java
private void simpleInterpolateMerge(FixedBucketsHistogram otherHistogram) { double rangeStart = Math.max(lowerLimit, otherHistogram.getLowerLimit()); double rangeEnd = Math.min(upperLimit, otherHistogram.getUpperLimit()); int myCurBucket = (int) ((rangeStart - lowerLimit) / bucketSize); double myNext...
python
def new(self, isdir, isparent, name, parent): # type: (bool, bool, bytes, Optional[UDFFileEntry]) -> None ''' A method to create a new UDF File Identifier. Parameters: isdir - Whether this File Identifier is a directory. isparent - Whether this File Identifier is a par...
java
public void unlink(Name name) { DirectoryEntry entry = remove(checkNotReserved(name, "unlink")); entry.file().unlinked(); }
java
public synchronized void addHandler(String handlerId) { // If it is first async handler subscribed, then create the main buffer if (ringBuffer == null) { ringBuffer = new Buffer<Object>(capacity); } /* * Every new Asynchronous handler starts off with all events from EMQ. * So we write all EMQ messages ...