language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public boolean useCode(String username, String code) throws GuacamoleException { // Repeatedly attempt to use the given code until an explicit success // or failure has occurred UsedCode usedCode = new UsedCode(username, code); for (;;) { // Explicitly invalidat...
java
private static String pickDelimiter(String[] strings) { boolean allLength1 = true; for (String s : strings) { if (s.length() != 1) { allLength1 = false; break; } } if (allLength1) { return ""; } String[] delimiters = new String[]{" ", ";", ",", "{", "}", null}...
python
def com_google_fonts_check_negative_advance_width(ttFont): """ Check that advance widths cannot be inferred as negative. """ failed = False for glyphName in ttFont["glyf"].glyphs: coords = ttFont["glyf"][glyphName].coordinates rightX = coords[-3][0] leftX = coords[-4][0] advwidth = rightX - leftX ...
java
public IMatrix add(IMatrix b) { IMatrix result = new IMatrix(rows, columns); add(b, result); return result; }
python
def get_agent(self, agent_id): """Gets the ``Agent`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``Agent`` may have a different ``Id`` than requested, such as the case where a duplicate ``Id`` was assigne...
java
private void consolidate() { if (decreasePoolSize == 0) { return; } // lazily initialize comparator if (decreasePoolComparator == null) { if (comparator == null) { decreasePoolComparator = new Comparator<Node<K, V>>() { @Overri...
python
def _json_body_(cls): """Return the JSON body of given datapoints. :return: JSON body of these datapoints. """ json = [] for series_name, data in six.iteritems(cls._datapoints): for point in data: json_point = { "measurement": seri...
java
public void billingAccount_redirect_serviceName_PUT(String billingAccount, String serviceName, OvhRedirect body) throws IOException { String qPath = "/telephony/{billingAccount}/redirect/{serviceName}"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
python
def btreeSearch(self, ip): """ " b-tree search method " param: ip """ if not ip.isdigit(): ip = self.ip2Long(ip) if len(self.__headerSip) < 1: #pass the super block self.__f.seek(8) #read the header block b = self.__f.read(...
java
public List<CmsResource> readResourcesWithProperty( CmsDbContext dbc, CmsResource folder, String propertyDefinition, String value, CmsResourceFilter filter) throws CmsException { String cacheKey; if (value == null) { cacheKey = getCacheKey( ...
python
def sanitize_http_request_querystring(client, event): """ Sanitizes http request query string :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: query_string = force_text(event["context"]["request"]["url"]["search"], e...
java
protected void parseDefaultType( TokenStream tokens, JcrNodeDefinitionTemplate childDefn ) throws ConstraintViolationException { if (tokens.canConsume('=')) { if (!tokens.canConsume('?')) { Name defaultType = parseName(tokens); chi...
java
public long getCrc64() { try { if (isDirectory()) { String []list = list(); long digest = 0x1; for (int i = 0; i < list.length; i++) { digest = Crc64.generate(digest, list[i]); } return digest; } else if (canRead()) { ReadStreamOld is ...
java
public static String normalizeDriveLetter(String file) { if (file.length() > 2 && file.charAt(1) == ':') { return Character.toUpperCase(file.charAt(0)) + file.substring(1); } else if (file.length() > 3 && file.charAt(0) == '*' && file.charAt(2) == ':') { // Han...
java
static public void registerClasses (final Kryo kryo) { kryo.register(Object[].class); kryo.register(InvokeMethod.class); FieldSerializer<InvokeMethodResult> resultSerializer = new FieldSerializer<InvokeMethodResult>(kryo, InvokeMethodResult.class) { public void write (Kryo kryo, Output output, InvokeMethod...
java
public Observable<RouteFilterInner> beginUpdateAsync(String resourceGroupName, String routeFilterName, PatchRouteFilter routeFilterParameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilterInner...
java
public static MetricInstrumentedIterator of(KeyIterator keyIterator, String... prefix) { if (keyIterator == null) { return null; } Preconditions.checkNotNull(prefix); return new MetricInstrumentedIterator(keyIterator, StringUtils.join(prefix,".")); }
python
def guard(ctx, opts=""): """ Execute all tests and then watch for changes, re-running. """ # TODO if coverage was run via pytest-cov, we could add coverage here too return test(ctx, include_slow=True, loop_on_fail=True, opts=opts)
python
def get_node(manager, handle_id, legacy=True): """ :param manager: Manager to handle sessions and transactions :param handle_id: Unique id :param legacy: Backwards compatibility :type manager: norduniclient.contextmanager.Neo4jDBSessionManager :type handle_id: str|unicode :type legacy: Bool...
java
private String doBackwardPathOnly(final FedoraResource resource) { final String path = reverse.convert(resource.getPath()); if (path == null) { throw new RepositoryRuntimeException("Unable to process reverse chain for resource " + resource); } return convertToExternalPath(p...
python
def shift_click(self, locator, params=None, timeout=None): """ Shift-click web element. :param locator: locator tuple or WebElement instance :param params: (optional) locator parameters :param timeout: (optional) time to wait for element :return: None """ ...
java
public void marshall(StepFunctionsAction stepFunctionsAction, ProtocolMarshaller protocolMarshaller) { if (stepFunctionsAction == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(stepFunctionsAction.ge...
python
def delete_expired_requests(): """Delete expired inclusion requests.""" InclusionRequest.query.filter_by( InclusionRequest.expiry_date > datetime.utcnow()).delete() db.session.commit()
python
def create_from_format_name(self, format_name): """ Create a file loader from a format name. Supported file formats are as follows: ========================== ====================================== Format name Loader =========================...
java
public boolean isNotVisited(int loc) { if (checkBounds(loc)) { return (ZERO == this.registry[loc]); } else { throw new RuntimeException( "The location " + loc + " out of bounds [0," + (this.registry.length - 1) + "]"); } }
python
def _getHead(self, branch): """Return a deferred for branch head revision or None. We'll get an error if there is no head for this branch, which is probably a good thing, since it's probably a misspelling (if really buildbotting a branch that does not have any changeset yet, one...
java
@Check(CheckType.FAST) public void checkActionName(SarlAction action) { final JvmOperation inferredType = this.associations.getDirectlyInferredOperation(action); final QualifiedName name = QualifiedName.create(inferredType.getQualifiedName('.').split("\\.")); //$NON-NLS-1$ if (this.featureNames.isDisallowedName(...
java
@Override public boolean onClick() { if (!(parent instanceof UITabGroup)) return super.onClick(); if (!fireEvent(new TabChangeEvent((UITabGroup) parent, this))) return super.onClick(); tabGroup().setActiveTab(this); return true; }
java
@Override public synchronized void addCallBack(RecoveryLogCallBack callback) { if (tc.isEntryEnabled()) Tr.entry(tc, "addCallBack", callback); if (_registeredCallbacks == null) { _registeredCallbacks = new HashSet<RecoveryLogCallBack>(); } _registeredCallbac...
python
def get_qualifier(self): """Gets the qualifier for this authorization. return: (osid.authorization.Qualifier) - the qualifier raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template...
python
def calc_atlas_projections(subject_cortices, atlas_cortices, atlas_map, worklog, atlases=Ellipsis): ''' calc_atlas_projections calculates the lazy map of atlas projections. Afferent parameters: @ atlases The atlases that should be applied to the subject. This can be specified as a list/tuple...
python
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 4: return self.print_help() text_format = gf.safe_unicode(self.actual_arguments[0]) if text_format == u"list": ...
python
def plot_sfs_folded(*args, **kwargs): """Plot a folded site frequency spectrum. Parameters ---------- s : array_like, int, shape (n_chromosomes/2,) Site frequency spectrum. yscale : string, optional Y axis scale. bins : int or array_like, int, optional Allele count bins....
python
def load_file(self, file_obj, verbose): """ The type of open file objects such as sys.stdout; alias of the built-in file. @TODO: when is this used? """ if verbose: printDebug("----------") if verbose: printDebug("Reading: <%s> ...'" % file_obj.name) if type(file...
java
protected void bingo(int risk, int confidence, String uri, String param, String attack, String otherInfo, HttpMessage msg) { bingo(risk, confidence, this.getName(), this.getDescription(), uri, param, attack, otherInfo, this.getSolution(), msg); }
python
def calculate_normals(vertices): """Return Nx3 normal array from Nx3 vertex array.""" verts = np.array(vertices, dtype=float) normals = np.zeros_like(verts) for start, end in pairwise(np.arange(0, verts.shape[0] + 1, 3)): vecs = np.vstack((verts[start + 1] - verts[start], verts[start + 2] - vert...
python
def find_project_config_file(project_root: str) -> str: """Return absolute path to project-specific config file, if it exists. :param project_root: Absolute path to project root directory. A project config file is a file named `YCONFIG_FILE` found at the top level of the project root dir. Return ...
java
private JToolBar getToolbar() { if (toolbar == null) { toolbar = new JToolBar("Classification"); toolbar.add(getTagsButton()); toolbar.add(getClassesButton()); } return toolbar; }
python
async def AddPendingResources(self, application_tag, charm_url, resources): """Fix the calling signature of AddPendingResources. The ResourcesFacade doesn't conform to the standard facade pattern in the Juju source, which leads to the schemagened code not matching up properly with the a...
python
def optimize_image(arg): """Optimize a given image from a filename.""" try: filename, image_format, settings = arg Settings.update(settings) format_module, nag_about_gifs = _get_format_module(image_format) if format_module is None: if Settings.verbose > 1: ...
java
public Texture createTexture (Texture.Config config) { if (!isLoaded()) throw new IllegalStateException( "Cannot create texture from unready image: " + this); int texWidth = config.toTexWidth(pixelWidth()); int texHeight = config.toTexHeight(pixelHeight()); if (texWidth <= 0 || texHeight <= 0) th...
python
def return_resource(self, resource, status=200, statusMessage="OK"): """Return a resource response :param str resource: The JSON String representation of a resource response :param int status: Status code to use :param str statusMessage: The message to use in the error response ...
python
def clean(self): """Check that at least one service has been entered.""" super(AtLeastOneRequiredInlineFormSet, self).clean() if any(self.errors): return if not any(cleaned_data and not cleaned_data.get('DELETE', False) for cleaned_data in self.cleaned_data): rais...
java
public int getBlastGapCreation() { String gapCosts = getAlignmentOption(GAPCOSTS); try { String gapCreation = gapCosts.split("\\+")[0]; return Integer.parseInt(gapCreation); } catch (Exception e) { return -1; } }
java
public synchronized final void setClassShutter(ClassShutter shutter) { if (sealed) onSealedMutation(); if (shutter == null) throw new IllegalArgumentException(); if (hasClassShutter) { throw new SecurityException("Cannot overwrite existing " + ...
python
def get_user(self, id, **kwargs): # noqa: E501 """Retrieves a user by identifier (email addr) # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_user(id, asy...
python
def binding_of(self, typevar): """Returns the type the typevar is bound to, or None.""" if typevar in self._ns: return self._ns[typevar] if self._instance_ns and typevar in self._instance_ns: return self._instance_ns[typevar] return None
java
public UnixPath toAbsolutePath(UnixPath currentWorkingDirectory) { checkArgument(currentWorkingDirectory.isAbsolute()); return isAbsolute() ? this : currentWorkingDirectory.resolve(this); }
python
def lookstr(table, limit=0, **kwargs): """Like :func:`petl.util.vis.look` but use str() rather than repr() for data values. """ kwargs['vrepr'] = str return look(table, limit=limit, **kwargs)
python
def get(self, aud=None): """Retrieves the jti and aud of all tokens in the blacklist. Args: aud (str, optional): The JWT's aud claim. The client_id of the application for which it was issued. See: https://auth0.com/docs/api/management/v2#!/Blacklists/get_tokens ...
java
public static <T> KeyRange<T> atMost(final T stop) { return new KeyRange<>(KeyRangeType.FORWARD_AT_MOST, null, stop); }
java
EditText generatePinBox(int i, int inputType) { EditText editText = (EditText) LayoutInflater.from(getContext()).inflate(R.layout.partial_pin_box, this, false); int generateViewId = PinViewUtils.generateViewId(); editText.setId(generateViewId); editText.setTag(i); if (inputType !...
python
def get_flops(): """ # DOESNT WORK """ from sys import stdout from re import compile filename = "linpack.out" fpnum = r'\d+\.\d+E[+-]\d\d' fpnum_1 = fpnum + r' +' pattern = compile(r'^ *' + fpnum_1 + fpnum_1 + fpnum_1 + r'(' + fpnum + r') +' + fpnum_1 + fpnum + r' *\n$') speeds = [0.0, ...
python
def queryTs(ts, expression): """ Find the indices of the time series entries that match the given expression. | Example: | D = lipd.loadLipd() | ts = lipd.extractTs(D) | matches = queryTs(ts, "archiveType == marine sediment") | matches = queryTs(ts, "geo_meanElev <= 2000") :param str e...
java
public static void main(String args[]) throws ParseException { SPathParser parser = new SPathParser(System.in); Path p = parser.expression(); java.util.List l = p.getSteps(); // output for simple testing System.out.println(); if (p instanceof AbsolutePath) System.out.println("Root: /"...
java
public Entity get(Entity where) throws SQLException { return db.find(null, fixEntity(where), new EntityHandler()); }
java
public String filter (String msg, Name otherUser, boolean outgoing) { // first, check against the drop-always list _stopMatcher.reset(msg); if (_stopMatcher.find()) { return null; } // then see what kind of curse filtering the user has configured Mode lev...
python
def run(ident): '''Launch or resume an harvesting for a given source if none is running''' source = get_source(ident) cls = backends.get(current_app, source.backend) backend = cls(source) backend.harvest()
java
public void updateTextureParameters(GVRTextureParameters textureParameters) { mTextureParams = textureParameters; long nativePtr = getNative(); if (nativePtr != 0) { NativeTexture.updateTextureParameters(nativePtr, textureParameters.getCurrentValuesArray()); } ...
java
@Override public void apply(final App app, final Page sourcePage, final Page newPage) throws FrameworkException { final InsertPosition insertPosition = findInsertPosition(sourcePage, parentHash, siblingHashes, newNode); if (insertPosition != null) { final DOMNode parent = insertPosition.getParent(); ...
java
public String foreignKeyColumnName( String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName ) { String header = propertyName != null ? unqualify( propertyName ) : propertyTableName; checkState(header != null, "NamingStrategy not properly filled"); return col...
java
void or(LongBitSet other) { assert other.numWords <= numWords : "numWords=" + numWords + ", other.numWords=" + other.numWords; int pos = Math.min(numWords, other.numWords); while (--pos >= 0) { bits[pos] |= other.bits[pos]; } }
java
public final ProtoParser.enum_block_return enum_block(Proto proto, Message message) throws RecognitionException { ProtoParser.enum_block_return retval = new ProtoParser.enum_block_return(); retval.start = input.LT(1); Object root_0 = null; Token ENUM118=null; Token ID119=null; ...
python
def gen_sites(path): " Seek sites by path. " for root, _, _ in walklevel(path, 2): try: yield Site(root) except AssertionError: continue
python
def authenticate(self): """Determine the current domain and zone IDs for the domain.""" try: payload = self._api.domain.info(self._api_key, self._domain) self._zone_id = payload['zone_id'] return payload['id'] except xmlrpclib.Fault as err: raise E...
java
public Observable<ServiceResponse<TroubleshootingResultInner>> beginGetTroubleshootingResultWithServiceResponseAsync(String resourceGroupName, String networkWatcherName, String targetResourceId) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is req...
python
def start(self): """Start the logging for this entry""" if (self.cf.link is not None): if (self._added is False): self.create() logger.debug('First time block is started, add block') else: logger.debug('Block already registered, sta...
python
def get_filebase(path, pattern): """Get the end of *path* of same length as *pattern*.""" # A pattern can include directories tail_len = len(pattern.split(os.path.sep)) return os.path.join(*str(path).split(os.path.sep)[-tail_len:])
java
private void createObjectClass(Set<String> objectClasses, DirContext schemaContext, ObjectSchema schema) throws NamingException, ClassNotFoundException { // Super classes Set<String> supList = new HashSet<String>(); // For each of the given object classes for (String...
java
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/2563") public CallOptions withMaxInboundMessageSize(int maxSize) { checkArgument(maxSize >= 0, "invalid maxsize %s", maxSize); CallOptions newOptions = new CallOptions(this); newOptions.maxInboundMessageSize = maxSize; return newOptions; }
python
def send_tan(self, challenge: NeedTANResponse, tan: str): """ Sends a TAN to confirm a pending operation. :param challenge: NeedTANResponse to respond to :param tan: TAN value :return: Currently no response """ with self._get_dialog() as dialog: tan_...
python
def refresh_token(self): """Refresh token""" # perform the request r = self.session.get(self.base_url + '/refresh_token') r.raise_for_status() # set the Authorization header self.session.headers['Authorization'] = 'Bearer ' + r.json()['token'] # update token_dat...
java
private void leftDelete( GBSNode p, GBSNode r, Object deleteKey, DeleteNode point) { if (r == null) /* There is no upper predecessor */ ...
python
def get_tile_properties_by_layer(self, layer): """ Get the tile properties of each GID in layer :param layer: layer number :rtype: iterator of (gid, properties) tuples """ try: assert (int(layer) >= 0) layer = int(layer) except (TypeError, Asserti...
java
public JSONObject newsSummary(String content, int maxSummaryLen, HashMap<String, Object> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("content", content); request.addBody("max_summary_len", maxSummaryLen); if ...
java
public MucEnterConfiguration.Builder getEnterConfigurationBuilder(Resourcepart nickname) { return new MucEnterConfiguration.Builder(nickname, connection.getReplyTimeout()); }
java
@Reference(cardinality = ReferenceCardinality.MULTIPLE) protected void setJaasLoginModuleConfig(JAASLoginModuleConfig lmc, Map<String, Object> props) { String pid = (String) props.get(KEY_SERVICE_PID); loginModuleMap.put(pid, lmc); }
java
public void setStart(int index, Date value) { set(selectField(TaskFieldLists.CUSTOM_START, index), value); }
python
def _draw_uniform(self,num_reals=1): """ Draw parameter realizations from a (log10) uniform distribution described by the parameter bounds. Respect Log10 transformation Parameters ---------- num_reals : int number of realizations to generate """ if ...
java
@Override public GenerateCredentialReportResult generateCredentialReport(GenerateCredentialReportRequest request) { request = beforeClientExecution(request); return executeGenerateCredentialReport(request); }
java
private void checkInitializationMethod(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException { if (!CHECKLEVEL_STRICT.equals(checkLevel)) { return; } String initMethodName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_INITIALIZATI...
java
@Override public List<Metric> transform(QueryContext context, List<Metric> metrics) { if (metrics.size() == 1) { return rangeOfOneMetric(metrics.get(0)); } else { return new MetricReducerOrMappingTransform(new RangeValueReducerOrMapping()).transform(context, metrics); ...
java
public static String getSessionID(HttpServletRequest req) { String sessionID = null; final HttpServletRequest f_req = req; try { sessionID = AccessController.doPrivileged(new PrivilegedExceptionAction<String>() { @Override public String run() throws E...
python
def normalize_params(params): """Take a list of dictionaries, and tokenize/normalize.""" # Collect a set of all fields fields = set() for p in params: fields.update(p) fields = sorted(fields) params2 = list(pluck(fields, params, MISSING)) # Non-basic types (including MISSING) are un...
python
def shall_save(self, form, name, composite_form): """ Return ``True`` if the given ``composite_form`` (the nested form of this field) shall be saved. Return ``False`` if the form shall not be saved together with the super-form. By default it will return ``False`` if the form was...
java
public void setChildrenMax(int max) { addField(ConfigureNodeFields.children_max, FormField.Type.text_single); setAnswer(ConfigureNodeFields.children_max.getFieldName(), max); }
java
public void setCancelAction(Action.OnActionListener listener) { setCancelAction(listener, null, null, null, null); }
python
def allocation(self, node_id=None, params=None): """ Allocation provides a snapshot of how shards have located around the cluster and the state of disk usage. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-allocation.html>`_ :arg node_id: A comma-separated...
java
public Optional<QueryData> list(long accountId, String query) { QueryParameterList queryParams = new QueryParameterList(); queryParams.add("nrql", encode(query)); return HTTP.GET(String.format("/v1/accounts/%d/query", accountId), null, queryParams, QUERY_DATA); }
python
def get_schedules_for_season(self, season, season_type="REG"): """ Game schedule for a specified season. """ try: season = int(season) if season_type not in ["REG", "PRE", "POST"]: raise ValueError except (ValueError, TypeError): ...
java
public static List<X509Certificate> toRootFirst(List<X509Certificate> chain) { if (chain == null || chain.isEmpty()) throw new IllegalArgumentException("Must provide a chain that is non-null and non-empty"); final List<X509Certificate> out; // Sort the list so the root certificate comes first if (!isSelfSi...
python
def _get(auth, path, fmt, autobox=True, params=None): ''' Issue a GET request to the XNAT REST API and box the response content. Example: >>> import yaxil >>> from yaxil import Format >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.get(auth...
java
private void removeIdleTimeoutConnection() { //descending iterator since first from queue are the first to be used Iterator<MariaDbPooledConnection> iterator = idleConnections.descendingIterator(); MariaDbPooledConnection item; while (iterator.hasNext()) { item = iterator.next(); long id...
python
def query_series_episodes(self, id, absolute_number=None, aired_season=None, aired_episode=None, dvd_season=None, dvd_episode=None, imdb_id=None, page=1): """Query series episodes""" # perform the request params = {'absoluteNumber': absolute_number, 'airedSeason': a...
java
public static String valueOf(char source[], int start, int limit, int offset16) { switch (bounds(source, start, limit, offset16)) { case LEAD_SURROGATE_BOUNDARY: return new String(source, start + offset16, 2); case TRAIL_SURROGATE_BOUNDARY: return new String(source, start...
java
boolean deleteInternal(String src, INode[] inodes, boolean recursive, boolean enforcePermission) throws IOException { ArrayList<BlockInfo> collectedBlocks = new ArrayList<BlockInfo>(); INode targetNode = null; byte[][] components = inodes == null ? INodeDirectory.getPathCompo...
java
@Override protected void prepare(final AbstractSQLInsertUpdate<?> _insertUpdate, final Attribute _attribute, final Object... _values) throws SQLException { checkSQLColumnSize(_attribute, 1); try { _insertUpdate.column(_att...
java
private void writeLegacyFormatting(List<Object> list, Object paramExtractor) { if (paramExtractor != null) { list.add("{\"params\":"); list.add(paramExtractor); list.add(","); } else { list.add("{"); } if (HAS_SCRIPT) { ...
java
private void populateContainer(FieldType field, byte[] values, byte[] descriptions) { CustomField config = m_container.getCustomField(field); CustomFieldLookupTable table = config.getLookupTable(); List<Object> descriptionList = convertType(DataType.STRING, descriptions); List<Object> valueL...
python
def flat(l): """ Returns the flattened version of a '2D' list. List-correlate to the a.flat() method of NumPy arrays. Usage: flat(l) """ newl = [] for i in range(len(l)): for j in range(len(l[i])): newl.append(l[i][j]) return newl