language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static void reconfigure(InputStream config) { if (CONTEXT == null) { log.warn("当前日志上下文不是logback,不能使用该配置器重新配置"); return; } reconfigure(config, CONTEXT); }
java
static String pullFontPathFromStyle(Context context, AttributeSet attrs, int[] attributeId) { if (attributeId == null || attrs == null) return null; final TypedArray typedArray = context.obtainStyledAttributes(attrs, attributeId); if (typedArray != null) { try { ...
python
def load(self, email, master_token, android_id): """Authenticate to Google with the provided master token. Args: email (str): The account to use. master_token (str): The master token. android_id (str): An identifier for this client. Raises: Login...
python
def count_alleles(self, max_allele=None, subpop=None): """Count the number of calls of each allele per variant. Parameters ---------- max_allele : int, optional The highest allele index to count. Alleles above this will be ignored. subpop : sequence of in...
java
public static String getContextURL(ODataUri oDataUri, EntityDataModel entityDataModel, boolean isPrimitive) throws ODataRenderException { if (ODataUriUtil.isActionCallUri(oDataUri) || ODataUriUtil.isFunctionCallUri(oDataUri)) { return buildContextUrlFromOperationCall(oDat...
python
def add_user( self, username, first_name, last_name, email, role, password="", hashed_password="", ): """ Generic function to create user """ try: user = self.user_model() user.first_name = fi...
python
def list_rows( self, table, selected_fields=None, max_results=None, page_token=None, start_index=None, page_size=None, retry=DEFAULT_RETRY, ): """List the rows of the table. See https://cloud.google.com/bigquery/docs/reference/...
python
def project_views( self, projects, access='all-access', agent='all-agents', granularity='daily', start=None, end=None): """ Get pageview counts for one or more wikimedia projects See `<https://wikimedia.org/api/rest_v1/metrics/pageviews/?doc\\ ...
python
def url(self): """ Returns the whole URL from the base to this node. """ path = None nodes = self.parents() while not nodes.empty(): path = urljoin(path, nodes.get().path()) return path
java
static void countHetero(List<IRingSet> rsets) { for (IRingSet rset : rsets) { int numHeteroAtoms = 0; int numHeteroRings = 0; for (IAtomContainer ring : rset.atomContainers()) { int prevNumHeteroAtoms = numHeteroAtoms; for (IAtom atom : ring.at...
java
protected double computeABOF(KernelMatrix kernelMatrix, DBIDRef pA, DBIDArrayIter pB, DBIDArrayIter pC, MeanVariance s) { s.reset(); // Reused double simAA = kernelMatrix.getSimilarity(pA, pA); for(pB.seek(0); pB.valid(); pB.advance()) { if(DBIDUtil.equal(pB, pA)) { continue; } do...
java
public void transform(final URI input, final URI output, final List<XMLFilter> filters) throws DITAOTException { if (input.equals(output)) { transform(input, filters); } else { transformURI(input, output, filters); } }
java
@Restricted(NoExternalUse.class) public synchronized void persistInstallStatus() { List<UpdateCenterJob> jobs = getJobs(); boolean activeInstalls = false; for (UpdateCenterJob job : jobs) { if (job instanceof InstallationJob) { InstallationJob installationJob = (...
python
def zoom(ax, xy='x', factor=1): """Zoom into axis. Parameters ---------- """ limits = ax.get_xlim() if xy == 'x' else ax.get_ylim() new_limits = (0.5*(limits[0] + limits[1]) + 1./factor * np.array((-0.5, 0.5)) * (limits[1] - limits[0])) if xy == 'x': ax.set_xlim(ne...
java
@Override public GetKeyPairResult getKeyPair(GetKeyPairRequest request) { request = beforeClientExecution(request); return executeGetKeyPair(request); }
python
def cf_tokenize(s): """ Parses UserData for Cloudformation helper functions. http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/qu...
python
def setup(self): """Setup.""" self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] self.prefix = self.config['prefix'] self.generic_mode = self.config['generic_mode'] self.string...
python
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'): ''' Make a web call to DigitalOcean ''' base_path = six.text_type(config.get_cloud_config_value( 'api_root', get_configured_provider(), __opts__, search_global=False, defaul...
python
def _resolve_viewname(self, viewname): """ Check for special view names and return existing rTorrent one. """ if viewname == "-": try: # Only works with rTorrent-PS at this time! viewname = self.open().ui.current_view() except xmlrpc.ERRORS...
java
public boolean isRectangular () { return (_isPolygonal) && (_rulesSize <= 5) && (_coordsSize <= 8) && (_coords[1] == _coords[3]) && (_coords[7] == _coords[5]) && (_coords[0] == _coords[6]) && (_coords[2] == _coords[4]); }
python
def as_dict(self): """ Serializes the object necessary data in a dictionary. :returns: Serialized data in a dictionary. :rtype: dict """ result_dict = super(Group, self).as_dict() statuses = list() version = None titles = list() descript...
python
def geometry_checker(geometry): """Perform a cleaning if the geometry is not valid. :param geometry: The geometry to check and clean. :type geometry: QgsGeometry :return: Tuple of bool and cleaned geometry. True if the geometry is already valid, False if the geometry was not valid. A c...
python
def _api_type(self, value): """ Returns the API type of the given value based on its python type. """ if isinstance(value, six.string_types): return 'string' elif isinstance(value, six.integer_types): return 'integer' elif type(value) is datetime....
python
def hexists(self, key, field): """Determine if hash field exists.""" fut = self.execute(b'HEXISTS', key, field) return wait_convert(fut, bool)
python
def net_transform(transform_func, block=None, **kwargs): """ Maps nets to new sets of nets according to a custom function :param transform_func: Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool) :return: """ block = working_block(block) with set_working_block(blo...
python
def keyvalue( name, key=None, value=None, key_values=None, separator="=", append_if_not_found=False, prepend_if_not_found=False, search_only=False, show_changes=True, ignore_if_missing=False, count=1, uncomment=None, ...
java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean xml = false; logger.debug("Got request: {}?{}", request.getRequestURL(), request.getQueryString()); // Check for xml parameter. ...
java
private void nextChunk() throws IOException { if (!this.bof) { this.readCrlf(); } this.size = ChunkedInputStream.chunkSize(this.origin); this.bof = false; this.pos = 0; if (this.size == 0) { this.eof = true; } }
java
public void terminate() { if (!isTerminated()) { for (final Stage stage : stages.values()) { stage.stop(); } loggerProviderKeeper.close(); mailboxProviderKeeper.close(); completesProviderKeeper.close(); } }
python
def install_libs(self): """Install Required Libraries using pip.""" # default or current python version lib_data = [{'python_executable': sys.executable, 'lib_dir': self.lib_directory}] # check for requirements.txt if not os.path.isfile(self.requirements_file): self....
python
def epubcheck(epubname, config=None): """ This method takes the name of an epub file as an argument. This name is the input for the java execution of a locally installed epubcheck-.jar. The location of this .jar file is configured in config.py. """ if config is None: config = load_config...
java
public static void configure(Job conf, SimpleConfiguration config) { try { FluoConfiguration fconfig = new FluoConfiguration(config); try (Environment env = new Environment(fconfig)) { long ts = env.getSharedResources().getTimestampTracker().allocateTimestamp().getTxTimestamp(); ...
java
public final void removeRelationshipsWithTag(@Nonnull String tag) { getRelationships().stream() .map(RelationshipView::getRelationship) .filter(r -> r.hasTag(tag)) .forEach(this::remove); }
java
public boolean moveAndDeleteFromEachVolume(String pathName) throws IOException { boolean result = true; for (int i = 0; i < volumes.length; i++) { result = result && moveAndDeleteRelativePath(volumes[i], pathName); } return result; }
python
def attriblist2str(discoursegraph): """ converts all node/edge attributes whose values are lists into string values (e.g. to export them into the `gexf` and `graphml` formats). WARNING: This function iterates over all nodes and edges! You can speed up conversion by writing a custom function that on...
python
def free_param_names(self): """Returns the names of the free hyperparameters. Returns ------- free_param_names : :py:class:`Array` Array of the names of the free parameters, in order. """ return scipy.concatenate((self.k1.free_param_names, self.k2.fre...
java
private void doRemoveDatasource() throws PageException { admin.removeDataSource(getString("admin", action, "name")); store(); adminSync.broadcast(attributes, config); }
java
protected BufferedImage create_FOREGROUND_Image(final int WIDTH, final boolean WITH_CENTER_KNOB, final ForegroundType TYPE) { return create_FOREGROUND_Image(WIDTH, WITH_CENTER_KNOB, TYPE, null); }
java
public void delete(String resourceGroupName, String jobName) { deleteWithServiceResponseAsync(resourceGroupName, jobName).toBlocking().last().body(); }
python
def _af_inv_scaled(x): """Scale a random vector for using the affinely invariant measures""" x = _transform_to_2d(x) cov_matrix = np.atleast_2d(np.cov(x, rowvar=False)) cov_matrix_power = _mat_sqrt_inv(cov_matrix) return x.dot(cov_matrix_power)
python
def time2pbspro(timeval, unit="s"): """ Convert a number representing a time value in the given unit (Default: seconds) to a string following the PbsPro convention: "hours:minutes:seconds". >>> assert time2pbspro(2, unit="d") == '48:0:0' """ h, m, s = 3600, 60, 1 timeval = Time(timeval, un...
java
public static byte[] asArray(ByteBuffer byteBuffer) { ByteBuffer bb = ByteBufferUtil.clone(byteBuffer); byte[] bytes = new byte[bb.remaining()]; bb.get(bytes); return bytes; }
java
public com.google.api.ads.admanager.axis.v201811.AudienceSegmentDataProvider getDataProvider() { return dataProvider; }
java
void setLocale(Locale locale) { m_taskNames = LocaleData.getStringArray(locale, LocaleData.TASK_NAMES); String name; m_taskNumbers.clear(); for (int loop = 0; loop < m_taskNames.length; loop++) { name = m_taskNames[loop]; if (name != null) { m_t...
java
public FessMessages addErrorsFailedToPrintThreadDump(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_failed_to_print_thread_dump)); return this; }
java
@java.lang.Deprecated public java.util.Map<java.lang.String, com.google.cloud.redis.v1.ZoneMetadata> getAvailableZones() { return getAvailableZonesMap(); }
java
@Bench(runs = RUNS, beforeEachRun = "vectorAdd") public void vectorGet() { for (int i = 0; i < vector.size(); i++) { vector.get(i); } }
python
def _closeCompletion(self): """Close completion, if visible. Delete widget """ if self._widget is not None: self._widget.close() self._widget = None self._completionOpenedManually = False
python
def _ISO8601_to_UNIXtime(iso): """ Converts an ISO8601-formatted string in the format ``YYYY-MM-DD HH:MM:SS+00`` to the correspondant UNIXtime :param iso: the ISO8601-formatted string :type iso: string :returns: an int UNIXtime :raises: *TypeError* when bad argument types are provided, *Val...
python
def txt_line_iterator(path): """Iterate through lines of file.""" with tf.gfile.Open(path) as f: for line in f: yield line.strip()
python
def run(self, host=None, port=None, debug=None, **options): """ Start the AgoraApp expecting the provided config to have at least REDIS and PORT fields. """ tasks = options.get('tasks', []) for task in tasks: if task is not None and hasattr(task, '__call__'): ...
python
def compute_displays_sweep( self, program: Union[circuits.Circuit, schedules.Schedule], params: Optional[study.Sweepable] = None, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Union[int, np.ndarray] = 0, ) -> List[study.ComputeDisplaysResult]: ...
java
public static boolean isMethodCall(Expression expression, String methodObjectPattern, String methodNamePattern) { return isMethodCallOnObject(expression, methodObjectPattern) && isMethodNamed((MethodCallExpression) expression, methodNamePattern); }
python
def Convert(self, metadata, value, token=None): """Converts a single ArtifactFilesDownloaderResult.""" for r in self.BatchConvert([(metadata, value)], token=token): yield r
python
def get_storage_controller_hotplug_capable(self, controller_type): """Returns whether the given storage controller supports hot-plugging devices. in controller_type of type :class:`StorageControllerType` The storage controller to check the setting for. return hotplug_capabl...
python
def body_block_content_render(tag, recursive=False, base_url=None): """ Render the tag as body content and call recursively if the tag has child tags """ block_content_list = [] tag_content = OrderedDict() if tag.name == "p": for block_content in body_block_paragraph_render(tag, bas...
java
private void tryToMoveMemberFunction( NameInfo nameInfo, JSModule deepestCommonModuleRef, ClassMemberFunction classMemberFunction) { // We should only move a property across chunks if: // 1) We can move it deeper in the chunk graph, // 2) and it's a normal member function, and not a GETTER_DEF or a S...
python
def replace(self, repl_class, replacement, target_segment_name=None): """Replace a pipe segment, specified by its class, with another segment""" for segment_name, pipes in iteritems(self): if target_segment_name and segment_name != target_segment_name: raise Exception() ...
java
public TimeFrameFilterType getType() { if (startDate == null && endDate == null) { return TimeFrameFilterType.INOPERATIVE; } else if (startDate != null && endDate == null) { return TimeFrameFilterType.MIN_DATE; } else if (st...
python
def read_string(self, content): """Parse a string containing C/C++ source code. :param content: C/C++ source code. :type content: str :rtype: Declarations """ reader = source_reader.source_reader_t( self.__config, None, self.__decl_fac...
java
public static FilterOperator toFilterOperator(ComparableFilter.Operator operator) { if (operator == ComparableFilter.Operator.EQUAL_TO) { return FilterOperator.EQUAL; } else if (operator == ComparableFilter.Operator.GREATER_THAN) { return FilterOperator.GREATER_THAN; } else if (operator == ComparableFilter....
java
static final <T> void validateValues(final T[] values, final Comparator<? super T> comparator) { final int lenM1 = values.length - 1; for (int j = 0; j < lenM1; j++) { if ((values[j] != null) && (values[j + 1] != null) && (comparator.compare(values[j], values[j + 1]) < 0)) { continue; ...
python
def __get_tags(vm_): ''' Get configured tags. ''' t = config.get_cloud_config_value( 'tags', vm_, __opts__, default='[]', search_global=False) # Consider warning the user that the tags in the cloud profile # could not be interpreted, bad formatting? try: tags = litera...
java
public void setMaximumDuration(@NotNull final Duration maximumDuration) { if (maximumDuration.compareTo(MAXIMUM_DURATION) > 0) { throw new IllegalArgumentException("The maximum duaration has to be smaller than 23:59:59."); } this.maximumDuration = durationToDate(maximumDuration); ...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'synonyms') and self.synonyms is not None: _dict['synonyms'] = [x._to_dict() for x in self.synonyms] if hasattr(self, 'pagination') and self.pagination is not None: ...
python
def _set_params(self, x): """set the value of the parameters.""" assert x.size == self.num_params self.varianceU = x[0] self.varianceY = x[1] self.lengthscaleU = x[2] self.lengthscaleY = x[3]
python
def rl_ellipsis(x): """ Replace three dots to ellipsis """ patterns = ( # если больше трех точек, то не заменяем на троеточие # чтобы не было глупых .....->….. (r'([^\.]|^)\.\.\.([^\.]|$)', u'\\1\u2026\\2'), # если троеточие в начале строки или возле кавычки -- #...
java
@Override public boolean validate(Field f, Object validationObject) { boolean checkvalidation = true; for (Annotation annotation : f.getDeclaredAnnotations()) { AttributeConstraintType eruleType = getERuleType(annotation.annotationType().getSimpleName()); if (e...
python
def commit(self, frame): """ Handles COMMIT command: Commits specified transaction. """ if not frame.transaction: raise ProtocolError("Missing transaction for COMMIT command.") if not frame.transaction in self.engine.transactions: raise ProtocolError("Inv...
python
def getsource(classorfunc): """ Return the source code for a class or function. Notes: Returned source will not include any decorators for the object. This will only return the explicit declaration of the object, not any dependencies Args: classorfunc (type or function): the object...
python
def save(self, fname): """ Saves the dictionary in json format :param fname: file to save to """ with open(fname, 'wb') as f: json.dump(self, f)
java
public static BufferedImage getImage(ByteBuffer imageData, Format format, Rectangle size) { final int width = size.getWidth(); final int height = size.getHeight(); final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final int[] pixels = ((DataBuffer...
java
public Map<String, CmsJspResourceWrapper> getLocaleResource() { Map<String, CmsJspResourceWrapper> result = getPageResource().getLocaleResource(); List<Locale> locales = CmsLocaleGroupService.getPossibleLocales(m_cms, getPageResource()); for (Locale locale : locales) { if (!result.c...
python
def report(self, device_name_filter=None, tensor_name_filter=None): """Get a report of offending device/tensor names. The report includes information about the device name, tensor name, first (earliest) timestamp of the alerting events from the tensor, in addition to counts of nan, positive inf and neg...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SimpleAntlrPackage.REFERENCE_OR_LITERAL__NAME: setName((String)newValue); return; } super.eSet(featureID, newValue); }
java
@Programmatic public Clob downloadMetaModel() { final Collection<ObjectSpecification> specifications = specificationLoader.allSpecifications(); final List<MetaModelRow> rows = Lists.newArrayList(); for (final ObjectSpecification spec : specifications) { if (exclude(spec)) { ...
python
def _call(self, x, out=None): """Implement ``self(x[, out])``.""" if out is None: return self.operator(x * self.vector) else: tmp = self.domain.element() x.multiply(self.vector, out=tmp) self.operator(tmp, out=out)
python
def set_parent(self, task_id, params={}, **options): """Changes the parent of a task. Each task may only be a subtask of a single parent, or no parent task at all. Returns an empty data block. Parameters ---------- task : {Id} Globally unique identifier for the task. [da...
python
def _GetSignatureScanner(cls, specification_store): """Initializes a signature scanner based on a specification store. Args: specification_store (FormatSpecificationStore): specification store. Returns: pysigscan.scanner: signature scanner. """ signature_scanner = pysigscan.scanner() ...
java
void deleteResource(String id) throws IOException { storeWithRetries(() -> { datastore.delete(datastore.newKeyFactory().setKind(KIND_COUNTER_LIMIT).newKey(id)); return null; }); deleteShardsForCounter(id); }
java
public static String urlInJobHistory( Path jobHistoryFileLocation, String jobId) throws IOException { try { FileSystem fs = jobHistoryFileLocation.getFileSystem(conf); fs.getFileStatus(jobHistoryFileLocation); } catch (FileNotFoundException e) { return null; } return "http://"...
python
def _member_defs(self): """ A single string containing the aggregated member definitions section of the documentation page """ members = self._clsdict['__members__'] member_defs = [ self._member_def(member) for member in members if member.name is n...
java
public ExceptionRule addExceptionRule(Recurrence recur) { ExceptionRule prop = new ExceptionRule(recur); addExceptionRule(prop); return prop; }
java
public static WindowOver<Double> regrIntercept(Expression<? extends Number> arg1, Expression<? extends Number> arg2) { return new WindowOver<Double>(Double.class, SQLOps.REGR_INTERCEPT, arg1, arg2); }
java
protected void registerColumnType(String columnType, int jdbcType) { columnTypeMatchers.add(new ColumnTypeMatcher(columnType)); jdbcTypes.put(columnType, jdbcType); }
java
@Override public DRFModel createImpl() { DRFV3.DRFParametersV3 p = this.parameters; DRFModel.DRFParameters parms = p.createImpl(); return new DRFModel( model_id.key(), parms, new DRFModel.DRFOutput(null) ); }
python
def has_local_job_refs(io_hash): ''' :param io_hash: input/output hash :type io_hash: dict :returns: boolean indicating whether any job-based object references are found in *io_hash* ''' q = [] for field in io_hash: if is_job_ref(io_hash[field]): if get_job_from_jbor(io_...
java
public static ClientInterceptor newCaptureMetadataInterceptor( AtomicReference<Metadata> headersCapture, AtomicReference<Metadata> trailersCapture) { return new MetadataCapturingClientInterceptor(headersCapture, trailersCapture); }
java
Txn txn_begin(Txn parent, IsolationLevel level, int timeout, TimeUnit unit) throws Exception { return txn_begin(parent, level); }
python
def get_float_info(self, field): """Get float property from the DMatrix. Parameters ---------- field: str The field name of the information Returns ------- info : array a numpy array of float information of the data """ le...
python
def DOM_copyTo(self, nodeId, targetNodeId, **kwargs): """ Function path: DOM.copyTo Domain: DOM Method name: copyTo WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'nodeId' (type: NodeId) -> Id of the node to copy. 'targetNodeId' (type: NodeId) -> Id ...
java
public static String generateSwidFileName(final String regId, final String productName, final String uniqueSoftwareId, final String extension) { StringBuilder res = new StringBuilder() .append(regId) .append("_") .append(productName) .a...
python
def ssn(self): """ Returns a 9 digits Dutch SSN called "burgerservicenummer (BSN)". the Dutch "burgerservicenummer (BSN)" needs to pass the "11-proef", which is a check digit approach; this function essentially reverses the checksum steps to create a random valid BSN (which is 9...
java
public void marshall(CreateGeoMatchSetRequest createGeoMatchSetRequest, ProtocolMarshaller protocolMarshaller) { if (createGeoMatchSetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createG...
java
@Override public ITextNode getTextNode(String key) { for (ITextNode node : textNodeList) { if (key.equals(node.getKey())) { return node; } } return null; }
java
protected String getValue(String str) { int index = str.indexOf('='); String value = null; if (index > 0) { value = str.substring(index + 1).trim(); if (value.charAt(0) == '\"') { value = value.substring(1, value.length() - 1); } } ...
python
def lift(obj, memo=None): """Make a promise out of object `obj`, where `obj` may contain promises internally. :param obj: Any object. :param memo: used for internal caching (similar to :func:`deepcopy`). If the object is a :class:`PromisedObject`, or *pass-by-value* (:class:`str`, :class:`int`...
python
def filter_host_by_regex(regex): """Filter for host Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for host. Accept if regex match host_name""" host...
java
@TargetApi(Build.VERSION_CODES.KITKAT) public static boolean hasStepDetectorSensorFeature(Context context) { return hasStepDetectorSensorFeature(context.getPackageManager()); }
python
def save_password(entry, password, username=None): """ Saves the given password in the user's keychain. :param entry: The entry in the keychain. This is a caller specific key. :param password: The password to save in the keychain. :param username: The username to get the password for. Defau...