language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def gradients_X(self, dL_dK, X, X2, target): """Derivative of the covariance matrix with respect to X.""" if X2==None or X2 is X: dL_dKdiag = dL_dK.flat[::dL_dK.shape[0]+1] self.dKdiag_dX(dL_dKdiag, X, target)
java
public void setResizable(boolean resize) { if (resize != m_isResize) { if (resize) { getElement().appendChild(m_resize.getElement()); adopt(m_resize); m_resize.addMouseDownHandler(new MouseDownHandler() { public void onMou...
java
public Observable<DatabaseInner> updateAsync(String resourceGroupName, String serverName, String databaseName, DatabaseUpdate parameters) { return updateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).map(new Func1<ServiceResponse<DatabaseInner>, DatabaseInner>() { ...
java
public static <T> Collector<T, ?, List<T>> last(final int n) { N.checkArgNotNegative(n, "n"); final Supplier<Deque<T>> supplier = new Supplier<Deque<T>>() { @Override public Deque<T> get() { return n <= 1024 ? new ArrayDeque<T>(n) : new LinkedList<T>(); ...
java
public SortedSet<TypeElement> allSubClasses(TypeElement typeElement, boolean isEnum) { // new entries added to the set are searched as well, this is // really a work queue. List<TypeElement> list = new ArrayList<>(directSubClasses(typeElement, isEnum)); for (int i = 0; i < list.size(); i...
python
def get_cell_boundary_variables(ds): ''' Returns a list of variable names for variables that represent cell boundaries through the `bounds` attribute :param netCDF4.Dataset nc: netCDF dataset ''' boundary_variables = [] has_bounds = ds.get_variables_by_attributes(bounds=lambda x: x is not N...
python
def _initialize_indices(model_class, name, bases, attrs): """Stores the list of indexed attributes.""" model_class._indices = [] for k, v in attrs.iteritems(): if isinstance(v, (Attribute, ListField)) and v.indexed: model_class._indices.append(k) if model_class._meta['indices']: ...
python
def destroy(name, call=None): ''' To destroy a VM from the VMware environment CLI Example: .. code-block:: bash salt-cloud -d vmname salt-cloud --destroy vmname salt-cloud -a destroy vmname ''' if call == 'function': raise SaltCloudSystemExit( 'The ...
java
protected boolean doesLevelMatch(final Level level, final CSNodeWrapper node, boolean matchContent) { if (!EntityUtilities.isNodeALevel(node)) return false; // If the unique id is not from the parser, than use the unique id to compare if (level.getUniqueId() != null && level.getUniqueId().match...
java
@Deprecated @Override public void remove(final WComponent item) { if (item instanceof MenuItem) { removeMenuItem((MenuItem) item); } }
python
def area(self): r"""The area of the current curved polygon. This assumes, but does not check, that the current curved polygon is valid (i.e. it is bounded by the edges). This computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`...
java
public static Object invokeMethod(Object bean, Method method, Object... args) throws Exception { Class<?>[] types = method.getParameterTypes(); int argCount = args == null ? 0 : args.length; // 参数个数对不上 if (argCount != types.length) { throw new IllegalStateException(...
java
public Signer build() { Util.notNull(signingService, "KSI signing service"); if (defaultHashAlgorithm == null) { this.defaultHashAlgorithm = HashAlgorithm.SHA2_256; } defaultHashAlgorithm.checkExpiration(); if (policy == null) { this.policy = ContextAwareP...
java
@Exported @Restricted(DoNotUse.class) @CheckForNull public String getAbsoluteRemotePath() { if(hasPermission(CONNECT)) { return getAbsoluteRemoteFs(); } else { return null; } }
java
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mIsCapturingGesture = true; mIsClickCandidate = true; mActionDownTime = event.getEventTime(); mActionDownX = event.getX(); mActionDownY = event.getY(); br...
python
def python_sidebar_navigation(python_input): """ Create the `Layout` showing the navigation information for the sidebar. """ def get_text_fragments(): tokens = [] # Show navigation info. tokens.extend([ ('class:sidebar', ' '), ('class:sidebar.key', '[A...
java
private boolean builtInEdit(String initialText, Consumer<String> saveHandler, Consumer<String> errorHandler) { try { ServiceLoader<BuildInEditorProvider> sl = ServiceLoader.load(BuildInEditorProvider.class); // Find the highest ranking provider ...
python
def instance(self, root, baseurl, loaded_schemata, options): """ Create and return an new schema object using the specified I{root} and I{URL}. @param root: A schema root node. @type root: L{sax.element.Element} @param baseurl: A base URL. @type baseurl: str ...
python
def json(self): """ Output the security rules as a json string. Return: str """ return json.dumps(self.dict_rules, sort_keys=True, indent=2, separators=(',', ': '))
python
def update(self, cookies): """Add specified cookies to our cookie jar, and persists it. :param cookies: Any iterable that yields http.cookiejar.Cookie instances, such as a CookieJar. """ cookie_jar = self.get_cookie_jar() for cookie in cookies: cookie_jar.set_cookie(cookie) with self._loc...
python
def get_redirect_args(self, request, callback): """Get request parameters for redirect url.""" callback = request.build_absolute_uri(callback) args = { 'client_id': self.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } scope ...
java
@SuppressWarnings("WeakerAccess") public SnackbarBuilder actionDismissCallback(final SnackbarActionDismissCallback callback) { callbacks.add(new SnackbarCallback() { public void onSnackbarActionPressed(Snackbar snackbar) { callback.onSnackbarActionPressed(snackbar); } }); return this; ...
java
private static String getUPNStringFromSequence(final ASN1Sequence seq) { if (seq == null) { return null; } val id = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0)); if (id != null && UPN_OBJECTID.equals(id.getId())) { val obj = (ASN1TaggedObject) seq.getObjec...
python
def load_module_from_modpath(parts, path=None, use_sys=1): """Load a python module from its split name. :type parts: list(str) or tuple(str) :param parts: python name of a module or package split on '.' :type path: list or None :param path: optional list of path where the module or pac...
java
public void marshall(OrganizationAggregationSource organizationAggregationSource, ProtocolMarshaller protocolMarshaller) { if (organizationAggregationSource == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.m...
java
public void addGSV( GSVSentence gsv ) { try { if (gsv.isValid()) satelliteInfo = gsv.getSatelliteInfo(); } catch (Exception e) { // ignore it, this should be handled in the isValid, // if an exception is thrown, we can't deal with it here. } ...
java
public com.google.api.ads.adwords.axis.v201809.cm.Budget getBudget() { return budget; }
python
def logfile(filename, formatter=None, mode='a', maxBytes=0, backupCount=0, encoding=None, loglevel=None, disableStderrLogger=False): """ Setup logging to file (using a `RotatingFileHandler <https://docs.python.org/2/library/logging.handlers.html#rotatingfilehandler>`_ internally). By default, the file grow...
python
def take_at_most_n_seconds(time_s, func, *args, **kwargs): """A function that returns whether a function call took less than time_s. NOTE: The function call is not killed and will run indefinitely if hung. Args: time_s: Maximum amount of time to take. func: Function to call. *args: Arguments to call...
python
def data(self, column, role): """Return the data for the specified column and role The column addresses one attribute of the data. :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depen...
java
@Override public ZKData<byte[]> getZKByteData(String path) throws InterruptedException, KeeperException { return getZKByteData(path, null); }
python
def createRole(self, *args, **kwargs): """ Create Role Create a new role. The caller's scopes must satisfy the new role's scopes. If there already exists a role with the same `roleId` this operation will fail. Use `updateRole` to modify an existing role. Creat...
java
public void marshall(CreateFileSystemRequest createFileSystemRequest, ProtocolMarshaller protocolMarshaller) { if (createFileSystemRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createFile...
java
protected Statement createStatement(Connection conn, OutputHandler outputHandler, String sql) throws SQLException { Statement result = null; Integer resultSetType = null; Integer resultSetConcurrency = null; if (outputHandler instanceof LazyScrollOutputHandler) { ...
python
def channel_info(self, chan): """get soundfont, bank, prog, preset name of channel""" info=fluid_synth_channel_info_t() fluid_synth_get_channel_info(self.synth, chan, byref(info)) return (info.sfont_id, info.bank, info.program, info.name)
python
def _nodes(e): """ A helper for ordered() which returns the node count of ``e`` which for Basic objects is the number of Basic nodes in the expression tree but for other objects is 1 (unless the object is an iterable or dict for which the sum of nodes is returned). """ from .basic import Bas...
python
def get_descendants_group_count(cls, parent=None): """ Helper for a very common case: get a group of siblings and the number of *descendants* (not only children) in every sibling. :param parent: The parent of the siblings to return. If no parent is given, the ro...
python
def match_validator(expression): """Return validator function that will check if matches given expression. Args: match: if string then this will be converted to regular expression using ``re.compile``. Can be also any object that has ``match()`` method like already compiled regula...
python
def has_generic_permission(self, request, permission_type): """ Return true if the current user has permission on this image. Return the string 'ALL' if the user has all rights. """ user = request.user if not user.is_authenticated(): return False elif ...
python
def get_used_fields(payload): """ Get a list containing the names of the fields that are used in the xso.Query. :param payload: Query object o be :type payload: :class:`~aioxmpp.ibr.Query` :return: :attr:`list` """ return [ tag for tag, descriptor in payload.CHILD_MAP.it...
java
public void ensureHasSpace(int numBytesToAdd) { if (numBytesToAdd < 0) { throw new IllegalArgumentException("Number of bytes can't be negative"); } int capacityLeft = getCapacityLeft(); if (capacityLeft < numBytesToAdd) { grow(numBytesToAdd - capacityLeft, true); } }
java
@TimerJ public TableMetadataBuilder withOptions(Map<Selector, Selector> opts) { options = new HashMap<Selector, Selector>(opts); return this; }
python
def format_datetime(value): """ Format datetime """ dt_format = '%Y-%m-%dT%H:%M:%I' if isinstance(value, datetime): return value.strftime(dt_format) return value
java
public boolean isTransitionApplied (Class<?> clazz, final String name) throws PersistenceException { final String cname = clazz.getName(); return execute(new Operation<Boolean>() { public Boolean invoke (Connection conn, DatabaseLiaison liaison) throws SQLExceptio...
java
private void delete(Node<K, V> n) { if (root == n) { deleteMin(); n.o_c = null; n.y_s = null; n.o_s = null; return; } if (n.o_s == null) { throw new IllegalArgumentException("Invalid handle!"); } // unlink ...
java
protected void purgeZeroObject(Long bucketId, Long objectId, AllocationPoint point, boolean copyback) { allocationsMap.remove(objectId); memoryHandler.purgeZeroObject(bucketId, objectId, point, copyback); getFlowController().getEventsProvider().storeEvent(point.getLastWriteEvent()); ge...
python
def compute_payments(self, precision=None): ''' Returns the total amount of payments made to this invoice. @param precision:int Number of decimal places @return: Decimal ''' return quantize(sum([payment.amount for payment in self.__payments]), prec...
python
def get_mosaic_by_name(self, name): '''Get the API representation of a mosaic by name. :param name str: The name of the mosaic :returns: :py:Class:`planet.api.models.Mosaics` :raises planet.api.exceptions.APIException: On API error. ''' params = {'name__is': name} ...
java
void addInvokes(MethodDescriptor methodDescriptor, final Integer lineNumber, MethodDescriptor invokedMethodDescriptor) { InvokesDescriptor invokesDescriptor = scannerContext.getStore().create(methodDescriptor, InvokesDescriptor.class, invokedMethodDescriptor); invokesDescriptor.setLineNumber(lineNumber)...
java
public void evaluateAndSet(Object target, Object value) { MVEL.executeSetExpression(getCompiledSetExpression(), target, value); }
python
def handle_presence(self, old_present): ''' Fire presence events if enabled ''' # On the first run it may need more time for the EventPublisher # to come up and be ready. Set the timeout to account for this. if self.presence_events and self.event.connect_pull(timeout=3): ...
java
public NotificationChain basicSetFinallyExpression(XExpression newFinallyExpression, NotificationChain msgs) { XExpression oldFinallyExpression = finallyExpression; finallyExpression = newFinallyExpression; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notificat...
python
def _create_flags(self, kw): """ this clones the kw dict, adding a lower-case version of every key (duplicated in circuit.py; consider putting in util?) """ flags = {} for k in kw.keys(): flags[k] = kw[k] flags[k.lower()] = flags[k] return...
java
private boolean nextSegment() { assert(state == State.ITER_CHECK_FWD); // The input text [start..(iter index)[ passes the FCD check. pos = iter.getIndex(); // Collect the characters being checked, in case they need to be normalized. if(s == null) { s = new StringBuild...
java
public DenyAssignmentInner get(String scope, String denyAssignmentId) { return getWithServiceResponseAsync(scope, denyAssignmentId).toBlocking().single().body(); }
python
def redirect(self, where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, **url_kwargs): """ Convenience method for returning redirect responses. :param where: A URL, endpoint, or config key...
java
public long run(String partitionValue, long maxTotalRows, long targetMaxRowsToDelete) { if (targetMaxRowsToDelete <= 0) { throw new VoltAbortException("maxRowsToDeletePerProc must be > 0."); } if (maxTotalRows < 0) { throw new VoltAbortException("maxTotalRows must be >= 0...
python
def valid_url(url): """Validate url. :rtype: str :return: url :param str url: package homepage url. """ regex = re.compile( r'^(?:http)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+' r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?))' r'(?:/?|[/?]\S+)$', re.IGNORECA...
python
def split_data_cwl_items(items, default_keys=None): """Split a set of CWL output dictionaries into data samples and CWL items. Handles cases where we're arrayed on multiple things, like a set of regional VCF calls and data objects. """ key_lens = set([]) for data in items: key_lens.add(...
python
def show_vcs_output_vcs_nodes_vcs_node_info_node_public_ipv6_addresses_node_public_ipv6_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") ...
java
protected boolean isWellDefined() { int size = references.size(); if (size == 0) { return false; } // If this is a declaration that does not instantiate the variable, // it's not well-defined. Reference init = getInitializingReference(); if (init == null) { return false; } ...
java
public void setInitialized() { boolean okay = (this.state == STATE_INITIALIZING); this.state = STATE_INITIALIZED; if (!okay) { if (isInitialized()) { throw new IllegalStateException("Already initialized."); } else { throw new IllegalStateException("You need to call setInitializi...
java
@Override public void visit(NodeVisitor v) { if (v.visit(this)) { initializer.visit(v); condition.visit(v); increment.visit(v); body.visit(v); } }
python
def create_metadata_file(output_path, data_dir): '''Creates a METADATA.json file from a data directory The file is written to output_path ''' # Relative path to all (BASIS).metadata.json files meta_filelist, table_filelist, _, _ = get_all_filelist(data_dir) metadata = {} for meta_file_rel...
python
def get_request_participants(self, issue_id_or_key, start=0, limit=50): """ Get request participants :param issue_id_or_key: str :param start: OPTIONAL: int :param limit: OPTIONAL: int :return: Request participants """ url = 'rest/servicedeskapi/request/{...
python
def write_master_ninja(master_ninja, targets): """Writes master build.ninja file, referencing all given subninjas.""" master_ninja.variable('cxx', 'c++') master_ninja.variable('ld', '$cxx') if sys.platform == 'darwin': master_ninja.variable('alink', 'libtool -static') else: master_ni...
python
def parse(self, ticket): """Parses the passed ticket, returning a tuple containing the digest, user_id, valid_until, tokens, and user_data fields """ if len(ticket) < self._min_ticket_size(): raise TicketParseError(ticket, 'Invalid ticket length') digest_len = self._...
java
public static Schema recordOf(String name) { Preconditions.checkNotNull(name, "Record name cannot be null."); return new Schema(Type.RECORD, null, null, null, null, name, null, null); }
java
public boolean isDone() { int count = 0; for (Pair<T, Future<?>> pair: _pairs) { if (pair.second.isDone()) ++count; } return count == _pairs.size(); }
python
def set_metadata(self, set_id, fp): """ Set the XML metadata on a set. :param file fp: file-like object to read the XML metadata from. """ base_url = self.client.get_url('SET', 'GET', 'single', {'id': set_id}) self._metadata.set(base_url, fp)
java
public void enableReceiveNotifyMsg(boolean enable, EnableReceiveNotifyMsgHandler handler) { HMSAgentLog.i("enableReceiveNotifyMsg:enable=" + enable + " handler=" + StrUtils.objDesc(handler)); this.enable = enable; this.handler = handler; connect(); }
python
def set_mtime(self, name, mtime, size): """Set modification time on file.""" self.check_write(name) os.utime(os.path.join(self.cur_dir, name), (-1, mtime))
python
def connectProcess(connection, processProtocol, commandLine='', env={}, usePTY=None, childFDs=None, *args, **kwargs): """Opens a SSHSession channel and connects a ProcessProtocol to it @param connection: the SSH Connection to open the session channel on @param processProtocol: the Proces...
python
def write_stats_to_json(cls, file_name, stats): """Write stats to a local json file.""" params = cls._json_dump_options(stats) mode = 'w' if PY3 else 'wb' try: safe_file_dump(file_name, params, mode=mode) except Exception as e: # Broad catch - we don't want to fail in stats related failure. ...
java
public void marshall(AlarmConfiguration alarmConfiguration, ProtocolMarshaller protocolMarshaller) { if (alarmConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(alarmConfiguration.getEna...
java
public synchronized void close() throws IOException { writable = false; if (map != null) { ByteArrayUtil.unmapByteBuffer(map); map = null; } if (lock != null) { lock.release(); lock = null; } file.close(); }
python
def _set_allow(self, v, load=False): """ Setter method for allow, mapped from YANG variable /port_profile/allow (container) If this variable is read-only (config: false) in the source YANG file, then _set_allow is considered as a private method. Backends looking to populate this variable should ...
python
def get_freesasa_annotations(self, outdir, include_hetatms=False, force_rerun=False): """Run ``freesasa`` on this structure and store the calculated properties in the corresponding ChainProps """ if self.file_type != 'pdb': log.error('{}: unable to run freesasa with "{}" file type. P...
python
def run(self): """Begins simultaneous generation/acquisition :returns: numpy.ndarray -- read samples """ try: if self.aotask is None: print u"You must arm the calibration first" return # acquire data and stop task, lock must have b...
java
public void deleteExpired(IEntityLock lock) throws LockingException { deleteExpired(new Date(), lock.getEntityType(), lock.getEntityKey()); }
java
public Comment addComment(long sheetId, long discussionId, Comment comment) throws SmartsheetException{ return this.createResource("sheets/" + sheetId + "/discussions/" + discussionId + "/comments", Comment.class, comment); }
python
def parsecommonarguments(object, doc, annotationtype, required, allowed, **kwargs): """Internal function to parse common FoLiA attributes and sets up the instance accordingly. Do not invoke directly.""" object.doc = doc #The FoLiA root document if required is None: required = tuple() if allowe...
java
public void set(double m00, double m01, double m02, double m10, double m11, double m12) { set(m00, m01, m02, m10, m11, m12, 0., 0., 1.); }
java
protected void rotateLeft(final OMVRBTreeEntry<K, V> p) { if (p != null) { OMVRBTreeEntry<K, V> r = p.getRight(); p.setRight(r.getLeft()); if (r.getLeft() != null) r.getLeft().setParent(p); r.setParent(p.getParent()); if (p.getParent() == null) setRoot(r); ...
java
@GET @Path("/{pushAppID}/count") @Produces(MediaType.APPLICATION_JSON) public Response countInstallations(@PathParam("pushAppID") String pushApplicationID) { logger.trace("counting devices by type for push application '{}'", pushApplicationID); Map<String, Long> result = pushAppService.coun...
java
public static String join(Collection collection, String separator, boolean trailing) { StringBuilder b = new StringBuilder(); // fast return on empty collection if (collection.isEmpty()) { return trailing ? separator : ""; ...
python
def del_actor(self, actor): """Remove an actor when the socket is closed.""" if _debug: TCPClientDirector._debug("del_actor %r", actor) del self.clients[actor.peer] # tell the ASE the client has gone away if self.serviceElement: self.sap_request(del_actor=actor) ...
java
@SuppressWarnings("unchecked") public Map<String, Object> getNextPropertiesParam(InputStream in, String strName, Map<String, Object> properties) { return (Map)this.getNextObjectParam(in, strName, properties); }
java
public boolean confirmFailure(String orderNumber, String timestamp, String authCode) { String base = new StringBuilder() .append(orderNumber) .append('|') .append(timestamp) .append('|') .append(merchantSecret) .toString(); return StringUtils.equals( StringUtils.upperCase(Di...
python
def rulejoin(class_rule, method_rule): """ Join class and method rules. Used internally by :class:`ClassView` to combine rules from the :func:`route` decorators on the class and on the individual view handler methods:: >>> rulejoin('/', '') '/' >>> rulejoin('/', 'first') ...
java
private Queue<ReadFuture> getReadyReadFutures() { Queue<ReadFuture> readyReadFutures = (Queue<ReadFuture>) getAttribute(READY_READ_FUTURES_KEY); if (readyReadFutures == null) { readyReadFutures = new CircularQueue<>(); Queue<ReadFuture> oldReadyReadFutures = ...
java
public static ContentType get( final HttpEntity entity) throws ParseException, UnsupportedCharsetException { if (entity == null) { return null; } Header header = entity.getContentType(); if (header != null) { HeaderElement[] elements = header.getElemen...
python
def start(self): """ Start the server and run forever. """ Server().start(self.options,self.handler_function, self.__class__.component_type)
java
public Observable<Page<VirtualWANInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<VirtualWANInner>>, Page<VirtualWANInner>>() { @Override public Page<VirtualWANInner> call(ServiceResponse<Page<VirtualWANInner>> response) ...
java
static Set<String> determineImportOnUpdatePaths( String templateLoc, Set<String> relResourcePathSet) { String templateLocPath = templateLoc.split("\\*")[0]; // up to wildcard pattern if (!templateLocPath.endsWith("/")) { templateLocPath = templateLocPath + "/"; } ...
python
def record(self, frame_parameters: dict=None, channels_enabled: typing.List[bool]=None, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Record data and return a list of data_and_metadata objects. .. versionadded:: 1.0 :param frame_parameters: The frame parameters for t...
python
def update_email_template(self, template_id, template_dict): """ Updates a emailtemplate :param template_id: the template id :param template_dict: dict :return: dict """ return self._create_put_request( resource=EMAIL_TEMPLATES, billomat_i...
python
def fromfile(self, path_to_file, mimetype=None): """ load blob content from file in StorageBlobModel instance. Parameters are: - path_to_file (required): path to a local file - mimetype (optional): set a mimetype. azurestoragewrap will guess it if not given """ if os....
python
def count(self, *urls): """ Return comment count for one ore more urls.. """ threads = dict(self.db.execute([ 'SELECT threads.uri, COUNT(comments.id) FROM comments', 'LEFT OUTER JOIN threads ON threads.id = tid AND comments.mode = 1', 'GROUP BY thread...
java
public byte[] deliverSm(int sequenceNumber, String serviceType, byte sourceAddrTon, byte sourceAddrNpi, String sourceAddr, byte destAddrTon, byte destAddrNpi, String destinationAddr, byte esmClass, byte protocolId, byte priorityFlag, byte registeredDelivery, byte dataCodi...