language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def filter(self, filter_id=""): """ Takes a filter's ID to be used in the current search context. Filter IDs can be found at <https://derpibooru.org/filters/> by inspecting the URL parameters. If no filter is provided, the user's current filter will be used. """ params = join_params(self.pa...
java
@Override public int differenceSize(IntSet other) { return other == null ? size() : size() - intersectionSize(other); }
java
private Collection<File> doListAllFiles(File rootDir, boolean includeDirectories) { Collection<File> result = new Stack<File>(); File[] files = rootDir.listFiles(); for (File f : files) { if (f.isDirectory()) { if (includeDi...
java
public static void setGroup(FileSystem fs, Path path, String group) throws IOException { fs.setOwner(path, fs.getFileStatus(path).getOwner(), group); }
java
private List<RunResults> generateRunResultList(List<File> reportInputDataDirs, SrcTree srcTree) throws IllegalDataStructureException { List<RunResults> resultsList = new ArrayList<>(reportInputDataDirs.size()); for (File reportInputDataDir : reportInputDataDirs) { RunResults resu...
python
def get_field_min_max(self, name, **query_dict): """Returns the minimum and maximum values of the specified field. This requires two search calls to the service, each requesting a single value of a single field. @param name(string) Name of the field @param q(string) Query identi...
python
def fetch_ticker(self) -> Ticker: """Fetch the market ticker.""" return self._fetch('ticker', self.market.code)(self._ticker)()
java
public Request makeRequest(HttpMethod httpMethod, String urlPath) throws IOException { return makeRequest(httpMethod, urlPath, true); }
python
def rs_find_errata_locator(e_pos, generator=2): '''Compute the erasures/errors/errata locator polynomial from the erasures/errors/errata positions (the positions must be relative to the x coefficient, eg: "hello worldxxxxxxxxx" is tampered to "h_ll_ worldxxxxxxxxx" with xxxxxxxxx being the ecc of length n-k=9, here...
java
protected final int applyAllCaseFoldWithMap(int mapSize, int[][]map, boolean essTsettFlag, int flag, ApplyAllCaseFoldFunction fun, Object arg) { asciiApplyAllCaseFold(flag, fun, arg); int[]code = new int[]{0}; for (int i=0; i<mapSize; i++) { ...
python
def submatrix(matrix,i1,i2,j1,j2): """ returns the submatrix defined by the index bounds i1-i2 and j1-j2 Endpoints included! """ new = [] for i in range(i1,i2+1): new.append(matrix[i][j1:j2+1]) return _n.array(new)
java
public String getText(final String toTest, final int group) { Matcher m = pattern.matcher(toTest); StringBuilder result = new StringBuilder(); while (m.find()) { result.append(m.group(group)); } return result.toString(); }
java
public static String decode(Style style) { if (style != null) { if (style instanceof ShapeStyle) { return decode((ShapeStyle) style); } else if (style instanceof FontStyle) { return decode((FontStyle) style); } else if (style instanceof PictureStyle) { return decode((PictureStyle) style); } ...
python
def from_name(cls, name): """ Retrieve a snapshot profile accsociated to a name.""" snps = cls.list({'name': name}) if len(snps) == 1: return snps[0]['id'] elif not snps: return raise DuplicateResults('snapshot profile name %s is ambiguous.' % name)
python
def __nms(boxes, threshold, method): """ Non Maximum Suppression. :param boxes: np array with bounding boxes. :param threshold: :param method: NMS method to apply. Available values ('Min', 'Union') :return: """ if boxes.size == 0: return np.em...
java
public CifarRaw readImage() throws IOException { int label = readUnsignedByte(); // peel off the first byte which is the image label int[][] red = new int[getRows()][getCols()]; for (int i = 0; i < getCols(); i++) { for (int j = 0; j < getRows(); j++) { red[i][j] = readUnsignedByte(); ...
python
def _get_game_number(cls, gid_path): """ Game Number :param gid_path: game logs directory path :return: game number(int) """ game_number = str(gid_path[len(gid_path)-2:len(gid_path)-1]) if game_number.isdigit(): return int(game_number) else: ...
python
def bias_field_correction( fmr, fimout = '', outpath = '', fcomment = '_N4bias', executable = '', exe_options = [], sitk_image_mask = True, verbose = False,): ''' Correct for bias field in MR image(s) given in <fmr> as a string (single file) o...
java
public void write(DataOutput out) throws IOException { out.writeInt(size); out.write(bytes, 0, size); }
java
public DescribeApplicationVersionsResult withApplicationVersions(ApplicationVersionDescription... applicationVersions) { if (this.applicationVersions == null) { setApplicationVersions(new com.amazonaws.internal.SdkInternalList<ApplicationVersionDescription>(applicationVersions.length)); } ...
java
public PackedDecimal add(PackedDecimal summand) { if (this.isBruch() || summand.isBruch()) { return add(summand.toBruch()); } else { return add(summand.toBigDecimal()); } }
python
def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: retur...
java
public PowerShell executeCommandAndChain(String command, PowerShellResponseHandler... response) { PowerShellResponse powerShellResponse = executeCommand(command); if (response.length > 0) { handleResponse(response[0], powerShellResponse); } return this; }
java
private int determineHeartbeatInterval(Map properties) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "determineHeartbeatInterval", properties); // How often should we heartbeat? int heartbeatInterval = JFapChannelConstants.DEFAULT_HEARTBEAT...
python
def search(self, q, **kwargs): """ You can pass in any of the Summon Search API parameters (without the "s." prefix). For example to remove highlighting: result = api.search("Web", hl=False) See the Summon API documentation for the full list of possible parameters:...
python
def bandreject(self, frequency, q=1.0): """bandreject takes 2 parameters: filter center frequency in Hz and "q" or band-width (default=1.0). It gradually removes frequencies within the band specified. """ self.command.append('bandreject') self.command.append(frequency) ...
java
public boolean sameJob(AutoTask jobAtIndex, AutoTask jobToAdd) { Map<String, Object> propJobAtIndex = jobAtIndex.getProperties(); Map<String, Object> propJobToAdd = jobToAdd.getProperties(); if (propJobAtIndex.size() != propJobToAdd.size()) return false; boolean bSameJob...
python
def use_value(self, value): """Converts value to field type or use original""" if self.check_value(value): return value return self.convert_value(value)
python
def parallel_coordinates(X, y, ax=None, features=None, classes=None, normalize=None, sample=1.0, color=None, colormap=None, alpha=None, fast=False, vlines=True, vlines_kwds=None, **kwargs): """Displays each feature as a vertical axis and eac...
python
def best_guess(f,X): ''' Gets the best current guess from a vector. :param f: function to evaluate. :param X: locations. ''' n = X.shape[0] xbest = np.zeros(n) for i in range(n): ff = f(X[0:(i+1)]) xbest[i] = ff[np.argmin(ff)] return xbest
java
protected Map<String, List<Object>> getCasPrincipalAttributes(final Map<String, Object> model, final RegisteredService registeredService) { return getPrincipalAttributesAsMultiValuedAttributes(model); }
java
public final Element parse(final String html) { checkNotNull(html, "Received a null pointer as body"); return Jsoup.parse(html).body(); }
python
def import_data( self, raw_buffer ): """Import data from a byte array. raw_buffer Byte array to import from. """ klass = self.__class__ if raw_buffer: assert common.is_bytes( raw_buffer ) # raw_buffer = memoryview( raw_buffer ) self._f...
python
def get_view_definition(self, connection, view_name, schema=None, **kw): """Return view definition. Given a :class:`.Connection`, a string `view_name`, and an optional string `schema`, return the view definition. Overrides interface :meth:`~sqlalchemy.engine.interfaces.Dialect.g...
java
public static FSInfo instance(Context context) { FSInfo instance = context.get(FSInfo.class); if (instance == null) instance = new FSInfo(); return instance; }
python
def at(self, hour, minute=0, second=0, microsecond=0): """ Returns a new instance with the current time to a different time. :param hour: The hour :type hour: int :param minute: The minute :type minute: int :param second: The second :type second: int ...
python
def get_return_description_indexes(self, data): """Get from a docstring the return parameter description indexes. In javadoc style it is after @return. :param data: string to parse :returns: start and end indexes of found element else (-1, -1) Note: the end index is the index ...
python
def time_col_turbulent(EnergyDis, ConcAl, ConcClay, coag, material, DiamTarget, DIM_FRACTAL): """Calculate single collision time for turbulent flow mediated collisions. Calculated as a function of floc size. """ return((1/6) * (6/np.pi)**(1/9) * EnergyDis**(-1/3) * DiamTarget**(2...
python
def convert(self, image, output=None): """ Convert an image to a PDF. :param image: Image file path :param output: Output name, same as image name with .pdf extension by default :return: PDF file path """ return self._convert(image, image.replace(Path(image).suff...
python
def commit(self): """ Insert the specified text in all selected lines, always at the same column position. """ # Get the number of lines and columns in the last line. last_line, last_col = self.qteWidget.getNumLinesAndColumns() # If this is the first ever call t...
java
private Polygon parsePolygon(JsonParser jp) throws IOException, SQLException { jp.nextToken(); // FIELD_NAME coordinates String coordinatesField = jp.getText(); if (coordinatesField.equalsIgnoreCase(GeoJsonField.COORDINATES)) { jp.nextToken(); // START_ARRAY [ coordinates ...
java
@Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(b.length); for (double aB : b) { out.writeDouble(aB); } }
java
public void marshall(DeleteApplicationSnapshotRequest deleteApplicationSnapshotRequest, ProtocolMarshaller protocolMarshaller) { if (deleteApplicationSnapshotRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
python
def full_match(self, other): """Find the mapping between vertex indexes in self and other. This also works on disconnected graphs. Derived classes should just implement get_vertex_string and get_edge_string to make this method aware of the different nature of certain vertices. ...
java
@Nullable public static PasswordSalt createFromStringMaybe (@Nullable final String sSalt) { if (StringHelper.hasNoText (sSalt)) return null; // Decode String to bytes // Throws an IllegalArgumentException if an invalid character is encountered final byte [] aBytes = StringHelper.getHexDecoded...
python
def unit_of_work(metadata=None, timeout=None): """ This function is a decorator for transaction functions that allows extra control over how the transaction is carried out. For example, a timeout (in seconds) may be applied:: @unit_of_work(timeout=25.0) def count_people(tx): re...
python
def calculate_eclipses(M1s, M2s, R1s, R2s, mag1s, mag2s, u11s=0.394, u21s=0.296, u12s=0.394, u22s=0.296, Ps=None, period=None, logperkde=RAGHAVAN_LOGPERKDE, incs=None, eccs=None, mininc=None, calc_mininc=True, ...
java
public MediaItem getMediaItem(String id) { DailyMotionUrl url = new DailyMotionUrl(requestPrefix + id); HttpRequest request; try { request = requestFactory.buildGetRequest(url); DailyMotionVideo video = request.execute().parseAs(DailyMotionVideo.class); if(video != null) { MediaItem mediaIt...
python
def style_get_property(self, property_name, value=None): """style_get_property(property_name, value=None) :param property_name: the name of a style property :type property_name: :obj:`str` :param value: Either :obj:`None` or a correctly initialized :obj:`GObject...
java
private ZealotKhala appendParams(Object value, int objType) { Object[] values = CollectionHelper.toArray(value, objType); if (CollectionHelper.isNotEmpty(values)) { Collections.addAll(this.source.getSqlInfo().getParams(), values); } return this; }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SimpleAntlrPackage.OR_EXPRESSION__LEFT: return getLeft(); case SimpleAntlrPackage.OR_EXPRESSION__RIGHT: return getRight(); } return super.eGet(featureID, resolve, co...
java
public void selectByIndex(String[] indexes) { for (int i = 0; i < indexes.length; i++) { selectByIndex(Integer.parseInt(indexes[i])); } }
python
def plot_clock_diagrams(self, colormap="summer"): """ Ploting clock diagrams - one or more rings around residue name and id (and chain id). The rings show the fraction of simulation time this residue has spent in the vicinity of the ligand - characterised by distance. """ ...
java
public void subscribeWithFilter(String channel, boolean subscribeOnReconnect, String filter, OnMessageWithFilter onMessage) { resolveSubscriptionChannels(channel, subscribeOnReconnect, onMessage, false, true, filter); }
python
def fire(self, *args, **kwargs): """ Emit the signal, calling all connected objects in-line with the given arguments and in the order they were registered. :class:`AdHocSignal` provides full isolation with respect to exceptions. If a connected listener raises an exception, the o...
python
def serialize(self, include_class=True, save_dynamic=False, **kwargs): """Serialize nested HasUID instances to a flat dictionary **Parameters**: * **include_class** - If True (the default), the name of the class will also be saved to the serialized dictionary under key :cod...
java
private void readCalendar(net.sf.mpxj.planner.schema.Calendar plannerCalendar, ProjectCalendar parentMpxjCalendar) throws MPXJException { // // Create a calendar instance // ProjectCalendar mpxjCalendar = m_projectFile.addCalendar(); // // Populate basic details // mp...
python
def _create_dictionary_of_IFS( self): """*Generate the list of dictionaries containing all the rows in the IFS stream* **Return:** - ``dictList`` - a list of dictionaries containing all the rows in the IFS stream **Usage:** .. code-block:: python ...
java
public Milestone getMilestone(Object projectIdOrPath, Integer milestoneId) throws GitLabApiException { Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", getProjectIdOrPath(projectIdOrPath), "milestones", milestoneId); return (response.readEntity(Milestone....
python
def speakerDiarization(filename, n_speakers, mt_size=2.0, mt_step=0.2, st_win=0.05, lda_dim=35, plot_res=False): ''' ARGUMENTS: - filename: the name of the WAV file to be analyzed - n_speakers the number of speakers (clusters) in the recording (<=0 for unknown) ...
python
def load_uint_b(buffer, width): """ Loads fixed size integer from the buffer :param buffer: :return: """ result = 0 for idx in range(width): result += buffer[idx] << (8 * idx) return result
java
public static Pair<ComputationGraph, Normalizer> restoreComputationGraphAndNormalizer( @NonNull InputStream is, boolean loadUpdater) throws IOException { checkInputStream(is); File tmpFile = null; try { tmpFile = tempFileFromStream(is); return restoreComputat...
python
def cb(option, value, parser): """ Callback function to handle variable number of arguments in optparse """ arguments = [value] for arg in parser.rargs: if arg[0] != "-": arguments.append(arg) else: del parser.rargs[:len(arguments)] break if g...
java
public AnimaQuery<T> in(String column, Object... args) { if (null == args || args.length == 0) { log.warn("Column: {}, query params is empty."); return this; } conditionSQL.append(" AND ").append(column).append(" IN ("); this.setArguments(args); conditionS...
python
def ichunks(iterable, chunksize, bordermode=None): r""" generates successive n-sized chunks from ``iterable``. Args: iterable (list): input to iterate over chunksize (int): size of sublist to return bordermode (str): None, 'cycle', or 'replicate' References: http://stac...
python
def run_path(path_name, init_globals=None, run_name=None): """Execute code located at the specified filesystem location Returns the resulting top level namespace dictionary The file path may refer directly to a Python script (i.e. one that could be directly executed with execfile) or else ...
java
@Procedure(mode = Mode.WRITE) @Description("apoc.refactor.rename.label(oldLabel, newLabel, [nodes]) | rename a label from 'oldLabel' to 'newLabel' for all nodes. If 'nodes' is provided renaming is applied to this set only") public Stream<BatchAndTotalResultWithInfo> label(@Name("oldLabel") String oldLabel, @Name("new...
java
@Pure public static boolean containsTrianglePoint( double ax, double ay, double az, double bx, double by, double bz, double cx, double cy, double cz, double px, double py, double pz, boolean forceCoplanar, double epsilon) { // // Compute vectors // // v0 = C - A double v0x = cx - ax; ...
java
@Override @SuppressWarnings("unchecked") public <T> List<T> search(Name base, String filter, SearchControls controls, ParameterizedContextMapper<T> mapper, DirContextProcessor processor) { return ldapOperations.search(base, filter, controls, mapper, processor); }
java
public void read() throws IOException { readFileId(); in.resetCRC(); long startcode = in.readStartCode(); while (true) { // Start parsing main and stream information header = new MainHeaderPacket(); if (!Startcode.MAIN.equalsCode(startcode)) { throw new IOException(String.fo...
java
public NodeData getAggregateRoot(NodeData nodeState) throws RepositoryException { for (int i = 0; i < nodeIncludes.length; i++) { NodeData aggregateRoot = nodeIncludes[i].matches(nodeState); if (aggregateRoot != null && aggregateRoot.getPrimaryTypeName().equals(nodeTypeName)) {...
python
def _SetGuide(self, guideName): """ Select guide corresponding to guideName Parameters ---------- guideName : string Name of guide to use. Note ---------- Supported guide names are: EPGUIDES """ if(guideName == epguides.EPGuidesLookup.GUIDE_NAME): self._guide = ...
python
def _get_types(self): """ extracts the needed types from the configspace for faster retrival later type = 0 - numerical (continuous or integer) parameter type >=1 - categorical parameter TODO: figure out a way to properly handle ordinal parameters """ types = [] num_values = [] for hp in se...
java
public final long[] getTick() { List list = (List)jmo.getField(ControlAccess.BODY_REQUESTACK_TICK); long lists[] = new long[list.size()]; for (int i = 0; i < lists.length; i++) lists[i] = ((Long)list.get(i)).longValue(); return lists; } /* * Get summary trace line for this message *...
java
@Override public boolean isAttributePresent(String attributeName) throws WidgetException { try { WebElement webElement = null; String attrValue = null; // WebDriver get attribute try { webElement = findElement(); attrValue = webElement.getAttribute(attributeName); highlight(HIGHLIGHT_MODES.G...
java
@SuppressWarnings("rawtypes") public CompletableFuture<Void> shutdownAsync(long quietPeriod, long timeout, TimeUnit timeUnit) { if (shutdown.compareAndSet(false, true)) { logger.debug("Initiate shutdown ({}, {}, {})", quietPeriod, timeout, timeUnit); return closeResources().thenCom...
python
def kwargs_warn_until(kwargs, version, category=DeprecationWarning, stacklevel=None, _version_info_=None, _dont_call_warnings=False): ''' Helper function to raise a warning (by default, a ``DeprecationW...
java
@Override public void collectParameters(Object pojo, List<Object> parameters) { forEachBinding(binding -> binding.collectParameters(pojo, parameters)); }
python
def generate_psk(self, identity): """ Generates the PRE_SHARED_KEY from the gateway. Returns a Command. """ def process_result(result): return result[ATTR_PSK] return Command('post', [ROOT_GATEWAY, ATTR_AUTH], { ATTR_IDENTITY: identity },...
java
public Connection getReadWriteConnection() throws SQLException { try { Connection conn = dataSource.getConnection(); setConnectionReadOnly(conn, false); return conn; } finally { if (logger.isDebugEnabled()) { logger.debug("Got connection fr...
python
def get_commit_from_tag(self, tag: str) -> Commit: """ Obtain the tagged commit. :param str tag: the tag :return: Commit commit: the commit the tag referred to """ try: selected_tag = self.repo.tags[tag] return self.get_commit(selected_tag.commit....
python
def config_make(config_file): """Create config.ini on first use, make dir and copy sample.""" from pkg_resources import resource_filename import shutil if not os.path.exists(CONFIG_DIR): os.makedirs(CONFIG_DIR) filename = resource_filename("mcc", "config.ini") try: shutil.copyfil...
java
public ServiceFuture<Void> updateAsync(String resourceGroupName, String clusterName, String configurationName, Map<String, String> parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, clusterName, configurationName, parame...
java
public static <ContainingType extends MessageLite, Type> GeneratedExtension<ContainingType, Type> newRepeatedGeneratedExtension( final ContainingType containingTypeDefaultInstance, final MessageLite messageDefaultInstance, final Internal.EnumLiteMap<?> enumTypeM...
java
private static SAXParser createSAXParser() throws ParserConfigurationException, SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); factory.setXIncludeAware(false); factory.setFeature( "http://xml.org/sax/features/external-general-entitie...
java
private String[] enumFieldsToNames(EntityField... fields) { String[] fieldsNames = new String[fields.length]; for (int i = 0; i < fields.length; i++) { fieldsNames[i] = fields[i].name(); } return fieldsNames; }
java
public T plus( double b ) { T ret = createLike(); ops.plus(mat,b,ret.mat); return ret; }
java
public static boolean setSpecialContentModeEnabled( AccessibilityNodeInfoCompat node, boolean enabled) { final int direction = (enabled) ? DIRECTION_FORWARD : DIRECTION_BACKWARD; return performSpecialAction(node, ACTION_TOGGLE_SPECIAL_CONTENT, direction); }
python
def subscribers(self): """Property returning the subscriber list""" return [s for p, s in sorted(self._subscribers, key=lambda x: x[0])]
python
def create(cls, mp, part_number, stream=None, **kwargs): """Create a new part object in a multipart object.""" if part_number < 0 or part_number > mp.last_part_number: raise MultipartInvalidPartNumber() with db.session.begin_nested(): obj = cls( multipart...
python
def hypergeometric_like(x, n, m, N): R""" Hypergeometric log-likelihood. Discrete probability distribution that describes the number of successes in a sequence of draws from a finite population without replacement. .. math:: f(x \mid n, m, N) = \frac{\left({ \begin{array}{c} {m} \\ {x} \\...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.MPORG__RG_LENGTH: setRGLength(RG_LENGTH_EDEFAULT); return; case AfplibPackage.MPORG__TRIPLETS: getTriplets().clear(); return; } super.eUnset(featureID); }
java
public void addDouble(double value) { data[endOffset] = value; endOffset++; // Grow the buffer if needed if (endOffset == data.length && !reachedMax) resize(); // Loop over and advance the start point if needed if (endOffset == data....
python
def _load_profile_imports(self, symbol_table): """ profile_imports is a list of module names or tuples of (module_name, names to import) in the form of ('.', names) it behaces like: from . import name1, name2, name3 or similarly import .name1, .name2, .name3 i.e. "name" in names becomes...
java
public static dnsaddrec get(nitro_service service, String hostname) throws Exception{ dnsaddrec obj = new dnsaddrec(); obj.set_hostname(hostname); dnsaddrec response = (dnsaddrec) obj.get_resource(service); return response; }
java
public static base_response update(nitro_service client, tmsessionaction resource) throws Exception { tmsessionaction updateresource = new tmsessionaction(); updateresource.name = resource.name; updateresource.sesstimeout = resource.sesstimeout; updateresource.defaultauthorizationaction = resource.defaultauthor...
python
def select_catalogue(self, selector, distance, distance_metric="rupture", upper_eq_depth=None, lower_eq_depth=None): """ Select earthquakes within a specied distance of the fault """ if selector.catalogue.get_number_events() < 1: raise ValueError('No ...
java
public static boolean isLetterNumber(char c) { return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || c == '_' || c == '.' || c == '@' || c == '#' || c == '$' || c == '+' || c == '-'; }
python
def patcher(args): """ %prog patcher backbone.bed other.bed Given optical map alignment, prepare the patchers. Use --backbone to suggest which assembly is the major one, and the patchers will be extracted from another assembly. """ from jcvi.formats.bed import uniq p = OptionParser(pat...
python
def _createIndexesFor(self, tableClass, extantIndexes): """ Create any indexes which don't exist and are required by the schema defined by C{tableClass}. @param tableClass: A L{MetaItem} instance which may define a schema which includes indexes. @param extantIndexes...