language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def decr(self, name, amount=1): """ Decrease the value at key ``name`` by ``amount``. If no key exists, the value will be initialized as 0 - ``amount`` . Like **Redis.DECR** :param string name: the key name :param int amount: decrements :return: the integer valu...
java
@View(name = "by_type_and_local_date_time", map = "function(doc) { emit([doc.type, doc.creationTime], doc) }") public List<CouchDbCasEvent> findByTypeSince(final String type, final LocalDateTime localDateTime) { val view = createQuery("by_type_and_local_date_time").startKey(ComplexKey.of(type, localDateTime...
python
def feed(self, data): """ Add new incoming data to buffer and try to process """ self.buffer += data while len(self.buffer) >= 6: self.next_packet()
java
public static Expression decodeJson(JsonObject json) { char[] encoded = JsonStringEncoder.getInstance().quoteAsString(json.toString()); return x("DECODE_JSON(\"" + new String(encoded) + "\")"); }
java
public String decryptStr(String data, KeyType keyType) { return decryptStr(data, keyType, CharsetUtil.CHARSET_UTF_8); }
python
def _build_parent_list(policy_definition, return_full_policy_names, adml_language): ''' helper function to build a list containing parent elements of the ADMX policy ''' parent_list = [] policy_namespace = list(policy_definition.nsmap.keys())[0] ...
java
public static PredicateExpression nin(Object... rhs) { PredicateExpression ex = new PredicateExpression("$nin", rhs); if (rhs.length == 1) { ex.single = true; } return ex; }
java
private static File artifactToFile(final Artifact artifact) throws IllegalArgumentException { if (artifact == null) { throw new IllegalArgumentException("ArtifactResult must not be null"); } // FIXME: this is not a safe assumption, file can have a different name if ("pom.xml...
python
def token_new(): """Create new token.""" form = TokenForm(request.form) form.scopes.choices = current_oauth2server.scope_choices() if form.validate_on_submit(): t = Token.create_personal( form.data['name'], current_user.get_id(), scopes=form.scopes.data ) db.session....
java
private ScheduleTaskImpl readInTask(Element el) throws PageException { long timeout = su.toLong(el, "timeout"); if (timeout > 0 && timeout < 1000) timeout *= 1000; if (timeout < 0) timeout = 600000; try { ScheduleTaskImpl st = new ScheduleTaskImpl(this, su.toString(el, "name").trim(), su.toResource(config, el,...
python
def empty_directory(path=None): """ Context manager that creates a temporary directory, and cleans it up when exiting. >>> with empty_directory(): >>> pass """ install_dir = tempfile.mkdtemp(dir=path) try: yield install_dir finally: shutil.rmtree(install_dir)
python
def get_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """ from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %...
python
def send_email_with_callback_token(user, email_token, **kwargs): """ Sends a Email to user.email. Passes silently without sending in test environment """ try: if api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS: # Make sure we have a sending address before sending. ...
java
private void resolveDependenciesInParallel(List<DependencyNode> nodes) { List<ArtifactRequest> artifactRequests = nodes.stream() .map(node -> new ArtifactRequest(node.getArtifact(), this.remoteRepositories, null)) .collect(Collectors.toList()); try { this.res...
python
def __get_owner_windows(self): """ Return the name of the owner of this file or directory. Follow symbolic links. Return a name of the form ``r'DOMAIN\\User Name'``; may be a group. .. seealso:: :attr:`owner` """ desc = win32security.GetFileSecurity( ...
java
public Observable<ServiceResponse<Export>> exportIterationWithServiceResponseAsync(UUID projectId, UUID iterationId, String platform, String flavor) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (iterationId...
python
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. If there are ``summarized_intensities`` provided, reads the files (:py:func:`read_summarized_intensities`) and skips to ste...
python
def task_class(self): """Return the Task class type configured for the scenario.""" from scenario_player.tasks.base import get_task_class_for_type root_task_type, _ = self.task task_class = get_task_class_for_type(root_task_type) return task_class
java
public SlotOffer generateSlotOffer() { Preconditions.checkState(TaskSlotState.ACTIVE == state || TaskSlotState.ALLOCATED == state, "The task slot is not in state active or allocated."); Preconditions.checkState(allocationId != null, "The task slot are not allocated"); return new SlotOffer(allocationId, index,...
python
def __setUpTrakers(self): ''' set securities ''' for security in self.securities: self.__trakers[security]=OneTraker(security, self, self.buying_ratio)
python
def parse_mmtf_header(infile): """Parse an MMTF file and return basic header-like information. Args: infile (str): Path to MMTF file Returns: dict: Dictionary of parsed header Todo: - Can this be sped up by not parsing the 3D coordinate info somehow? - OR just store th...
java
public static String encryptMD5(String data) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); return copyValueOf(Hex.encodeHex(digest.digest(data.getBytes(StandardCharsets.UTF_8)))); } catch (final NoSuchAlgorithmException ex) { throw new TechnicalExce...
python
def get_form_class(self, request, plugins, plugin): """ Returns a subclass of Form to be used by this plugin """ widget = self.get_editor_widget( request=request, plugins=plugins, plugin=plugin, ) instance = plugin.get_plugin_instance(...
python
def get_file_object(username, password, utc_start=None, utc_stop=None): """Make the connection. Return a file-like object.""" if not utc_start: utc_start = datetime.now() if not utc_stop: utc_stop = utc_start + timedelta(days=1) logging.info("Downloading schedules for username [%s] in...
python
def get_value(self, name): """Ask kernel for a value""" code = u"get_ipython().kernel.get_value('%s')" % name if self._reading: method = self.kernel_client.input code = u'!' + code else: method = self.silent_execute # Wait until the kernel ret...
python
def from_xyzt_string(xyzt_string): """ Args: xyz_string: string of the form 'x, y, z, +1', '-x, -y, z, -1', '-2y+1/2, 3x+1/2, z-y+1/2, +1', etc. Returns: MagSymmOp object """ symmop = SymmOp.from_xyz_string(xyzt_string.rsplit(',', 1)[0]) ...
python
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution ord...
python
def construct_request(model_type, client_name, client_pass, command, values): """ Construct the request url. Inputs: - model_type: PServer usage mode type. - client_name: The PServer client name. - client_pass: The PServer client's password. - command: A PServer command....
python
def create_items(self, items, container_id, scope=None): """CreateItems. [Preview API] Creates the specified items in in the referenced container. :param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.file_container.models.VssJsonCollectionWrapper>` items: :param int container_id:...
java
public static <T1, T2, T3, R> Func3<T1, T2, T3, Observable<R>> toAsync(Func3<? super T1, ? super T2, ? super T3, ? extends R> func) { return toAsync(func, Schedulers.computation()); }
java
@Override public boolean killJob() { List<String> auroraCmd = new ArrayList<>(Arrays.asList("aurora", "job", "killall")); auroraCmd.add(jobSpec); appendAuroraCommandOptions(auroraCmd, isVerbose); return runProcess(auroraCmd); }
python
def remote_server_command(command, environment, user_profile, **kwargs): """ Wraps web_command function with docker bindings needed to connect to a remote server (such as datacats.com) and run commands there (for example, when you want to copy your catalog to that server). The files binded ...
java
public AnnotationType annotationType(Attribute.Compound a, Symbol s) { Attribute.Compound atTarget = a.type.tsym.attribute(syms.annotationTargetType.tsym); if (atTarget == null) { return inferTargetMetaInfo(a, s); } Attribute atValue = atTarget.member(names.value)...
java
private void saveAddInfo(String key, String value) { int pos = key.indexOf("@"); String className = ""; if (pos > -1) { className = key.substring(pos + 1); key = key.substring(0, pos); } if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) { m_...
python
def on_zijd_mark(self, event): """ Get mouse position on double right click find the interpretation in range of mouse position then mark that interpretation bad or good Parameters ---------- event : the wx Mouseevent for that click Alters ------ ...
python
def put(self, request, bot_id, id, format=None): """ Update existing Telegram chat state --- serializer: TelegramChatStateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request...
python
def select_symbols(self, symbols, ret_list=False): """ Return a :class:`PseudoTable` with the pseudopotentials with the given list of chemical symbols. Args: symbols: str or list of symbols Prepend the symbol string with "-", to exclude pseudos. ret_list:...
java
private <T> Optional<T> tryWithLock(long timeout, TimeUnit unit, Supplier<T> task) { checkLockNotHeld("Lock can not be reacquired"); boolean acquired = false; try { acquired = exclusiveLock.tryLock(timeout, unit); } catch (InterruptedException e) { Th...
java
public Mac getMac(final @NotNull String alias) { try { Mac mac = Mac.getInstance(getAlgorithm(alias)); mac.init(new SecretKeySpec(secret, mac.getAlgorithm())); return mac; } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeExcep...
java
public SubscriptionEnvelope deleteSubscription(String subId) throws ApiException { ApiResponse<SubscriptionEnvelope> resp = deleteSubscriptionWithHttpInfo(subId); return resp.getData(); }
java
public JvmTypeReference wildcardExtends(JvmTypeReference extendsBound) { WildcardTypeReference wildcardTypeReference = typeReferenceOwner.newWildcardTypeReference(); wildcardTypeReference.addUpperBound(typeReferenceOwner.toLightweightTypeReference(extendsBound)); return wildcardTypeReference.toTypeReference(); }
java
public static TreeRewriteRule compile(final String rule) { final String[] parts = rule.split("->"); if (parts.length != 2) { throw new IllegalArgumentException(format( "Invalid rewrite rule: %s", rule )); } return of( TreePattern.compile(parts[0]), TreePattern.compile(parts[1]) ); }
java
public static UNode createArrayNode(String name) { return new UNode(name, NodeType.ARRAY, null, false, ""); }
python
def size_tee(Q1, Q2, D, D2, n=1, pipe_diameters=5): r'''Calculates CoV of an optimal or specified tee for mixing at a tee according to [1]_. Assumes turbulent flow. The smaller stream in injected into the main pipe, which continues straight. COV calculation is according to [2]_. .. math:: ...
java
public ValueList getValues(PExp exp, ObjectContext ctxt) { try { return exp.apply(af.getExpressionValueCollector(), ctxt);// FIXME: should we handle exceptions like this } catch (AnalysisException e) { return null; // Most have none } }
python
def login_url(self, org=None): """ Returns the login url which will automatically log into the target Salesforce org. By default, the org_name passed to the library constructor is used but this can be overridden with the org option to log into a different org. """ ...
java
@Override public void persistJoinTable(JoinTableData joinTableData) { String joinTableName = joinTableData.getJoinTableName(); String joinColumnName = joinTableData.getJoinColumnName(); String invJoinColumnName = joinTableData.getInverseJoinColumnName(); Map<Object, Set<Object>> ...
python
def begin_connection(self, connection_id, internal_id, callback, context, timeout): """Asynchronously begin a connection attempt Args: connection_id (int): The external connection id internal_id (string): An internal identifier for the connection callback (callable):...
python
def field_dict_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), strip=True, blank_none=True, ignore_related=True, ignore_values=(None,), ignore_errors=Tr...
python
def _config_sortable(self, sortable): """Configure a new sortable state""" for col in self["columns"]: command = (lambda c=col: self._sort_column(c, True)) if sortable else "" self.heading(col, command=command) self._sortable = sortable
java
JsonEvent readEvent() throws IOException { char next = readNext(); // whitespace while (next == ' ' || next == '\t' || next == '\n' || next == '\r') { next = readNext(); } // identify token switch (next) { case '{': return JsonEvent...
python
def _record(self, value, rank, delta, successor): """Catalogs a sample.""" self._observations += 1 self._items += 1 return _Sample(value, rank, delta, successor)
python
def contains(self, string): """Summary Returns: TYPE: Description """ # Check that self.weld_type is a string type vectype = self.weld_type if isinstance(vectype, WeldVec): elem_type = vectype.elemType if isinstance(elem_type, WeldChar): ...
python
def email_type(arg): """An argparse type representing an email address.""" if not is_valid_email_address(arg): raise argparse.ArgumentTypeError("{0} is not a valid email address".format(repr(arg))) return arg
python
def add_to_cart(item_id): """ Cart with Product """ cart = Cart(session['cart']) if cart.change_item(item_id, 'add'): session['cart'] = cart.to_dict() return list_products()
python
async def info(self, fields: Iterable[str] = None) -> dict: ''' Returns the keypair's information such as resource limits. :param fields: Additional per-agent query fields to fetch. .. versionadded:: 18.12 ''' if fields is None: fields = ( 'a...
java
public static void validateOutputLayerForClassifierEvaluation(Layer outputLayer, Class<? extends IEvaluation> classifierEval){ if(outputLayer instanceof Yolo2OutputLayer){ throw new IllegalStateException("Classifier evaluation using " + classifierEval.getSimpleName() + " class cannot be applied for ...
python
def distance_centimeters_continuous(self): """ Measurement of the distance detected by the sensor, in centimeters. The sensor will continue to take measurements so they are available for future reads. Prefer using the equivalent :meth:`UltrasonicSensor.distance_centimet...
python
def list_directories(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all the directories using their absolute paths within the specified directory, optionally recursively. :param dir_pathname: The directo...
java
IAtom getUnplacedHeavyAtom(IAtomContainer molecule) { for (IAtom atom : molecule.atoms()) { if (isUnplacedHeavyAtom(atom)) return atom; } return null; }
python
def _merge_entity(entity, if_match, require_encryption=False, key_encryption_key=None): ''' Constructs a merge entity request. ''' _validate_not_none('if_match', if_match) _validate_entity(entity) _validate_encryption_unsupported(require_encryption, key_encryption_key) request = HTTPRequest...
python
def get_field_errors(node): """ return a list of FieldErrors if the specified securityData element has field errors """ assert node.Name == 'securityData' and not node.IsArray nodearr = node.GetElement('fieldExceptions') if nodearr.NumValues > 0: secid = XmlHelper.get_child_v...
python
def _initialize(self, runtime): """Common initializer for OsidManager and OsidProxyManager""" if runtime is None: raise NullArgument() if self._my_runtime is not None: raise IllegalState('this manager has already been initialized.') self._my_runtime = runtime ...
java
public int getOffsetForPattern(IXtextDocument document, int startOffset, String pattern) { final Pattern compiledPattern = Pattern.compile(pattern); final Matcher matcher = compiledPattern.matcher(document.get()); if (matcher.find(startOffset)) { final int end = matcher.end(); return end; } return -1; ...
java
@ReadOperation public Map<String, Object> handle(final String username, final String password, final String service) { val selectedService = this.serviceFactory.createService(service); val registeredService = this.servicesM...
java
public double[] positionAt( int col, int row ) { if (isInRaster(col, row)) { GridGeometry2D gridGeometry = getGridGeometry(); Coordinate coordinate = CoverageUtilities.coordinateFromColRow(col, row, gridGeometry); return new double[]{coordinate.x, coordinate.y}; } ...
java
public String getModuleJenkinsJobInfo(final DbArtifact dbArtifact) { final DbModule module = getModule(dbArtifact); if(module == null){ return ""; } final String jenkinsJobUrl = module.getBuildInfo().get("jenkins-job-url"); if(jenkinsJobUrl == null){ return ""; } return jenkinsJobUrl; }
python
def get_local_addr(self, timeout=None): """ Retrieve the current local address. :param timeout: If not given or given as ``None``, waits until the local address is available. Otherwise, waits for as long as specified. If the local ...
python
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is exist. name A user-defined chain name. table The table to own the chain. family Networking family, either ipv4 or ipv6...
python
def write_phosphopath_ratio(df, f, a, *args, **kwargs): """ Write out the data frame ratio between two groups protein-Rsite-multiplicity-timepoint ID Ratio Q13619-S10-1-1 0.5 Q9H3Z4-S10-1-1 0.502 Q6GQQ9-S100-1-1 0.504 Q86YP4-S100-1-1 0.506 Q9H307-S100-1-1 0.508 Q8NEY1-S1000-1-1 0...
java
public static List<CPDefinitionVirtualSetting> toModels( CPDefinitionVirtualSettingSoap[] soapModels) { if (soapModels == null) { return null; } List<CPDefinitionVirtualSetting> models = new ArrayList<CPDefinitionVirtualSetting>(soapModels.length); for (CPDefinitionVirtualSettingSoap soapModel : soapMode...
java
public static String getIssuerFromSamlObject(final SAMLObject object) { if (object instanceof RequestAbstractType) { return RequestAbstractType.class.cast(object).getIssuer().getValue(); } if (object instanceof StatusResponseType) { return StatusResponseType.class.cast(ob...
java
protected void evict() { lock.lock(); Map<K, E> removingObjects = null; try { for (Map.Entry<K, E> entry : pool.entrySet()) { if (entry.getValue().activityPrint().isExpired()) { if (removingObjects == null) { removi...
python
def _create_lua_method(self, name, code): """ Registers the code snippet as a Lua script, and binds the script to the client as a method that can be called with the same signature as regular client methods, eg with a single key arg. """ script = self.register_scri...
python
def hav_dist(locs1, locs2): """ Return a distance matrix between two set of coordinates. Use geometric distance (default) or haversine distance (if longlat=True). Parameters ---------- locs1 : numpy.array The first set of coordinates as [(long, lat), (long, lat)]. locs2 : numpy.arra...
java
static void injectSecond(SpanContext spanContext, Headers headers, Tracer tracer) { tracer.inject(spanContext, Format.Builtin.TEXT_MAP, new HeadersMapInjectAdapter(headers, true)); }
python
def cheat(num): """View the answer to a problem.""" # Define solution before echoing in case solution does not exist solution = click.style(Problem(num).solution, bold=True) click.confirm("View answer to problem %i?" % num, abort=True) click.echo("The answer to problem {} is {}.".format(num, solutio...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ntp_sync_responses result = (ntp_sync_responses) service.get_payload_formatter().string_to_resource(ntp_sync_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION...
python
def write(self, data): """Write ``data`` into the wire. Returns an empty tuple or a :class:`~asyncio.Future` if this protocol has paused writing. """ if self.closed: raise ConnectionResetError( 'Transport closed - cannot write on %s' % self ...
java
public static <E> Iterator<E> slice(long from, long howMany, Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot call slice with a null iterable"); final Iterator<E> dropping = new FilteringIterator<E>(iterable.iterator(), new DropWhile<E>(new UntilCount<E>(from))); return new Tak...
java
@Nonnull public static ACLContext as(@CheckForNull User user) { return as(user == null ? Jenkins.ANONYMOUS : user.impersonate()); }
python
def timestamp(value, timezone=None): """ Returns a timestamp literal if value is likely coercible to a timestamp Parameters ---------- value : timestamp value as string timezone: timezone as string defaults to None Returns -------- result : TimestampScalar """ if is...
python
def jump(self, addr): """ Add an exit representing jumping to an address. """ self.inhibit_autoret = True self._exit_action(self.state, addr) self.successors.add_successor(self.state, addr, self.state.solver.true, 'Ijk_Boring')
java
public static <T extends CharSequence> T notEmpty(final T chars, final String message) { return INSTANCE.notEmpty(chars, message); }
java
private boolean readIntoPushBack() throws IOException { // File finished? boolean eof = false; // Next char. final int ch = in.read(); if (ch >= 0) { // Discard whitespace at start? if (!(pulled == 0 && isWhiteSpace(ch))) { // Good code. ...
java
public synchronized AsynchConsumerProxyQueue createOrderedProxyQueue(OrderingContext context) throws SIResourceException, SIIncorrectCallException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createOrderedProxyQueue", context); short id = nextId(); ...
python
def index_raw_bulk(self, header, document): """ Function helper for fast inserting :param header: a string with the bulk header must be ended with a newline :param document: a json document string must be ended with a newline """ self.bulker.add("%s%s" % (header, documen...
python
async def unsubscribe(self, container, *keys): ''' Unsubscribe specified channels. Every subscribed key should be unsubscribed exactly once, even if duplicated subscribed. :param container: routine container :param \*keys: subscribed channels ''' await s...
python
def OpenFileObject(cls, path_spec_object, resolver_context=None): """Opens a file-like object defined by path specification. Args: path_spec_object (PathSpec): path specification. resolver_context (Optional[Context]): resolver context, where None represents the built in context which is n...
java
@Override public FedoraBinary find(final FedoraSession session, final String path) { return cast(findNode(session, path)); }
python
def makedoetree(ddict, bdict): """makedoetree""" dlist = list(ddict.keys()) blist = list(bdict.keys()) dlist.sort() blist.sort() #make space dict doesnot = 'DOES NOT' lst = [] for num in range(0, len(blist)): if bdict[blist[num]] == doesnot:#belong lst = lst + [bl...
java
public float[] viewArea(float[] area) { float s = 1.0f / (m00 * m11 - m01 * m10); float rm00 = m11 * s; float rm01 = -m01 * s; float rm10 = -m10 * s; float rm11 = m00 * s; float rm20 = (m10 * m21 - m20 * m11) * s; float rm21 = (m20 * m01 - m00 * m21) * s; ...
python
def _layout(self): """Initial layout of grid""" self.EnableGridLines(False) # Standard row and col sizes for zooming default_cell_attributes = \ self.code_array.cell_attributes.default_cell_attributes self.std_row_size = default_cell_attributes["row-height"] ...
java
public static Counter counter(String name, String... tags) { return globalRegistry.counter(name, tags); }
java
public XMLGregorianCalendar newXMLGregorianCalendarTime( final int hours, final int minutes, final int seconds, final int timezone) { return newXMLGregorianCalendar( DatatypeConstants.FIELD_UNDEFINED, // Year DatatypeConstants.FIEL...
python
def all_species_release_pairs(cls): """ Generator which yields (species, release) pairs for all possible combinations. """ for species_name in cls.all_registered_latin_names(): species = cls._latin_names_to_species[species_name] for _, release_range in spe...
python
def find_clean_dirs(self): """Finds all (temporary) directories according to the glob and re patterns that should be cleaned.""" for folder in glob.glob(self.glob_pattern): if re.match(self.re_pattern, folder): yield folder for folder in glob.glob(self.orig_glob_patt...
java
protected void rebuild() { mandatoryArcsList.clear(); ISet nei; for (int i = 0; i < n; i++) { nei = gV.getMandNeighOf(i); for (int j : nei) { if (i < j) { mandatoryArcsList.add(i * n + j); } } } }
java
public CmsResource createResource( CmsDbContext dbc, String resourcePath, CmsResource resource, byte[] content, List<CmsProperty> properties, boolean importCase) throws CmsException { CmsResource newResource = null; if (resource.isFolder()) { ...
python
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError as e: msg = "invalid Python installation: unable to open %s" % makefile i...