language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void send(Message message, TestContext context) {
String correlationKeyName = getEndpointConfiguration().getCorrelator().getCorrelationKeyName(getName());
String correlationKey = getEndpointConfiguration().getCorrelator().getCorrelationKey(message);
correlationManager.saveCorrelationKey(c... |
python | def filter(self, msg_type=None, maxsize=0):
"""
Get a filtered iterator of messages for synchronous, blocking use in
another thread.
"""
if self._dead:
return iter(())
iterator = Handler._SBPQueueIterator(maxsize)
# We use a weakref so that the iterato... |
python | def default_display(value, with_module=True):
"""Default display for unknown objects."""
object_type = type(value)
try:
name = object_type.__name__
module = object_type.__module__
if with_module:
return name + ' object of ' + module + ' module'
else:
r... |
java | public static RowMajorSparseMatrix fromCSV(String csv) {
return Matrix.fromCSV(csv).to(Matrices.SPARSE_ROW_MAJOR);
} |
python | def zincr(self, name, key, amount=1):
"""
Increase the score of ``key`` in zset ``name`` by ``amount``. If no key
exists, the value will be initialized as ``amount``
Like **Redis.ZINCR**
:param string name: the zset name
:param string key: the key name
:... |
java | public void addPlugin(String name, MoskitoPlugin plugin, PluginConfig config){
plugins.put(name, plugin);
try{
plugin.initialize();
configs.put(name, config);
}catch(Exception e){
log.warn("couldn't initialize plugin "+name+" - "+plugin+", removing", e);
plugins.remove(name);
}
} |
java | public void marshall(GetComplianceSummaryByConfigRuleRequest getComplianceSummaryByConfigRuleRequest, ProtocolMarshaller protocolMarshaller) {
if (getComplianceSummaryByConfigRuleRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
... |
python | def has_offline_historical_manager_or_raise(self):
"""Raises an exception if model uses a history manager and
historical model history_id is not a UUIDField.
Note: expected to use edc_model.HistoricalRecords instead of
simple_history.HistoricalRecords.
"""
try:
... |
java | @Override
protected void prepareGUI(Container container)
{
renderer = new SwingBiomorphRenderer();
console = new SwingConsole(5);
selectionDialog = new JDialog((JFrame) null, "Biomorph Selection", true);
biomorphHolder = new JPanel(new GridLayout(1, 1));
container.add(ne... |
java | static URL tryToGetValidUrl(String workingDir, String path, String filename) {
try {
if (new File(filename).exists())
return new File(filename).toURI().toURL();
if (new File(path + File.separator + filename).exists())
return new File(path + File.separator ... |
java | private JButton getBtnCapture() {
if (btnCapture == null) {
btnCapture = new JButton();
btnCapture.setText("Capture");
btnCapture.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
btnCapture.setHorizontalTextPosition(javax.swing.SwingConstants.TRAILING);
// btnCapture.setPreferredSize(new... |
java | public static Class<?> commonType(Class<?> baseType, Object fromValue, IntSupplier length) {
if ( Object.class != baseType )
return baseType;
Class<?> common = null;
int len = length.getAsInt();
for (int i = 0; i < len; i++)
if ( Object.class == (common = Types.ge... |
python | def insert(self, nodes, pos):
# TODO: check docstring
"""Inserts all nodes from `nodes` list into this route at position `pos`
Parameters
----------
nodes : type
Desc
pos : type
Desc
"""
node_list = []
... |
python | def get_by_addr(self, address):
"""
Lookup a set of notifications by address
Args:
address (UInt160 or str): hash of address for notifications
Returns:
list: a list of notifications
"""
addr = address
if isinstance(address, str) and len(ad... |
java | public static Object readUrl(Context cx, Scriptable thisObj, Object[] args,
Function funObj)
throws IOException
{
if (args.length == 0) {
throw reportRuntimeError("msg.shell.readUrl.bad.args");
}
String url = ScriptRuntime.toString(args[0]... |
python | def props_value(props):
"""
Properties value.
:param dict props:
Properties dictionary.
:rtype:
str
:return:
Properties as string.
"""
sep = ""
result_value = ""
for prop_key, prop_value in props.items():
result_value = "{}{}{}={}".format(
result_value,
sep,
prop_key,
prop_value
... |
python | def session(self):
"""
This is a session between the consumer (your website) and the provider
(e.g. Twitter). It is *not* a session between a user of your website
and your website.
:return:
"""
return self.session_class(
client_key=self.client_key,
... |
python | def get_JWT(url, address=None):
"""
Given a URL, fetch and decode the JWT it points to.
If address is given, then authenticate the JWT with the address.
Return None if we could not fetch it, or unable to authenticate it.
NOTE: the URL must be usable by the requests library
"""
jwt_txt = No... |
java | public boolean shouldDisplay(String operationId, PMSecurityUser user) {
if (operationId == null) {
return false;
}
//First we check permissions
for (FieldOperationConfig config : getConfigs()) {
if (config.includes(operationId)) {
if (config.getPer... |
python | def _to_dict(self):
"""Return keyrange's state as a dict.
:rtype: dict
:returns: state of this instance.
"""
mapping = {}
if self.start_open:
mapping["start_open"] = self.start_open
if self.start_closed:
mapping["start_closed"] = self.st... |
java | public void setRetainViewMode(@NonNull RetainViewMode retainViewMode) {
this.retainViewMode = retainViewMode != null ? retainViewMode : RetainViewMode.RELEASE_DETACH;
if (this.retainViewMode == RetainViewMode.RELEASE_DETACH && !attached) {
removeViewReference();
}
} |
java | public static final double compact(long sign, double natlog) {
return Double.longBitsToDouble(sign | (FLOAT_MASK & Double.doubleToRawLongBits(natlog)));
} |
java | protected void configureHandlerInterceptor(ApplicationContext context) {
if (context.containsBean(HANDLER_INTERCEPTOR_BEAN_NAME)) {
DelegatingHandlerInterceptor handlerInterceptor = context.getBean(HANDLER_INTERCEPTOR_BEAN_NAME, DelegatingHandlerInterceptor.class);
handlerInterceptor.set... |
python | def filter_slaves(selfie, slaves):
"""
Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have 'ok' master-link-status
"""
return [(s['ip'], s['port']) for s in slaves
if not s['is_odown'] and
not s['is_sdown'] and
... |
python | def pre_filter(self):
""" Return rTorrent condition to speed up data transfer.
"""
if self._name not in self.PRE_FILTER_FIELDS or self._template:
return ''
if not self._value:
return '"equal={},cat="'.format(self.PRE_FILTER_FIELDS[self._name])
if self._is... |
java | protected void initializeExecutorServices() {
final int downloadPoolSize;
final int max = settings.getInt(Settings.KEYS.MAX_DOWNLOAD_THREAD_POOL_SIZE, 3);
if (DOWNLOAD_THREAD_POOL_SIZE > max) {
downloadPoolSize = max;
} else {
downloadPoolSize = DOWNLOAD_THREAD_PO... |
python | def do_edit_settings(fake):
"""Opens legit settings in editor."""
path = resources.user.open('config.ini').name
click.echo('Legit Settings:\n')
for (option, _, description) in legit_settings.config_defaults:
click.echo(columns([crayons.yellow(option), 25], [description, None]))
click.echo... |
java | public ListenableFuture<ChangeRequestsSnapshot<DataSegmentChangeRequest>> getSegmentChangesSince(ChangeRequestHistory.Counter counter)
{
if (counter.getCounter() < 0) {
synchronized (lock) {
Iterable<DataSegmentChangeRequest> segments = Iterables.transform(
segmentLookup.keySet(),
... |
java | public static String removeWhitespace(String string) {
if (string == null || string.length() == 0) {
return string;
} else {
int codePoints = string.codePointCount(0, string.length());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c... |
java | @Override
public void close() {
closeComponent(this.containerManager);
closeComponent(this.containerRegistry);
closeComponent(this.dataLogFactory);
closeComponent(this.readIndexFactory);
closeComponent(this.cacheFactory);
this.cacheManager.close();
this.thread... |
java | public static Map<String, Object> findFreeMarkerExtensions(Furnace furnace, GraphRewrite event)
{
Imported<WindupFreeMarkerMethod> freeMarkerMethods = furnace.getAddonRegistry().getServices(
WindupFreeMarkerMethod.class);
Map<String, Object> results = new HashMap<>();
fo... |
java | public static JavaRDD<List<Writable>> normalize(Schema schema, JavaRDD<List<Writable>> data,
List<String> skipColumns) {
return normalize(schema, data, 0, 1, skipColumns);
} |
python | def get_fields_by_class(cls, field_class):
""" Return a list of field names matching a field class
:param field_class: field class object
:return: list
"""
ret = []
for key, val in getattr(cls, '_fields').items():
if isinstance(val, field_class):
... |
java | protected ActionErrors validateBean( Object bean, String beanName, ActionMapping mapping, HttpServletRequest request )
{
MessageResources messageResources = ( MessageResources ) request.getAttribute( Globals.MESSAGES_KEY );
ExpressionAwareMessageResources.update( messageResources, bean );
/... |
java | @Override
public CPDefinitionInventory findByPrimaryKey(Serializable primaryKey)
throws NoSuchCPDefinitionInventoryException {
CPDefinitionInventory cpDefinitionInventory = fetchByPrimaryKey(primaryKey);
if (cpDefinitionInventory == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRI... |
java | public void connect(SocketAddress endpoint, int timeout) throws IOException {
String filename;
if (host == null || host.equals("localhost")) {
filename = "\\\\.\\pipe\\" + name;
} else {
filename = "\\\\" + host + "\\pipe\\" + name;
}
//use a default timeout of 100ms if no timeout set.
... |
python | def visit_create_library_command(element, compiler, **kw):
"""
Returns the actual sql query for the CreateLibraryCommand class.
"""
query = """
CREATE {or_replace} LIBRARY {name}
LANGUAGE pythonplu
FROM :location
WITH CREDENTIALS AS :credentials
{region}
"""
... |
java | public Paragraph paragraph() {
Paragraph paragraph = new Paragraph(before.getLeading());
paragraph.add(before);
if (numbered) {
paragraph.addSpecial(new Chunk(String.valueOf(pageN), before.getFont()));
}
if (after != null) {
paragraph.addSpecial(after);
... |
python | def _subtitlesRemoved(self, path, subNos):
"""When subtitle is removed, all syncPoints greater than removed
subtitle are decremented. SyncPoint equal to removed subtitle is also
removed."""
def action(current, count, model, row):
if count.equal > 0:
model.remo... |
python | def reference(self, ):
"""Reference a file
:returns: None
:rtype: None
:raises: None
"""
tfi = self.get_taskfileinfo_selection()
if tfi:
self.reftrack.reference(tfi) |
python | def describe_file_set(modules):
"""Build a file set from a specified Python modules.
Args:
modules: Iterable of Python module to describe.
Returns:
Initialized FileSet instance describing the modules.
"""
descriptor = FileSet()
file_descriptors = []
for module in modules:
... |
python | def _make_tile(self, value, background, text):
"""Renders a tile, according to its value, and background and foreground colours."""
tile = pygame.Surface((self.cell_width, self.cell_height), pygame.SRCALPHA)
pygame.draw.rect(tile, background, (0, 0, self.cell_width, self.cell_height))
# ... |
python | def get_user_stats(self, users, lang=None, concepts=None, since=None, recalculate=True):
"""
Finds all UserStats of given concepts and users.
Recompute UserStats if necessary
Args:
users (Optional[list of users] or [user]): list of primary keys of user or users
... |
java | public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {
try {
return c.getMethod(name, argTypes);
} catch(NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
} |
java | public void processSpace(Properties properties) {
try {
Transform transform = null;
// Load any optionally specifie transform class
String transformClass =
properties.getProperty(MATRIX_TRANSFORM_PROPERTY);
if (transformClass != null)
... |
python | def cmd_map(self, args):
'''map commands'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if len(args) < 1:
print("usage: map <icon|set>")
elif args[0] == "icon":
if len(args) < 3:
print("Usage: map icon <lat> <lon> <icon>")
else... |
python | def get_name_or_instance_id(self, with_id=False):
"""Returns the name of an instance if existant, else return the instance id
Args:
with_id (bool): Include the instance ID even if the name is found (default: False)
Returns:
Name and/or instance ID of the instance object... |
python | def pin(value):
'''A small pin that represents the result of the build process'''
if value is False:
return draw_pin('Build Failed', 'red')
elif value is True:
return draw_pin('Build Passed')
elif value is NOT_FOUND:
return draw_pin('Build N / A', 'lightGray', 'black')
return... |
java | public boolean handleRemoteCriteria(StringBuffer strFilter, boolean bIncludeFileName, Vector<BaseField> vParamList)
{
BaseListener nextListener = this.getNextEnabledListener();
if (nextListener != null)
return ((FileListener)nextListener).doRemoteCriteria(strFilter, bIncludeFileName, vP... |
python | def prepare_notes(self, *notes, **keyword_notes):
"""Get injection values for all given notes."""
__partial = keyword_notes.pop('__partial', False)
args = tuple(self.get(note) for note in notes)
kwargs = {}
for arg in keyword_notes:
note = keyword_notes[arg]
... |
java | @Override
public Behavior initialBehavior(Optional<BlogState> snapshotState) {
if (snapshotState.isPresent() && !snapshotState.get().isEmpty()) {
// behavior after snapshot must be restored by initialBehavior
// if we have a non-empty BlogState we know that the initial
// AddPost has been perfor... |
java | public Model getModel(MP params) {
Key<Model> mKey = getModelKey(params);
return mKey != null ? mKey.get() : null;
} |
python | def compile(self):
"""
This method isn't yet idempotent; calling multiple times may yield
unexpected results
"""
# Can't tell if this is a hack or not. Revisit later
self.context.set_query(self)
# If any subqueries, translate them and add to beginning of query as... |
java | public GetMaterialTotalCountResponse countMaterial(){
GetMaterialTotalCountResponse response = null;
String url = BASE_API_URL + "cgi-bin/material/get_materialcount?access_token=#";
BaseResponse r = executeGet(url);
String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJson... |
python | def print_environment_vars(env):
"""
Print ``Ansible`` and ``Molecule`` environment variables and returns None.
:param env: A dict containing the shell's environment as collected by
``os.environ``.
:return: None
"""
ansible_env = {k: v for (k, v) in env.items() if 'ANSIBLE_' in k}
print... |
java | public static DumpData toDumpData(Node node, PageContext pageContext, int maxlevel, DumpProperties props) {
if (maxlevel <= 0) {
return DumpUtil.MAX_LEVEL_REACHED;
}
maxlevel--;
// Document
if (node instanceof Document) {
DumpTable table = new DumpTable("xml", "#cc9999", "#ffffff", "#000000");
table... |
python | def listfiles(data_name):
"""
List files in a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
... |
java | public static QuantityFeature<AbstractSequence<NucleotideCompound>, NucleotideCompound> createErrorProbabilities(final Fastq fastq)
{
if (fastq == null)
{
throw new IllegalArgumentException("fastq must not be null");
}
QuantityFeature<AbstractSequence<NucleotideCompound>, NucleotideCompound> errorProbabilit... |
python | def print_mhc_peptide(neoepitope_info, peptides, pepmap, outfile, netmhc=False):
"""
Accept data about one neoepitope from merge_mhc_peptide_calls and print it to outfile. This is
a generic module to reduce code redundancy.
:param pandas.core.frame neoepitope_info: object containing with allele, pept,... |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
public Table aggregate(ListMultimap<String, AggregateFunction<?,?>> functions) {
Preconditions.checkArgument(!getSlices().isEmpty());
Table groupTable = summaryTableName(sourceTable);
StringColumn groupColumn = StringColumn.create("Group");
... |
java | private boolean StringFieldMatch (String original, String matching) {
boolean equal = false;
original = original.toLowerCase().trim();
matching = matching.toLowerCase();
if (original.endsWith(matching)) {
equal = true;
}
else if (original.startsWith(matching))... |
python | def get_meshables(self):
"""
return a list of components that are meshable (generally stars, but handles
the envelope for an contact_binary)
"""
l = re.findall(r"[\w']+", self.get_value())
# now search for indices of star and take the next entry from this flat list
... |
python | def _parse_mode(mode):
'''
Converts ls mode output (rwxrwxrwx) -> integer (755).
'''
result = ''
# owner, group, world
for group in [mode[0:3], mode[3:6], mode[6:9]]:
if group in SYMBOL_TO_OCTAL_PERMISSIONS:
result = '{0}{1}'.format(result, SYMBOL_TO_OCTAL_PERMISSIONS[group]... |
java | public static BitMatrix encode(String content, QrConfig config) {
return encode(content, BarcodeFormat.QR_CODE, config);
} |
java | public static com.liferay.commerce.model.CommerceWarehouseItem deleteCommerceWarehouseItem(
com.liferay.commerce.model.CommerceWarehouseItem commerceWarehouseItem) {
return getService().deleteCommerceWarehouseItem(commerceWarehouseItem);
} |
java | public JBBPOut Float(final float... value) throws IOException {
assertNotEnded();
assertArrayNotNull(value);
if (this.processCommands) {
for (final float f : value) {
_writeFloat(f);
}
}
return this;
} |
java | private String[] getHeaders() {
final List<String> headers = new ArrayList<>();
if(decorator.getShowSources()){
headers.add(SOURCE_FIELD);
}
if(decorator.getShowSourcesVersion()){
headers.add(SOURCE_VERSION_FIELD);
}
if(decorator.getShowTargets(... |
java | public ServiceFuture<ElasticPoolInner> beginUpdateAsync(String resourceGroupName, String serverName, String elasticPoolName, ElasticPoolUpdate parameters, final ServiceCallback<ElasticPoolInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceGroupName, serverNam... |
python | def getAll(self):
'''Return a dictionary with all variables'''
if not bool(len(self.ATTRIBUTES)):
self.load_attributes()
return eval(str(self.ATTRIBUTES)) |
java | @Override
public boolean filter(Object entity) {
if (fixture instanceof FilterableFixture) {
return filterableFixture().filter(entity);
}
return true;
} |
python | def from_cli_multi_ifos(opt, ifos, **kwargs):
"""
Get the strain for all ifos when using the multi-detector CLI
"""
strain = {}
for ifo in ifos:
strain[ifo] = from_cli_single_ifo(opt, ifo, **kwargs)
return strain |
java | public static void swap(byte[] byteArray1, byte[] byteArray2, int index) {
TrivialSwap.swap(byteArray1, index, byteArray2, index);
} |
java | public Observable<Map<String, String>> listEndpointsAsync(UUID appId) {
return listEndpointsWithServiceResponseAsync(appId).map(new Func1<ServiceResponse<Map<String, String>>, Map<String, String>>() {
@Override
public Map<String, String> call(ServiceResponse<Map<String, String>> response... |
python | def ext_publish(self, instance, loop, *args, **kwargs):
"""If 'external_signaller' is defined, calls it's publish method to
notify external event systems.
This is for internal usage only, but it's doumented because it's part
of the interface with external notification systems.
"... |
java | public static IntegerBinding negateExact(final ObservableIntegerValue a) {
return createIntegerBinding(() -> Math.negateExact(a.get()), a);
} |
python | def addChildFn(self, fn, *args, **kwargs):
"""
Adds a function as a child job.
:param fn: Function to be run as a child job with ``*args`` and ``**kwargs`` as \
arguments to this function. See toil.job.FunctionWrappingJob for reserved \
keyword arguments used to specify resource... |
python | def get_numeric_score_increment(self):
"""Gets the incremental step.
return: (decimal) - the increment
raise: IllegalState - ``is_based_on_grades()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
if self.is_based_on_grades():
r... |
java | public Observable<LegalHoldInner> clearLegalHoldAsync(String resourceGroupName, String accountName, String containerName, List<String> tags) {
return clearLegalHoldWithServiceResponseAsync(resourceGroupName, accountName, containerName, tags).map(new Func1<ServiceResponse<LegalHoldInner>, LegalHoldInner>() {
... |
python | def match_file(pattern, filename):
'''
The function will match a pattern in a file and return
a rex object, which will have all the matches found in the file.
'''
# Validate user data.
if pattern is None:
return None
if os.stat(filename).st_size == 0:
return None
rexo... |
java | @Override
public <TResponse> TResponse post(IReturn<TResponse> request) {
return send(createUrl(request, HttpMethods.Post), HttpMethods.Post, request, request.getResponseType());
} |
java | private Asset getUnverifiedAsset(String assetId) throws IOException, RequestFailureException {
HttpURLConnection connection = createHttpURLConnectionToMassive("/assets/"
+ assetId);
connection.setRequestMethod("GET");
testRe... |
java | public<V> boolean isConsolidated(Function<E,V> convertAdds, Function<K,V> convertDels) {
int delBefore = getDeletions().size();
consolidate(convertAdds,convertDels);
return getDeletions().size()==delBefore;
} |
java | public static Object invoke(Object object, String methodName, Object[] parameters) {
try {
Class[] classTypes = new Class[parameters.length];
for (int i = 0; i < classTypes.length; i++) {
classTypes[i] = parameters[i].getClass();
}
Method method = ... |
java | static ImmutableList<NameValuePair> buildParameters(
String analyticsId,
String clientId,
String virtualPageName,
String virtualPageTitle,
String eventType,
String eventName,
boolean isUserSignedIn,
boolean isUserInternal,
Optional<Boolean> isUserTrialEligible,
... |
java | public Observable<Void> suspendAsync(String resourceGroupName, String automationAccountName, UUID jobId) {
return suspendWithServiceResponseAsync(resourceGroupName, automationAccountName, jobId).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Voi... |
python | def _repair_row(self):
'''
Searches for missing titles that can be inferred from the surrounding data and automatically
repairs those titles.
'''
# Repair any title rows
check_for_title = True
for row_index in range(self.start[0], self.end[0]):
table_r... |
java | @Deprecated
public final <T extends Query> T addGroupByField(String fieldname) {
return addGroupByField(new SimpleField(fieldname));
} |
python | def get_global_dist_packages_dir():
"""
Attempts to work around virtualenvs and find the system dist_pacakges.
Essentially this is implmenented as a lookuptable
"""
import utool as ut
if not ut.in_virtual_env():
# Non venv case
return get_site_packages_dir()
else:
can... |
java | private boolean parse() {
///CLOVER:OFF
if (vtzlines == null || vtzlines.size() == 0) {
return false;
}
///CLOVER:ON
// timezone ID
String tzid = null;
int state = INI;
boolean dst = false; // current zone type
String from = null; ... |
java | @Override
public ExecutionEntity createChildExecution(ExecutionEntity parentExecutionEntity) {
ExecutionEntity childExecution = executionDataManager.create();
inheritCommonProperties(parentExecutionEntity, childExecution);
childExecution.setParent(parentExecutionEntity);
childExecution.setProcessDefin... |
java | private void convertCharset(final File inputFile) {
if (inputFile.isDirectory()) {
final File[] files = inputFile.listFiles();
if (files != null) {
for (final File file : files) {
convertCharset(file);
}
}
} else if ... |
python | def createmeta(self,
projectKeys=None,
projectIds=[],
issuetypeIds=None,
issuetypeNames=None,
expand=None,
):
"""Get the metadata required to create issues, optionally filtered by projects and issue... |
java | public void readArray(float[] data) throws IOException {
int size = data.length;
for (int i = 0; i < size; ++i)
data[i] = getFloat();
} |
python | def jiggle_source_code(self): # type: () ->int
"""
Updates version of central package
"""
changed = 0
for file_name in self.file_inventory.source_files:
to_write = []
# self.create_missing(file_name, file_name)
if not os.path.isfile(file_name)... |
python | def get_monitors(self, condition=None, page_size=1000):
"""Return an iterator over all monitors matching the provided condition
Get all inactive monitors and print id::
for mon in dc.monitor.get_monitors(MON_STATUS_ATTR == "DISABLED"):
print(mon.get_id())
Get all t... |
java | protected void processResult(RHI aggregatedResult) {
// Process the result with all result handlers
for (ResultHandler<RHI> resultHandler : resultHandlers) {
resultHandler.handleResult(aggregatedResult);
}
} |
python | def getstate(d):
'''Deep copies a dict, and returns it without the keys _links and
_embedded
'''
if not isinstance(d, dict):
raise TypeError("Can only get the state of a dictionary")
cpd = copy.deepcopy(d)
cpd.pop('_links', None)
cpd.pop('_embedded', None)
return cpd |
python | def partition_version_classifiers(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]:
"""Find version number classifiers in given list and partition them into 2 groups."""
versions_min, ve... |
java | public static byte[] copyBytes(ByteBuffer bytes) {
ByteBuffer copy = bytes.duplicate();
byte[] result = new byte[copy.remaining()]; // bytes between position and limit
copy.get(result);
return result;
} |
java | public void removeNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException {
delegate.removeNotificationListener(name, listener, filter, handback);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.