language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void delete(String resourceGroupName, String routeTableName, String routeName) { deleteWithServiceResponseAsync(resourceGroupName, routeTableName, routeName).toBlocking().last().body(); }
python
def shelter_get(self, **kwargs): """ shelter.get wrapper. Given a shelter ID, retrieve its details in dict form. :rtype: dict :returns: The shelter's details. """ root = self._do_api_call("shelter.get", kwargs) shelter = root.find("shelter") for...
python
def prompt_for_new_password(): """ Prompt the user to enter a new password, with confirmation """ while True: passw = getpass.getpass() passw2 = getpass.getpass() if passw == passw2: return passw print 'Passwords do not match'
python
def items(self): """An iterable of all (anchor-id, Anchor) mappings in the repository. """ for anchor_id in self: try: anchor = self[anchor_id] except KeyError: assert False, 'Trying to load from missing file or something' yiel...
java
@SuppressWarnings("unchecked") @Override public EList<IfcBoundaryCurve> getBoundaries() { return (EList<IfcBoundaryCurve>) eGet(Ifc4Package.Literals.IFC_CURVE_BOUNDED_SURFACE__BOUNDARIES, true); }
python
def _match_filenames_w_dfs(filenames, lo_dfs): """ Match a list of filenames to their data frame counterparts. Return data frames :param list filenames: Filenames of data frames to retrieve :param dict lo_dfs: All data frames :return dict: Filenames and data frames (filtered) """ logger_data...
python
def save_configuration_to_hdf5(register, configuration_file, name=''): '''Saving configuration to HDF5 file from register object Parameters ---------- register : pybar.fei4.register object configuration_file : string, file Filename of the HDF5 configuration file or file object. ...
python
def _state_to_task(cls, tstate, shard_state, eta=None, countdown=None): """Generate task for slice according to current states. Args: tstate: An instance of TransientShardState. shard_state: An instance of ShardStat...
java
private void visit(ReturnValueRestrictionDescr descr) { ReturnValueRestriction restriction = new ReturnValueRestriction(pattern); restriction.setPatternIsNot(pattern.isPatternNot()); restriction.setFieldPath(field.getPath()); restriction.setOperator(Operator.determineOperator(descr.get...
java
public String replace(Map<String, String> varMap) { StringBuilder newString = new StringBuilder(); int p = 0; int p0 = 0; while (true) { p = templateText.indexOf("${", p); if (p == -1) { newString.append(templateText.substring(p0, templateText.len...
python
def model_changed(self, model): """ Determines if the bokeh model was just changed on the frontend. Useful to suppress boomeranging events, e.g. when the frontend just sent an update to the x_range this should not trigger an update on the backend. """ callbacks = ...
java
public static final PoliciesBean from(PolicyBean policy) { PoliciesBean rval = new PoliciesBean(); rval.setType(policy.getType()); rval.setOrganizationId(policy.getOrganizationId()); rval.setEntityId(policy.getEntityId()); rval.setEntityVersion(policy.getEntityVersion()); ...
python
def merge_conflicts(self): """The filenames of any files with merge conflicts (a list of strings).""" filenames = set() listing = self.context.capture('hg', 'resolve', '--list') for line in listing.splitlines(): tokens = line.split(None, 1) if len(tokens) == 2: ...
java
public <T, EXTYPE extends Exception> T writeLockedThrowing (@Nonnull final IThrowingSupplier <? extends T, EXTYPE> aCallable) throws EXTYPE { writeLock ().lock (); try { return aCallable.get (); } finally { writeLock ().unlock (); } }
java
private static Manifest standardSoyJarManifest() { Manifest mf = new Manifest(); mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); mf.getMainAttributes().put(new Attributes.Name("Created-By"), "soy"); return mf; }
python
def template(page=None, layout=None, **kwargs): """ Decorator to change the view template and layout. It works on both View class and view methods on class only $layout is applied, everything else will be passed to the kwargs Using as first argument, it will be the layout. :fi...
python
def _determine_beacon_config(self, current_beacon_config, key): ''' Process a beacon configuration to determine its interval ''' interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval
java
@Override public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) { return commerceAccountOrganizationRelPersistence.findWithDynamicQuery(dynamicQuery); }
python
def getdef(self, defname, tag='*'): """Return definition element with name *defname*""" if defname.startswith('a:'): defname = defname[2:] for xsd in self.__xsd_trees: xpath = "./%s[@name='%s']" % (tag, defname) elements = xsd.xpath(xpath) if eleme...
python
def plot_noncontiguous(ax, data, ind, color='black', label='', offset=0, linewidth=0.5, linestyle='-'): '''Plot non-contiguous slice of data Args ---- data: ndarray The data with non continguous regions to plot ind: ndarray indices of data to be plotted color: matplotlib...
java
public Collection<Epic> getOwnedEpics(EpicFilter filter) { filter = (filter != null) ? filter : new EpicFilter(); filter.owners.clear(); filter.owners.add(this); return getInstance().get().epics(filter); }
java
public QueryResult execute(long offset, long limit, boolean caseInsensitiveOrder) throws RepositoryException { if (log.isDebugEnabled()) { log.debug("Executing query: \n" + root.dump()); } setCaseInsensitiveOrder(caseInsensitiveOrder); // build lucene query Query ...
java
public HttpLogEntry withRequestHeader(String name, String value) { requestHeaders.add(new Header(name, value)); return this; }
java
public void comment(String comment) throws SAXException { flushPending(); // Ignore if a lexical handler has not been set if (m_lexHandler != null) { final int len = comment.length(); if (len > m_charsBuff.length) { m_charsBuff = ne...
python
def do_eof(self, line): """Exit on system EOF character.""" d1_cli.impl.util.print_info("") self.do_exit(line)
java
protected void validate(String operationType) throws Exception { super.validate(operationType); MPSString iscsi_iqn_validator = new MPSString(); iscsi_iqn_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128); iscsi_iqn_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1...
python
def get_suggestions(self, iteration_config=None): """Return a list of suggestions based on random search. Params: matrix: `dict` representing the {hyperparam: hyperparam matrix config}. n_suggestions: number of suggestions to make. """ matrix = self.hptuning_conf...
java
public synchronized Set<String> getGroupIds( String parentGroupId ) { Set<String> result = new TreeSet<String>(); if ( StringUtils.isEmpty( parentGroupId ) ) { for ( String groupId : contents.keySet() ) { int index = groupId.indexOf( '.' ); ...
python
def swap_pairs(line, starttag=position_tag): """Swap coordinate pairs Inputs line: gml line assumed to contain pairs of coordinates ordered as latitude, longitude starttag: tag marking the start of the coordinate pairs. """ endtag = starttag.replace('<', '</') index ...
java
@SuppressWarnings("unchecked") public <T> Promise<T> dispatch(final SerializedRequest request, final Class<T> resultType) { final Deferred<T> deferred = deferredFactory.getDeferred(); request.getAuth().auth(new PreparedRequestImpl(this, request, deferred, resultType, null)); return deferred....
python
def _check_workflows_align(config): """ Ensure that the common shared jobs in the `raiden-default` and `nightly` workflows are identical. """ jobs_default = config['workflows']['raiden-default']['jobs'] jobs_nightly = config['workflows']['nightly']['jobs'] if jobs_default == jobs_nightly[:...
python
def getargspec(func): """Variation of inspect.getargspec that works for more functions. This function works for Cythonized, non-cpdef functions, which expose argspec information but are not accepted by getargspec. It also works for Python 3 functions that use annotations, which are simply ignored. Howe...
java
@Override public void process(Node externs, Node root) { checkState(compiler.getLifeCycleStage().isNormalized()); if (!allowRemovalOfExternProperties) { referencedPropertyNames.addAll(compiler.getExternProperties()); } traverseAndRemoveUnusedReferences(root); // This pass may remove definiti...
python
def read(self, sync_map_format, input_file_path, parameters=None): """ Read sync map fragments from the given file in the specified format, and add them the current (this) sync map. Return ``True`` if the call succeeded, ``False`` if an error occurred. :param sync_map_f...
java
private void addVirtualEdges(IntObjectMap<VirtualEdgeIterator> node2EdgeMap, EdgeFilter filter, boolean base, int node, int virtNode) { VirtualEdgeIterator existingIter = node2EdgeMap.get(node); if (existingIter == null) { existingIter = new VirtualEdgeIterat...
java
private Range<RowKeyWrapper> rowRangeToRange(RowRange btRange) { final BoundType startBound; final ByteString startKey; switch (btRange.getStartKeyCase()) { case START_KEY_OPEN: startBound = BoundType.OPEN; startKey = btRange.getStartKeyOpen(); break; case START_KEY_CLOS...
python
def save_as_header(self, response, **kwargs): """ * if save_as is False the header will not be added * if save_as is a filename, it will be used in the header * if save_as is True or None the filename will be determined from the file path """ save_as = kwargs.ge...
python
def scoped(cls, optionable, removal_version=None, removal_hint=None): """Returns a dependency on this subsystem, scoped to `optionable`. :param removal_version: An optional deprecation version for this scoped Subsystem dependency. :param removal_hint: An optional hint to accompany a deprecation removal_ver...
python
def fit(self, X, y=None, **fit_params): """Fit base estimators. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- ...
java
public Content getConstantMembersHeader(ClassDoc cd) { //generate links backward only to public classes. Content classlink = (cd.isPublic() || cd.isProtected()) ? getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.CONSTANT_SUMMARY, cd)) : new StringCont...
python
def remove(self, cls, originalMemberNameList, memberName, classNamingConvention): """ :type cls: type :type originalMemberNameList: list(str) :type classNamingConvention: INamingConvention|None """ if memberName not in originalMemberNameList: delattr(cls, memberName)
java
protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ...
java
public ByteBuffer putInt (int value) { int newPosition = position + 4; //if (newPosition > limit) { //throw new BufferOverflowException(); //} putInt(position, value); position = newPosition; return this; }
python
def update(self, params): """Update the dev_info data from a dictionary. Only updates if it already exists in the device. """ dev_info = self.json_state.get('deviceInfo') dev_info.update({k: params[k] for k in params if dev_info.get(k)})
python
def _to_legacy_path(dict_path): """Convert a tuple of ints and strings in a legacy "Path". .. note: This assumes, but does not verify, that each entry in ``dict_path`` is valid (i.e. doesn't have more than one key out of "name" / "id"). :type dict_path: lsit :param dict_path: ...
java
public void getFieldData(FieldStuff fieldStuff, boolean bThin) { FieldData recFieldData = (FieldData)this.getRecord(FieldData.FIELD_DATA_FILE); Record recClassInfo2 = this.readFieldClass(); // Get the field and class this is based on if (recClassInfo2 == null) fieldStuff.str...
python
def remove_child(self, child_pid, reorder=False): """Remove a child from a PID concept.""" super(PIDNodeOrdered, self).remove_child(child_pid) child_relations = self._resolved_pid.child_relations.filter( PIDRelation.relation_type == self.relation_type.id).order_by( PI...
python
def _check_link_completion(self, link, fail_pending=False, fail_running=False): """Internal function to check the completion of all the dispatched jobs Returns ------- status_vect : `JobStatusVector` Vector that summarize the number of jobs in various states. """ ...
java
protected int[] getConstantKeySet(int input) { Operator<?> contract = getPactContract(); if (contract instanceof AbstractUdfOperator<?, ?>) { AbstractUdfOperator<?, ?> abstractPact = (AbstractUdfOperator<?, ?>) contract; int[] keyColumns = abstractPact.getKeyColumns(input); if (keyColumns != null) { if...
python
def drop_retention_policy(self, name, database=None): """Drop an existing retention policy for a database. :param name: the name of the retention policy to drop :type name: str :param database: the database for which the retention policy is dropped. Defaults to current clien...
java
public Observable<ServiceResponse<Void>> disableRecommendationForSubscriptionWithServiceResponseAsync(String name) { if (name == null) { throw new IllegalArgumentException("Parameter name is required and cannot be null."); } if (this.client.subscriptionId() == null) { thr...
python
def none(value, allow_empty = False, **kwargs): """Validate that ``value`` is :obj:`None <python:None>`. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty but **not** :obj:`None <python:None>`. If ``False`...
java
@SuppressWarnings("unused") private static final void dump(HttpClient client, HttpUriRequest req) { if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder("\n=== Request ==="); sb.append("\n").append(req.getRequestLine()); for (Header h : req.getAllHeaders()) { sb.append("\n...
java
public java.util.List<RoleDetail> getRoleDetailList() { if (roleDetailList == null) { roleDetailList = new com.amazonaws.internal.SdkInternalList<RoleDetail>(); } return roleDetailList; }
java
public static Date plusSeconds(Date date, int seconds) { return plus(date, seconds, DateTimeField.SECONDS); }
java
public int setupGridOrder() { int iErrorCode = DBConstants.NORMAL_RETURN; boolean bOrder = DBConstants.ASCENDING; int iKeyOrder = (int)((NumberField)this.getOwner()).getValue(); if (iKeyOrder == 0) return DBConstants.KEY_NOT_FOUND; if (iKeyOrder < 0) { ...
java
public static synchronized SocketFactory getDefault() { // Android-changed: Use security version instead of propertyChecked. if (defaultSocketFactory != null && lastVersion == Security.getVersion()) { return defaultSocketFactory; } lastVersion = Security.getVersion(); ...
java
public Class<? extends org.eclipse.xtext.IGrammarAccess> bindIGrammarAccess() { return org.eclipse.xtext.xtext.generator.parser.antlr.splitting.services.SimpleExpressionsGrammarAccess.class; }
python
def basic_stats(self): """Return a markdown representation of simple statistics.""" comment_score = sum(comment.score for comment in self.comments) if self.comments: comment_duration = (self.comments[-1].created_utc - self.comments[0].created_utc) ...
java
public synchronized boolean reloadConfigsIfNecessary() { long time = RaidNode.now(); if (time > lastReloadAttempt + reloadInterval) { lastReloadAttempt = time; try { File file = new File(configFileName); long lastModified = file.lastModified(); if (lastModified > lastSuccessf...
python
def create_or_update(model, *, defaults=None, save=True, **kwargs): """ Create or update a django model instance. :param model: :param defaults: :param kwargs: :return: object, created, updated """ obj, created = model._default_manager.get_or_create(defaults=defaults, **kwargs) up...
python
def event(self, utype, **kw): ''' Make a meta-event with a utype of @type. **@kw works the same as for pygame.event.Event(). ''' d = {'utype': utype} d.update(kw) pygame.event.post(pygame.event.Event(METAEVENT, d))
java
public void addParameter( String name, String value, boolean encoded ) { testFrozen(); super.addParameter( name, value, encoded ); }
java
public static void initClass() { // registers a factory for creating new instances of this widget CmsWidgetFactoryRegistry.instance().registerFactory(WIDGET_TYPE, new I_CmsFormWidgetFactory() { /** * @see org.opencms.gwt.client.ui.input.form.I_CmsFormWidgetFactory#createWidget...
java
public String getRedirectURL(FacesContext context, String viewId, Map<String,List<String>>parameters, boolean includeViewParams) { return getActionURL(context, viewId); }
python
def StartFlowAndWorker(client_id, flow_name, **kwargs): """Launches the flow and worker and waits for it to finish. Args: client_id: The client common name we issue the request. flow_name: The name of the flow to launch. **kwargs: passthrough to flow. Returns: A flow session id. Note: you...
python
def _import(self, datadict): """ Internal method to import instance variables data from a dictionary :param dict datadict: The dictionary containing variables values. """ self.GUID = datadict.get("GUID", uuid.uuid1()) self.FileName = datadict.get("FileName", "") ...
java
public static MimeMessage createMimeMessage(Session session, String from, String[] to, String subject, String content, DataSource[] attachments) { logger.debug("Creates a mime message with {} attachments", (attachments == null) ? 0 : attachments.length); try { MimeMessage message = new MimeMessage(session); ...
python
def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|arg...
python
def _parse_record_line(record_line): """ Extract fields from a record line string into a dictionary """ # Dictionary for record fields record_fields = {} # Read string fields from record line (record_fields['record_name'], record_fields['n_seg'], record_fields['n_sig'], record_fields[...
java
@Override public synchronized String lookup(String id) { if(this.properties == null) this.setUp(); String associated = this.properties.getProperty(id); if(associated == null) { associated = this.next(); //Est. new association register(id,associated); } return associated; }
java
public SymbolScope getEnclosingFunctionScope(Node n) { Node current = n.getParent(); if (n.isName() && current != null && current.isFunction()) { current = current.getParent(); } for (; current != null; current = current.getParent()) { SymbolScope scope = scopes.get(current); if (scop...
python
def find_by_index(self, cls, index_name, value): """Find records matching index query - defer to backend.""" return self.backend.find_by_index(cls, index_name, value)
java
public static String modifyURIPort(String uri, int newPort) { try { URI uriObj = new URI(uri); return uriToString(URLUtils.modifyURIPort(uriObj, newPort)); } catch (URISyntaxException e) { try { return (new NetworkInterfaceURI(uri)).modifyURIPo...
java
private String ifNull(){ if(params.length != 2){ throw new IllegalArgumentException("Wrong number of Parameters for if null expression"); } final String field1 = record.getValueByFieldName(params[0]); if (!field1.isEmpty()){ return field1; } fina...
java
public static void initializeCitrus(ApplicationContext applicationContext) { if (citrus != null) { if (!citrus.getApplicationContext().equals(applicationContext)) { log.warn("Citrus instance has already been initialized - creating new instance and shutting down current instance"); ...
python
def bar(self, subset=None, axis=0, color='#d65f5f', width=100, align='left', vmin=None, vmax=None): """ Draw bar chart in the cell backgrounds. Parameters ---------- subset : IndexSlice, optional A valid slice for `data` to limit the style application to....
python
def check(schema, data, trace=False): """Verify some json. Args: schema - the description of a general-case 'valid' json object. data - the json data to verify. Returns: bool: True if data matches the schema, False otherwise. Raises: TypeError: ...
python
def execute(self, style, xpoints, ypoints, mask=None, backend='vectorized', n_closest_points=None): """Calculates a kriged grid and the associated variance. This is now the method that performs the main kriging calculation. Note that currently measurements (i.e., z values) ...
python
def get_stream_action_type(stream_arn): """Returns the awacs Action for a stream type given an arn Args: stream_arn (str): The Arn of the stream. Returns: :class:`awacs.aws.Action`: The appropriate stream type awacs Action class Raises: ValueError: If the stream ty...
java
@Pure public Point3f getCenterWithoutProperties() { return new Point3f(this.cxProperty.doubleValue(), this.cyProperty.doubleValue(), this.czProperty.doubleValue()); }
java
public void addRemedyIndex(RemedyIndexEventData data) { String path = StagePathUtils.getRemedyRoot(data.getPipelineId()); try { zookeeper.create(path + "/" + RemedyIndexEventData.formatNodeName(data), new byte[] {}, CreateMode.PERSISTENT); } catch (ZkNode...
java
public static <T> Supplier<T> recover(Supplier<T> supplier, Function<Exception, T> exceptionHandler){ return () -> { try{ return supplier.get(); }catch (Exception exception){ return exceptionHandler.apply(exception); } }; }
java
private static <T extends HierarchyEntity<T, ?>> void loadChildren(T node, Set<T> children) { if (null == node.getChildren()) { return; } for (T one : node.getChildren()) { children.add(one); loadChildren(one, children); } }
java
private void btSearchInputDirActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btSearchInputDirActionPerformed {//GEN-HEADEREND:event_btSearchInputDirActionPerformed if (!"".equals(txtInputDir.getText())) { File f = new File(txtInputDir.getText()); if (f.exists() && (f.is...
python
def add_parser_options(options: Dict[str, Dict[str, Any]], parser_id: str, parser_options: Dict[str, Dict[str, Any]], overwrite: bool = False): """ Utility method to add options for a given parser, to the provided options structure :param options: :param parser_id: :param pars...
java
public static boolean isTrigonalBipyramidal(IAtom atomA, IAtom atomB, IAtom atomC, IAtom atomD, IAtom atomE, IAtom atomF) { Point3d pointA = atomA.getPoint3d(); Point3d pointB = atomB.getPoint3d(); Point3d pointC = atomC.getPoint3d(); Point3d pointD = atomD.getPoint3d(); ...
python
def _process_event_queue(self): """File event notification queue processor. """ try: event = self._event_queue.get(timeout=0.05) except queue.Empty: return try: subscription, is_initial_event, files = (event['subscription'], event['is_fre...
java
private final int[] robin(int numberOfChannels) { if (this.channels == null || this.channels.length != 1) { this.channels = new int[1]; } int nextChannel = nextChannelToSendTo + 1; nextChannel = nextChannel < numberOfChannels ? nextChannel : 0; this.nextChannelToSendTo = nextChannel; this.channels[...
java
public Observable<ServiceResponse<LanguageBatchResult>> detectLanguageWithServiceResponseAsync(DetectLanguageOptionalParameter detectLanguageOptionalParameter) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be...
python
def plot_data(self, proj, ax): """ Creates and plots the contourplot of the original data. This is done by evaluating the density of projected datapoints on a grid. """ x, y = proj x_data = self.ig.independent_data[x] y_data = self.ig.dependent_data[y] pro...
java
@Override public void close() throws IOException { if (encodingWriter != null) { encodingWriter.close(); } pgOutput.close(); pgInput.close(); connection.close(); }
python
def reset(self): """Resets the generator by stopping all processes""" self.alive.value = False qsize = 0 try: while True: self.queue.get(timeout=0.1) qsize += 1 except QEmptyExcept: pass print("Queue size on reset: {...
java
public synchronized Timestamp toTimestamp(Calendar cal, String s) throws SQLException { if (s == null) { return null; } int slen = s.length(); // convert postgres's infinity values to internal infinity magic value if (slen == 8 && s.equals("infinity")) { return new Timestamp(PGStatemen...
java
public void setLicense( final CharSequence license) { if ( license != null) format.getHeader().createEntry( LICENSE, license); }
java
@Override public FastSet union(IntSet other) { if (other == null || other.isEmpty() || this == other) { return clone(); } final FastSet o = convert(other); if (isEmpty()) { return o.clone(); } FastSet res = new FastSet(Math.max(firstEmptyWord, o.firstEmptyWord)); ...
python
def get_posts(self, offset=0, limit=1000, order=None, filters=None): """ This method returns list of Posts for this Data Source starting at a given offset and not more than limit It will call content-specific methods: _format() to format output from the DataStore """ order =...
java
public Results analyze(RuleSet ruleSet) { long startTime = System.currentTimeMillis(); DirectoryResults reportResults = new DirectoryResults(); int numThreads = Runtime.getRuntime().availableProcessors() - 1; numThreads = numThreads > 0 ? numThreads : 1; ExecutorService ...
python
def disconnect(self, signal=None, slot=None, transform=None, condition=None): """Removes connection(s) between this objects signal and connected slot(s) signal: the signal this class will emit, to cause the slot method to be called receiver: the object containing the slot method to be cal...
java
private boolean accepted(Columns columns, IndexExpression expression) { ByteBuffer expectedValue = expression.value; ColumnDefinition def = metadata.getColumnDefinition(expression.column); String name = def.name.toString(); Column column = columns.getColumn(name); if (column =...