language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void setOpen(boolean open, boolean fireEvents) { if (m_open == open) { return; } m_open = open; executeOpen(fireEvents); CmsDomUtil.resizeAncestor(getParent()); }
python
def peekuntil(self, token, size=0): """ Peeks for token into the FIFO. Performs the same function as readuntil() without removing data from the FIFO. See readuntil() for further information. """ self.__append() i = self.buf.find(token, self.pos) if i < 0...
python
def split_page_artid(page_artid): """Split page_artid into page_start/end and artid.""" page_start = None page_end = None artid = None if not page_artid: return None, None, None # normalize unicode dashes page_artid = unidecode(six.text_type(page_artid)) if '-' in page_artid: ...
python
def monitor_resource_sync_state(resource, callback, exit_event=None): """Coroutine that monitors a KATCPResource's sync state. Calls callback(True/False) whenever the resource becomes synced or unsynced. Will always do an initial callback(False) call. Exits without calling callback() if exit_event is s...
python
def config(param_map, mastercode=DEFAULT_MASTERCODE): """Takes a dictionary of {Config.key: value} and returns a dictionary of processed keys and values to be used in the construction of a POST request to FlashAir's config.cgi""" pmap = {Config.mastercode: mastercode} pmap.update(param_map) proc...
python
def sigterm_handler(signum, stack_frame): """ Just tell the server to exit. WARNING: There are race conditions, for example with TimeoutSocket.accept. We don't care: the user can just rekill the process after like 1 sec. if the first kill did not work. """ # pylint: disable-msg=W0613 gl...
java
public Content getFieldDetails(Content fieldDetailsTree) { if (configuration.allowTag(HtmlTag.SECTION)) { HtmlTree htmlTree = HtmlTree.SECTION(getMemberTree(fieldDetailsTree)); return htmlTree; } return getMemberTree(fieldDetailsTree); }
java
public void marshall(GetUsagePlanKeyRequest getUsagePlanKeyRequest, ProtocolMarshaller protocolMarshaller) { if (getUsagePlanKeyRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getUsagePlanK...
java
public RabbitmqClient createRabbitmqClient() throws RabbitmqCommunicateException { List<RabbitmqClusterContext> contextList = this.reader.readConfiguration(); return createRabbitmqClient(contextList); }
java
public static void writeVector( String path, SimpleFeatureCollection featureCollection ) throws IOException { OmsVectorWriter writer = new OmsVectorWriter(); writer.file = path; writer.inVector = featureCollection; writer.process(); }
python
def print_dependencies(package_name): """Print the formatted information to standard out.""" info = get_sys_info() print("\nSystem Information") print("==================") print_info(info) info = get_pkg_info(package_name) print("\nPackage Versions") print("================") print...
python
def flatten_dict(root, parents=None, sep='.'): ''' Args: root (dict) : Nested dictionary (e.g., JSON object). parents (list) : List of ancestor keys. Returns ------- list List of ``(key, value)`` tuples, where ``key`` corresponds to the ancestor keys of the respecti...
java
public static void migrate(Connection connection, String... tables) throws SQLException { new PKMigrate(connection, tables).migrate(); }
python
def setScales(self,scales=None,term_num=None): """ get random initialization of variances based on the empirical trait variance Args: scales: if scales==None: set them randomly, else: set scales to term_num (if term_num==None: set to all terms) ...
java
public static final Object deserialize(byte[] bytes) throws Exception { if (bytes == null || bytes.length < 4) { return new LinkedHashMap<>(); } // Try to deserialize content as Object (type-safe serialization) if (bytes[0] == 1) { try { ByteArrayInputStream bais = new ByteArrayInputStream(by...
java
public void setRawParameters(Hashtable params) { if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){ checkRequestObjectInUse(); } //321485 if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_N...
java
public List<Subscription> matches(String topic) { List<Token> tokens; try { tokens = splitTopic(topic); } catch (ParseException ex) { //TODO handle the parse exception Log.error(null, ex); return Collections.EMPTY_LIST; } Queue<Tok...
python
def do_status(self, service): """ List all services on the cluster Usage: > status """ if service: self.do_show("services", single=service) else: self.do_show("services")
java
public <G, ERR> OrFuture<G, ERR> firstCompletedOf(Iterable<? extends OrFuture<? extends G, ? extends ERR>> input) { OrPromise<G, ERR> promise = promise(); input.forEach(future -> future.onComplete(promise::tryComplete)); return promise.future(); }
java
private void findParamDescMethods() { for (Method method : m_commandClass.getMethods()) { if (method.isAnnotationPresent(ParamDescription.class)) { try { RESTParameter cmdParam = (RESTParameter) method.invoke(null, (Object[])null); addParameter...
java
@Override public void usageDetail( final char commandPrefix, final ICmdLineArg<?> arg, final int _indentLevel) { nameIt(commandPrefix, arg); final String help = ((AbstractCLA<?>) arg).getHelp(); if (help != null && help.trim().length() > 0) { ...
java
private void createProxyListener() throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createProxyListener"); // Create the proxy listener instance _proxyListener = new NeighbourProxyListener(_neighbours, this); /* * Now we can cr...
python
def get_d1str(self, goobj, reverse=False): """Get D1-string representing all parent terms which are depth-01 GO terms.""" return "".join(sorted(self.get_parents_letters(goobj), reverse=reverse))
python
def unzip(zip_file, dest, excludes=None, options=None, template=None, runas=None, trim_output=False, password=None, extract_perms=True): ''' Uses the ``zipfile`` Python module to unpack zip files .. versionchanged:: 2015.5.0 ...
python
def download(self, media_id, as_stream=False): """ Скачивает указанный файл :param media_id: string :rtype: requests.Response """ response = self.__app.native_api_call('media', 'd/' + media_id, {}, self.__options, False, None, as_stream, http_path="/api/meta/v1/", http_me...
python
def classify_import(module_name, application_directories=('.',)): """Classifies an import by its package. Returns a value in ImportType.__all__ :param text module_name: The dotted notation of a module :param tuple application_directories: tuple of paths which are considered application roots. ...
java
public static int sort( LongArray array, long numRecords, int startByteIndex, int endByteIndex, boolean desc, boolean signed) { assert startByteIndex >= 0 : "startByteIndex (" + startByteIndex + ") should >= 0"; assert endByteIndex <= 7 : "endByteIndex (" + endByteIndex + ") should <= 7"; assert...
python
def makeSingleBandWKBRaster(cls, session, width, height, upperLeftX, upperLeftY, cellSizeX, cellSizeY, skewX, skewY, srid, dataArray, initialValue=None, noDataValue=None): """ Generate Well Known Binary via SQL. Must be used on a PostGIS database as it relies on several PostGIS database function...
java
public HttpRequest withBody(byte[] content) { headers.set("Content-Length", String.valueOf(content.length)); // Unpooled.wrappedBuffer(body) allocates ByteBuf from unpooled heap return withBody(Flux.defer(() -> Flux.just(Unpooled.wrappedBuffer(content)))); }
python
def normalize(self, text): """Run the Normalizer on a string. :param text: The string to normalize. """ # Normalize to canonical unicode (using NFKC by default) if self.form is not None: text = unicodedata.normalize(self.form, text) # Strip out any control c...
java
public static double pdf(double val, int v) { // TODO: improve precision by computing "exp" last? return FastMath.exp(GammaDistribution.logGamma((v + 1) * .5) - GammaDistribution.logGamma(v * .5)) // * (1 / FastMath.sqrt(v * Math.PI)) * FastMath.pow(1 + (val * val) / v, -((v + 1) * .5)); }
python
def buffer_close(self, buf, redraw=True): """ closes given :class:`~alot.buffers.Buffer`. This it removes it from the bufferlist and calls its cleanup() method. """ # call pre_buffer_close hook prehook = settings.get_hook('pre_buffer_close') if prehook is not No...
java
@Deprecated public void request(Bundle parameters, RequestListener listener, final Object state) { request(null, parameters, "GET", listener, state); }
python
def parse(self, xml_data): """ Parse XML data """ # parse tree if isinstance(xml_data, string_types): # Presumably, this is textual xml data. try: root = ET.fromstring(xml_data) except StdlibParseError as e: raise ParseError(st...
java
public String ingest(Context context, InputStream serialization, String logMessage, String format, String encoding, String pid) throws ServerException { return worker.ingest(context, ...
python
def _what_default(self, pronunciation): """Provide the default prediction of the what task. This function is used to predict the probability of a given pronunciation being reported for a given token. :param pronunciation: The list or array of confusion probabilities at each index """ ...
java
public final void setShadowElevation(final int elevation) { Condition.INSTANCE.ensureAtLeast(elevation, 0, "The elevation must be at least 0"); Condition.INSTANCE.ensureAtMaximum(elevation, ElevationUtil.MAX_ELEVATION, "The elevation must be at maximum " + ElevationUtil.MAX_ELEVATION); ...
java
protected byte[] spoolInternalValue() { try { return value.getString().getBytes(Constants.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException("FATAL ERROR Charset " + Constants.DEFAULT_ENCODING + " is not supported!"); } }
java
public static Menu get(final String _name) throws CacheReloadException { return AbstractUserInterfaceObject.<Menu>get(_name, Menu.class, CIAdminUserInterface.Menu.getType()); }
java
public void setLastSegment(boolean v) { if (SourceDocumentInformation_Type.featOkTst && ((SourceDocumentInformation_Type)jcasType).casFeat_lastSegment == null) jcasType.jcas.throwFeatMissing("lastSegment", "org.apache.uima.examples.SourceDocumentInformation"); jcasType.ll_cas.ll_setBooleanValue(addr, ((So...
python
def clean_url(url): """ Normalize the url and clean it >>> clean_url("http://www.assemblee-nationale.fr/15/dossiers/le_nouveau_dossier.asp#deuxieme_partie") 'http://www.assemblee-nationale.fr/dyn/15/dossiers/deuxieme_partie' >>> clean_url("http://www.conseil-constitutionnel.fr/conseil-constitutionn...
python
def to_pickle(self, path, compression='infer', protocol=pickle.HIGHEST_PROTOCOL): """ Pickle (serialize) object to file. Parameters ---------- path : str File path where the pickled object will be stored. compression : {'infer', 'gzip', 'bz2...
java
public boolean isTimeIncluded (final long timeStamp) { if (timeStamp <= 0) { throw new IllegalArgumentException ("timeStamp must be greater 0"); } if (m_aBaseCalendar != null) { if (m_aBaseCalendar.isTimeIncluded (timeStamp) == false) { return false; } } ...
java
final void writeLong(long value) { byte writeBuffer[] = new byte[8]; writeBuffer[0] = (byte) (value >>> 56); writeBuffer[1] = (byte) (value >>> 48); writeBuffer[2] = (byte) (value >>> 40); writeBuffer[3] = (byte) (value >>> 32); writeBuffer[4] = (byte) (value >>> 24);...
python
def bin_executables(self): """A normalized map of bin executable names and local path to an executable :rtype: dict """ if isinstance(self.payload.bin_executables, string_types): # In this case, the package_name is the bin name return { self.package_name: self.payload.bin_executables } ...
python
def normalize_datum(self, datum): """ Convert `datum` into something that umsgpack likes. :param datum: something that we want to process with umsgpack :return: a packable version of `datum` :raises TypeError: if `datum` cannot be packed This message is called by :meth:...
python
def get_search_fields(self): """Return list of lookup names.""" if self.search_fields: return self.search_fields raise NotImplementedError('%s, must implement "search_fields".' % self.__class__.__name__)
python
def filter_belief(): """Filter to beliefs above a given threshold.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') belief_cutoff = body.get('belief_cutoff') if belief_cutoff is...
python
def first_or_new(self, _attributes=None, **attributes): """ Get the first related model record matching the attributes or instantiate it. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attributes is not None: attribut...
java
public void setProductConstraints(com.google.api.ads.admanager.axis.v201805.ProposalLineItemConstraints productConstraints) { this.productConstraints = productConstraints; }
python
def remove_shard(self, shard, drop_buffered_records=False): """Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is active or a root, it is removed and any children promoted to those roles. :param shard: The shard to remove :type shard: :cla...
java
@Override public String getOperationReplyValueTypeDescription(String operationName, Locale locale, ResourceBundle bundle, String... suffixes) { try { return bundle.getString(getVariableBundleKey(new String[]{operationName, REPLY}, suffixes)); } catch (MissingResourceException e) { ...
python
def stack(frame, level=-1, dropna=True): """ Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series """ def factorize(index): if index.is_unique: return index, np.arange...
python
def visible(self): """ Return the comments that are visible based on the ``COMMENTS_XXX_VISIBLE`` settings. When these settings are set to ``True``, the relevant comments are returned that shouldn't be shown, and are given placeholders in the template ``generic/includes/c...
java
protected final CnvIbnDateToCv createPutCnvIbnDateToCv() throws Exception { CnvIbnDateToCv convrt = new CnvIbnDateToCv(); this.convertersMap .put(CnvIbnDateToCv.class.getSimpleName(), convrt); return convrt; }
python
def find_matlab_version(process_path): """ Tries to guess matlab's version according to its process path. If we couldn't gues the version, None is returned. """ bin_path = os.path.dirname(process_path) matlab_path = os.path.dirname(bin_path) matlab_dir_name = os.path.basename(matlab_path) v...
java
public boolean areRepairLogsComplete() { for (Entry<Long, ReplicaRepairStruct> entry : m_replicaRepairStructs.entrySet()) { if (!entry.getValue().logsComplete()) { return false; } } return true; }
java
private boolean isAcceptableCandidate(int targetLength, ViterbiNode glueBase, ViterbiNode candidate) { return (glueBase == null || candidate.getSurface().length() < glueBase.getSurface().length()) && candidate.getSurface().length() >= targetLength; }
python
def load(mod, persist=False): ''' Load the specified kernel module mod Name of module to add persist Write module to /etc/modules to make it load on system reboot CLI Example: .. code-block:: bash salt '*' kmod.load kvm ''' pre_mods = lsmod() res = __salt...
java
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) { inactivityTimer.onActivity(); lastResult = rawResult; ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult); boolean fromLiveScan = barcode != null; if (fromLiveScan) { historyManag...
java
protected void setResultType(MappedStatement ms, Class<?> entityClass) { EntityTable entityTable = EntityHelper.getEntityTable(entityClass); List<ResultMap> resultMaps = new ArrayList<ResultMap>(); resultMaps.add(entityTable.getResultMap(ms.getConfiguration())); MetaObject metaObject = M...
java
private State handleResetChunk(CellChunk cellChunk) { validate(cellChunk.getRowKey().isEmpty(), "Reset chunks can't have row keys"); validate(!cellChunk.hasFamilyName(), "Reset chunks can't have families"); validate(!cellChunk.hasQualifier(), "Reset chunks can't have qualifiers"); validate(cellChunk.get...
python
def merge_partition(self, partition, path, value): """ Merge a value into a partition for a key path. """ dct = self.partitions[partition] *heads, tail = path for part in heads: dct = dct.setdefault(part, dict()) dct[tail] = value
python
def add_comment(self, comment, metadata=""): """ Add a canned comment :type comment: str :param comment: New canned comment :type metadata: str :param metadata: Optional metadata :rtype: dict :return: A dictionnary containing canned comment description ...
python
def parse_value(self, stream): """ Value ::= (SimpleValue | Set | Sequence) WSC UnitsExpression? """ if self.has_sequence(stream): value = self.parse_sequence(stream) elif self.has_set(stream): value = self.parse_set(stream) else: value...
python
def debug(func): """ Decorator that prints a message whenever a function is entered or left. """ @wraps(func) def wrapped(*args, **kwargs): arg = repr(args) + ' ' + repr(kwargs) sys.stdout.write('Entering ' + func.__name__ + arg + '\n') try: result = func(*args, *...
python
def ld_prune(df, ld_beds, snvs=None): """ Prune set of GWAS based on LD and significance. A graph of all SNVs is constructed with edges for LD >= 0.8 and the most significant SNV per connected component is kept. Parameters ---------- df : pandas.DataFrame Pandas dataframe with ...
java
public final BuilderType setHeaderIconTintMode(@NonNull final PorterDuff.Mode mode) { getProduct().setHeaderIconTintMode(mode); return self(); }
python
def _GetExtractionErrorsAsWarnings(self): """Retrieves errors from from the store, and converts them to warnings. This method is for backwards compatibility with pre-20190309 storage format stores which used ExtractionError attribute containers. Yields: ExtractionWarning: extraction warnings. ...
python
def run(self): """ Esegue il montaggio delle varie condivisioni chiedendo all'utente username e password di dominio. """ logging.info('start run with "{}" at {}'.format( self.username, datetime.datetime.now())) progress = Progress(text="Controllo requisiti sof...
java
private static TriFunction<AnyBiPredicate, MetricValue, MetricValue, Optional<Boolean>> select_(SelType x, SelType y) { switch (x) { case BOOLEAN: switch (y) { case BOOLEAN: { TriFunction<AnyBiPredicate, Boolean, Boolean...
java
@Nullable public synchronized V remove(K key) { V oldValue = mMap.remove(key); mSizeInBytes -= getValueSizeInBytes(oldValue); return oldValue; }
python
def number_aware_alphabetical_cmp(str1, str2): """ cmp function for sorting a list of strings by alphabetical order, but with numbers sorted numerically. i.e., foo1, foo2, foo10, foo11 instead of foo1, foo10 """ def flatten_tokens(tokens): l = [] for token in tokens...
python
def _get_parent_classes_transparent(cls, slot, page, instance=None): """ Return all parent classes including those marked as "transparent". """ parent_classes = super(CascadePluginBase, cls).get_parent_classes(slot, page, instance) if parent_classes is None: if cls.ge...
python
def _cl_int_plot_top_losses(self, k, largest=True, figsize=(12,12), heatmap:bool=True, heatmap_thresh:int=16, return_fig:bool=None)->Optional[plt.Figure]: "Show images in `top_losses` along with their prediction, actual, loss, and probability of actual class." tl_val,tl_idx = self.to...
python
def bootstrap_salt(name, config=None, approve_key=True, install=True, pub_key=None, priv_key=None, bootstrap_url=None, force_install=False, unconditional_install=False,...
python
def decompress(self, value): """ Retreieve each field value or provide the initial values """ if value: return [value.get(field.name, None) for field in self.fields] return [field.field.initial for field in self.fields]
java
@Override public void addCodeBase(ICodeBaseLocator locator, boolean isApplication) { addToWorkList(projectWorkList, new WorkListItem(locator, isApplication, ICodeBase.Discovered.SPECIFIED)); }
java
private void updateBindings(Map<String, Object> props) { // Process the user element processProps(props, CFG_KEY_USER, users); // Process the user-access-id element processProps(props, CFG_KEY_USER_ACCESSID, users); // Process the group element processProps(props, CFG_KE...
java
public static <E extends Enum<? extends Style.HasCssName>> E fromStyleName(final String styleName, final Class<E> enumClass, final E defaultValue) { retur...
java
public static byte schemaToColumnType(String s) { switch (s.toLowerCase()) { case "boolean": case "smallint": case "tinyint": case "bigint": // FIXME: make sure this is fixed by Tomas. case "int": case "float": case "double": ...
python
def __type2js(cls, value): """ :Description: Convert python value to executable javascript value by type. :param value: Value to transform. :type value: None, bool, int, float, string :return: string """ if value is None: return 'null' elif isi...
python
def pub_connect(self): ''' Create and connect this thread's zmq socket. If a publisher socket already exists "pub_close" is called before creating and connecting a new socket. ''' if self.pub_sock: self.pub_close() ctx = zmq.Context.instance() ...
java
static List<String> getFQDNValueListCMS(JSONObject jObj, String projectionStr) throws JSONException { final List<String> labelList = new ArrayList<String>(); if (!jObj.has("result")) { logger.error("!!CMS_ERROR! result key is not in jOBJ in getFQDNValueListCMS!!: \njObj:" ...
python
def count_nonzero(data, mapper=None, blen=None, storage=None, create='array', **kwargs): """Count the number of non-zero elements.""" return reduce_axis(data, reducer=np.count_nonzero, block_reducer=np.add, mapper=mapper, blen=blen, storage=storage...
java
public byte[] ensureBufferHasCapacityLeft(int size) throws FileParsingException { if (bytesHolder == null) { bytesHolder = new ByteArrayHolder(size); } else { bytesHolder.ensureHasSpace(size); } return bytesHolder.getUnderlyingBytes(); }
java
@Override public String getEnterpriseBeanClassName(Object homeKey) { HomeRecord hr = homesByName.get(homeKey); // d366845.3 return hr.homeInternal.getEnterpriseBeanClassName(homeKey); }
java
public JsHandlerRegistration addGeometryIndexDisabledHandler(final GeometryIndexDisabledHandler handler) { org.geomajas.plugin.editing.client.event.state.GeometryIndexDisabledHandler h; h = new org.geomajas.plugin.editing.client.event.state.GeometryIndexDisabledHandler() { public void onGeometryIndexDisabled(Ge...
java
public Calendar ceil(long t) { Calendar cal = new GregorianCalendar(Locale.US); cal.setTimeInMillis(t); return ceil(cal); }
python
def _validate_python_type(self, python_type): """Validate the possible combinations of python_type and type_name.""" if python_type == 'bool': if self.variable: raise ArgumentError("You can only specify a bool python type on a scalar (non-array) type_name", type_name=self.ty...
java
protected static List<String> splitViewKeys(String viewKeysString) { List<String> splits = new ArrayList<>(); char[] chars = viewKeysString.toCharArray(); boolean betweenSquareBraces = false; boolean betweenQuotes = false; int lastMatch = 0; for (int i = 0; i < chars.length; i++) { if ((...
python
def format_dapi_score(cls, meta, offset): '''Format the line with DAPI user rating and number of votes''' if 'average_rank' and 'rank_count' in meta: label = (cls._nice_strings['average_rank'] + ':').ljust(offset + 2) score = cls._format_field(meta['average_rank']) vo...
python
def get_cdpp(self, flux=None): ''' Returns the scalar CDPP for the light curve. ''' if flux is None: flux = self.flux return self._mission.CDPP(self.apply_mask(flux), cadence=self.cadence)
java
protected void closeCDATA() throws org.xml.sax.SAXException { try { m_writer.write(CDATA_DELIMITER_CLOSE); // write out a CDATA section closing "]]>" m_cdataTagOpen = false; // Remember that we have done so. } catch (IOException e) { ...
python
def set_appium_timeout(self, seconds): """Sets the timeout in seconds used by various keywords. There are several `Wait ...` keywords that take timeout as an argument. All of these timeout arguments are optional. The timeout used by all of them can be set globally using this keywor...
python
def _lastWord(self, text): """Move backward to the start of the word at the end of a string. Return the word """ for index, char in enumerate(text[::-1]): if char.isspace() or \ char in ('(', ')'): return text[len(text) - index :] else: ...
java
public static Class<?> getPropertyClass(Class<?> beanClass, String field) { return INSTANCE.findPropertyClass(beanClass, field); }
python
def all_enclosing_scopes(scope, allow_global=True): """Utility function to return all scopes up to the global scope enclosing a given scope.""" _validate_full_scope(scope) # TODO: validate scopes here and/or in `enclosing_scope()` instead of assuming correctness. def scope_within_range(tentative_scope): ...
python
def generic_add(a, b): """Simple function to add two numbers""" logger.debug('Called generic_add({}, {})'.format(a, b)) return a + b
java
protected List<PropertyData> getChildProps(String parentId, boolean withValue) { return getChildProps.run(parentId, withValue); }