language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def pop(self) -> Square:
"""
Removes a square from the set and returns it.
:raises: :exc:`KeyError` on an empty set.
"""
if not self.mask:
raise KeyError("pop from empty SquareSet")
square = lsb(self.mask)
self.mask &= (self.mask - 1)
return ... |
java | protected void setObjects(PreparedStatement ps, Object... objects)
throws SQLException {
int index = 1;
for (Object obj : objects) {
ps.setObject(index, obj);
index++;
}
} |
java | @Nonnull
public final <B> ImmutableList<B> bind(@Nonnull F<A, ImmutableList<B>> f) {
return this.flatMap(f);
} |
java | public void setAddresses(java.util.Collection<Address> addresses) {
if (addresses == null) {
this.addresses = null;
return;
}
this.addresses = new com.amazonaws.internal.SdkInternalList<Address>(addresses);
} |
java | public static void copyFile(File fromFile, File toFile) throws IOException {
copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile));
} |
java | @Override
public void close() throws TTIOException {
try {
mService.shutdown();
mService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException exc) {
throw new TTIOException(exc);
}
mFirstWriter.close();
mSecondWriter.close(... |
python | def parse_bed(bed_file):
"""Import a BED file (where the data entries are analogous to what may be
expected in an info_frags.txt file) and return a scaffold dictionary,
similarly to parse_info_frags.
"""
new_scaffolds = {}
with open(bed_file) as bed_handle:
for line in bed_handle:
... |
java | public void marshall(UpdateTrailRequest updateTrailRequest, ProtocolMarshaller protocolMarshaller) {
if (updateTrailRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateTrailRequest.getNam... |
java | @SneakyThrows
public static Resource prepareClasspathResourceIfNeeded(final Resource resource,
final boolean isDirectory,
final String containsName) {
LOGGER.trace("Preparing possible clas... |
java | public SpatialReferenceSystem queryForOrganizationCoordsysId(
String organization, long organizationCoordsysId)
throws SQLException {
SpatialReferenceSystem srs = null;
QueryBuilder<SpatialReferenceSystem, Long> qb = queryBuilder();
qb.where().like(SpatialReferenceSystem.COLUMN_ORGANIZATION,
organizati... |
python | def _query_filter(search, urlkwargs, definitions):
"""Ingest query filter in query."""
filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions)
for filter_ in filters:
search = search.filter(filter_)
return (search, urlkwargs) |
java | public <T0, T1> DataSource<Tuple2<T0, T1>> types(Class<T0> type0, Class<T1> type1) {
TupleTypeInfo<Tuple2<T0, T1>> types = TupleTypeInfo.getBasicTupleTypeInfo(type0, type1);
CsvInputFormat<Tuple2<T0, T1>> inputFormat = new CsvInputFormat<Tuple2<T0, T1>>(path);
configureInputFormat(inputFormat, type0, type1);
re... |
java | public static int unsignedUnion2by2(
final short[] set1, final int offset1, final int length1,
final short[] set2, final int offset2, final int length2,
final short[] buffer) {
if (0 == length2) {
System.arraycopy(set1, offset1, buffer, 0, length1);
return length1;
}
... |
java | public void marshall(UnsubscribeFromDatasetRequest unsubscribeFromDatasetRequest, ProtocolMarshaller protocolMarshaller) {
if (unsubscribeFromDatasetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.m... |
java | public static String getValueFromStaticMapping(String mapping, String key) {
Map<String, String> m = Splitter.on(";")
.omitEmptyStrings()
.trimResults()
.withKeyValueSeparator("=")
.split(mapping);
return m.get(key);
} |
java | public static void main(final String[] args)
{
for (int i = 0; i < 10; i++)
{
perfTestEncode(i);
perfTestDecode(i);
}
} |
java | public static <K,V> Level0MapOperator<Map<K,V>,K,V> on(final Map<K,V> target) {
return onMap(target);
} |
python | def iter_multichunks(iterable, chunksizes, bordermode=None):
"""
CommandLine:
python -m utool.util_iter --test-iter_multichunks
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_iter import * # NOQA
>>> import utool as ut
>>> iterable = list(range(20))
>>> c... |
python | def build(self):
"""
Build the simulation components from the model.
@return: A runnable simulation object
@rtype: lems.sim.sim.Simulation
"""
self.sim = Simulation()
for component_id in self.model.targets:
if component_id not in self.model.componen... |
java | public static String serializeKeys(Set<String> foreignKeys)
{
if (null == foreignKeys || foreignKeys.isEmpty())
{
return null;
}
StringBuilder sb = new StringBuilder();
for (String key : foreignKeys)
{
if (sb.length() > 0)
... |
python | def remove_legend(self):
""" Removes legend actor """
if hasattr(self, 'legend'):
self.remove_actor(self.legend, reset_camera=False)
self._render() |
python | def cluster(self, dist_type='cosine', run_clustering=True,
dendro=True, views=['N_row_sum', 'N_row_var'],
linkage_type='average', sim_mat=False, filter_sim=0.1,
calc_cat_pval=False, run_enrichr=None, enrichrgram=None):
'''
The main function performs hierarchica... |
python | def save_as_pdf_pages(plots, filename=None, path=None, verbose=True, **kwargs):
"""
Save multiple :class:`ggplot` objects to a PDF file, one per page.
Parameters
----------
plots : collection or generator of :class:`ggplot`
Plot objects to write to file. `plots` may be either a
coll... |
java | public ServiceFuture<List<EventTypeInner>> listEventTypesAsync(String topicTypeName, final ServiceCallback<List<EventTypeInner>> serviceCallback) {
return ServiceFuture.fromResponse(listEventTypesWithServiceResponseAsync(topicTypeName), serviceCallback);
} |
python | def _read_openephys(openephys_file):
"""Read the channel labels and their respective files from the
'Continuous_Data.openephys' file
Parameters
----------
openephys_file : Path
path to Continuous_Data.openephys inside the open-ephys folder
Returns
-------
int
sampling f... |
python | def _parse_extra_args(self, api, extra_args_raw):
"""
Parses extra arguments into a map keyed on particular data types.
"""
extra_args = {}
def invalid(msg, extra_arg_raw):
print('Invalid --extra-arg:%s: %s' % (msg, extra_arg_raw),
file=sys.stderr)
... |
python | def throttle(self):
"""Uses time.monotonic() (or time.sleep() if not available) to limit to the desired rate. Should be called once
per iteration of action which is to be throttled. Returns None unless a custom wait_cmd was specified in the
constructor in which case its return value is used if a... |
python | def _remaining_points(hands):
'''
:param list hands: hands for which to compute the remaining points
:return: a list indicating the amount of points
remaining in each of the input hands
'''
points = []
for hand in hands:
points.append(sum(d.first + d.second for d in hand))
... |
python | def expand_config(dct,
separator='.',
skip_to=0,
key_func=lambda key: key.lower(),
key_parts_filter=lambda key_parts: True,
value_func=lambda value: value):
"""
Expand a dictionary recursively by splitting keys along the s... |
python | def dafgh():
"""
Return (get) the handle of the DAF currently being searched.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgh_c.html
:return: Handle for current DAF.
:rtype: int
"""
outvalue = ctypes.c_int()
libspice.dafgh_c(ctypes.byref(outvalue))
return outvalue.val... |
java | private void writeWBS(Task mpxj)
{
if (mpxj.getUniqueID().intValue() != 0)
{
WBSType xml = m_factory.createWBSType();
m_project.getWBS().add(xml);
String code = mpxj.getWBS();
code = code == null || code.length() == 0 ? DEFAULT_WBS_CODE : code;
Task parentTas... |
python | def limits(self, low, high):
"""
Convenience function for determining appropriate limits in the API. If
the (usually logged-in) client has the ``apihighlimits`` right, it will
return *high*; otherwise it will return *low*.
It's generally a good idea to use the highest limit poss... |
java | private List<String> getDomainsFromUrl(URL url) {
String host = url.getHost();
String[] paths = new String[] {};
if (url.getPath() != null) {
paths = url.getPath().split("/");
}
List<String> domains = new ArrayList<String>(paths.length + 1);
StringBuilder rela... |
java | public void copyFrom(FileItem file) throws IOException, InterruptedException {
if(channel==null) {
try {
file.write(writing(new File(remote)));
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);... |
python | def get_computers(self, filterTerm=None, domain=None):
"""
Return hosts from the database.
"""
cur = self.conn.cursor()
# if we're returning a single host by ID
if self.is_computer_valid(filterTerm):
cur.execute("SELECT * FROM computers WHERE id=? LIMIT 1", ... |
java | @BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
public final OperationFuture<Empty, Struct> restoreAgentAsync(RestoreAgentRequest request) {
return restoreAgentOperationCallable().futureCall(request);
} |
java | @Nonnull
public JSVar var (@Nonnull @Nonempty final String sName, final boolean bInitValue) throws JSNameAlreadyExistsException
{
return var (sName, JSExpr.lit (bInitValue));
} |
java | public ServiceFuture<ApplicationSecurityGroupInner> beginCreateOrUpdateAsync(String resourceGroupName, String applicationSecurityGroupName, ApplicationSecurityGroupInner parameters, final ServiceCallback<ApplicationSecurityGroupInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWithS... |
python | def c_Prada(z, m, h=h, Om_M=Om_M, Om_L=Om_L):
"""Concentration from c(M) relation published in Prada et al. (2012).
Parameters
----------
z : float or array_like
Redshift(s) of halos.
m : float or array_like
Mass(es) of halos (m200 definition), in units of solar masses.
h : floa... |
java | public Object getField(Object instance, String fieldname, boolean isStatic) throws IllegalAccessException {
FieldReaderWriter fieldReaderWriter = locateField(fieldname);
if (isStatic && !fieldReaderWriter.isStatic()) {
throw new IncompatibleClassChangeError("Expected static field "
+ fieldReaderWriter.theFi... |
python | def parseCCUSysVar(self, data):
"""Helper to parse type of system variables of CCU"""
if data['type'] == 'LOGIC':
return data['name'], data['value'] == 'true'
elif data['type'] == 'NUMBER':
return data['name'], float(data['value'])
elif data['type'] == 'LIST':
... |
python | def _set_adj_3way_state(self, v, load=False):
"""
Setter method for adj_3way_state, mapped from YANG variable /adj_neighbor_entries_state/adj_neighbor/adj_3way_state (isis-dcm-3way-adj-state)
If this variable is read-only (config: false) in the
source YANG file, then _set_adj_3way_state is considered as... |
python | def handle_form_submit(self):
"""Handle form submission
"""
protect.CheckAuthenticator(self.request)
logger.info("Handle ResultsInterpration Submit")
# Save the results interpretation
res = self.request.form.get("ResultsInterpretationDepts", [])
self.context.setRe... |
python | def drawSquiggle(self, p1, p2, breadth = 2):
"""Draw a squiggly line from p1 to p2.
"""
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad ... |
python | def reset(self, data, size):
"""
Set new contents for frame
"""
return lib.zframe_reset(self._as_parameter_, data, size) |
python | def chunks(arr, size):
"""Splits a list into chunks
:param arr: list to split
:type arr: :class:`list`
:param size: number of elements in each chunk
:type size: :class:`int`
:return: generator object
:rtype: :class:`generator`
"""
for i in _range(0, len(arr), size):
yield ar... |
python | def untrace_modules(self, modules):
"""
Untraces given modules.
:param modules: Modules to untrace.
:type modules: list
:return: Method success.
:rtype: bool
"""
for module in modules:
foundations.trace.untrace_module(module)
self.__m... |
python | def DecompressMessageList(cls, packed_message_list):
"""Decompress the message data from packed_message_list.
Args:
packed_message_list: A PackedMessageList rdfvalue with some data in it.
Returns:
a MessageList rdfvalue.
Raises:
DecodingError: If decompression fails.
"""
com... |
python | def get_dsdl_signature_source_definition(self):
"""
Returns normalized DSDL definition text.
Please refer to the specification for details about normalized DSDL definitions.
"""
txt = StringIO()
txt.write(self.full_name + '\n')
def adjoin(attrs):
retu... |
python | def main(_):
"""Run the sample attack"""
# Images for inception classifier are normalized to be in [-1, 1] interval,
# eps is a difference between pixels so it should be in [0, 2] interval.
# Renormalizing epsilon from [0, 255] to [0, 2].
eps = 2.0 * FLAGS.max_epsilon / 255.0
alpha = 2.0 * FLAGS.iter_alpha ... |
java | protected FieldMetadata createParameterizedFieldMetadataFrom( Type type ) {
FieldMetadata parameterizedTypeFieldMetadata = null;
if (type.isSimpleType()) {
SimpleType simpleType = (SimpleType)type;
parameterizedTypeFieldMetadata = FieldMetadata.parametrizedType(JavaMetadataUtil.g... |
python | def load_validation_plugin(name=None):
"""Find and load the chosen validation plugin.
Args:
name (string): the name of the entry_point, as advertised in the
setup.py of the providing package.
Returns:
an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules... |
java | @Override
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
return method.getAnnotation(annotationClass);
} |
java | public int getOntologyTermDistance(OntologyTerm ontologyTerm1, OntologyTerm ontologyTerm2) {
String nodePath1 = getOntologyTermNodePath(ontologyTerm1);
String nodePath2 = getOntologyTermNodePath(ontologyTerm2);
if (StringUtils.isEmpty(nodePath1)) {
throw new MolgenisDataAccessException(
"Th... |
python | def parse_hh_mm(self):
"""Parses raw time
:return: Time parsed
"""
split_count = self.raw.count(":")
if split_count == 1: # hh:mm
return datetime.strptime(self.raw, "%H:%M").time()
return datetime.strptime(self.raw, "%M").time() |
java | public static Pair<INDArray, INDArray> mergeLabels(@NonNull INDArray[][] labelsToMerge,
INDArray[][] labelMasksToMerge, int inOutIdx) {
Pair<INDArray[], INDArray[]> p = selectColumnFromMDSData(labelsToMerge, labelMasksToMerge, inOutIdx);
return mergeLabels(p.getFirst(), p.getSecond()... |
java | public static Calendar getDateCeil(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
return new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
} |
python | def getresponse(self):
"""Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :att... |
python | def query_relative(self, query, event_time=None, relative_duration_before=None, relative_duration_after=None):
"""Perform the query and calculate the time range based on the relative values."""
assert event_time is None or isinstance(event_time, datetime.datetime)
assert relative_duration_before... |
java | private Map<String, String[]> findAllFiles(Collection<String> pathsToScan, String[] includesPattern, Collection<String> excludes) {
Map<String, String[]> pathToIncludedFilesMap = new HashMap<>();
pathsToScan.stream().forEach(scanFolder -> {
String[] includedFiles = getDirectoryContent(new Fi... |
java | private List<ResolveTask> collectProcessingTopics(final Collection<FileInfo> fis, final KeyScope rootScope, final Document doc) {
final List<ResolveTask> res = new ArrayList<>();
final FileInfo input = job.getFileInfo(fi -> fi.isInput).iterator().next();
res.add(new ResolveTask(rootScope, input,... |
python | def forward_iter(self, X, training=False, device='cpu'):
"""Yield outputs of module forward calls on each batch of data.
The storage device of the yielded tensors is determined
by the ``device`` parameter.
Parameters
----------
X : input data, compatible with skorch.data... |
java | private ValueNumber[] popInputValues(int numWordsConsumed) {
ValueNumberFrame frame = getFrame();
ValueNumber[] inputValueList = allocateValueNumberArray(numWordsConsumed);
// Pop off the input operands.
try {
frame.getTopStackWords(inputValueList);
while (numWor... |
java | @Override
public List<SampleRowKeysResponse> sampleRowKeys(SampleRowKeysRequest request) {
if (shouldOverrideAppProfile(request.getAppProfileId())) {
request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build();
}
return createStreamingListener(request, sampleRowKeysAsync, reque... |
java | private static int _parseEndOfLine (@Nonnull final String sHeaderPart, final int nEnd)
{
int nIndex = nEnd;
for (;;)
{
final int nOffset = sHeaderPart.indexOf ('\r', nIndex);
if (nOffset == -1 || nOffset + 1 >= sHeaderPart.length ())
throw new IllegalStateException ("Expected headers t... |
java | @Override
public DescribeAgentsResult describeAgents(DescribeAgentsRequest request) {
request = beforeClientExecution(request);
return executeDescribeAgents(request);
} |
python | def _resolve_placeholder(placeholder, original):
"""Resolve a placeholder to the given original object.
:param placeholder: The placeholder to resolve, in place.
:type placeholder: dict
:param original: The object that the placeholder represents.
:type original: dict
"""
new = copy.deepcopy... |
python | def get_views(self, path, year=None, month=None, day=None, hour=None):
""" Get the number of views for a Telegraph article
:param path: Path to the Telegraph page
:param year: Required if month is passed. If passed, the number of
page views for the requested year will be r... |
java | @BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
public final OperationFuture<Instance, OperationMetadata> createInstanceAsync(
LocationName parent, String instanceId, Instance instance) {
CreateInstanceRequest request =
CreateInstanceReques... |
java | public long skip(long n) throws IOException {
synchronized (lock) {
ensureOpen();
long avail = count - pos;
if (n > avail) {
n = avail;
}
if (n < 0) {
return 0;
}
pos += n;
return n;
... |
java | @Override
public double getPopulationVariance() {
Variance populationVariance = new Variance(_getSecondMoment());
populationVariance.setBiasCorrected(false);
return populationVariance.getResult();
} |
python | def load(self, value):
""" enforce env > value when loading from file """
self.reset(
value,
validator=self.__dict__.get('validator'),
env=self.__dict__.get('env'),
) |
python | def lastmod(self, category):
"""Return the last modification of the entry."""
lastitems = EntryModel.objects.published().order_by('-modification_date').filter(categories=category).only('modification_date')
return lastitems[0].modification_date |
python | def getarchive(project, user, format=None):
"""Generates and returns a download package (or 403 if one is already in the process of being prepared)"""
if os.path.isfile(Project.path(project, user) + '.download'):
#make sure we don't start two compression processes at the same time
... |
java | public SpannableStringBuilder replace(final int start, final int end,
CharSequence tb, int tbstart, int tbend) {
checkRange("replace", start, end);
int filtercount = mFilters.length;
for (int i = 0; i < filtercount; i++) {
CharSequence repl = mFilters[i].filter(tb, tbsta... |
java | protected List fetch()
{
EntityMetadata metadata = getEntityMetadata();
Client client = persistenceDelegeator.getClient(metadata);
List results = isRelational(metadata) ? recursivelyPopulateEntities(metadata, client) : populateEntities(
metadata, client);
return resul... |
java | public void getAllMapNames(Callback<List<SimpleName>> callback) throws NullPointerException {
gw2API.getAllMapNames(GuildWars2.lang.getValue()).enqueue(callback);
} |
java | public static void printHelp(PrintStream stream) {
stream.println();
stream.println("Voldemort Admin Tool Async-Job Commands");
stream.println("---------------------------------------");
stream.println("list Get async job list from nodes.");
stream.println("stop Stop async jo... |
python | def _do_close(self):
"""
Tear down this object, after we've agreed to close with the server.
"""
AMQP_LOGGER.debug('Closed channel #%d' % self.channel_id)
self.is_open = False
del self.connection.channels[self.channel_id]
self.channel_id = self.connection = None
... |
java | @Pure
public static boolean intersectsSolidSphereOrientedBox(
double sphereCenterx, double sphereCentery, double sphereCenterz, double sphereRadius,
double boxCenterx, double boxCentery, double boxCenterz,
double boxAxis1x, double boxAxis1y, double boxAxis1z,
double boxAxis2x, double boxAxis2y, double boxA... |
python | def _add_index(self, index):
"""
Adds an index to the table.
:param index: The index to add
:type index: Index
:rtype: Table
"""
index_name = index.get_name()
index_name = self._normalize_identifier(index_name)
replaced_implicit_indexes = []
... |
java | @Override
public CreateAccountResult createAccount(CreateAccountRequest request) {
request = beforeClientExecution(request);
return executeCreateAccount(request);
} |
python | def _process_input(self, data, events):
"""
_process_input:
_process_input will be notified when there is data ready on the
serial connection to be read. It will read and process the data
into an API Frame and then either resolve a frame future, or push
the frame into t... |
python | async def get_friendly_name(self) -> Text:
"""
Let's use the first name of the user as friendly name. In some cases
the user object is incomplete, and in those cases the full user is
fetched.
"""
if 'first_name' not in self._user:
user = await self._get_full_... |
python | def _reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
"""
Same as `django.core.urlresolvers.reverse`, but optionally takes a request
and returns a fully qualified URL, using the request to get the base URL.
"""
if format is not None:
kwargs = kwargs or {}
... |
python | def dirty(field,ttl=None):
"decorator to cache the result of a function until a field changes"
if ttl is not None: raise NotImplementedError('pg.dirty ttl feature')
def decorator(f):
@functools.wraps(f)
def wrapper(self,*args,**kwargs):
# warning: not reentrant
d=self.dirty_cache[field]... |
java | public List executeNativeQuery(String jsonClause, EntityMetadata entityMetadata)
{
List entities = new ArrayList();
String[] tempArray = jsonClause.split("\\.");
String tempClause = tempArray[tempArray.length - 1];
if (tempClause.contains("findOne(") || tempClause.contains("findAndM... |
python | def nPr(n, r):
"""
Calculates nPr.
Args:
n (int): total number of items.
r (int): items to permute
Returns:
nPr.
"""
f = math.factorial
return int(f(n) / f(n-r)) |
python | def complete_offer(self, offer_id, complete_dict):
"""
Completes an offer
:param complete_dict: the complete dict with the template id
:param offer_id: the offer id
:return: Response
"""
return self._create_put_request(
resource=OFFERS,
bi... |
python | def delete(self, force_drop=False, *args, **kwargs):
"""
Deletes this row. Drops the tenant's schema if the attribute
auto_drop_schema set to True.
"""
if connection.schema_name not in (self.schema_name, get_public_schema_name()):
raise Exception("Can't delete tenant ... |
python | def _get_desired_pkg(name, desired):
'''
Helper function that retrieves and nicely formats the desired pkg (and
version if specified) so that helpful information can be printed in the
comment for the state.
'''
if not desired[name] or desired[name].startswith(('<', '>', '=')):
oper = ''
... |
java | public static void writeFullBeanXml(
Object object, OutputStream outputStream)
{
XMLEncoder encoder = XmlEncoders.createVerbose(outputStream);
encoder.setExceptionListener(new ExceptionListener()
{
@Override
public void exceptionThrown(Exception e)
... |
python | def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
"""
Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
root = ElementTree.fromstrin... |
java | private void checkCallConventions(NodeTraversal t, Node n) {
SubclassRelationship relationship =
compiler.getCodingConvention().getClassesDefinedByCall(n);
TypedScope scope = t.getTypedScope();
if (relationship != null) {
ObjectType superClass =
TypeValidator.getInstanceOfCtor(
... |
python | def add_missing(self, distribution, requirement):
"""
Add a missing *requirement* for the given *distribution*.
:type distribution: :class:`distutils2.database.InstalledDistribution`
or :class:`distutils2.database.EggInfoDistribution`
:type requirement: ``str... |
java | @Nullable
@Override
public final ImageFormat determineFormat(byte[] headerBytes, int headerSize) {
Preconditions.checkNotNull(headerBytes);
if (WebpSupportStatus.isWebpHeader(headerBytes, 0, headerSize)) {
return getWebpFormat(headerBytes, headerSize);
}
if (isJpegHeader(headerBytes, headerS... |
java | public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchChar, startPos);
} |
python | def _connect(self):
"""Connect to the server."""
assert get_thread_ident() == self.ioloop_thread_id
if self._stream:
self._logger.warn('Disconnecting existing connection to {0!r} '
'to create a new connection')
self._disconnect()
... |
python | def make_uninstall(parser):
"""
Remove Ceph packages from remote hosts.
"""
parser.add_argument(
'host',
metavar='HOST',
nargs='+',
help='hosts to uninstall Ceph from',
)
parser.set_defaults(
func=uninstall,
) |
java | public static Response execute(int maxBuffer, String ... command) {
if(command.length == 0){
throw new IllegalArgumentException("Command must be provided.");
}
String[] commandAndArgs = command.length == 1 && command[0].contains(" ") ? Util.split(command[0], " ") : command;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.