language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void waitForNewTableMetadata() { TableMetadata metadata; int retries = 0; final int waitTime = 100; do { metadata = getSession() .getCluster() .getMetadata() .getKeyspace(this.catalog) .ge...
java
public void marshall(NonCompliantSummary nonCompliantSummary, ProtocolMarshaller protocolMarshaller) { if (nonCompliantSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(nonCompliantSummary.ge...
python
def get_registration(self, path): """ Returns registration item for specified path. If an email template is not registered, this will raise NotRegistered. """ if not self.is_registered(path): raise NotRegistered("Email template not registered") return self._r...
python
def fun_wv(xchannel, crpix1, crval1, cdelt1): """Compute wavelengths from channels. The wavelength calibration is provided through the usual parameters CRPIX1, CRVAL1 and CDELT1. Parameters ---------- xchannel : numpy array Input channels where the wavelengths will be evaluated. cr...
java
private static UIComponent getChild( UIComponentClassicTagBase tag, UIComponent component, String componentId) { int childCount = component.getChildCount(); // we only need to bother to check if we even have children if (childCount > 0) { List<UIComponent> ch...
python
def GetFeedMapping(client, feed, placeholder_type): """Gets the Feed Mapping for a given Feed. Args: client: an AdWordsClient instance. feed: the Feed we are retrieving the Feed Mapping for. placeholder_type: the Placeholder Type we are looking for. Returns: A dictionary containing the Feed Mappi...
python
def ReinstallInstance(r, instance, os=None, no_startup=False, osparams=None): """ Reinstalls an instance. @type instance: str @param instance: The instance to reinstall @type os: str or None @param os: The operating system to reinstall. If None, the instance's current operating syst...
python
def set_itunes_closed_captioned(self): """Parses isClosedCaptioned from itunes tags and sets value""" try: self.itunes_closed_captioned = self.soup.find( 'itunes:isclosedcaptioned').string self.itunes_closed_captioned = self.itunes_closed_captioned.lower() ...
python
def from_string(contents): """ Creates XYZ object from a string. Args: contents: String representing an XYZ file. Returns: XYZ object """ if contents[-1] != "\n": contents += "\n" white_space = r"[ \t\r\f\v]" natoms_li...
java
public final void retrievePage(final Map<String, Object> pAddParam, final IRequestData pRequestData, final Map<String, Class<?>> pEntityMap, final boolean pShowDbgMsg, final IDelegateEvaluate<IRequestData, String> pFilterFiMaker) throws Exception { String nmEnt; if (pAddParam.get("na...
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataPropertyAssertionAxiomImpl instance) throws SerializationException { serialize(streamWriter, instance); }
python
def _compute(self, funcTilde, R, z, phi): """ NAME: _compute PURPOSE: evaluate the NxLxM density or potential INPUT: funcTidle - must be _rhoTilde or _phiTilde R - Cylindrical Galactocentric radius z - vertical height phi ...
python
def request(self, action, params=None, action_token_type=None, upload_info=None, headers=None): """Perform request to MediaFire API action -- "category/name" of method to call params -- dict of parameters or query string action_token_type -- action token to use: None, "u...
java
protected ISourceAppender appendFiresClause(ISourceAppender appendable) { final List<LightweightTypeReference> types = getFires(); final Iterator<LightweightTypeReference> iterator = types.iterator(); if (iterator.hasNext()) { appendable.append(" ").append(this.keywords.getFiresKeyword()).append(" "); //$NON-N...
java
public static WritableRaster integerArray2WritableRaster( int[] array, double divide, int width, int height ) { WritableRaster writableRaster = createWritableRaster(width, height, null, null, null); int index = 0;; for( int x = 0; x < width; x++ ) { for( int y = 0; y < height; y++ ) ...
java
public static int size(AsciiString str) { return str == null? Global.SHORT_SIZE : Global.SHORT_SIZE + str.length(); }
python
def crash_signature_matcher(text_log_error): """ Query for TextLogErrorMatches with the same crash signature. Produces two queries, first checking if the same test produces matches and secondly checking without the same test but lowering the produced scores. """ failure_line = text_log_erro...
java
public T withManagedEntityClasses(List<Class<?>> entityClasses) { configMap.put(MANAGED_ENTITIES, entityClasses); return getThis(); }
java
public static String stripExt(final String aFileName) { final int index = aFileName.lastIndexOf(DOT); if (index != -1) { return aFileName.substring(0, index); } return aFileName; }
python
def _CreateFeedMapping(client, feed_details): """Creates the feed mapping for DSA page feeds. Args: client: an AdWordsClient instance. feed_details: a _DSAFeedDetails instance. """ # Get the FeedMappingService. feed_mapping_service = client.GetService('FeedMappingService', ...
python
def make_update(cls, table, set_query, where=None): """ Make UPDATE query. :param str table: Table name of executing the query. :param str set_query: SET part of the UPDATE query. :param str where: Add a WHERE clause to execute query, if the value is not ...
java
private char getRelationFromStringMatchers(String sourceLabel, String targetLabel) { char relation = IMappingElement.IDK; int i = 0; while ((relation == IMappingElement.IDK) && (i < stringMatchers.size())) { relation = stringMatchers.get(i).match(sourceLabel, targetLabel); ...
python
def unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame """ path = self.list[name] df = pd.read_pickl...
python
def decode(self, data, delimiter=';'): """Decode a message from command string.""" try: list_data = data.rstrip().split(delimiter) self.payload = list_data.pop() (self.node_id, self.child_id, self.type, self.ack, sel...
python
def align(self, alignment_tool = 'clustalw', gap_opening_penalty = 0.2, ignore_bad_chains = False): '''If ignore_bad_chains is True then any chains containing all Xs as the sequence will be silently skipped. The default behavior is to raise a MalformedSequenceException in this case.''' if len...
java
@GET @Produces("text/plain") @Path("check") public String check(@QueryParam("q") String query, @DefaultValue("") @QueryParam("corpora") String rawCorpusNames) { Subject user = SecurityUtils.getSubject(); List<String> corpusNames = splitCorpusNamesFromRaw(rawCorpusNames); for (String c : corpusN...
java
@Override public CommerceAccount fetchCommerceAccountByReferenceCode(long companyId, String externalReferenceCode) { return commerceAccountPersistence.fetchByC_ERC(companyId, null); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); Object result = mapping.get(value); if( result == null ) { result = defaultValue; } return next.execute(result, context); }
python
def stop_trial(self, trial_id): """Requests to stop trial by trial_id.""" response = requests.put( urljoin(self._path, "trials/{}".format(trial_id))) return self._deserialize(response)
python
def get_device_elements(self): """Get the DOM elements for the device list.""" plain = self._aha_request('getdevicelistinfos') dom = xml.dom.minidom.parseString(plain) _LOGGER.debug(dom) return dom.getElementsByTagName("device")
python
def delim(arguments): """ Execute delim action. :param arguments: Parsed command line arguments from :func:`main` """ if bool(arguments.control_files) == bool(arguments.directory): raise ValueError( 'Exactly one of control_files and `-d` must be specified.') if argumen...
python
def flatten(iterable, check=is_iterable): """Produces a recursively flattened version of ``iterable`` ``check`` Recurses only if check(value) is true. """ for value in iterable: if check(value): for flat in flatten(value, check): yield flat else: ...
python
def del_watch(self, wd): """ Remove watch entry associated to watch descriptor wd. @param wd: Watch descriptor. @type wd: int """ try: del self._wmd[wd] except KeyError as err: log.error('Cannot delete unknown watch descriptor %s' % str(er...
java
public synchronized void setAdminMain(JsMain o) { if (_jsmain != null) { // We have received a second or subsequent set request. This indicates an internal // programming error or some abuse of the interface. Rather than throw exceptions // at this point, we simply remember this and output some RA...
java
public void marshall(AssociationExecution associationExecution, ProtocolMarshaller protocolMarshaller) { if (associationExecution == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(associationExecutio...
java
private boolean isSetterForField(ExecutableElement setter, VariableElement field) { return setter.getParameters() != null && setter.getParameters().size() == 1 && setter.getParameters().get(0).asType().equals(field.asType()); // TODO inheritance? TypeUtils is applicable? }
python
def roll_qtrday(other, n, month, day_option, modby=3): """Possibly increment or decrement the number of periods to shift based on rollforward/rollbackward conventions. Parameters ---------- other : cftime.datetime n : number of periods to increment, before adjusting for rolling month : int ...
java
protected boolean loadPropertyValue(LocalVariable[] stashedProperties, Boolean[] stashedFromInstances, CodeAssembler a, StorablePropertyInfo info, int ordinal, ...
python
def _compute_primary_smooths(self): """Compute fixed-span smooths with all of the default spans.""" for span in DEFAULT_SPANS: smooth = smoother.perform_smooth(self.x, self.y, span) self._primary_smooths.append(smooth)
python
def remove(text, exclude): """Remove ``exclude`` symbols from ``text``. Example: >>> remove("example text", string.whitespace) 'exampletext' Args: text (str): The text to modify exclude (iterable): The symbols to exclude Returns: ``text`` with ``exclude`` symbo...
java
@SuppressWarnings("deprecation") public static String urlUnescape(String s) { try { return URLDecoder.decode(s, "UTF8"); } catch (UnsupportedEncodingException e) { // should be impossible; all JVMs must support UTF8 // but have a fallback just in case ...
java
@Nullable static VariableElement findCreator(Elements elements, Types types, TypeMirror type) { if (type.getKind() != TypeKind.DECLARED) { return null; } DeclaredType declaredType = (DeclaredType) type; TypeElement typeElement = (TypeElement) declaredType.asElement(); return findCreator(elemen...
java
public Object getArgumentValue() { try { return getUnderlyingField().get(getContainingObject()); } catch (final IllegalAccessException e) { throw new CommandLineException.ShouldNeverReachHereException( "This shouldn't happen since we setAccessible(true).", e);...
java
protected char[] encodeHex(byte[] data) { final int len = data.length; final char[] out = new char[len << 1]; for (int i = 0, j = 0; i < len; i++) { out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4]; out[j++] = DIGITS_LOWER[0x0F & data[i]]; } return out; ...
java
boolean isIntermediaryPath(final JsonPointer jp) { List<String> jpRefTokens = jp.tokens(); int jpSize = jpRefTokens.size(); if (jpSize == 1) { return false; } Node node = root; for (int i = 1; i < jpSize; i++) { Node childMatch = node.match(jpRefT...
java
protected void parseTableConstraint( DdlTokenStream tokens, AstNode tableNode, boolean isAlterTable ) throws ParsingException { assert tokens != null; assert tableNode != null; String mixinType = isAlterTable ? TY...
python
def main(): """ Main entry point for running baseconvert as a command. Examples: $ python -m baseconvert -n 0.5 -i 10 -o 20 -s True 0.A $ echo 3.1415926 | python -m baseconvert -i 10 -o 16 -d 3 -s True 3.243 """ # Parse arguments parser = argparse.ArgumentParse...
java
public final HttpClient addNameValuePair(final String param, final Integer value) { return addNameValuePair(param, value.toString()); }
java
public StreamBlock poll() { StreamBlock sb = null; if (m_memoryDeque.peek() != null) { sb = m_memoryDeque.poll(); } else { sb = pollPersistentDeque(true); } return sb; }
java
protected DropDownChoice<T> newChildChoice(final String id, final IModel<TwoDropDownChoicesBean<T>> model) { final IModel<T> selectedChildOptionModel = new PropertyModel<>(model, "selectedChildOption"); final IModel<List<T>> childChoicesModel = PropertyModel.of(model, "childChoices"); final DropDownChoice<T...
python
def create_socketpair(size=None): """ Create a :func:`socket.socketpair` to use for use as a child process's UNIX stdio channels. As socket pairs are bidirectional, they are economical on file descriptor usage as the same descriptor can be used for ``stdin`` and ``stdout``. As they are sockets their...
java
public Observable<Page<ProtectionContainerResourceInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<ProtectionContainerResourceInner>>, Page<ProtectionContainerResourceInner>>() { @Override ...
python
def uuid(self, name=None, pad_length=22): """ Generate and return a UUID. If the name parameter is provided, set the namespace to the provided name and generate a UUID. """ # If no name is given, generate a random UUID. if name is None: uuid = _uu.uui...
java
@Override @Transactional(rollbackFor = Exception.class) public void updateAll(List pDatas) throws APPErrorException { for (int i = 0; i < pDatas.size(); i++) { update(pDatas.get(i)); } }
java
public boolean isXForwardedHeaderRequired() { return forwardedHeader == null && (xForwardedForHeader != null || xForwardedByHeader != null || xForwardedHostHeader != null || xForwardedProtoHeader != null); }
python
def get_iscsi_initiator_info(self): """Give iSCSI initiator information of iLO. :returns: iSCSI initiator information. :raises: IloError, on an error from iLO. :raises: IloCommandNotSupportedError, if the system is in the bios boot mode. """ headers, bio...
python
async def async_get(self, url): """Get an arbitrary page. This resets the iterator and then fully consumes it to return the specific page **only**. :param str url: URL to arbitrary page results. """ self.reset() self.next_link = url return await self.asy...
java
public boolean remove(Entry<K,V> e) { int _hash = modifiedHashCode(e.hashCode); OptimisticLock[] _locks = locks; int si = _hash & LOCK_MASK; OptimisticLock l = _locks[si]; long _stamp = l.writeLock(); try { Entry<K,V> f; Entry<K,V>[] tab = entries; if (tab == null) { throw ne...
java
public static double distance(Point p1, Point p2) { double x = p2.x - p1.x; double y = p2.y - p1.y; double z = p2.z - p1.z; return Math.sqrt(x * x + y * y + z * z); }
python
def read_members_of(self, member_id, query_membership=None): """ReadMembersOf. [Preview API] :param str member_id: :param str query_membership: :rtype: [str] """ route_values = {} if member_id is not None: route_values['memberId'] = self._seria...
python
def fast_sync_snapshot_compress( snapshot_dir, export_path ): """ Given the path to a directory, compress it and export it to the given path. Return {'status': True} on success Return {'error': ...} on failure """ snapshot_dir = os.path.abspath(snapshot_dir) export_path = os.path.abspa...
python
def cpfs(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], noise: Optional[Noise] = None) -> Tuple[List[TensorFluent], List[TensorFluent]]: '''Compiles the intermediate and next state fluent CPFs given the current `state` and `action`. Args: ...
python
def plot_conv_activity(layer, x, figsize=(6, 8)): """Plot the acitivities of a specific layer. Only really makes sense with layers that work 2D data (2D convolutional layers, 2D pooling layers ...). Parameters ---------- layer : lasagne.layers.Layer x : numpy.ndarray Only takes one ...
python
def create_exposed_session(self, session, key=None, context=None): """ :type session: SimpleSession """ # shiro ignores key and context parameters return DelegatingSession(self, SessionKey(session.session_id))
python
def authenticate(self, session: Session, listener): """ This method call the authenticate method on registered plugins to test user authentication. User is considered authenticated if all plugins called returns True. Plugins authenticate() method are supposed to return : - True ...
python
def WriteToPath(obj, filepath): """Serializes and writes given Python object to the specified YAML file. Args: obj: A Python object to serialize. filepath: A path to the file into which the object is to be written. """ with io.open(filepath, mode="w", encoding="utf-8") as filedesc: WriteToFile(obj,...
java
protected Object readResolve() throws ObjectStreamException { try { if (type == Type.SECRET && RAW.equals(format)) { return new SecretKeySpec(encoded, algorithm); } else if (type == Type.PUBLIC && X509.equals(format)) { KeyFactory f = KeyFactory.getInstanc...
java
public static Set<IProcessor> createStandardProcessorsSet(final String dialectPrefix) { /* * It is important that we create new instances here because, if there are * several dialects in the TemplateEngine that extend StandardDialect, they should * not be returning the exact same ins...
java
public void runtimeEventOccurred(RuntimeEvent event) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "runtimeEventOccurred", new Object[] { event}); // Call out to the real GatewayLink MBean's RuntimeEventListener // if we determ...
java
protected void updateBreadCrumb(Map<String, String> breadCrumbEntries) { LinkedHashMap<String, String> entries = new LinkedHashMap<String, String>(); I_CmsWorkplaceAppConfiguration launchpadConfig = OpenCms.getWorkplaceAppManager().getAppConfiguration( CmsAppHierarchyConfiguration.APP_ID); ...
java
public void validate(final ValidationContext context) { if (!isValid()) { val messages = context.getMessageContext(); messages.addMessage(new MessageBuilder() .error() .source("token") .defaultText("Unable to accept credential with an empty...
python
def main(): """Play Conway's Game of Life on the terminal.""" def die((x, y)): """Pretend any out-of-bounds cell is dead.""" if 0 <= x < width and 0 <= y < height: return x, y LOAD_FACTOR = 9 # Smaller means more crowded. NUDGING_LOAD_FACTOR = LOAD_FACTOR * 3 # Smaller mea...
python
def snmp_server_view_mibtree(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") view = ET.SubElement(snmp_server, "view") viewname_key = ET.SubElement(view...
java
public static boolean depthFirstTargetSearch(IAtomContainer molecule, IAtom root, IAtom target, IAtomContainer path) { List<IBond> bonds = molecule.getConnectedBondsList(root); IAtom nextAtom; root.setFlag(CDKConstants.VISITED, true); boolean first = path.isEmpty(); if (first) ...
java
public Integer getInteger(String key) { Integer iVal = null; String sVal = getText(key); if ((sVal != null) && (sVal.length() > 0)) { iVal = Integer.valueOf(sVal); } return iVal; }
python
def normalize_rgb_colors_to_hex(css): """Convert `rgb(51,102,153)` to `#336699`.""" regex = re.compile(r"rgb\s*\(\s*([0-9,\s]+)\s*\)") match = regex.search(css) while match: colors = [s.strip() for s in match.group(1).split(",")] hexcolor = '#%.2x%.2x%.2x' % tuple(map(int, colors)) ...
java
public boolean isDefaultNamespace(String namespaceURI) { int type = getNodeType(); if (type == NodeKind.ATTR) { if (this instanceof AttrImpl == false) { // ns decl throw new UnsupportedOperationException(); } } Node p = getParentNod...
java
public List<CmsResource> readSiblingsForResourceId(CmsUUID resourceId, CmsResourceFilter filter) throws CmsException { CmsResource pseudoResource = new CmsResource( null, resourceId, null, 0, false, 0, null, nul...
java
public static CouchbaseAsyncCluster create(final CouchbaseEnvironment environment, final List<String> nodes) { return new CouchbaseAsyncCluster(environment, ConnectionString.fromHostnames(nodes), true); }
python
def extract_geo(self): ''' Extract geo-related information from exif ''' altitude = self.extract_altitude() dop = self.extract_dop() lon, lat = self.extract_lon_lat() d = {} if lon is not None and lat is not None: d['latitude'] = lat ...
python
def _get_assessment_part(self, part_id=None): """Gets an AssessmentPart given a part_id. Returns this Section's own part if part_id is None. Make this a private part, so that it doesn't collide with the AssessmentPart.get_assessment_part method, which does not expect any arguments... ...
python
def get_master(exchange_id, format=u"Default"): """ Requests a calendar item from the store. exchange_id is the id for this event in the Exchange store. format controls how much data you get back from Exchange. Full docs are here, but acceptible values are IdOnly, Default, and AllProperties. ht...
python
def get_form_schema(form): """Return a JSON Schema object for a Django Form.""" schema = { 'type': 'object', 'properties': {}, } for name, field in form.base_fields.items(): schema['properties'][name] = get_field_schema(name, field) if field.required: schema....
python
def value_to_python(self, value): """ Converts the input single value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. """ if not isins...
python
def _drawBackground(self, scene, painter, rect): """ Draws the backgroud for a particular scene within the charts. :param scene | <XChartScene> painter | <QPainter> rect | <QRectF> """ rect = scene.sceneRect() ...
python
def login(username, password, **kwargs): """ Login a user, returning a dict containing their user_id and session_id This does the DB login to check the credentials, and then creates a session so that requests from apps do not need to perform a login args: username (stri...
python
def get_import_data_kwargs(self, request, *args, **kwargs): """ Prepare kwargs for import_data. """ form = kwargs.get('form') if form: kwargs.pop('form') return kwargs return {}
java
static String likeToRegex(String like) { StringBuilder builder = new StringBuilder(); boolean wasPercent = false; for (int i = 0; i < like.length(); ++i) { char c = like.charAt(i); if (isPlain(c)) { if (wasPercent) {...
java
@Deprecated public MamPrefsResult updateArchivingPreferences(List<Jid> alwaysJids, List<Jid> neverJids, DefaultBehavior defaultBehavior) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, NotLoggedInException { Objects.requireNonNull(defaultB...
python
def sectionFromFunction(function,*args,**kwargs): """ This staticmethod executes the function that is passed with the provided args and kwargs. The first line of the function docstring is used as the section title, the comments within the function body are parsed and added as the section...
python
def monthdays2calendar(cls, year, month): """ Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers. """ weeks = [] week = [] for day in NepCal.itermonthdays2(year, month): week.appe...
java
public EClass getIfcMagneticFluxMeasure() { if (ifcMagneticFluxMeasureEClass == null) { ifcMagneticFluxMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(704); } return ifcMagneticFluxMeasureEClass; }
python
def _bind_as(self, bind_dn, bind_password, sticky=False): """ Binds to the LDAP server with the given credentials. This does not trap exceptions. If sticky is True, then we will consider the connection to be bound for the life of this object. If False, then the caller only wishe...
java
public static void unescapeJson(final String text, final Writer writer) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (text == null) { return; } if (text.indexOf('\\') <...
java
ProofreadingResult getCheckResults(String paraText, Locale locale, ProofreadingResult paRes, int[] footnotePositions, boolean isParallelThread, JLanguageTool langTool) { try { SingleProofreadingError[] sErrors = null; paraNum = getParaPos(paraText, isParallelThread); // Don't use Cache for ...
java
private CmsLock getParentLock(final String absoluteResourcename) { CmsLock parentFolderLock = getParentFolderLock(absoluteResourcename); if (!parentFolderLock.isNullLock()) { return parentFolderLock; } return CmsLock.getNullLock(); }
python
def refresh_token(self, request, data, client): """ Handle ``grant_type=refresh_token`` requests as defined in :rfc:`6`. """ rt = self.get_refresh_token_grant(request, data, client) # this must be called first in case we need to purge expired tokens self.invalidate_refre...
java
@Override public final int compareTo(final Id that) { if (!that.getClass().equals(this.getClass())) { throw new ClassCastException("Incomparable Id types: " + that.getClass() + " being compared to " + this.getClass()); } else { return this.id.compareTo(that.id); } }
python
def iter_all_dict_combinations_ordered(varied_dict): """ Same as all_dict_combinations but preserves order """ tups_list = [[(key, val) for val in val_list] for (key, val_list) in six.iteritems(varied_dict)] dict_iter = (OrderedDict(tups) for tups in it.product(*tups_list)) retu...
java
public static <V> void addCallback( ListenableFuture<V> future, FutureCallback<? super V> callback) { addCallback(future, callback, directExecutor()); }