language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void append(final int b) { final int newlen = this.len + 1; if (newlen > this.array.length) { expand(newlen); } this.array[this.len] = (byte)b; this.len = newlen; }
java
public static void addFilterMapping(Document doc, Element root) { Element filterMapping = doc.createElement("filter-mapping"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filterMapping.appendChild(filterName); Element urlPattern =...
java
public IndexDoc getNextDoc(String field, int previousDocId) { if (fieldReferences.containsKey(field)) { FieldReferences fr = fieldReferences.get(field); try { if (previousDocId < 0) { return new IndexDoc(fr.refIndexDoc); } else { int nextDocId = previousDocId + 1; ...
python
def get_nn(self, structure, n): """ Get near neighbors of site with index n in structure. Args: structure (Structure): input structure. n (integer): index of site in structure for which to determine neighbors. Returns: sites (list ...
python
def register(self, fd, eventmask=None): """ Register a new descriptor :param fd: The descriptor to register. :param eventmask: Bit-mask of events that will be monitored. By default EPOLLIN, EPOLLOUT and EPOLLPRI are used. Note that EPOLLHUP is implici...
python
def retrieve_nodes(self): """ retrieve nodes from old mysql DB """ self.verbose('retrieving nodes from old mysql DB...') self.old_nodes = list(OldNode.objects.all()) self.message('retrieved %d nodes' % len(self.old_nodes))
java
protected static String debugText(String heading, Authentication auth, Collection<ConfigAttribute> config, Object resource, int decision) { StringBuilder sb = n...
python
def scan_ipaddr(ipaddr, apikey): """ If an IP Address is found, scan it """ logger.info('Query VirusTotal API for Public IP Found: %s', ipaddr) v_api = virus_total.VirusTotal() scan_ip = v_api.send_ip(ipaddr, apikey) response_code = scan_ip['response_code'] verbose_msg = scan_ip['verbose...
java
public LocalDate atYearMonth(YearMonth yearMonth) { return yearMonth.atDay(Math.min(day, yearMonth.lengthOfMonth())); }
python
def _get_hashtable_algo(values): """ Parameters ---------- values : arraylike Returns ------- tuples(hashtable class, vector class, values, dtype, ndtype) """ values, dtype, ndtype = _ensure_data(values) if ndtype == 'object': ...
java
@Override public void writeOutput(VisualizerInput input, Writer w) { // root html element Html html = new Html(); Head head = new Head(); Body body = new Body(); html.removeXmlns(); html.appendChild(head); html.appendChild(body); try { LinkedList<String> fonts = ...
java
public synchronized MetaStore storeVote(int vote) { LOGGER.trace("Store vote {}", vote); metadataBuffer.writeInt(8, vote).flush(); return this; }
java
public static List<CPAttachmentFileEntry> findByLtD_S(Date displayDate, int status, int start, int end) { return getPersistence().findByLtD_S(displayDate, status, start, end); }
java
public void loadTldsFromJar(URL url, String resourcePath, List loadedLocations, JspXmlExtConfig webAppConfig) { if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINE)){ logger.logp(Level.FINE, CLASS_NAME, "loadTldsFromJar", "url ["+url+"]"+"resourcePath ["+resourc...
python
def printTPRegionParams(tpregion): """ Note: assumes we are using TemporalMemory/TPShim in the TPRegion """ tm = tpregion.getSelf()._tfdr print "------------PY TemporalMemory Parameters ------------------" print "numberOfCols =", tm.getColumnDimensions() print "cellsPerColumn =", tm...
python
def write_to_conll_eval_file(prediction_file: TextIO, gold_file: TextIO, verb_index: Optional[int], sentence: List[str], prediction: List[str], gold_labels: List[str]): ""...
java
public String getTimeNow() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ROOT); return format.format(new Date()); }
java
public Boolean isPerformBootstrap() { // configuration for Togglz >= 2.0.0 String managerProvided = servletContext.getInitParameter("org.togglz.FEATURE_MANAGER_PROVIDED"); if (managerProvided != null) { return !toBool(managerProvided); } // deprecated configuration ...
java
public T getValueByString(String key) { for (T value : values) { if (keyFactory.generateKey(value).equals(key)) { return value; } } return null; }
python
def BitVecSym( name: str, size: int, annotations: Annotations = None ) -> z3.BitVecRef: """Creates a new bit vector with a symbolic value.""" return z3.BitVec(name, size)
python
def _printable_id_code(self): """ Returns the code in a printable form, separating it into groups of three characters using a point between them. :return: the ID code in a printable form """ code = super(ISWCCode, self)._printable_id_code() code1 = code[:3] ...
python
def get_job(self, job_id): """GetJob https://apidocs.joyent.com/manta/api.html#GetJob with the added sugar that it will retrieve the archived job if it has been archived, per: https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival """ ...
python
def recarrayuniqify(X, retainorder=False): """ Very fast uniqify routine for numpy record arrays (or ndarrays with structured dtype). Record array version of func:`tabular.fast.arrayuniqify`. **Parameters** **X** : numpy recarray Determine the unique elements of...
java
private void removeFromWebContainer() { if (!Thread.holdsLock(terminated)) { throw new IllegalStateException(); } synchronized (addRemoveLock) { //we'll either succeed or fail at the removal, but either //way we want to guarantee the tracker is closed. ...
python
def cookie(self, k, v, expires=None, domain=None, path='/', secure=False): """ Sets cookie value. :param k: Name for cookie value :param v: Cookie value :param expires: Cookie expiration date :param domain: Cookie domain :param path: Cookie path :param secure: Fl...
java
private MessageConsumer createConsumer(Destination destination, String name, String messageSelector, boolean noLocal, boolean isSharedNonDurable) throws JMSException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "c...
java
public java.util.List<String> getSupportedEngineModes() { if (supportedEngineModes == null) { supportedEngineModes = new com.amazonaws.internal.SdkInternalList<String>(); } return supportedEngineModes; }
python
def add_customers(self, service_desk_id, list_of_usernames): """ Adds one or more existing customers to the given service desk. If you need to create a customer, see Create customer method. Administer project permission is required, or agents if public signups and invites are en...
python
def motif3funct_wei(W): ''' Functional motifs are subsets of connection patterns embedded within anatomical motifs. Motif frequency is the frequency of occurrence of motifs around a node. Motif intensity and coherence are weighted generalizations of motif frequency. Parameters ---------- ...
java
public void deleteShape(Paintable paintable, Object group, MapContext context) { VectorTile tile = (VectorTile) paintable; context.getVectorContext().deleteGroup(tile.getFeatureContent()); context.getVectorContext().deleteGroup(tile.getLabelContent()); context.getRasterContext().deleteGroup(tile.getFeatureConte...
python
def forward(self, inputs, begin_state): # pylint: disable=arguments-differ """Implement forward computation. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list ...
java
protected String getFacebookFieldName(FieldWithAnnotation<Facebook> fieldWithAnnotation) { String facebookFieldName = fieldWithAnnotation.getAnnotation().value(); Field field = fieldWithAnnotation.getField(); // If no Facebook field name was specified in the annotation, assume // it's the same name as ...
python
def msregularize(msname, newname): """ Regularize an MS The output MS will be such that it has the same number of baselines for each time stamp. Where needed fully flagged rows are added. Possibly missing rows are written into a separate MS <newname>-add. It is concatenated with the original MS an...
java
public static Object instantiateClass(String className, Class assignableFrom) { if(className == null) throw new IllegalArgumentException(Bundle.getErrorString("DataGridUtil_CantCreateClass")); Class clazz = null; try { clazz = Class.forName(className, false, Thread.curre...
python
def apply_rules(self, rules, recursive=True): """Rebuild the expression while applying a list of rules The rules are applied against the instantiated expression, and any sub-expressions if `recursive` is True. Rule application is best though of as a pattern-based substitution. This is d...
java
@Deprecated public void changeApiToken() throws IOException { // just to keep the same level of security user.checkPermission(Jenkins.ADMINISTER); LOGGER.log(Level.FINE, "Deprecated usage of changeApiToken"); ApiTokenStore.HashedToken existingLegacyToken = tokenStore.getLegacyToken...
python
def activate_cython(self): """ Activate Cython support. We need to run this here because if the support is active, we don't to run the UMR at all. """ run_cython = os.environ.get("SPY_RUN_CYTHON") == "True" if run_cython: try: __impor...
java
public Matrix4d arcball(double radius, double centerX, double centerY, double centerZ, double angleX, double angleY, Matrix4d dest) { double m30 = m20 * -radius + this.m30; double m31 = m21 * -radius + this.m31; double m32 = m22 * -radius + this.m32; double m33 = m23 * -radius + this.m33...
python
def hidePopup(self): """ Overloads the hide popup method to handle when the user hides the popup widget. """ if self._treePopupWidget and self.showTreePopup(): self._treePopupWidget.close() super(XOrbRecordBox, self).hidePopup()
python
def make_confidence_report_spsa(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, report_path=REPORT...
python
def fastp_read_n_plot(self): """ Make the read N content plot for Fastp """ data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_n_content_data, 'Base Content Percent') pconfig = { 'id': 'fastp-seq-content-n-plot', 'title': 'Fastp: Read N Content', ...
java
@Override public CPDefinitionSpecificationOptionValue findByC_COC_Last( long CPDefinitionId, long CPOptionCategoryId, OrderByComparator<CPDefinitionSpecificationOptionValue> orderByComparator) throws NoSuchCPDefinitionSpecificationOptionValueException { CPDefinitionSpecificationOptionValue cpDefinitionSpecific...
java
@Override public Iterator<ResourceRecordSet<?>> iterateByName(String name) { Filter<ResourceRecordSet<?>> filter = andNotAlias(nameEqualTo(name)); return lazyIterateRRSets(api.listResourceRecordSets(zoneId, name), filter); }
python
def is_valid_resource_name(rname, exception_type=None): """Validates the given resource name to ARM guidelines, individual services may be more restrictive. :param rname: The resource name being validated. :type rname: str :param exception_type: Raises this Exception if invalid. :type exception_typ...
java
public Stream<Discussion> getIssueDiscussionsStream(Object projectIdOrPath, Integer issueIid) throws GitLabApiException { Pager<Discussion> pager = getIssueDiscussionsPager(projectIdOrPath, issueIid, getDefaultPerPage()); return (pager.stream()); }
java
public static ns_configtemplate[] get_filtered(nitro_service service, String filter) throws Exception { ns_configtemplate obj = new ns_configtemplate(); options option = new options(); option.set_filter(filter); ns_configtemplate[] response = (ns_configtemplate[]) obj.getfiltered(service, option); retu...
java
public static final <K,V> MapList<K,V> unmodifiableMapList(MapList<K,V> map) { return new UnmodifiableMapList(Collections.unmodifiableMap(map), map.getComparator()); }
python
def core_name(self): """Returns the name of the target ARM core. Args: self (JLink): the ``JLink`` instance Returns: The target core's name. """ buf_size = self.MAX_BUF_SIZE buf = (ctypes.c_char * buf_size)() self._dll.JLINKARM_Core2CoreName(...
java
private void addCriticalityToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) { if (null != vulnerability) { final String criticality = nextLine.substring(CRITICALITY.length()).trim(); float score = -1.0f; Vulnerability v = null; if (...
java
public Gather<T> takeWhile(final Predicate<T> predicate) { final Iterator<T> it = each().iterator(); return from(new AbstractIterator<T>() { protected T computeNext() { if (!it.hasNext()) { return endOfData(); } T t = it.next()...
java
public static ResourceRecordSet<AData> a(String name, Collection<String> addresses) { return new ABuilder().name(name).addAll(addresses).build(); }
python
def interact_plain(header=UP_LINE, local_ns=None, module=None, dummy=None, stack_depth=1, global_ns=None): """ Create an interactive python console """ frame = sys._getframe(stack_depth) variables = {} if local_ns is not None: variables.update(loca...
java
public static <MSG extends Message> void writeStream(Iterable<MSG> messages, OutputStream output) { try { for (Message message : messages) { message.writeDelimitedTo(output); } } catch (Exception e) { throw ContextException.of("Unable to write messages", e); } }
python
def get_json_ld_extra(key, value): '''Serialize an extras key, value pair into JSON-LD''' value = value.serialize() if hasattr(value, 'serialize') else value return { '@type': 'http://schema.org/PropertyValue', 'name': key, 'value': value, }
python
def replace_suffixes_3(self, word): """. Perform replacements on more common suffixes. """ length = len(word) replacements = {'tional': 'tion', 'enci': 'ence', 'anci': 'ance', 'abli': 'able', 'entli': 'ent', 'ization': 'ize', 'izer...
python
def modify_request(self, request): """ Apply common path conventions eg. / > /index.html, /foobar > /foobar.html """ filename = URL.build(path=request.match_info['filename'], encoded=True).path raw_path = self._directory.joinpath(filename) try: filepath = raw_...
java
public void addDrawer(JFXDrawer drawer) { if (drawer == null) { return; } if (drawer.getCachePolicy().equals(CachePolicy.IMAGE)) { throw new RuntimeException("Drawer is using unsupported cache strategy inside JFXDrawerStack"); } if (drawers.isEmpty()) { ...
python
def apply_profile_or_settings(self, image): """Apply a profile to the viewer. Parameters ---------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object. This function is used to initialize the viewer when a new image is loaded. ...
java
public Observable<String> replaceContentAsync(String resourceGroupName, String automationAccountName, String runbookName, String runbookContent) { return replaceContentWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, runbookContent).map(new Func1<ServiceResponseWithHeaders<String,...
python
def update_state(self): """ Update state with latest info from Wink API. """ response = self.api_interface.get_device_state(self, type_override="button") return self._update_state_from_response(response)
python
async def cancel_handler(message: types.Message, state: FSMContext, raw_state: Optional[str] = None): """ Allow user to cancel any action """ if raw_state is None: return # Cancel state and inform user about it await state.finish() # And remove keyboard (just in case) await mess...
python
def _walk_phys_parts(phys_reader, srels, visited_partnames=None): """ Generate a 3-tuple `(partname, blob, srels)` for each of the parts in *phys_reader* by walking the relationship graph rooted at srels. """ if visited_partnames is None: visited_partnames = [] ...
java
public void set(int index, byte[] items, int start, int length) { rangeCheck(index, index + length); for (int i = 0; i < length; i++) { elements[index + i] = items[start + i]; } }
java
public Object run(GroovyCodeSource source, String[] args) throws CompilationFailedException { Class scriptClass = parseClass(source); return runScriptOrMainOrTestOrRunnable(scriptClass, args); }
python
def get_word_break_property(value, is_bytes=False): """Get `WORD BREAK` property.""" obj = unidata.ascii_word_break if is_bytes else unidata.unicode_word_break if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['wordbreak'].get(negated, negated) else: ...
python
def _get_workflow_by_name(workflow_name, user_uuid): """From Workflows named as `workflow_name` the latest run_number. Only use when you are sure that workflow_name is not UUIDv4. :rtype: reana-db.models.Workflow """ from reana_db.models import Workflow workflow = Workflow.query.filter( ...
python
def loads(self, value): '''Returns deserialized `value`.''' for serializer in reversed(self): value = serializer.loads(value) return value
python
def lastNoiseCurve(expPath, suite, iteration="last"): """ Print the noise errors from the last iteration of this experiment """ noiseValues = ["0.0", "0.05", "0.1", "0.15", "0.2", "0.25", "0.3", "0.35", "0.4", "0.45", "0.5"] print("\nNOISE CURVE =====",expPath,"====== ITERATION:",i...
java
public boolean exists(Object key) { Jedis jedis = getJedis(); try { return jedis.exists(keyToBytes(key)); } finally {close(jedis);} }
java
protected static boolean isNull(Object val) { return (val == null) || STRING_NULL.equals(val) || DOUBLE_NULL.equals(val) || INTEGER_NULL.equals(val); }
java
public static Project parseMinimalProject(JSONObject content) throws JSONException { final Project result = new Project(); result.setId(JsonInput.getInt(content, "id")); result.setIdentifier(JsonInput.getStringOrNull(content, "identifier")); result.setName(JsonInput.getStringNotNull(content, "name")); retu...
java
public synchronized <T> List<T> getAttachmentList(AttachmentKey<? extends List<T>> key) { if (key == null) { return null; } List<T> list = key.cast(attachments.get(key)); if (list == null) { return Collections.emptyList(); } return list; }
python
def available_args(self): """Return args that can be used given the current cmd line rtype: command.Arg generator """ used = list(self.used_args) logger.debug('Found used args: %s' % used) for arg in list(self.cmd.args.values()): if (arg.is_multiple o...
java
public ServiceFuture<UUID> addHierarchicalEntityAsync(UUID appId, String versionId, HierarchicalEntityModel hierarchicalModelCreateObject, final ServiceCallback<UUID> serviceCallback) { return ServiceFuture.fromResponse(addHierarchicalEntityWithServiceResponseAsync(appId, versionId, hierarchicalModelCreateObjec...
java
@Override public DescribeDomainsResult describeDomains(DescribeDomainsRequest request) { request = beforeClientExecution(request); return executeDescribeDomains(request); }
java
public static void copyToUnsafe( MemorySegment[] segments, int offset, Object target, int pointer, int numBytes) { if (inFirstSegment(segments, offset, numBytes)) { segments[0].copyToUnsafe(offset, target, pointer, numBytes); } else { copyMultiSegmentsToUnsafe(segments, offset, target, pointer,...
java
public void setBeginnings(FloatArray v) { if (DocumentLine_Type.featOkTst && ((DocumentLine_Type)jcasType).casFeat_beginnings == null) jcasType.jcas.throwFeatMissing("beginnings", "ch.epfl.bbp.uima.types.DocumentLine"); jcasType.ll_cas.ll_setRefValue(addr, ((DocumentLine_Type)jcasType).casFeatCode_beginni...
java
void writeArguments(Iterator<String> names, Writer writer) throws IOException { while(names.hasNext()) { String name = names.next(); writer.append(name); // argname if(names.hasNext()) { writer.append(COMMA).append(SPACEOPTIONAL); //, } } }
python
def migrate(self, migrations_package_name, up_to=9999): ''' Executes schema migrations. - `migrations_package_name` - fully qualified name of the Python package containing the migrations. - `up_to` - number of the last migration to apply. ''' from .migrations i...
python
def tick(self, events): """Execute one frame of the interpreter. Don't call more than 40 times per second. """ self.add_new_threads() if self.drag_sprite: (mx, my) = self.screen.get_mouse_pos() (ox, oy) = self.drag_offset new_position = (mx ...
python
def connect( self, server, port, nickname, password=None, username=None, ircname=None, connect_factory=connection.Factory()): """Connect/reconnect to a server. Arguments: * server - Server name * port - Port number * nickname - The nickname * pas...
python
def process_bind_param(self, value, dialect): # type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any] """Encode data, if required.""" if self.__use_json(dialect) or value is None: return value return self.__json_codec.dumps(value, ensure_ascii=not self.__enforce_unico...
python
def expand(self, model=None, ignoreFilter=False): """ Expands any shortcuts that were created for this query. Shortcuts provide the user access to joined methods using the '.' accessor to access individual columns for referenced tables. :param model | <orb.Model> ...
python
def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point']
java
@Override public IIOMetadata getImageMetadata(int imageIndex) throws IOException { // checkBounds needed, as we catch the IndexOutOfBoundsException below. checkBounds(imageIndex); initHeader(imageIndex); IIOMetadata imageMetadata; if (isLossless()) { return new ...
java
public static long sizeof(final Object obj) { if (null == obj || isSharedFlyweight(obj)) { return 0; } final IdentityHashMap visited = new IdentityHashMap(80000); try { return computeSizeof(obj, visited, CLASS_METADATA_CACHE); } catch (RuntimeException r...
java
public static Game of(GameType type, String name, String url) { Checks.notNull(type, "Type"); switch (type) { case DEFAULT: return playing(name); case STREAMING: return streaming(name, url); case LISTENING: r...
java
public void curveTo(float x, float y, float cx1, float cy1, float cx2, float cy2, int segments) { // special case for zero movement if ((cx == x) && (cy == y)) { return; } Curve curve = new Curve(new Vector2f(cx,cy),new Vector2f(cx1,cy1),new Vector2f(cx2,cy2),new Vector2f(x,y)); float step = 1.0f...
java
public Observable<List<LogFileInner>> listByServerAsync(String resourceGroupName, String serverName) { return listByServerWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<List<LogFileInner>>, List<LogFileInner>>() { @Override public List<LogFileInner>...
java
public void connect(String eventSourceUrl) throws IOException { LOG.entering(CLASS_NAME, "connect", eventSourceUrl); if (stream != null) { LOG.warning("Reusing the same event source for a differnt URL, please create a new EventSource object"); throw new IllegalArgumentException( ...
java
public void complete(V value) { try { setRawResult(value); } catch (Throwable rex) { setExceptionalCompletion(rex); return; } setCompletion(NORMAL); }
python
def _cas_3(self): ''' Latitude overlap (2 images). ''' lonc = self._format_lon(self.lonm) latc_top = self._format_lat(self.latM) latc_bot = self._format_lat(self.latm) img_name_top = self._format_name_map(lonc, latc_top) print(img_name_top) img_top = BinaryTable...
java
public void addFirstChild( PlanNode child ) { assert child != null; this.children.addFirst(child); child.removeFromParent(); child.parent = this; }
python
def chi_square_calc(classes, table, TOP, P, POP): """ Calculate chi-squared. :param classes: confusion matrix classes :type classes : list :param table: confusion matrix table :type table : dict :param TOP: test outcome positive :type TOP : dict :param P: condition positive :typ...
java
public static String getPropNameForAccessor(String accessorName) { if (!isValidAccessorName(accessorName)) return accessorName; int prefixLength = accessorName.startsWith("is") ? 2 : 3; return String.valueOf(accessorName.charAt(prefixLength)).toLowerCase() + accessorName.substring(prefixLength +...
java
public static String syncRestCall(final String purl) { try { return CACHE.get(purl); } catch (final ExecutionException e) { GWT.log(e.getMessage(), e); return null; } }
python
def _not32(ins): """ Negates top (Logical NOT) of the stack (32 bits in DEHL) """ output = _32bit_oper(ins.quad[2]) output.append('call __NOT32') output.append('push af') REQUIRES.add('not32.asm') return output
python
def upsert_keys(session, key_table, keys): """Bulk add annotation keys to the specified table. :param key_table: The sqlalchemy class to insert into. :param keys: A map of {name: [candidate_classes]}. """ # Do nothing if empty if not keys: return for key_batch in _batch_postgres_qu...
java
public XNodeSet getNodeSetDTMByKey( XPathContext xctxt, int doc, QName name, XMLString ref, PrefixResolver nscontext) throws javax.xml.transform.TransformerException { XNodeSet nl = null; ElemTemplateElement template = (ElemTemplateElement) nscontext; // yuck -sb if ((null != temp...
python
def resample(self, seed=None): """Resample the dataset. Args: seed (int, optional): Seed for resampling. By default no seed is used. """ if seed is not None: gen = torch.manual_seed(seed) else: gen = torch.default_generator ...