language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public String remove(String content, String selector) { Element body = parseContent(content); List<Element> elements = body.select(selector); if (elements.size() > 0) { for (Element element : elements) { element.remove(); } return body.html(); } else { // nothing changed return conten...
python
def get_vlan_brief_output_last_vlan_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief output = ET.SubElement(get_vlan_brief, "output") last_vlan_id = ET.SubElement(out...
python
def is_absolute(self): """True if the path is absolute (has both a root and, if applicable, a drive).""" if not self._root: return False return not self._flavour.has_drv or bool(self._drv)
python
def _CheckAttribute(self, attribute, value): """Check that the value is of the expected type. Args: attribute: An instance of Attribute(). value: An instance of RDFValue. Raises: ValueError: when the value is not of the expected type. AttributeError: When the attribute is not o...
python
def load_py_config(conf_file): # type: (str) -> None """ Import configuration from a python file. This will just import the file into python. Sky is the limit. The file has to deal with the configuration all by itself (i.e. call conf.init()). You will also need to add your src directory to sys.path...
python
def correlation_matrix(nums_with_uncert): """ Calculate the correlation matrix of uncertain variables, oriented by the order of the inputs Parameters ---------- nums_with_uncert : array-like A list of variables that have an associated uncertainty Returns ------- cor...
java
static public void main(String ... args) throws Exception { FileInputStream fin = new FileInputStream(args[0]); XMLReader<Sample> reader = new XMLReader<Sample>(); for( Map<String,Object> map : reader.read(fin, Sample.class) ) { System.out.println("Next..."); for...
python
def write(self, filepath, skip_unknown=False): """Write the metadata fields to filepath.""" fp = codecs.open(filepath, 'w', encoding='utf-8') try: self.write_file(fp, skip_unknown) finally: fp.close()
python
def pfx_path(path): """ Prefix a path with the OS path separator if it is not already """ if path[0] != os.path.sep: return os.path.sep + path else: return path
python
def item(ctx, appid, title): """Market-related commands.""" ctx.obj['appid'] = appid ctx.obj['title'] = title
python
def customize_ruleset(self, custom_ruleset_file=None): """ Updates the ruleset to include a set of custom rules. These rules will be _added_ to the existing ruleset or replace the existing rule with the same ID. Args: custom_ruleset_file (optional): The filepath to ...
python
def get_about(self, element_to_query=None): """ Returns ElementTree containing the result of <host>/System/deviceInfo or if element_to_query is not None, the value of that element """ url = '%s/System/deviceInfo' % self._base _LOGGING.info('url: %s', url) ...
java
@SuppressWarnings("unused") @Internal @UsedByGeneratedCode protected final void addProperty(@Nonnull BeanProperty<T, Object> property) { ArgumentUtils.requireNonNull("property", property); beanProperties.put(property.getName(), property); }
java
public List<Element> findElements(String tag) { List<Element> result = new ArrayList<>(); LinkedList<Element> stack = new LinkedList<>(this.getChildren()); if (tag.equalsIgnoreCase(this.getMessageMLTag())) { result.add(this); } while (!stack.isEmpty()) { Element child = stack.pop(); ...
java
public List<StmtEphemeralTableScan> getEphemeralTableScans() { List<StmtEphemeralTableScan> scans = new ArrayList<>(); if (m_joinTree != null) { m_joinTree.extractEphemeralTableQueries(scans); } return scans; }
java
public void setPermissions(String userNameorApikey, EnumSet<Permissions> permissions) { assertNotEmpty(userNameorApikey, "userNameorApikey"); assertNotEmpty(permissions, "permissions"); final JsonArray jsonPermissions = new JsonArray(); for (Permissions s : permissions) { fin...
python
def buildURL(self, action, **query): """Build a URL relative to the server base_url, with the given query parameters added.""" base = urllib.parse.urljoin(self.server.base_url, action) return appendArgs(base, query)
java
public static java.sql.Time rollTime(java.util.Date startDate, int period, int amount) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(startDate); gc.add(period, amount); return new java.sql.Time(gc.getTime().getTime()); }
python
def list_to_csv_response(data, title='report', header=None, widths=None): """ Make 2D list into a csv response for download data. """ response = HttpResponse(content_type="text/csv; charset=UTF-8") cw = csv.writer(response) for row in chain([header] if header else [], data): cw.writerow([for...
java
public static String asTokenSeparatedValues(String token, Collection<String> strings) { StringBuilder newString = new StringBuilder(); boolean first = true; for(String str : strings) { if(! first) { newString.append(token); } first = false; ...
python
def add_func(self, func, *arg, **kwargs): """QADATASTRUCT的指标/函数apply入口 Arguments: func {[type]} -- [description] Returns: [type] -- [description] """ return self.groupby(level=1, sort=False).apply(func, *arg, **kwargs)
python
def clamp(n, lower, upper): """ Restricts the given number to a lower and upper bound (inclusive) :param n: input number :param lower: lower bound (inclusive) :param upper: upper bound (inclusive) :return: clamped number """ if lower > upper: lower, upper = upper, lower...
python
def delete(self, event): """Abort running task if it exists.""" super(CeleryReceiver, self).delete(event) AsyncResult(event.id).revoke(terminate=True)
python
def verify(self, signed): ''' Recover the message (digest) from the signature using the public key :param str signed: The signature created with the private key :rtype: str :return: The message (digest) recovered from the signature, or an empty string if the decrypti...
python
def _iter_loci(meta, clusters, s2p, filtered, n_cluster): """ Go through all locus and decide if they are part of the same TU or not. :param idx: int cluster id :param s2p: dict with [loci].coverage[start] = # of sequences there :param filtered: dict with clusters object :param n_cluster: i...
java
public synchronized void reset(short[] shortArray) throws IOException { _writer.flush(); _writer.position(DATA_START_POSITION); for(int i = 0; i < shortArray.length; i++) { _writer.writeShort(shortArray[i]); } _writer.flush(); }
java
public void finalizeConfig() { // See if not set by configuration, if there are defaults // in order from the Endpoint, Service, or Bus. configureConduitFromEndpointInfo(this, endpointInfo); logConfig(); if (getClient().getDecoupledEndpoint() != null) { this.endpoin...
python
def urltool(classqname, filt, reverse): """ Dump all urls branching from a class as OpenAPI 3 documentation The class must be given as a FQPN which points to a Klein() instance. Apply optional [FILT] as a regular expression searching within urls. For example, to match all urls beginning with api, ...
python
def create_conf_loader(*args, **kwargs): # pragma: no cover """Create a default configuration loader. .. deprecated:: 1.0.0b1 Use :func:`create_config_loader` instead. This function will be removed in version 1.0.1. """ import warnings warnings.warn( '"create_conf_loader" has...
java
public static void setDebugEnabled(ClassLoader classLoader, boolean isDebug) throws Exception { Class<?> greenPepperClass = classLoader.loadClass("com.greenpepper.GreenPepper"); Method setDebugEnabledMethod = greenPepperClass.getMethod("setDebugEnabled", boolean.class); setDebugE...
python
def get_advanced_params(): """ Get `Parameters` struct with parameters that most users do not want to think about. """ p = Parameters() # Internal format used during the registration process p.FixedInternalImagePixelType = "float" p.MovingInternalImagePixelType = "float" #...
python
def triple_exponential_moving_average(data, period): """ Triple Exponential Moving Average. Formula: TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA)) """ catch_errors.check_for_period_error(data, period) tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) + ema(em...
java
protected void initInterceptors() { interceptors = new ArrayList<>(); ControllerUtils.collectRouteInterceptors(controllerMethod).forEach(handlerClass -> { try { interceptors.add(handlerClass.newInstance()); } catch (InstantiationException | IllegalAccessException ...
java
@Override public CircuitBreaker circuitBreaker(String name, Supplier<CircuitBreakerConfig> circuitBreakerConfigSupplier) { return computeIfAbsent(name, () -> CircuitBreaker.of(name, Objects.requireNonNull(Objects.requireNonNull(circuitBreakerConfigSupplier, SUPPLIER_MUST_NOT_BE_NULL).get(), CONFIG_MUST_NOT_BE_NULL))...
python
def verify_response(self, response, otp, nonce, return_response=False): """ Returns True if the OTP is valid (status=OK) and return_response=False, otherwise (return_response = True) it returns the server response as a dictionary. Throws an exception if the OTP is replayed, the ...
java
public static DiffException createDiffException(final ErrorKeys errorId, final String message) { return new DiffException(errorId.toString() + ":\r\n" + message); }
java
public static String getCalendarJavaDateFormat(String dateFormat) { dateFormat = CmsStringUtil.substitute(dateFormat, "%", ""); // remove all "%" dateFormat = CmsStringUtil.substitute(dateFormat, "m", "${month}"); dateFormat = CmsStringUtil.substitute(dateFormat, "H", "${hour}"); dateFo...
java
public static void writeScriptFile( InputStream stream, String scriptString, Reader reader, LineEndingStyle style, File scriptfile ) throws IOException { try (FileWriter writer = new FileWriter(scriptfile)) { if (null != scriptStri...
python
def hex2bin(fin, fout, start=None, end=None, size=None, pad=None): """Hex-to-Bin convertor engine. @return 0 if all OK @param fin input hex file (filename or file-like object) @param fout output bin file (filename or file-like object) @param start start of address range (optional)...
python
def get_queryset(self): """ Returns a VersionedQuerySet capable of handling version time restrictions. :return: VersionedQuerySet """ qs = VersionedQuerySet(self.model, using=self._db) if hasattr(self, 'instance') and hasattr(self.instance, '_querytime'): ...
python
def create_marginalized_hist(ax, values, label, percentiles=None, color='k', fillcolor='gray', linecolor='navy', linestyle='-', title=True, expected_value=None, expected_color='red', rotated=False, ...
java
public BetaConstraints createBetaNodeConstraint(final BuildContext context, final List<BetaNodeFieldConstraint> list, final boolean disableIndexing) { BetaConstraints constraints; switch ( list.size()...
java
public String read() throws IOException { CurrentInProgressMetadataWritable cip = localWritable.get(); if (readAndUpdateVersion(cip)) { return cip.getPath(); } else { if (LOG.isDebugEnabled()) { LOG.debug(fullyQualifiedZNode + " is currently clear."); } } return null; }
java
public void putWithVersion(RowCursor cursor, Result<Boolean> cont) { _tableService.put(cursor, PutType.PUT, cont); }
java
public void updateArray(int i, java.sql.Array array) throws SQLException { try { rsetImpl.updateArray(i, array); } catch (SQLException ex) { FFDCFilter.processException(ex, "com.ibm.ws.rsadapter.jdbc.WSJdbcResultSet.updateArray", "3993", this); throw WSJdbcUtil.mapE...
python
def get_driver(self, name, version): """Authenticates and creates new API driver to perform scope stuff :param name: Name of driver :param version: Version of driver :return: driver """ user_credentials = self.get_user_credentials() # get credentials return disc...
java
public static byte[] encode(byte[] in) { return org.apache.commons.codec.binary.Base64.encodeBase64(in); }
java
public static IntegerVector subtract(IntegerVector vector1, IntegerVector vector2) { if (vector2.length() != vector1.length()) throw new IllegalArgumentException( "Vectors of different sizes cannot be added"); // If vector is a spa...
python
def zscan(self, name, cursor=0, match=None, count=None, score_cast_func=float): """ Incrementally return lists of elements in a sorted set. Also return a cursor indicating the scan position. ``match`` allows for filtering the members by pattern ``count`` allows fo...
python
def scan_url(self, this_url): """ Submit a URL to be scanned by VirusTotal. :param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the standard request rate) so as to perform a batch scanning request with one single call. The ...
python
def get_app_region_products(self, app_uri): """获得指定应用所在区域的产品信息 Args: - app_uri: 应用的完整标识 Returns: 返回产品信息列表,若失败则返回None """ apps, retInfo = self.list_apps() if apps is None: return None for app in apps: if (app.get('...
java
public static boolean is_chavarganta(String str) { String s1 = VarnaUtil.getAntyaVarna(str); if (is_chavarga(s1)) return true; return false; }
python
def relation_to_role_and_interface(relation_name): """ Given the name of a relation, return the role and the name of the interface that relation uses (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A tuple containing ``(role, interface)``, or ``(None, None)``. """ _me...
java
protected void setLength(long length) throws IOException { if(length<0) throw new IllegalArgumentException("Invalid length: "+length); synchronized(this) { file.seek(8); file.writeLong(length); if(length==0) setFirstIndex(0); } }
python
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None): ''' .. versionadded:: 2015.8.0 Show a storage container's acl CLI Example: .. code-block:: bash salt-cloud -f show_storage_container_acl my-azure name=myservice name: Name of existing container. l...
python
def vertex_enumeration_gen(g, qhull_options=None): """ Generator version of `vertex_enumeration`. Parameters ---------- g : NormalFormGame NormalFormGame instance with 2 players. qhull_options : str, optional(default=None) Options to pass to `scipy.spatial.ConvexHull`. See the ...
python
def gen_source(self, ast, name, customize, is_lambda=False, returnNone=False): """convert SyntaxTree to Python source code""" rn = self.return_none self.return_none = returnNone old_name = self.name self.name = name # if code would be empty, append 'pass' if len(...
python
def response_change(self, request, obj): """Determine the HttpResponse for the change_view stage.""" opts = self.opts.app_label, self.opts.model_name pk_value = obj._get_pk_val() if '_continue' in request.POST: msg = _( 'The %(name)s block was changed success...
java
private boolean recycle(Segment seg) { if(_recycleList.size() < _recycleLimit) { return _recycleList.add(seg); } return false; }
python
def Weber(mp, rhop, dp, rhog, D, Vterminal=4): r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_. If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2. .. math:: Fr_s = \left(7 + \frac{8}{3}V_{termin...
java
static ByteBufferRange decode(String string) { int prefix = string.indexOf(':'); int sep = string.indexOf('-', prefix + 1); checkArgument(prefix >= 0 && sep >= 0, "Invalid split string: %s", string); char[] start = new char[prefix + sep - (prefix + 1)]; string.getChars(0, prefix...
java
public static NodeImpl makeIterableAndSetMapKey(final NodeImpl node, final Object key) { return new NodeImpl( // node.name, // node.parent, // true, // null, // key, // node.kind, // node.parameterTypes, // node.parameterIndex, // node.value, /...
python
def mix(color1, color2, pos=0.5): """ Return the mix of two colors at a state of :pos: Retruns color1 * pos + color2 * (1 - pos) """ opp_pos = 1 - pos red = color1[0] * pos + color2[0] * opp_pos green = color1[1] * pos + color2[1] * opp_pos blue = color1[2] * pos + color2[2] * opp_pos ...
python
def parse_querystring(self, req, name, field): """Pull a querystring value from the request.""" return core.get_value(req.GET, name, field)
java
public static int compareQualifiers(final byte[] a, final int offset_a, final byte[] b, final int offset_b) { final long left = Internal.getOffsetFromQualifier(a, offset_a); final long right = Internal.getOffsetFromQualifier(b, offset_b); if (left == right) { return 0; } return (left < ...
python
def get_alter_table_sql(self, diff): """ Get the ALTER TABLE SQL statement :param diff: The table diff :type diff: eloquent.dbal.table_diff.TableDiff :rtype: list """ #sql = self._get_simple_alter_table_sql(diff) from_table = diff.from_table if ...
java
public void stopServer() { // _heartbeatState.notifyHeartbeatStop(); SocketPool pool = _clusterSocketPool.get(); if (pool != null) { pool.getFactory().notifyHeartbeatStop(); } }
python
def install(self): """Install packages from the packages_dict.""" self.distro = distro_check() package_list = self.packages_dict.get(self.distro) self._installer(package_list=package_list.get('packages'))
java
public void setPresence(Object newPresence, final Respoke.TaskCompletionListener completionListener) { if (isConnected()) { Object presenceToSet = newPresence; if (null == presenceToSet) { presenceToSet = "available"; } JSONObject typeData = new ...
java
void findNodes(List<RBBINode> dest, int kind) { if (fType == kind) { dest.add(this); } if (fLeftChild != null) { fLeftChild.findNodes(dest, kind); } if (fRightChild != null) { fRightChild.findNodes(dest, kind); } }
python
def wrap_viscm(cmap, dpi=100, saveplot=False): '''Evaluate goodness of colormap using perceptual deltas. :param cmap: Colormap instance. :param dpi=100: dpi for saved image. :param saveplot=False: Whether to save the plot or not. ''' from viscm import viscm viscm(cmap) fig = plt.gcf(...
python
def define_as_input(self, pin, pullup=False): """Set the input or output mode for a specified pin. Mode should be either GPIO.OUT or GPIO.IN. """ self._validate_channel(pin) # Set bit to 1 for input or 0 for output. self.iodir[int(pin/8)] |= 1 << (int(pin%8)) sel...
java
@Override public void update(ChannelData inputData) { this.handshakeErrorTracker = createSSLHandshakeErrorTracker(inputData); this.sslConfig.updateChannelData(inputData); }
java
public static Method getMethodByName(Class<?> clazz, boolean ignoreCase, String methodName) throws SecurityException { if (null == clazz || StrUtil.isBlank(methodName)) { return null; } final Method[] methods = getMethods(clazz); if (ArrayUtil.isNotEmpty(methods)) { for (Method method : methods) {...
java
public Matrix4x3d scale(double xyz, Matrix4x3d dest) { return scale(xyz, xyz, xyz, dest); }
java
public static void showAbout() { final CmsPopup popup = new CmsPopup(Messages.get().key(Messages.GUI_ABOUT_DIALOG_TITLE_0)); FlowPanel container = new FlowPanel(); int height = 450; if (Window.getClientHeight() < height) { height = Math.max(300, Window.getClientHeight() - 50...
java
public synchronized void setMaxCacheSizeInBytes(final int newsize) { if (validState) { log.info(this.getClass().getName() + "::setMaxCacheSizeInBytes newsize=" + newsize + " flushing write-cache"); privateSync(true, false); clearReadCaches(); } if (newsize >= 1024) { // 1KB minimal maxCacheSizeIn...
python
def _subst_libs(env, libs): """ Substitute environment variables and split into list. """ if SCons.Util.is_String(libs): libs = env.subst(libs) if SCons.Util.is_String(libs): libs = libs.split() elif SCons.Util.is_Sequence(libs): _libs = [] for l in libs: ...
python
def update(self): """Update hook """ super(AnalysisRequestAnalysesView, self).update() analyses = self.context.getAnalyses(full_objects=True) self.analyses = dict([(a.getServiceUID(), a) for a in analyses]) self.selected = self.analyses.keys()
java
protected boolean isLazy(final Class<?> type, final boolean lazy) { if (isHkExtension(type) && lazy) { logger.warn("@LazyBinding is ignored, because @HK2Managed set: {}", type.getName()); return false; } return lazy; }
python
def _return_pub_multi(self, rets, ret_cmd='_return', timeout=60, sync=True): ''' Return the data from the executed command to the master server ''' if not isinstance(rets, list): rets = [rets] jids = {} for ret in rets: jid = ret.get('jid', ret.get...
java
public static Recipient[] toRecipient(List<String> to) { Recipient[] addresses = new Recipient[to.size()]; int i = 0; for (String t : to) { addresses[i++] = new Recipient(t); } return addresses; }
python
def _format_preconditions(preconditions: List[List[icontract._Contract]], prefix: Optional[str] = None) -> List[str]: """ Format preconditions as reST. :param preconditions: preconditions of a function :param prefix: prefix of the ``:requires:`` and ``:requires else:`` directive :return: list of li...
python
def parse_ports(ports_text): """Parse ports text e.g. ports_text = "12345,13000-15000,20000-30000" """ ports_set = set() for bit in ports_text.split(','): if '-' in bit: low, high = bit.split('-', 1) ports_set = ports_set.union(range(int(low), int(high) + 1)) ...
java
private String cleanupExpressions(String drl) { // execute cleanup for ( final DSLMappingEntry entry : this.cleanup ) { drl = entry.getKeyPattern().matcher( drl ).replaceAll( entry.getValuePattern() ); } return drl; }
python
def compile_contracts(self, target_path: Path) -> ContractManager: """ Store compiled contracts JSON at `target_path`. """ self.checksum_contracts() if self.overall_checksum is None: raise ContractSourceManagerCompilationError('Checksumming failed.') contracts_compiled = se...
java
RuleReturnScope invoke(TreeParser treeParser) throws Exception { assert treeParser != null; return (RuleReturnScope)method.invoke(treeParser, arguments); }
python
def ambiguate(sequence1, sequence2, delete_ambiguous=False): """ delete_ambiguous: Marks sequences for deletion by replacing all chars with 'X'. These seqs are deleted later with remove_empty """ delete = False combination = list() z = list(zip(sequence1, sequence2)) for (a, b) in z: if ...
python
def process_associations(self, limit): """ Loop through the xml file and process the article-breed, article-phene, breed-phene, phene-gene associations, and the external links to LIDA. :param limit: :return: """ myfile = '/'.join((self.rawdir, self.files['data'...
python
def _set_packagebase(self, variant): self.setEnabled(variant is not None) self.variant = variant is_package = isinstance(variant, Package) prev_index = self.currentIndex() disabled_tabs = set() for d in self.tabs.itervalues(): index = d["index"] i...
python
def _get_url(self, url): """ Returns normalized url. If schema is not given, would fall to filesystem (``file:///``) schema. """ url = str(url) if url != 'default' and not '://' in url: url = ':///'.join(('file', url)) return url
java
public final ListDatasetsPagedResponse listDatasets(String parent, String filter) { PROJECT_PATH_TEMPLATE.validate(parent, "listDatasets"); ListDatasetsRequest request = ListDatasetsRequest.newBuilder().setParent(parent).setFilter(filter).build(); return listDatasets(request); }
java
public void setEventAggregates(java.util.Collection<EventAggregate> eventAggregates) { if (eventAggregates == null) { this.eventAggregates = null; return; } this.eventAggregates = new java.util.ArrayList<EventAggregate>(eventAggregates); }
java
public synchronized void add(@Nonnull String jobFullName, int n) throws IOException { addWithoutSaving(jobFullName, n); save(); }
python
def rollback(name, **kwargs): ''' Roll back the given dataset to a previous snapshot. name : string name of snapshot recursive : boolean destroy any snapshots and bookmarks more recent than the one specified. recursive_all : boolean destroy any more recent snapshots ...
python
def get_methods(self): """ Returns a list of `MethodClassAnalysis` objects """ for c in self.classes.values(): for m in c.get_methods(): yield m
python
def eeg_add_channel(raw, channel, sync_index_eeg=0, sync_index_channel=0, channel_type=None, channel_name=None): """ Add a channel to a mne's Raw m/eeg file. It will basically synchronize the channel to the eeg data following a particular index and add it. Parameters ---------- raw : mne.io.Raw ...
java
public Matrix4d translate(Vector3fc offset) { return translate(offset.x(), offset.y(), offset.z()); }
python
def global_variable_action(self, text, loc, var): """Code executed after recognising a global variable""" exshared.setpos(loc, text) if DEBUG > 0: print("GLOBAL_VAR:",var) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return index = self.sy...
python
def to_astropy(self, **kwargs): """ Creates a new AstroPy quantity with the same unit information. Example ------- >>> from unyt import g, cm >>> data = [3, 4, 5]*g/cm**3 >>> data.to_astropy() <Quantity [3., 4., 5.] g / cm3> """ return sel...