language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static ClassFileReader newInstance(Path path, JarFile jf) throws IOException { return new JarFileReader(path, jf); }
python
def interpolate(self, transform, transitions=None, Y=None): """Interpolate new data onto a transformation of the graph data One of either transitions or Y should be provided Parameters ---------- transform : array-like, shape=[n_samples, n_transform_features] transiti...
java
public static synchronized @CheckForNull PermissionGroup get(Class owner) { for (PermissionGroup g : PERMISSIONS) { if (g.owner == owner) { return g; } } return null; }
java
private void setSlice() { // slicing initialisation if (labels == null) { double min = base.getPrecisionUnit()[index] * Math.ceil(base.getLowerBounds()[index] / base.getPrecisionUnit()[index]); double max = base.getPrecisionUnit()[index] * Math.floor(base.getUpperBounds()[index] ...
python
def fromlist(items, accessor=None, index=None, labels=None, dtype=None, npartitions=None, engine=None): """ Load series data from a list with an optional accessor function. Will call accessor function on each item from the list, providing a generic interface for data loading. Parameters ------...
python
def Write(self, output_writer): """Writes the table to the output writer. Args: output_writer (OutputWriter): output writer. Raises: RuntimeError: if the title exceeds the maximum width or if the table has more than 2 columns or if the column width is out of bounds. """...
java
private void preDelete(MembershipType type) throws Exception { for (MembershipTypeEventListener listener : listeners) { listener.preDelete(type); } }
python
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ celery_task = getattr(request, '_cache_update_cache', False) if not request.method in ('GET', 'HEAD'): request._cache_update_cac...
python
def safe_makedirs(path): """Safe makedirs. Works in a multithreaded scenario. """ if not os.path.exists(path): try: os.makedirs(path) except OSError: if not os.path.exists(path): raise
python
def GetUcsPropertyMetaAttributeList(classId): """ Methods returns the class meta. """ if classId in _ManagedObjectMeta: attrList = _ManagedObjectMeta[classId].keys() attrList.remove("Meta") return attrList if classId in _MethodFactoryMeta: attrList = _MethodFactoryMeta[classId].keys() attrList.remo...
python
def furthest_from_root(self): '''Return the ``Node`` that is furthest from the root and the corresponding distance. Edges with no length will be considered to have a length of 0 Returns: ``tuple``: First value is the furthest ``Node`` from the root, and second value is the corresponding dis...
python
def range_union(ranges): """ Returns total size of ranges, expect range as (chr, left, right) >>> ranges = [("1", 30, 45), ("1", 40, 50), ("1", 10, 50)] >>> range_union(ranges) 41 >>> ranges = [("1", 30, 45), ("2", 40, 50)] >>> range_union(ranges) 27 >>> ranges = [("1", 30, 45), ("1...
java
public void addNodeTypes(List<NodeTypeData> nodeTypes) throws RepositoryException { new CNDStreamWriter(namespaceRegistry).write(nodeTypes, os); }
java
public void execute() throws MojoExecutionException { final MavenProject project = getProject(); if (skip) { getLog().info("skipping as configured (skip)"); return; } if (skipPOMs && isPOM()) { getLog().info("skipping because artifact is a pom (skip...
java
static Character[] createCharacters() { int len = CHARACTER_UPPER_BOUND - CHARACTER_LOWER_BOUND + 1; Character[] ret = new Character[len]; char val = (char) CHARACTER_LOWER_BOUND; for (int i = 0; i < len; i++, val++) { ret[i] = new Character(val); } return ret...
java
private void writeResourceAdapter(Definition def, Writer out, int indent) throws IOException { writeIndent(out, indent); out.write("/**\n"); writeIndent(out, indent); out.write(" * Get the resource adapter\n"); writeIndent(out, indent); out.write(" *\n"); writeIndent(out, in...
java
private void processInternalListeners() { List<Class<?>> internalListeners = getAllInternalListeners(); for (Class<?> internalListener : internalListeners) { processInternalListener(internalListener); } }
java
public static void setShakeGestureSensitivity(float sensitivity) { requireApplication(); AppComponent.Holder.getInstance(application).getPublicControl().setShakeGestureSensitivity(sensitivity); }
java
public void setRefCSys(Integer newRefCSys) { Integer oldRefCSys = refCSys; refCSys = newRefCSys; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.OBP__REF_CSYS, oldRefCSys, refCSys)); }
java
public void restore( ObjectInputStream ois, int dataVersion) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "restore", new Object[] { ois, new Integer(dataVersion) }); try { HashMap hm = (HashMap)ois.readObject(); _topicSpaceUuid ...
java
protected static RequestParams getParams(Uri uri) { RequestParams params = new RequestParams(); Set<String> keys = getQueryParameterNames(uri); for (String key : keys) { String value = uri.getQueryParameter(key); if (TextUtils.isEmpty(value)) { value = nul...
python
def discard(self, element): """Remove element from the RangeSet if it is a member. If the element is not a member, do nothing. """ try: i = int(element) set.discard(self, i) except ValueError: pass
java
public static String encodeLines(byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) { final int blockLen = lineLen * 3 / 4; if (blockLen <= 0) { throw new IllegalArgumentException(); } final int lines = (iLen + blockLen - 1) / blockLen; final int bufLen = (iLen + 2) / 3 * 4 + lines...
java
private void serveError(Status status, HTTPTrackerErrorMessage error, RequestHandler requestHandler) throws IOException { requestHandler.serveResponse(status.getCode(), status.getDescription(), error.getData()); }
java
public static void main(String[] args) throws ParseException, ConfigurationException { CommandLineParser parser = new PosixParser(); try { cmd = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { System.err.printl...
java
private static String escapeXml(String source) { if (source == null) { return null; } StringBuffer result = new StringBuffer(source.length() * 2); for (int i = 0; i < source.length(); ++i) { char ch = source.charAt(i); switch (ch) { ...
python
async def listNamespaces(self, *args, **kwargs): """ List Namespaces List the namespaces immediately under a given namespace. This endpoint lists up to 1000 namespaces. If more namespaces are present, a `continuationToken` will be returned, which can be given in the nex...
java
public boolean isSimpleType() { if (// fieldType.equals(Double.class.getCanonicalName()) || // fieldType.equals(Float.class.getCanonicalName()) || // fieldType.equals(Integer.class.getCanonicalName()) || // fieldType.equals(double.class.getCanonicalName())...
java
public static TransactionContext getTransactionContext(HazelcastInstance hazelcastInstance) { TransactionContextHolder transactionContextHolder = (TransactionContextHolder) TransactionSynchronizationManager.getResource(hazelcastInstance); if (transactionContextHolder == null) { ...
java
public static RequestToken fetch(String username, BaasHandler<BaasUser> handler) { BaasUser user = BaasUser.withUserName(username); return user.refresh(handler); }
python
def create_from_name_and_dictionary(self, name, datas): """Return a populated object Object from dictionary datas """ if "type" not in datas: str_type = "any" else: str_type = str(datas["type"]).lower() if str_type not in ObjectRaw.Types: type...
java
private void initializeBigMapField(StorageEngine storageEngine, Field field) { field.setAccessible(true); try { BigMap a = field.getAnnotation(BigMap.class); field.set(this, storageEngine.getBigMap(field.getName(), a.keyClass(), a.valueClass(), a.mapType(), a.storageHint(), a.co...
python
def fromProfileName(cls, name): """Return a `SessionAPI` from a given configuration profile name. :see: `ProfileStore`. """ with profiles.ProfileStore.open() as config: return cls.fromProfile(config.load(name))
java
protected String __string(int offset) { offset += bb.getInt(offset); int length = bb.getInt(offset); return utf8.decodeUtf8(bb, offset + SIZEOF_INT, length); }
java
public static Optional<ButtonType> alert(String title, String content) { return alert(title, null, content); }
python
def connect(sock, addr): """Connect to some addr.""" try: sock.connect(addr) except ssl.SSLError as e: return (ssl.SSLError, e.strerror if e.strerror else e.message) except socket.herror as (_, msg): return (socket.herror, msg) except socket.gaierror as (_, msg): retu...
python
def onPersonRemoved( self, mid=None, removed_id=None, author_id=None, thread_id=None, ts=None, msg=None, ): """ Called when the client is listening, and somebody removes a person from a group thread :param mid: The action ID :p...
java
private String getResourceNameInOtherFolder(String resName, String sourceMergeFolder, String targetMergefolder) { // get the resourcename of the resouce to test without the source merge folder String resourcename = resName.substring(sourceMergeFolder.length()); // get the complete path of the r...
python
def pretty(self, obj=None, display=True): """ Formats @obj or :prop:obj @obj: the object you'd like to prettify -> #str pretty object """ ret = self._format_obj(obj if obj is not None else self.obj) if display: print(ret) else: re...
java
public com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KAnonymityResult getKAnonymityResult() { if (resultCase_ == 5) { return (com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KAnonymityResult) result_; } return com.google.privacy.dlp.v2.AnalyzeDataSourceRiskDetails.KAnonymityResul...
python
def get_choices_file_urls_map(self): """stub""" file_urls_map = [] for choice in self.get_choices(): choice = dict(choice) small_asset_content = self._get_asset_content( Id(choice['assetId']), OV_SET_SMALL_ASSET_CONTENT_TYPE) choice['smallOrtho...
python
def to_array(self): """ Serializes this CallbackQuery to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(CallbackQuery, self).to_array() array['id'] = u(self.id) # py2: type unicode, py3: type str array['fr...
python
def _set_item_class(self): """ cls: The custom generator class for which to create an item-class """ clsname = self.__tohu_items_name__ self.item_cls = make_item_class(clsname, self.field_names)
java
@PublicEvolving public <K, S extends State, V> CompletableFuture<S> getKvState( final JobID jobId, final String queryableStateName, final K key, final TypeHint<K> keyTypeHint, final StateDescriptor<S, V> stateDescriptor) { Preconditions.checkNotNull(keyTypeHint); TypeInformation<K> keyTypeInfo = k...
python
def add_edge(self, edge, double=False): """ Adds an edge to the ``DictGraph``. An edge is just a pair of **node objects**. If the **node objects** are not in the graph they are created. Arguments: - edge(iterable) An ordered pair of **node objects**....
java
static Class<?> validateElementType(Class<?> clazz) { if (clazz.isEnum()) { return clazz; } if (supportedElementTypes.containsKey(clazz)) { return clazz; } throw new IllegalArgumentException("Parameter type '" + clazz.getName() + "' is not supported."); ...
python
def frombinary(self, s): """Decode the binary string into an in memory list. S is a binary string.""" entrylen = struct.calcsize(self.ENTRYSTRUCT) p = 0 while p<len(s): (slen, dpos, dlen, ulen, flag, typcd) = struct.unpack(self.ENTRYSTRUCT, ...
python
def _extract_domain_id(string, regex): """ Extracts domain ID from given string and returns the domain ID. """ regex = re.compile(regex) match = regex.search(string) if not match: return False return str(match.group(1))
java
static URI updateToSecureConnectionIfNeeded(URI uri, ServiceInstance ribbonServer) { String scheme = uri.getScheme(); if (StringUtils.isEmpty(scheme)) { scheme = "http"; } if (!StringUtils.isEmpty(uri.toString()) && unsecureSchemeMapping.containsKey(scheme) && ribbonServer.isSecure()) { return upgra...
python
def etree(A): """ Compute elimination tree from upper triangle of A. """ assert isinstance(A,spmatrix), "A must be a sparse matrix" assert A.size[0] == A.size[1], "A must be a square matrix" n = A.size[0] cp,ri,_ = A.CCS parent = matrix(0,(n,1)) w = matrix(0,(n,1)) for k in ran...
python
def get_message(routing_key, properties, body): """ Construct a Message instance given the routing key, the properties and the body received from the AMQP broker. Args: routing_key (str): The AMQP routing key (will become the message topic) properties (pika.BasicProperties): the AMQP pr...
python
def domain(self, expparams): """ Returns a list of :class:`Domain` objects, one for each input expparam. :param numpy.ndarray expparams: Array of experimental parameters. This array must be of dtype agreeing with the ``expparams_dtype`` property, or, in the case where `...
python
def parse(self, context): """ Parse command line arguments. This method relies on ``context.argv`` and ``context.early_parser`` and produces ``context.args``. Note that ``.argv`` is modified by :meth:`preparse()` so it actually has _less_ things in it. The ``context.arg...
java
public MigrateArgs<K> auth(char[] password) { LettuceAssert.notNull(password, "Password must not be null"); this.password = Arrays.copyOf(password, password.length); return this; }
java
public static ZMatrixRMaj pivotMatrix(ZMatrixRMaj ret, int pivots[], int numPivots, boolean transposed ) { if( ret == null ) { ret = new ZMatrixRMaj(numPivots, numPivots); } else { if( ret.numCols != numPivots || ret.numRows != numPivots ) throw new IllegalArgume...
java
private void timeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_timeFocusLost String time = jTextField3.getText(); setTime(time); }
java
public Observable<ServiceResponse<Image>> addImageWithServiceResponseAsync(String listId, AddImageOptionalParameter addImageOptionalParameter) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } ...
python
def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any: """ :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html """ headers, post_data = _buildmessageobject(messageobject) newdm_path = "/direct_me...
java
protected TTTState<I, D> getAnyTarget(TTTTransition<I, D> trans) { if (trans.isTree()) { return trans.getTreeTarget(); } return trans.getNonTreeTarget().anySubtreeState(); }
java
protected int getInt(String key, int defaultValue) { try { return getConfig().getInt(key, defaultValue); } catch (ConversionException e) { logConversionException(key, e); } return defaultValue; }
python
def to_ip(self, values, from_unit): """Return values in IP and the units to which the values have been converted.""" if from_unit in self.ip_units: return values, from_unit elif from_unit == 'tonne': return self.to_unit(values, 'ton', from_unit), 'ton' else: ...
python
def camel_to_snake(text): """ Will convert CamelCaseStrings to snake_case_strings. >>> camel_to_snake('CamelCase') 'camel_case' >>> camel_to_snake('CamelCamelCase') 'camel_camel_case' >>> camel_to_snake('Camel2Camel2Case') 'camel2_camel2_case' >>> camel_to_snake('getHTTPResponseCode'...
java
public ToStringBuilder append(final String fieldName, final double[] array) { style.append(buffer, fieldName, array, null); return this; }
python
def Analyze(self, source_path, output_writer): """Analyzes the source. Args: source_path (str): the source path. output_writer (StdoutWriter): the output writer. Raises: RuntimeError: if the source path does not exists, or if the source path is not a file or directory, or if th...
python
def sealed_keys(self): """A subset of the :attr:`entries` dictionary, filtered down to only those entries of type :class:`BksSealedKeyEntry`.""" return dict([(a, e) for a, e in self.entries.items() if isinstance(e, BksSealedKeyEntry)])
python
def dump_by_server(self, hosts): """Returns the output of dump for each server. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A dictionary of ((server_ip, port), ClientInfo). """ dump_by_endpoint = {} for endpoint in self._to_endpoints(ho...
java
private static String createTypeId(Type type) { if (type instanceof Class<?>) { return Reflections.<Class<?>> cast(type).getName(); } if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; StringBuilder builder...
java
public <C> Maybe<DbxEntry./*@Nullable*/WithChildrenC<C>> getMetadataWithChildrenIfChangedC( String path, /*@Nullable*/String previousFolderHash, Collector<DbxEntry,? extends C> collector) throws DbxException { return getMetadataWithChildrenIfChangedC(path, false, previousFolderHash, coll...
python
def import_from_string(val): """ Attempt to import a class from a string representation. """ try: module_path, class_name = val.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) as e: msg = f"Cou...
python
def freeze(dest_dir, opt): """Iterates over the Secretfile looking for secrets to freeze""" tmp_dir = ensure_tmpdir() dest_prefix = "%s/dest" % tmp_dir ensure_dir(dest_dir) ensure_dir(dest_prefix) config = get_secretfile(opt) Context.load(config, opt) \ .freeze(dest_prefix) zi...
java
@Override protected boolean notHaveAnyExpirableRecord(PartitionContainer partitionContainer) { boolean notExist = true; final ConcurrentMap<String, RecordStore> maps = partitionContainer.getMaps(); for (RecordStore store : maps.values()) { if (store.isExpirable()) { ...
python
def __has_language(self, bundleId, languageId): """Returns ``True`` if the bundle has the language, ``False`` otherwise """ return True if self.__get_language_data(bundleId=bundleId, languageId=languageId) \ else False
java
public Matrix4 setToSkew (IVector3 normal, float constant, IVector3 amount) { return setToSkew(normal.x(), normal.y(), normal.z(), constant, amount.x(), amount.y(), amount.z()); }
java
public static String setTermType(final String postag) { if (postag.startsWith("N") || postag.startsWith("V") || postag.startsWith("G") || postag.startsWith("A")) { return "open"; } else { return "close"; } }
python
def install_API_key(api_key, profile_name='default'): """Put the given API key into the given profile name.""" fname = API_profile_fname(profile_name) if not os.path.isdir(os.path.dirname(fname)): os.makedirs(os.path.dirname(fname)) with open(fname, 'w') as fh: fh.write(api_key)
python
def _set_openflow_global(self, v, load=False): """ Setter method for openflow_global, mapped from YANG variable /openflow_global (container) If this variable is read-only (config: false) in the source YANG file, then _set_openflow_global is considered as a private method. Backends looking to populat...
python
def resource_redirect(id): ''' Redirect to the latest version of a resource given its identifier. ''' resource = get_resource(id) return redirect(resource.url.strip()) if resource else abort(404)
python
def _sync_labels(self, labels_json): """"Populate the user's labels from a JSON encoded list.""" for label_json in labels_json: label_id = label_json['id'] self.labels[label_id] = Label(label_json, self)
python
def filter_by_doys(self, doys): """Filter the Data Collection based on a list of days of the year (as integers). Args: doys: A List of days of the year [1..365] Return: A new Data Collection with filtered data """ _filt_values = [] _filt_datetimes...
java
@Nullable public static Path getCanonicalFile (@Nullable final Path aFile) throws IOException { return aFile == null ? null : aFile.toRealPath (); }
python
def dump_grammar(self, out=sys.stdout): """ Print grammar rules """ for rule in sorted(self.rule2name.items()): out.write("%s\n" % rule2str(rule[0])) return
python
def _get_lattice_parameters(lattice): """Return basis vector lengths Parameters ---------- lattice : array_like Basis vectors given as column vectors shape=(3, 3), dtype='double' Returns ------- ndarray, shape=(3,), dtype='double' """ return np.array(np.sqrt(np.do...
python
def _StubMethod(self, stub, method_descriptor, rpc_controller, request, callback): """The body of all service methods in the generated stub class. Args: stub: Stub instance. method_descriptor: Descriptor of the invoked method. rpc_controller: Rpc controller to execute the me...
java
@Path("/new") @POST public Response addRelationship( @PathParam(RestParam.PID) String pid, @QueryParam(RestParam.SUBJECT) String subject, @QueryParam(RestParam.PREDICATE) String predicate, @QueryParam(RestParam.OBJECT) ...
java
public <F> void updateProfileField(ProfileField<F, ?> field, F value) { if (field.isSingle()) { getResourceFactory() .getApiResource("/user/profile/" + field.getName()) .entity(new ProfileFieldSingleValue<F>(value), MediaType.APPLICATION_JSON_TYPE).put(); } else { getResourceFactory() .g...
java
protected void addHighLevelBindings(final DocWorkUnit workUnit) { workUnit.setProperty("name", workUnit.getName()); workUnit.setProperty("group", workUnit.getGroupName()); workUnit.setProperty("summary", workUnit.getSummary()); // Note that these properties are inserted into the top...
java
public <T> void addRepository(JpaRepositoryConfig<T> config) { Class<?> resourceClass = config.getResourceClass(); if (repositoryConfigurationMap.containsKey(resourceClass)) { throw new IllegalStateException(resourceClass.getName() + " is already registered"); } repositoryCon...
java
public SmartHandle permuteWith(SmartHandle target) { String[] argNames = target.signature().argNames(); return new SmartHandle(this, permuteWith(target.handle(), argNames)); }
java
public static void configNotPresent(Class<?> clazz,XML xml){ throw new MappingNotFoundException(MSG.INSTANCE.message(Constants.mappingNotFoundException1path, clazz.getSimpleName(),xml.getXmlPath())); }
java
public Node simplify() { Node simplifiedLeft = left.simplify(); Node simplifiedRight = right.simplify(); // Adding zero is pointless, the expression can be reduced to its other argument. if (simplifiedRight instanceof Constant && simplifiedRight.evaluate(NO_ARGS) == 0) { ...
java
public static JSONArray merge(final JSONArray src, final JSONArray dest) { return merge(src, dest, true); }
java
public boolean isEqualsInheritedFromObject() { ClassAccessor<? super T> i = this; while (i.getType() != Object.class) { if (i.declaresEquals() && !i.isEqualsAbstract()) { return false; } i = i.getSuperAccessor(); } return true; }
python
def super_lm_moe(): """Add mixture of experts with ~1B params.""" hparams = super_lm_base() hparams.layers = ( ("n,att,m,d,a," "n,moe,m,d,a,") * 4 + "n,ffn,d") hparams.moe_num_experts = 32 hparams.moe_hidden_sizes = "1024" return hparams
java
public static lbmetrictable_metric_binding[] get(nitro_service service, String metrictable) throws Exception{ lbmetrictable_metric_binding obj = new lbmetrictable_metric_binding(); obj.set_metrictable(metrictable); lbmetrictable_metric_binding response[] = (lbmetrictable_metric_binding[]) obj.get_resources(servic...
java
public static <R> Observable<R> ifThen(Func0<Boolean> condition, Observable<? extends R> then) { return ifThen(condition, then, Observable.<R> empty()); }
java
protected WebMarkupContainer newWebMarkupContainer(final String id, final IModel<GooglePlusShareModelBean> model) { final WebMarkupContainer googlePlusButton = ComponentFactory.newWebMarkupContainer(id, model); googlePlusButton.add(new AttributeModifier("class", model.getObject().getCssClass())); googlePlus...
java
public GetVerifiedDomainResponse getVerifiedDomain(GetVerifiedDomainRequest request) { checkNotNull(request, "object request should not be null."); assertStringNotNullOrEmpty(request.getDomainName(), "object domainName should not be null or empty"); InternalRequest internalRequest = ...
java
public VendorSpecificationExtensionModel associateAsVendorExtension(FileModel model, String localFileName) { String pathToDescriptor = model.getFilePath(); pathToDescriptor = StringUtils.removeEnd(pathToDescriptor, model.getFileName()); pathToDescriptor += localFileName; // now loo...
python
def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: ...
python
def parse(self, limit=None): """ Override Source.parse() Args: :param limit (int, optional) limit the number of rows processed Returns: :return None """ if limit is not None: LOG.info("Only parsing first %d rows", limit) ensemb...