language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def present(name, type, url, access=None, user=None, password=None, database=None, basic_auth=None, basic_auth_user=None, basic_auth_password=None, tls_auth=None, json_data=None, ...
java
public static <T> Iterator<T> drop(final Iterator<T> iterator, final int count) { if (iterator == null) throw new NullPointerException("iterator"); if (count == 0) return iterator; if (count < 0) throw new IllegalArgumentException("Cannot drop a negative number of elements. Argument 'count' was: " +...
java
private void resize(Object[] oldTable, int newSize) { int oldCapacity = oldTable.length; int end = oldCapacity - 1; Object last = arrayAt(oldTable, end); if (this.size() < ((end*3) >> 2) && last == RESIZE_SENTINEL) { return; } if (oldCapac...
python
def raw_clean(self, datas): """ Apply a cleaning on raw datas. """ datas = strip_tags(datas) # Remove HTML datas = STOP_WORDS.rebase(datas, '') # Remove STOP WORDS datas = PUNCTUATION.sub('', datas) # Remove punctuation datas = datas.lower() ...
python
def _safe_string(self, source, encoding='utf-8'): """Convert unicode to string as gnomekeyring barfs on unicode""" if not isinstance(source, str): return source.encode(encoding) return str(source)
python
def pause(name): ''' Pauses a container name Container name or ID **RETURN DATA** A dictionary will be returned, containing the following keys: - ``status`` - A dictionary showing the prior state of the container as well as the new state - ``result`` - A boolean noting whe...
python
def get_id(self, natural_key, date, enhancement=None): """ Returns the technical ID for a natural key at a date or None if the given natural key is not valid. :param T natural_key: The natural key. :param str date: The date in ISO 8601 (YYYY-MM-DD) format. :param T enhancement: ...
python
def get_next(cls, task, releasetype, typ, descriptor=None): """Returns a TaskFileInfo that with the next available version and the provided info :param task: the task of the taskfile :type task: :class:`jukeboxcore.djadapter.models.Task` :param releasetype: the releasetype :type...
python
def read_config_environment(self, config_data=None, quiet=False): """read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a uniqu...
java
@Trivial void initForRepeatingTask(boolean isFixedRate, long initialDelay, long interval) { this.initialDelay = initialDelay; this.interval = interval; this.isFixedRate = isFixedRate; }
python
def by_external_id_and_provider(cls, external_id, provider_name, db_session=None): """ Returns ExternalIdentity instance based on search params :param external_id: :param provider_name: :param db_session: :return: ExternalIdentity """ db_session = get_db_...
python
def getImemb(self): """Gather membrane currents from PtrVector into imVec (does not need a loop!)""" self.imembPtr.gather(self.imembVec) return self.imembVec.as_numpy()
python
def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
java
public void replaceStringChildren(List<String> strings, String parentId) { ArrayList<StringEntity> entities = new ArrayList<>(); for (String string : strings) { if (string != null) { StringEntity entity = new StringEntity(); entity.setParentId(parentId); entity.setValue(string); entities.add(enti...
java
@Override protected void checkIfHeartbeatSkipped(String name, EventChannelStruct eventChannelStruct) { // Check if heartbeat have been skipped, can happen if // 1- the notifd is dead (if not ZMQ) // 2- the server is dead // 3- The network was down; // 4- T...
python
def generate_regular_range(start, end, periods, freq): """ Generate a range of dates with the spans between dates described by the given `freq` DateOffset. Parameters ---------- start : Timestamp or None first point of produced date range end : Timestamp or None last point o...
java
public OutlierResult run(Relation<V> relation) { final DBIDs ids = relation.getDBIDs(); KNNQuery<V> knnQuery = QueryUtil.getKNNQuery(relation, getDistanceFunction(), k + 1); final int dim = RelationUtil.dimensionality(relation); if(k <= dim + 1) { LOG.warning("PCA is underspecified with a too low...
java
public void write(Object from, File target) throws IOException { OutputStream outputStream = new FileOutputStream(target); try { write(from, outputStream); } finally { outputStream.close(); } }
java
protected String generateCacheKey( CmsObject cms, String targetSiteRoot, String detailPagePart, String absoluteLink) { return cms.getRequestContext().getSiteRoot() + ":" + targetSiteRoot + ":" + detailPagePart + absoluteLink; }
java
public Observable<ServiceResponse<Page<DomainOwnershipIdentifierInner>>> listOwnershipIdentifiersNextWithServiceResponseAsync(final String nextPageLink) { return listOwnershipIdentifiersNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<DomainOwnershipIdentifierInner>>, Obse...
python
def interpretValue(value,*args,**kwargs): """Interprets a passed value. In this order: - If it's callable, call it with the parameters provided - If it's a tuple/list/dict and we have a single, non-kwarg parameter, look up that parameter within the tuple/list/dict - Else, just return it """ ...
java
public void putShortString(String value) { checkAvailable(value.length() + 1); Wire.putShortString(needle, value); }
python
def logging_file_install(path): """ Install logger that will write to file. If this function has already installed a handler, replace it. :param path: path to the log file, Use None for default file location. """ if path is None: path = configuration_get_default_folder() / LOGGING_DEFAULTNAM...
java
private List<String> resolveVariable(String filter, String text) { List<String> ret = new ArrayList<>(); Matcher m = PATTERN.matcher(text); while (m.find()) { ParsedStatement statement = ParsedStatement.fromMatcher(m); if (statement != null && statement.getVariable().startsWith(filter)) { ...
python
def calculate_size(name, permits): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES return data_size
java
public void setFrom(String from) { try { this.from = new EndpointReference(new URI(from)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid from uri", e); } }
java
protected String formatLogMessage(LogLevel level,Object[] message,Throwable throwable) { //get text String messageText=this.format(message); String throwableText=this.format(throwable); //init buffer StringBuilder buffer=new StringBuilder(); //append prefix ...
python
def conf_sets(self): '''The dictionary of configuration sets in this component, if any.''' with self._mutex: if not self._conf_sets: self._parse_configuration() return self._conf_sets
java
public void setupSFields() { this.getRecord(LogicFile.LOGIC_FILE_FILE).getField(LogicFile.SEQUENCE).setupDefaultView(this.getNextLocation(ScreenConstants.NEXT_LOGICAL, ScreenConstants.ANCHOR_DEFAULT), this, ScreenConstants.DEFAULT_DISPLAY); this.getRecord(LogicFile.LOGIC_FILE_FILE).getField(LogicFil...
java
public TableColumnVisibility convertTableColumnVisibility(final String tableIdentifier, final String json) { final String[] split = this.splitColumns(json); final List<String> visibleColumns = new ArrayList<>(); final List<String> invisibleColumns = new ArrayList<>(); for (String colum...
java
public static boolean contentEquals(File file1, File file2) throws IORuntimeException { boolean file1Exists = file1.exists(); if (file1Exists != file2.exists()) { return false; } if (false == file1Exists) { // 两个文件都不存在,返回true return true; } if (file1.isDirectory() || file2.isDirectory(...
java
public List<String> getVariables() { return this.templateChunks.stream() .filter(templateChunk -> Expression.class.isAssignableFrom(templateChunk.getClass())) .map(templateChunk -> ((Expression) templateChunk).getName()) .filter(Objects::nonNull) .collect(Collectors.toList()); }
java
@Transformer public static String capFirst(Object o) { if (null == o) return ""; String string = o.toString(); if (string.length() == 0) { return string; } return ("" + string.charAt(0)).toUpperCase() + string.substring(1); }
java
public void marshall(GetSegmentVersionsRequest getSegmentVersionsRequest, ProtocolMarshaller protocolMarshaller) { if (getSegmentVersionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getS...
java
@Override public List<StringSource> createSources(String sourceFileName) { return Util.list(new StringSource(sourceFileName, source)); }
java
public void addObject (int x, int y, Object object) { Record record = new Record(x, y, object); // if this is the very first element, we have to insert it // straight away because our binary search algorithm doesn't work // on empty arrays if (_size == 0) { _reco...
python
def display_information_message_bar( title=None, message=None, more_details=None, button_text=tr('Show details ...'), duration=8, iface_object=iface): """ Display an information message bar. :param iface_object: The QGIS IFace instance. Note that we cannot ...
java
public static DateTime toDateAdvanced(Object o, TimeZone timezone) throws PageException { if (o instanceof Date) { if (o instanceof DateTime) return (DateTime) o; return new DateTimeImpl((Date) o); } else if (o instanceof Castable) return ((Castable) o).castToDateTime(); else if (o instanceof String) { ...
python
def readfile(filename): """ returns the content of a file :param filename: the filename :return: """ with open(path_expand(filename), 'r') as f: content = f.read() return content
java
protected DataHash calculateMac() throws KSIException { try { HashAlgorithm algorithm = HashAlgorithm.getByName("DEFAULT"); algorithm.checkExpiration(); return new DataHash(algorithm, Util.calculateHMAC(getContent(), this.loginKey, algorithm.getName())); } catch (IOEx...
python
def insert_level(df, label, level=0, copy=0, axis=0, level_name=None): """Add a new level to the index with the specified label. The newly created index will be a MultiIndex. :param df: DataFrame :param label: label to insert :param copy: If True, copy the DataFrame before assigning new index ...
python
def unset_access_cookies(response): """ takes a flask response object, and configures it to unset (delete) the access token from the response cookies. if `jwt_csrf_in_cookies` (see :ref:`configuration options`) is `true`, this will also remove the access csrf double submit value from the response co...
python
def rename_sectors(self, sectors): """ Sets new names for the sectors Parameters ---------- sectors : list or dict In case of dict: {'old_name' : 'new_name'} with an entry for each old_name which should be renamed In case of list: List of new nam...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.FONT_DESCRIPTOR_SPECIFICATION__FT_WT_CLASS: setFtWtClass((Integer)newValue); return; case AfplibPackage.FONT_DESCRIPTOR_SPECIFICATION__FT_WD_CLASS: setFtWdClass((Integer)newValue); return; ca...
python
def inherit_docstring_from(cls): """ This decorator modifies the decorated function's docstring by replacing occurrences of '%(super)s' with the docstring of the method of the same name from the class `cls`. If the decorated method has no docstring, it is simply given the docstring of cls metho...
python
def DeleteInstance(r, instance, dry_run=False): """ Deletes an instance. @type instance: str @param instance: the instance to delete @rtype: int @return: job id """ return r.request("delete", "/2/instances/%s" % instance, query={"dry-run": dry_run})
python
def _memo(f): """Return a function like f but caching its results. Its arguments must be hashable.""" memos = {} def memoized(*args): try: return memos[args] except KeyError: result = memos[args] = f(*args) return result return memoized
python
def example(fn): '''Wrap the examples so they generate readable output''' @functools.wraps(fn) def wrapped(): try: sys.stdout.write('Running: %s\n' % fn.__name__) fn() sys.stdout.write('\n') except KeyboardInterrupt: sys.stdout.write('\nSkippi...
python
def receive(self): ''' Return the message received and the address. ''' try: msg, addr = self.skt.recvfrom(self.buffer_size) except socket.error as error: log.error('Received listener socket error: %s', error, exc_info=True) raise ListenerExcep...
java
public static void initEN16931 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL21NamespaceContext.getInstance ()); LocationBeautifierSPI.addMappings (CIID16BNamespaceContext.ge...
python
def format_data(data): """ Format bytes for printing :param data: Bytes :type data: None | bytearray | str :return: Printable version :rtype: unicode """ if data is None: return None return u":".join([u"{:02x}".format(ord(c)) for c in data])
python
def retrieve_records(self, timeperiod, include_running, include_processed, include_noop, include_failed, include_disabled): """ method looks for suitable UOW records and returns them as a dict""" resp = dict() try: query = unit_of_work_dao.QUERY_GET_FREERUN_S...
python
def cache_mappings(file_path): """ Make a full mapping for 2 --> 3 columns. Output the mapping to json in the specified file_path. Note: This file is currently called maps.py, full path is PmagPy/pmagpy/mapping/maps.py. Parameters ---------- file_path : string with full file path to dum...
java
public static String createIdentifier(EnhancedAnnotatedType<?> type, EjbDescriptor<?> descriptor) { StringBuilder builder = BeanIdentifiers.getPrefix(SessionBean.class); appendEjbNameAndClass(builder, descriptor); if (!type.isDiscovered()) { builder.append(BEAN_ID_SEPARATOR).append(t...
java
public NotificationChain basicSetPropertyParameters(PropertyParameters newPropertyParameters, NotificationChain msgs) { PropertyParameters oldPropertyParameters = propertyParameters; propertyParameters = newPropertyParameters; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImp...
python
def _walk_paths(self, base: pathlib.PurePath) \ -> Iterator[pathlib.PurePath]: """ Internal helper for walking paths. This is required to exclude the name of the root entity from the walk. :param base: The base path to prepend to the entity name. :return: An iterator...
java
public static String toSocketAddressString(String host, int port) { String portStr = String.valueOf(port); return newSocketAddressStringBuilder( host, portStr, !isValidIpV6Address(host)).append(':').append(portStr).toString(); }
java
public void putRequestBaggage(String key, String value) { if (BAGGAGE_ENABLE && key != null && value != null) { requestBaggage.put(key, value); } }
java
public int chooseShardForInsert(DocumentID key) { int hashCode = key.hashCode(); return hashCode >= 0 ? hashCode % numShards : (-hashCode) % numShards; }
java
@Override public void sortSpecification(String collateName, boolean isAscending) { // collationName is ignored for now PropertyPath<TypeDescriptor<TypeMetadata>> property = resolveAlias(propertyPath); checkAnalyzed(property, false); //todo [anistor] cannot sort on analyzed field? if (sor...
java
@SuppressWarnings("unchecked") @Override public String submitTopologyWithOpts(String topologyName, String uploadedJarLocation, String jsonConf, StormTopology topology, SubmitOptions options) throws TException { LOG.info("Received topology: " + topologyName + ", u...
python
def retrieve_object_query(self, view_kwargs, filter_field, filter_value): """Build query to retrieve object :param dict view_kwargs: kwargs from the resource view :params sqlalchemy_field filter_field: the field to filter on :params filter_value: the value to filter with :return...
python
def validate_email(self, email_address): ''' a method to validate an email address :param email_address: string with email address to validate :return: dictionary with validation fields in response_details['json'] ''' title = '%s.validate_email...
java
private static TypedArray obtainStyledAttributes(@NonNull final Context context, @StyleRes final int themeResourceId, @AttrRes final int resourceId) { Condition.INSTANCE.ensureNotNull(context, "The context ...
python
def _import_sub_module(module, name): """import_sub_module will mimic the function of importlib.import_module""" module = __import__(module.__name__ + "." + name) for level in name.split("."): module = getattr(module, level) return module
java
public static void setInputKeyCobolContext(Job job, Class<? extends CobolContext> cobolContext) { job.getConfiguration().setClass(CONF_INPUT_KEY_COBOL_CONTEXT, cobolContext, CobolContext.class); }
python
def to_dict(self): # type: () -> OrderedDict """Create a dictionary representation of object attributes Returns: OrderedDict serialised version of self """ d = OrderedDict() if self.typeid: d["typeid"] = self.typeid for k in self.call_ty...
python
def _generateForOAuthSecurity(self, client_id, secret_id, token_url=None): """ generates a token based on the OAuth security model """ grant_type="client_credentials" if token_url is None: token_url = "https://www.arcgis.com/sharing/rest/oauth2/token...
python
def send(self, data): """Send message to the server :param str data: message. """ if not self._ws_connection: raise RuntimeError('Web socket connection is closed.') self._ws_connection.write_message(json.dumps(data))
java
public LambdaDslObject minArrayLike(String name, Integer size, Consumer<LambdaDslObject> nestedObject) { final PactDslJsonBody minArrayLike = object.minArrayLike(name, size); final LambdaDslObject dslObject = new LambdaDslObject(minArrayLike); nestedObject.accept(dslObject); minArrayLike...
python
def get_context(template, line, num_lines=5, marker=None): ''' Returns debugging context around a line in a given string Returns:: string ''' template_lines = template.splitlines() num_template_lines = len(template_lines) # In test mode, a single line template would return a crazy line num...
python
def get_binary_path(executable, logging_level='INFO'): """Gets the software name and returns the path of the binary.""" if sys.platform == 'win32': if executable == 'start': return executable executable = executable + '.exe' if executable in os.listdir('.'): binar...
python
def bootstrap_fit( rv_cont, data, n_iter=10, quant=95, print_params=True, **kwargs ): """Bootstrap a distribution fit + get confidence intervals for the params. Parameters ========== rv_cont: scipy.stats.rv_continuous instance The distribution which to fit. data: array-like, 1d ...
python
def markdown(text, renderer=None, **options): """ Parses the provided Markdown-formatted text into valid HTML, and returns it as a :class:`flask.Markup` instance. :param text: Markdown-formatted text to be rendered into HTML :param renderer: A custom misaka renderer to be used instead of the defaul...
java
@SuppressWarnings("unchecked") public <R> ScoredValue<R> map(Function<? super V, ? extends R> mapper) { LettuceAssert.notNull(mapper, "Mapper function must not be null"); if (hasValue()) { return new ScoredValue<>(score, mapper.apply(getValue())); } return (ScoredValue...
java
public RemoteIterator<LocatedFileStatus> listFiles(Path f, boolean recursive) throws FileNotFoundException, IOException { try (Closeable context = new TimerContextWithLog(this.listFilesTimer.time(), "listFiles", f, recursive)) { return super.listFiles(f, recursive); } }
java
static Function<Optional<Descriptor>, String> fieldNumbersFunction( final String fmt, final Iterable<Integer> fieldNumbers) { return new Function<Optional<Descriptor>, String>() { @Override public String apply(Optional<Descriptor> optDescriptor) { return resolveFieldNumbers(optDescriptor, ...
python
def uninstall(pecls): ''' Uninstall one or several pecl extensions. pecls The pecl extensions to uninstall. CLI Example: .. code-block:: bash salt '*' pecl.uninstall fuse ''' if isinstance(pecls, six.string_types): pecls = [pecls] return _pecl('uninstall {0}'....
java
@Override void setScanResult(final ScanResult scanResult) { super.setScanResult(scanResult); if (typeArguments != null) { for (final TypeArgument typeArgument : typeArguments) { typeArgument.setScanResult(scanResult); } } if (suffixTypeArgument...
python
def lstsq(cls, a, b): """Return the least-squares solution to a linear matrix equation. :param Matrix a: Design matrix with the values of the independent variables. :param Matrix b: Matrix with the "dependent variable" values. b can only have one column. ...
java
public static int getMemoryInUse() { Runtime runtime = Runtime.getRuntime(); long mb = 1024 * 1024; long total = runtime.totalMemory(); long free = runtime.freeMemory(); return (int) ((total - free) / mb); }
python
def get_dashboard_version(self, id, version, **kwargs): # noqa: E501 """Get a specific version of a specific dashboard # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thre...
python
def get_season(self, season_key, card_type="micro_card"): """ Calling Season API. Arg: season_key: key of the season card_type: optional, default to micro_card. Accepted values are micro_card & summary_card Return: json data """ ...
java
public BigDecimal getBigDecimal( int index ) throws OdaException { BigDecimal value = (BigDecimal) getFieldValue(index); return value==null?new BigDecimal(0):value; }
python
def _save_new_defaults(self, defaults, new_version, subfolder): """Save new defaults""" new_defaults = DefaultsConfig(name='defaults-'+new_version, subfolder=subfolder) if not osp.isfile(new_defaults.filename()): new_defaults.set_defaults(de...
java
public void notReady() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "notReady"); updateLastNotReadyTime(); super.notReady(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "notReady"); }
java
@Override public ListJobExecutionsForThingResult listJobExecutionsForThing(ListJobExecutionsForThingRequest request) { request = beforeClientExecution(request); return executeListJobExecutionsForThing(request); }
python
def td_is_finished(tomodir): """Return the state of modeling and inversion for a given tomodir. The result does not take into account sensitivities or potentials, as optionally generated by CRMod. Parameters ---------- tomodir: string Directory to check Returns ------- crmo...
java
private Preference.OnPreferenceChangeListener createShowValueAsSummaryListener() { return new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { boolean showValueAsSummary = (Boolean...
python
def _py_code_variables(lines, executable, lparams, tab): """Adds the variable code lines for all the parameters in the executable. :arg lparams: a list of the local variable declarations made so far that need to be passed to the executable when it is called. """ allparams = executable.ordered_par...
java
public static Class<?> getComponentClass(final Object object) { if (object == null) { return null; } return object.getClass().getComponentType(); }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { traceroute_responses result = (traceroute_responses) service.get_payload_formatter().string_to_resource(traceroute_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == S...
java
private void processConsumerSetChangeCallback (CommsByteBuffer buffer, Conversation conversation) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processConsumerSetChangeCallback", new Object[]{buffer, conversation}); final ClientConversationState convState = (Client...
java
@Override public void process(HttpServerRequest vertxRequest, ContainerRequest jerseyRequest, Handler<Void> done) { jerseyRequest.setProperty(FIRST_BYTE_TIMER_CONTEXT, firstByteTimer.time()); jerseyRequest.setProperty(LAST_BYTE_TIMER_CONTEXT, lastByteTimer.time()); done.handle(null); }
java
public Map getQueryParams() { Map params = _codec.getExistingParams(); Map newParams = new HashMap(); addSortParams(newParams); addFilterParams(newParams); addPagerParams(newParams); params = mergeMaps(params, newParams); params = transformMap(params); ...
java
@RequestMapping("/web") public void webPay(@RequestParam("orderNumber") String orderNumber, HttpServletResponse resp){ WebPayDetail detail = new WebPayDetail(orderNumber, "测试订单-" + orderNumber, "0.01"); String form = alipayService.webPay(detail); logger.info("web pay form: {}", form); ...
python
def kill(self): """Sometime terminate() is not enough, we must "help" external modules to die... :return: None """ logger.info("Killing external module (pid=%d) for module %s...", self.process.pid, self.name) if os.name == 'nt': self.proc...
java
@Override public List<CommerceSubscriptionEntry> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def upload_file_sections(self, user_id, section_id, assignment_id): """ Upload a file. Upload a file to a submission. This API endpoint is the first step in uploading a file to a submission as a student. See the {file:file_uploads.html File Upload Documentation} ...
python
def load(self, urlpath, output=None, **kwargs): """ Downloads data from a given url, generates a hashed filename, logs metadata, and caches it locally. Parameters ---------- urlpath: str, location of data May be a local path, or remote path if including a pr...