language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def load_eggs(entry_point_name): """Loader that loads any eggs in `sys.path`.""" def _load_eggs(env): distributions, errors = working_set.find_plugins( pkg_resources.Environment() ) for dist in distributions: if dist not in working_set: env.log.deb...
python
def _average_genome_coverage(data, bam_file): """Quickly calculate average coverage for whole genome files using indices. Includes all reads, with duplicates. Uses sampling of 10M reads. """ total = sum([c.size for c in ref.file_contigs(dd.get_ref_file(data), data["config"])]) read_counts = sum(x.a...
java
private void addObjectIfNotFound(Object obj, Vector v) { int n = v.size(); boolean addIt = true; for (int i = 0; i < n; i++) { if (v.elementAt(i) == obj) { addIt = false; break; } } if (addIt) { v.addElement(obj); } }
java
final void addTaskAndWakeup(Runnable task) { // in this loop we are going to either send the task to the owner // or store the delayed task to be picked up as soon as the migration // completes for (; ; ) { NioThread localOwner = owner; if (localOwner != null) { ...
python
def build_configuration(self): """Parse the haproxy config file Raises: Exception: when there are unsupported section Returns: config.Configuration: haproxy config object """ configuration = config.Configuration() pegtree = pegnode.parse(self.fil...
java
private URL getRequiredUrlParameter(String keyword, Map<String, String> parms) { String urlString = getRequiredParameter(keyword, parms); try { return new URL(urlString); } catch (MalformedURLException e) { throw new ValidatorProces...
python
def match_replace_regex(regex, src_namespace, dest_namespace): """Return the new mapped namespace if the src_namespace matches the regex.""" match = regex.match(src_namespace) if match: return dest_namespace.replace("*", match.group(1)) return None
python
def highest_expr_genes( adata, n_top=30, show=None, save=None, ax=None, gene_symbols=None, **kwds ): """\ Fraction of counts assigned to each gene over all cells. Computes, for each gene, the fraction of counts assigned to that gene within a cell. The `n_top` genes with the highest ...
java
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); WebOperation operation = null; try{ operation = getOperation(request); }catch (WebOperatio...
python
def safe_eval(source, *args, **kwargs): """ eval without import """ source = source.replace('import', '') # import is not allowed return eval(source, *args, **kwargs)
java
public static ExtensionElement parseExtensionElement(String elementName, String namespace, XmlPullParser parser, XmlEnvironment outerXmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { ParserUtils.assertAtStartTag(parser); // See if a provider is regis...
python
def check_calling_sequence(name, function_name, function, possible_variables): """ Check the calling sequence for the function looking for the variables specified. One or more of the variables can be in the calling sequence. Note that the order of the variables will be enforced. ...
java
public void decode(AsnInputStream ais) throws ParseException { this.dialogTermitationPermission = false; this.originatingTransactionId = null; this.dp = null; this.component = null; try { if (ais.getTag() == TCQueryMessage._TAG_QUERY_WITH_PERM) dialog...
java
@Override public void releaseJsMessage() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(this, tc, "releaseJsMessage"); } // We check to see if it is safe to remove a non persistent msg now. i.e. the asynchronous // gap betwee...
java
protected void computePsiDataPsiGradient(GrayF32 image1, GrayF32 image2, GrayF32 deriv1x, GrayF32 deriv1y, GrayF32 deriv2x, GrayF32 deriv2y, GrayF32 deriv2xx, GrayF32 deriv2yy, GrayF32 deriv2xy, GrayF32 du, GrayF32 dv, GrayF32 psiData, GrayF32 psiGradient ) { ...
java
public static Structure readStructure(String pdbId, int bioAssemblyId) { // pre-computed files use lower case PDB IDs pdbId = pdbId.toLowerCase(); // we just need this to track where to store PDB files // this checks the PDB_DIR property (and uses a tmp location if not set) AtomCache cache = new AtomCache(...
java
public static CommerceWarehouseItem fetchByCPI_CPIU_First(long CProductId, String CPInstanceUuid, OrderByComparator<CommerceWarehouseItem> orderByComparator) { return getPersistence() .fetchByCPI_CPIU_First(CProductId, CPInstanceUuid, orderByComparator); }
java
private static RuleList parseRuleChain(String description) throws ParseException { RuleList result = new RuleList(); // remove trailing ; if (description.endsWith(";")) { description = description.substring(0,description.length()-1); } String[] rules = SEM...
java
protected void addCommand(String label, String help, Command cmd, boolean needsAuth) { commands.put(label.toUpperCase(), new CommandInfo(cmd, help, needsAuth)); }
java
@Override public boolean isDeepMemberOf(IEntityGroup group) throws GroupsException { return isMemberOf(group) ? true : group.deepContains(this); }
python
async def get_initial_offset_async(self): # throws InterruptedException, ExecutionException """ Gets the initial offset for processing the partition. :rtype: str """ _logger.info("Calling user-provided initial offset provider %r %r", self.host.guid, self.par...
java
private Class<?> resolveClassWithCL(String name) throws ClassNotFoundException { SecurityManager security = System.getSecurityManager(); if (security != null) { return Class.forName(name, false, getClassLoader(thisClass)); } // The platform classloader is null if we failed t...
python
def get_html(self): """ Downloads HTML content of page given the page_url""" if self.use_ghost: self.url = urljoin("http://", self.url) import selenium import selenium.webdriver driver = selenium.webdriver.PhantomJS( service_log_path=os.pa...
python
def check(): """ Checks the long description. """ dist_path = Path(DIST_PATH) if not dist_path.exists() or not list(dist_path.glob('*')): print("No distribution files found. Please run 'build' command first") return subprocess.check_call(['twine', 'check', 'dist/*'])
python
def _trade(self, event): "内部函数" print('==================================market enging: trade') print(self.order_handler.order_queue.pending) print('==================================') self.order_handler._trade() print('done')
java
public Properties appendProperties(Properties properties, File configFile) { if(!configFile.exists()) { return properties; } return reader.appendProperties(properties, configFile, log); }
java
public static byte[] serialize(final Serializable object) { val outBytes = new ByteArrayOutputStream(); serialize(object, outBytes); return outBytes.toByteArray(); }
python
def find_module_defining_flag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module ...
java
private void computeCBLOFs(Relation<O> relation, NumberVectorDistanceFunction<? super O> distance, WritableDoubleDataStore cblofs, DoubleMinMax cblofMinMax, List<? extends Cluster<MeanModel>> largeClusters, List<? extends Cluster<MeanModel>> smallClusters) { List<NumberVector> largeClusterMeans = new ArrayList<>(la...
java
@Override public boolean onTouchEvent(MotionEvent ev) { if (null != mGestureDetector) { return mGestureDetector.onTouchEvent(ev); } else { return super.onTouchEvent(ev); } }
python
def create_gemini_db_orig(gemini_vcf, data, gemini_db=None, ped_file=None): """Original GEMINI specific data loader, only works with hg19/GRCh37. """ if not gemini_db: gemini_db = "%s.db" % utils.splitext_plus(gemini_vcf)[0] if not utils.file_exists(gemini_db): if not vcfutils.vcf_has_va...
python
def set_handler(self, handler): """ set the callback processing object to be used by the receiving thread after receiving the data.User should set their own callback object setting in order to achieve event driven. :param handler:the object in callback handler base :return: ret_e...
java
public static Project readProject(String argument) throws IOException { String projectFileName = argument; File projectFile = new File(projectFileName); if (projectFileName.endsWith(".xml") || projectFileName.endsWith(".fbp")) { try { return Project.readXML(projectF...
python
def ACC_calc(TP, TN, FP, FN): """ Calculate accuracy. :param TP: true positive :type TP : int :param TN: true negative :type TN : int :param FP: false positive :type FP : int :param FN: false negative :type FN : int :return: accuracy as float """ try: result ...
python
def _convert_reftype_to_jaeger_reftype(ref): """Convert opencensus reference types to jaeger reference types.""" if ref == link_module.Type.CHILD_LINKED_SPAN: return jaeger.SpanRefType.CHILD_OF if ref == link_module.Type.PARENT_LINKED_SPAN: return jaeger.SpanRefType.FOLLOWS_FROM return N...
python
def rm_filesystems(name, device, config='/etc/filesystems'): ''' .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg ''' modified = False view_lines = [] if 'AIX' not in ...
java
public static String mask(WildcardPattern pattern, CharSequence input) { char[] tokens = pattern.getTokens(); int[] types = pattern.getTypes(); char separator = pattern.getSeparator(); int tlen = tokens.length; int clen = input.length(); char[] masks = new char[clen]; ...
python
def tsv_import(self, xsv_source, encoding="UTF-8", transforms=None, row_class=DataObject, **kwargs): """Imports the contents of a tab-separated data file into this table. @param xsv_source: tab-separated data file - if a string is given, the file with that name will be opened, read, an...
python
def target_heating_level(self): """Return target heating level.""" try: if self.side == 'left': level = self.device.device_data['leftTargetHeatingLevel'] elif self.side == 'right': level = self.device.device_data['rightTargetHeatingLevel'] ...
java
public void initialize(Language language, DocumentType typeToProcess, OutputType outputType, String configPath, POSTagger posTagger) { initialize(language, typeToProcess, outputType, configPath, posTagger, false); }
java
public static Object getAs(Map<String,Object> properties, String strKey, Class<?> classData, Object objDefault) { if (properties == null) return objDefault; Object objData = properties.get(strKey); try { return Converter.convertObjectToDatatype(objData, classData, obj...
java
public TransportApiResult<List<FareProduct>> getFareProducts(FareProductQueryOptions options) { if (options == null) { options = FareProductQueryOptions.defaultQueryOptions(); } return TransportApiClientCalls.getFareProducts(tokenComponent, settings, options); }
java
@Override public void doFilter(ServletRequest inRequest, ServletResponse inResponse, FilterChain inChain) throws IOException, ServletException { HttpServletRequest servletRequest = (HttpServletRequest) inRequest; Principal principal = servletRequest.getUserPrincipal(); HttpSession session = ...
python
def load_module(self, filename): '''Load a benchmark module from file''' if not isinstance(filename, string_types): return filename basename = os.path.splitext(os.path.basename(filename))[0] basename = basename.replace('.bench', '') modulename = 'benchmarks.{0}'.forma...
java
public Observable<KeyBundle> createKeyAsync(String vaultBaseUrl, String keyName, JsonWebKeyType kty) { return createKeyWithServiceResponseAsync(vaultBaseUrl, keyName, kty).map(new Func1<ServiceResponse<KeyBundle>, KeyBundle>() { @Override public KeyBundle call(ServiceResponse<KeyBundle> ...
java
public void marshall(DecisionTaskCompletedEventAttributes decisionTaskCompletedEventAttributes, ProtocolMarshaller protocolMarshaller) { if (decisionTaskCompletedEventAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { ...
java
@Override public <K, V> Cache<K, V> getCache(String name) { final org.apache.shiro.cache.Cache<K, V> shiroCache = SHIRO_CACHE_MANAGER.getCache(name); return new ShiroCache<K, V>(shiroCache); }
java
private void setCurrentItemShowing(int index, boolean animateCircle, boolean delayLabelAnimate, boolean announce) { mTimePicker.setCurrentItemShowing(index, animateCircle); TextView labelToAnimate; switch(index) { case HOUR_INDEX: int hours = mTimePicker....
java
public boolean fbml_refreshImgSrc(URL imageUrl) throws FacebookException, IOException { return extractBoolean(this.callMethod(FacebookMethod.FBML_REFRESH_IMG_SRC, new Pair<String, CharSequence>("url", ...
java
private ObjectMapper createObjectMapperWithRootUnWrap() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.addHandler(new CustomDeserializationProblemHandler()); mapper.registerModule(new JodaModule()); ...
java
public static LongGene of(final long min, final long max) { return of(nextLong(getRandom(), min, max), min, max); }
java
public double approximationDistancePAA(double[] ts, int winSize, int paaSize, double normThreshold) throws Exception { double resDistance = 0d; int windowCounter = 0; double pointsPerWindow = (double) winSize / (double) paaSize; for (int i = 0; i < ts.length - winSize + 1; i++) { ...
python
def disable_key(key_id, region=None, key=None, keyid=None, profile=None): ''' Mark key as disabled. CLI example:: salt myminion boto_kms.disable_key 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: key = conn.disable_key(...
python
def create(cls, name, iplist=None, comment=None): """ Create an IP List. It is also possible to add entries by supplying a list of IPs/networks, although this is optional. You can also use upload/download to add to the iplist. :param str name: name of ip list :param list...
python
def convolve_hrf(stimfunction, tr_duration, hrf_type='double_gamma', scale_function=True, temporal_resolution=100.0, ): """ Convolve the specified hrf with the timecourse. The output of this is a downsampled convolution of the ...
java
public PdfTemplate createTemplateWithBarcode(PdfContentByte cb, Color barColor, Color textColor) { PdfTemplate tp = cb.createTemplate(0, 0); Rectangle rect = placeBarcode(tp, barColor, textColor); tp.setBoundingBox(rect); return tp; }
python
def from_user_config(cls): """ Initialize the :class:`TaskManager` from the YAML file 'manager.yaml'. Search first in the working directory and then in the AbiPy configuration directory. Raises: RuntimeError if file is not found. """ global _USER_CONFIG_TASKM...
python
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> form...
java
public List<FeatureTileLink> queryForFeatureTableName( String featureTableName) { List<FeatureTileLink> results = null; try { results = queryForEq(FeatureTileLink.COLUMN_FEATURE_TABLE_NAME, featureTableName); } catch (SQLException e) { throw new GeoPackageException( "Failed to query for Feature...
python
def present( name, attributes, region=None, key=None, keyid=None, profile=None): ''' Ensure the cloudwatch alarm exists. name Name of the alarm attributes A dict of key/value cloudwatch alarm attributes. region Region to conn...
java
public Request sendRequest(String requestData, RequestCallback callback) throws RequestException { StringValidator.throwIfNull("callback", callback); return doSend(requestData, callback); }
python
def componentSelection(self, comp): """Toggles the selection of *comp* from the currently active parameter""" # current row which is selected in auto parameters to all component selection to indexes = self.selectedIndexes() index = indexes[0] self.model().toggleSelection(index, c...
java
public static int [] createRemapTable(String [] controlFields, String [] remappedFields) { // create hash map with remapped fields HashMap<String,Integer> map = new HashMap<String, Integer>(); for (int index = 0; index < remappedFields.length; index++) { String field = remappedFields...
java
private void removeField(OpcodeStack.Item itm) { XField xf = itm.getXField(); if (xf != null) { mapFields.remove(xf.getName()); xf = (XField) itm.getUserValue(); if (xf != null) { mapFields.remove(xf.getName()); } if (mapFields....
python
def unwrap(self, value, session=None): ''' Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value unwrapped using ``DictField.value_type`` ''' self.validate_unwrap(value) ret = {} for k, v in value.items(): ret[k] ...
java
public Class<?> getRelationshipMetaType(Class<?> clazz, String relationshipName) { return relationshipMetaTypeMap.get(clazz).get(relationshipName); }
java
@Override public T addAsDirectory(final String path) throws IllegalArgumentException { // Precondition check Validate.notNullOrEmpty(path, "path must be specified"); // Delegate and return return this.addAsDirectory(ArchivePaths.create(path)); }
java
private void postProcess(ProcessMethodCallback callback, TransactionContext txContext, InputDatum input, ProcessMethod.ProcessResult result) { InputContext inputContext = input.getInputContext(); Throwable failureCause = null; FailureReason.Type failureType = FailureReason.Type.IO...
java
public float[] get(int x, int y, float[] storage) { if (!isInBounds(x, y)) throw new ImageAccessException("Requested pixel is out of bounds"); if (storage == null) { storage = new float[numBands]; } int index = getIndex(x, y, 0); for (int i = 0; i < numBands; i++, index++) { storage[i] = data[index...
python
def get_class_members(self, cls_name, cls): """Returns the list of class members to document in `cls`. This function filters the class member to ONLY return those defined by the class. It drops the inherited ones. Args: cls_name: Qualified name of `cls`. cls: An inspect object of type 'cl...
python
def get_items(self, page=1, order_by=None, filters=None): """ Fetch database for items matching. Args: page (int): which page will be sliced slice size is ``self.per_page``. order_by (str): a field name to order query by. ...
python
def cytoscape(namespace,command="",PARAMS={},host=cytoscape_host,port=cytoscape_port,method="POST",verbose=False): """ General function for interacting with Cytoscape API. :param namespace: namespace where the request should be executed. eg. "string" :param commnand: command to execute. eg. "protei...
java
protected void handleSimpleCORS( final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain) throws IOException, ServletException { CorsFilter.CORSRequestType requestType = checkRequestType(request); if (!(requestT...
java
protected int hamming(short[] a, short[] b) { int distance = 0; for (int i = 0; i < a.length; i++) { distance += DescriptorDistance.hamming((a[i]&0xFFFF) ^ (b[i]&0xFFFF)); } return distance; }
java
public synchronized void remove(Entry entry) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "remove", new Object[] { entry }); super.remove(entry); DestinationHandler dh = (DestinationHandler) entry.data; if(dh.isMQLink()) removeFromMQLinkIndex(dh); Desti...
java
public LocalDate minusWeeks(int weeks) { if (weeks == 0) { return this; } long instant = getChronology().weeks().subtract(getLocalMillis(), weeks); return withLocalMillis(instant); }
python
def _update_centers(X, membs, n_clusters, distance): """ Update Cluster Centers: calculate the mean of feature vectors for each cluster. distance can be a string or callable. """ centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float) sse = np.empty(shape=n_clusters, dtype=fl...
java
public void setResourceKeys(java.util.Collection<ResourceKey> resourceKeys) { if (resourceKeys == null) { this.resourceKeys = null; return; } this.resourceKeys = new com.amazonaws.internal.SdkInternalList<ResourceKey>(resourceKeys); }
python
def draw_graph(matrix, clusters, **kwargs): """ Visualize the clustering :param matrix: The unprocessed adjacency matrix :param clusters: list of tuples containing clusters as returned by 'get_clusters' :param kwargs: Additional keyword arguments to be passed to ...
java
@Override protected void onNonComplyingFile(File file, String formatted) throws IOException { CharSink sink = Files.asCharSink(file, Charsets.UTF_8); sink.write(formatted); }
python
def _add_potential(self, potential, parent_tag): """ Adds Potentials to the ProbModelXML. Parameters ---------- potential: dict Dictionary containing Potential data. For example: {'role': 'Utility', 'Variables': ['D0', 'D1', 'C0'...
python
def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1): """ Find the indices of a set of angles into a set of pixels Parameters: ----------- pix : set of search pixels pixels : set of reference pixels Returns: -------- index : index into the reference pixels ...
java
public synchronized void clear() { peers.clear(); for(Future<?> timeout : timeouts.values()) { timeout.cancel(true); } timeouts.clear(); }
java
private void setTypeString(final String type) { if (type == null) { this.type = null; } else if (type.equalsIgnoreCase("WARN")) { this.type = Type.WARN; } else if (type.equalsIgnoreCase("ERROR")) { this.type = Type.ERROR; } else if (type.equalsIgnoreCa...
python
def get_db_prep_value(self, value, connection=None, prepared=False): """Returns field's value prepared for interacting with the database backend. Used by the default implementations of ``get_db_prep_save``and `get_db_prep_lookup``` """ if not value: return ...
java
public void excludeStandardObjectNames() { String[] names = { "Object", "Object.prototype", "Function", "Function.prototype", "String", "String.prototype", "Math", // no Math.prototype "Array", "Array.pr...
java
public void onClose(Session session, CloseReason closeReason) { if (getOnCloseHandle() != null) { callMethod(getOnCloseHandle(), getOnCloseParameters(), session, true, closeReason); } }
python
def transit_export_key(self, name, key_type, version=None, mount_point='transit'): """GET /<mount_point>/export/<key_type>/<name>(/<version>) :param name: :type name: :param key_type: :type key_type: :param version: :type version: :param mount_point: ...
java
public ListTopicsResult withTopics(Topic... topics) { if (this.topics == null) { setTopics(new com.amazonaws.internal.SdkInternalList<Topic>(topics.length)); } for (Topic ele : topics) { this.topics.add(ele); } return this; }
python
def get_relationships_by_genus_type_for_source(self, source_id=None, relationship_genus_type=None): """Gets a ``RelationshipList`` corresponding to the given peer ``Id`` and relationship genus ``Type. Relationships`` of any genus derived from the given genus are returned. In plenary mo...
python
def copy(self, path, dest, raise_if_exists=False): """ Copies the contents of a single file path to dest """ if raise_if_exists and dest in self.get_all_data(): raise RuntimeError('Destination exists: %s' % path) contents = self.get_all_data()[path] self.get_a...
java
@Override public synchronized void upload(File fileToUpload, String filename, String contents, String comment) throws Exception { this.upload(new FileInputStream(fileToUpload), filename, contents, comment); }
python
def to_xarray(input): '''Convert climlab input to xarray format. If input is a climlab.Field object, return xarray.DataArray If input is a dictionary (e.g. process.state or process.diagnostics), return xarray.Dataset object with all spatial axes, including 'bounds' axes indicating cell boundaries ...
java
public ServiceFuture<List<ResourceMetricInner>> listMultiRolePoolInstanceMetricsAsync(final String resourceGroupName, final String name, final String instance, final Boolean details, final ListOperationCallback<ResourceMetricInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listM...
java
public void dissociateConnections() throws ResourceException { // We don't call cleanup(), as cleanup() could be doing additional contracts // with the physical connection for (HelloWorldConnectionImpl connection : connections) { connection.setManagedConnection(null); } ...
python
def _metaconfigure(self, argv=None): """Initialize metaconfig for provisioning self.""" metaconfig = self._get_metaconfig_class() if not metaconfig: return if self.__class__ is metaconfig: # don't get too meta return override = { 'c...
python
def get_project_export(self, project_id): """ Get project info for export """ try: result = self._request('/getprojectexport/', {'projectid': project_id}) return TildaProject(**result) except NetworkError: return []
java
void start(CmdArgs args) { String graphLocation = args.get("graph.location", ""); String propLocation = args.get("measurement.location", ""); boolean cleanGraph = args.getBool("measurement.clean", false); String summaryLocation = args.get("measurement.summaryfile", ""); String ti...
java
@Override public void dereferenceLocalisation(LocalizationPoint ptoPMessageItemStream) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "dereferenceLocalisation", new Object[] { ptoPMessageItemStream, this }); _localisationManager.dereferenceLocalis...
java
public static int[] arraySlice(int[] source, int start, int count) { int[] slice = new int[count]; System.arraycopy(source, start, slice, 0, count); return slice; }