language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Nullable V doComputeIfAbsent(K key, Object keyRef,
Function<? super K, ? extends V> mappingFunction, long[/* 1 */] now, boolean recordStats) {
@SuppressWarnings("unchecked")
V[] oldValue = (V[]) new Object[1];
@SuppressWarnings("unchecked")
V[] newValue = (V[]) new Object[1];
@SuppressWarning... |
python | def get_project_files():
"""Retrieve a list of project files, ignoring hidden files.
:return: sorted list of project files
:rtype: :class:`list`
"""
if is_git_project():
return get_git_project_files()
project_files = []
for top, subdirs, files in os.walk('.'):
for subdir in... |
java | @Override
public Set<Long> getCandidateItemsToRank(final Long user) {
final Set<Long> allItems = getModelTrainingDifference(getTraining(), user);
allItems.addAll(getModelTrainingDifference(getTest(), user));
// return only N not relevant items
List<Long> shuffledItems = new ArrayList... |
python | def mass_from_composition(composition):
""" Calculates molecular mass from atomic weights
Parameters
----------
composition: dict
Dictionary mapping int (atomic number) to int (coefficient)
Returns
-------
float
molecular weight in atomic mass units
Notes
-----
... |
python | def _get_app_module(self):
# type: () -> Callable
"""Returns a module which binds the current app and configuration.
:return: configuration callback
:rtype: Callable
"""
def configure(binder):
# type: (Binder) -> Callable
binder.bind(ServiceAppli... |
java | public List<TopicRelationship> getRelatedTopicRelationships() {
final ArrayList<TopicRelationship> relationships = new ArrayList<TopicRelationship>();
/* Check the topic to topic relationships for related relationships */
for (final TopicRelationship relationship : topicRelationships) {
... |
python | def repeatingfields(theidd, commdct, objkey, flds):
"""return a list of repeating fields
fld is in format 'Component %s Name'
so flds = [fld % (i, ) for i in range(n)]
does not work for 'fields as indicated' """
# TODO : make it work for 'fields as indicated'
if type(flds) != list:
flds ... |
java | public synchronized void setPoolSize(int poolSize)
{
if (poolSize < 0)
{
throw new IllegalArgumentException("New poolSize (" + poolSize + ") is must not be negative");
}
if (pool != null)
{
pool.setCorePoolSize(poolSize);
}
this.poolSi... |
python | async def memberships(client: Client, search: str) -> dict:
"""
GET list of Membership documents for UID/Public key
:param client: Client to connect to the api
:param search: UID/Public key
:return:
"""
return await client.get(MODULE + '/memberships/%s' % search, schema=MEMBERSHIPS_SCHEMA) |
java | public void setAttribute(String name, String value)
{
Params.notNullOrEmpty(name, "Attribute name");
Params.notEmpty(value, "Attribute value");
if(value != null) {
attributes.put(name, value);
}
else {
attributes.remove(name);
}
} |
java | @UiHandler("m_searchInput")
protected void onSearchInputChange(ValueChangeEvent<String> event) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(event.getValue()) && (event.getValue().length() >= 3)) {
m_tabHandler.setSearchQuery(event.getValue());
} else {
m_tabHandler.setSear... |
python | def annotate(args):
"""
%prog annotate agpfile gaps.linkage.bed assembly.fasta
Annotate AGP file with linkage info of `paired-end` or `map`.
File `gaps.linkage.bed` is generated by assembly.gaps.estimate().
"""
from jcvi.formats.agp import AGP, bed, tidy
p = OptionParser(annotate.__doc__)
... |
java | void createContainer( String imageId ) throws TargetException {
// Get the command to pass to the container
this.logger.info( "Creating container " + this.machineId + " from image " + imageId );
// Extract parameters as local variables
Map<String,String> targetProperties = this.parameters.getTargetProperties(... |
java | public void cancelNumber(String country, String msisdn) throws IOException, NexmoClientException {
this.cancelNumber.execute(new CancelNumberRequest(country, msisdn));
} |
java | public final long getLong(int index) {
final long pos = address + index;
if (index >= 0 && pos <= addressLimit - 8) {
return UNSAFE.getLong(heapMemory, pos);
}
else if (address > addressLimit) {
throw new IllegalStateException("segment has been freed");
}
else {
// index is in fact invalid
throw... |
python | def train_image(self):
"""Return the Docker image to use for training.
The :meth:`~sagemaker.estimator.EstimatorBase.fit` method, which does the model training,
calls this method to find the image to use for model training.
Returns:
str: The URI of the Docker image.
... |
java | static void runPartialLearner(boolean withCache) {
// setup SULs and counters
StateLocalInputSUL<Integer, Character> target = SUL;
ResetCounterStateLocalInputSUL<Integer, Character> resetCounter =
new ResetCounterStateLocalInputSUL<>("Resets", target);
SymbolCounterStat... |
python | def get_host_domainname(name, domains=None, **api_opts):
'''
Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
... |
java | private static void dirToTarArchiveOutputStreamRecursive(FileStatus dirFileStatus, FileSystem fs,
Optional<Path> destDir, TarArchiveOutputStream tarArchiveOutputStream) throws IOException {
Preconditions.checkState(fs.isDirectory(dirFileStatus.getPath()));
Path dir = destDir.isPresent() ? new Path(destD... |
python | def mkdir(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Ensure that the directory is available and permissions are set.
Args:
path (str):
The full path to the directory.
owner (str):
... |
python | def dlogpdf_dlink(self, link_f, y, Y_metadata=None):
"""
Gradient of the log likelihood function at y, given link(f) w.r.t link(f)
.. math::
:param link_f: latent variables (f)
:type link_f: Nx1 array
:param y: data
:type y: Nx1 array
:param Y_metadata: ... |
java | public Collection<Object> collectAll(InputStream inputStream, String... paths) {
return collectAll(inputStream, compile(paths));
} |
java | public void marshall(DecisionTaskTimedOutEventAttributes decisionTaskTimedOutEventAttributes, ProtocolMarshaller protocolMarshaller) {
if (decisionTaskTimedOutEventAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
pr... |
python | def ip_rtm_config_route_static_route_nh_route_attributes_metric(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns="urn:broc... |
java | private String getInvokerMethodName(MethodLiteral<?, ?> method,
NameGenerator nameGenerator) throws NoSourceNameException {
Class<?> methodDeclaringType = method.getRawDeclaringType();
String invokeeTypeName = ReflectUtil.getSourceName(methodDeclaringType);
String methodBaseName = nameGenerator.conver... |
python | def _effective_value(self, attr_name):
"""
The effective value of *attr_name* on this placeholder shape; its
directly-applied value if it has one, otherwise the value on the
layout placeholder it inherits from.
"""
directly_applied_value = getattr(
super(_Inhe... |
python | def batch_retrieve_overrides_in_course(self, course_id, assignment_overrides_id, assignment_overrides_assignment_id):
"""
Batch retrieve overrides in a course.
Returns a list of specified overrides in this course, providing
they target sections/groups/students visible to the curren... |
python | def getProductUIDs(self):
""" return the uids of the products referenced by order items
"""
uids = []
for orderitem in self.objectValues('XupplyOrderItem'):
product = orderitem.getProduct()
if product is not None:
uids.append(orderitem.getProduct()... |
python | def _send_raw_command(ipmicmd, raw_bytes):
"""Use IPMI command object to send raw ipmi command to BMC
:param ipmicmd: IPMI command object
:param raw_bytes: string of hexadecimal values. This is commonly used
for certain vendor specific commands.
:returns: dict -- The response from IPMI device
... |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.GDD__GOC_ADES:
return GOC_ADES_EDEFAULT == null ? gocAdes != null : !GOC_ADES_EDEFAULT.equals(gocAdes);
case AfplibPackage.GDD__COMMANDS:
return commands != null && !commands.isEmpty();
}
return super.eIsSet(fe... |
java | public void doNewRecord(boolean bDisplayOption)
{
Record recUserInfo = this.getOwner();
RecordOwner recordOwner = recUserInfo.getRecordOwner();
Record recUserScreenRecord = (Record)recordOwner.getScreenRecord();
recUserScreenRecord.getField(UserScreenRecord.CURRENT_PASSWORD).setData(... |
python | def get_disabled():
'''
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=False,
... |
python | def is_hubbard(self):
"""
True if run is a DFT+U run.
"""
if len(self.hubbards) == 0:
return False
return sum(self.hubbards.values()) > 1e-8 |
python | def endaccess(self):
"""Terminates access to the SDS.
Args::
no argument
Returns::
None.
The SDS instance should not be used afterwards.
The 'endaccess()' method is implicitly called when
the SDS instance is deleted.
C library equivalent ... |
java | public final T get(Object... args) {
// Grab a read lock to try retrieving the object
this.readLock.lock();
try {
// See if the object already exists and is valid
final T value = this.retrieve(args);
if (!this.invalid(value, args)) {
if (getLo... |
java | private static boolean pointContainsPoint_(Point2D pt_a, Point2D pt_b,
double tolerance, ProgressTracker progress_tracker) {
return pointEqualsPoint_(pt_a, pt_b, tolerance, progress_tracker);
} |
python | def has_valid_soma(data_wrapper):
'''Check if a data block has a valid soma
Returns:
CheckResult with result
'''
try:
make_soma(data_wrapper.soma_points())
return CheckResult(True)
except SomaError:
return CheckResult(False) |
java | private void release(boolean cleartargetstate) {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
if (cleartargetstate) {
mTargetState = STATE_IDLE;
... |
java | private ApiCallAttemptMonitoringEvent generateApiCallAttemptMonitoringEvent(HandlerAfterAttemptContext context) {
Request<?> request = context.getRequest();
AWSRequestMetrics metrics = context.getRequest().getAWSRequestMetrics();
String apiName = request.getHandlerContext(HandlerContextKey.OPER... |
python | def copy(self):
"""
Copy constructor.
"""
return self._constructor(values=self._codes.copy(),
dtype=self.dtype,
fastpath=True) |
java | private static PBXObjectRef createPBXNativeTarget(final String name, final PBXObjectRef buildConfigurationList,
final List buildPhases, final List buildRules, final List dependencies, final String productInstallPath,
final String productName, final PBXObjectRef productReference, final String productType) {
... |
python | def extract_macaroons(headers_or_request):
''' Returns an array of any macaroons found in the given slice of cookies.
If the argument implements a get_header method, that will be used
instead of the get method to retrieve headers.
@param headers_or_request: dict of headers or a
urllib.request.Reques... |
java | public int getFlowAt( Direction direction ) {
switch( direction ) {
case E:
return eFlow;
case W:
return wFlow;
case N:
return nFlow;
case S:
return sFlow;
case EN:
return enFlow;
case NW:
ret... |
java | protected String loadNotice(Scriptable cfg) throws IOException, URISyntaxException {
String notice = null;
Object noticeObj = cfg.get(NOTICE_CONFIGPARAM, cfg);
if (noticeObj != Scriptable.NOT_FOUND) {
String noticeUriStr = toString(noticeObj);
URI noticeUri = new URI(noticeUriStr).normalize();
if (... |
python | def process_delete(self, obj, pk_set=None, action=None, update_fields=None, **kwargs):
"""Recreate queryset from the index and rebuild the index."""
build_kwargs = self.delete_cache.take(obj)
if build_kwargs:
self.index.build(**build_kwargs) |
java | public Observable<List<ApplicationInsightsComponentFavoriteInner>> listAsync(String resourceGroupName, String resourceName) {
return listWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<List<ApplicationInsightsComponentFavoriteInner>>, List<ApplicationInsightsComponentFavo... |
python | def tempo(self,
factor,
use_tree=False,
opt_flag=None,
segment=82,
search=14.68,
overlap=12):
"""tempo takes 6 parameters: factor, use tree (True or False), option
flag, segment, search and overlap).
This effect... |
java | public static void changePassphrase(Path pathToVault, String masterkeyFilename, byte[] pepper, CharSequence oldPassphrase, CharSequence newPassphrase)
throws InvalidPassphraseException, FileSystemNeedsMigrationException, IOException {
if (Migrators.get().needsMigration(pathToVault, masterkeyFilename)) {
thro... |
python | def query(url,
method='GET',
params=None,
data=None,
data_file=None,
header_dict=None,
header_list=None,
header_file=None,
username=None,
password=None,
auth=None,
decode=False,
decode_type='auto',
... |
python | def _filesec(self, files=None):
"""
Returns fileSec Element containing all files grouped by use.
"""
if files is None:
files = self.all_files()
filesec = etree.Element(utils.lxmlns("mets") + "fileSec")
filegrps = {}
for file_ in files:
if ... |
java | public void show(RequestManager requestManager, ActionRuntime runtime, InOutLogKeeper keeper) {
if (!isLoggerEnabled()) { // e.g. option is true but no logger settings
return;
}
if (isExceptLogging(requestManager, runtime, keeper)) { // e.g. HealthcheckAction
return;
... |
python | def temporal_firing_rate(self,time_dimension=0,resolution=1.0,units=None,
min_t=None,max_t=None,weight_function=None,normalize_time=False,
normalize_n=False,start_units_with_0=True,cell_dimension='N'):
"""
Outputs a time histogram of spikes.
... |
python | def file_supports_color(file_obj):
"""
Returns True if the running system's terminal supports color, and False
otherwise.
Borrowed from Django
https://github.com/django/django/blob/master/django/core/management/color.py
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' an... |
java | public static UnixPath getPath(boolean permitEmptyComponents, String path) {
if (path.isEmpty()) {
return EMPTY_PATH;
} else if (isRootInternal(path)) {
return ROOT_PATH;
} else {
return new UnixPath(permitEmptyComponents, path);
}
} |
java | private Document uploadSslCertificate(SSLCertificateCreateOptions opts, boolean cs44hack) throws InternalException, CloudException {
// TODO: add trace
final List<Param> params = new ArrayList<Param>();
try {
params.add(new Param("certificate",
cs44hack ? URLEncod... |
java | public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {
final Client client = getClient(user, password);
final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());
... |
python | def raxml_alignment(align_obj,
raxml_model="GTRCAT",
params={},
SuppressStderr=True,
SuppressStdout=True):
"""Run raxml on alignment object
align_obj: Alignment object
params: you can set any params except -w and -n
returns: tuple (ph... |
python | def maximum_address(self):
"""The maximum address of the data, or ``None`` if the file is empty.
"""
maximum_address = self._segments.maximum_address
if maximum_address is not None:
maximum_address //= self.word_size_bytes
return maximum_address |
java | public void marshall(DetectEntitiesRequest detectEntitiesRequest, ProtocolMarshaller protocolMarshaller) {
if (detectEntitiesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(detectEntitiesRe... |
java | public SortDirection nextDirection(SortDirection direction) {
if(direction == SortDirection.NONE)
return SortDirection.ASCENDING;
else if(direction == SortDirection.ASCENDING)
return SortDirection.DESCENDING;
else if(direction == SortDirection.DESCENDING)
retu... |
python | def sign_attribute_query(self, statement, **kwargs):
"""Sign a SAML attribute query.
See sign_statement() for the kwargs.
:param statement: The statement to be signed
:return: The signed statement
"""
return self.sign_statement(
statement, class_name(sam... |
java | @Nonnull
public static LDblConsumer dblConsumerFrom(Consumer<LDblConsumerBuilder> buildingFunction) {
LDblConsumerBuilder builder = new LDblConsumerBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
python | def convert(self, inp):
"""Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representin... |
java | @RequirePOST
public HttpResponse doSiteConfigure(@QueryParameter String site) throws IOException {
Jenkins hudson = Jenkins.getInstance();
hudson.checkPermission(CONFIGURE_UPDATECENTER);
UpdateCenter uc = hudson.getUpdateCenter();
PersistedList<UpdateSite> sites = uc.getSites();
... |
python | def File(name, mode='a', chunk_cache_mem_size=1024**2, w0=0.75, n_cache_chunks=None, **kwds):
"""Create h5py File object with cache specification
This function is basically just a wrapper around the usual h5py.File constructor,
but accepts two additional keywords:
Parameters
----------
name : ... |
python | def createActionGroup(self, parent=None, name=''):
"""
Overloads teh create action method to handle the proper base
instance information, similar to the PyQt4 loading system.
:param parent | <QWidget> || None
name | <str>
"""
ac... |
java | public <T> void store(@Nonnull Resource resource, @Nonnull Key key, @Nonnull Optional<T> model) {
if (resource == null) {
throw new IllegalArgumentException("Method argument resource must not be null");
}
if (key == null) {
throw new IllegalArgumentException("Method argum... |
python | def get_spec(self):
"""
Return the Core ML spec
"""
if _mac_ver() >= (10, 14):
return self.vggish_model.get_spec()
else:
vggish_model_file = VGGish()
coreml_model_path = vggish_model_file.get_model_path(format='coreml')
return MLMod... |
python | def depth_slice(self):
"""
Interact with segy in depth slice mode (fixed z-coordinate)
Returns
-------
depth : Depth
Notes
-----
.. versionadded:: 1.1
.. versionchanged:: 1.7.1
enabled for unstructured files
"""
if s... |
java | @Override
public void indexInner(ByteBuffer key, ColumnFamily columnFamily, long timestamp) {
DeletionInfo deletionInfo = columnFamily.deletionInfo();
DecoratedKey partitionKey = rowMapper.partitionKey(key);
if (columnFamily.iterator().hasNext()) {
List<CellName> clusteringKeys ... |
java | public ServiceFuture<Void> revokeAsync(String vaultName, String resourceGroupName, String fabricName, String containerName, String protectedItemName, String recoveryPointId, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(revokeWithServiceResponseAsync(vaultName, resourceGroupNa... |
python | def difference(self, *others):
"""Return the difference of two or more sets as a new :class:`set`.
(i.e. all elements that are in this set but not the others.)
Operates on either redish.types.Set or __builtins__.set.
"""
if all([isinstance(a, self.__class__) for a in others]):... |
java | public boolean decompose( DMatrixRMaj a )
{
decomposeCommonInit(a);
double LUcolj[] = vv;
for( int j = 0; j < n; j++ ) {
// make a copy of the column to avoid cache jumping issues
for( int i = 0; i < m; i++) {
LUcolj[i] = dataLU[i*n + j];
... |
python | def _get_last_worker_died(self):
"""Return the last died worker information or None"""
for service_id in list(self._running_services.keys()):
# We copy the list to clean the orignal one
processes = list(self._running_services[service_id].items())
for process, worker_i... |
java | static String capitalizeAsciiOnly(String s) {
if (s == null || s.isEmpty()) {
return s;
}
char c = s.charAt(0);
if (isLowerCaseAsciiOnly(c)) {
return Character.toUpperCase(c) + s.substring(1);
}
return s;
} |
java | private boolean createEmptyHeader( String filePath, int rows ) {
try {
RandomAccessFile theCreatedFile = new RandomAccessFile(filePath, "rw");
rowaddresses = new long[rows + 1];
// the size of a long
theCreatedFile.write(4);
// write the addresses of... |
python | def _netid_category_url(netid, category_codes):
"""
Return UWNetId resource for provided netid and category
code or code list
"""
return "{0}/{1}/category/{2}".format(
url_base(), netid,
(','.join([str(n) for n in category_codes])
if isinstance(category_codes, (list, tuple))... |
java | public static MutableFst copyAndTranslateSymbols(Fst fst, WriteableSymbolTable newInputSymbols,
WriteableSymbolTable newOutputSymbols) {
SymbolTable.InvertedSymbolTable origInput = fst.getInputSymbols().invert();
SymbolTable.InvertedSymbolTable origOutput = fst... |
java | public static File wrap(final File pPath) {
if (pPath == null) {
return null;
}
if (IS_WINDOWS) {
// Don't wrap if allready wrapped
if (pPath instanceof Win32File || pPath instanceof Win32Lnk) {
return pPath;
}
... |
java | public static void main(String[] args) throws Exception {
OptionParser parser = null;
OptionSet options = null;
try {
parser = getParser();
options = parser.parse(args);
} catch(OptionException oe) {
parser.printHelpOn(System.out);
printUsa... |
python | def str_count(arr, pat, flags=0):
"""
Count occurrences of pattern in each string of the Series/Index.
This function is used to count the number of times a particular regex
pattern is repeated in each of the string elements of the
:class:`~pandas.Series`.
Parameters
----------
pat : st... |
python | def bishop88_i_from_v(voltage, photocurrent, saturation_current,
resistance_series, resistance_shunt, nNsVth,
method='newton'):
"""
Find current given any voltage.
Parameters
----------
voltage : numeric
voltage (V) in volts [V]
photocurrent :... |
python | def export_inclusive_exclusive_gateway_info(node_params, output_element):
"""
Adds InclusiveGateway or ExclusiveGateway node attributes to exported XML element
:param node_params: dictionary with given inclusive or exclusive gateway parameters,
:param output_element: object representing... |
python | def _bridge(self, channel):
""" Full-duplex bridge between a websocket and a SSH channel """
channel.setblocking(False)
channel.settimeout(0.0)
self._tasks = [
gevent.spawn(self._forward_inbound, channel),
gevent.spawn(self._forward_outbound, channel)
]
... |
java | public CacheControl hint(DataFetchingEnvironment dataFetchingEnvironment, Scope scope) {
return hint(dataFetchingEnvironment, null, scope);
} |
java | @Override
protected void write(LogLevel level, String correlationId, Exception error, String message) {
for (ILogger logger : _loggers)
logger.log(level, correlationId, error, message);
} |
python | def run(self):
"""Collector main loop."""
while True:
data = self.queue.get()
if data is None:
Logger.get_logger(__name__).info("Stopping collector process ...")
break
# updating the report data
self.store.update(data)
... |
java | private JpaDistributionSet touch(final Long distId) {
return touch(get(distId).orElseThrow(() -> new EntityNotFoundException(DistributionSet.class, distId)));
} |
python | def is_cache_valid(self):
''' Determines if the cache files have expired, or if it is still
valid '''
if os.path.isfile(self.cache_path_cache):
mod_time = os.path.getmtime(self.cache_path_cache)
current_time = time()
if (mod_time + self.cache_max_age) > curre... |
python | def create_bucket(self, name, headers=None):
"""
Creates a bucket named :attr:`name`.
:param dict headers: Any headers to use when performing the HTTP PUT.
"""
self.provider.swift_client.put_container(name, headers) |
java | protected Object convertValue(AnnotatedElement element, String value) {
Class<?> type = getValueType(element);
Type genericType = getValueGenericType(element);
try {
if (element.isAnnotationPresent(Use.class)) {
Converter converter = getConverterForElementWithUseAnno... |
java | public static SoapAttachment parseAttachment(Element attachmentElement) {
SoapAttachment soapAttachment = new SoapAttachment();
if (attachmentElement.hasAttribute("content-id")) {
soapAttachment.setContentId(attachmentElement.getAttribute("content-id"));
}
if (attachmentEle... |
python | def path(self):
""":return: path of the underlying mapped file
:raise ValueError: if attached path is not a path"""
if isinstance(self._rlist.path_or_fd(), int):
raise ValueError("Path queried although mapping was applied to a file descriptor")
# END handle type
retur... |
python | def content_type(self, response):
"""
Ensures the response is of type
:param obj response: The scrapy response
:return bool: Determines wether the response is of the correct type
"""
if not re_html.match(response.headers.get('Content-Type').decode('utf-8')):
... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.AMI__DSPLCMNT:
return getDSPLCMNT();
}
return super.eGet(featureID, resolve, coreType);
} |
java | public SortedMap<String, String> getDisplayNames(ULocale locale, String matchID) {
return getDisplayNames(locale, null, matchID);
} |
python | def route_many(self, *args, **kwargs):
"""
>>> from torext.route import include
>>> app = TorextApp()
>>> app.route_many([
... ('/account', include('account.views')),
... ('/account', include('account.views')),
... ], '^account.example.com$')
"""
... |
python | def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None):
"""
- Parse HTML and get miniDOM
- Extract CSS informations, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context object
"""
global CSSAttrCache
C... |
java | private void mapTreeHierarchy(final WComponent currentComponent,
final StringTreeNode currentNode, final WText selectedMenuText) {
if (currentNode.isLeaf()) {
WMenuItem menuItem = new WMenuItem(currentNode.getData(), new ExampleMenuAction(
selectedMenuText));
menuItem.setActionObject(currentNode.getData... |
python | def power_curve(wind_speed, power_curve_wind_speeds, power_curve_values,
density=None, density_correction=False):
r"""
Calculates the turbine power output using a power curve.
This function is carried out when the parameter `power_output_model` of an
instance of the :class:`~.modelchain... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.