language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _try_coerce_args(self, values, other): """ Coerce values and other to dtype 'i8'. NaN and NaT convert to the smallest i8, and will correctly round-trip to NaT if converted back in _try_coerce_result. values is always ndarray-like, other may not be Parameters ...
python
def get_brain_by_uid(uid, default=None): """Query a brain by a given UID :param uid: The UID of the object to find :type uid: string :returns: ZCatalog brain or None """ if not is_uid(uid): return default # we try to find the object with the UID catalog uc = get_tool("uid_catal...
python
def _handle_presentation(self, msg): """Process a MQTT presentation message.""" ret_msg = handle_presentation(msg) if msg.child_id == 255 or ret_msg is None: return # this is a presentation of a child sensor topics = [ '{}/{}/{}/{}/+/+'.format( ...
python
def vtmv(v1, matrix, v2): """ Multiply the transpose of a 3-dimensional column vector a 3x3 matrix, and a 3-dimensional column vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vtmv_c.html :param v1: 3 dimensional double precision column vector. :type v1: 3-Element Array of floa...
java
public static CompactionSuiteFactory getCompactionSuiteFactory(State state) { try { String factoryName = state.getProp(ConfigurationKeys.COMPACTION_SUITE_FACTORY, ConfigurationKeys.DEFAULT_COMPACTION_SUITE_FACTORY); ClassAliasResolver<CompactionSuiteFactory> conditionClassAliasResolver = ...
python
def login(self, username='admin', password='admin'): """ Method to authenticate the qBittorrent Client. Declares a class attribute named ``session`` which stores the authenticated session if the login is correct. Else, shows the login error. :param username: Username. ...
python
def _get_func(cls, source_ver, target_ver): """ Return exactly one function to convert from source to target """ matches = ( func for func in cls._upgrade_funcs if func.source == source_ver and func.target == target_ver ) try: match, = matches except ValueError: raise ValueError( f"No migr...
java
public Observable<ServiceResponse<TagResult>> tagImageWithServiceResponseAsync(String url, TagImageOptionalParameter tagImageOptionalParameter) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } ...
java
@Override public UpdateSecretResult updateSecret(UpdateSecretRequest request) { request = beforeClientExecution(request); return executeUpdateSecret(request); }
python
def register(self, name): """Decorator for registering a function with PyPhi. Args: name (string): The name of the function """ def register_func(func): self.store[name] = func return func return register_func
python
def _assert_same(values): """Assert that all values are identical and return the unique value.""" assert len(values) > 0 first, rest = values[0], values[1:] for v in rest: assert v == first return first
python
def is_colliding(self, other): """Check to see if two AABoundingBoxes are colliding.""" if isinstance(other, AABoundingBox): if self.rect.colliderect(other.rect): return True return False
python
def _remove_extraneous_xml_declarations(xml_str): """ Sometimes devices return XML with more than one XML declaration in, such as when returning their own XML config files. This removes the extra ones and preserves the first one. """ xml_declaration = '' if xml_str.starts...
java
public java.util.List<StartRequest> getStartWorkspaceRequests() { if (startWorkspaceRequests == null) { startWorkspaceRequests = new com.amazonaws.internal.SdkInternalList<StartRequest>(); } return startWorkspaceRequests; }
python
def prune_existing_features(project, force=False): """Prune existing features""" if not force and not project.on_master_after_merge(): raise SkippedValidationTest('Not on master') out = project.build() X_df, y, features = out['X_df'], out['y'], out['features'] proposed_feature = get_propose...
java
public static String getStringFromBundle(String resourceBundleName, String msgKey, Locale tmpLocale, String rawMessage) { return getStringFromBundle(null, resourceBundleName, msgKey, tmpLocale, rawMessage); }
java
private String trimLeadingSlashIfNeeded(String rawName) { if (rawName != null && rawName.startsWith("/")) { return rawName.substring(1); } return rawName; }
python
def default_suse_tr(mod): """ Default translation function for openSUSE, SLES, and other SUSE based systems Returns a tuple of 3 elements - the unversioned name, the python2 versioned name and the python3 versioned name. """ pkg = 'python-%s' % mod py2pkg = 'python2-%s' % mod py3pkg...
python
def _make_info(shape_list, num_classes): """Create an info-like tuple for feature given some shapes and vocab size.""" feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"]) cur_shape = list(shape_list[0]) # We need to merge the provided shapes, put None where they disagree. for shape ...
java
private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) { if (!checkEDBObjectModelType(object, model)) { return null; } filterEngineeringObjectInformation(object, model); List<OpenEngSBModelEntry> entries = new ArrayList<>(); for (PropertyDes...
java
public void executeDDL(String name, Map<String, Object> params) throws SQLException { String ddl = xQueryMap.get(name).getSql(); for (Map.Entry<String, Object> entry : params.entrySet()) { ddl = ddl.replaceAll("[:]" + entry.getKey(), entry.getValue().toString()); } Statement st = connection.createStatement(...
python
def load(self): """Return the current load. The load is represented as a float, where 1.0 represents having hit one of the flow control limits, and values between 0.0 and 1.0 represent how close we are to them. (0.5 means we have exactly half of what the flow control setting all...
java
@Api public void setDefaultCursorString(String cursor) { try { defaultCursor = cursor.toUpperCase(); Cursor.valueOf(cursor.toUpperCase()); } catch (Exception e) { // NOSONAR // Let us assume the cursor points to an image: defaultCursor = cursor; if (!cursor.contains("url")) { defaultCursor = "ur...
java
private SignatureFieldExtension initExtension() { SignatureFieldExtension ext = new SignatureFieldExtension(this); ext.addSignatureChangeListener(new SignatureFieldExtension.SignatureChangeListener() { private static final long serialVersionUID = 1L; @Override ...
java
static <T1, T2, T3> Flowable<Notification<Tuple3<T1, T2, T3>>> createWithThreeOutParameters( Single<Connection> connection, String sql, Flowable<List<Object>> parameterGroups, List<ParameterPlaceholder> parameterPlaceholders, Class<T1> cls1, Class<T2> cls2, Class<T3> cls3) { return conne...
python
def remove(self, path): """Remove the FakeFile object at the specified file path. Args: path: Path to file to be removed. Raises: OSError: if path points to a directory. OSError: if path does not exist. OSError: if removal failed. """ ...
java
public static <X> String createParameterListId(List<AnnotatedParameter<X>> parameters) { StringBuilder builder = new StringBuilder(); builder.append("("); for (int i = 0; i < parameters.size(); ++i) { AnnotatedParameter<X> ap = parameters.get(i); builder.append(createPara...
python
def hack_old_nagios_parameters(self): # pylint: disable=too-many-branches """ Check if modules exist for some of the Nagios legacy parameters. If no module of the required type is present, it alerts the user that the parameters will be ignored and the functions will be disabled, else it...
java
public static Metadata of(Map<String, String> values) { return newBuilder().setValues(values).build(); }
java
public final boolean isScrolledToBottom() { int y = getScrollY(); View view = getChildAt(0); return (view.getBottom() - y) == getHeight(); }
java
public Split<JobXMLDescriptor> getOrCreateSplit() { List<Node> nodeList = model.get("split"); if (nodeList != null && nodeList.size() > 0) { return new SplitImpl<JobXMLDescriptor>(this, "split", model, nodeList.get(0)); } return createSplit(); }
python
def defaultBuilder(value, nt): """Reasonably sensible default handling of put builder """ if callable(value): def logbuilder(V): try: value(V) except: _log.exception("Error in Builder") raise # will be logged again retu...
java
protected Node upImpl(int steps) { Node currNode = this.xmlNode; int stepCount = 0; while (currNode.getParentNode() != null && stepCount < steps) { currNode = currNode.getParentNode(); stepCount++; } return currNode; }
java
public Iterable<ServerInstanceLogRecordList> getLogLists(RepositoryPointer after, Date endTime, final LogRecordHeaderFilter filter) { if (after instanceof RepositoryPointerImpl) { final RepositoryPointerImpl location = (RepositoryPointerImpl) after; final long max = endTime == null ? -1 ...
java
public int getMapMemoryUsedInWords() { int headerSize = 2; int sizeInWords = this.table.length + headerSize; for (int i = 0; i < this.table.length; i += 2) { if (this.table[i] == CHAINED_KEY) { sizeInWords += headerSize + ((Object[]) this.table...
python
def addTitle(self, title, titleAlignments): """ Add a new title to self. @param title: A C{str} title. @param titleAlignments: An instance of L{TitleAlignments}. @raises KeyError: If the title is already present. """ if title in self: raise KeyError('...
java
@Override public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { CallParameter callParameter = getParameter(parameterIndex); callParameter.setOutput(true); callParameter.setOutputSqlType(sqlType); callParameter.setScale(scale); }
python
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The slave view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, the first toplevel widget is discovered in the Builder file...
java
public boolean waitForActivity(String name){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "waitForActivity(\""+name+"\")"); } return waiter.waitForActivity(name, Timeout.getLargeTimeout()); }
java
@NonNull public RequestCreator placeholder(@DrawableRes int placeholderResId) { if (!setPlaceholder) { throw new IllegalStateException("Already explicitly declared as no placeholder."); } if (placeholderResId == 0) { throw new IllegalArgumentException("Placeholder image resource invalid."); ...
python
def blueprint(blueprint_name): """ create and register a blueprint """ app = os.getcwd().split('/')[-1] if app != 'app': logger.warning('''\033[31m{Warning}\033[0m ==> your current path is \033[32m%s\033[0m\n ==> please create your blueprint under app folder!''' % os.getcwd()) exit(1...
java
public Extensions getOrCreate(String tableName, String columnName, GeometryType geometryType) { String extensionName = getExtensionName(geometryType); Extensions extension = getOrCreate(extensionName, tableName, columnName, GEOMETRY_TYPES_EXTENSION_DEFINITION, ExtensionScopeType.READ_WRITE); return e...
java
public static <E> List<E> deleteOutofRange(Counter<E> c, int top, int bottom) { List<E> purgedItems = new ArrayList<E>(); int numToPurge = top + bottom; if (numToPurge <= 0) { return purgedItems; } List<E> l = Counters.toSortedList(c); for (int i = 0; i < top; i++) { E it...
python
def _extractPayload(response, slaveaddress, mode, functioncode): """Extract the payload data part from the slave's response. Args: * response (str): The raw response byte string from the slave. * slaveaddress (int): The adress of the slave. Used here for error checking only. * mode (str...
python
def plot_acquisition(self,filename=None): """ Plots the model and the acquisition function. if self.input_dim = 1: Plots data, mean and variance in one plot and the acquisition function in another plot if self.input_dim = 2: as before but it separates the mean and variance of the...
python
def last(self, db=_DefaultDB): ''' Return the last key/value pair from the given db. ''' self._acqXactForReading() try: with self.xact.cursor(db=db.db) as curs: if not curs.last(): return None return curs.key(), curs...
python
def controversial(self, limit=None): """GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return """ return self._reddit.controversial(self.display_name, limit=limit)
python
def compute_lower_upper_errors(sample, num_sigma=1): """ computes the upper and lower sigma from the median value. This functions gives good error estimates for skewed pdf's :param sample: 1-D sample :return: median, lower_sigma, upper_sigma """ if num_sigma > 3: raise ValueError("Nu...
java
public void setDiffuseColor(float r, float g, float b, float a) { setVec4("diffuse_color", r, g, b, a); }
java
private String resolvePropertyName(String propertyName) { final Class<? extends Entity> clazz = getEntityType(); final String methodName = getterName(propertyName); final Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equ...
java
public static String figureIndexedHash(String repositoryHash, long entryIndex) { return String.valueOf((entryIndex + repositoryHash).hashCode()); }
python
def extract_profiles(self, pipeline_name, expose_data=True): """ Extract all the profiles of a specific pipeline and exposes the data in the namespace """ compas_pipe = self.__profile_definition(pipeline_name) get_variable = compas_pipe.GEtUserVariable if os.path....
python
def _make_patterns(patterns): """Create a ScreenPatternList from a given pattern text. Args: pattern_txt (str list): the patterns Returns: mpdlcd.display_pattern.ScreenPatternList: a list of patterns from the given entries. """ field_registry = display_fields.FieldRegis...
java
public void maybeAppendColumn(Cell cell, DeletionInfo.InOrderTester tester, int gcBefore) { if (cell.getLocalDeletionTime() >= gcBefore && !tester.isDeleted(cell)) { internalAdd(cell); sortedSize++; } }
java
public void delete(final DecoratedKey partitionKey) { if (indexQueue == null) { deleteInner(partitionKey); } else { indexQueue.submitAsynchronous(partitionKey, new Runnable() { @Override public void run() { deleteInner(partition...
python
def license_from_trove(trove): """Finds out license from list of trove classifiers. Args: trove: list of trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers. """ license = [] for classifi...
java
public Timecode resamplePrecise(final Timebase toRate) throws ResamplingException { final Timecode resampled = resample(toRate); // Resample to the new timebase final Timecode back = resampled.resample(this.timebase); // Resample back to the source timebase // If we don't have the same number of seconds and fr...
java
public void marshall(CreatePortfolioRequest createPortfolioRequest, ProtocolMarshaller protocolMarshaller) { if (createPortfolioRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createPortfol...
java
public static <T> CachedFlowable<T> cache(Flowable<T> source) { return new CachedFlowable<T>(source); }
java
public void setSecurityProfileIdentifiers(java.util.Collection<SecurityProfileIdentifier> securityProfileIdentifiers) { if (securityProfileIdentifiers == null) { this.securityProfileIdentifiers = null; return; } this.securityProfileIdentifiers = new java.util.ArrayList<S...
python
def _clear_pattern(self): """ Clears this event recurrence """ # pattern group self.__interval = None self.__days_of_week = set() self.__first_day_of_week = None self.__day_of_month = None self.__month = None self.__index = 'first' # range group ...
python
def check_frequency(freq, res, aniso, epermH, epermV, mpermH, mpermV, verb): r"""Calculate frequency-dependent parameters. This check-function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a detailed description of the input parameters. Paramet...
python
def toElkJson_registerPorts(self, idStore): """ The index of a port in the fixed order around a node. The order is assumed as clockwise, starting with the leftmost port on the top side. This option must be set if ‘Port Constraints’ is set to FIXED_ORDER and no specific positions ...
java
public void stop() { hits = 0; misses = 0; unavailable = 0; delayedHits = 0; delayedMisses = 0; data.clear(); mirror.clear(); isStarted = false; }
python
def sbatch_template(self): """:return Jinja sbatch template for the current tag""" template = self.sbatch_template_str if template.startswith('#!'): # script is embedded in YAML return jinja_environment.from_string(template) return jinja_environment.get_template(t...
python
def percent_point(self, U): """Given a cdf value, returns a value in original space. Args: U: `int` or `float` cdf value in [0,1] Returns: float: value in original space """ self.check_fit() if not 0 < U < 1: raise ValueError('cdf va...
python
def scatter(self, *args, **kwargs): ''' Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : ...
java
protected void updateMailingList(MailingList value, String xmlTag, Counter counter, Element element) { Element root = element; Counter innerCount = new Counter(counter.getDepth() + 1); findAndReplaceSimpleElement(innerCount, root, "name", value.getName(), null); findAndReplaceSimpleElement(in...
java
public void setForcedUser(int contextId, int userId) throws IllegalStateException { User user = getUserManagementExtension().getContextUserAuthManager(contextId).getUserById(userId); if (user == null) throw new IllegalStateException("No user matching the provided id was found."); setForcedUser(contextId, user)...
python
def blue(self, value): """gets/sets the blue value""" if value != self._blue and \ isinstance(value, int): self._blue = value
python
def read_pkginfo(filename): """ Help us read the pkginfo without accessing __init__ """ COMMENT_CHAR = '#' OPTION_CHAR = '=' options = {} f = open(filename) for line in f: if COMMENT_CHAR in line: line, comment = line.split(COMMENT_CHAR, 1) if OPTION_CHAR in ...
java
public void close() throws IOException { switch (state) { case READY: throw new IllegalStateException("File " + tempFile + " hasn't been opened yet."); case CLOSED: throw new IllegalStateException("File " + tempFile ...
python
def from_dict(cls, data): """Create a new Measurement subclass instance using the given dict. If Measurement.name_from_class was previously called with this data's associated Measurement sub-class in Python, the returned object will be an instance of that sub-class. If the measurement n...
python
def collect_non_report_files(args, discovered_files): """Collects the source files that have no coverage reports. """ excl_paths = exclude_paths(args) abs_root = os.path.abspath(args.root) non_report_files = [] for root, dirs, files in os.walk(args.root, followlinks=args.follow_symlinks): ...
java
public static String getTemplatedURL( ServletContext servletContext, ServletRequest request, MutableURI uri, String key, URIContext uriContext ) { TemplatedURLFormatter formatter = getTemplatedURLFormatter( request ); ...
java
public static CompressionType getOutputCompressionType(JobConf conf) { String val = conf.get("mapred.output.compression.type", CompressionType.RECORD.toString()); return CompressionType.valueOf(val); }
python
def detect_fold_level(self, prev_block, block): """ Detects fold level by looking at the block indentation. :param prev_block: previous text block :param block: current block to highlight """ text = block.text() prev_lvl = TextBlockHelper().get_fold_lvl(prev_bloc...
java
private int insertNewKey(Object key, int hash) { if (check && occupiedCount != keyCount) Kit.codeBug(); if (check && keyCount == 1 << power) Kit.codeBug(); int fraction = hash * A; int index = fraction >>> (32 - power); int N = 1 << power; if (keys[index] != null) { ...
python
def rooms(self, sid, namespace=None): """Return the rooms a client is in. The only difference with the :func:`socketio.Server.rooms` method is that when the ``namespace`` argument is not given the namespace associated with the class is used. """ return self.server.rooms(...
java
@SuppressWarnings("rawtypes") public static <T, R> Collector<T, ?, R> streaming(final Function<? super Stream<T>, R> streamingCollector) { return streaming((Supplier) queueSupplier, streamingCollector); }
python
def get_mimetype(self): """ Mimetype is calculated based on the file's content. If ``_mimetype`` attribute is available, it will be returned (backends which store mimetypes or can easily recognize them, should set this private attribute to indicate that type should *NOT* be calcu...
python
def generic_intersect( nodes1, degree1, nodes2, degree2, verify, all_intersections ): r"""Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates will be checked by :func:`verify_duplicates` if ``verify`` is...
python
def zplot(pvalue_dict, name='', format='png', path='./', fontmap=None, verbose=1): """Plots absolute values of z-scores for model validation output from diagnostics.validate().""" if verbose: print_('\nGenerating model validation plot') if fontmap is None: fontmap = {1: 10, 2...
python
def update_balances(self, recursive=True): """ Calculate tree balance factor """ if self.node: if recursive: if self.node.left: self.node.left.update_balances() if self.node.right: self.node.right.update...
python
def _pop_from_list(bracket, lst, line, real_pos, offset, msg_stack): """ _pop_from_list(char : str, lst : [str], line : str, real_pos : int, offset : int) The function is called when a closing bracket is encountered. The function simply pops the last pushed item and issues a warning...
python
def as_pil_image(self): """Extract the image as a Pillow Image, using decompression as necessary Returns: PIL.Image.Image """ from PIL import Image try: bio = BytesIO() self._extract_direct(stream=bio) bio.seek(0) retu...
java
@Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g.create(); g2d.translate(x, y); double coef1 = (double) this.width / (double) getOrigWidth(); double coef2 = (double) this.height / (double) getOrigHeight(); g2d.scale(coe...
java
public static GoogleCloudStorageItemInfo createNotFound(StorageResourceId resourceId) { checkArgument(resourceId != null, "resourceId must not be null"); // Bucket or StorageObject. return new GoogleCloudStorageItemInfo( resourceId, /* creationTime= */ 0, /* size= */ -1, /* l...
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_added`` if it exists. ''' super(SessionCallbackAdded, self).dispatch(receiver) if hasattr(receiver, '_session_callback_added'): ...
java
public void loadMehtodAnnotations(Class cclass, ContainerWrapper containerWrapper) { try { for (Method method : ClassUtil.getAllDecaredMethods(cclass)) { if (method.isAnnotationPresent(OnCommand.class)) { addConsumerMethod(method, cclass, containerWrapper); } } } catch (Exception e) { ...
java
@BetaApi public final Operation deleteGlobalAddress(ProjectGlobalAddressName address) { DeleteGlobalAddressHttpRequest request = DeleteGlobalAddressHttpRequest.newBuilder() .setAddress(address == null ? null : address.toString()) .build(); return deleteGlobalAddress(request); ...
python
def getFileObjects(self): """ Retrieve a dictionary of file objects. This is a utility method that can be used to programmatically access the GsshaPy file objects. Use this method in conjunction with the getFileKeys method to access only files that have been read into the database. ...
python
def create(app_id: int = None, login: str = None, password: str = None, service_token: str = None, proxies: dict = None) -> API: """ Creates an API instance, requires app ID, login and password or service token to create connection :param app_id: int: specifi...
java
INode unprotectedDelete(String src, long modificationTime) { return unprotectedDelete(src, this.getExistingPathINodes(src), null, BLOCK_DELETION_NO_LIMIT, modificationTime); }
java
@Nullable public static Type getResultType(ExpressionTree expressionTree) { Type type = ASTHelpers.getType(expressionTree); return type == null ? null : Optional.ofNullable(type.getReturnType()).orElse(type); }
java
void setFilter(Filter filter) { this.filter = Optional.ofNullable(filter).orElse(FilterNone.INSTANCE); transform = getTransform(); }
python
def save_model(model, output_file): """Save model to output_file, if given""" if not output_file: return with open(output_file, 'wb') as f: pickle.dump(model, f) print("Saved model to file '{}'.".format(output_file))
java
public Image createImage(String src, int width, int height) { return this.add(new Image(src, width, height)); }
java
public static Method getGetterMethod(Class<?> clazz, Field field) { return getMethod(clazz, getGetterMethodName(field)); }
python
def to_rec_single(samples, default_keys=None): """Convert output into a list of single CWL records. """ out = [] for data in samples: recs = samples_to_records([normalize_missing(utils.to_single_data(data))], default_keys) assert len(recs) == 1 out.append(recs[0]) return out