language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Bean @ConditionalOnMissingBean SoftwareModuleManagement softwareModuleManagement(final EntityManager entityManager, final DistributionSetRepository distributionSetRepository, final SoftwareModuleRepository softwareModuleRepository, final SoftwareModuleMetadataRepository soft...
java
public boolean isParamPanelOrChildSelected(String panelName) { DefaultMutableTreeNode node = getTreeNodeFromPanelName(panelName); if (node != null) { TreePath panelPath = new TreePath(node.getPath()); if (getTreeParam().isPathSelected(panelPath)) { return tru...
java
public void interpret(Specification table) { Statistics stats = new Statistics(); Example row = table.nextExample(); Example scenario = row.firstChild(); try { ScenarioMessage message = new ScenarioMessage( fixture.getTarget(), scenario.getContent() ); ...
python
def last(self, values, axis=0): """return values at last occurance of its associated key Parameters ---------- values : array_like, [keys, ...] values to pick the last value of per group axis : int, optional alternative reduction axis for values ...
java
protected ControlAreYouFlushed createControlAreYouFlushed(SIBUuid8 target, long ID, SIBUuid12 stream) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createControlAreYouFlushed"); ControlAreYouFlushed flushedqMsg; // Create new mess...
java
public LongConstant getLongByValue(long value) { for (int i = 0; i < _entries.size(); i++) { ConstantPoolEntry entry = _entries.get(i); if (! (entry instanceof LongConstant)) continue; LongConstant longEntry = (LongConstant) entry; if (longEntry.getValue() == value) retu...
python
def get_inline_styles(cls, instance): """ Returns a dictionary of CSS attributes to be added as style="..." to the current HTML tag. """ inline_styles = getattr(cls, 'default_inline_styles', {}) css_style = instance.glossary.get('inline_styles') if css_style: ...
java
private void scheduleGeneralConfiguredJobs() throws ConfigurationException, JobException, IOException { LOG.info("Scheduling configured jobs"); for (Properties jobProps : loadGeneralJobConfigs()) { if (!jobProps.containsKey(ConfigurationKeys.JOB_SCHEDULE_KEY)) { // A job without a cron sche...
java
private void onSetReplicateOnWrite(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String replicateOnWrite = cfProperties.getProperty(CassandraConstants.REPLICATE_ON_WRITE); if (builder != null) { String replicateOn_Write = CQLTranslator.getKeyword(CassandraConstan...
java
private boolean creatingFunctionShortensGremlin(GroovyExpression headExpr) { int tailLength = getTailLength(); int length = headExpr.toString().length() - tailLength; int overhead = 0; if (nextFunctionBodyStart instanceof AbstractFunctionExpression) { overhead = functionDefL...
python
def is_analysis_compatible(using): """ Returns True if the analysis defined in Python land and ES for the connection `using` are compatible """ python_analysis = collect_analysis(using) es_analysis = existing_analysis(using) if es_analysis == DOES_NOT_EXIST: return True # we want to...
java
@Override public void print(String line) { try { console.pushToConsole(line); } catch (IOException e) { e.printStackTrace(); } }
java
private static void writeZonePropsByDOW_GEQ_DOM_sub(Writer writer, int month, int dayOfMonth, int dayOfWeek, int numDays, long untilTime, int fromOffset) throws IOException { int startDayNum = dayOfMonth; boolean isFeb = (month == Calendar.FEBRUARY); if (dayOfMonth < 0 && !isFeb) { ...
python
def assess(self, cases=None): """Try to sort the **cases** using the network, return the number of misses. If **cases** is None, test all possible cases according to the network dimensionality. """ if cases is None: cases = product(range(2), repeat=self.dimension) ...
python
def parse_column_key_value(table_schema, setting_string): """ Parses 'setting_string' as str formatted in <column>[:<key>]=<value> and returns str type 'column' and json formatted 'value' """ if ':' in setting_string: # splits <column>:<key>=<value> into <column> and ...
java
public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(methodName, "Method name must not be null"); try { Method method = clazz.getMethod(methodName, args); return Modifier.isStatic(method.getModifiers()) ? ...
java
public static DateTimeComponents parse(String dateString, Boolean hasTime) { Matcher m = regex.matcher(dateString); if (!m.find()) { throw Messages.INSTANCE.getIllegalArgumentException(19, dateString); } int i = 1; int year = Integer.parseInt(m.group(i++)); int month = Integer.parseInt(m.group(i++)); ...
python
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): # type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node # NOQA """Resolve the pending_xref *node* with the given *typ* and *target*. This method sho...
python
def log(ltype, method, page, user_agent): """Writes to the log a message in the following format:: "<datetime>: <exception> method <HTTP method> page <path> \ user agent <user_agent>" """ try: f = open(settings.DJANGOSPAM_LOG, "a") f.write("%s: %s method %s pag...
java
@Override public void transferSucceeded(TransferEvent event) { TransferResource resource = event.getResource(); downloads.remove(resource); long contentLength = event.getTransferredBytes(); if (contentLength >= 0) { long duration = System.currentTimeMillis() - resource....
java
public static <T> List<T> slice(List<T> list, int... indexes) { List<T> slice = new ArrayList<>(indexes.length); for (int i : indexes) { slice.add(list.get(i)); } return slice; }
python
def logout(self): """ Log out, revoking the access tokens and forgetting the login details if they were given. """ self.revoke_refresh_token() self.revoke_access_token() self._username, self._password = None, None
python
def argmin(self, values): """return the index into values corresponding to the minimum value of the group Parameters ---------- values : array_like, [keys] values to pick the argmin of per group Returns ------- unique: ndarray, [groups] u...
python
def fit_predict(self, X, num_epochs=10, updates_epoch=10, stop_param_updates=dict(), batch_size=1, show_progressbar=False): """First fit, then predict.""" self.fit(X, ...
python
def typestring(obj): """Make a string for the object's type Parameters ---------- obj : obj Python object. Returns ------- `str` String representation of the object's type. This is the type's importable namespace. Examples -------- >>> import docutils.n...
python
def raid_alert(self, status, used, available, type): """RAID alert messages. [available/used] means that ideally the array may have _available_ devices however, _used_ devices are in use. Obviously when used >= available then things are good. """ if type == 'raid0': ...
java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String title = this.getIntent().getStringExtra(EXTRA_TITLE); if(title == null) title = getApplicationName(this); boolean enableAnonymous = this.getIntent().getBooleanExtra(EXTRA_ENABLE_ANO...
python
def add(self, sim, module, package=None): """ Add simulation to layer. """ super(Simulations, self).add(sim, module, package) # only update layer info if it is missing! if sim not in self.layer: # copy simulation source parameters to :attr:`Layer.layer` ...
python
def get_resources_to_check(client_site_url, apikey): """Return a list of resource IDs to check for broken links. Calls the client site's API to get a list of resource IDs. :raises CouldNotGetResourceIDsError: if getting the resource IDs fails for any reason """ url = client_site_url + u"d...
java
public final boolean removeExistingConfigurations(String filter) throws Exception { final boolean trace = TraceComponent.isAnyTracingEnabled(); BundleContext bundleContext = DataSourceService.priv.getBundleContext(FrameworkUtil.getBundle(DataSourceResourceFactoryBuilder.class)); ConfigurationAd...
java
public static byte[] readBytes(byte b[], int offset, int length) { byte[] retValue = new byte[length]; System.arraycopy(b, offset, retValue, 0, length); return retValue; }
java
public Association getAssociation(String collectionRole) { if ( associations == null ) { return null; } return associations.get( collectionRole ); }
java
private void printMetaMasterInfo() throws IOException { mIndentationLevel++; Set<MasterInfoField> masterInfoFilter = new HashSet<>(Arrays .asList(MasterInfoField.LEADER_MASTER_ADDRESS, MasterInfoField.WEB_PORT, MasterInfoField.RPC_PORT, MasterInfoField.START_TIME_MS, MasterInfoFi...
java
@Reference(authors = "T. Ooura", // title = "Gamma / Error Functions", booktitle = "", // url = "http://www.kurims.kyoto-u.ac.jp/~ooura/gamerf.html", // bibkey = "web/Ooura96") public static double erfc(double x) { if(Double.isNaN(x)) { return Double.NaN; } if(Double.isInfinite(x))...
java
public void detachMetadataCache(SlotReference slot) { MetadataCache oldCache = metadataCacheFiles.remove(slot); if (oldCache != null) { try { oldCache.close(); } catch (IOException e) { logger.error("Problem closing metadata cache", e); ...
python
def _update_settings(self, dialect): """Sets the widget settings to those of the chosen dialect""" # the first parameter is the dialect itself --> ignore for parameter in self.csv_params[2:]: pname, ptype, plabel, phelp = parameter widget = self._widget_from_p(pname, pt...
java
private DataBlockScanner getNextNamespaceSliceScanner(int currentNamespaceId) { Integer nextNsId = null; while ((nextNsId == null) && datanode.shouldRun && !blockScannerThread.isInterrupted()) { waitForOneNameSpaceUp(); synchronized (this) { if (getNamespaceSetSize() > 0) { ...
python
def SensorsDataGet(self, sensorIds, parameters): """ Retrieve sensor data for the specified sensors from CommonSense. If SensorsDataGet is successful, the result can be obtained by a call to getResponse(), and should be a json string. @param sensorIds (list) a list of s...
java
@Override public void die(String reason) { log.info("[die] Robot {} died with reason: {}", serialNumber, reason); if (alive) { // if not alive it means it was killed at creation alive = false; interrupted = true; // to speed up death world.remove(Robot.this); } }
java
public Object resolveProperty(Object object, String propertyName) { return resolveProperty(object, Collections.singletonList(propertyName)); }
python
def select_authors_by_geo(query): """Pass exact name (case insensitive) of geography name, return ordered set of author ids. """ for geo, ids in AUTHOR_GEO.items(): if geo.casefold() == query.casefold(): return set(ids)
java
public BitapMatcher substitutionOnlyMatcherFirst(int substitutions, final Sequence sequence) { return substitutionOnlyMatcherFirst(substitutions, sequence, 0, sequence.size()); }
java
public int compareTo(Point<E> obj) { if (obj == null) return -1; if (dimensions() != obj.dimensions()) return -1; for (int i = 0; i < dimensions(); i++) { if (getValue(i).getClass() != obj.getValue(i).getClass()) return -1; if (getValue(i) instanceof Double) { ...
java
static final int match(String text, int pos, String str) { for (int i = 0; i < str.length() && pos >= 0;) { int ch = UTF16.charAt(str, i); i += UTF16.getCharCount(ch); if (isBidiMark(ch)) { continue; } pos = match(text, pos, ch); ...
python
def _add_dophot_matches_to_database( self, dophotMatches, exposureIds): """*add dophot matches to database* **Key Arguments:** - ``dophotMatches`` -- a list of lists of dophot matches - ``exposureIds`` -- the ATLAS exposure IDs these matches w...
python
def prepare_request( url: Union[str, methods], data: Optional[MutableMapping], headers: Optional[MutableMapping], global_headers: MutableMapping, token: str, as_json: Optional[bool] = None, ) -> Tuple[str, Union[str, MutableMapping], MutableMapping]: """ Prepare outgoing request Cre...
python
def publish(self, channel, message, pipeline=False): """Post a message to a given channel. Args: channel (str): Channel where the message will be published message (str): Message to publish pipeline (bool): True, start a transaction block. Default false. """...
java
public static SynchronizedGeneratorIdentity basedOn(String quorum, String znode, Long claimDuration) throws IOException { ZooKeeperConnection zooKeeperConnection = new ZooKeeperConnection(...
java
public boolean isSubDirectory(File file1, File file2) { try { return (file1.getCanonicalPath()+File.separator).startsWith(file2.getCanonicalPath()+File.separator); } catch (IOException e) { e.printStackTrace(); return false; } }
java
public double getKeyAsDouble(int index) throws IOException { if (index >= structure.keySizes.size()) { throw new IOException("Index " + index + " is out of range."); } return Bytes.toDouble(key, structure.keyByteOffsets.get(index)); }
python
def __on_disconnect(self, client, userdata, result_code): # pylint: disable=W0613 """ Client has been disconnected from the server :param client: Client that received the message :param userdata: User data (unused) :param result_code: Disconnection reason (0: expected, 1...
java
@Override public StringBuffer getRequestURL() { StringBuffer sb = new StringBuffer(getScheme()); sb.append("://"); // Note: following code required if IPv6 IP host does not contain brackets // String host = getTargetHost(); // if (-1 != host.indexOf(":")) { // // wra...
java
public void writePlacemark(XMLStreamWriter xmlOut, ResultSet rs, int geoFieldIndex, String spatialFieldName) throws XMLStreamException, SQLException { xmlOut.writeStartElement("Placemark"); if (columnCount > 1) { writeExtendedData(xmlOut, rs); } StringBuilder sb = new StringB...
java
public static URI uriFromUrl(URL url) throws IllegalArgumentException { try { return url.toURI(); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
java
public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException { synchronized(m_objSync) { return m_tableRemote.doRemoteAction(strCommand, properties); } }
python
def OnMouseMotion(self, event): """Mouse motion event handler""" grid = self.grid pos_x, pos_y = grid.CalcUnscrolledPosition(event.GetPosition()) row = grid.YToRow(pos_y) col = grid.XToCol(pos_x) tab = grid.current_table key = row, col, tab merge_area...
java
public static BufferedImage loadImage(File file, int imageType){ BufferedImage img = loadImage(file); if(img.getType() != imageType){ img = BufferedImageFactory.get(img, imageType); } return img; }
python
def _process_status(self, status): """ Process latest status update. """ self._screen_id = status.get(ATTR_SCREEN_ID) self.status_update_event.set()
java
private void appendBranched(int startOffset, int pastEnd) { // Main tricky thing here is just replacing of linefeeds... if (mConvertLFs) { char[] inBuf = mBuffer; /* this will also unshare() and ensure there's room for at * least one more char */ ...
java
public static <W extends WitnessType<W>,ST,A> EitherT<W,ST,A> fromAnyM(final AnyM<W,A> anyM) { return of(anyM.map(Either::right)); }
java
protected final void applyTagId(AbstractHtmlState state, String tagId) throws JspException { state.id = generateTagId(tagId); }
python
def is_out_of_range(brain_or_object, result=_marker): """Checks if the result for the analysis passed in is out of range and/or out of shoulders range. min max warn min max warn ·········|----...
python
def _validate_and_parse_course_key(self, course_key): """ Returns a validated parsed CourseKey deserialized from the given course_key. """ try: return CourseKey.from_string(course_key) except InvalidKeyError: raise ValidationError(_("Invalid course key: {}...
java
public void marshall(EnvironmentPropertyUpdates environmentPropertyUpdates, ProtocolMarshaller protocolMarshaller) { if (environmentPropertyUpdates == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(e...
python
def _handle_tag_definefontname(self): """Handle the DefineFontName tag.""" obj = _make_object("DefineFontName") obj.FontId = unpack_ui16(self._src) obj.FontName = self._get_struct_string() obj.FontCopyright = self._get_struct_string() return obj
java
public static String serialize(String xmlString) { StringWriter sw = new StringWriter(); serialize(asStreamSource(xmlString), sw); return sw.toString(); }
java
public static void generate(ConfigurationImpl configuration, ClassTree classtree) throws DocFileIOException { ClassUseMapper mapper = new ClassUseMapper(configuration, classtree); for (TypeElement aClass : configuration.getIncludedTypeElements()) { // If -nodeprecated option is set and the ...
java
public Vector3d div(Vector3dc v, Vector3d dest) { dest.x = x / v.x(); dest.y = y / v.y(); dest.z = z / v.z(); return dest; }
java
@Override public void visitCode(final Code obj) { try { localCollections = new HashMap<>(); localScopeEnds = new HashMap<>(); localSourceLineAnnotations = new HashMap<>(); stack.resetForMethodEntry(this); super.visitCode(obj); } finally { ...
java
public static ObjectFields convertGenObjectFieldsToObjectFields(org.fcrepo.server.types.gen.ObjectFields source) { if (source == null) { return null; } ObjectFields result = new ObjectFields(); result.setPid(source.getPid() != null ? source.getPid().getValue() : null); ...
python
def _handle_qos1_message_flow(self, app_message): """ Handle QOS_1 application message acknowledgment For incoming messages, this method stores the message and reply with PUBACK For outgoing messages, this methods sends PUBLISH and waits for the corresponding PUBACK :param app_me...
java
public BioCDocument readDocument() throws XMLStreamException { if (reader.document != null) { BioCDocument thisDocument = reader.document; reader.read(); return thisDocument; } else { return null; } }
python
def comment(request, template="generic/comments.html", extra_context=None): """ Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ response = initial_validation(request, "comment") if isinstance(response, HttpResponse): return response obj, post_...
java
byte[][] getFamilyKeys() { Charset c = Charset.forName(charset); byte[][] familyKeys = new byte[this.familyMap.size()][]; int i = 0; for (String name : this.familyMap.keySet()) { familyKeys[i++] = name.getBytes(c); } return familyKeys; }
java
public void revive(CmsObject adminCms, CmsPublishList publishList) throws CmsException { CmsContextInfo context = new CmsContextInfo(adminCms.readUser(m_userId).getName()); CmsProject project = adminCms.readProject(m_projectId); context.setLocale(m_locale); m_cms = OpenCms.initCmsObjec...
python
def apache_md5crypt(password, salt, magic='$apr1$'): """ Calculates the Apache-style MD5 hash of a password """ password = password.encode('utf-8') salt = salt.encode('utf-8') magic = magic.encode('utf-8') m = md5() m.update(password + magic + salt) mixin = md5(password + salt + pa...
java
public Q profiler(QueryProfiler profiler) { Preconditions.checkNotNull(profiler); this.profiler=profiler; return getThis(); }
python
def dock_help(): """Help message for Dock Widget. .. versionadded:: 3.2.1 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) return message
python
def add_job(self, job, merged=False, widened=False): """ Appended a new job to this JobInfo node. :param job: The new job to append. :param bool merged: Whether it is a merged job or not. :param bool widened: Whether it is a widened job or not. """ job_type = '' ...
java
public void marshall(DvbTdtSettings dvbTdtSettings, ProtocolMarshaller protocolMarshaller) { if (dvbTdtSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(dvbTdtSettings.getTdtInterval(), TDTI...
python
def parse_field(self, field_data, index=0): """Parse field and add missing options""" field = { '__index__': index, } if isinstance(field_data, str): field.update(self.parse_string_field(field_data)) elif isinstance(field_data, dict): field.up...
python
def subject(self) -> Optional[UnstructuredHeader]: """The ``Subject`` header.""" try: return cast(UnstructuredHeader, self[b'subject'][0]) except (KeyError, IndexError): return None
java
public void addRule(IntDependency dependency, double count) { if ( ! directional) { dependency = new IntDependency(dependency.head, dependency.arg, false, dependency.distance); } if (verbose) System.err.println("Adding dep " + dependency); // coreDependencies.incrementCount(dependency, cou...
python
def betas_for_cov(self, covariate = '0'): """betas_for_cov returns the beta values (i.e. IRF) associated with a specific covariate. :param covariate: name of covariate. :type covariate: string """ # find the index in the designmatrix of the current covariate this...
python
async def update(self, _id=None, **new_data): """Updates fields values. Accepts id of sigle entry and fields with values. update(id, **kwargs) => {"success":200, "reason":"Updated"} (if success) update(id, **kwargs) => {"error":400, "reason":"Missed required fields"} (if error) """ if not _id or not ne...
java
public void setMobileApplicationSegment(com.google.api.ads.admanager.axis.v201902.MobileApplicationTargeting mobileApplicationSegment) { this.mobileApplicationSegment = mobileApplicationSegment; }
python
def is_a_sequence(var, allow_none=False): """ Returns True if var is a list or a tuple (but not a string!) """ return isinstance(var, (list, tuple)) or (var is None and allow_none)
java
public void setUrlAttribute(String name, String value) { ensureValue(); Attribute attribute = new UrlAttribute(value); attribute.setEditable(isEditable(name)); getValue().getAllAttributes().put(name, attribute); }
java
public final <R> Iterable<R> mapReduce(String name, DBObject query, DBObject sort, Map<String, Object> scope, final MapReduceResultHandler<R> conv) { String map = this.getMRFunction(name, "map"); String reduce = this.getMRFunction(name, "reduce"); MapReduceCommand mrc = new MapReduceCommand(thi...
java
public void put(ItemData item) { // There is different commit processing for NullNodeData and ordinary ItemData. if (item instanceof NullItemData) { putNullItem((NullItemData)item); return; } boolean inTransaction = cache.isTransactionActive(); try ...
python
def getargspec(fn): # type: (Callable) -> inspect.ArgSpec """Get the names and default values of a function's arguments. Args: fn (function): a function Returns: `inspect.ArgSpec`: A collections.namedtuple with the following attributes: * Args: args (list): a...
python
def _stringlist_to_dictionary(input_string): ''' Convert a stringlist (comma separated settings) to a dictionary The result of the string setting1=value1,setting2=value2 will be a python dictionary: {'setting1':'value1','setting2':'value2'} ''' li = str(input_string).split(',') ret = {} ...
java
@Override protected AstNode parseCustomStatement( DdlTokenStream tokens, AstNode parentNode ) throws ParsingException { assert tokens != null; assert parentNode != null; if (tokens.matches(STMT_RENAME_DATABASE)) { markStartOfStatement(...
python
def _get_document_data(database, document): """ A safer version of Xapian.document.get_data Simply wraps the Xapian version and catches any `Xapian.DatabaseModifiedError`, attempting a `database.reopen` as needed. Required arguments: `database` -- The database to be...
java
protected void rehash(final int newN) { final char key[] = this.key; final char value[] = this.value; final int mask = newN - 1; // Note that this is used by the hashing macro final char newKey[] = new char[newN + 1]; final char newValue[] = new char[newN + 1]; int i = n,...
python
def close(self): """ Just send a message off to all the pool members which contains the special :class:`_close_pool_message` sentinel. """ if self.is_master(): for i in range(self.size): self.comm.isend(_close_pool_message(), dest=i + 1)
java
private void setConnector(final SocketConnector connector) { if (connector == null) { throw new NullPointerException("connector cannot be null"); } this.connector = connector; String className = ProxyFilter.class.getName(); // Removes an old ProxyFilter instance fro...
python
def default_logger(self, name=__name__, enable_stream=False, enable_file=True): """Default Logger. This is set to use a rotating File handler and a stream handler. If you use this logger all logged output that is INFO and above will be logged, unless debug_logging...
python
def insert_many(cls, documents, ordered=True): """ Inserts a list of documents into the Collection and returns their _ids """ return cls.collection.insert_many(documents, ordered).inserted_ids
java
public T fql_query(CharSequence query) throws FacebookException, IOException { assert (null != query); return this.callMethod(FacebookMethod.FQL_QUERY, new Pair<String, CharSequence>("query", query)); }