language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _construct_filter_value(self, candidate, data): """ Construct and return a LDAP directory search filter value from the candidate identifier. Argument 'canidate' is a dictionary with one required key and two optional keys: key required value --...
java
public static void checkMatrixMultiplication() { DoubleMatrix A = new DoubleMatrix(new double[][]{ {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0} }); DoubleMatrix E = new DoubleMatrix(new double[][]{ {0.0...
java
public int dot(int[] other) { int dot = 0; for (int c = 0; c < used && indices[c] < other.length; c++) { if (indices[c] > Integer.MAX_VALUE) { break; } dot += values[c] * other[SafeCast.safeLongToInt(indices[c])]; } return dot; }
python
def tinsel(to_patch, module_name, decorator=mock_decorator): """ Decorator for simple in-place decorator mocking for tests Args: to_patch: the string path of the function to patch module_name: complete string path of the module to reload decorator (optional): replacement decorator. ...
python
def new_node(self): """Adds a new, blank node to the graph. Returns the node id of the new node.""" node_id = self.generate_node_id() node = {'id': node_id, 'edges': [], 'data': {} } self.nodes[node_id] = node self._num_nodes += ...
java
public NetworkInterface withPrivateIpAddresses(NetworkInterfacePrivateIpAddress... privateIpAddresses) { if (this.privateIpAddresses == null) { setPrivateIpAddresses(new com.amazonaws.internal.SdkInternalList<NetworkInterfacePrivateIpAddress>(privateIpAddresses.length)); } for (Netwo...
python
def assignees(self, assignee=None, resource_id=None): """Add an assignee to a Task GET: /v2/tasks/{uniqueId}/assignees GET: /v2/tasks/{uniqueId}/assignees/{assigneeId} POST: /v2/tasks/{uniqueId}/assignees/{assigneeId} DELETE: /v2/tasks/{uniqueId}/assignees/{assigneeId} ...
python
def _strand_flag(data): """ 0: unstranded 1: stranded 2: reverse stranded """ strand_flag = {"unstranded": "0", "firststrand": "2", "secondstrand": "1"} stranded = dd.get_strandedness(data) assert stranded in strand_flag, ("%s is not a valid strandedness va...
java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { InstanceInfo myInfo = ApplicationInfoManager.getInstance().getInfo(); InstanceStatus status = myInfo.getStatus(); if (status != InstanceStatus...
python
def content_type(self): """ Get the Content-Type option of a response. :return: the Content-Type value or 0 if not specified by the response """ value = 0 for option in self.options: if option.number == defines.OptionRegistry.CONTENT_TYPE.number: ...
java
public static AnnotationTypeBuilder getInstance(Context context, TypeElement annotationTypeDoc, AnnotationTypeWriter writer) { return new AnnotationTypeBuilder(context, annotationTypeDoc, writer); }
python
def count(self, *args, **kw): """ Counts whether the memoized value has already been set (a hit) or not (a miss). """ obj = args[0] if self.method_name in obj._memo: self.hit = self.hit + 1 else: self.miss = self.miss + 1
java
@Override public void declareOutputFields(OutputFieldsDeclarer ofd) { if (this.outputTypes == null) { throw new FailedException("outputTypes cannot be null"); } for (Map.Entry<String, List<String>> outputEventType : this.outputTypes.entrySet()) { List<String> fields =...
java
public static <T> String getInstanceVariables(Class<T> clas) { StringBuffer fieldsString = new StringBuffer(); Field[] fields = clas.getDeclaredFields(); int i = 0; for (Field field : fields) { if (i++ > 0) { fieldsString.append(JK.CSV_SEPARATOR); } fieldsString.append(field.getName()); ...
python
def serialize_list(self, data): """ Given a collection of data (``objects`` or ``dicts``), serializes them. :param data: The collection of items to serialize :type data: list or iterable :returns: The serialized body :rtype: string """ if data is None: ...
python
def heightmap_has_land_on_border(hm: np.ndarray, waterlevel: float) -> bool: """Returns True if the map edges are below ``waterlevel``, otherwise False. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. waterLevel (float): The water level to use. Returns: ...
java
public void init(Object parent, Object record) { super.init(parent, record); record = this.getFieldList(); // Created/set in JBaseScreen.init this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); FieldTable table = ((FieldList)record).getTable(); CalendarModel model = this...
python
def run_primlist(self, primlist, skip_remaining=False): '''Runs runs from a primlist. Parameters ---------- primlist : string Filename of primlist. skip_remaining : bool If True, skip remaining runs, if a run does not exit with status FINISHED. N...
python
def _setup_name_tables(): """ Ensures the scan code/virtual key code/name translation tables are filled. """ with tables_lock: if to_name: return # Go through every possible scan code, and map them to virtual key codes. # Then vice-versa. all_scan_codes = [(sc, user3...
java
@Override public Double exp2(Double arg1) { if (arg1 == null) { return Double.NaN; } else { return Math.exp(arg1); } }
java
@Override public RebootInstanceResult rebootInstance(RebootInstanceRequest request) { request = beforeClientExecution(request); return executeRebootInstance(request); }
java
public final void release(TotalOrderRemoteTransactionState state) { TotalOrderLatch synchronizedBlock = state.getTransactionSynchronizedBlock(); if (synchronizedBlock == null) { //already released! return; } Collection<Object> lockedKeys = state.getLockedKeys(); synchroni...
java
@Override public DescribeTagsResult describeTags(DescribeTagsRequest request) { request = beforeClientExecution(request); return executeDescribeTags(request); }
python
def iterator(n: Union[Node, CompatNodeIterator, dict], order: TreeOrder = TreeOrder.PRE_ORDER) -> CompatNodeIterator: """ This function has the same signature as the pre-v3 iterator() call returning a compatibility CompatNodeIterator. """ if isinstance(n, CompatNodeIterator): return...
java
@VisibleForTesting protected int stringToInt(final String exp) { final Integer value = fieldConstraints.getStringMappingValue(exp); if (value != null) { return value; } else { try { return Integer.parseInt(exp); } catch (final NumberFormatE...
java
public void put(GVRAndroidResource androidResource, T resource) { Log.d(TAG, "put resource %s to cache", androidResource); super.put(androidResource, resource); }
python
def verify_cert(self): ''' Checks that the provided cert and key are valid and usable ''' log.debug('Verifying the %s certificate, keyfile: %s', self.certificate, self.keyfile) try: ssl.create_default_context().load_cert_chain(self.certificate, keyfi...
java
public TimeOfDay withMillisOfSecond(int millis) { int[] newValues = getValues(); newValues = getChronology().millisOfSecond().set(this, MILLIS_OF_SECOND, newValues, millis); return new TimeOfDay(this, newValues); }
java
public static double simpleMovingAverageQuick(double Yt, double YtminusN, double Ft, int N) { double SMA=(Yt-YtminusN)/N+Ft; return SMA; }
python
def script_to_hex(script): """ Parse the string representation of a script and return the hex version. Example: "OP_DUP OP_HASH160 c629...a6db OP_EQUALVERIFY OP_CHECKSIG" """ hex_script = '' parts = script.split(' ') for part in parts: if part[0:3] == 'OP_': try: ...
java
public SparseMatrix toSparseMatrix() { int[] pos = new int[numColumns]; int[] colIndex = new int[numColumns + 1]; for (int i = 0; i < numColumns; i++) { colIndex[i + 1] = colIndex[i] + colSize[i]; } int nrows = size(); int[] rowIndex = new int[n]; dou...
java
public List<String> ls(String path, final Filter<LsEntry> filter) { final List<String> fileNames = new ArrayList<>(); try { channel.ls(path, new LsEntrySelector() { @Override public int select(LsEntry entry) { String fileName = entry.getFilename(); if (false == StrUtil.equals(".", fileNa...
java
public static String get(String extension, String defaultCt) { final String mime = contentTypes.get(extension); return mime == null ? defaultCt : mime; }
python
def import_and_wrap_deprecated(module_name, module_dict, warn_import=True): """ Usage: import_and_wrap_deprecated('conda.common.connection', locals()) # looks for conda.common.connection.__all__ """ if warn_import: deprecated_import(module_name) from importlib import import_...
python
async def communicate(self, data_id=None, run_sync=False, save_settings=True): """Scan database for resolving Data objects and process them. This is submitted as a task to the manager's channel workers. :param data_id: Optional id of Data object which (+ its children) should be pro...
java
public void forceRemovalInRegister(ArrayList<Node> ping) { for (Node pingNode : ping) { InvocationContext ctx = balancerRunner.getInvocationContext( pingNode.getProperties().get("version")); //ctx.nodes.remove(pingNode); String instanceId = pingNode.getPro...
python
def _handle_usecols(self, columns, usecols_key): """ Sets self._col_indices usecols_key is used if there are string usecols. """ if self.usecols is not None: if callable(self.usecols): col_indices = _evaluate_usecols(self.usecols, usecols_key) ...
python
def get_post_reference_section_title_patterns(): """Return a list of compiled regex patterns used to search for the title of the section after the reference section in a full-text document. @return: (list) of compiled regex patterns. """ compiled_patterns = [] thead = ur'^\s*([\{\(\<\[]?\s...
java
private Set<String> getGroupsByMember(DirContext context, String callerDn, String groupSearchBase, String groupSearchFilter) { String groupNameAttribute = idStoreDefinition.getGroupNameAttribute(); String[] attrIds = { groupNameAttribute }; long limit = Long.valueOf(idStoreDefinition.getMaxRes...
python
def text_ui(self): """ Start Text UI main loop """ self.logger.info("Starting command line interface") self.help() try: self.ipython_ui() except ImportError: self.fallback_ui() self.system.cleanup()
python
def is_iterable(maybe_iter, unless=(string_types, dict)): """ Return whether ``maybe_iter`` is an iterable, unless it's an instance of one of the base class, or tuple of base classes, given in ``unless``. Example:: >>> is_iterable('foo') False >>> is_iterable(['foo']) True ...
java
private boolean patternMatchesAttributeValue(final Object value) { val matcher = value.toString(); LOGGER.trace("Compiling a pattern matcher for [{}]", matcher); return this.compiledPattern.matcher(matcher).matches(); }
python
def adjust_whitespace(text): """remove the left-whitespace margin of a block of Python code.""" state = [False, False] (backslashed, triplequoted) = (0, 1) def in_multi_line(line): start_state = (state[backslashed] or state[triplequoted]) if re.search(r"\\$", line): state[...
java
@RequestMapping(value = "/api/history/{profileIdentifier}/{id}", method = RequestMethod.GET) public @ResponseBody HashMap<String, Object> getHistoryForId(Model mode, @PathVariable String profileIdentifier, @PathVariable Integer id, @RequestParam(value = "format", ...
python
def catch_exceptions(*exceptions): """Catch all exceptions provided as arguments, and raise CloudApiException instead.""" def wrap(fn): @functools.wraps(fn) def wrapped_f(*args, **kwargs): try: return fn(*args, **kwargs) except exceptions: ...
java
private boolean checkDomainRanges(SortedSet<String> domainRanges) { if ( (domainRanges == null) || (domainRanges.size() == 0)){ return true; } for ( String d : domainRanges){ //System.out.println("domainRange: >" + d +"< " + d.length()); if ( (d != null) && (d.length() >0)){ return false; } } ...
python
def unpackfile(filename, destdir): """Unpack a mar or exe into destdir""" if filename.endswith(".mar"): return unpackmar(filename, destdir) elif filename.endswith(".exe"): return unpackexe(filename, destdir) elif filename.endswith(".tar") or filename.endswith(".tar.gz") \ or ...
java
public void setProperties(Point3d a, Point3d b, DoubleProperty radius1) { this.medial1.setProperties(a.xProperty, a.yProperty, a.zProperty); this.medial2.setProperties(b.xProperty, b.yProperty, b.zProperty); this.radiusProperty = radius1; ensureAIsLowerPoint(); }
python
def stop(name, runas=None): ''' Stop a launchd service. Raises an error if the service fails to stop .. note:: Though ``service.stop`` will unload a service in macOS, the service will start on next boot unless it is disabled. Use ``service.disable`` to disable the service :par...
python
def parse_seqres(self, pdb): """Parse the SEQRES entries into the object""" seqresre = re.compile("SEQRES") seqreslines = [line for line in pdb.lines if seqresre.match(line)] for line in seqreslines: chain = line[11] resnames = line[19:70].strip() self.setdefault(chain, ...
java
public void applyWorkaround205(String appName, List<NativeLauncher> secondaryLaunchers, Map<String, Object> params) { // to workaround, we are gathering the fixed versions of the previous executed "app-bundler" // and assume they all are existing Set<File> filenameFixedConfigFiles = new HashSet<...
java
public List<JAXBElement<Object>> get_GenericApplicationPropertyOfAddress() { if (_GenericApplicationPropertyOfAddress == null) { _GenericApplicationPropertyOfAddress = new ArrayList<JAXBElement<Object>>(); } return this._GenericApplicationPropertyOfAddress; }
python
def populate(self, priority, address, rtr, data): """ -DB1 last bit = local_control -DB1 bit 2+3 = status_mode -DB1 bit 4 = auto send -DB1 bit 5+6+7 = mode -DB1 bit 8 = cool -DB2 = program ...
python
def work(self): """ Use a blocking <sleep> call to periodically trigger a signal. """ import time for val in range(200): time.sleep(0.1) self.sigUpdate.emit(val + 1)
python
def _call_shallow_validation(self, value): """Call the initial set of _validate() methods. This is similar to _call_to_base_type() except it only calls those _validate() methods that can be called without needing to call _to_base_type(). An example: suppose the class hierarchy is A -> B -> C -> ...
python
def assoc_indexed(cls, ops, kwargs): r"""Flatten nested indexed structures while pulling out possible prefactors For example, for an :class:`.IndexedSum`: .. math:: \sum_j \left( a \sum_i \dots \right) = a \sum_{j, i} \dots """ from qnet.algebra.core.abstract_quantum_algebra import ( ...
java
public final void synpred25_InternalPureXbase_fragment() throws RecognitionException { // InternalPureXbase.g:2555:8: ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) ) // InternalPureXbase.g:2555:9: ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJ...
python
def _compute_acq(self,x): """ Integrated GP-Lower Confidence Bound """ means, stds = self.model.predict(x) f_acqu = 0 for m,s in zip(means, stds): f_acqu += -m + self.exploration_weight * s return f_acqu/(len(means))
java
public void symm2x2_fast( double a11 , double a12, double a22 ) { // double p = (a11 - a22)*0.5; // double r = Math.sqrt(p*p + a12*a12); // // value0.real = a22 + a12*a12/(r-p); // value1.real = a22 - a12*a12/(r+p); // } // // public void symm2x2_std( double a11 , double a12, doubl...
java
void endNavigation() { NavigationTelemetry.getInstance().endSession(); routeFetcher.clearListeners(); locationUpdater.removeLocationUpdates(); notificationProvider.shutdown(getApplication()); thread.quit(); }
java
public boolean lock(boolean shared, boolean block) { if (shared && !_canRead) { // Invalid request for a shared "read" lock on a write only stream. return false; } if (!shared && !_canWrite) { // Invalid request for an exclusive "write" lock on a read only stream. return false; ...
python
def payload_body(req): """ A generator that will include the sha256 signature of the request's body in the JWT payload. This is only done if the request could have a body: if the method is POST or PUT. >>> auth = JWTAuth('secret') >>> auth.add_field('body', payload_body) """ to_hash = ...
java
public WSEJBEndpointManager createWebServiceEndpointManager(J2EEName j2eeName, Class<?> provider, // d492780, F87951 Method[] methods) throws EJBException, EJBConfigurationException { ...
python
def get_chacra_repo(shaman_url): """ From a Shaman URL, get the chacra url for a repository, read the contents that point to the repo and return it as a string. """ shaman_response = get_request(shaman_url) chacra_url = shaman_response.geturl() chacra_response = get_request(chacra_url) ...
python
def delete_lifecycle_configuration(Bucket, region=None, key=None, keyid=None, profile=None): ''' Delete the lifecycle configuration for the given bucket Returns {deleted: true} if Lifecycle was deleted and returns {deleted: False} if Lifecycle was not deleted. CLI Example: .. code-...
java
private TypeOfApplication.Enum getTypeOfApplication() { String proposalTypeCode = pdDoc.getDevelopmentProposal().getProposalType().getCode(); TypeOfApplication.Enum typeOfApplication = null; if (proposalTypeCode != null) { if (s2SConfigurationService.getValuesFromCommaSeparatedParam(...
python
def reraise(additional_msg): """Reraise an exception with an additional message.""" exc_type, exc_value, exc_traceback = sys.exc_info() msg = str(exc_value) + "\n" + additional_msg six.reraise(exc_type, exc_type(msg), exc_traceback)
python
def align(fastq_file, pair_file, index_dir, names, align_dir, data): """Perform piped alignment of fastq input files, generating sorted, deduplicated BAM. Pipes in input, handling paired and split inputs, using interleaving magic from: https://biowize.wordpress.com/2015/03/26/the-fastest-darn-fastq-decoupl...
java
@Override public void cacheResult(CommerceCountry commerceCountry) { entityCache.putResult(CommerceCountryModelImpl.ENTITY_CACHE_ENABLED, CommerceCountryImpl.class, commerceCountry.getPrimaryKey(), commerceCountry); finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G, new Object[] { commerceCountry.getUuid...
java
public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; if(paintBorder != null) paintBorder.setStrokeWidth(borderWidth); requestLayout(); invalidate(); }
java
@Override public void serializeCollection(BinderContext context, SerializerWrapper serializerWrapper, Collection<E> collection) throws Exception { switch (context.getSupportedFormat()) { case XML: { throw (new KriptonRuntimeException(context.getSupportedFormat() + " context does not support direct collection pe...
java
public String getString() { final int len = getVInt(); final byte[] utf = new byte[len]; System.arraycopy(buf, bufPosition, utf, 0, utf.length); bufPosition += utf.length; return new String(utf, 0, len, charsetUTF8); }
python
def to_env_vars(self): """Environment variable representation of the training environment Returns: dict: an instance of dictionary """ env = { 'hosts': self.hosts, 'network_interface_name': self.network_interface_name, 'hps': self.hyperparameters, 'u...
java
public static void validatePath(String path) throws InvalidPathException { boolean invalid = (path == null || path.isEmpty()); if (!OSUtils.isWindows()) { invalid = (invalid || !path.startsWith(AlluxioURI.SEPARATOR)); } if (invalid) { throw new InvalidPathException(ExceptionMessage.PATH_INV...
python
def _write_info(self): """ Write API Info file """ self.write(destination=self.output_directory, filename="vspk/SdkInfo.cs", template_name="sdkinfo.cs.tpl", version=self.api_version, product_accronym=self._product_accron...
python
def attach_template(self, _template, _key, **unbound_var_values): """Attaches the template to this such that _key=this layer. Note: names were chosen to avoid conflicts with any likely unbound_var keys. Args: _template: The template to construct. _key: The key that this layer should replace. ...
python
def search_allowed_users_for_issue(self, user, issueKey=None, projectKey=None, startAt=0, maxResults=50): """Get a list of user Resources that match a username string and have browse permission for the issue or project. :param user: a string to match usernames against. :type user: str :...
java
public List<String> getAllKeys(final int limit) { final List<String> keyList = new ArrayList<String>(limit); byte[] array = new byte[EVCacheConfig.getInstance().getDynamicIntProperty(appName + ".all.keys.reader.buffer.size.bytes", 4*1024*1024).get()]; final int waitInSec = EVCacheConfig.getInsta...
java
public static int getQuarter(int packedDate) { if (packedDate == DateColumnType.missingValueIndicator()) { return -1; } Month month = getMonth(packedDate); switch (month) { case JANUARY: case FEBRUARY: case MARCH: return 1; ...
java
public static <T> Filter<T> xor(Filter<T> filterOne, Filter<T> filterTwo) { return compose(filterOne, LogicalOperator.XOR, filterTwo); }
python
def hooks(self, project): """ Look up the urls we need to post to""" return self.get_queryset().filter( Q(project=None) | Q(project=project) ).distinct('url')
java
public TtsVoiceSenderResult send(String nationCode, String phoneNumber, int templateId, ArrayList<String> params, int playtimes, String ext) throws HTTPException, JSONException, IOException { long random = SmsSenderUtil.getRandom(); long now = SmsSenderUtil.getCurrentTime();...
python
def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=25): ''' Run a cone search of the GALEX archive ''' self.magnitudelimit = magnitudelimit # run the query self.speak('querying GALEX, centered on {} with radius {}'.format(center, radius, magnitudelimit)) ...
java
public static INDArray asExampleMatrix(Window window, Word2Vec vec) { INDArray[] data = new INDArray[window.getWords().size()]; for (int i = 0; i < data.length; i++) { data[i] = vec.getWordVectorMatrix(window.getWord(i)); // if there's null elements if (data[i] == nu...
python
def passphrase_entropy(amount_w: int, entropy_w: Union[int, float], entropy_n: Union[int, float], amount_n: int) -> float: """Calculate the entropy of a passphrase with given words and numbers.""" if not isinstance(amount_w, int): rais...
java
public final void setNextButtonText(@NonNull final CharSequence text) { Condition.INSTANCE.ensureNotNull(text, "The text may not be null"); Condition.INSTANCE.ensureNotEmpty(text, "The text may not be empty"); this.nextButtonText = text; adaptNextButtonText(); }
python
def ensure_row_dep_constraint( self, M_c, T, X_L, X_D, row1, row2, dependent=True, wrt=None, max_iter=100, force=False): """Ensures dependencey or indepdendency between rows with respect to columns.""" X_L_list, X_D_list, was_multistate = su.ensure_multistate(X_L, X_D) ...
java
@SuppressWarnings("unused") public static List<String> internListOf(Object... objects) { if (objects == null || objects.length == 0) { return Collections.emptyList(); } List<String> strings = new ArrayList<>(objects.length); for (Object object : objects) { str...
java
private void printNodeTypeDeclaration(NodeTypeData nodeTypeData, OutputStreamWriter out) throws RepositoryException, IOException { /** Print name */ out.write("[" + qNameToString(nodeTypeData.getName()) + "] "); /** Print supertypes */ InternalQName[] superTypes = nodeTypeData.getDecla...
java
@SuppressWarnings("unchecked") public static List<HierarchicalConfiguration> getRequiredConfigurationsAt(HierarchicalConfiguration config, String key) throws DeployerConfigurationException { List<HierarchicalConfiguration>...
java
public <E> void delete(Class<E> entityClass, DatastoreKey parentKey, long id) { try { EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); Key nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); nativeWriter.delete(nativeKey); } catch...
java
public void partialDeserialize(TBase<?,?> base, DBObject dbObject, TFieldIdEnum... fieldIds) throws TException { try { protocol_.setDBOject(dbObject); protocol_.setBaseObject( base ); protocol_.setFieldIdsFilter(base, fieldIds); base.read(protocol_); } finally { protocol_.reset();...
python
def _slr_build_parser_table(productionset): """SLR method to build parser table""" result = ParserTable() statesset = build_states_sets(productionset) for itemindex, itemset in enumerate(statesset): LOG.debug("_slr_build_parser_table: Evaluating itemset:" + str(itemset)) for symbol in pr...
python
def construct_scalar(self, node): ''' Verify integers and pass them in correctly is they are declared as octal ''' if node.tag == 'tag:yaml.org,2002:int': if node.value == '0': pass elif node.value.startswith('0') and not node.value.startsw...
java
private void reply(final String response, final boolean error, final String errorMessage, final String stackTrace, final String statusCode, final int statusCodeInt, Map<String, List<String>> responseHeaders) { if (!sentReply) { // must update sentReply first to a...
java
public Matrix3 setToTransform (IVector translation, double rotation, double scale) { return setToRotation(rotation).set(m00 * scale, m10 * scale, translation.x(), m01 * scale, m11 * scale, translation.y(), 0f, 0f, 1f); }
java
private void generateLicenses(final Metadata m, final Element e) { for (final License license : m.getLicenses()) { final Element licenseElement = new Element("license", NS); addNotNullAttribute(licenseElement, "type", license.getType()); addNotNullAttribute(licenseElement, "h...
python
def _make_clusters(self, matrix, num_clusters_per_roi, metric): """clusters a given matrix by into specified number of clusters according to given metric""" from scipy.cluster.hierarchy import fclusterdata # maxclust needed to ensure t is interpreted as # clusters in heirarchical clustering ...
python
def get_labels(): """ Labels to make Cannon model spectra """ cannon_teff = data['cannon_teff_2'] cannon_logg = data['cannon_logg_2'] cannon_m_h = data['cannon_m_h'] cannon_alpha_m = data['cannon_alpha_m'] cannon_a_k = data['cannon_a_k'] labels = np.vstack( (cannon_teff, cannon_l...
java
public ApiResponse<List<MarketHistoryResponse>> getMarketsRegionIdHistoryWithHttpInfo(Integer regionId, Integer typeId, String datasource, String ifNoneMatch) throws ApiException { com.squareup.okhttp.Call call = getMarketsRegionIdHistoryValidateBeforeCall(regionId, typeId, datasource, ...