language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void marshall(ListVPCEConfigurationsRequest listVPCEConfigurationsRequest, ProtocolMarshaller protocolMarshaller) { if (listVPCEConfigurationsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.m...
java
@Indexable(type = IndexableType.REINDEX) @Override public CPTaxCategory updateCPTaxCategory(CPTaxCategory cpTaxCategory) { return cpTaxCategoryPersistence.update(cpTaxCategory); }
python
def put_task(self, task): '''put task to task queue''' _schedule = task.get('schedule', self.default_schedule) self.projects[task['project']].task_queue.put( task['taskid'], priority=_schedule.get('priority', self.default_schedule['priority']), exetime=_schedu...
python
def complete(self, return_code): """ Mark the process as complete with provided return_code """ self.return_code = return_code self.status = 'COMPLETE' if not return_code else 'FAILED' self.end_time = datetime.datetime.now()
python
def guess_format( filename, ext, formats, io_table ): """ Guess the format of filename, candidates are in formats. """ ok = False for format in formats: output( 'guessing %s' % format ) try: ok = io_table[format].guess( filename ) except AttributeError: ...
java
protected void initHistoryClearObject() { Object o; if (CmsStringUtil.isEmpty(getParamAction())) { o = new CmsHistoryClear(); } else { // this is not the initial call, get the job object from session o = getDialogObject(); } if (!(o instance...
java
public DeletedSasDefinitionBundle getDeletedSasDefinition(String vaultBaseUrl, String storageAccountName, String sasDefinitionName) { return getDeletedSasDefinitionWithServiceResponseAsync(vaultBaseUrl, storageAccountName, sasDefinitionName).toBlocking().single().body(); }
java
public void marshall(DeleteRemediationConfigurationRequest deleteRemediationConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (deleteRemediationConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { ...
java
public static Optional<JMProgressiveManager<Path, Path>> movePathListAsync( List<Path> pathList, Path destinationDirPath, CopyOption... options) { return operateBulk(pathList, destinationDirPath, sourcePath -> JMPath.isDirectory(sourcePath) ? moveD...
java
@Override public InRequest newInRequest() { RequestHttp2 request = _freeRequest.allocate(); if (request == null) { request = new RequestHttp2(_httpProtocol); /* connTcp(), _httpContainer, this...
python
def gdalwarp(src, dst, options): """ a simple wrapper for :osgeo:func:`gdal.Warp` Parameters ---------- src: str, :osgeo:class:`ogr.DataSource` or :osgeo:class:`gdal.Dataset` the input data set dst: str the output data set options: dict additional parameters passed t...
python
def compute_cheby_coeff(f, m=30, N=None, *args, **kwargs): r""" Compute Chebyshev coefficients for a Filterbank. Parameters ---------- f : Filter Filterbank with at least 1 filter m : int Maximum order of Chebyshev coeff to compute (default = 30) N : int Grid...
java
public final GenerateIdTokenResponse generateIdToken( ServiceAccountName name, List<String> delegates, String audience, boolean includeEmail) { GenerateIdTokenRequest request = GenerateIdTokenRequest.newBuilder() .setName(name == null ? null : name.toString()) .addAllDelegates...
python
def merge_directories(self, directory_digests): """Merges any number of directories. :param directory_digests: Tuple of DirectoryDigests. :return: A Digest. """ result = self._native.lib.merge_directories( self._scheduler, self._to_value(_DirectoryDigests(directory_digests)), ) ...
java
public void writeTo (@Nonnull final byte [] aBuf) { ValueEnforcer.notNull (aBuf, "Buffer"); writeTo (aBuf, 0, aBuf.length, true); }
java
public static void closeQuietly(Socket socket) { if (socket != null) { try { socket.close(); } catch (AssertionError e) { if (!isAndroidGetsocknameError(e)) throw e; } catch (RuntimeException rethrown) { throw rethrown; } catch (Exception ignored) { } } }
java
public void releaseCall( String connId, KeyValueCollection reasons, KeyValueCollection extensions ) throws WorkspaceApiException { try { VoicecallsidanswerData releaseData = new VoicecallsidanswerData(); releaseData.setReasons(Util.toKVLis...
java
private void _serializeQuery(String name, Query query, StringBuilder sb, Set<Object> done) throws ConverterException { if (useWDDX) _serializeWDDXQuery(name, query, sb, done); else _serializeASQuery(name, query, sb, done); }
java
protected IStatus revalidate(int ignoreCauses) { try { setDirty(false); resolveDirtyFields(false); return getValidity(ignoreCauses); } catch (Throwable e) { if ((ignoreCauses & CODE_GENERAL) == 0) { return SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR, CODE_GENERAL, e); } return SA...
python
def construct_transformed_regex(annotations): """ construct a regex that matches possible fields in a transformed file annotations is a set of which keys in BARCODEINFO are present in the file """ re_string = '.*' if "cellular" in annotations: re_string += ":CELL_(?P<CB>.*)" if "mole...
java
@Override public FastStr toUpperCase(Locale locale) { String s = toString(); return unsafeOf(s.toUpperCase(locale)); }
python
def oldconfig(node): """ Prompts the user for a value if node.item is a visible symbol/choice with no user value. """ # See main() global conf_changed # Only symbols and choices can be configured if not isinstance(node.item, (Symbol, Choice)): return # Skip symbols and choi...
java
public void printHelp(int width, String cmdLineSyntax, String header, Options options, String footer, boolean autoUsage) { PrintWriter pw = new PrintWriter(System.out); printHelp(pw, width, cmdLineSyntax, header, options, getLeftPadding(), getDescPadding(), footer, autoUsa...
java
private void resolveWeakLinks(AvpRepresentation newAvp) { for (AvpRepresentation avp : avpMap.values()) { if (avp.isGrouped()) { if (avp.getName().equals(newAvp.getName())) { continue; } List<AvpRepresentation> avpChilds = avp.getChildren(); for (int n = 0; n <...
java
SimpleArticle readData(int properties, String name) { return getPerformedAction(new GetRevision(null, name, properties)).getArticle(); }
java
@SuppressWarnings("unchecked") static <P> LightMetaProperty<P> of( MetaBean metaBean, Field field, MethodHandles.Lookup lookup, String propertyName, int constructorIndex) { MethodHandle getter; try { getter = lookup.fin...
java
public final Job submitJob(String projectId, String region, Job job) { SubmitJobRequest request = SubmitJobRequest.newBuilder().setProjectId(projectId).setRegion(region).setJob(job).build(); return submitJob(request); }
java
@Deprecated @SuppressWarnings({ "rawtypes", "unchecked" }) public Map<String, PrimitiveAttribute<?>> getAttributes() { if (!isPrimitiveOnly()) { throw new UnsupportedOperationException("Primitive API not supported for nested association values"); } return (Map) attributes; }
python
def set_conf_set_value(self, set_name, param, value): '''Set a configuration set parameter value. @param set_name The name of the configuration set the destination parameter is in. @param param The name of the parameter to set. @param value The new value for the ...
java
public void eInit(EObject context, String name, IJvmTypeProvider typeContext) { setTypeResolutionContext(typeContext); this.context = context; this.parameter = this.jvmTypesFactory.createJvmTypeParameter(); this.parameter.setName(name); }
python
def set_all_name_components(self, name, weight, width, custom_name): """This function ensures that after being called, the master.name, master.weight, master.width, and master.customName match the given values. """ self.weight = weight or "Regular" self.width = width or "...
python
def validate_instance_password(self, password): ''' Validate instance passwords ''' # 1-16 alphanumeric characters - first character must be a letter - # cannot be a reserved MySQL word if re.match('[\w-]+$', password) is not None: if len(password) <= 41 and len(password) >= ...
python
def ugettext(self): """ Dispatch to the appropriate gettext method to handle text objects. Note that under python 3, this uses `gettext()`, while under python 2, it uses `ugettext()`. This should not be used with bytestrings. """ # pylint: disable=no-member if s...
python
def start_listener_thread(self, timeout_ms=30000, exception_handler=None): """ Start a listener thread to listen for events in the background. Args: timeout (int): How long to poll the Home Server for before retrying. exception_handler (func(exception)): Optional ...
java
@Path("/users") @Post @Public public void add(@Valid @LoginAvailable User user) { validator.onErrorUsePageOf(HomeController.class).login(); userDao.add(user); // you can add objects to result even in redirects. Added objects will // survive one more request when redirecting. result.include(...
python
def fit(self, data): """ Computes a [[PCAModel]] that contains the principal components of the input vectors. :param data: source vectors """ jmodel = callMLlibFunc("fitPCA", self.k, data) return PCAModel(jmodel)
java
public RESTImportTaskList uploadFile(Integer importJobId, File file, String sourceSrs) throws Exception { LOG.debug("Uploading file " + file.getName() + " to import job " + importJobId); Response httpResponse = HttpUtil.post( this.addEndPoint(importJobId + "/tasks"), file, ...
python
def evaluate_single_config( hparams, sampling_temp, max_num_noops, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the PPO agent in the real environment.""" tf.logging.info("Evaluating metric %s", get_metric_name( sampling_temp, max_num_noops, clipped=False )) eval_hparams = trainer_...
java
@NonNull public ListenerToken addChangeListener(Executor executor, @NonNull DatabaseChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("listener cannot be null."); } synchronized (lock) { mustBeOpen(); return addDatabaseChangeListener(execu...
python
def is_valid(self): """ Runs the SAM Translator to determine if the template provided is valid. This is similar to running a ChangeSet in CloudFormation for a SAM Template Raises ------- InvalidSamDocumentException If the template is not valid, an InvalidSam...
python
def stop(self): """ Stop the reader """ # print('stopping NonBlockingStreamReader..') # print('acquire..') NonBlockingStreamReader._stream_mtx.acquire() # print('acquire..ok') NonBlockingStreamReader._streams.remove(self._descriptor) if not NonBloc...
java
public String login(String token, Authentication authentication) { if (null == token) { return login(authentication); } tokens.put(token, new TokenContainer(authentication)); return token; }
python
def tokenize_sentences(self): """Apply sentence tokenization to this Text instance. Creates ``sentences`` layer. Automatically tokenizes paragraphs, if they are not already tokenized. Also, if word tokenization has already been performed, tries to fit the sentence tokenization ...
python
def get_offset(name): """ Return DateOffset object associated with rule name Examples -------- get_offset('EOM') --> BMonthEnd(1) """ if name not in libfreqs._dont_uppercase: name = name.upper() name = libfreqs._lite_rule_alias.get(name, name) name = libfreqs._lite_r...
python
def set_plain_text(self, text, is_code): """Set plain text docs""" # text is coming from utils.dochelpers.getdoc if type(text) is dict: name = text['name'] if name: rst_title = ''.join(['='*len(name), '\n', name, '\n', ...
java
public static Editor clear() { final Editor editor = getPreferences().edit().clear(); editor.apply(); return editor; }
java
public <T> NettyServerBuilder withChildOption(ChannelOption<T> option, T value) { this.channelOptions.put(option, value); return this; }
java
private void createDesignDocForAggregations() throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException { HttpResponse response = null; URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), Couch...
python
def DiffPrimitiveArrays(self, oldObj, newObj): """Diff two primitive arrays""" if len(oldObj) != len(newObj): __Log__.debug('DiffDoArrays: Array lengths do not match %d != %d' % (len(oldObj), len(newObj))) return False match = True if self._ignoreArrayOrder: ...
java
public Object initModelIF(EventModel em, ModelForm form, HttpServletRequest request) throws Exception { Object result = null; try { HandlerMetaDef hm = this.modelMapping.getHandlerMetaDef(); String serviceName = hm.getServiceRef(); Debug.logVerbose("[JdonFramework] construct the CRUD method for the se...
java
@Help(help = "create VNFCInstance. Aka SCALE OUT") public void createVNFCInstance( final String idNsr, final String idVnfr, final VNFComponent vnfComponent, ArrayList<String> vimInstanceNames) throws SDKException { String url = idNsr + "/vnfrecords/" + idVnfr + "/vdunits/vnfcinstance...
java
public boolean isAnnotated(ExecutableElement method) { List<? extends AnnotationMirror> annotationMirrors = method.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { String typeName = annotationMirror.getAnnotationType().toString(); if (!Annotat...
java
public static <T> T mode(Collection<T> values) { Set<T> modes = modes(values); return modes.iterator().next(); }
python
def validate_precision(self, value): """ Ensure that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. Override this method to disable the precision validation for input values or to enhance it in any way you need to...
python
def _extract_secrets_from_file(self, f, filename): """Extract secrets from a given file object. :type f: File object :type filename: string """ try: log.info("Checking file: %s", filename) for results, plugin in self._results_accumulator(filename)...
python
def zlib_processor(entity): # pragma: no cover, not used in the testing environment... """Read application/zlib data and put content into entity.params for later use. :param entity: cherrypy entity :type entity: cherrypy._cpreqbody.Entity :return: None """ if not entity.headers.get(ntou("Conte...
java
public static String getName(String filePath) { if (null == filePath) { return filePath; } int len = filePath.length(); if (0 == len) { return filePath; } if (CharUtil.isFileSeparator(filePath.charAt(len - 1))) { // 以分隔符结尾的去掉结尾分隔符 len--; } int begin = 0; char c; for (int ...
java
@Override public List<Calendar> getIMMDates(final Calendar start, final Calendar end, final IMMPeriod period) { final List<Calendar> dates = new ArrayList<>(); Calendar cal = (Calendar) start.clone(); while (true) { cal = getNextIMMDate(true, cal, period); if ...
java
public static void log(Throwable t) { Throwable top = t; if (t instanceof DebugException) { Throwable throwable = ((DebugException) t).getStatus().getException(); if (throwable != null) { top = throwable; } } log(new Status(IStatus.ERROR, PLUGIN_ID, INTERNAL_ERROR, "internalErrorLoggedFromVdm...
python
def _get_catalogue_bin_limits(catalogue, dmag): """ Returns the magnitude bins corresponing to the catalogue """ mag_bins = np.arange( float(np.floor(np.min(catalogue.data['magnitude']))) - dmag, float(np.ceil(np.max(catalogue.data['magnitude']))) + dmag, dmag) counter = np.h...
python
def __start(self): # pragma: no cover """Starts the real-time engine that captures events.""" assert not self._listener_thread self._listener_thread = threading.Thread(target=self.__run_listener, name='clearly-listener') self._listener_...
java
public static Integer getIntegerProperty(Properties properties, String key) { String property = getStringProperty(properties, key); if (property == null) { return null; } Integer value; try { value = Integer.parseInt(property); } catch (RuntimeExce...
java
public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) { return ordinalIndexOf(str, searchStr, ordinal, false); }
python
def process_table(fname): """Return processor by processing a given sheet of a spreadsheet file. Parameters ---------- fname : str The name of the Excel file (typically .xlsx extension) to process Returns ------- sp : indra.sources.sofia.processor.SofiaProcessor A SofiaProc...
java
static boolean isPossibleQualifiedName(@Nonnull String value, @Nonnull String extraAllowedCharacters) { // package-info violates the spec for Java Identifiers. // Nevertheless, expressions that end with this string are still legal. // See 7.4.1.1 of the Java language spec for discussion. ...
java
private LinkedHashMap<HypergraphNode<Variable>, Integer> orderingFromTentativeNewLocations(final LinkedHashMap<HypergraphNode<Variable>, Double> newLocations) { final LinkedHashMap<HypergraphNode<Variable>, Integer> ordering = new LinkedHashMap<>(); final List<Map.Entry<HypergraphNode<Variable>, Double>> list =...
java
public static void swap(byte[] byteArray1, int array1Index, byte[] byteArray2, int array2Index) { if(byteArray1[array1Index] != byteArray2[array2Index]) { byteArray1[array1Index] = (byte) (byteArray1[array1Index] ^ byteArray2[array2Index]); byteArray2[array2Index] = (byte) (byteArray1[ar...
java
protected static CmsRelationType getRelationType(String typeName) { for (CmsRelationType relType : CmsRelationType.getAll()) { if (relType.getName().equalsIgnoreCase(typeName)) { return relType; } } return null; }
python
def default_distdiff_options(updates=None): """ generate an options object with the appropriate default values in place for API usage of distdiff features. overrides is an optional dictionary which will be used to update fields on the options object. """ parser = create_optparser() opti...
python
def person_involved(self, person): """Return True if the given person has been involved in the discussion, False otherwise. """ return any(message.posted_by == person for message in self.discussion)
java
public static ExternalTableDefinition of( List<String> sourceUris, Schema schema, FormatOptions format) { return newBuilder(sourceUris, schema, format).build(); }
java
public Observable<ControllerInner> updateAsync(String resourceGroupName, String name, Map<String, String> tags) { return updateWithServiceResponseAsync(resourceGroupName, name, tags).map(new Func1<ServiceResponse<ControllerInner>, ControllerInner>() { @Override public ControllerInner cal...
python
def process_host_check_result(self, host, status_code, plugin_output): """Process host check result Format of the line that triggers function call:: PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output> :param host: host to process check to :type host: alignak.obj...
python
def get(self, logical_id, property): """ Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias :param logical_id: Logical Id of the resource :param property: Property of the resource you want to resolve. None if you want to get value of all prop...
java
public ChainedProperty<?> tail() { if (getChainCount() == 0) { throw new IllegalStateException(); } if (getChainCount() == 1) { if (!isOuterJoin(1)) { return get(mChain[0]); } else { return get(mChain[0], null, new boole...
python
def commit(self, partitions=None): """Commit stored offsets to Kafka via OffsetCommitRequest (v0) Keyword Arguments: partitions (list): list of partitions to commit, default is to commit all of them Returns: True on success, False on failure """ # s...
python
def solveConsAggMarkov(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,MrkvArray, PermGroFac,PermGroFacAgg,aXtraGrid,BoroCnstArt,Mgrid, AFunc,Rfunc,wFunc,DeprFac): ''' Solve one period of a consumption-saving problem with idiosyncratic and aggregate shocks (transit...
java
private IndexedContainer createContainer() throws IOException, CmsException { IndexedContainer container = null; if (m_bundleType.equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) { container = createContainerForDescriptorEditing(); } else { if (hasDescriptor()...
python
def _read_accept_states(self): """ Read DFA accepted states from flex compiled file Args: None Returns: list: The list of accepted states """ states = [] i = 0 regex = re.compile('[ \t\n\r:,]+') found = 0 # For maintaining ...
java
public RunbookInner update(String resourceGroupName, String automationAccountName, String runbookName, RunbookUpdateParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, parameters).toBlocking().single().body(); }
python
def InsertFloatArg(self, string='', **unused_kwargs): """Inserts a Float argument.""" try: float_value = float(string) except (TypeError, ValueError): raise errors.ParseError('{0:s} is not a valid float.'.format(string)) return self.InsertArg(float_value)
python
def _build_category_tree(slug, reference=None, items=None): """ Builds a recursive tree with category relations as children. """ if items is None: items = [] for key in reference: category = reference[key] if category["parent"] == slug: children = _build_catego...
python
def _from_dict(cls, _dict): """Initialize a Parties object from a json dictionary.""" args = {} if 'party' in _dict: args['party'] = _dict.get('party') if 'importance' in _dict: args['importance'] = _dict.get('importance') if 'role' in _dict: a...
python
def get_universe(self, as_str=False): """Returns universe the client is connected to. See ``Universe``. :param bool as_str: Return human-friendly universe name instead of an ID. :rtype: int|str """ result = self._iface.get_connected_universe() if as_str: ret...
python
def save(self): """ Create or update a playlist. """ d = self._to_dict() if len(d.get('videoIds', [])) > 0: if not self.id: self.id = self.connection.post('create_playlist', playlist=d) else: data = self.connection.post('upd...
java
@Override public boolean isDirectory() { final ArchivePath archivePath = ArchivePaths.create(path.toString()); Node node = archive.get(archivePath); return node.getAsset() == null; }
python
def _build_compatibility_members(binding, decorators=None): """Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can ...
java
public void stop() { try { Stopwatch watch = Stopwatch.createStarted(); stopAsync(); log.info("Awaiting PeerGroup shutdown ..."); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); log.info("... took {}", watch); } catch (InterruptedE...
python
def get_plugins(directory): """ returns the list of plugins from the specified directory :param directory: directory that contains the plugins. Files starting with _ will be ignored. """ # not just plugin_*.py plugins = [] files = glob.glob(directory + "/*.py") for p in files: p ...
java
private String layoutChars(boolean sci) { if (scale == 0) // zero scale is trivial return (intCompact != INFLATED) ? Long.toString(intCompact): intVal.toString(); if (scale == 2 && intCompact >= 0 && intCompact < Integer.MAX_V...
python
def left(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press left key n times **中文文档** 按左方向键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.left_key, n, interval) self.delay(post_dl)
python
def error_handler(self, error): """ Provides a flask error handler that is used for PraetorianErrors (and derived exceptions). """ warnings.warn( """ error_handler is deprecated. Use FlaskBuzz.build_error_handler instead """, ...
java
public FindingFilter withUserAttributes(Attribute... userAttributes) { if (this.userAttributes == null) { setUserAttributes(new java.util.ArrayList<Attribute>(userAttributes.length)); } for (Attribute ele : userAttributes) { this.userAttributes.add(ele); } ...
python
def update_selection(self): """ Convenience function update display (figures, text boxes and statistics windows) with a new selection of specimen """ self.clear_boxes() # commented out to allow propogation of higher level viewing state self.clear_high_level_pars(...
java
public final Link advance() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "advance"); Link replyLink = null; Link newLastLink = null; synchronized (_parent) { // We start our search from either the lastLink we found, or ...
python
def get_main_filename_attr(self): '''Returns the main filename attribute of the entry. As an entry can have multiple FILENAME attributes, this function allows to return the main one, i.e., the one with the lowest attribute id and the "biggest" namespace. ''' fn_attrs = s...
java
public DescribeTableResult describeTable(DescribeTableRequest describeTableRequest) throws AmazonServiceException, AmazonClientException { ExecutionContext executionContext = createExecutionContext(describeTableRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMet...
java
@SuppressWarnings("unchecked") @Override public EList<IfcRelAssignsToProduct> getReferencedBy() { return (EList<IfcRelAssignsToProduct>) eGet(Ifc4Package.Literals.IFC_TYPE_PRODUCT__REFERENCED_BY, true); }
python
def addPlugin(self, method="remote", **kwargs): """Add a plugin, support only for `.tar.gz` or `.zip` compression packages. :param method: `remote`, download and unpack a remote plugin package; `local`, unzip a local plugin package. :param url: str: for method is...
java
public static void processAllCounterProbeExtensions(Event event){ List<ProbeExtension> probeExtnList = RequestProbeService.getProbeExtensions(); for (int i = 0; i < probeExtnList.size(); i ++) { ProbeExtension probeExtension = probeExtnList.get(i); try{ //Check if this probe extension is interested in ...