language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public EList<JvmEnumerationLiteral> getValues() { if (values == null) { values = new EObjectResolvingEList<JvmEnumerationLiteral>(JvmEnumerationLiteral.class, this, TypesPackage.JVM_ENUM_ANNOTATION_VALUE__VALUES); } return values; }
java
protected static String insertPattern(final String logFileName, final String rollPattern) { int index = logFileName.lastIndexOf('.'); if(index==-1) return logFileName + rollPattern; return logFileName.substring(0, index) + rollPattern + logFileName.substring(index); }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.MMTRG__RG_LENGTH: return getRGLength(); case AfplibPackage.MMTRG__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); }
python
def unpack_scope(cls, scope): """Unpacks the response from a scope function. The function should return either a query, a query and a projection, or a query a projection and an query options hash.""" query = {} projection = {} options = {} if isinstance(scope, tu...
java
@Override public CommerceAccountOrganizationRel findByOrganizationId_Last( long organizationId, OrderByComparator<CommerceAccountOrganizationRel> orderByComparator) throws NoSuchAccountOrganizationRelException { CommerceAccountOrganizationRel commerceAccountOrganizationRel = fetchByOrganizationId_Last(organiza...
python
def _show_feedback_label(self, message, seconds=None): """Display a message in lbl_feedback, which times out after some number of seconds. """ if seconds is None: seconds = CONFIG['MESSAGE_DURATION'] logger.debug('Label feedback: "{}"'.format(message)) self....
python
def distribute(self, f, n): """Distribute the computations amongst the multiprocessing pools Parameters ---------- f : function Function to be distributed to the processors n : int The values in range(0,n) will be passed as arguments to the function...
java
public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { dnstxtrec addresources[] = new dnstxtrec[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new dnstxtrec(...
python
def extract_time(match): """extract time from a time_re match.""" hour = int(match.group('hour')) minute = int(match.group('minute')) return dt.time(hour, minute)
python
def validate(self, model=None, context=None): """ Validate model and return validation result object :param model: object or dict :param context: object, dict or None :return: shiftschema.result.Result """ # inject with settings result = Result(translato...
python
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance :rtype: twilio.rest.taskrouter.v1...
python
def _get_parameter_conversion_entry(parameter_config): """Get information needed to convert the given parameter to its API type. Args: parameter_config: The dictionary containing information specific to the parameter in question. This is retrieved from request.parameters in the method config. Re...
python
def _updateExtraSelections(self): """Highlight current line """ cursorColumnIndex = self.textCursor().positionInBlock() bracketSelections = self._bracketHighlighter.extraSelections(self, self.textCursor().block(), ...
python
def parse_url(cls, string): # pylint: disable=redefined-outer-name """ If it can be parsed as a version_guid with no preceding org + offering, returns a dict with key 'version_guid' and the value, If it can be parsed as a org + offering, returns a dict with key 'id' and optiona...
python
def _set_operable_view(self, session): """Sets the underlying operable views to match current view""" for obj_name in self._operable_views: if self._operable_views[obj_name] == ACTIVE: try: getattr(session, 'use_active_' + obj_name + '_view')() ...
python
def stop(self): """ Stop the server. """ log.debug("Stopping listeners") self.queue_lock.acquire() for s in self.listeners: log.debug("Stopping {}".format(s)) s.shutdown() s.socket.close() self.cancel_queue() for t in se...
python
def vary_by_categories(self): """ Read/write boolean value specifying whether to use a different color for each of the points in this plot. Only effective when there is a single series; PowerPoint automatically varies color by series when more than one series is present. ...
java
@Override public BigDecimal handle(ResultSet rs) throws SQLException { if (rs.next()) { if (this.columnName == null) { return new BigDecimal(((Number) rs.getObject(this.columnIndex)).toString()); } return new BigDecimal(((Number) rs.getObject(this.columnIndex)).toString()); } re...
python
def store_inputs(self, line_num, source, source_raw=None): """Store source and raw input in history and create input cache variables ``_i*``. Args: line_num (int): The prompt number of this input. source (str): Python input. source_raw (str): If given, this i...
python
def extract_subjects(bill): """ Return a list subject for legislation. """ logger.debug("Extracting Subjects") subject_map = [] subjects = bill.get('subjects', []) bill_id = bill.get('bill_id', None) bill_type = bill.get('bill_type', None) for sub in subjects: subject_map.ap...
python
def loadextendedcompoundinfo(self): """ Load extended compound info from the Mass Spec API """ apiurl = 'http://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?CSID=%s&token=%s' % (self.csid,TOKEN) response = urlopen(apiurl) tree = ET.parse(response) mf = tree.find('{...
python
def hagen_poiseuille(target, pore_area='pore.area', throat_area='throat.area', pore_viscosity='pore.viscosity', throat_viscosity='throat.viscosity', conduit_lengths='throat.conduit_lengths', con...
java
public ResourceRefType<WebAppDescriptor> getOrCreateResourceRef() { List<Node> nodeList = model.get("resource-ref"); if (nodeList != null && nodeList.size() > 0) { return new ResourceRefTypeImpl<WebAppDescriptor>(this, "resource-ref", model, nodeList.get(0)); } return createRe...
java
private void writeFile(File file, String csvData) throws IOException { LOG.debug("Will try to write CSV data to file: " + file.getAbsolutePath()); FileUtils.writeStringToFile(file, csvData, Charset.forName(ENCODING), false); LOG.debug("Finished writing CSV data to file: " + file.getAbsolutePath...
java
@Override public void setClientID(String clientID) throws JMSException { checkClosing(); if (clientID == null || clientID.isEmpty()) { throw new InvalidClientIDException("ClientID is empty"); } if (this.clientID != null) { throw new IllegalStateException("Clie...
java
@Override public Date next() { if (!hasNext()) { throw new NoSuchElementException(toString() + " ended"); } current = next; computeNext(); return current(); }
java
void serializeNode(OutputArchive oa, StringBuilder path) throws IOException { String pathString = path.toString(); DataNode node = getNode(pathString); if (node == null) { return; } String children[] = null; synchronized (node) { scount++; ...
python
def force_log_type_flags(self, logType, stdoutFlag, fileFlag): """ Force a logtype logging flags. :Parameters: #. logType (string): A defined logging type. #. stdoutFlag (None, boolean): The standard output logging flag. If None, logtype stdoutFlag forcing is...
java
static SQLTransform getSqlTransform(TypeName typeName) { if (Time.class.getName().equals(typeName.toString())) { return new SQLTimeSQLTransform(); } if (java.sql.Date.class.getName().equals(typeName.toString())) { return new SQLDateSQLTransform(); } return null; }
java
protected String getUniqueTargetNamespace(String targetNamespacePrefix, final String baseName) throws IOException { if (targetNamespacePrefix == null || targetNamespacePrefix.length() == 0) { return null; } if (baseName == null || baseName.length() == 0)...
python
def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(Tru...
java
public void unannounce(String path) { final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); final String parentPath = pathAndNode.getPath(); final ConcurrentMap<String, byte[]> subPaths = announcements.get(parentPath); if (subPaths == null || subPaths.remove(pathAndNode.getNode()) ==...
java
public boolean isHashEquals(byte[] expectedSignature, BuilderMode builderMode) { final byte[] signature = build(builderMode); return MessageDigest.isEqual(signature, expectedSignature); }
java
public static int count(final Object array) { if (isArray(array)) { return Array.getLength(array); } else if (array != null) { throw new IllegalArgumentException("Given data is not an array."); } else { return 0; } }
java
public void flush() { if(inline.length() > 0) { outStream.println(inline); } inline.setLength(0); if(comment.length() > 0) { quotePrintln(outStream, comment.toString()); } comment.setLength(0); }
java
@Override public double getDiscountFactor(AnalyticModelInterface model, double maturity) { // Change time scale maturity *= timeScaling; double beta1 = parameter[0]; double beta2 = parameter[1]; double beta3 = parameter[2]; double beta4 = parameter[3]; double tau1 = parameter[4]; double tau2 = para...
java
public void serializeToPagesWithoutLength( BinaryRow record, AbstractPagedOutputView out) throws IOException { int remainSize = record.getSizeInBytes(); int posInSegOfRecord = record.getOffset(); int segmentSize = record.getSegments()[0].size(); for (MemorySegment segOfRecord : record.getSegments()) { ...
java
@Override public final String toIso8601DateNoTz(final Date pDate, final Map<String, Object> pAddParam) throws Exception { return this.dateNoTzFormatIso8601.format(pDate); }
java
public void marshall(AdminListGroupsForUserRequest adminListGroupsForUserRequest, ProtocolMarshaller protocolMarshaller) { if (adminListGroupsForUserRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.m...
python
def onShortcutIndentAfterCursor(self): """Tab pressed and no selection. Insert text after cursor """ cursor = self._qpart.textCursor() def insertIndent(): if self.useTabs: cursor.insertText('\t') else: # indent to integer count of indents from li...
java
public CommandLine setHelpSectionKeys(List<String> keys) { getCommandSpec().usageMessage().sectionKeys(keys); for (CommandLine command : getCommandSpec().subcommands().values()) { command.setHelpSectionKeys(keys); } return this; }
python
def download(input, filename, representation, overwrite=False, resolvers=None, get3d=False, **kwargs): """Convenience function to save a CIR response as a file. This is just a simple wrapper around the resolve function. :param string input: Chemical identifier to resolve :param string filename: File p...
python
def add_population(self,pop): """Adds population to PopulationSet """ if pop.model in self.modelnames: raise ValueError('%s model already in PopulationSet.' % pop.model) self.modelnames.append(pop.model) self.shortmodelnames.append(pop.modelshort) self.poplist...
java
public ListenableFuture<Boolean> removeAsync(@NotNull V entity) { Timer removeAsyncTimer = METRICS.getTimer(MetricsType.DATA_PROVIDER_REMOVE.name()); Delete from = QueryBuilder.delete() .from(getEntityMetadata().getTableName()); int primaryKeysSize = getEntity...
python
def apply_cut(self, cut): """Return a cut version of this transition.""" return Transition(self.network, self.before_state, self.after_state, self.cause_indices, self.effect_indices, cut)
python
def results( self ): """Return a list of all the results currently available. This excludes pending results. Results are returned as a single flat list, so any repetition structure is lost. :returns: a list of results""" rs = [] for k in self._results.keys(): ...
java
public static InStream create(String name, ByteBuffer input, CompressionCodec codec, int bufferSize, boolean useVInts) throws IOException { if (codec == null) { return new UncompressedStream(name, input, useVInts); } else { return new CompressedStream(name, input, codec, bufferSize, useVInts);...
python
def get_stream_formats(self, media_item): """Get the available media formats for a given media item @param crunchyroll.models.Media @return dict """ scraper = ScraperApi(self._ajax_api._connector) formats = scraper.get_media_formats(media_item.media_id) return fo...
python
def _get_sig_prefix(self, sig): """Return signature prefix text. For attribute, data, and proc/iter directives this might be part of the signature. E.g. `type myNewType` will return a prefix of 'type' and `inline proc foo()` will return 'inline proc'. """ if self._is_proc_like():...
python
def reduce_terms(term_doc_matrix, scores, num_term_to_keep=None): ''' Parameters ---------- term_doc_matrix: TermDocMatrix or descendant scores: array-like Same length as number of terms in TermDocMatrix. num_term_to_keep: int, default=4000. Should be> 0. Number of terms to keep. Will keep between num...
java
public void setContentType(String contentType) { if (contentType == null) { _properties.remove(AMQP_PROP_CONTENT_TYPE); return; } _properties.put(AMQP_PROP_CONTENT_TYPE, contentType); }
java
public void applyTo(String[] arr) { for(int i = 0; i < arr.length; i++) arr[i] = stem(arr[i]); }
java
public static <T> Collector<T, ?, Optional<T>> reducing(BinaryOperator<T> op) { class OptionalBox implements Consumer<T> { T value = null; boolean present = false; @Override public void accept(T t) { if (present) { value = ...
java
public Photos getPopularPhotos(Date date, JinxConstants.PopularPhotoSort sort, Integer perPage, Integer page) throws JinxException { Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.stats.getPopularPhotos"); if (date != null) { params.put("date", JinxUtils.formatDateAsYMD(dat...
java
private void createPersistentSubsets(TransactionCommon tran) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "createPersistentSubsets", tran); for(int i=0; i<subsets.length; i++) { createPersistentSubset(getReliabil...
python
def _configure_manager(self): """ Creates a manager to handle autoscale operations. """ self._manager = ScalingGroupManager(self, resource_class=ScalingGroup, response_key="group", uri_base="groups")
java
public List<GoogleCalendar> getGoogleCalendars() { List<GoogleCalendar> googleCalendars = new ArrayList<>(); for (Calendar calendar : getCalendars()) { if (!(calendar instanceof GoogleCalendar)) { continue; } googleCalendars.add((GoogleCalendar) calend...
python
def _CanSkipDataStream(self, file_entry, data_stream): """Determines if analysis and extraction of a data stream can be skipped. This is used to prevent Plaso trying to run analyzers or extract content from a pipe or socket it encounters while processing a mounted filesystem. Args: file_entry (d...
python
def directly_or_indirectly_related(self, ns1, id1, ns2, id2, closure_dict, relation_func): """Return True if two entities have the speicified relationship. This relation is constructed possibly through multiple links connecting the two entities directly or...
python
def serialize(self): """This function serialize into a simple dict object. It is used when transferring data to other daemons over the network (http) Here we directly return all attributes :return: json representation of a DependencyNode :rtype: dict """ return ...
python
def body_encode(s, maxlinelen=76, eol=NL): r"""Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this fun...
java
public void polyDivide(GrowQueue_I8 dividend , GrowQueue_I8 divisor , GrowQueue_I8 quotient, GrowQueue_I8 remainder ) { // handle special case if( divisor.size > dividend.size ) { remainder.setTo(dividend); quotient.resize(0); return; } else { remainder.resize(divisor.size-1); quotient.se...
java
public Cases<java.sql.Date, DateExpression<java.sql.Date>> then(java.sql.Date then) { return thenDate(ConstantImpl.create(then)); }
java
protected void clearListeners(int code, String phrase) { listeners.forEach(listener -> listener.eventStreamClosed(code, phrase)); // Clear out the listeners listeners.clear(); }
python
def page(self, iso_code=values.unset, continent=values.unset, country_code=values.unset, low_risk_numbers_enabled=values.unset, high_risk_special_numbers_enabled=values.unset, high_risk_tollfraud_numbers_enabled=values.unset, page_token=values.unset, page_number=value...
java
public String appPay(AppPayDetail appPayDetail){ checkNotNullAndEmpty(alipay.appPriKey, "app private key"); Map<String, String> appPayParams = buildAppPayParams(appPayDetail); return buildRsaPayString(appPayParams); }
python
def losc_frame_urls(ifo, start_time, end_time): """ Get a list of urls to losc frame files Parameters ---------- ifo: str The name of the IFO to find the information about. start_time: int The gps time in GPS seconds end_time: int The end time in GPS seconds Returns...
java
@Override public void addAttack(Attack attack) { if(! initializedProperly) { throw new IllegalStateException(getUninitializedMessage()); } String message = gson.toJson(attack); try { RabbitMqUtils.sendMessage(message, Arrays.asList(APPSENSOR_ADD_ATTACK_QUEUE), environment); } catch (IOException e...
python
def contour_canny(image, radius, mult_coarse=.40, mult_fine=.1, clip_rmin=.9, clip_rmax=1.1, maxiter=20, verbose=True): """Heuristic Canny edge detection for circular objects Two Canny-based edge detections with different filter sizes are performed to find the outmost co...
python
def _fact_ref_eval(cls, cpeset, wfn): """ Returns True if wfn is a non-proper superset (True superset or equal to) any of the names in cpeset, otherwise False. :param CPESet cpeset: list of CPE bound Names. :param CPE2_3_WFN wfn: WFN CPE Name. :returns: True if wfn is a ...
python
def ngettext(self, singular, plural, num, domain=None, **variables): """Translate a string wity the current locale. The `num` parameter is used to dispatch between singular and various plural forms of the message. """ variables.setdefault('num', num) t = self.get_transl...
java
protected void channelRequest(String requesttype, boolean wantreply, byte[] requestdata) throws SshException { if (wantreply) { ByteArrayWriter msg = new ByteArrayWriter(); try { msg.write((byte) SSH_MSG_CHANNEL_FAILURE); msg.writeInt(remoteid); connection.sendMessage(msg.toByteArray(), true); ...
python
def cmd(command, *args, **kwargs): ''' NOTE: This function is preserved for backwards compatibilty. This allows commands to be executed using either of the following syntactic forms. salt '*' nxos.cmd <function> or salt '*' nxos.<function> command function from `salt.modules.nxo...
java
public List<HString> collectHString(@NonNull HString hString) { return streamHString(hString).collect(Collectors.toList()); }
java
public ItemRequest<Project> addCustomFieldSetting(String project) { String path = String.format("/projects/%s/addCustomFieldSetting", project); return new ItemRequest<Project>(this, Project.class, path, "POST"); }
python
def bootstrap(v): """ Constructs Monte Carlo simulated data set using the Bootstrap algorithm. Usage: >>> bootstrap(x) where x is either an array or a list of arrays. If it is a list, the code returns the corresponding list of bootst...
java
@Override public boolean isCalendarTimer() { boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "isCalendarTimer: " + this); // Determine if the calling bean is in a state that allows timer service // method a...
python
def stationary_distribution(self): r""" Compute stationary distribution of hidden states if possible. Raises ------ ValueError if the HMM is not stationary """ assert _tmatrix_disconnected.is_connected(self._Tij, strong=False), \ 'No unique stationary distri...
java
@Override public synchronized void messagingEngineStopping( final JsMessagingEngine messagingEngine, final int mode) { final String methodName = "messagingEngineStopping"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) ...
java
public void sbbExceptionThrown(Exception exception, Object obj, javax.slee.ActivityContextInterface activityContextInterface) { logger.info("CommonSbb: " + this + ": sbbExceptionThrown() called."); }
java
private void clearLock() throws CmsException { if ((m_lockActionRecord != null) && (m_lockActionRecord.getChange() == LockChange.locked)) { CmsResource updatedRes = m_cms.readResource(m_resource.getStructureId(), CmsResourceFilter.ALL); try { m_cms.unlockResource(updated...
python
def wait_on_event(self, in_event_type, timeout, capture_timeout=False): """Waits for an occurrence of the specified event in this resource. :param in_event_type: Logical identifier of the event(s) to wait for. :param timeout: Absolute time period in time units that the resource shall wait for a...
java
private void parseValue(byte[] data, CookieData token) { int start = -1; int stop = -1; int pos = this.bytePosition; int num_quotes = 0; // cycle through each byte until we hit a delimiter or end of data for (; pos < data.length; pos++) { byte b = data[pos];...
java
public static float[] cmykFromRgb(int rgbColor) { int red = (0xff0000 & rgbColor) >> 16; int green = (0xff00 & rgbColor) >> 8; int blue = (0xff & rgbColor); float black = Math.min(1.0f - red / 255.0f, Math.min(1.0f - green / 255.0f, 1.0f - blue / 255.0f)); float cyan = 1.0f; ...
python
def add_transcoder(application, transcoder, content_type=None): """ Register a transcoder for a specific content type. :param tornado.web.Application application: the application to modify :param transcoder: object that translates between :class:`bytes` and :class:`object` instances :param ...
java
public SparseDataset parse(String name, InputStream stream) throws IOException, ParseException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { // process header int nrow = 1; String line = reader.readLine(); for (; nrow <...
python
def ensure_compatible_admin(view): """ Ensures that the user is in exactly one role. Other checks could be added, such as requiring one prison if in prison-clerk role. """ def wrapper(request, *args, **kwargs): user_roles = request.user.user_data.get('roles', []) if len(user_roles) ...
java
@Override public void removeChangeListener(@NonNull ListenerToken token) { if (token == null) { throw new IllegalArgumentException("token cannot be null."); } liveQuery().removeChangeListener(token); }
java
public TimeDuration minus(TimeDuration duration) { return createWithCarry(sec - duration.getSec(), nanoSec - duration.getNanoSec()); }
java
public static String read(InputStream in) { InputStreamReader reader; try { reader = new InputStreamReader(in, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e.getMessage(), e); } return read(reader); }
python
def default(event, data): """The default handler prints basic event info.""" messages = defaultdict(lambda: 'Avast:') messages['start'] = 'Thar she blows!' messages['tag'] = 'Thar she blows!' messages['stop'] = 'Away into the depths:' messages['destroy'] = 'Away into the ...
java
protected UploadFile convertUploadFile(File file) { Date lastModifiedDate = new Date(); // Avoid parsing error on last modified date if (file.lastModifiedDate != null && !file.lastModifiedDate.isEmpty()) { lastModifiedDate = new Date(file.lastModifiedDate); } return n...
java
JCTree attribSpeculative(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) { return attribSpeculative(tree, env, resultInfo, treeCopier, (newTree)->new DeferredAttrDiagHandler(log, newTree), null); }
java
public Locale locale() { String languages = getHeader("Accept-Language"); if (languages != null) { // parse String[] acceptLanguages = languages.split(" *, *"); // sort on quality Arrays.sort(acceptLanguages, ACCEPT_X_COMPARATOR); String bestL...
python
def system_old(cls, line): """ duplicated """ print('') print('$ {}'.format(line)) return os.system(line)
java
@Override public Template getWsagObject(String serializedData) throws ParserException{ Template templateXML = null; try{ logger.info("Will parse {}", serializedData); JAXBContext jaxbContext = JAXBContext.newInstance(Template.class); Unmarshaller jaxbUnmarsh...
java
@Pure public static boolean containsOrientedBoxPoint( double cx, double cy, double cz, double axis1x, double axis1y, double axis1z, double axis2x, double axis2y, double axis2z, double axis3x, double axis3y, double axis3z, double axis1Extent, double axis2Extent, double axis3Extent, double px, double p...
java
@Restricted(NoExternalUse.class) public static void deleteContentsRecursive(@Nonnull Path path, @Nonnull PathRemover.PathChecker pathChecker) throws IOException { newPathRemover(pathChecker).forceRemoveDirectoryContents(path); }
java
private void addQuaternaryClause(final MiniSatStyleSolver s, int a, int b, int c, int d, int blocking) { assert this.clause.size() == 0; assert a != LIT_UNDEF && b != LIT_UNDEF && c != LIT_UNDEF && d != LIT_UNDEF; assert var(a) < s.nVars() && var(b) < s.nVars() && var(c) < s.nVars() && var(d) < s.nVars(); ...
python
def img2img_transformer2d_base(): """Base params for img2img 2d attention.""" hparams = image_transformer2d_base() # learning related flags hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" # This version seems to benefit from a higher learning rate. hparams.learning_rate =...