language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def insert_volume(self, metadata, attachments=[]): '''Insert a new volume Returns the ID of the added volume `metadata` must be a dict containg metadata of the volume:: { "_language" : "it", # language of the metadata "key1" : "value1", # attribute ...
python
def scroll_to_bottom(self): """ Scoll to the very bottom of the page TODO: add increment & delay options to scoll slowly down the whole page to let each section load in """ if self.driver.selenium is not None: try: self.driver.selenium.execute_script("...
java
public void toBeBetween(double lower, double upper) { Arguments.ensureTrue(lower < upper, "upper has to be greater than lower"); boolean isBetween = this.value >= lower && this.value <= upper; Expectations.expectTrue(isBetween, "Expected %s to be between %s and %s", this.value, lower, upper); }
java
protected void initWidget(Widget widget) { // Validate. Make sure the widget is not being set twice. if (m_widget != null) { throw new IllegalStateException("Composite.initWidget() may only be " + "called once."); } // Use the contained widget's element as the composite's e...
java
protected Node findNextWrite() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "findNextWrite entry: on node " + this + "With status: " + status + "and positive ratio of: " + getPriorityRatioPositive()); } if (status == NODE_STATUS.REQUESTING_WRITE...
java
public void register(Label label, List<StackSize> stackSizes) { sizes.put(label, stackSizes); }
python
async def update_state(self, msg, _context): """Update the status of a service.""" name = msg.get('name') status = msg.get('new_status') await self.service_manager.update_state(name, status)
java
public static AuthCallsIpAccessControlListMappingDeleter deleter(final String pathAccountSid, final String pathDomainSid, final String pathSid) { return new AuthCallsIpAcce...
java
public Activation[] getActivations() { final List<Activation> list = new ArrayList<Activation>(); for (InternalAgendaGroup group : this.agendaGroups.values()) { for (Match activation : group.getActivations()) { list.add((Activation) activation); } } ...
python
def convert_UCERFSource(self, node): """ Converts the Ucerf Source node into an SES Control object """ dirname = os.path.dirname(self.fname) # where the source_model_file is source_file = os.path.join(dirname, node["filename"]) if "startDate" in node.attrib and "investigationTime" in node.attri...
java
public void setPoint( double x, double y ) { if (selection >= 0) { Coordinate coordinate = new Coordinate(x, y); pts.set(selection, coordinate); } }
python
def setup_top_concepts(rdf, mark_top_concepts): """Determine the top concepts of each concept scheme and mark them using hasTopConcept/topConceptOf.""" for cs in sorted(rdf.subjects(RDF.type, SKOS.ConceptScheme)): for conc in sorted(rdf.subjects(SKOS.inScheme, cs)): if (conc, RDF.type, ...
java
public Duration minusDays(long daysToSubtract) { return (daysToSubtract == Long.MIN_VALUE ? plusDays(Long.MAX_VALUE).plusDays(1) : plusDays(-daysToSubtract)); }
java
public static nspbr6_stats[] get(nitro_service service, options option) throws Exception{ nspbr6_stats obj = new nspbr6_stats(); nspbr6_stats[] response = (nspbr6_stats[])obj.stat_resources(service,option); return response; }
java
private boolean matches(String str, Pattern... patterns) { // Check given string against all provided patterns for (Pattern pattern : patterns) { // Fail overall test if any pattern fails to match Matcher matcher = pattern.matcher(str); if (!matcher.find()) ...
python
def help(self, message, plugin=None): """help: the normal help you're reading.""" # help_data = self.load("help_files") selected_modules = help_modules = self.load("help_modules") self.say("Sure thing, %s." % message.sender.handle) help_text = "Here's what I know how to do:" ...
java
protected Assertion validateServiceTicket(final WebApplicationService service, final String serviceTicketId) { return serviceValidateConfigurationContext.getCentralAuthenticationService().validateServiceTicket(serviceTicketId, service); }
java
public WorkflowTriggerInner get(String resourceGroupName, String workflowName, String triggerName) { return getWithServiceResponseAsync(resourceGroupName, workflowName, triggerName).toBlocking().single().body(); }
java
public void addColumn(FastTrackColumn column) { FastTrackField type = column.getType(); Object[] data = column.getData(); for (int index = 0; index < data.length; index++) { MapRow row = getRow(index); row.getMap().put(type, data[index]); } }
python
def cli(ctx, feature_id, organism="", sequence=""): """Delete a feature Output: A standard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.delete_feature(feature_id, organism=organism, sequence=sequence)
python
def _(s: Influence, cutoff: float = 0.7) -> bool: """ Returns true if both subj and obj are grounded to the UN ontology. """ return all(map(lambda c: is_well_grounded(c, cutoff), s.agent_list()))
python
def main(): """Sanitizes the loaded *.ipynb.""" with open(sys.argv[1], 'r') as nbfile: notebook = json.load(nbfile) # remove kernelspec (venvs) try: del notebook['metadata']['kernelspec'] except KeyError: pass # remove outputs and metadata, set execution counts to None ...
python
def search_texts(args, parser): """Searches texts for presence of n-grams.""" store = utils.get_data_store(args) corpus = utils.get_corpus(args) catalogue = utils.get_catalogue(args) store.validate(corpus, catalogue) ngrams = [] for ngram_file in args.ngrams: ngrams.extend(utils.get_...
java
Symbol findGlobalType(Env<AttrContext> env, Scope scope, Name name, RecoveryLoadClass recoveryLoadClass) { Symbol bestSoFar = typeNotFound; for (Symbol s : scope.getSymbolsByName(name)) { Symbol sym = loadClass(env, s.flatName(), recoveryLoadClass); if (bestSoFar.kind == TYP && s...
python
def _poll_once(self, timeout_ms, max_records): """Do one round of polling. In addition to checking for new data, this does any needed heart-beating, auto-commits, and offset updates. Arguments: timeout_ms (int): The maximum time in milliseconds to block. Returns: ...
python
def sample_from_posterior(self, A: pd.DataFrame) -> None: """ Run Bayesian inference - sample from the posterior distribution.""" self.sample_from_proposal(A) self.set_latent_state_sequence(A) self.update_log_prior(A) self.update_log_likelihood() candidate_log_joint_prob...
java
public Observable<EncryptionProtectorInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, EncryptionProtectorInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<EncryptionProtectorInner>, Encrypti...
java
public static boolean check(Class<?> clz) { if (Config.CACHE_SEEN_CLASSES_V) { int index = hash(clz); if (CACHE[index] == clz) { return true; } CACHE[index] = clz; } return false; }
python
def ids(self): """ Returns set with all todo IDs. """ if config().identifiers() == 'text': ids = self._id_todo_map.keys() else: ids = [str(i + 1) for i in range(self.count())] return set(ids)
python
def with_binaries(self, *args, **kw): """Add binaries tagged to this artifact. For example: :: provides = setup_py( name = 'my_library', zip_safe = True ).with_binaries( my_command = ':my_library_bin' ) This adds a console_script entry_point for the python_binary...
python
def _apply_udfs(self, record, hist, udf_type): """ Excute user define processes, user-defined functionalty is designed to applyies custome trasformations to data. :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ ...
java
@Override public void watch(DatabaseWatch watch, Result<Cancel> result, Object... args) { TableKelp tableKelp = _table.getTableKelp(); RowCursor minCursor = tableKelp.cursor(); RowCursor maxCursor = tableKelp.cursor(); minCursor.clear(); maxCur...
python
def id2word(self, xs): """Map id(s) to word(s) Parameters ---------- xs : int id or a list of ids Returns ------- str or list word or a list of words """ if isinstance(xs, list): return [self._id2word[x] for x ...
python
def run_command(self, stream=sys.stdout, dry_run=False): """Runs the command for this link. This method can be overridden by sub-classes to invoke a different command Parameters ----------- stream : `file` Must have 'write' function dry_run : bool ...
java
protected Apikey createFromMapInternal(@Nullable String user, long start, long duration, @Nullable Arr roles, Map<String, Object> nameAndValMap) { return createFromMapWithFingerprint(user, start, duration, roles, nameAndValMap, randomFingerprint()); }
java
public long readNBit(int n) throws IOException { if (n > 64) throw new IllegalArgumentException("Can not readByte more then 64 bit"); long val = 0; for (int i = 0; i < n; i++) { val <<= 1; val |= read1Bit(); } return val; }
python
def get_arthur_params_from_url(cls, url): # In the url the org and the repository are included params = url.split() """ Get the arthur params given a URL for the data source """ params = {"owner": params[0], "repository": params[1]} return params
python
def query(self, query): """Q.query(query string) -> category string -- return the matched category for any user query """ self.query = query self.process_query() matching_corpus_index = self.match_query_to_corpus() return self.category_list[matching_corpus_index].strip()
java
public SemanticVersion getNextVersion() { int major = head.getMajorVersion(); int minor = head.getMinorVersion(); int patch = head.getPatchVersion(); return new SemanticVersion(major, minor, patch + 1); }
python
def value_validate(self, value): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not isinstance(value, six.string_types): raise tldap.exceptions.ValidationError("should be a string")
python
async def cursor(self) -> Cursor: """Create an aiosqlite cursor wrapping a sqlite3 cursor object.""" return Cursor(self, await self._execute(self._conn.cursor))
java
@SuppressWarnings("WeakerAccess") public ApiFuture<Instance> createInstanceAsync(CreateInstanceRequest request) { return ApiFutures.transform( stub.createInstanceOperationCallable().futureCall(request.toProto(projectId)), new ApiFunction<com.google.bigtable.admin.v2.Instance, Instance>() { ...
java
protected void set(double values[][]) { this.nRows = values.length; this.nCols = values[0].length; this.values = values; for (int r = 1; r < nRows; ++r) { nCols = Math.min(nCols, values[r].length); } }
java
public void setBaselineWork(int baselineNumber, Duration value) { set(selectField(ResourceFieldLists.BASELINE_WORKS, baselineNumber), value); }
java
protected void generateMemberAppender(MemberDescription description) { if (description.isTopElement()) { return; } final TypeReference appender = description.getElementDescription().getAppenderType(); final String generatedFieldAccessor = getGeneratedMemberAccessor(description); final StringConcatenationCl...
python
def getWorkingStandingZeroPoseToRawTrackingPose(self): """Returns the standing origin from the working copy.""" fn = self.function_table.getWorkingStandingZeroPoseToRawTrackingPose pmatStandingZeroPoseToRawTrackingPose = HmdMatrix34_t() result = fn(byref(pmatStandingZeroPoseToRawTrackin...
java
public int sizeOfIn(String expr, Map<String, Object> map) { int result; Object val = getValue(map, expr); if (val instanceof Map) { result = ((Map) val).size(); } else if (val instanceof Collection) { result = ((Collection) val).size(); } else { ...
python
def get_associated_profile_names(profile_path, result_role, org_vm, server, include_classnames=False): """ Get the Associated profiles and return the string names (org:name:version) for each profile as a list. """ insts = get_associated_profiles(profile_path, result_...
python
def create_from_remote_file(self, group, snapshot=True, **args): """ Creates from remote GAF """ import requests url = "http://snapshot.geneontology.org/annotations/{}.gaf.gz".format(group) r = requests.get(url, stream=True, headers={'User-Agent': get_user_agent(modules=[...
java
public ApiResponse<MoonResponse> getUniverseMoonsMoonIdWithHttpInfo(Integer moonId, String datasource, String ifNoneMatch) throws ApiException { com.squareup.okhttp.Call call = getUniverseMoonsMoonIdValidateBeforeCall(moonId, datasource, ifNoneMatch, null); Type localVarReturnType = new Type...
java
@Override public DurationFormatterFactory setLocale(String localeName) { if (!localeName.equals(this.localeName)) { this.localeName = localeName; if (builder != null) { builder = builder.withLocale(localeName); } if (formatter != null) { formatter = formatter.withLocale...
java
@Override public String getValue(String propertyName) { String theValue = null; String theModifiedPropertyName = null; // First pass theValue = super.getValue(propertyName); // Second pass, replace Non-Alphanumeric characters if (theValue == null) { theM...
java
public long writeFrom(Readable readable) throws IOException { checkNotNull(readable); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); long written = CharStreams.copy(readable, out); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?...
java
public static Field[] getFields(Class<?> clazz, String... fieldNames) { final List<Field> fields = new LinkedList<Field>(); for (Field field : getAllFields(clazz)) { for (String fieldName : fieldNames) { if (field.getName().equals(fieldName)) { fields.add...
python
def _add_width_of(self, other_tc): """ Add the width of *other_tc* to this cell. Does nothing if either this tc or *other_tc* does not have a specified width. """ if self.width and other_tc.width: self.width += other_tc.width
java
protected int maxDepth(Layout.Node node) { int depth = 0; for(int i = 0; i < node.numChildren(); i++) { depth = Math.max(depth, maxDepth(node.getChild(i))); } return depth + 1; }
java
public void setHorizontalAlignment(final HorizontalAlignment align) { if(cell.getCellStyle().getAlignmentEnum().equals(align)) { // 既に横位置が同じ値 return; } cloneStyle(); cell.getCellStyle().setAlignment(align); }
python
def _start_plasma_store(plasma_store_memory, use_valgrind=False, use_profiler=False, stdout_file=None, stderr_file=None, plasma_directory=None, huge_pages=False, ...
java
static int readRawVarint32(final InputStream input) throws IOException { final int firstByte = input.read(); if (firstByte == -1) { throw ProtobufException.truncatedMessage(); } if ((firstByte & 0x80) == 0) { return firstByte; } ...
java
public static boolean isFloat(String s) { if (isEmpty(s)) return defaultEmptyOK; boolean seenDecimalPoint = false; if (s.startsWith(decimalPointDelimiter)) return false; // Search through string's characters one by one // until we find a non-numeric character. ...
java
public long count(List<Predicate> predicates) { // Criteria Builder CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); // Requete de criteres CriteriaQuery<Long>criteriaQuery = criteriaBuilder.createQuery(Long.class); // Construction de la racine Root<T> root = criter...
python
def preprocess_data(Xs_raw): '''Translate the center of mass (COM) of the data to the origin. Return the prossed data and the shift of the COM''' n = len(Xs_raw) Xs_raw_mean = sum(X for X in Xs_raw) / n return [X - Xs_raw_mean for X in Xs_raw], Xs_raw_mean
java
public CertificateDeleteHeaders withLastModified(DateTime lastModified) { if (lastModified == null) { this.lastModified = null; } else { this.lastModified = new DateTimeRfc1123(lastModified); } return this; }
python
def _check_1st_line(line, **kwargs): """First line check. Check that the first line has a known component name followed by a colon and then a short description of the commit. :param line: first line :type line: str :param components: list of known component names :type line: list :para...
python
async def get_async(self, type_name, **parameters): """Gets entities asynchronously using the API. Shortcut for using async_call() with the 'Get' method. :param type_name: The type of entity. :param parameters: Additional parameters to send. :return: The JSON result (decoded into a dict...
java
public static String getIdString(Object object) { if (object == null) { throw new NullPointerException(); } return String.valueOf(getId(object)); }
python
def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if name and name[0] != '<' and name[-1] != '>': return os.path.basename(name)
python
def generate_overlay_urls(self): """Return dict with overlay/URL pairs for the dataset overlays.""" overlays = {} for o in self.dataset.list_overlay_names(): url = self.generate_url(".dtool/overlays/{}.json".format(o)) overlays[o] = url return overlays
python
def access_token(self, request_token, request_secret): """Returns access_token, access_secret""" logging.debug("Getting access token from %s:%d", self.server, self.port) self.access_token, self.access_secret = \ self._token("/oauth/accessToken", request_token, r...
java
public static int cusparseXbsrsm2_zeroPivot( cusparseHandle handle, bsrsm2Info info, Pointer position) { return checkResult(cusparseXbsrsm2_zeroPivotNative(handle, info, position)); }
java
private String computeSetterName(String name) { StringBuilder _result = new StringBuilder().append(PREFIX__SETTER); _result.append(Character.toUpperCase(name.charAt(0))).append(name.substring(1)); return _result.toString(); }
python
def find(self, query): '''Passes the query to the upstream, if it exists''' if self.upstream: return self.upstream.find(query) else: return False
java
public static boolean isQueueEntry(byte[] queueRowPrefix, KeyValue keyValue) { return isQueueEntry(queueRowPrefix, keyValue.getBuffer(), keyValue.getRowOffset(), keyValue.getRowLength()); }
python
def getWindowPID(self, hwnd): """ Gets the process ID that the specified window belongs to """ pid = ctypes.c_ulong() ctypes.windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) return int(pid.value)
python
def edges(self, tail_head_iter): """Create a bunch of edges. Args: tail_head_iter: Iterable of ``(tail_name, head_name)`` pairs. """ edge = self._edge_plain quote = self._quote_edge lines = (edge % (quote(t), quote(h)) for t, h in tail_head_iter) self...
python
def lemmas(self): """Returns the synset's lemmas/variants' literal represantions. Returns ------- list of Lemmas List of its variations' literals as Lemma objects. """ return [lemma("%s.%s"%(self.name,variant.literal)) for variant in self._raw_...
java
@GwtIncompatible("Unnecessary") private Writer fileNameToOutputWriter2(String fileName) throws IOException { if (fileName == null) { return null; } if (isInTestMode()) { return new StringWriter(); } return streamToOutputWriter2(filenameToOutputStream(fileName)); }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "multiPointDomain", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "domainSet") public JAXBElement<MultiPointDomainType> createMultiPointDomain(MultiPointDomainType value) { return new JAXBElement<MultiPointDo...
python
def index(environment, start_response, headers): """ Return the status of this Kronos instance + its backends> Doesn't expect any URL parameters. """ response = {'service': 'kronosd', 'version': kronos.__version__, 'id': settings.node['id'], 'storage': {}, ...
python
def _build_voronoi_polygons(df): """ Given a GeoDataFrame of point geometries and pre-computed plot extrema, build Voronoi simplexes for the given points in the given space and returns them. Voronoi simplexes which are located on the edges of the graph may extend into infinity in some direction. In ...
python
def _section_from_spec(elf_file, spec): ''' Retrieve a section given a "spec" (either number or name). Return None if no such section exists in the file. ''' if isinstance(spec, int): num = int(spec) if num < elf_file.num_sections(): return elf_file.get_se...
java
private List<String> parseComment(List<String> content, String propertyName) { List<String> comments = new ArrayList<>(); String commentEnd = content.get(annotationIndex - 1).trim(); if (commentEnd.equals("*/")) { int startCommentIndex = -1; for (int index = annotationInd...
java
private boolean isTypedTimeFullyLegal() { if (mIs24HourMode) { // For 24-hour mode, the time is legal if the hours and minutes are each legal. Note: // getEnteredTime() will ONLY call isTypedTimeFullyLegal() when NOT in 24hour mode. int[] values = getEnteredTime(null); ...
java
private void initInflightMessageStore() { BTreeIndexFactory<String, StoredPublishEvent> indexFactory = new BTreeIndexFactory<String, StoredPublishEvent>(); indexFactory.setKeyCodec(StringCodec.INSTANCE); m_inflightStore = (SortedIndex<String, StoredPublishEvent>) m_multiIndexFactory.openOrCreat...
java
@Override public Access authenticate() { try { JSONObject user = new JSONObject(); user.put("id", mUserId); user.put("password", mPassword); JSONObject password = new JSONObject(); password.put("user", user); JSONArray methods = new JSONArray(); methods.add("password"); ...
python
def post(self, request, *args, **kwargs): """ Handles POST requests. """ self.init_attachment_cache() # Stores a boolean indicating if we are considering a preview self.preview = 'preview' in self.request.POST # Initializes the forms post_form_class = self.get_post_form...
java
public static URI asURI(final String algorithm, final String value) { try { final String scheme = DIGEST_ALGORITHM.getScheme(algorithm); return new URI(scheme, value, null); } catch (final URISyntaxException unlikelyException) { LOGGER.warn("Exception creating checks...
python
def median(arr): """median of the values, must have more than 0 entries. :param arr: list of numbers :type arr: number[] a number array :return: median :rtype: float """ if len(arr) == 0: sys.stderr.write("ERROR: no content in array to take average\n") sys.exit() if len(arr) == 1: return arr[0...
java
public static authenticationnegotiatepolicy_binding get(nitro_service service, String name) throws Exception{ authenticationnegotiatepolicy_binding obj = new authenticationnegotiatepolicy_binding(); obj.set_name(name); authenticationnegotiatepolicy_binding response = (authenticationnegotiatepolicy_binding) obj.ge...
java
@Override public List<CPInstance> getCPInstances(int start, int end) { return cpInstancePersistence.findAll(start, end); }
python
def load_yamlf(fpath, encoding): """ :param unicode fpath: :param unicode encoding: :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return yaml.safe_load(f)
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case XtextPackage.ABSTRACT_NEGATED_TOKEN__TERMINAL: setTerminal((AbstractElement)newValue); return; } super.eSet(featureID, newValue); }
java
public static Set<String> getBuildFilesForAjdtFile( String ajdtBuildDefFile, File basedir ) throws MojoExecutionException { Set<String> result = new LinkedHashSet<String>(); Properties ajdtBuildProperties = new Properties(); try { ajdtBuildProperties.load( new Fi...
python
def get_action_side_effects(self): """Returns all side effects for all batches of this Executor used by the underlying Action. """ result = SCons.Util.UniqueList([]) for target in self.get_action_targets(): result.extend(target.side_effects) return result
python
def char(self, c: str) -> None: """Parse the specified character. Args: c: One-character string. Raises: EndOfInput: If past the end of `self.input`. UnexpectedInput: If the next character is different from `c`. """ if self.peek() == c: ...
java
public final ByteArrayOutputStream encode() throws IOException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); buffer.write(type); buffer.write(clientId); buffer.write(clientDestId); encode(buffer); return buffer; }
python
def del_value(self, keys, complete=False, on_projects=False, on_globals=False, projectname=None, base='', dtype=None, **kwargs): """ Delete a value in the configuration Parameters ---------- keys: list of str A list of keys to be d...
java
public RadarSeries setLineStyle(BasicStroke basicStroke) { stroke = basicStroke; if (this.lineWidth > 0.0f) { stroke = new BasicStroke( lineWidth, this.stroke.getEndCap(), this.stroke.getLineJoin(), this.stroke.getMiterLimit(), ...
java
public JobResponseInner getJob(String resourceGroupName, String resourceName, String jobId) { return getJobWithServiceResponseAsync(resourceGroupName, resourceName, jobId).toBlocking().single().body(); }
python
async def send_event(self, client_id, service_name, event_name, event_info, directed_client=None): """Send an event to a client.""" if directed_client is not None and directed_client != client_id: return client_info = self.clients.get(client_id) if client_info is None: ...