language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static LocalCall<String> getUid(String path, boolean followSymlinks) { Map<String, Object> args = new LinkedHashMap<>(); args.put("path", path); args.put("follow_symlinks", followSymlinks); return new LocalCall<>("file.get_uid", Optional.empty(), Optional.of(args), ...
java
public static <T extends ImageGray<T>, D extends ImageGray<D>> InterestPointDetector<T> wrapPoint(GeneralFeatureDetector<T, D> feature, double scale , Class<T> inputType, Class<D> derivType) { ImageGradient<T, D> gradient = null; ImageHessian<D> hessian = null; if (feature.getRequiresGradient() || feature.getR...
python
def output_summary(self, output_stream=sys.stdout): """outputs a usage tip and the list of acceptable commands. This is useful as the output of the 'help' option. parameters: output_stream - an open file-like object suitable for use as the target of a pri...
python
def get_devices(self, refresh=False, generic_type=None): """Get all devices from Abode.""" if refresh or self._devices is None: if self._devices is None: self._devices = {} _LOGGER.info("Updating all devices...") response = self.send_request("get", CO...
python
def handle(self): """ Executes the command. """ if not self.confirm_to_proceed( "<question>Are you sure you want to refresh the database?:</question> " ): return database = self.option("database") options = [("--force", True)] if...
python
def _get_next_occurrence(haystack, offset, needles): """ Find next occurence of one of the needles in the haystack :return: tuple of (index, needle found) or: None if no needle was found""" # make map of first char to full needle (only works if all needles # have di...
python
def makeblastdb(self, fastapath): """ Makes blast database files from targets as necessary """ # remove the path and the file extension for easier future globbing db = fastapath.split('.')[0] nhr = '{}.nhr'.format(db) # add nhr for searching if not os.path.isfile...
python
def json_to_string(self, source): """ Serialize JSON structure into string. *Args:*\n _source_ - JSON structure *Returns:*\n JSON string *Raises:*\n JsonValidatorError *Example:*\n | *Settings* | *Value* | | Library | JsonVal...
java
public static <T, F> FieldAugment<T, F> augment(Class<T> type, Class<? super F> fieldType, String name) { checkNotNull(type, "type"); checkNotNull(fieldType, "fieldType"); checkNotNull(name, "name"); @SuppressWarnings("unchecked") F defaultValue = (F) getDefaultValue(fieldType); FieldAugment<T, F> ret = ...
java
public static Config getConfig(@Nonnull final URI configLocation, @Nullable final String configName) { final ConfigFactory configFactory = new ConfigFactory(configLocation, configName); return new Config(configFactory.load()); }
python
def crc_ihex(hexstr): """Calculate the CRC for given Intel HEX hexstring. """ crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc = ((~crc + 1) & 0xff) return crc
python
def draw(self, filename, color=True): ''' Render a plot of the graph via pygraphviz. Args: filename (str): Path to save the generated image to. color (bool): If True, will color graph nodes based on their type, otherwise will draw a black-and-white graph. ...
python
def create(self, image, command=None, **kwargs): """ Create a container without starting it. Similar to ``docker create``. Takes the same arguments as :py:meth:`run`, except for ``stdout``, ``stderr``, and ``remove``. Returns: A :py:class:`Container` object. ...
python
def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that ha...
java
@Override public Request<DeleteVpnConnectionRequest> getDryRunRequest() { Request<DeleteVpnConnectionRequest> request = new DeleteVpnConnectionRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def _validate_input_data(self, data, request): """ Validate input data. :param request: the HTTP request :param data: the parsed data :return: if validation is performed and succeeds the data is converted into whatever format the validation uses (by default Django's ...
java
static void setHost(String scheme, String host, int port) { BASE_URL = scheme + "://" + host + ":" + port + "/" + VERSION + "/"; }
java
@Deprecated // to force even if someone wants to remove the one from the class @Restricted(NoExternalUse.class) public static @Nonnull ApiTokenStats load(@CheckForNull File parent) { // even if we are not using statistics, we load the existing one in case the configuration // is enabled aft...
java
public static int writeInt(ArrayView target, int offset, int value) { return writeInt(target.array(), target.arrayOffset() + offset, value); }
java
public void marshall(ListTriggersRequest listTriggersRequest, ProtocolMarshaller protocolMarshaller) { if (listTriggersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listTriggersRequest.ge...
java
public java.util.List<AccountWithRestoreAccess> getAccountsWithRestoreAccess() { if (accountsWithRestoreAccess == null) { accountsWithRestoreAccess = new com.amazonaws.internal.SdkInternalList<AccountWithRestoreAccess>(); } return accountsWithRestoreAccess; }
java
public static MessageHandler signallingMessageHandler(final ProcessEngine processEngine) { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { String executionId = message.getHeaders().containsKey("executionId"...
python
def add_widget(self, widget=None, row=None, col=None, row_span=1, col_span=1, **kwargs): """ Add a new widget to this grid. This will cause other widgets in the grid to be resized to make room for the new widget. Can be used to replace a widget as well Paramet...
java
private void flushEventBuffer() { Holder<T> holder = buffer.get(); logger.accept(holder.getBuffer().get()); holder.clear(); }
java
public ConstructorDoc[] constructors(boolean filter) { Names names = tsym.name.table.names; List<ConstructorDocImpl> constructors = List.nil(); for (Symbol sym : tsym.members().getSymbols(NON_RECURSIVE)) { if (sym != null && sym.kind == MTH && sym.name == names.init) ...
python
def cast_values_csvs(d, idx, x): """ Attempt to cast string to float. If error, keep as a string. :param dict d: Data :param int idx: Index number :param str x: Data :return any: """ try: d[idx].append(float(x)) except ValueError: d[idx].append(x) # logger_mi...
python
def file_handle(fnh, mode="rU"): """ Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in wh...
java
public static void insertEditEmpty( PageContext context, I_CmsXmlContentContainer container, CmsDirectEditMode mode, String id) throws CmsException, JspException { ServletRequest req = context.getRequest(); if (isEditableRequest(req) && (container.getColl...
java
public static BaseException translateException(Exception exception) { if (exception instanceof BaseException) { return (BaseException) exception; } else { for (SeedExceptionTranslator exceptionTranslator : exceptionTranslators) { if (exceptionTranslator.canTransla...
python
def gene_id_check(genes, errors, columns, row_number): """ Validate gene identifiers against a known set. Parameters ---------- genes : set The known set of gene identifiers. errors : Passed by goodtables. columns : Passed by goodtables. row_number : Pass...
java
public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) { this.downloadRange(output, rangeStart, rangeEnd, null); }
python
def decode_full_layer_uri(full_layer_uri_string): """Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple """ if not full_layer_uri_string...
python
def SMGetJobDictionaries(self, domain='kSMDomainSystemLaunchd'): """Copy all Job Dictionaries from the ServiceManagement. Args: domain: The name of a constant in Foundation referencing the domain. Will copy all launchd services by default. Returns: A marshalled python list of dic...
java
public ManagedDatabaseInner beginUpdate(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseUpdate parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).toBlocking().single().body(); }
python
def _access_through_series(values, name): """Coerce an array of datetime-like values to a pandas Series and access requested datetime component """ values_as_series = pd.Series(values.ravel()) if name == "season": months = values_as_series.dt.month.values field_values = _season_from_...
java
@Override public CommerceWishList[] findByUserId_PrevAndNext( long commerceWishListId, long userId, OrderByComparator<CommerceWishList> orderByComparator) throws NoSuchWishListException { CommerceWishList commerceWishList = findByPrimaryKey(commerceWishListId); Session session = null; try { session = ...
java
@Override public void endElement(CMLStack xpath, String uri, String name, String raw) { if (name.equals("molecule")) { // System.out.println("Ending element mdmolecule"); // add chargeGroup, and then delete them if (currentChargeGroup != null) { if (curr...
python
def fixture_to_tables(fixture): """ convert fixture into *behave* examples :param fixture: a dictionary in the following form:: { "test1name": { "test1property1": ..., "test1property2": ..., ... }, "test2nam...
python
def optional(p, default_value=None): '''`Make a parser as optional. If success, return the result, otherwise return default_value silently, without raising any exception. If default_value is not provided None is returned instead. ''' @Parser def optional_parser(text, index): res = p(text...
java
@Override public double distance(NumberVector v1, NumberVector v2) { return 1 - PearsonCorrelation.coefficient(v1, v2); }
python
def change_setting(self, instance_name, key, raw_value): """ Change the settings <key> to <raw_value> of an instance named <instance_name>. <raw_value> should be a string and is properly converted. """ ii = self.insts[instance_name] mo = self.modules[ii.module] i...
java
public <T> T parse(Reader in, JsonReaderI<T> mapper) throws ParseException { this.base = mapper.base; // this.in = in; return super.parse(mapper); }
python
def _strip_stray_atoms(self): """Remove stray atoms and surface pieces. """ components = self.bond_graph.connected_components() major_component = max(components, key=len) for atom in list(self.particles()): if atom not in major_component: self.remove(atom)
java
public MAP outboundMap(Map<String, Object> ctx) { AddressingProperties implementation = (AddressingProperties)ctx.get(CXFMAPConstants.CLIENT_ADDRESSING_PROPERTIES_OUTBOUND); if (implementation == null) { implementation = new AddressingProperties(); ctx.put(CXFMAPConstants.CLIENT_A...
python
def _GetNameFromProduct(self): """Determines the predefined operating system name from the product. Returns: str: operating system name, such as "macOS Mojave" or "Windows XP" or None if the name cannot be determined. This value is used to programmatically link a parser preset to an o...
java
public void setSSECustomerKey(SSECustomerKey sseKey) { if (sseKey != null && this.sseAwsKeyManagementParams != null) { throw new IllegalArgumentException( "Either SSECustomerKey or SSEAwsKeyManagementParams must not be set at the same time."); } this.sseCustomerKey = ...
python
def find_asts(self, ast_root, name): ''' Finds an AST node with the given name and the entire subtree under it. A function borrowed from scottfrazer. Thank you Scott Frazer! :param ast_root: The WDL AST. The whole thing generally, but really any portion that y...
python
def peek(self, default=None): '''Returns `default` is there is no subsequent item''' try: result = self.pointer.next() # immediately push it back onto the front of the iterable self.pointer = itertools.chain([result], self.pointer) return result ex...
python
def normalizeGlyphHeight(value): """ Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("Glyph height must be an :ref:`type-int-float`, not " ...
java
public final void setUtc(final boolean utc) { if (getDate() != null && (getDate() instanceof DateTime)) { ((DateTime) getDate()).setUtc(utc); } getParameters().remove(getParameter(Parameter.TZID)); }
java
protected <T extends Annotation> T extractPropertyAnnotation(Method writeMethod, Method readMethod, Class<T> annotationClass) { T parameterDescription = writeMethod.getAnnotation(annotationClass); if (parameterDescription == null && readMethod != null) { parameterDescription...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict
java
public void enc_ndr_string ( String s ) { align(4); int i = this.index; int len = s.length(); Encdec.enc_uint32le(len + 1, this.buf, i); i += 4; Encdec.enc_uint32le(0, this.buf, i); i += 4; Encdec.enc_uint32le(len + 1, this.buf, i); i += 4; ...
python
def plot_eighh(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eighh([tick_interval, xlabel, ylabel, ax, color...
python
def last_written_time(self): """dfdatetime.DateTimeValues: last written time.""" timestamp = self._pyregf_key.get_last_written_time_as_integer() if timestamp == 0: return dfdatetime_semantic_time.SemanticTime('Not set') return dfdatetime_filetime.Filetime(timestamp=timestamp)
python
def iterate_nodes(self, key, distinct=True): """hash_ring compatibility implementation. Given a string key it returns the nodes as a generator that can hold the key. The generator iterates one time through the ring starting at the correct position. if `distinct` is set, ...
python
def check_assertions(self, checklist, all=False): """Check a set of assertions @param all boolean if False, stop at first failure @return: False if any assertion fails. """ assert isinstance(checklist, dict) and 'checks' in checklist retval = None retlist = [] ...
python
def invalidate_m2m_cache(sender, instance, model, **kwargs): """ Signal receiver for models to invalidate model cache for many-to-many relationship. Parameters ~~~~~~~~~~ sender The model class instance The instance whose many-to-many relation is updated. model The c...
java
public void addMasterListeners() { super.addMasterListeners(); this.getField(FileHdr.FILE_NAME).addListener(new MoveOnChangeHandler(this.getField(FileHdr.FILE_MAIN_FILENAME), null, false, true)); }
java
public void setContentTypeEngine(ContentTypeEngine engine) { String contentType = engine.getContentType(); String suffix = StringUtils.removeStart(contentType.substring(contentType.lastIndexOf('/') + 1), "x-"); engines.put(engine.getContentType(), engine); suffixes.put(suffix.toLowerCas...
python
def __check_index(self, start_date, end_date): """check if maybe index needs rebuilding in the time span""" index_query = """SELECT id FROM facts WHERE (end_time >= ? OR end_time IS NULL) AND start_time <= ? ...
java
public static String getStaticResourceContext(String opencmsContext, String opencmsVersion) { return opencmsContext + STATIC_RESOURCE_PREFIX + "/v" + opencmsVersion.hashCode() + "v"; }
java
public static boolean isDirectoryPath(URI path) { return (path != null) && path.toString().endsWith(GoogleCloudStorage.PATH_DELIMITER); }
python
async def keep_alive(self, command): """ Periodically send a keep alive message to the Arduino. Frequency of keep alive transmission is calculated as follows: keep_alive_sent = period - (period * margin) :param command: {"method": "keep_alive", "params": [PERIOD, MARGIN]} ...
python
def _draw_visible_area(self, painter): """ Draw the visible area. This method does not take folded blocks into account. :type painter: QtGui.QPainter """ if self.editor.visible_blocks: start = self.editor.visible_blocks[0][-1] end = self.editor.v...
java
void parse( CharSequence text, ParseLog status, AttributeQuery attributes, ParsedEntity<?> parsedResult, boolean quickPath ) { AttributeQuery aq = (quickPath ? this.fullAttrs : this.getQuery(attributes)); if ( (this.padLeft == 0) && (...
java
@Override public void setup(AbstractInvokable parent) { @SuppressWarnings("unchecked") final GenericCollectorMap<IT, OT> mapper = RegularPactTask.instantiateUserCode(this.config, userCodeClassLoader, GenericCollectorMap.class); this.mapper = mapper; mapper.setRuntimeContext(getUdfRuntimeContext()); }
python
def rmtree_errorhandler(func, path, exc_info): """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""" # if file type currently read only if os.stat...
java
public void setTCPBufferSize(int size) throws IOException, ServerException { if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } try { boolean succeeded = false; String sizeString = Integer.toString(size); FeatureList feat =...
java
@Override public boolean requeueSilent(IQueueMessage<ID, DATA> msg) { try { return putToQueue(msg.clone(), true); } catch (RocksDBException e) { throw new QueueException(e); } }
java
private static void checkFinalImageBounds(Bitmap source, int x, int y, int width, int height) { Preconditions.checkArgument( x + width <= source.getWidth(), "x + width must be <= bitmap.width()"); Preconditions.checkArgument( y + height <= source.getHeight(), "y + height must be ...
python
def org_invite(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/invite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Finvite """ return DXHTTPRequest('/%s/invite' % object_id, input_para...
java
public static String matchListPrefix( String objectNamePrefix, String delimiter, String objectName) { Preconditions.checkArgument(!Strings.isNullOrEmpty(objectName), "objectName must not be null or empty, had args %s/%s/%s: ", objectNamePrefix, delimiter, objectName); // The suffix th...
python
def match_string(pattern, search_string): ''' Match a pattern in a string ''' rexobj = REX(pattern, None) rexpatstr = reformat_pattern(pattern) #print "rexpatstr: ", rexpatstr rexpat = re.compile(rexpatstr) rexobj.rex_patternstr = rexpatstr rexobj.rex_pattern = rexpat line_co...
python
def on_episode_begin(self, episode, logs): """ Reset environment variables at beginning of each episode """ self.episode_start[episode] = timeit.default_timer() self.observations[episode] = [] self.rewards[episode] = [] self.actions[episode] = [] self.metrics[episode] = [...
python
def stats(self, symbol): """ curl https://api.bitfinex.com/v1/stats/btcusd [ {"period":1,"volume":"7410.27250155"}, {"period":7,"volume":"52251.37118006"}, {"period":30,"volume":"464505.07753251"} ] """ data = self._get(self.url_for(PAT...
python
def browse( plugins, parent = None, default = None ): """ Prompts the user to browse the wizards based on the inputed plugins \ allowing them to launch any particular wizard of choice. :param plugins | [<XWizardPlugin>, ..] parent | <QWidget> ...
python
def get_bugs(*key_value): """Get list of bugs matching certain criteria. The conditions are defined by key value pairs. Possible keys are: * "package": bugs for the given package * "submitter": bugs from the submitter * "maint": bugs belonging to a maintainer * "src": bugs ...
python
def remove(self, param, author=None): """Remove by url or name""" if isinstance(param, SkillEntry): skill = param else: skill = self.find_skill(param, author) skill.remove() skills = [s for s in self.skills_data['skills'] if s['name'] != ...
python
def _do_post_text(tx): """ Try to find out what the variables mean: tx A structure containing more informations about paragraph ??? leading Height of lines ff 1/8 of the font size y0 The "baseline" postion ??? y 1/8 below the baseline """ xs = t...
java
public ListOutgoingCertificatesResult withOutgoingCertificates(OutgoingCertificate... outgoingCertificates) { if (this.outgoingCertificates == null) { setOutgoingCertificates(new java.util.ArrayList<OutgoingCertificate>(outgoingCertificates.length)); } for (OutgoingCertificate ele : ...
python
def load(self, name, location='local'): """Load saved data from the cache directory.""" path = self._get_path(name, location, file_ext='.json') if op.exists(path): return _load_json(path) path = self._get_path(name, location, file_ext='.pkl') if op.exists(path): ...
java
public DRUMSReader<Data> getReader() throws FileLockException, IOException { if (reader_instance != null && !reader_instance.filesAreOpened) { reader_instance.openFiles(); } else { reader_instance = new DRUMSReader<Data>(this); } return reader_instance; ...
java
public void marshall(ListActionExecutionsRequest listActionExecutionsRequest, ProtocolMarshaller protocolMarshaller) { if (listActionExecutionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def export(self, name, columns, points): """Export the stats to the Statsd server.""" for i in range(len(columns)): if not isinstance(points[i], Number): continue stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i]) stat_value = points[i] ...
java
public Charset getCharset() { String enc = getEncoding(); if (enc == null) { return Charset.defaultCharset(); } else { return Charset.forName(enc); } }
python
def getEditPerson(self, name): """ Get an L{EditPersonView} for editing the person named C{name}. @param name: A person name. @type name: C{unicode} @rtype: L{EditPersonView} """ view = EditPersonView(self.organizer.personByName(name)) view.setFragmentPa...
java
public static InputStream wrap(InputStream is, String task) { ProgressBarBuilder pbb = new ProgressBarBuilder().setTaskName(task).setInitialMax(Util.getInputStreamSize(is)); return wrap(is, pbb); }
java
public static String unescape(String oldstr) { /* * In contrast to fixing Java's broken regex charclasses, * this one need be no bigger, as unescaping shrinks the string * here, where in the other one, it grows it. */ StringBuilder newstr = new StringBuilder(oldstr.le...
python
def r2_score(pred:Tensor, targ:Tensor)->Rank0Tensor: "R2 score (coefficient of determination) between `pred` and `targ`." pred,targ = flatten_check(pred,targ) u = torch.sum((targ - pred) ** 2) d = torch.sum((targ - targ.mean()) ** 2) return 1 - u / d
java
private static int getPreviousPageOffset(final int offset, final int limit) { return hasFullPreviousPage(offset, limit) ? getPreviousFullPageOffset(offset, limit) : getFirstPageOffset(); }
java
public PreferredValueMakersRegistry addFieldOrPropertyMaker(Class ownerType, String propertyName, Maker<?> maker) { Preconditions.checkNotNull(ownerType); Preconditions.checkNotNull(propertyName); makers.put(Matchers.equalTo(String.format(Settable.FULL_NAME_FORMAT, ownerType.getName(), propertyN...
python
def get_check_threads(self): """Return iterator of checker threads.""" for t in self.threads: name = t.getName() if name.startswith("CheckThread-"): yield name
python
def _setup_file_hierarchy_limit( self, files_count_limit, files_size_limit, temp_dir, cgroups, pid_to_kill): """Start thread that enforces any file-hiearchy limits.""" if files_count_limit is not None or files_size_limit is not None: file_hierarchy_limit_thread = FileHierarchyLim...
java
private boolean gatherHomePageEvidence(Dependency dependency, EvidenceType type, Pattern pattern, String source, String name, String contents) { final Matcher matcher = pattern.matcher(contents); boolean found = false; if (matcher.find()) { final String url = matcher.grou...
java
public static Map<String, Field> getDeepDeclaredFieldMap(Class c) { Map<String, Field> fieldMap = new HashMap<>(); Collection<Field> fields = getDeepDeclaredFields(c); for (Field field : fields) { String fieldName = field.getName(); if (fieldMap.containsKey(fi...
python
def add_to_following(self, following): """ :calls: `PUT /user/following/:user <http://developer.github.com/v3/users/followers>`_ :param following: :class:`github.NamedUser.NamedUser` :rtype: None """ assert isinstance(following, github.NamedUser.NamedUser), following ...
java
protected int getPopupHeight() { if (m_popup.isShowing()) { return m_popup.getOffsetHeight(); } else { Element el = CmsDomUtil.clone(m_popup.getElement()); RootPanel.getBodyElement().appendChild(el); el.getStyle().setProperty("position", "absolute"); ...
python
def presets(self, presets, opt): """Will create representational objects for any preset (push) based AppRole Secrets.""" for preset in presets: secret_obj = dict(preset) secret_obj['role_name'] = self.app_name self.secret_ids.append(AppRoleSecret(secret_obj, o...
java
protected void writeCombiner( TupleCombiner combiner) { writer_ .element( COMBINE_TAG) .attribute( TUPLES_ATR, String.valueOf( combiner.getTupleSize())) .content( () -> { Arrays.stream( combiner.getIncluded()) .sorted() .forEach( this::writeIncluded); ...