language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def find_matching_endpoints(self, swagger_ns):
"""
Compute current matching endpoints.
Evaluated as a property to defer evaluation.
"""
def match_func(operation, ns, rule):
# only expose endpoints that have the correct path prefix and operation
return (
... |
python | def parse_temperature_response(
temperature_string: str) -> Mapping[str, Optional[float]]:
'''
Example input: "T:none C:25"
'''
err_msg = 'Unexpected argument to parse_temperature_response: {}'.format(
temperature_string)
if not temperature_string or \
not isinstance(temp... |
python | def dump_registers_peek(registers, data, separator = ' ', width = 16):
"""
Dump data pointed to by the given registers, if any.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
This value is returned by L{Thread.get... |
python | def _set_port_channel_redundancy_group(self, v, load=False):
"""
Setter method for port_channel_redundancy_group, mapped from YANG variable /port_channel_redundancy_group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_channel_redundancy_group is considered a... |
java | @Override
public JsonElement serialize(Duration src, Type typeOfSrc, JsonSerializationContext context)
{
return new JsonPrimitive(src.toString());
} |
python | def error_leader(self, infile=None, lineno=None):
"Emit a C-compiler-like, Emacs-friendly error-message leader."
if infile is None:
infile = self.infile
if lineno is None:
lineno = self.lineno
return "\"%s\", line %d: " % (infile, lineno) |
java | private void nextFromPrologBang(boolean isProlog)
throws XMLStreamException
{
int i = getNext();
if (i < 0) {
throwUnexpectedEOF(SUFFIX_IN_PROLOG);
}
if (i == 'D') { // Doctype declaration?
String keyw = checkKeyword('D', "DOCTYPE");
if (ke... |
java | private void forward() {
try {
CmsDbSettingsPanel panel = m_panel[0];
panel.saveToSetupBean();
boolean createDb = panel.getCreateDb();
boolean dropDb = panel.getDropDb();
boolean createTables = panel.getCreateTables();
setupDb(createDb, c... |
python | def load(cls, filename=None):
"""Load a test report configuration."""
if filename is None:
LOGGER.debug("Loading default configuration.")
with open_text(templates, "test_config.yml",
encoding="utf-8") as file_handle:
content = yaml.load(... |
python | def compute_topk_scores_and_seq(sequences,
scores,
scores_to_gather,
flags,
beam_size,
batch_size,
prefix="default",
... |
python | def register(self, callback, name):
'Register a callback on server and on connected clients.'
server.CALLBACKS[name] = callback
self.run('''
window.skink.%s = function(args=[]) {
window.skink.call("%s", args);
}''' % (name, name)) |
java | public final boolean isTransactional() {
// Take a snapshot of the value with first use (or reuse from pool) of the managed connection.
// This value will be cleared when the managed connection is returned to the pool.
if (transactional == null) {
transactional = mcf.dsConfig.get().t... |
python | def sendToReplica(self, msg, frm):
"""
Send the message to the intended replica.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
# TODO: discard or stash messages here instead of doing
# this in msgHas* methods!!!
... |
java | public static void bufferedToGray(DataBufferUShort buffer , WritableRaster src, GrayI16 dst) {
short[] srcData = buffer.getData();
int numBands = src.getNumBands();
int size = dst.getWidth() * dst.getHeight();
int srcStride = stride(src);
int srcOffset = getOffset(src);
int srcStrideDiff = srcStride-src.... |
java | public int size() {
int size = cleared ? 0 : snapshot.size();
for ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) {
switch ( op.getValue().getType() ) {
case PUT:
if ( cleared || !snapshot.containsKey( op.getKey() ) ) {
size++;
}
break;
case REMOVE:
if ( ... |
java | public UpdateEventConfigurationsRequest withEventConfigurations(java.util.Map<String, Configuration> eventConfigurations) {
setEventConfigurations(eventConfigurations);
return this;
} |
java | String readNonEscaped() throws IOException {
StringBuilder s = new StringBuilder();
do {
int c = reader.read();
if (c < 0) {
return s.toString().trim();
}
if (c == SEPARATOR || c == '\n') {
reader.unread(c);
return s.toString().trim();
} else {
s.append((char) c);
}
} while (true... |
java | public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int n = input.read(buf); n != -1; n = input.read(buf)) {
os.write(buf, 0, n);
}
return os.toByteArray();
... |
java | @SuppressWarnings("unchecked")
private static <T> T newInstance(Class<?> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new ServiceException("Cannot instantiate service class " + type, e);
}
} |
python | async def container_size(
self, container_len=None, container_type=None, params=None
):
"""
Container size
:param container_len:
:param container_type:
:param params:
:return:
"""
if hasattr(container_type, "serialize_archive"):
... |
java | public static base_responses add(nitro_service client, lbmonitor resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
lbmonitor addresources[] = new lbmonitor[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new lbmonitor(... |
java | private int getInitialPartitionCount() throws IllegalAccessException
{
AppointerState currentState = m_state.get();
if (currentState != AppointerState.INIT && currentState != AppointerState.CLUSTER_START) {
throw new IllegalAccessException("Getting cached partition count after cluster " ... |
python | def _netbsd_interfaces_ifconfig(out):
'''
Uses ifconfig to return a dictionary of interfaces with various information
about each (up/down state, ip address, netmask, and hwaddr)
'''
ret = dict()
piface = re.compile(r'^([^\s:]+)')
pmac = re.compile('.*?address: ([0-9a-f:]+)')
pip = re.c... |
java | public int getDays() {
switch (_units) {
case Days:
return _amount;
case Weeks:
return _amount * 7;
case Months:
if (_amount <= 1)
return _amount * 30;
else if (_amount < 12)
return (_amount * 61) / 2;
else
return (_amount * 365) / 12;
default:
throw new UnsupportedOperationExcep... |
java | public boolean add(ByteBuf buf) {
if (count == IOV_MAX) {
// No more room!
return false;
} else if (buf.nioBufferCount() == 1) {
final int len = buf.readableBytes();
if (len == 0) {
return true;
}
if (buf.hasMemoryAd... |
python | def get_smart_task(self, task_id):
"""
Return specified transition.
Returns a Command.
"""
def process_result(result):
return SmartTask(self, result)
return Command('get', [ROOT_SMART_TASKS, task_id],
process_result=process_result) |
python | def fmt_second(time_total):
"""
>>> fmt_second(100)
'00:01:40'
"""
def _ck(t):
return t < 10 and "0%s" % t or t
times = int(time_total)
h = times / 3600
m = times % 3600 / 60
s = times % 3600 % 60
return "%s:%s:%s" % (_ck(h), _ck(m), _ck(s)) |
java | @SuppressWarnings("unchecked")
@Override
public EList<IfcCovering> getRelatedCoverings() {
return (EList<IfcCovering>) eGet(Ifc4Package.Literals.IFC_REL_COVERS_SPACES__RELATED_COVERINGS, true);
} |
java | public static void badConversion(Field destinationField, Class<?> destinationClass, Field sourceField, Class<?> sourceClass,String plus){
throw new UndefinedMappingException(MSG.INSTANCE.message(undefinedMappingException,destinationField.getName(),destinationClass.getSimpleName(),sourceField.getName(),sourceClass.ge... |
java | @Nullable
public static Resource mergeResources(List<Resource> resources) {
Resource currentResource = null;
for (Resource resource : resources) {
currentResource = merge(currentResource, resource);
}
return currentResource;
} |
python | def with_name(self, name):
"""Return a new path with the file name changed."""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name]) |
java | @SuppressWarnings("unchecked")
public EList<IfcClassificationNotationSelect> getRelatedClassifications() {
return (EList<IfcClassificationNotationSelect>) eGet(
Ifc2x3tc1Package.Literals.IFC_CONSTRAINT_CLASSIFICATION_RELATIONSHIP__RELATED_CLASSIFICATIONS, true);
} |
java | public static SameDiff fromFlatBuffers(ByteBuffer bbIn) throws IOException {
FlatGraph fg = FlatGraph.getRootAsFlatGraph(bbIn);
int numOps = fg.nodesLength();
int numVars = fg.variablesLength();
List<FlatNode> ops = new ArrayList<>(numOps);
for( int i=0; i<numOps; i++ ){
... |
python | def _path(self, s):
"""Parse a path."""
if s.startswith(b'"'):
if not s.endswith(b'"'):
self.abort(errors.BadFormat, '?', '?', s)
else:
return _unquote_c_string(s[1:-1])
return s |
java | public static Workbook createBook(boolean isXlsx) {
Workbook workbook;
if (isXlsx) {
workbook = new XSSFWorkbook();
} else {
workbook = new org.apache.poi.hssf.usermodel.HSSFWorkbook();
}
return workbook;
} |
java | @SuppressWarnings("PMD.UseStringBufferForStringAppends")
public static String getContextMarkers(final AdminContext context) {
String res = "";
if (isForAdmin(context)) {
if (isForMain(context)) {
res += "M";
}
res += "A";
}
return r... |
java | public static Object newInstance(Class type) {
Constructor _constructor = null;
Object[] _constructorArgs = new Object[0];
try {
_constructor = type.getConstructor(new Class[] {});// 先尝试默认的空构造函数
} catch (NoSuchMethodException e) {
// ignore
}
if (... |
java | boolean shouldCollect(@NonNull Context context, @NonNull CoreConfiguration config, @NonNull ReportField collect, @NonNull ReportBuilder reportBuilder) {
return config.reportContent().contains(collect);
} |
python | def tagify(suffix='', prefix='', base=SALT):
'''
convenience function to build a namespaced event tag string
from joining with the TABPART character the base, prefix and suffix
If string prefix is a valid key in TAGS Then use the value of key prefix
Else use prefix string
If suffix is a list T... |
python | def applicant(self, column=None, value=None, **kwargs):
"""
Find the applicant information for a grant.
>>> GICS().applicant('zip_code', 94105)
"""
return self._resolve_call('GIC_APPLICANT', column, value, **kwargs) |
java | public String addLock(Session session, String path) throws LockException
{
String repoPath = session.getRepository().hashCode() + "/" + session.getWorkspace().getName() + "/" + path;
if (!nullResourceLocks.containsKey(repoPath))
{
String newLockToken = IdGenerator.generate();
... |
java | @Pure
public Iterable<RoadSegment> roadSegments() {
return new Iterable<RoadSegment>() {
@Override
public Iterator<RoadSegment> iterator() {
return roadSegmentsIterator();
}
};
} |
python | def build_model(self, n_features, n_classes):
"""Create the computational graph.
:param n_features: number of features
:param n_classes: number of classes
:return: self
"""
self._create_placeholders(n_features, n_classes)
self._create_variables(n_features, n_clas... |
java | private String computeEventDescriptor(Method method)
{
StringBuilder sb = new StringBuilder();
// Add event class and method name
sb.append(method.getDeclaringClass().getName());
sb.append(".");
sb.append(method.getName());
// Add event arguments
Class [] pa... |
java | @Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
try {
switch (req.method()) {
case OPTIONS:
return doOptions(ctx, req);
case GET:
return doGet(ctx, req);
cas... |
java | public Map<String, Object> evaluateVerifyCredentialsResponse(String responseBody) {
String endpoint = TwitterConstants.TWITTER_ENDPOINT_VERIFY_CREDENTIALS;
Map<String, Object> responseValues = null;
try {
responseValues = populateJsonResponse(responseBody);
} catch (JoseExce... |
java | public void makeSpace(int sizeNeeded) {
int needed = count + sizeNeeded - buf.length;
if (needed > 0) {
bump(needed);
}
} |
java | public static PactDslJsonRootValue stringType(String example) {
PactDslJsonRootValue value = new PactDslJsonRootValue();
value.setValue(example);
value.setMatcher(TypeMatcher.INSTANCE);
return value;
} |
python | def predict(self, Xnew, full_cov=False, Y_metadata=None, kern=None,
likelihood=None, include_likelihood=True):
"""
Predict the function(s) at the new point(s) Xnew. This includes the
likelihood variance added to the predicted underlying function
(usually referred to as f)... |
python | def encode_date_optional_time(obj):
"""
ISO encode timezone-aware datetimes
"""
if isinstance(obj, datetime.datetime):
return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ')
raise TypeError("{0} is not JSON serializable".format(repr(obj))) |
python | def discard_until(fd, s, deadline):
"""Read chunks from `fd` until one is encountered that ends with `s`. This
is used to skip output produced by ``/etc/profile``, ``/etc/motd`` and
mandatory SSH banners while waiting for :attr:`Stream.EC0_MARKER` to
appear, indicating the first stage is ready to receiv... |
python | def show_system_monitor_output_switch_status_component_status_component_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_system_monitor = ET.Element("show_system_monitor")
config = show_system_monitor
output = ET.SubElement(show_system_m... |
java | @Override
public String toImplementationClassName(final String className) {
final String implementationClassName = interfaceToImplementationMap.get(className);
if (implementationClassName != null) {
return implementationClassName;
}
final int index = className.lastIndexOf... |
java | @POST
@Path("{id}/email/confirm")
@PermitAll
public Response confirmChangeEmail(@PathParam("id") Long userId, EmailRequest request) {
checkNotNull(userId);
checkNotNull(request.getToken());
boolean isSuccess = userService.confirmEmailAddressChangeUsingToken(userId, request.getToken());
return isS... |
python | def set_warning_handler(codec, handler, data=None):
"""Wraps openjp2 library function opj_set_warning_handler.
Set the warning handler use by openjpeg.
Parameters
----------
codec : CODEC_TYPE
Codec initialized by create_compress function.
handler : python function
The callback... |
java | public List executeQuery(String query, EntityMetadata m, KunderaQuery kunderaQuery)
{
DataFrame dataFrame = getDataFrame(query, m, kunderaQuery);
// dataFrame.show();
return dataHandler.loadDataAndPopulateResults(dataFrame, m, kunderaQuery);
} |
python | def IntegerLike(msg=None):
'''
Checks whether a value is:
- int, or
- long, or
- float without a fractional part, or
- str or unicode composed only of digits
'''
def fn(value):
if not any([
isinstance(value, numbers.Integral),
(isinstance(v... |
java | public static ZonedDateTime from(TemporalAccessor temporal) {
if (temporal instanceof ZonedDateTime) {
return (ZonedDateTime) temporal;
}
try {
ZoneId zone = ZoneId.from(temporal);
if (temporal.isSupported(INSTANT_SECONDS)) {
long epochSecond =... |
java | int ingestFSEdits() throws IOException {
FSDirectory fsDir = fsNamesys.dir;
int numEdits = 0;
long recentOpcodeOffsets[] = new long[2];
Arrays.fill(recentOpcodeOffsets, -1);
EnumMap<FSEditLogOpCodes, Holder<Integer>> opCounts =
new EnumMap<FSEditLogOpCodes, Holder<Integer>>(FSEditLogOpC... |
java | protected void redirectToReferrer(String defaultReference) {
String referrer = context.requestHeader("Referer");
referrer = referrer == null? defaultReference: referrer;
redirect(referrer);
} |
java | @Override
public AttributeDefinition[] getAttributeDefinitions(int filter) {
List<AttributeDefinition> adList;
if (filter == ObjectClassDefinition.ALL) {
adList = new ArrayList<AttributeDefinition>(requiredAttributeDefinitions.size() + optionalAttributeDefinitions.size());
ad... |
java | public void addData(byte[] data) throws InternalLogException
{
if (tc.isEntryEnabled()) Tr.entry(tc, "addData",new java.lang.Object[] {RLSUtils.toHexString(data,RLSUtils.MAX_DISPLAY_BYTES), this});
// If the parent recovery log instance has experienced a serious internal error then prevent
// this operat... |
java | public void listAll(final String orderBy, final SuccessCallback<List<T>> successCallback, final ErrorCallback errorCallback) {
checkNotNull(successCallback);
checkNotNull(errorCallback);
final Callable<List<T>> call = new Callable<List<T>>() {
@Override
public List<T> ca... |
python | def generate_VJ_junction_transfer_matrices(self):
"""Compute the transfer matrices for the VJ junction.
Sets the attributes Tvj, Svj, Dvj, lTvj, and lDvj.
"""
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
#Compute Tvj
Tv... |
java | public Transliterator safeClone() {
UnicodeFilter filter = getFilter();
if (filter != null && filter instanceof UnicodeSet) {
filter = new UnicodeSet((UnicodeSet)filter);
}
return new AnyTransliterator(getID(), filter, target, targetScript, widthFix, cache);
} |
java | public static boolean skipUntil(InputStream in, byte separator) throws IOException {
int r;
while((r = in.read()) >= 0) {
if(((byte) r) == separator) { return true; }
}
return false;
} |
python | def _swap_rows(self, i, j):
"""Swap i and j rows
As the side effect, determinant flips.
"""
L = np.eye(3, dtype='intc')
L[i, i] = 0
L[j, j] = 0
L[i, j] = 1
L[j, i] = 1
self._L.append(L.copy())
self._A = np.dot(L, self._A) |
python | def _handle_switch(self, node, scope, ctxt, stream):
"""Handle break node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
def exec_case(idx, cases):
# keep executing cases until a break is found,
# or they've... |
java | private String buildReportChapter(final BuildData buildData) {
log.info("\tBuilding Report Chapter");
final ContentSpec contentSpec = buildData.getContentSpec();
final String locale = buildData.getBuildLocale();
final ZanataDetails zanataDetails = buildData.getZanataDetails();
... |
java | public void reset(AccessibilityNodeInfoRef newNode) {
reset(newNode.get());
mOwned = newNode.mOwned;
newNode.mOwned = false;
} |
python | def format_entry(record, show_level=False, colorize=False):
"""
Format a log entry according to its level and context
"""
if show_level:
log_str = u'{}: {}'.format(record.levelname, record.getMessage())
else:
log_str = record.getMessage()
if colorize and record.levelname in LOG_... |
java | public void createEnterpriseCustomFieldMap(Props props, Class<?> c)
{
byte[] fieldMapData = null;
for (Integer key : ENTERPRISE_CUSTOM_KEYS)
{
fieldMapData = props.getByteArray(key);
if (fieldMapData != null)
{
break;
}
}
if (fieldMapData... |
python | def nice_repr(name, param_kvs, line_width=30, line_offset=5, decimals=3, args=None, flatten_attrs=True):
"""
tool to do a nice repr of a class.
Parameters
----------
name : str
class name
param_kvs : dict
dict containing class parameters names as keys,
and the correspond... |
java | public void getDescriptorsInRegion(int pixelX0 , int pixelY0 , int pixelX1 , int pixelY1 ,
List<TupleDesc_F64> output ) {
int gridX0 = (int)Math.ceil(pixelX0/(double) pixelsPerCell);
int gridY0 = (int)Math.ceil(pixelY0/(double) pixelsPerCell);
int gridX1 = pixelX1/ pixelsPerCell - cellsPerBlockX;
i... |
python | def add_equipamento_remove(self, id, id_ip, ids_ips_vips):
'''Adiciona um equipamento na lista de equipamentos para operação de remover um grupo virtual.
:param id: Identificador do equipamento.
:param id_ip: Identificador do IP do equipamento.
:param ids_ips_vips: Lista com os identifi... |
java | @Nonnull
public static <T> PredicateBuilder<T> predicate(Consumer<Predicate<T>> consumer) {
return new PredicateBuilder(consumer);
} |
java | public com.squareup.okhttp.Call getCorporationsCorporationIdContractsAsync(Integer corporationId,
String datasource, String ifNoneMatch, Integer page, String token,
final ApiCallback<List<CorporationContractsResponse>> callback) throws ApiException {
com.squareup.okhttp.Call call = getC... |
java | public Response leave(String groupId, boolean deletePhotos) throws JinxException {
JinxUtils.validateParams(groupId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.groups.leave");
params.put("group_id", groupId);
if (deletePhotos) {
params.put("delete_photos", "tru... |
java | List<Type> erasedSupertypes(Type t) {
ListBuffer<Type> buf = new ListBuffer<>();
for (Type sup : closure(t)) {
if (sup.hasTag(TYPEVAR)) {
buf.append(sup);
} else {
buf.append(erasure(sup));
}
}
... |
java | protected static void appendEntityNode(String alias, EntityKeyMetadata entityKeyMetadata, StringBuilder queryBuilder) {
appendEntityNode( alias, entityKeyMetadata, queryBuilder, 0 );
} |
python | def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
# No explicit ... |
java | public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
LogicExpression<String> expr = LogicExpressionParsers.trivial.parse(line);
System.out.println("string: " + expr.toString());
... |
python | def LateBind(self, target=None):
"""Late binding callback.
This method is called on this field descriptor when the target RDFValue
class is finally defined. It gives the field descriptor an opportunity to
initialize after the point of definition.
Args:
target: The target nested class.
R... |
python | def get_ilo_firmware_version_as_major_minor(self):
"""Gets the ilo firmware version for server capabilities
:returns: String with the format "<major>.<minor>" or None.
"""
try:
manager, reset_uri = self._get_ilo_details()
ilo_fw_ver_str = (
manag... |
java | public BatchGetNamedQueryResult withNamedQueries(NamedQuery... namedQueries) {
if (this.namedQueries == null) {
setNamedQueries(new java.util.ArrayList<NamedQuery>(namedQueries.length));
}
for (NamedQuery ele : namedQueries) {
this.namedQueries.add(ele);
}
... |
java | public static Bitmap colorToBitmap(final int width, final int height,
@ColorInt final int color) {
Condition.INSTANCE.ensureAtLeast(width, 1, "The width must be at least 1");
Condition.INSTANCE.ensureAtLeast(height, 1, "The height must be at least 1");
Bitm... |
python | def dimensions(self):
"""Get width and height of a PDF"""
size = self.pdf.getPage(0).mediaBox
return {'w': float(size[2]), 'h': float(size[3])} |
python | def subsample(self, down_to=1, new_path=None):
"""Pick a number of sequences from the file pseudo-randomly."""
# Auto path #
if new_path is None: subsampled = self.__class__(new_temp_path())
elif isinstance(new_path, FASTA): subsampled = new_path
else: subsampled =... |
java | public static void listHandlers( List<IMonitoringHandler> handlers, Logger logger ) {
if( handlers.isEmpty()) {
logger.info( "No monitoring handler was found." );
} else {
StringBuilder sb = new StringBuilder( "Available monitoring handlers: " );
for( Iterator<IMonitoringHandler> it = handlers.iterator()... |
java | private void checkReferenceForeignkeys(ModelDef modelDef, ReferenceDescriptorDef refDef) throws ConstraintException
{
String foreignkey = refDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
if ((foreignkey == null) || (foreignkey.length() == 0))
{
throw new Constra... |
java | protected void callChildVisitors(XSLTVisitor visitor, boolean callAttrs)
{
if(callAttrs)
{
if(null != m_name_avt)
m_name_avt.callVisitors(visitor);
if(null != m_namespace_avt)
m_namespace_avt.callVisitors(visitor);
}
super.callChildVisitors(visitor, callAttrs);
} |
python | def highest_minor(python_versions):
'''Return highest minor of a list of stable (semantic) versions.
Example:
>>> python_versions = [
... '2.6.9', '2.7.14', '3.3.7', '3.4.8', '3.5.5', '3.6.4']
>>> highest_minor(python_versions)
'3.6'
'''
highest = python_versions[-1... |
python | def cable_from_row(row):
"""\
Returns a cable from the provided row (a tuple/list).
Format of the row:
<identifier>, <creation-date>, <reference-id>, <origin>, <classification-level>, <references-to-other-cables>, <header>, <body>
Note:
The `<identifier>` and `<references-to-other-cab... |
java | public void queryEvents(@NonNull final String conversationId, @NonNull final Long from, @NonNull final Integer limit, @Nullable Callback<ComapiResult<EventsQueryResponse>> callback) {
adapter.adapt(queryEvents(conversationId, from, limit), callback);
} |
python | def to_jacobian(self):
"""
Converts this point to a Jacobian representation.
Returns:
JacobianPoint: The Jacobian representation.
"""
if not self:
return JacobianPoint(X=0, Y=0, Z=0)
return JacobianPoint(X=self.X, Y=self.Y, Z=1) |
java | public void setConstraints(Component component, CellConstraints constraints) {
checkNotNull(component, "The component must not be null.");
checkNotNull(constraints, "The constraints must not be null.");
constraints.ensureValidGridBounds(getColumnCount(), getRowCount());
constraintMap.put... |
python | def missing_output_files(self):
"""Make and return a dictionary of the missing output files.
This returns a dictionary mapping
filepath to list of links that produce the file as output.
"""
missing = self.check_output_files(return_found=False)
ret_dict = {}
for m... |
python | async def run_action(self, action_name, **params):
"""Run an action on this unit.
:param str action_name: Name of action to run
:param **params: Action parameters
:returns: A :class:`juju.action.Action` instance.
Note that this only enqueues the action. You will need to call
... |
python | def add_song(fpath, g_songs, g_artists, g_albums):
"""
parse music file metadata with Easymp3 and return a song
model.
"""
try:
if fpath.endswith('mp3') or fpath.endswith('ogg') or fpath.endswith('wma'):
metadata = EasyMP3(fpath)
elif fpath.endswith('m4a'):
me... |
python | def do_reload(module: types.ModuleType, newer_than: int) -> bool:
"""
Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.