language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def load_rabit_checkpoint(self): """Initialize the model by load from rabit checkpoint. Returns ------- version: integer The version number of the model. """ version = ctypes.c_int() _check_call(_LIB.XGBoosterLoadRabitCheckpoint( self.hand...
java
public static Object concat(List<?> lhs, List<?> rhs) { List<Object> list = lhs instanceof Queue ? new LinkedList<>(lhs) : new ArrayList<>(lhs); list.addAll(rhs); return list; }
python
def change_password(self, current_password, new_password): """ Changes account password. @param current_password: current password @param new_password: new password """ attrs = {sconstant.A_BY: sconstant.V_NAME} account = SOAPpy.Types.stringType(data=self.auth_tok...
java
public static Optional<String> wavefrontLine(DateTime ts, GroupName group, MetricName metric, MetricValue metric_value) { return wavefrontValue(metric_value) .map(value -> { final Map<String, String> tag_map = tags(group.getTags()); final String source = e...
java
public ServiceFuture<Void> reactivateAsync(String jobId, String taskId, TaskReactivateOptions taskReactivateOptions, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(reactivateWithServiceResponseAsync(jobId, taskId, taskReactivateOptions), serviceCallback); }
java
protected void updateA( int w ) { final double u[] = dataQR[w]; for( int j = w+1; j < numCols; j++ ) { final double colQ[] = dataQR[j]; double val = colQ[w]; for( int k = w+1; k < numRows; k++ ) { val += u[k]*colQ[k]; } v...
python
def unroll(self, length, inputs, begin_state=None, layout='NTC', merge_outputs=None, valid_length=None): """Unrolls an RNN cell across time steps. Parameters ---------- length : int Number of steps to unroll. inputs : Symbol, list of Symbol, or None ...
python
def _get_image_for_different_arch(self, image, platform): """Get image from random arch This is a workaround for aarch64 platform, because orchestrator cannot get this arch from manifests lists so we have to provide digest of a random platform to get image metadata for orchestrator. ...
java
public void printHtmlLogo(PrintWriter out, ResourceBundle reg) throws DBException { char chMenubar = HBasePanel.getFirstToUpper(this.getProperty(DBParams.LOGOS), 'H'); if (chMenubar == 'H') if (((BasePanel)this.getScreenField()).isMainMenu()) chMenubar = 'Y'; if (chMenuba...
java
public static boolean acceptName(String pattern, String absPath) { absPath = normalizePath(absPath); pattern = adopt2JavaPattern(pattern); return absPath.matches(pattern); }
java
public java.util.List<OptionGroup> getOptionGroupsList() { if (optionGroupsList == null) { optionGroupsList = new com.amazonaws.internal.SdkInternalList<OptionGroup>(); } return optionGroupsList; }
java
private String getCacheNamePrefix() { String cacheNamePrefix = getPrefix( isDefaultURI ? null : uri, isDefaultClassLoader ? null : getClassLoader()); if (cacheNamePrefix == null) { return HazelcastCacheManager.CACHE_MANAGER_PREFIX; } else { ...
python
def verification_upload( self, verification_id, audio_file=None, bypass=False, bypass_pin=None, bypass_code=None, ): """ Upload verification data. Uses PUT to /verfications/<verification_id> interface :Args: ...
java
@SuppressWarnings("unchecked") public Map<String, Field> getValueAsMap() { return (Map<String, Field>) type.convert(getValue(), Type.MAP); }
python
def read_ascii_catalog(filename, format_, unit=None): """ Read an ASCII catalog file using Astropy. This routine is used by pymoctool to load coordinates from a catalog file in order to generate a MOC representation. """ catalog = ascii.read(filename, format=format_) columns = catalog.colu...
python
def insert_usb_device_filter(self, position, filter_p): """Inserts the given USB device to the specified position in the list of filters. Positions are numbered starting from @c 0. If the specified position is equal to or greater than the number of elements in the list, ...
java
@SdkProtectedApi public static URL convertRequestToUrl(Request<?> request, boolean removeLeadingSlashInResourcePath, boolean urlEncode) { String resourcePath = urlEncode ? SdkHttpUtils.urlEncode(request.getRe...
java
public void marshall(DetectSentimentRequest detectSentimentRequest, ProtocolMarshaller protocolMarshaller) { if (detectSentimentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(detectSentime...
java
public void encode(OutputStream out) throws IOException { // in cases where default constructor is used check for // null values if (notBefore == null || notAfter == null) { throw new IOException("CertAttrSet:CertificateValidity:" + " null values to...
java
static void assertVersionCompatible(final String expectedVersion, final String actualVersion) { final String shortActualVersion = actualVersion.replaceAll(VERSION_BUILD_PART_REGEX, ""); final String shortExpectedVersion = expectedVersion.replaceAll(VERSION_BUILD_PART_REGEX, ""); if (shortExpecte...
python
def reset_scan_stats(self): """Clears the scan event statistics and updates the last reset time""" self._scan_event_count = 0 self._v1_scan_count = 0 self._v1_scan_response_count = 0 self._v2_scan_count = 0 self._device_scan_counts = {} self._last_reset_time = tim...
python
def plugin_get_rfu(plugin): """ Returns "regular file urls" for a particular plugin. @param plugin: plugin class. """ if isinstance(plugin.regular_file_url, str): rfu = [plugin.regular_file_url] else: rfu = plugin.regular_file_url return rfu
python
def startPacketCapture(self, pcap_output_file, pcap_data_link_type="DLT_EN10MB"): """ :param pcap_output_file: PCAP destination file for the capture :param pcap_data_link_type: PCAP data link type (DLT_*), default is DLT_EN10MB """ self._capturing = True self._pcap_outpu...
python
def get_template(self, name=None, params=None): """ Retrieve an index template by its name. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html>`_ :arg name: The name of the template :arg flat_settings: Return settings in flat format (default:...
python
def end(self): """This pants run is over, so stop tracking it. Note: If end() has been called once, subsequent calls are no-ops. :return: PANTS_SUCCEEDED_EXIT_CODE or PANTS_FAILED_EXIT_CODE """ if self._end_memoized_result is not None: return self._end_memoized_result if self._background...
python
def _example_from_allof(self, prop_spec): """Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict """ example_dict = {} for definition in prop_spec['allOf']: ...
java
public int maxLogFileSize() { if (tc.isEntryEnabled()) Tr.entry(tc, "maxLogFileSize", this); if (tc.isEntryEnabled()) Tr.exit(tc, "maxLogFileSize", new Integer(_maxLogFileSize)); return _maxLogFileSize; }
python
def save(self): """ persist the fields in this object into the db, this will update if _id is set, otherwise it will insert see also -- .insert(), .update() """ ret = False # we will only use the primary key if it hasn't been modified pk = None i...
python
def tag_value_setter(tag, attrib): """ Decorator used to declare that the setter function is an attribute of embedded tag """ def outer(func): def inner(self, value): tag_elem = self.et.find(tag) if tag_elem is None: et = ElementTree.fromstring("<{}></{}>...
python
def format(self, info_dict, delimiter='/'): """ This formatter will take a data structure that represent a tree and will print all the paths from the root to the leaves in our case it will print each value and the keys that needed to get to it, for example: vm0:...
java
public String getParentIdentifier() { // Translate null parent to proper identifier String parentIdentifier = getModel().getParentIdentifier(); if (parentIdentifier == null) return RootConnectionGroup.IDENTIFIER; return parentIdentifier; }
java
public static boolean containsValue(Map<?, ?> data, Object what) { return data != null && data.containsValue(what); }
python
def call_handlers(event): """ Invoke all handlers for the provided event type/sub-type. The handlers are invoked in the following order: 1. Global handlers 2. Event type handlers 3. Event sub-type handlers Handlers within each group are invoked in order of registration. :param event: The event model object....
java
@Nonnull public static ImmutableKeyValueSource<Symbol, ByteSource> fromZip(final ZipFile zipFile) { return fromZip(zipFile, SymbolUtils.symbolizeFunction()); }
java
protected void loadClasses(Path pluginPath, PluginClassLoader pluginClassLoader) { for (String directory : pluginClasspath.getClassesDirectories()) { File file = pluginPath.resolve(directory).toFile(); if (file.exists() && file.isDirectory()) { pluginClassLoader.addFile(f...
python
def types_strict(instance): """Ensure that no custom object types are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: yield JSONError("Object type '%s' is not one of those defined in the" " specification." % instance['t...
python
def rdf_catalog(): '''Root RDF endpoint with content negociation handling''' format = RDF_EXTENSIONS[negociate_content()] url = url_for('site.rdf_catalog_format', format=format) return redirect(url)
python
def get_volume(self, id): """ return volume information if the argument is an id or a path """ # If the id is actually a path if exists(id): with open(id) as file: size = os.lseek(file.fileno(), 0, os.SEEK_END) return {'path': id, 'size': s...
python
def submit_safe_jobs(root_dir, jobs, sgeargs=None): """Submit the passed list of jobs to the Grid Engine server, using the passed directory as the root for scheduler output. - root_dir Path to output directory - jobs Iterable of Job objects """ # Loop over each job, constructing S...
python
def _resolve(self, path, migration_file): """ Resolve a migration instance from a file. :param migration_file: The migration file :type migration_file: str :rtype: orator.migrations.migration.Migration """ name = "_".join(migration_file.split("_")[4:]) m...
python
def from_bl(fname): """Read Seabird bottle-trip (bl) file Example ------- >>> from pathlib import Path >>> import ctd >>> data_path = Path(__file__).parents[1].joinpath("tests", "data") >>> df = ctd.from_bl(str(data_path.joinpath('bl', 'bottletest.bl'))) >>> df._metadata["time_of_reset"...
python
def request_span(request: Request, request_key: str = REQUEST_AIOZIPKIN_KEY) -> SpanAbc: """Returns span created by middleware from request context, you can use it as parent on next child span. """ return cast(SpanAbc, request[request_key])
java
private boolean needsLocalVariableTypeEntry(Type t) { //a local variable needs a type-entry if its type T is generic //(i.e. |T| != T) and if it's not an intersection type (not supported //in signature attribute grammar) return (!types.isSameType(t, types.erasure(t)) && !...
java
public EClass getObjectFunctionSetSpecification() { if (objectFunctionSetSpecificationEClass == null) { objectFunctionSetSpecificationEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(367); } return objectFunctionSetSpecificationEClass; }
python
def from_json(cls, json): """Inherit doc.""" obj = cls(property_range.PropertyRange.from_json(json["property_range"]), namespace_range.NamespaceRange.from_json_object(json["ns_range"]), model.QuerySpec.from_json(json["query_spec"])) cursor = json["cursor"] # lint bug. Class m...
java
public void write(byte []buf, int offset, int length, boolean isEnd) throws IOException { OutputStream os = _os; if (os != null) { os.write(buf, offset, length); } }
java
@Override public void start(Future<Void> startedResult) throws Exception { jerseyServer.createServer() .then(server -> { startedResult.complete(); return null; }) .otherwise(t -> { startedResult.fail...
java
public Observable<ServiceResponse<Void>> getLongRunningOperationStatusWithServiceResponseAsync(String operationStatusLink) { if (operationStatusLink == null) { throw new IllegalArgumentException("Parameter operationStatusLink is required and cannot be null."); } return service.getLon...
python
def _verify_connection(self): """ Checks availability of the Alooma server :return: If the server is reachable, returns True :raises: If connection fails, raises exceptions.ConnectionFailed """ try: res = self._session.get(self._connection_validation_url, json...
python
def time(self): """ Returns time as list [hh,mm,ss]. """ slist = self.toList() if slist[0] == '-': slist[1] *= -1 # We must do a trick if we want to # make negative zeros explicit if slist[1] == -0: slist[1] = -0.0 return s...
python
def mark_selection(self, star, fromtable=False): """Mark or unmark a star as selected. (fromtable)==True if the selection action came from the table (instead of the star plot). """ self.logger.debug("star selected name=%s ra=%s dec=%s" % ( star['name'], star['ra'], star['dec...
python
def create(self, product, data, store_view=None, identifierType=None): """ Upload a new product image. :param product: ID or SKU of product :param data: `dict` of image data (label, position, exclude, types) Example: { 'label': 'description of photo', 'positi...
python
def entity_readme_content(self, entity_id, channel=None): '''Get the readme for an entity. @entity_id The id of the entity (i.e. charm, bundle). @param channel Optional channel name. ''' readme_url = self.entity_readme_url(entity_id, channel=channel) response = self._get...
java
public SemanticStatus matches(final Signature other) { if (other == null) return null; // Check simple function/return types first if (getFunction() != other.getFunction()) return INVALID_FUNCTION; if (getReturnType() != other.getReturnType()) return INVALID_RETURN_TYPE; ...
java
public UOWCookie preInvoke(EJBKey key, EJBMethodInfoImpl methodInfo) throws CSIException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) { // d173022.3 Tr.entry(tc, "preInvoke"); } // Control poi...
java
protected boolean internalCanExpire() { boolean can = super.internalCanExpire(); if (can && _referenceCount > 0) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "preventing expiry as references remain"); can = false; }...
java
@Override public List<CommerceWarehouse> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
public static SSBondImpl toSsBond(Bond bond) { if (!bond.getAtomA().getGroup().getPDBName().equals("CYS") || !bond.getAtomB().getGroup().getPDBName().equals("CYS") ) { throw new IllegalArgumentException("Trying to create a SSBond from a Bond between 2 groups that are not CYS"); } SSBondImpl ssbond = n...
java
private final void fold(DataManipulate manipulate) { int leadIndexes[] = new int[SURROGATE_BLOCK_COUNT_]; int index[] = m_index_; // copy the lead surrogate indexes into a temporary array System.arraycopy(index, 0xd800 >> SHIFT_, leadIndexes, 0, SURROGATE_B...
python
def unroll_auth_headers(self, authheaders, exclude_signature=False, sep=",", quote=True): """Converts an authorization header dict-like object into a string representing the authorization. Keyword arguments: authheaders -- A string-indexable object which contains the headers appropriate for thi...
python
def invalid_foot_to_spondee(self, feet: list, foot: str, idx: int) -> str: """ In hexameters, a single foot that is a unstressed_stressed syllable pattern is often just a double spondee, so here we coerce it to stressed. :param feet: list of string representations of meterical feet ...
java
private static String[] parseRawParamKey(String rawKey) { List<String> list = new ArrayList<>(); int len = rawKey.length(); boolean inSquare = false; S.Buffer token = S.buffer(); for (int i = 0; i < len; ++i) { char c = rawKey.charAt(i); switch (c) { ...
python
def get_num_division_kpoints(structure, kppa): """ Get kpoint divisions for a given k-point density (per reciprocal-atom): kppa and a given structure """ output = run_aconvasp_command(["aconvasp", "--kpoints", str(kppa)], structure) tmp = output[0].rsplit("\n")[...
python
def use_comparative_log_entry_view(self): """Pass through to provider LogEntryLookupSession.use_comparative_log_entry_view""" self._object_views['log_entry'] = COMPARATIVE # self._get_provider_session('log_entry_lookup_session') # To make sure the session is tracked for session in self._...
java
public CmsContainerConfiguration getConfiguration(String name) { Map<String, CmsContainerConfiguration> configurationsForLocale = null; if (m_configurations.containsKey(CmsLocaleManager.MASTER_LOCALE)) { configurationsForLocale = m_configurations.get(CmsLocaleManager.MASTER_LOCALE); ...
java
public int previousCodePoint() { int ch1 = previous(); if (UTF16.isTrailSurrogate((char) ch1)) { int ch2 = previous(); if (UTF16.isLeadSurrogate((char) ch2)) { return Character.toCodePoint((char) ch2, (char) ch1); } else if (ch2 != DONE) { ...
python
def get_iter_string_reader(stdin): """ return an iterator that returns a chunk of a string every time it is called. notice that even though bufsize_type might be line buffered, we're not doing any line buffering here. that's because our StreamBufferer handles all buffering. we just need to return a r...
python
def get_photos_info(photoset_id): """Request the photos information with the photoset id :param photoset_id: The photoset id of flickr :type photoset_id: str :return: photos information :rtype: list """ args = _get_request_args( 'flickr.photosets.getPhotos', photoset_id=phot...
java
public static String replaceTabsWithSpaces(String text, int tabSize) { String tabText = ""; for (int i = 0; i < tabSize; i++) { tabText += " "; } return text.replaceAll("\t", " "); }
java
<T> void mockClass(MockFeatures<T> features) { boolean subclassingRequired = !features.interfaces.isEmpty() || Modifier.isAbstract(features.mockedType.getModifiers()); if (subclassingRequired && !features.mockedType.isArray() && !features.mockedType.isPri...
python
def get_language_model_status(self, model_id, token=None, url=API_TRAIN_LANGUAGE_MODEL): """ Gets the status of your model, including whether the training has finished. :param model_id: string, the ID for a model you created previously. returns: a request object """ ...
python
def _release(self, lease): """ Free the given lease Args: lease (lago.subnet_lease.Lease): The lease to free """ if lease.exist: os.unlink(lease.path) LOGGER.debug('Removed subnet lease {}'.format(lease.path))
python
def _send_tune_ok(self, frame_in): """Send Tune OK frame. :param specification.Connection.Tune frame_in: Tune frame. :return: """ self.max_allowed_channels = self._negotiate(frame_in.channel_max, MAX_CHANNELS) self.max...
java
public static <E> Iterator<E> cycle(Iterator<E> iterator) { return new CyclicIterator<E>(iterator); }
python
def PwCrypt(self, password): """Obfuscate password. RADIUS hides passwords in packets by using an algorithm based on the MD5 hash of the packet authenticator and RADIUS secret. If no authenticator has been set before calling PwCrypt one is created automatically. Changing the auth...
python
def dispatch(self, request, *args, **kwargs): """ Dispatches an incoming request. """ self.request = request self.args = args self.kwargs = kwargs response = self.check_permissions(request) if response: return response return super().dispatch(request, ...
python
def get_reviewable_hits(self, hit_type=None, status='Reviewable', sort_by='Expiration', sort_direction='Ascending', page_size=10, page_number=1): """ Retrieve the HITs that have a status of Reviewable, or HITs that have a status of Reviewi...
java
public static String[] getAvailableCurrencyCodes(ULocale loc, Date d) { String region = ULocale.getRegionForSupplementalData(loc, false); CurrencyFilter filter = CurrencyFilter.onDate(d).withRegion(region); List<String> list = getTenderCurrencies(filter); // Note: Prior to 4.4 the spec d...
java
public void addEntry(String id, int score, RelType context) { this.score.put(id, score); this.context.put(id, context); }
java
private Object[] compile(String path) { List<String> lst; lst = Filesystem.SEPARATOR.split(path); if (lst.size() == 0) { throw new IllegalArgumentException("empty path: " + path); } if (lst.get(0).equals("")) { throw new IllegalArgumentException("absolute...
java
@SafeVarargs public static <T> StreamEx<T> of(T... elements) { return of(Arrays.spliterator(elements)); }
python
def accepts(**schemas): """Create a decorator for validating function parameters. Example:: @accepts(a="number", body={"+field_ids": [int], "is_ok": bool}) def f(a, body): print (a, body["field_ids"], body.get("is_ok")) :param schemas: The schema for validating a given paramet...
python
def int_args(self): """ Iterate through all the possible arg positions that can only be used to store integer or pointer values Does not take into account customizations. Returns an iterator of SimFunctionArguments """ if self.ARG_REGS is None: raise NotImple...
python
def MoV_SNTV(profile, K): """ Returns an integer that represents the winning candidate given an election profile. Tie-breaking rule: numerically increasing order :ivar Profile profile: A Profile object that represents an election profile. """ # Currently, we expect the profile to contain compl...
java
public Counter<HString> countHString(@NonNull HString hString) { return getValueCalculator().adjust(Counters.newCounter(streamHString(hString))); }
python
def _get_return_dict(success=True, data=None, errors=None, warnings=None): ''' PRIVATE METHOD Creates a new return dict with default values. Defaults may be overwritten. success : boolean (True) True indicates a successful result. data : dict<str,obj> ({}) Data to be returned to the...
python
def _parse_dates(self, prop=DATES): """ Creates and returns a Date Types data structure parsed from the metadata """ return parse_dates(self._xml_tree, self._data_structures[prop])
python
def vert_opposites_per_edge(self): """Returns a dictionary from vertidx-pairs to opposites. For example, a key consist of [4, 5)] meaning the edge between vertices 4 and 5, and a value might be [10, 11] which are the indices of the vertices opposing this edge.""" result = {} ...
java
protected void transferOnlineContents(CmsSetupDb dbCon, int pubTag) throws SQLException { String query = readQuery(QUERY_TRANSFER_ONLINE_CONTENTS); Map<String, String> replacer = Collections.singletonMap("${pubTag}", "" + pubTag); dbCon.updateSqlStatement(query, replacer, null); }
python
def _recon_lcs(x, y): """ Returns the Longest Subsequence between x and y. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence :param x: sequence of words :param y: sequence of words :returns sequence: LCS of x and y """ table = _lcs(x, y) def _recon(i, j): ...
java
public final <T extends KeySpec> T getKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException { if (serviceIterator == null) { return spi.engineGetKeySpec(key, keySpec); } Exception failure = null; KeyFactorySpi mySpi = spi; do { try ...
java
public static boolean isSubgraph(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException { if (sourceGraph instanceof IQueryAtomContainer) { throw new CDKException("The first IAtomContainer must not be an IQueryAtomContainer"); } ...
python
def is_nonterminal(self, symbol: str) -> bool: """ Determines whether an input symbol is a valid non-terminal in the grammar. """ nonterminal_productions = self.get_nonterminal_productions() return symbol in nonterminal_productions
python
def claim_new_token(self): """ Update internal state to have a new token using a no authorization data service. """ # Intentionally doing this manually so we don't have a chicken and egg problem with DataServiceApi. headers = { 'Content-Type': ContentType.json, ...
python
def to_bytes(self): """Convert the entire image to bytes. :rtype: bytes """ chunks = [PNG_SIGN] chunks.extend(c[1] for c in self.chunks) return b"".join(chunks)
python
def _set_routes(self, v, load=False): """ Setter method for routes, mapped from YANG variable /rbridge_id/vrf/address_family/ipv6/unicast/ipv6/import/routes (list) If this variable is read-only (config: false) in the source YANG file, then _set_routes is considered as a private method. Backends look...
python
def update_execution_state_kernel(self): """Update actions following the execution state of the kernel.""" client = self.get_current_client() if client is not None: executing = client.stop_button.isEnabled() self.interrupt_action.setEnabled(executing)
python
def clean_helper(B, obj, clean_func): """ Clean object, intercepting and collecting any missing-relation or unique-constraint errors and returning the relevant resource ids/fields. Returns: - tuple: (<dict of non-unique fields>, <dict of missing refs>) """ try: clean_func(obj) ...
python
def set_table_acl(self, table_name, signed_identifiers=None, timeout=None): ''' Sets stored access policies for the table that may be used with Shared Access Signatures. When you set permissions for a table, the existing permissions are replaced. To update the table’s...
python
def add_line(self, line, source, *lineno): """Append one line of generated reST to the output.""" if 'conference_scheduler.scheduler' in source: module = 'scheduler' else: module = 'resources' rst[module].append(line) self.directive.result.append(self.indent + line, source, *lineno)