language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void setFallbackIntervalPattern(String fallbackPattern)
{
if ( frozen ) {
throw new UnsupportedOperationException("no modification is allowed after DII is frozen");
}
int firstPatternIndex = fallbackPattern.indexOf("{0}");
int secondPatternIndex = fallbackPattern.i... |
python | def openfile(cls, filepath):
"""Class method that opens (load) a vntree pickle file.
:param filepath: the file path for the pickle file.
:type filepath: str
:returns: root node of tree or `False` if failure.
:rtype: Node or bool
"""
if not os.path.isfi... |
python | def peer_echo(includes=None, force=False):
"""Echo filtered attributes back onto the same relation for storage.
This is a requirement to use the peerstorage module - it needs to be called
from the peer relation's changed hook.
If Juju leader support exists this will be a noop unless force is True.
... |
python | def actionnames(self):
"""
Returns a alphabetical sorted list of tuples with all known
service- and action-names.
"""
actions = []
for service_name in sorted(self.services.keys()):
action_names = self.services[service_name].actions.keys()
for actio... |
java | public ClassFinder add(File file) {
log.info("Adding file to look into: " + file.getAbsolutePath());
if (fileCanContainClasses(file)) {
String absPath = file.getAbsolutePath();
if (placesToSearch.get(absPath) == null) {
placesToSearch.put(absPath, file);
for (AdditionalResourceLoade... |
python | def _get_composition_collection(self, composition_id):
"""Returns a Mongo Collection and Composition given a Composition Id"""
collection = JSONClientValidated('repository',
collection='Composition',
runtime=self._runtime)... |
python | def get_receive_message(self, data):
'''
http://channels.readthedocs.io/en/stable/asgi/www.html#receive
'''
self.order += 1
message = {
'channel': 'websocket.receive',
'reply_channel': None,
'path': self.path,
'order': self.order,
... |
java | public <C extends CalendarVariant<C>> GeneralTimestamp<C> now(
CalendarFamily<C> family,
VariantSource variantSource,
StartOfDay startOfDay
) {
return this.now(family, variantSource.getVariant(), startOfDay);
} |
java | public Rectangle rectangle(float top, float bottom) {
Rectangle tmp = new Rectangle(this);
if (getTop() > top) {
tmp.setTop(top);
tmp.disableBorderSide(TOP);
}
if (getBottom() < bottom) {
tmp.setBottom(bottom);
tmp.disableBorderSide(BOTTOM);
}
return tmp;
} |
java | static StructrMethodDefinition deserialize(final StructrTypeDefinition parent, final String name, final Map<String, Object> source) {
final StructrMethodDefinition newMethod = new StructrMethodDefinition(parent, name);
newMethod.deserialize(source);
return newMethod;
} |
java | public void notifyAfterEvaluation(String expression) {
for (EvaluationListener listener : listeners) {
try {
listener.afterEvaluation(this, expression);
} catch (Throwable t) {
Util.handleThrowable(t);
// Ignore - no option to log
... |
python | def fixup_parents(self, node, parent):
"""Make sure each node has a parent"""
start, finish = 0, self.last_finish
# We assume anything with a start has a finish.
needs_range = not hasattr(node, 'start')
if not hasattr(node, 'parent'):
node.parent = parent
fo... |
python | def get_quantity_of_splits_for_account(self, account_id: str) -> Decimal:
""" Returns the sum of values for all splits for the given account """
splits = self.get_split_for_account(account_id)
result = Decimal(0)
for split in splits:
result += split.quantity
return re... |
java | private synchronized DatanodeInfo blockSeekTo(long target,
boolean throwWhenNotFound) throws IOException {
// We only allow to seek before the end of the file, or the end of the file
// and allowSeedtoEnd, which is the case called by available().
//
if (target > getFileLength() || (target == getFi... |
python | def put(self, request, *args, **kwargs):
""" custom put method to support django-reversion """
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR'])
return s... |
python | def create_domain_name(self,
domain_name,
certificate_name,
certificate_body=None,
certificate_private_key=None,
certificate_chain=None,
certificate_arn=None,... |
java | static final Entry getEntry (final String key, final Collection<Entry> entries) {
for (Entry e : entries)
if (e.matchKey(key)) return e;
return null;
} |
python | def getFixedStar(ID, date):
""" Returns a fixed star from the ephemeris. """
star = eph.getFixedStar(ID, date.jd)
return FixedStar.fromDict(star) |
java | public static Set<String> getTagSet(String tags) {
tags = StringUtils.substringBefore(tags, "\n");
String[] tagArr = tags.split("[\\s,,;;]");
Set<String> tagSet = new HashSet<String>();
for (int i = 0; i < tagArr.length; i++) {
String tag = tagArr[i].trim();
if (!tag.isEmpty()) {
tagSet.add(tag);
}... |
python | def newResponseEvent(self):
"""creates a response event and adds it to a waiting list
When the reponse arrives it will be removed from the list.
"""
respEvt = ResponseEvent()
self.respLock.acquire()
eid = id(respEvt)
self.respEvents[eid] = respEvt
self... |
java | public void close() throws java.io.IOException
{
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"close", "Closing");
}
if (_observer != null) {
_observer.... |
java | public ServiceFuture<Void> beginDownloadAsync(String resourceGroupName, String virtualWANName, GetVpnSitesConfigurationRequest request, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(beginDownloadWithServiceResponseAsync(resourceGroupName, virtualWANName, request), serviceCallb... |
java | public void set(int index, double value) {
updated = true;
int newIndex = getIndex(index);
if (newIndex == -1)
return;
doubleVector.set(newIndex, value);
} |
java | private MapEntryUpdateResult<K, byte[]> replaceIf(
long index, K key, MapEntryValue newValue, Predicate<MapEntryValue> predicate) {
MapEntryValue oldValue = entries().get(key);
// If the key is not set or the current value doesn't match the predicate, return a PRECONDITION_FAILED error.
if (valueIsNu... |
java | @Override
public CPInstance[] findByLtD_S_PrevAndNext(long CPInstanceId,
Date displayDate, int status,
OrderByComparator<CPInstance> orderByComparator)
throws NoSuchCPInstanceException {
CPInstance cpInstance = findByPrimaryKey(CPInstanceId);
Session session = null;
try {
session = openSession();
... |
java | public final String getMethod() {
if(method == null) {
method = message instanceof Request ? ((Request) message).getMethod()
: ((CSeqHeader) message.getHeader(CSeqHeader.NAME)).getMethod();
}
if(logger.isDebugEnabled()) {
logger.debug("getMethod - return=" + method);
}
return method;
} |
java | public static <I, O> JMConcurrentProcessor<I, O> buildWithThreadPool(
Function<I, O> transformerFunction) {
return buildWithThreadPool(OS.getAvailableProcessors(),
transformerFunction);
} |
python | def get_http_response(self):
"""Get this exception as an HTTP response suitable for output"""
return _get_response(
code=self.code,
body=str(self),
headers={
'Content-Type': 'text/plain'
}
) |
python | def keyPressEvent(self, event):
"""
Listens for the left/right keys and the escape key to control
the slides.
:param event | <QtCore.Qt.QKeyEvent>
"""
if event.key() == QtCore.Qt.Key_Escape:
self.cancel()
elif event.key() == QtCo... |
python | def start(builtins=False, profile_threads=True):
"""
Start profiler.
"""
if profile_threads:
threading.setprofile(_callback)
_yappi.start(builtins, profile_threads) |
java | public static Long getChatId(Update update) {
if (MESSAGE.test(update)) {
return update.getMessage().getChatId();
} else if (CALLBACK_QUERY.test(update)) {
return update.getCallbackQuery().getMessage().getChatId();
} else if (INLINE_QUERY.test(update)) {
return (long) update.getInlineQuery... |
python | def get_package_version(self, feed_id, package_id, package_version_id, project=None, include_urls=None, is_listed=None, is_deleted=None):
"""GetPackageVersion.
[Preview API] Get details about a specific package version.
:param str feed_id: Name or Id of the feed.
:param str package_id: I... |
python | def student_visible(self):
"""Return a list of groups that are student-visible.
"""
group_ids = set()
for group in Group.objects.all():
if group.properties.student_visible:
group_ids.add(group.id)
return Group.objects.filter(id__in=group_ids) |
java | public static MozuUrl updateSearchTuningRuleUrl(String responseFields, String searchTuningRuleCode)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/search/searchtuningrules/{searchTuningRuleCode}?responseFields={responseFields}");
formatter.formatUrl("responseFields", responseFields);
... |
java | private double[] lineSearchBacktrack(Function func, double[] dir, double[] x,
double[] newX, double[] grad, double lastValue)
throws MaxEvaluationsExceeded {
double normGradInDir = ArrayMath.innerProduct(dir, grad);
say("(" + nf.format(normGradInDir) + ")");
if (normGradInDir > 0) {
... |
java | @Override
public void accept(Visitor<Operator<?>> visitor) {
boolean descend = visitor.preVisit(this);
if (descend) {
this.input.accept(visitor);
visitor.postVisit(this);
}
} |
java | public static boolean isValidAccessorName(String accessorName) {
if (accessorName.startsWith("get") || accessorName.startsWith("is") || accessorName.startsWith("set")) {
int prefixLength = accessorName.startsWith("is") ? 2 : 3;
return accessorName.length() > prefixLength;
};
... |
python | def diagonal_gaussian_posterior_builder(
getter, name, shape=None, *args, **kwargs):
"""A pre-canned builder for diagonal gaussian posterior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a diagonal posterior over a variable of t... |
java | public static void remove( Key k, Futures fs ) {
Value val = DKV.get(k);
if( val==null ) return;
((Keyed)val.get()).remove(fs);
} |
java | public static <NodeT extends ConstituentNode<NodeT, ?>> HeadFinder<NodeT> createChinesePTBFromResources()
throws IOException {
final boolean headInitial = true;
final CharSource resource = Resources
.asCharSource(EnglishAndChineseHeadRules.class.getResource("ch_heads.sun.txt"),
Charset... |
java | public void removeResourceFromUsersPubList(CmsDbContext dbc, CmsUUID userId, Collection<CmsUUID> structureIds)
throws CmsDataAccessException {
for (CmsUUID structureId : structureIds) {
CmsLogEntry entry = new CmsLogEntry(
userId,
System.currentTimeMillis(),
... |
java | public Futures subRef( Vec vec, Futures fs ) {
assert fs != null : "Future should not be null!";
if ( vec.masterVec() != null ) subRef(vec.masterVec(), fs);
int cnt = _refcnt.get(vec)._val-1;
if ( cnt > 0 ) {
_refcnt.put(vec,new IcedInt(cnt));
} else {
UKV.remove(vec._key,fs);
_ref... |
java | public void setSceneModel (MisoSceneModel model)
{
_model = model;
// clear out old blocks and objects
clearScene();
centerOnTile(0, 0);
if (isShowing()) {
rethink();
_remgr.invalidateRegion(_vbounds);
}
} |
python | def directory_tarball(dirname):
"""Create a tarball of a complex directory, avoiding complex secondaryFiles.
Complex secondary files do not work on multiple platforms and are not portable
to WDL, so for now we create a tarball that workers will unpack.
"""
assert os.path.isdir(dirname), dirname
... |
java | private static void decode(InputStream in, StringBuilder result) throws ApiDataException, ApiConnectionException {
try {
int len = readLen(in);
if (len > 0) {
byte buf[] = new byte[len];
for (int i = 0; i < len; ++i) {
int c = in.read()... |
java | public static ApiBodyMetadata mapTypeToPojo(JCodeModel pojoCodeModel, RamlRoot document, TypeDeclaration type) {
RamlInterpretationResult interpret = RamlInterpreterFactory.getInterpreterForType(type).interpret(document, type, pojoCodeModel,
false);
// here we expect that a new object is created i guess... we'... |
python | def ParseDataStream(self, parser_mediator, file_entry, data_stream_name):
"""Parses a data stream of a file entry with the enabled parsers.
Args:
parser_mediator (ParserMediator): parser mediator.
file_entry (dfvfs.FileEntry): file entry.
data_stream_name (str): data stream name.
Raises:... |
java | @Override
public DeleteObjectResult deleteObject(DeleteObjectRequest request) {
request = beforeClientExecution(request);
return executeDeleteObject(request);
} |
python | def acceptNavigationRequest(self, url, kind, is_main_frame):
"""Open external links in browser and internal links in the webview"""
ready_url = url.toEncoded().data().decode()
is_clicked = kind == self.NavigationTypeLinkClicked
if is_clicked and self.root_url not in ready_url:
... |
python | def search_channels(self, **kwargs):
"""
Search for all channels by parameters
"""
params = [(key, kwargs[key]) for key in sorted(kwargs.keys())]
url = "/notification/v1/channel?{}".format(
urlencode(params, doseq=True))
response = NWS_DAO().getURL(url, self.... |
python | def _entity_paginator(namespace, workspace, etype, page_size=500,
filter_terms=None, sort_direction="asc"):
"""Pages through the get_entities_query endpoint to get all entities in
the workspace without crashing.
"""
page = 1
all_entities = []
# Make initial reques... |
python | def _iterate_marginal_coef_slices(self, i):
"""iterator of indices into tensor's coef vector for marginal term i's coefs
takes a tensor_term and returns an iterator of indices
that chop up the tensor's coef vector into slices belonging to term i
Parameters
----------
i ... |
java | public void addValueSet(ValueSet theValueSet) {
Validate.notBlank(theValueSet.getUrl(), "theValueSet.getUrl() must not return a value");
addToMap(theValueSet, myValueSets, theValueSet.getUrl());
} |
java | public void prune() {
if (children != null) {
List<String> removeList = new ArrayList<String>();
for (Entry<String, DepTreeNode> entry : children.entrySet()) {
DepTreeNode child = entry.getValue();
child.prune();
if ((child.defineDependencies == null && child.requireDependencies == null && chi... |
python | def show_batch_runner(self):
"""Show the batch runner dialog."""
from safe.gui.tools.batch.batch_dialog import BatchDialog
dialog = BatchDialog(
parent=self.iface.mainWindow(),
iface=self.iface,
dock=self.dock_widget)
dialog.exec_() |
java | @Override
public Response resynchronize( String applicationName ) {
this.logger.fine( "Request: resynchronize all the agents." );
String lang = lang( this.manager );
Response response = Response.ok().build();
try {
ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applica... |
python | def build(self, text, matrix, skim_depth=10, d_weights=False):
"""
1. For each term in the passed matrix, score its KDE similarity with
all other indexed terms.
2. With the ordered stack of similarities in hand, skim off the top X
pairs and add them as edges.
Args:
... |
python | def parse_xml_file(self, fileobj, id_generator=None):
"""Parse an open XML file, returning a usage id."""
root = etree.parse(fileobj).getroot()
usage_id = self._usage_id_from_node(root, None, id_generator)
return usage_id |
python | def load(self, addr, size=None, condition=None, fallback=None, add_constraints=None, action=None, endness=None,
inspect=True, disable_actions=False, ret_on_segv=False):
"""
Loads size bytes from dst.
:param dst: The address to load from.
:param size: ... |
python | def qualify(self):
"""
Convert attribute values, that are references to other
objects, into I{qref}. Qualfied using default document namespace.
Since many wsdls are written improperly: when the document does
not define a default namespace, the schema target namespace is used
... |
java | @Override
public Rectangle paint(IChemModel chemModel, IDrawVisitor drawVisitor) {
IAtomContainerSet moleculeSet = chemModel.getMoleculeSet();
IReactionSet reactionSet = chemModel.getReactionSet();
if (moleculeSet == null && reactionSet != null) {
Rectangle2D totalBounds = calc... |
java | private static MyfacesLogger createMyfacesLogger(String name, String resourceBundleName)
{
if (name == null)
{
throw new IllegalArgumentException(_LOG.getMessage(
"LOGGER_NAME_REQUIRED"));
}
Logger log = Logger.getLogger(name, resourceBundleName);
... |
java | private String readSqlFromResource(Resource resource)
{
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(
resource.
getFile()), "UTF-8"));)
{
StringBuilder sqlBuf = new StringBuilder();
for (String line = reader.readLine(); line != ... |
python | def bearing_to(self, point):
'''
Return the bearing to another point.
:param point: Point to measure bearing to
:type point: Point
:returns: The bearing to the other point
:rtype: Bearing
'''
delta_long = point.long_radians - self.long_radians
y ... |
python | def make_long_description(marker=None, intro=None):
"""
click_ is a framework to simplify writing composable commands for
command-line tools. This package extends the click_ functionality
by adding support for commands that use configuration files.
.. _click: https://click.pocoo.org/
EXAMPLE:
... |
java | @SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> List<Response<T>> getAndRemoveResponses(final String correlationId) {
synchronized (responseMap) {
final List rv = responseMap.remove(correlationId);
return rv == null ? Collections.emptyList() : new ArrayList(rv);
... |
python | def arch(self):
"""Return a more standard representation of the architecture."""
if self.machine in ["x86_64", "AMD64", "i686"]:
# 32 bit binaries running on AMD64 will still have a i386 arch.
if self.architecture == "32bit":
return "i386"
return "amd64"
elif self.machine == "x86"... |
python | def add_route(self, view: View, path: str, exact: bool = True) -> None:
"""Add a view to the app.
Parameters
----------
view : View
path : str
exact : bool, optional
"""
if path[0] != '/':
path = '/' + path
for route in self._routes:
... |
java | @Override
public ModifyInstanceEventStartTimeResult modifyInstanceEventStartTime(ModifyInstanceEventStartTimeRequest request) {
request = beforeClientExecution(request);
return executeModifyInstanceEventStartTime(request);
} |
python | def PlaceSOffsetT(self, x):
"""PlaceSOffsetT prepends a SOffsetT to the Builder, without checking
for space.
"""
N.enforce_number(x, N.SOffsetTFlags)
self.head = self.head - N.SOffsetTFlags.bytewidth
encode.Write(packer.soffset, self.Bytes, self.Head(), x) |
java | @Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
// TODO(bangert): Validate all the fields
if (!ASTHelpers.getSymbol(tree).toString().equals(RestrictedApi.class.getName())) {
return Description.NO_MATCH;
}
// TODO(bangert): make a more elegant API to get th... |
python | def label_ref_node(docname, ref_to, title):
"""Generate a node that references a label"""
txt = Text(title, rawsource=title)
newchild = inline(
':ref:`%s`' % ref_to,
'',
txt,
classes=['xref', 'std', 'std-ref']
)
newnode = pending_xref(
':ref:`%s`' % ref_to,
... |
python | def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 |
python | def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rderiv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT... |
java | @Nonnull
public static <T> LObjFltPredicateBuilder<T> objFltPredicate(Consumer<LObjFltPredicate<T>> consumer) {
return new LObjFltPredicateBuilder(consumer);
} |
python | def get_parse(self, show=True, proxy=None, timeout=0):
"""
GET MediaWiki:API action=parse request
https://en.wikipedia.org/w/api.php?action=help&modules=parse
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
O... |
python | def check_consistent_parameter_dimensions(self):
"""
Ensure that all parameter dimensions are consistent with
the :attr:`array_shape` dimension.
:raises ValueError: For inconsistent parameter dimensions.
"""
if self.indices_per_axis is not None:
if len(self.i... |
java | @Override
public List<String> getUniqueGroupIdsForUser(String uniqueUserId) throws EntryNotFoundException, RegistryException {
return getGroupsForUser(uniqueUserId);
} |
java | @Override
public BatchDetectKeyPhrasesResult batchDetectKeyPhrases(BatchDetectKeyPhrasesRequest request) {
request = beforeClientExecution(request);
return executeBatchDetectKeyPhrases(request);
} |
java | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalEmptyArgumentException.class })
public static <T extends CharSequence> T notEmpty(@Nonnull final T chars) {
notNull(chars);
notEmpty(chars, chars.length() == 0, EMPTY_ARGUMENT_NAME);
return chars;
} |
python | def zeroize():
'''
Resets the device to default factory settings
CLI Example:
.. code-block:: bash
salt 'device_name' junos.zeroize
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cli('request system zeroize')
ret['message'] = 'Com... |
python | def Version():
"""Gets the version of gdb as a 3-tuple.
The gdb devs seem to think it's a good idea to make --version
output multiple lines of welcome text instead of just the actual version,
so we ignore everything it outputs after the first line.
Returns:
The installed version of gdb in the... |
java | public Opt<String> assist(String commandLine) {
try {
return doAssist(commandLine);
} catch (ParseException e) {
handleParseException(e);
} catch (Exception e) {
err.printThrowable(e);
}
return Opt.absent();
} |
python | def parse(self, limit=None):
"""
Override Source.parse()
Args:
:param limit (int, optional) limit the number of rows processed
Returns:
:return None
"""
if limit is not None:
LOG.info("Only parsing first %d rows", limit)
protei... |
python | def specify_data_set(self, x_input, y_input, sort_data=False):
"""
Fully define data by lists of x values and y values.
This will sort them by increasing x but remember how to unsort them for providing results.
Parameters
----------
x_input : iterable
list o... |
python | def _construct_columns(self, column_map):
''' a helper method for constructing the column objects for a table object '''
from sqlalchemy import Column, String, Boolean, Integer, Float, Binary
column_args = []
for key, value in column_map.items():
recor... |
python | def image_path_processor_factory(path):
""" Processor for concatenating the ``path`` to relative path images """
def processor(line):
markup = ".. image::"
if line.startswith(markup):
fname = line[len(markup):].strip()
if not(fname.startswith("/") or "://" in fname):
return "{} {}{}".for... |
python | def insertFileParents(self, businput):
"""
This is a special function for WMAgent only.
input block_name: is a child block name.
input chils_parent_id_list: is a list of file id of child, parent pair: [[cid1, pid1],[cid2,pid2],[cid3,pid3],...]
The requirment for this API... |
java | @SafeVarargs
public static Boolean[] box(final boolean... a) {
if (a == null) {
return null;
}
return box(a, 0, a.length);
} |
python | def clear(self):
"""
Cleans up the manager. The manager can't be used after this method has
been called
"""
self.reference = None
self._pending_ref = None
super(SimpleDependency, self).clear() |
python | def chords(chord_labels, intervals, fs, **kwargs):
"""Synthesizes chord labels
Parameters
----------
chord_labels : list of str
List of chord label strings.
intervals : np.ndarray, shape=(len(chord_labels), 2)
Start and end times of each chord label
fs : int
Sampling rat... |
java | public void setHlsManifests(java.util.Collection<HlsManifest> hlsManifests) {
if (hlsManifests == null) {
this.hlsManifests = null;
return;
}
this.hlsManifests = new java.util.ArrayList<HlsManifest>(hlsManifests);
} |
java | protected byte[] readByteArray(InputStream is, int size) throws IOException
{
byte[] buffer = new byte[size];
if (is.read(buffer) != buffer.length)
{
throw new EOFException();
}
return (buffer);
} |
java | private ClassInfo classInfoFromMetaBean(MetaBean metaBean, Class<?> aClass) {
MetaProperty<?>[] metaProperties = StreamSupport.stream(metaBean.metaPropertyIterable().spliterator(), false)
.filter(metaProp -> settings.isSerialized(metaProp))
.toArray(MetaProperty<?>[]::new);
// P... |
python | def split_in_blocks(sequence, hint, weight=lambda item: 1, key=nokey):
"""
Split the `sequence` in a number of WeightedSequences close to `hint`.
:param sequence: a finite sequence of items
:param hint: an integer suggesting the number of subsequences to generate
:param weight: a function returning... |
java | public int unshift(Object obj) {
if (obj instanceof JavascriptObject) {
//jsObject.setSlot(length(), ((JavascriptObject) obj).getJSObject());
content.put(((JavascriptObject) obj).getJSObject(), (JavascriptObject) obj);
}
return checkInteger(invokeJavascript("unshift", obj... |
python | def get_module_source_path(modname, basename=None):
"""Return module *modname* source path
If *basename* is specified, return *modname.basename* path where
*modname* is a package containing the module *basename*
*basename* is a filename (not a module name), so it must include the
file ex... |
java | public void add(Featurable featurable)
{
featurables.put(featurable.getFeature(Identifiable.class).getId(), featurable);
for (final Class<?> type : featurable.getClass().getInterfaces())
{
addType(type, featurable);
}
for (final Class<? extends Feature>... |
java | @Override
public List<String> getInjectionClasses(Container moduleContainer) {
try {
if (!JaxRsUtils.isWebModule(moduleContainer)) {
return Collections.<String> emptyList();
}
return InjectionUtils.getJaxRsInjectionClasses(moduleContainer);
} catc... |
python | def solid_angle(center, coords):
"""
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.