language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "extension", scope = ApplyACL.class) public JAXBElement<CmisExtensionType> createApplyACLExtension( CmisExtensionType value) { return new JAXBElement<CmisExtensionType>( _GetPropertiesExtension_QNAME, CmisExtensionT...
java
public static Object stringToValue(String string) { if (string.equals("")) { return string; } if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } if (string.equalsIgnoreCase("null")) { return JSONObject.NULL; } /* ...
python
def load_yaml(yaml_file: str) -> Any: """ Load YAML from file. :param yaml_file: path to YAML file :return: content of the YAML as dict/list """ with open(yaml_file, 'r') as file: return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader)
java
public SICoreConnection getConnection() throws SISessionDroppedException, SIConnectionDroppedException, SISessionUnavailableException, SIConnectionUnavailableException { final String methodName = "getConnection"; if (TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE,...
java
public void calculateGisModelDwgPolylines() { for( int i = 0; i < dwgObjects.size(); i++ ) { DwgObject pol = (DwgObject) dwgObjects.get(i); if (pol instanceof DwgPolyline2D) { int flags = ((DwgPolyline2D) pol).getFlags(); int firstHandle = ((DwgPolyline2D)...
python
def _getLayers(self): """ gets layers for the featuer service """ params = {"f": "json"} json_dict = self._get(self._url, params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, ...
java
private List buildResourceTypeSelectWidgetList() { List fileFormats = new ArrayList(); // get all OpenCms resource types List resourceTypes = OpenCms.getResourceManager().getResourceTypes(); // put for every resource type type id and name into list object for select widget Itera...
java
public static int consumeCRLF(final Buffer buffer) throws SipParseException { try { buffer.markReaderIndex(); final byte cr = buffer.readByte(); final byte lf = buffer.readByte(); if (cr == CR && lf == LF) { return 2; } } catch ...
python
def from_text(text): """Convert text into an opcode. @param text: the textual opcode @type text: string @raises UnknownOpcode: the opcode is unknown @rtype: int """ if text.isdigit(): value = int(text) if value >= 0 and value <= 15: return value value = _by_...
python
def truncate(self, distance): """ Return a truncated version of the path. Only one vertex (at the endpoint) will be added. """ position = np.searchsorted(self._cum_norm, distance) offset = distance - self._cum_norm[position - 1] if offset < constants.tol_path.mer...
python
def formatDecimalMark(value, decimalmark='.'): """ Dummy method to replace decimal mark from an input string. Assumes that 'value' uses '.' as decimal mark and ',' as thousand mark. ::value:: is a string ::returns:: is a string with the decimal mark if needed """ # We...
java
public void beforeNullSafeOperation(SharedSessionContractImplementor session) { ConfigurationHelper.setCurrentSessionFactory(session.getFactory()); if (this instanceof IntegratorConfiguredType) { ((IntegratorConfiguredType)this).applyConfiguration(session.getFactory()); } }
python
def select_by_key(self, key): """Selects an item by its key. Args: key (str): The unique string identifier of the item that have to be selected. """ self._selected_key = None self._selected_item = None for item in self.children.values(): item.attr...
java
private List<org.jfrog.hudson.pipeline.types.File> getBuildFilesList(Stream<? extends BaseBuildFileBean> buildFilesStream) { return buildFilesStream .filter(buildFile -> StringUtils.isNotBlank(buildFile.getLocalPath())) .filter(buildFile -> StringUtils.isNotBlank(buildFile.getRem...
java
public final String stringReplace( String toBeReplaced, String toReplace, String replacement ) { Pattern pattern = Pattern.compile(toReplace); Matcher match = pattern.matcher(toBeReplaced); while (match.find()) { toBeReplaced = match.replaceAll(replacemen...
java
public static <T> Single<Set<T>> values(String key, Class<T> vClazz) { return values(CacheService.CACHE_CONFIG_BEAN, key, vClazz); }
python
def execute(db_name): """Execute any pending work in the database stored in `db_name`, recording the results. This looks for any work in `db_name` which has no results, schedules it to be executed, and records any results that arrive. """ try: with use_db(db_name, mode=WorkDB.Mode.open)...
python
def get_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(r'^[...
java
@Override public T transformElement(Tuple2<Object, LinkedMapWritable> tuple, DeepJobConfig<T, ? extends DeepJobConfig> config) { try { return (T) UtilES.getObjectFromJson(config.getEntityClass(), tuple._2()); } catch (Exception e) { LOG.error("C...
java
protected void HandelStack() { // Find out what the operator does to the stack int StackHandel = StackOpp(); if (StackHandel < 2) { // The operators that enlarge the stack by one if (StackHandel==1) PushStack(); // The operators that pop the stack else { ...
java
private void complete(Symbol sym) throws CompletionFailure { if (sym.kind == TYP) { ClassSymbol c = (ClassSymbol)sym; c.members_field = new Scope.ErrorScope(c); // make sure it's always defined annotate.enterStart(); try { completeOwners(c.owner); ...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case TypesPackage.JVM_MEMBER__DECLARING_TYPE: return getDeclaringType() != null; case TypesPackage.JVM_MEMBER__VISIBILITY: return visibility != VISIBILITY_EDEFAULT; case TypesPackage.JVM_MEMBER__SIMPLE_NAME: return SIMPLE_N...
python
def create_token_response(self, request, token_handler): """Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oaut...
java
@Nonnegative private static int _appendNextCharacterAndAdvanceLoop (@Nonnull final String sLine, @Nonnull final StringBuilder aSB, @Nonnegative final int nIndex) { aSB.append (sLine.charAt (nIndex +...
python
def _process_figure(value, fmt): """Processes the figure. Returns a dict containing figure properties.""" # pylint: disable=global-statement global Nreferences # Global references counter global has_unnumbered_figures # Flags unnumbered figures were found global cursec ...
java
public List<Node<K, V>> searchAll(Interval1D<K> interval) { LinkedList<Node<K, V>> list = new LinkedList<>(); searchAll(root, interval, list); return list; }
python
def params_to_blr(self, trans_handle, params): "Convert parameter array to BLR and values format." ln = len(params) * 2 blr = bs([5, 2, 4, 0, ln & 255, ln >> 8]) if self.accept_version < PROTOCOL_VERSION13: values = bs([]) else: # start with null indicator...
java
private void init(int tLen, byte[] src, int offset, int len) { if (tLen < 0) { throw new IllegalArgumentException( "Length argument is negative"); } this.tLen = tLen; // Input sanity check if ((src == null) ||(len < 0) || (offset < 0) ...
python
def milestones(self, extra_params=None): """ All Milestones in this Space """ # Default params params = { 'per_page': settings.MAX_PER_PAGE, } if extra_params: params.update(extra_params) return self.api._get_...
python
def _build_params(self, location, provider_key, **kwargs): """Will be overridden according to the targetted web service""" base_kwargs = { 'q': location, 'fuzzy': kwargs.get('fuzzy', 1.0), 'username': provider_key, 'maxRows': kwargs.get('maxRows', 1), ...
java
@Override public SIDestinationAddress checkMessagingRequired(SIDestinationAddress requestDestAddr, SIDestinationAddress replyDestAddr, DestinationType destinationType, ...
python
def get_maya_envpath(self): """Return the PYTHONPATH neccessary for running mayapy If you start native mayapy, it will setup these paths. You might want to prepend this to your path if running from an external intepreter. :returns: the PYTHONPATH that is used for running mayapy...
java
public static List<Precedence> newPrecedence(VM vmBefore, Collection<VM> vmsAfter) { return newPrecedence(Collections.singleton(vmBefore), vmsAfter); }
python
def coal(return_X_y=True): """coal-mining accidents dataset Parameters ---------- return_X_y : bool, if True, returns a model-ready tuple of data (X, y) otherwise, returns a Pandas DataFrame Returns ------- model-ready tuple of data (X, y) OR Pandas DataFrame ...
python
def endpoint_check( first, node_first, s, second, node_second, t, intersections ): r"""Check if curve endpoints are identical. .. note:: This is a helper for :func:`tangent_bbox_intersection`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively,...
java
protected static void main(String args[]) { int from = Integer.parseInt(args[0]); int to = Integer.parseInt(args[1]); statistics(from,to); }
python
def output_of(*cmd: Optional[str], **kwargs) -> str: """Invokes a subprocess and returns its output as a string. Args: cmd: Components of the command to execute, e.g. ["echo", "dog"]. **kwargs: Extra arguments for asyncio.create_subprocess_shell, such as a cwd (current working direc...
java
public void exclusiveOr (Area area) { Area a = clone(); a.intersect(area); add(area); subtract(a); }
java
public ChangeRequest applyChangeRequest( ChangeRequestInfo changeRequest, Dns.ChangeRequestOption... options) { checkNotNull(changeRequest); return dns.applyChangeRequest(getName(), changeRequest, options); }
java
@Override public void notifyOfAddedMetric(Metric metric, String metricName, MetricGroup group) { final String domain = generateJmxDomain(metricName, group); final Hashtable<String, String> table = generateJmxTable(group.getAllVariables()); AbstractBean jmxMetric; ObjectName jmxName; try { jmxName = new O...
python
def compute(self, inputVector, learn, activeArray): """ This method resembles the primary public method of the SpatialPooler class. """ super(SpatialPoolerWrapper, self).compute(inputVector, learn, activeArray) self._updateAvgActivityPairs(activeArray)
python
def Session(access_token=None, env=None): """Create an HTTP session. Parameters ---------- access_token : str Mapbox access token string (optional). env : dict, optional A dict that subsitutes for os.environ. Returns ------- requests.Session """ if env is None: ...
python
async def create_rev_reg(self, rr_id: str, rr_size: int = None) -> None: """ Create revocation registry artifacts and new tails file (with association to corresponding revocation registry identifier via symbolic link name) for input revocation registry identifier. Symbolic link presence ...
java
private static void convertUnicodeToHex(String str) { try { display("Unicode to hex: " + Utils.toHexBytes(Utils.toBytes(str))); } catch (Exception e) { } }
python
def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None): """ A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool c...
java
@SuppressWarnings("unchecked") public synchronized <T> T load(final PluggableService<T> service, final String providerName) throws ProviderLoaderException { final ProviderIdent ident = new ProviderIdent(service.getName(), providerName); debug("loadInstance for " + ident + ": " + pluginJa...
java
public void addPropertiesFieldBehavior(BaseField fldDisplay, String strProperty) { FieldListener listener = new CopyConvertersHandler(new PropertiesConverter(this, strProperty)); listener.setRespondsToMode(DBConstants.INIT_MOVE, false); listener.setRespondsToMode(DBConstants.READ_MOVE, false...
java
public alluxio.grpc.PAclEntryType getType() { alluxio.grpc.PAclEntryType result = alluxio.grpc.PAclEntryType.valueOf(type_); return result == null ? alluxio.grpc.PAclEntryType.Owner : result; }
python
def get(scope, source, index): """ Returns a copy of the list item with the given index. It is an error if an item with teh given index does not exist. :type source: string :param source: A list of strings. :type index: string :param index: A list of strings. :rtype: string :retu...
java
private String getDialogId(VaadinRequest request) { String path = request.getPathInfo(); // remove the leading slash return path != null ? path.substring(1) : null; }
java
private static Set<Long> getFeedItemIdsFromArgument(Function function) { if (function.getLhsOperand().length == 1 && function.getLhsOperand(0) instanceof RequestContextOperand) { RequestContextOperand requestContextOperand = (RequestContextOperand) function.getLhsOperand(0); if (Reques...
java
public static String getNativeLibraryVersion() { URL versionFile = SnappyLoader.class.getResource("/org/xerial/snappy/VERSION"); String version = "unknown"; try { if (versionFile != null) { InputStream in = null; try { Properti...
python
def getFileSecurity( self, fileName, securityInformation, securityDescriptor, lengthSecurityDescriptorBuffer, lengthNeeded, dokanFileInfo, ): """Get security attributes of a file. :param fileName: name of file to get security for :type...
python
def get_all(self, **options): """ Retrieves all records repetitively and returns a single list. >>> airtable.get_all() >>> airtable.get_all(view='MyView', fields=['ColA', '-ColB']) >>> airtable.get_all(maxRecords=50) [{'fields': ... }, ...] Keyword Args...
python
def grant_permission_to_users(self, permission, **kwargs): # noqa: E501 """Grants a specific user permission to multiple users # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
python
def GetSessionId(self): '''Retrieves the VMSessionID for the current session. Call this function after calling VMGuestLib_UpdateInfo. If VMGuestLib_UpdateInfo has never been called, VMGuestLib_GetSessionId returns VMGUESTLIB_ERROR_NO_INFO.''' sid = c_void_p() ret = vmGuestL...
python
def GetParentFileEntry(self): """Retrieves the parent file entry. Returns: FileEntry: parent file entry or None if not available. """ store_index = vshadow.VShadowPathSpecGetStoreIndex(self.path_spec) if store_index is None: return None return self._file_system.GetRootFileEntry()
python
def _GetSocket(self): """Establishes a connection to an nsrlsvr instance. Returns: socket._socketobject: socket connected to an nsrlsvr instance or None if a connection cannot be established. """ try: return socket.create_connection( (self._host, self._port), self._SOCKE...
java
private Object executeExp(PageContext pc, SQL sql, Query qr, ZExp exp, int row) throws PageException { if (exp instanceof ZConstant) return executeConstant(sql, qr, (ZConstant) exp, row); else if (exp instanceof ZExpression) return executeExpression(pc, sql, qr, (ZExpression) exp, row); throw new DatabaseException("...
java
public boolean isComplexQuery() { for (int i = 0; i < this.getRecordlistCount(); i++) { if (this.getRecordlistAt(i).getTable() instanceof org.jbundle.base.db.shared.MultiTable) return true; } return false; }
java
public boolean remove() { if (_last1.key() == null) throw new java.util.NoSuchElementException( "remove() without calling next()"); boolean result = internalRemove(); return result; }
python
def execute(self, conn, logical_file_name, transaction=False): """ simple execute """ if not conn: dbsExceptionHandler("dbsException-db-conn-failed", "Oracle/FileBuffer/DeleteDupicates. Expects db connection from upper layer.") print(self.sql) self.dbi.processData(self.sql, logical_fil...
python
def compute_and_cache_missing_buckets(self, start_time, end_time, untrusted_time, force_recompute=False): """ Return the results for `query_function` on every `bucket_width` time period between `start_time` and `end_time`. Look for previously cached results to av...
java
public GrailsClass getArtefact(String artefactType, String name) { ArtefactInfo info = getArtefactInfo(artefactType); return info == null ? null : info.getGrailsClass(name); }
python
def string_to_tokentype(s): """ Convert a string into a token type:: >>> string_to_token('String.Double') Token.Literal.String.Double >>> string_to_token('Token.Literal.Number') Token.Literal.Number >>> string_to_token('') Token Tokens that are already token...
python
def unpackSeptets(septets, numberOfSeptets=None, prevOctet=None, shift=7): """ Unpacks the specified septets into octets :param septets: Iterator or iterable containing the septets packed into octets :type septets: iter(bytearray), bytearray or str :param numberOfSeptets: The amount of septets to ...
python
def SetConsoleTextAttribute(stream_id, attrs): """Set a console text attribute.""" handle = handles[stream_id] return windll.kernel32.SetConsoleTextAttribute(handle, attrs)
python
def checkpoint(self): """ Update the database to reflect in-memory changes made to this item; for example, to make it show up in store.query() calls where it is now valid, but was not the last time it was persisted to the database. This is called automatically when in 'autocommi...
python
def do_resolve(self, line): """resolve <identifier> Find all locations from which the given Science Object can be downloaded.""" pid, = self._split_args(line, 1, 0) self._command_processor.resolve(pid)
python
def isFloat(nstr, schema): """ !~~isFloat """ if isinstance(nstr, (float, int, long)): return True elif not isinstance(nstr, basestring): return False try: float(nstr) except ValueError: return False return True
python
def import_subview(self, idx, subview): """ Add the given subview to the corpus. Args: idx (str): An idx that is unique in the corpus for identifying the subview. If already a subview exists with the given id it will be overridden. subview (Subview...
python
def pretty_description(description, wrap_at=None, indent=0): """ Return a pretty formatted string given some text. Args: description (str): string to format. wrap_at (int): maximum length of a line. indent (int): level of indentation. Returns: str: pretty formatted stri...
python
def PrepareMatches(self, file_system): """Prepare find specification for matching. Args: file_system (FileSystem): file system. """ if self._location is not None: self._location_segments = self._SplitPath( self._location, file_system.PATH_SEPARATOR) elif self._location_regex ...
java
private Set<Field> getItemFields() { Class next = Item.class; Set<Field> fields = new HashSet<>(getFields(next)); while (next.getSuperclass() != Object.class) { next = next.getSuperclass(); fields.addAll(getFields(next)); } return fields; }
python
async def send(self, data, id=None, event=None, retry=None): """Send data using EventSource protocol :param str data: The data field for the message. :param str id: The event ID to set the EventSource object's last event ID value to. :param str event: The event's type. If th...
java
public static boolean check(Map<String, Object> m, Map<String, Object> r) { if (r.get(m.get("cmd")).equals("OK")) { return true; } return false; }
python
def score(self, y_true, y_pred): """Calculate f1 score. Args: y_true (list): true sequences. y_pred (list): predicted sequences. Returns: score: f1 score. """ score = f1_score(y_true, y_pred) print(' - f1: {:04.2f}'.format(score * 100...
python
def resample_vinci( fref, fflo, faff, intrp = 0, fimout = '', fcomment = '', outpath = '', pickname = 'ref', vc = '', con = '', vincipy_path = '', atlas_resample = False, atlas_ref_make = False, atlas_ref_del...
python
def perlin(self, key, **kwargs): """Return perlin noise seede with the specified key. For parameters, check the PerlinNoise class.""" if hasattr(key, "encode"): key = key.encode('ascii') value = zlib.adler32(key, self.seed) return PerlinNoise(value, **kwargs)
python
def pyprf_opt_brute(strCsvCnfg, objNspc, lgcTest=False, strPathHrf=None, varRat=None): """ Function for optimizing given pRF paramaters using brute-force grid search. Parameters ---------- strCsvCnfg : str Absolute file path of config file. objNspc : object N...
java
private static void appendCondition(DbMapping dbMapping, StringBuilder sql, Map<String, Object> values, ResultSet rs) throws SQLException { // 拼接主键 for (Map.Entry<String, String> entry : dbMapping.getTargetPk().entrySet()) { String targetColumnName = e...
java
public synchronized Entry next() { if (tc.isEntryEnabled()) SibTr.entry(tc, "next"); // can only do anything if the cursor is still pointing in to a list checkEntryParent(); Entry nextEntry = null; synchronized(parentList) { //get the next entry in the list nextEnt...
python
def rmd_options_to_metadata(options): """ Parse rmd options and return a metadata dictionary :param options: :return: """ options = re.split(r'\s|,', options, 1) if len(options) == 1: language = options[0] chunk_options = [] else: language, others = options ...
python
def get_absolute_path(cls, roots, path): """Returns the absolute location of ``path`` relative to one of the ``roots``. ``roots`` is the path configured for this `StaticFileHandler` (in most cases the ``static_path`` `Application` setting). """ for root in roots: ...
java
public String print( TemporalAmount threeten, TextWidth width ) { return this.print(Duration.from(threeten), width); }
java
public void importArtifacts(SessionProvider sp, File folder) throws RepositoryException, FileNotFoundException { if (!folder.exists()) throw new FileNotFoundException("Source folder expected"); try { this.listErrorPom.clear(); importFilesToJCR(sp, folder); } c...
python
def compose(*fns): """Return the function composed with the given functions :param fns: functions :returns: a function >>> add2 = lambda x: x+2 >>> mult3 = lambda x: x*3 >>> new_fn = compose(add2, mult3) >>> new_fn(2) 8 .. note:: compose(fn1, fn2, fn3) is the same as fn1(fn2(fn3))...
python
def add_to_loaded_modules(self, modules): """ Manually add in `modules` to be tracked by the module manager. `modules` may be a single object or an iterable. """ modules = util.return_set(modules) for module in modules: if not isinstance(module, str): ...
java
@Override public MoreObjects.ToStringHelper toStringHelper() { return toStringHelper(this).add("from", from).add("to", to).add("operation", operation); }
java
protected boolean isForbidden(String scheme, String host, int port, boolean openNonPrivPorts) { // Check port Integer p = new Integer(port); if (port > 0 && !_allowedConnectPorts.contains(p)) { if (!openNonPrivPorts || port <= 1024) return true; } ...
python
def fix_flags(self, flags): """Fixes standard TensorBoard CLI flags to parser.""" FlagsError = base_plugin.FlagsError if flags.version_tb: pass elif flags.inspect: if flags.logdir and flags.event_file: raise FlagsError( 'Must specify either --logdir or --event_file, but n...
java
public WebhookDefinition withFilters(WebhookFilterRule... filters) { if (this.filters == null) { setFilters(new java.util.ArrayList<WebhookFilterRule>(filters.length)); } for (WebhookFilterRule ele : filters) { this.filters.add(ele); } return this; }
java
private void checkHasDistinctElements(Collection<T> coll) { // keep track of the already seen elements NonIterableSet<T> seenElems = new NonIterableSet<T>(coll.size()); for(T elem : coll) { if(!seenElems.add(elem)) { throw new IllegalArgumentException("coll has duplicate element:" + elem); } } }
java
private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { try { ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); Object embeddedObject = null; if (constructorMetadata.isClassicConstructionStrategy()) { embeddedObject = ...
java
@Override public T borrowObject() throws Exception { T redisClient = super.borrowObject(); if (redisClient != null) { activeClients.add(redisClient); } return redisClient; }
java
public static String href(String param, String value) { HttpServletRequest req = ContextUtils.getRequest(); String pagePath = (String) req.getAttribute(SiteController.PAGE_PATH); if (pagePath == null) return "javascript:void(0)"; StaticUrlProvider urlProvider = (StaticUrlProvider) req .getAttribute...
python
def touch(path): """ Creates a file located at the given path. """ with open(path, 'a') as f: os.utime(path, None) f.close()
java
public WebApp getWebApp() { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { logger.logp(Level.FINE, CLASS_NAME,"getWebApp", "webapp -> "+ _webApp +" ,this -> " + this); } return _webApp; }
java
public final EObject ruleXExpressionInClosure() throws RecognitionException { EObject current = null; Token otherlv_2=null; EObject lv_expressions_1_0 = null; enterRule(); try { // InternalXbaseWithAnnotations.g:3141:2: ( ( () ( ( (lv_expressions_1_0= ruleXExpre...
python
def loadImgs(self, ids=[]): """ Load anns with the specified ids. :param ids (int array) : integer ids specifying img :return: imgs (object array) : loaded img objects """ if type(ids) == list: return [self.imgs[id] for id in ids] elif type(ids) ...