language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def format_traceback(extracted_tb, exc_type, exc_value, cwd='', term=None, function_color=12, dim_color=8, editor='vi', template=DEFAULT_EDITOR_SHORTCUT...
java
public void setTopicIds(String v) { if (Token_Type.featOkTst && ((Token_Type)jcasType).casFeat_topicIds == null) jcasType.jcas.throwFeatMissing("topicIds", "de.julielab.jules.types.Token"); jcasType.ll_cas.ll_setStringValue(addr, ((Token_Type)jcasType).casFeatCode_topicIds, v);}
java
public com.google.api.ads.admanager.axis.v201811.TimeZoneType getTimeZoneType() { return timeZoneType; }
java
@VisibleForTesting void performLazySeek(long bytesToRead) throws IOException { throwIfNotOpen(); // Return quickly if there is no pending seek operation, i.e. position didn't change. if (currentPosition == contentChannelPosition && contentChannel != null) { return; } logger.atFine().log( ...
python
def gen_undef(): """Return an UNDEF instruction. """ empty_reg = ReilEmptyOperand() return ReilBuilder.build(ReilMnemonic.UNDEF, empty_reg, empty_reg, empty_reg)
java
protected void registerAddOperation(final ManagementResourceRegistration registration, final AbstractAddStepHandler handler, OperationEntry.Flag... flags) { registration.registerOperationHandler(getOperationDefinition(ModelDescriptionConstants.ADD, new Def...
python
def parse_inventory(inventory_output=None): """Parse the inventory text and return udi dict.""" udi = { "name": "", "description": "", "pid": "", "vid": "", "sn": "" } if inventory_output is None: return udi # find the record with chassis text in name...
python
def do_POST(self, ): """Handle POST requests When the user is redirected, this handler will respond with a website which will send a post request with the url fragment as parameters. This will get the parameters and store the original redirection url and fragments in :data:`Logi...
python
def yield_json(stream): """Uses array and object delimiter counts for balancing. """ buff = u"" arr_count = 0 obj_count = 0 while True: buff += read_chunk(stream) # If we finish parsing all objs or arrays, yield a finished JSON # entity. if buff.endswith('{'): ...
java
private static void doTaskHooksTranslation(Config heronConfig) { List<String> hooks = heronConfig.getAutoTaskHooks(); if (hooks != null && !hooks.isEmpty()) { heronConfig.put(backtype.storm.Config.STORMCOMPAT_TOPOLOGY_AUTO_TASK_HOOKS, hooks); List<String> translationHooks = new LinkedList<>(); ...
python
def md5(self): """ Get an MD5 reflecting everything in the DataStore. Returns ---------- md5: str, MD5 in hexadecimal """ hasher = hashlib.md5() for key in sorted(self.data.keys()): hasher.update(self.data[key].md5().encode('utf-8')) m...
java
public Node nextAvailableNode() { if (!isInit) { init(); } currentNodeIndex++; if (currentNodeIndex >= allNodes.length) { currentNodeIndex = 0; } return currentNode(); }
python
def push(self, local: _PATH = 'LICENSE', remote: _PATH = '/sdcard/LICENSE') -> None: '''Copy local files/directories to device.''' if not os.path.exists(local): raise FileNotFoundError(f'Local {local!r} does not exist.') self._execute('-s', self.device_sn, 'push', local, remote)
python
def section_names(self, ordkey="wall_time"): """ Return the names of sections ordered by ordkey. For the time being, the values are taken from the first timer. """ section_names = [] # FIXME this is not trivial for idx, timer in enumerate(self.timers()): ...
java
final static void enable() { if (lifeCycle.getStatus().equals(RunStatus.READY) || lifeCycle.getStatus().equals(RunStatus.STOPPED)) { init(); } else if (lifeCycle.getStatus().equals(RunStatus.DISABLED)) { lifeCycle.setStatus(RunStatus.RUNNING); } }
python
def close(self): """ Close the fits file and set relevant metadata to None """ if hasattr(self, '_FITS'): if self._FITS is not None: self._FITS.close() self._FITS = None self._filename = None self.mode = None self.charmo...
java
public static CPOptionValue fetchByCPOptionId_Last(long CPOptionId, OrderByComparator<CPOptionValue> orderByComparator) { return getPersistence() .fetchByCPOptionId_Last(CPOptionId, orderByComparator); }
java
public static int cusparseSdense2csr( cusparseHandle handle, int m, int n, cusparseMatDescr descrA, Pointer A, int lda, Pointer nnzPerRow, Pointer csrSortedValA, Pointer csrSortedRowPtrA, Pointer csrSortedColIndA) { ...
python
def assign_fonts(counts,maxsize,minsize,exclude_words): '''Defines the font size of a word in the cloud. Counts is a list of tuples in the form (word,count)''' valid_counts = [] if exclude_words: for i in counts: if i[1] != 1: valid_counts.append(i) else: ...
python
def main(argv=None): """ben-nett entry point""" arguments = cli_common(__doc__, argv=argv) benet = BeNet(arguments['CAMPAIGN_FILE']) benet.run() if argv is not None: return benet
java
static public void assertNull(Object object) { String message = "Expected: <null> but was: " + String.valueOf(object); assertNull(message, object); }
python
def with_body(self, body): # @todo take encoding into account """Sets the request body to the provided value and returns the request itself. Keyword arguments: body -- A UTF-8 string or bytes-like object which represents the request body. """ try: self.body =...
java
public static <N, E> List<List<N>> collectSCCs(Graph<N, E> graph) { return SCCs.collectSCCs(graph); }
java
public static PhasedBackoffWaitStrategy withSleep( long spinTimeout, long yieldTimeout, TimeUnit units) { return new PhasedBackoffWaitStrategy( spinTimeout, yieldTimeout, units, new SleepingWaitStrategy(0)); }
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<Empty, WorkflowMetadata> instantiateWorkflowTemplateAsync( String name, Map<String, String> parameters) { InstantiateWorkflowTemplateRequest request = InstantiateW...
python
def strings_to_categoricals(self, df: Optional[pd.DataFrame] = None): """Transform string annotations to categoricals. Only affects string annotations that lead to less categories than the total number of observations. Params ------ df If ``df`` is ``None``,...
java
public static void execute() throws EFapsException { RunLevel.RUNLEVEL.executeMethods(); final List<String> allInitializer = RunLevel.RUNLEVEL.getAllInitializers(); for (final AbstractCache<?> cache : AbstractCache.getCaches()) { final String initiliazer = cache.getInitia...
python
def get_ancestors(self): """ :returns: A queryset containing the current node object's ancestors, starting by the root node and descending to the parent. """ if self.is_root(): return get_result_class(self.__class__).objects.none() paths = [ s...
java
public static <R> FuncN<Observable<R>> asyncFunc(final FuncN<? extends R> func) { return toAsync(func); }
python
def list_tables(self, dataset): """Returns the list of tables in a given dataset. :param dataset: :type dataset: BQDataset """ request = self.client.tables().list(projectId=dataset.project_id, datasetId=dataset.dataset_id, ...
java
@Override @SuppressWarnings("unchecked") public K deleteMax() { K result; switch (size) { case 0: throw new NoSuchElementException(); case 1: result = array[1]; array[1] = null; size--; break; case 2: ...
java
public void writeLongUTF(String str) throws IOException { int length = str.length(); writeCompressedInt(length); for(int position = 0; position<length; position+=20480) { int blockLength = length - position; if(blockLength>20480) blockLength = 20480; String block = str.substring(position, position+blockL...
python
def on_sanji_message(self, client, userdata, msg): """This function will recevie all message from mqtt client the client instance for this callback userdata the private user data as set in Client() or userdata_set() message an instance of MQTTMessage. ...
python
def char2hex(a: str): """Convert a hex character to its integer value. '0' becomes 0, '9' becomes 9 'A' becomes 10, 'F' becomes 15 'a' becomes 10, 'f' becomes 15 Returns -1 on error. """ if "0" <= a <= "9": return ord(a) - 48 elif "A" <= a <= "F": return ord(a) - 55 ...
java
protected String getCurrentInterval(HttpServletRequest req, boolean saveToSession){ String intervalParameter = req.getParameter(PARAM_INTERVAL); String interval = intervalParameter; if (interval==null){ interval = (String)req.getSession().getAttribute(BEAN_INTERVAL); if (interval == null) interval = DEF...
python
def trace(args): """ %prog trace unitig{version}.{partID}.{unitigID} Call `grep` to get the erroneous fragment placement. """ p = OptionParser(trace.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(p.print_help()) s, = args version, partID, unitigID = g...
python
def decode_fetch_response(cls, data): """ Decode bytes to a FetchResponse Arguments: data: bytes to decode """ ((correlation_id, num_topics), cur) = relative_unpack('>ii', data, 0) for _ in range(num_topics): (topic, cur) = read_short_string(data...
python
def age(self, minimum: int = 16, maximum: int = 66) -> int: """Get a random integer value. :param maximum: Maximum value of age. :param minimum: Minimum value of age. :return: Random integer. :Example: 23. """ age = self.random.randint(minimum, maxim...
python
def _add_event_source(awsclient, evt_source, lambda_arn): """ Given an event_source dictionary, create the object and add the event source. """ event_source_obj = _get_event_source_obj(awsclient, evt_source) # (where zappa goes like remove, add) # we go with update and add like this: if eve...
java
public boolean addCellLink(GridCell<P> cell) { if (this.cells.add(cell)) { return isReferenceCell(cell); } return false; }
java
@Override public Object parse(String source) throws Exception { DocumentBuilder builder = builderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(source)); Node node = builder.parse(is).getFirstChild(); LinkedHashMap<String, Object> map = new LinkedHashMap<>(); return cop...
java
public <Result> Result submitRequest(TDApiRequest apiRequest, Optional<String> apiKeyCache, TDHttpRequestHandler<Result> handler) throws TDClientException { RequestContext requestContext = new RequestContext(config, apiRequest, apiKeyCache); try { return submitRequest(request...
python
def get_transcript(self, gene_pk, refseq_id): "Get a transcript from the cache or add a new record." if not refseq_id: return transcript_pk = self.transcripts.get(refseq_id) if transcript_pk: return transcript_pk gene = Gene(pk=gene_pk) transcript ...
python
def stop_stack(awsclient, stack_name, use_suspend=False): """Stop an existing stack on AWS cloud. :param awsclient: :param stack_name: :param use_suspend: use suspend and resume on the autoscaling group :return: exit_code """ exit_code = 0 # check for DisableStop #disable_stop = co...
python
def _selectView( self ): """ Matches the view selection to the trees selection. """ scene = self.uiGanttVIEW.scene() scene.blockSignals(True) scene.clearSelection() for item in self.uiGanttTREE.selectedItems(): item.viewItem().setSelected(True)...
java
public static <T extends MethodDescription> ElementMatcher.Junction<T> takesArgument(int index, ElementMatcher<? super TypeDescription> matcher) { return takesGenericArgument(index, erasure(matcher)); }
python
def ro(self): """ Return read-only copy of this object :return: WHTTPHeaders """ ro_headers = WHTTPHeaders() names = self.headers() for name in names: ro_headers.add_headers(name, *self.get_headers(name)) ro_headers.__cookies = self.__set_cookies.ro() ro_headers.__ro_flag = True return ro_headers
python
def space_labels(document): """Ensure space around bold compound labels.""" for label in document.xpath('.//bold'): # TODO: Make this more permissive to match chemical_label in parser if not label.text or not re.match('^\(L?\d\d?[a-z]?\):?$', label.text, re.I): continue paren...
java
public <T,E extends TypedEdge<T>> void write( Multigraph<T,E> g, File f, Indexer<String> vertexLabels) throws IOException { write(g, f, null, false, vertexLabels, true); }
python
def get_directories(self, request): """Return directories """ queryset = self.folder.media_folder_children.all().order_by(*config.MEDIA_FOLDERS_ORDER_BY.split(",")) paginator = Paginator(queryset, self.objects_per_page) page = request.GET.get('page', None) try: ...
java
@SuppressWarnings("rawtypes") static OutputType getStreamingType(Class<? extends CommandOutput> commandOutputClass) { ClassTypeInformation<? extends CommandOutput> classTypeInformation = ClassTypeInformation.from(commandOutputClass); TypeInformation<?> superTypeInformation = classTypeInformation.g...
java
private void parseAllowRetries(Map<Object, Object> props) { Object value = props.get(HttpConfigConstants.PROPNAME_ALLOW_RETRIES); if (null != value) { this.bAllowRetries = convertBoolean(value); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr...
java
private static double getSideLengthFromCircumscribedRadius(double radius, int n) { if (n == 2) { return radius; } return radius * (2 * Math.sin(Math.PI/n)); }
python
def assert_valid_execution_arguments( schema: GraphQLSchema, document: DocumentNode, raw_variable_values: Dict[str, Any] = None, ) -> None: """Check that the arguments are acceptable. Essential assertions before executing to provide developer feedback for improper use of the GraphQL library. ...
java
public static void saveMapFileSequences(String path, JavaRDD<List<List<Writable>>> rdd, int interval, Integer maxOutputFiles) { Configuration c = new Configuration(); c.set(MAP_FILE_INDEX_INTERVAL_KEY, String.valueOf(interval)); saveMapFileSequences(path, rdd, c, maxOutputFi...
python
def run(self, synchronous=True, **kwargs): """Helper to run existing job template :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. ...
java
public void marshall(DetachThingPrincipalRequest detachThingPrincipalRequest, ProtocolMarshaller protocolMarshaller) { if (detachThingPrincipalRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def _station_info(station_code): """filename based meta data for a station code.""" url_file = open(env.SRC_PATH + '/eere.csv') for line in csv.DictReader(url_file): if line['station_code'] == station_code: return line raise KeyError('Station not found')
python
def lt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores less than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(self._min_score, "(%f" % v, start=offset, num=limit)
python
def mkdir(self, mdir, parents=False): """Make a directory. Note that this will not error out if the directory already exists (that is how the PutDirectory Manta API behaves). @param mdir {str} A manta path, e.g. '/trent/stor/mydir'. @param parents {bool} Optional. Default false...
python
def assert_almost_equal( first, second, msg_fmt="{msg}", places=None, delta=None ): """Fail if first and second are not equal after rounding. By default, the difference between first and second is rounded to 7 decimal places. This can be configured with the places argument. Alternatively, delta can...
python
def get_properties(self, obj): """Fill out properties field.""" properties = {} for field_name, field in sorted(obj.fields.items()): schema = self._get_schema_for_field(obj, field) properties[field.name] = schema return properties
python
def bounding_box(positions): '''Computes the bounding box for a list of 3-dimensional points. ''' (x0, y0, z0) = (x1, y1, z1) = positions[0] for x, y, z in positions: x0 = min(x0, x) y0 = min(y0, y) z0 = min(z0, z) x1 = max(x1, x) y1 = max(y1, y) z1 = max(...
python
def _infer_record_outputs(inputs, unlist, file_vs, std_vs, parallel, to_include=None, exclude=None): """Infer the outputs of a record from the original inputs """ fields = [] unlist = set([_get_string_vid(x) for x in unlist]) input_vids = set([_get_string_vid(v) for v in _h...
python
def last_update_time(self) -> float: """The last time at which the report was modified.""" stdout = self.stdout_interceptor stderr = self.stderr_interceptor return max([ self._last_update_time, stdout.last_write_time if stdout else 0, stderr.last_writ...
java
@Nonnull public CSSRect setBottom (@Nonnull @Nonempty final String sBottom) { ValueEnforcer.notEmpty (sBottom, "Bottom"); m_sBottom = sBottom; return this; }
java
public static SObject of(String key, byte[] buf, Map<String, String> attrs) { SObject sobj = of(key, $.requireNotNull(buf)); sobj.setAttributes(attrs); return sobj; }
python
def create_subnet(self, vpc_id, cidr_block, availability_zone=None): """ Create a new Subnet :type vpc_id: str :param vpc_id: The ID of the VPC where you want to create the subnet. :type cidr_block: str :param cidr_block: The CIDR block you want the subnet to cover. ...
java
public void clearExpired() { Iterator keys = cacheLineTable.keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); if (hasExpired(key)) { removeObject(key); } } }
python
def _get_index(self): """ Get the anchor's index. This must return an ``int``. Subclasses may override this method. """ glyph = self.glyph if glyph is None: return None return glyph.anchors.index(self)
python
def __updateStack(self, key): """ Update the input stack in non-hotkey mode, and determine if anything further is needed. @return: True if further action is needed """ #if self.lastMenu is not None: # if not ConfigManager.SETTINGS[MENU_TAKES_FOCUS]: # ...
java
public void setNameconflict(String nameconflict) throws ApplicationException { this.nameconflict = FileUtil.toNameConflict(nameconflict, NAMECONFLICT_UNDEFINED | NAMECONFLICT_ERROR | NAMECONFLICT_OVERWRITE, NAMECONFLICT_DEFAULT); }
java
private String getStringResource(String path) { InputStream in = getClass().getResourceAsStream(path); StringBuilder index = new StringBuilder(); char[] buffer = new char[1024]; int read = 0; try(InputStreamReader reader = new InputStreamReader(in)){ while((read = reader.read(buffer...
java
public String toQueryString() { String result = null; List<String> parameters = new ArrayList<>(); for (Map.Entry<String, String> entry : entrySet()) { // We don't encode the key because it could legitimately contain // things like underscores, e.g. "_escaped_fragment_"...
python
def set_ipv4_routing(self, vrf_name, default=False, disable=False): """ Configures ipv4 routing for the vrf Args: vrf_name (str): The VRF name to configure default (bool): Configures ipv4 routing for the vrf value to default if this value is true disa...
python
def calcUminUmax(self,**kwargs): """ NAME: calcUminUmax PURPOSE: calculate the u 'apocenter' and 'pericenter' INPUT: OUTPUT: (umin,umax) HISTORY: 2012-11-27 - Written - Bovy (IAS) """ if hasattr(self,'_uminumax')...
java
@Override public WorkspaceStorageConnection openConnection(boolean readOnly) throws RepositoryException { try { if (this.containerConfig.dbStructureType.isMultiDatabase()) { return new PostgreMultiDbJDBCConnection(getJdbcConnection(readOnly), readOnly, containerCon...
java
private void setOtherAttachments( RROtherProjectInfo12Document.RROtherProjectInfo12 rrOtherProjectInfo) { OtherAttachments otherAttachments = OtherAttachments.Factory .newInstance(); otherAttachments.setOtherAttachmentArray(getAttachedFileDataTypes()); rrOtherProjectInfo.setOt...
java
static <T extends SAMLObject> MessageContext<T> toSamlObject(AggregatedHttpMessage msg, String name) { final SamlParameters parameters = new SamlParameters(msg); final byte[] decoded; try { decoded = Base64.getMimeDecoder().decode(parameters.getFirstValue(name)); } catch (Ill...
java
private @Nonnull LoadBalancerHealthCheck toLoadBalancerHealthCheck(JSONObject ob) throws JSONException, InternalException, CloudException { LoadBalancerHealthCheck.HCProtocol protocol = fromOSProtocol(ob.getString("type")); int count = ob.getInt("max_retries"); int port = -1; String path...
java
protected CompletableFuture<AppendResponse> handleAppend(final AppendRequest request) { CompletableFuture<AppendResponse> future = new CompletableFuture<>(); // Check that the term of the given request matches the local term or update the term. if (!checkTerm(request, future)) { return future; } ...
python
def files_comments_delete(self, *, file: str, id: str, **kwargs) -> SlackResponse: """Deletes an existing comment on a file. Args: file (str): The file id. e.g. 'F1234467890' id (str): The file comment id. e.g. 'Fc1234567890' """ kwargs.update({"file": file, "id"...
python
def _run_queries(self, queries, *args, **kwargs): """run the queries queries -- list -- the queries to run return -- string -- the results of the query? """ # write out all the commands to a temp file and then have psql run that file f = self._get_file() for q in...
python
def preprocess( self, nb: "NotebookNode", resources: dict ) -> Tuple["NotebookNode", dict]: """Remove any raw cells from the Notebook. By default, exclude raw cells from the output. Change this by including global_content_filter->include_raw = True in the resources dictionary. ...
java
public InputStream getResourceAsStream(String name, BeanContextChild bcc) throws IllegalArgumentException { // bcc must be a child of this context if (!contains(bcc)) { throw new IllegalArgumentException("Child is not a member of this context"); } ClassLoader cl = bcc.getCl...
java
public CouchDbConsentDecision findFirstConsentDecision(final String principal, final String service) { val view = createQuery("by_consent_decision").key(ComplexKey.of(principal, service)).limit(1).includeDocs(true); return db.queryView(view, CouchDbConsentDecision.class).stream().findFirst().orElse(null...
java
public void saveCertificateChain(OutputStream out) throws IOException, CertificateEncodingException { CertificateIOUtil.writeCertificate(out, this.certChain[0]); for (int i = 1; i < this.certChain.length; i++) { // skip the self-signed certificates if (this.certChain[i].getSubj...
python
def _f_ops(op1, op2, swap=True): """ Receives a list with two strings (operands). If none of them contains integers, returns None. Otherwise, returns a t-uple with (op[0], op[1]), where op[1] is the integer one (the list is swapped) unless swap is False (e.g. sub and div used this because they'r...
python
def bucket_update(self, name, current, bucket_password=None, replicas=None, ram_quota=None, flush_enabled=None): """ Update an existing bucket's settings. :param string name: The name of the bucket to update :param dict current: Current state of the bucket. ...
java
public Map getStringDecodedMap(final Map encodedMap, final Map defaults) { if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, "getStringDecodedMap", new Object[] {encodedMap,defaults}); } final Map<String,Object> decoded = new HashMap<Str...
java
public void hubHeartbeat(UpdateServerHeartbeat updateServer, UpdateRackHeartbeat updateRack, UpdatePodSystem updatePod, long sourceTime) { RackHeartbeat rack = getCluster().findRack(updateRack.getId()); if (rack == nul...
java
public boolean columnContainsKey(String key) { String resolvedKey = resolveColumnKey(key); return columnMap.containsKey(resolvedKey) || parent != null && parent.columnContainsKey(resolvedKey); }
python
def ylabel(self, labels): """ Determine x-axis label Parameters ---------- labels : dict Labels as specified by the user through the ``labs`` or ``ylab`` calls. Returns ------- out : str y-axis label """ ...
python
def cli(ctx): """PyHardLinkBackup""" click.secho("\nPyHardLinkBackup v%s\n" % PyHardLinkBackup.__version__, bg="blue", fg="white", bold=True)
java
public String build() { String url = buffer.toString(); if (url.length() > 2083) { LOG.warning("URL " + url + " is longer than 2083 chars (" + buffer.length() + "). It may not work properly in old IE versions."); } return url; }
python
def detect_events(self, max_attempts=3): """Returns a list of `Event`s detected from differences in state between the current snapshot and the Kindle Library. `books` and `progress` attributes will be set with the latest API results upon successful completion of the function. R...
java
public static String detectFormat(String strTime) { String format = null; if ((format = tryAndGetFormat(strTime, dateTimeWithSubSecAndTZFormat)) == null) { if ((format = tryAndGetFormat(strTime, dateTimeAndTZFormat)) == null) { if ((format = tryAndGetFormat(strTime, dateTimeW...
java
public void setMetricsToAnnotate(List<String> metricsToAnnotate) { this.metricsToAnnotate.clear(); if (metricsToAnnotate != null && !metricsToAnnotate.isEmpty()) { for (String metric : metricsToAnnotate) { requireArgument(getMetricToAnnotate(metric) != null, "Metrics to annot...
java
@Override public GetActiveNamesResult getActiveNames(GetActiveNamesRequest request) { request = beforeClientExecution(request); return executeGetActiveNames(request); }
java
public static final <T> Function<T,List<T>> intoSingletonListOf(final Type<T> type) { return new IntoSingletonList<T>(); }