language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def import_jwks(self, jwks, issuer): """ Imports all the keys that are represented in a JWKS :param jwks: Dictionary representation of a JWKS :param issuer: Who 'owns' the JWKS """ try: _keys = jwks["keys"] except KeyError: raise ValueErro...
python
def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ if inspect.isclass(value): cls = value else: cls = value.__class__ if ...
java
public static void segWithStopWords(File input, File output) throws Exception{ Utils.seg(input, output, false, SegmentationAlgorithm.MaxNgramScore); }
java
public static String[] merge(final String[] input, final String[] list) { final List<String> v = new ArrayList<String>(Arrays.asList(list)); for (final String anInput : input) { if ((null != anInput) && !v.contains(anInput)) { v.add(anInput); } } r...
python
def disable_cert_validation(): """Context manager to temporarily disable certificate validation in the standard SSL library. Note: This should not be used in production code but is sometimes useful for troubleshooting certificate validation issues. By design, the standard SSL library does not prov...
python
def _evolve_reader(in_file): """Generate a list of region IDs and trees from a top_k_trees evolve.py file. """ cur_id_list = None cur_tree = None with open(in_file) as in_handle: for line in in_handle: if line.startswith("id,"): if cur_id_list: ...
java
void signedSubtract(MutableBigInteger addend) { if (sign == 1) sign = sign * subtract(addend); else add(addend); if (intLen == 0) sign = 1; }
java
public static void set( Object obj, String method, String value ) throws NoSuchMethodException { for( Setter s : c_setters ) { try { s.set( obj, method, value ); return; } catch(Exception e) {} } ...
python
def get_endpoint_resources(self, device_id, **kwargs): # noqa: E501 """List the resources on an endpoint # noqa: E501 The list of resources is cached by Device Management Connect, so this call does not create a message to the device. **Example usage:** curl -X GET https://api.us-east-1.mbedclou...
java
public List<CmsSolrIndex> getAllSolrIndexes() { List<CmsSolrIndex> result = new ArrayList<CmsSolrIndex>(); for (String indexName : getIndexNames()) { CmsSolrIndex index = getIndexSolr(indexName); if (index != null) { result.add(index); } } ...
java
public void setFlashAssetSize(com.google.api.ads.admanager.axis.v201811.Size flashAssetSize) { this.flashAssetSize = flashAssetSize; }
java
@SuppressWarnings("unchecked") public QueryResult findTaxClassificationByParentId(IEntity entity) throws FMSException { IntuitMessage intuitMessage = prepareFindByParentId(entity); //execute interceptors executeInterceptors(intuitMessage); QueryResult queryResult = null; ...
java
@BetaApi public final ListForwardingRulesPagedResponse listForwardingRules(ProjectRegionName region) { ListForwardingRulesHttpRequest request = ListForwardingRulesHttpRequest.newBuilder() .setRegion(region == null ? null : region.toString()) .build(); return listForwardingRules...
java
public BareJid getOwnJid() { if (ownJid == null && connection().isAuthenticated()) { ownJid = connection().getUser().asBareJid(); } return ownJid; }
python
def write_tabular(obj, filepath): """Write tabular object in HDF5 or pickle format Args: obj (array or DataFrame): tabular object to write filepath (path-like): path to write to; must end in '.h5' or '.pkl' """ _, fn, ext = splitext2(filepath) if ext == '.h5': _write_tabular...
java
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException { HttpURLConnection conn = createConnection(imageUri, extra); int redirectCount = 0; while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) { conn = createConnection(conn.getHeaderField("Locat...
java
@Handler(channels = NetworkChannel.class) public void onPurge(Purge event, IOSubchannel netChannel) { LinkedIOSubchannel.downstreamChannel(this, netChannel, WebAppMsgChannel.class).ifPresent(appChannel -> { appChannel.handlePurge(event); }); }
python
def log_config(): """Logs the config used to start the application""" conf = '\n'.join( ['{}="{}"'.format(k, v) for k, v in sorted(options.as_dict().iteritems())]) logging.info('Service started with the following settings:\n' + conf)
java
protected void processKeyGenerator(EntityTable entityTable, EntityField field, EntityColumn entityColumn) { //KeySql 优先级最高 if (field.isAnnotationPresent(KeySql.class)) { processKeySql(entityTable, entityColumn, field.getAnnotation(KeySql.class)); } else if (field.isAnnotationPresent(...
java
@Override protected void handleEvents(final String EVENT_TYPE) { super.handleEvents(EVENT_TYPE); if ("VISIBILITY".equals(EVENT_TYPE)) { Helper.enableNode(titleText, !tile.getTitle().isEmpty()); Helper.enableNode(text, tile.isTextVisible()); countryContainer.setMaxSiz...
java
public final AnnotateAssessmentResponse annotateAssessment( String name, AnnotateAssessmentRequest.Annotation annotation) { AnnotateAssessmentRequest request = AnnotateAssessmentRequest.newBuilder().setName(name).setAnnotation(annotation).build(); return annotateAssessment(request); }
java
@Expose public static String oxford(Collection<?> items, Locale locale) { return oxford(items.toArray(), locale); }
java
public @Nullable <K, V> CacheProxy<K, V> tryToCreateFromExternalSettings(String cacheName) { Optional<CaffeineConfiguration<K, V>> configuration = TypesafeConfigurator.from(rootConfig, cacheName); return configuration.isPresent() ? createCache(cacheName, configuration.get()) : null; }
java
private static Object getPrivateAttributes(HttpServletRequest req, String key) { HttpServletRequest sr = req; if (sr instanceof HttpServletRequestWrapper) { HttpServletRequestWrapper w = (HttpServletRequestWrapper) sr; sr = (HttpServletRequest) w.getRequest(); while (...
python
def helpEvent( self, event ): """ Displays a tool tip for the given help event. :param event | <QHelpEvent> """ item = self.itemAt(event.scenePos()) if ( item and item and item.toolTip() ): parent = self.parent() rect = it...
python
def print_info(self): "andreax + pts/0 2013-08-21 08:58 . 32341 (l26.box)" " pts/34 2013-06-12 15:04 26396 id=s/34 term=0 exit=0" # if self.ut_type not in [6,7]: # return print("%-10s %-12s %15s %15s %-8s" % ( s...
python
def get_child(self, name: YangIdentifier, ns: YangIdentifier = None) -> Optional[SchemaNode]: """Return receiver's schema child. Args: name: Child's name. ns: Child's namespace (= `self.ns` if absent). """ ns = ns if ns else self.ns todo...
python
def run_mace_smothr(x, y, bass_enhancement=0.0): # pylint: disable=unused-argument """Run the FORTRAN SMOTHR.""" N = len(x) weight = numpy.ones(N) results = numpy.zeros(N) flags = numpy.zeros((N, 7)) mace.smothr(1, x, y, weight, results, flags) return results
java
private static int getCycleNumber(long epochDay) { Long[] days = ADJUSTED_CYCLES; int cycleNumber; try { for (int i = 0; i < days.length; i++) { if (epochDay < days[i].longValue()) { return i - 1; } } cycleNu...
java
public <V> V attachIfAbsent(final AttachmentKey<V> key, final V value) { assert key != null; return key.cast(contextAttachments.putIfAbsent(key, value)); }
java
private CompletableFuture<Integer> reconcileData(AggregatedAppendOperation op, SegmentProperties storageInfo, TimeoutTimer timer) { InputStream appendStream = this.dataSource.getAppendData(op.getStreamSegmentId(), op.getStreamSegmentOffset(), (int) op.getLength()); if (appendStream == null) { ...
java
public HitResult intersect(Shape shape, Line line) { float distance = Float.MAX_VALUE; HitResult hit = null; for (int i=0;i<shape.getPointCount();i++) { int next = rationalPoint(shape, i+1); Line local = getLine(shape, i, next); Vector2f pt = line.intersect(local, true); if (pt != null)...
python
def encode(self, encoding='utf-8', errors='strict'): """ Returns bytes Encode S using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a Un...
python
def load_file(self, path, objtype=None, encoding='utf-8'): ''' Load the file specified by path This method will first try to load the file contents from cache and if there is a cache miss, it will load the contents from disk Args: path (string): The full or relative...
java
@Override public <T> T parse(String in, Class<? extends T> type) throws JSONMarshallException { try { return mapper.readValue(in, type); } catch (JsonParseException e) { throw new JSONMarshallException("Unable to parse non-well-formed content", e); } catch (JsonMappin...
python
def _admin_metadata_from_uri(uri, config_path): """Helper function for getting admin metadata.""" uri = dtoolcore.utils.sanitise_uri(uri) storage_broker = _get_storage_broker(uri, config_path) admin_metadata = storage_broker.get_admin_metadata() return admin_metadata
java
public void fillInitially(List<CmsVfsEntryBean> entries, String selectedSiteRoot) { clear(); for (CmsVfsEntryBean entry : entries) { if (entry != null) { CmsLazyTreeItem item = createItem(entry); addWidgetToList(item); } } if (null...
java
public String cardinal(Long n) { return (n == null) ? null : cardinal(n.longValue()); }
python
def vector_distance(v1, v2): """Given 2 vectors of multiple dimensions, calculate the euclidean distance measure between them.""" dist = 0 for dim in v1: for x in v1[dim]: dd = int(v1[dim][x]) - int(v2[dim][x]) dist = dist + dd**2 return dist
java
public void setAce_class(String v) { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_ace_class == null) jcasType.jcas.throwFeatMissing("ace_class", "de.julielab.jules.types.ace.Entity"); jcasType.ll_cas.ll_setStringValue(addr, ((Entity_Type)jcasType).casFeatCode_ace_class, v);}
java
public void setToolbar(@NonNull Activity activity, @NonNull Toolbar toolbar) { setToolbar(activity, toolbar, false); }
python
def to_json(self): ''' Returns the JSON representation of this graph. ''' roots = [] for r in self.roots: roots.append(r.to_json()) return {'roots': roots}
python
def use_plenary_asset_view(self): """Pass through to provider AssetLookupSession.use_plenary_asset_view""" self._object_views['asset'] = PLENARY # self._get_provider_session('asset_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): ...
python
def set(context="notebook", style="darkgrid", palette="deep", font="sans-serif", font_scale=1, color_codes=False, rc=None): """Set aesthetic parameters in one step. Each set of parameters can be set directly or temporarily, see the referenced functions below for more information. Parameters ...
java
private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) { Method[] methods = argumentMatcher.getClass().getMethods(); for (Method method : methods) { if (isMatchesMethod(method)) { return method.getParameterTypes()[0]; } } thro...
java
public final <E> FluentCloseableIterable<E> transform(Function<? super T, ? extends E> function) { return from(CloseableIterables.transform(this, function)); }
java
public static String encode(byte[] bytes, String indentation) { int length = bytes.length; if (length == 0) return ""; // empty byte array String encoded = Base64.encodeBase64String(bytes).replaceAll("\\s", ""); // remove all white space StringBuilder result = new StringBuilder(); ...
java
public <T> T getDocument(String indexName, String documentId, Class<T> beanType) throws ElasticSearchException{ return getDocument( indexName, _doc, documentId, beanType); }
python
def set_schema_to_public(self): """ Instructs to stay in the common 'public' schema. """ self.tenant = FakeTenant(schema_name=get_public_schema_name()) self.schema_name = get_public_schema_name() self.set_settings_schema(self.schema_name) self.search_path_set = Fa...
java
public static IReactionSet getRelevantReactionsAsProduct(IReactionSet reactSet, IAtomContainer molecule) { IReactionSet newReactSet = reactSet.getBuilder().newInstance(IReactionSet.class); for (IReaction reaction : reactSet.reactions()) { for (IAtomContainer atomContainer : reaction.getProdu...
java
private void downloadConservation(Species species, String assembly, Path speciesFolder) throws IOException, InterruptedException { logger.info("Downloading conservation information ..."); Path conservationFolder = speciesFolder.resolve("conservation"); if (species.getScientificName(...
python
def cluster_count_key_in_slots(self, slot): """Return the number of local keys in the specified hash slot.""" if not isinstance(slot, int): raise TypeError("Expected slot to be of type int, got {}" .format(type(slot))) return self.execute(b'CLUSTER', b'COU...
python
def token_cache_pkgs(source=None, release=None): """Determine additional packages needed for token caching @param source: source string for charm @param release: release of OpenStack currently deployed @returns List of package to enable token caching """ packages = [] if enable_memcache(sou...
java
public byte[] generateSeed(int length) { for (SeedGenerator generator : GENERATORS) { try { byte[] seed = generator.generateSeed(length); try { boolean debug = System.getProperty(DEBUG_PROPERTY, "false").equa...
python
def parent_link_extent(self): # type: () -> int ''' Get the extent of the parent of this entry if it has one. Parameters: None. Returns: The logical block number of the parent if it exists. ''' if not self._initialized: raise pycdlib...
java
@SuppressWarnings("unchecked") public static <T extends Enum<T>> T likeValueOf(Class<T> enumClass, Object value) { if(value instanceof CharSequence) { value = value.toString().trim(); } final Field[] fields = ReflectUtil.getFields(enumClass); final Enum<?>[] enums = enumClass.getEnumConstants(); ...
java
private static String convertToValidJavaClassname(String inName) { if (inName == null) return "_"; if (inName.startsWith("scriptdef_")) inName = inName.substring(10); if (inName.equals("")) return "_"; StringBuilder output = new StringBuilder(inName.length()); boolean firstChar ...
java
public static CommerceWarehouseItem findByCWI_CPIU( long commerceWarehouseId, String CPInstanceUuid) throws com.liferay.commerce.exception.NoSuchWarehouseItemException { return getPersistence() .findByCWI_CPIU(commerceWarehouseId, CPInstanceUuid); }
python
def next_frame_stochastic_discrete_range(rhp): """Next frame stochastic discrete tuning grid.""" rhp.set_float("learning_rate_constant", 0.001, 0.01) rhp.set_float("dropout", 0.2, 0.6) rhp.set_int("filter_double_steps", 3, 5) rhp.set_discrete("hidden_size", [64, 96, 128]) rhp.set_discrete("bottleneck_bits",...
python
def getall(self, key): """ Return a list of all values matching the key (may be an empty list) """ result = [] for k, v in self._items: if key == k: result.append(v) return result
java
void writePayload(ByteArrayOutputStream os) { // RF frames don't use NPDU length field os.write(addInfo[ADDINFO_RFMEDIUM] != null ? 0 : data.length - 1); os.write(data, 0, data.length); }
java
public InstanceFailoverGroupInner get(String resourceGroupName, String locationName, String failoverGroupName) { return getWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName).toBlocking().single().body(); }
java
protected String buildSnapshotBody(CreateSnapshotTaskParameters taskParams) { CreateSnapshotBridgeParameters bridgeParams = new CreateSnapshotBridgeParameters(dcHost, dcPort, dcStoreId, taskParams.getSpaceId(), ...
java
private JTextField getUrlText() { if (urlText == null) { urlText = new JTextField(); urlText.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { dis...
java
protected void parseDefaultValues( TokenStream tokens, JcrPropertyDefinitionTemplate propDefn ) { if (tokens.canConsume('=')) { List<String> defaultValues = parseStringList(tokens); if (!defaultValues.isEmpty()) { propDefn.setDefault...
python
def regex(self, expression, ignore_case=False, options=None): """ A query to check if a field matches a given regular expression :param ignore_case: Whether or not to ignore the case (setting this to True is the same as setting the 'i' option) :param options: A string of option character...
python
def AnularCertificacion(self, coe): "Anular liquidación activa" ret = self.client.cgSolicitarAnulacion( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, coe=coe, ...
java
public static MemcachedClient create(final PippoSettings settings) { String host = settings.getString(HOST, "localhost:11211"); String prot = settings.getString(PROT, "BINARY"); CommandFactory protocol; switch (prot) { case "BINARY": protocol = new BinaryComma...
java
@NotNull public ResultSetFuture executeAsync(@NotNull String keyspace, @NotNull Statement statement) { Timer time = getMetricsFactory().getTimer(MetricsType.CASSANDRA_EXECUTE_ASYNC.name()); getMetricsFactory().getCounter(MetricsType.CASSANDRA_PROCESSING_QUERIES.name()).inc(); ResultSetFutu...
java
public static <T> SortedSet<HBaseColumn<T>> asSortedSet(T value, long version) { return asSortedSet(value, version, DESC_HBASE_COLUMN_COMPARATOR); }
python
def login_required(func): '''decorator describing User methods that need to be logged in''' def ret(obj, *args, **kw): if not hasattr(obj, 'sessionToken'): message = '%s requires a logged-in session' % func.__name__ raise ResourceRequestLoginRequired(message) return func(...
java
private Point calculatePointOnCircle(final float centerX, final float centerY, final float radius, final float degrees) { // for trigonometry, 0 is pointing east, so subtract 90 // compass degrees are the wrong way round final double dblRadians = Math.toR...
python
def dataset_prepare(self): '''Subcommand of dataset for processing a corpus into a dataset''' # Initialize the prepare subcommand's argparser parser = argparse.ArgumentParser(description='Preprocess a raw dialogue corpus into a dsrt dataset') self.init_dataset_prepare_args(parser) ...
python
def get_columns(context, query): """Get list of cartoframes.columns.Column""" table_info = context.sql_client.send(query) if 'fields' in table_info: return Column.from_sql_api_fields(table_info['fields']) return None
java
private DB openStorage(StorageType storageType) { DB storage = storageRegistry.get(storageType); if(!isOpenStorage(storage)) { DBMaker m; if(storageType == StorageType.PRIMARY_STORAGE || storageType == StorageType.SECONDARY_STORAGE) { //main storage ...
python
def get_track_by_mbid(self, mbid): """Looks up a track by its MusicBrainz ID""" params = {"mbid": mbid} doc = _Request(self, "track.getInfo", params).execute(True) return Track(_extract(doc, "name", 1), _extract(doc, "name"), self)
python
def predict(self, h=5): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? Returns ---------- - pd.DataFrame with predictions """ if s...
java
private KafkaMsgConsumer getKafkaConsumer(String consumerGroupId, boolean consumeFromBeginning) { KafkaMsgConsumer kafkaConsumer = cacheConsumers.get(consumerGroupId); if (kafkaConsumer == null) { kafkaConsumer = _newKafkaConsumer(consumerGroupId, consumeFromBeginning); ...
java
public ZonedDateTime getStartZonedDateTime() { if (zonedStartDateTime == null) { zonedStartDateTime = ZonedDateTime.of(startDate, startTime, zoneId); } return zonedStartDateTime; }
java
public String build() { StringBuilder scriptBuilder = new StringBuilder(); StringBuilder scriptBody = new StringBuilder(); String importStmt = "import "; try { if (scriptCode.contains(importStmt)) { BufferedReader reader = new BufferedReader(new Strin...
java
@Override public QueryResult query(final Query query, final TimeUnit timeUnit) { Call<QueryResult> call = null; if (query instanceof BoundParameterQuery) { BoundParameterQuery boundParameterQuery = (BoundParameterQuery) query; call = this.influxDBService.query(query.getDatabase(), ...
java
private <R> R doWithWriteLock(Action<K, V, R> action) { long stamp = sl.writeLock(); try { return action.doWith(commonCache); } finally { sl.unlockWrite(stamp); } }
java
@Override public ZipImporter importFrom(final InputStream stream) throws ArchiveImportException { return importFrom(stream, Filters.includeAll()); }
java
public void registerProblem(GitHubRepositoryName repo, Throwable throwable) { if (throwable == null) { return; } registerProblem(repo, throwable.getMessage()); }
python
def zext(self, width): """Zero-extends a word to a larger width. It is an error to specify a smaller width (use ``extract`` instead to crop off the extra bits). """ width = operator.index(width) if width < self._width: raise ValueError('zero extending to a smaller wi...
java
@Override public DeleteFilterResult deleteFilter(DeleteFilterRequest request) { request = beforeClientExecution(request); return executeDeleteFilter(request); }
python
def dodging(bar): """Return a context manager which erases the bar, lets you output things, and then redraws the bar. It's reentrant. """ class ShyProgressBar(object): """Context manager that implements a progress bar that gets out of the way""" def __enter__(s...
java
@Override protected IncomingDataPoint getDataPointFromString(final TSDB tsdb, final String[] words) { final RollUpDataPoint dp = new RollUpDataPoint(); final String interval_agg = words[TelnetIndex.INTERVAL_AGG.ordinal()]; String interval = null; ...
python
def simxSetBooleanParameter(clientID, paramIdentifier, paramValue, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' return c_SetBooleanParameter(clientID, paramIdentifier, paramValue, operationMode)
java
Object getClassInstance() throws UtilEvalError { if (this.classInstance != null) return this.classInstance; if (this.classStatic != null // || (getParent()!=null && getParent().classStatic != null) ) throw new UtilEvalError( "Can't refer to clas...
java
public static BitStore asStore(boolean[] bits) { if (bits == null) throw new IllegalArgumentException("null bits"); return new BooleansBitStore(bits, 0, bits.length, true); }
java
public void marshall(PutMailboxPermissionsRequest putMailboxPermissionsRequest, ProtocolMarshaller protocolMarshaller) { if (putMailboxPermissionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
python
def _f90complex(self, value): """Return a Fortran 90 representation of a complex number.""" return '({0:{fmt}}, {1:{fmt}})'.format(value.real, value.imag, fmt=self.float_format)
python
def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq, membship, centroids): """Move point between clusters, categorical attributes.""" membship[to_clust, ipoint] = 1 membship[from_clust, ipoint] = 0 # Update frequencies of attributes in cluster. for iattr, curattr ...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SarlPackage.SARL_BEHAVIOR_UNIT__NAME: setName((JvmParameterizedTypeReference)newValue); return; case SarlPackage.SARL_BEHAVIOR_UNIT__GUARD: setGuard((XExpression)newValue); return; case SarlPackage.SARL...
java
public Token scanCharacterLiteral() { int start = pos; pos++; char c = input.charAt(pos++); if (c == '\\') { // escape code switch (input.charAt(pos++)) { case 'b': c = '\b'; break; case 't': c = '\t'; break; case 'n': c = '\n'; break; case 'f': c = '\f'; break;...
python
def launched(): """Test whether the current python environment is the correct lore env. :return: :any:`True` if the environment is launched :rtype: bool """ if not PREFIX: return False return os.path.realpath(sys.prefix) == os.path.realpath(PREFIX)
java
public static <OPERATION> SubdocOperationResult<OPERATION> createError(String path, OPERATION operation, ResponseStatus status, CouchbaseException exception) { return new SubdocOperationResult<OPERATION>(path, operation, status, exception); }
python
def mom_recurse(self, idxi, idxj, idxk): """Backend mement main loop.""" rank_ = min( chaospy.bertran.rank(idxi, self.dim), chaospy.bertran.rank(idxj, self.dim), chaospy.bertran.rank(idxk, self.dim) ) par, axis0 = chaospy.bertran.parent(idxk, self.dim)...
python
def fetch_one(self, *args, **kwargs): """ return one document which match the structure of the object `fetch_one()` takes the same arguments than the the pymongo.collection.find method. If multiple documents are found, raise a MultipleResultsFound exception. If no document is fou...