language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def show_keyword_version_message(sender, keyword_version, inasafe_version):
"""Show a message indicating that the keywords version is mismatch
.. versionadded: 3.2
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param keyword_version: The version of the l... |
python | def check_exists(self):
'''
Check if resource exists, update self.exists, returns
Returns:
None: sets self.exists
'''
response = self.repo.api.http_request('HEAD', self.uri)
self.status_code = response.status_code
# resource exists
if self.status_code == 200:
self.exists = True
# resource no ... |
java | public DesignSpec setBaselineGridColor(int color) {
if (mBaselineGridPaint.getColor() == color) {
return this;
}
mBaselineGridPaint.setColor(color);
invalidateSelf();
return this;
} |
java | static List<String> split(String input)
{
if (input.isEmpty())
return Collections.<String>emptyList();
List<String> res = new ArrayList<String>();
int prev = 0;
for (int i = 0; i < input.length(); i++)
{
if (input.charAt(i) != ':' || (i > 0 && input.c... |
python | def has_textonly_pdf():
"""Does Tesseract have textonly_pdf capability?
Available in v4.00.00alpha since January 2017. Best to
parse the parameter list
"""
args_tess = ['tesseract', '--print-parameters', 'pdf']
params = ''
try:
params = check_output(args_tess, universal_newlines=Tru... |
python | def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... |
python | def cdhit_from_seqs(seqs, moltype, params=None):
"""Returns the CD-HIT results given seqs
seqs : dict like collection of sequences
moltype : cogent.core.moltype object
params : cd-hit parameters
NOTE: This method will call CD_HIT if moltype is PROTIEN,
CD_HIT_EST if moltype is RNA/DNA,... |
python | def keyPressEvent(self, event):
"""
Overrides the keyPressEvent to emit the key_pressed signal.
Also takes care of indenting and handling smarter home key.
:param event: QKeyEvent
"""
if self.isReadOnly():
return
initial_state = event.isAccepted()
... |
python | def path(self):
"""Return the full path to the Group, including any parent Groups."""
# If root, return '/'
if self.dataset is self:
return ''
else: # Otherwise recurse
return self.dataset.path + '/' + self.name |
java | public SubscriptionScheduleRevisionCollection revisions() throws StripeException {
return revisions((Map<String, Object>) null, (RequestOptions) null);
} |
java | public synchronized void stop() {
if (isRunning()) {
socket.get().close();
socket.set(null);
deliverLifecycleAnnouncement(logger, false);
}
} |
python | def create_linguistic_processor(self, layer, name, version, **kwargs):
"""
Create a new linguistic processor element and add it to the header
@type layer: string
@param layer: the layer to which the processor is related to
@type name: string
@param name: the name of the l... |
python | def get_full_angles(self):
"""Get the interpolated lons/lats.
"""
if (self.sun_azi is not None and self.sun_zen is not None and
self.sat_azi is not None and self.sat_zen is not None):
return self.sun_azi, self.sun_zen, self.sat_azi, self.sat_zen
self.sun_azi,... |
java | public static String[] parse(String[] args)
throws IOException
{
ListBuffer<String> newArgs = new ListBuffer<String>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.length() > 1 && arg.charAt(0) == '@') {
arg = arg.substring(1)... |
java | public com.google.api.ads.adwords.axis.v201809.cm.PageOnePromotedBiddingSchemeStrategyGoal getStrategyGoal() {
return strategyGoal;
} |
python | def get_calcs(db, request_get_dict, allowed_users, user_acl_on=False, id=None):
"""
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param request_get_dict:
a dictionary
:param allowed_users:
a list of users
:param user_acl_on:
if True, returns only the calcu... |
java | public int getDocumentFrequency(Token token)
{
Integer df = (Integer)documentFrequency.get(token);
if (df == null) return 0;
else return df.intValue();
} |
java | public CFMetaData getCFMetaData(String keyspace, List<ByteBuffer> variables) throws InvalidRequestException
{
validate(variables);
try
{
boolean isDense = columns.isEmpty();
CFMetaData newCFMD = new CFMetaData(keyspace,
... |
java | public void raInactive() {
sbbInterface.setActive(false);
activities = null;
client.shutdown();
client=null;
executorService.shutdown();
executorService = null;
} |
python | def _update_deferred(self, event):
"""
This does the actual work of updating channel metadata. This is called
by the update(), and runs this method in another thread.
"""
if isinstance(event, ChannelCreated):
i = event.channel[u'id']
event.channel[u'is_archived'] = event.channel[u'is_member'] = False
... |
python | def getmin(self):
"""Get minimiser after optimisation."""
if self.opt['ReturnVar'] == 'X':
return self.var_x()
elif self.opt['ReturnVar'] == 'Y0':
return self.var_y0()
elif self.opt['ReturnVar'] == 'Y1':
return self.var_y1()
else:
... |
java | public BiMap<V, K> inversed() {
return (inverse == null) ? inverse = new BiMap<>(valueMap, keyMap) : inverse;
} |
python | def restore__ast(_ast):
"""Attempt to restore the required classes to the _ast module if it
appears to be missing them
"""
if hasattr(_ast, 'AST'):
return
_ast.PyCF_ONLY_AST = 2 << 9
m = compile("""\
def foo(): pass
class Bar(object): pass
if False: pass
baz = 'mako'
1 + 2 - 3 * 4 / 5
6 ... |
python | def _extract_next_page_link(self):
""" Try to get next page link. """
# HEADS UP: we do not abort if next_page_link is already set:
# we try to find next (eg. find 3 if already at page 2).
for pattern in self.config.next_page_link:
items = self.parsed_tree.xpath(p... |
python | def to_circuit(self) -> Circuit:
"""Convert the schedule to a circuit.
This discards most timing information from the schedule, but does place
operations that are scheduled at the same time in the same Moment.
"""
circuit = Circuit(device=self.device)
time = None # type... |
java | private void copyFromRfs(String folder) throws CmsException {
// get the corresponding folder in the FS
File[] res;
File fsFile = getFileInRfs(folder);
// first of all, test if this folder existis in the VFS. If not, create it
try {
m_cms.readFolder(translate(folder)... |
java | private final State onCheckEndHeaderSection(final Buffer buffer) {
// can't tell. We need two bytes at least to check if there is
// more headers or not
if (buffer.getReadableBytes() < 2) {
return State.CHECK_FOR_END_OF_HEADER_SECTION;
}
// ok, so there was a CRLF so... |
java | public static TextLoader getInstance(Encoding encoding)
{
if (null == encoding)
{
return getInstance();
}
else
{
if (!INSTANCE_BY_ENCODING.containsKey(encoding.getIsoName()))
{
TextLoader _newInstance = new TextLoader(encoding);
INSTANCE_BY_ENCODING.put(encoding.getIsoName(), _newInstance);
... |
java | public void waitForConnectedAndDeflectorHealthy(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
LOG.debug("Waiting until the write-active index is healthy again, checking once per second.");
final CountDownLatch latch = new CountDownLatch(1);
final ScheduledFuture<?... |
python | def content_deleted(sender, instance=None, **kwargs):
"""removes content from the ES index when deleted from DB
"""
if getattr(instance, "_index", True):
cls = instance.get_real_instance_class()
index = cls.search_objects.mapping.index
doc_type = cls.search_objects.mapping.doc_type
... |
java | public Datatype.Builder setType(TypeClass type) {
this.type = Objects.requireNonNull(type);
_unsetProperties.remove(Property.TYPE);
return (Datatype.Builder) this;
} |
python | def resolution(self):
"""
Get the tile resolution at the current position.
The scale in WG84 depends on
* the zoom level (obviously)
* the latitude
* the tile size
References:
* http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Reso... |
java | public String getFieldTip()
{
String strTipKey = this.getFieldName() + Constants.TIP;
String strFieldTip = strTipKey;
if (this.getRecord() != null)
strFieldTip = this.getRecord().getString(strTipKey);
if (strFieldTip == strTipKey)
return this.getFieldDesc();
... |
java | private Object jsToJava(Object jsObj) {
if (jsObj instanceof Wrapper) {
Wrapper njb = (Wrapper) jsObj;
/* importClass feature of ImporterTopLevel puts
* NativeJavaClass in global scope. If we unwrap
* it, importClass won't work.
*/
if (n... |
java | private URI getHasMemberFromResource(final HttpServletRequest request) {
final FedoraResource resource = resource(request);
return getHasMemberFromResource(request, resource);
} |
python | def str_args(args):
"""formats a list of function arguments prettily not as code
(kwargs are tuples (argname, argvalue)
"""
res = []
for x in args:
if isinstance(x, tuple) and len(x) == 2:
key, value = x
if value and str_arg(value):
res += ["%s=%s" % ... |
java | public String getIgnoreEMail(String serverName) {
if (serverName != null) {
return ignoreEMails.get(serverName);
} else {
return null;
}
} |
java | @Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
BugsnagScheduledTaskExceptionHandler bugsnagErrorHandler =
new BugsnagScheduledTaskExceptionHandler(bugsnag);
// Decision process for finding a TaskScheduler, in order of preference:
//
// 1... |
python | def teecsv(table, source=None, encoding=None, errors='strict', write_header=True,
**csvargs):
"""
Returns a table that writes rows to a CSV file as they are iterated over.
"""
source = write_source_from_arg(source)
csvargs.setdefault('dialect', 'excel')
return teecsv_impl(table, sou... |
python | def is_valid_password(password):
"""
Check if a password is valid
"""
pattern = re.compile(r"^.{4,75}$")
return bool(pattern.match(password)) |
java | public static long getRandomUID(final int width) {
if (width > MAX_WIDTH) {
throw new IllegalArgumentException("Expecting to return an unsigned long "
+ "random integer, it can not be larger than " + MAX_WIDTH +
" bytes wide");
}
final byte[] bytes = new byte[width];
random_ge... |
java | static List<List<String>> handleNewLines( List<List<String>> tableModel ) {
List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );
for( List<String> row : tableModel ) {
if( hasNewline( row ) ) {
result.addAll( splitRow( row ) );
} e... |
java | public String decrypt(String encrypted) throws Exception {
byte[] decodedValue = Base64Coder.decode(encrypted.toCharArray());
Cipher c = getCipher(Cipher.DECRYPT_MODE);
byte[] decValue = c.doFinal(decodedValue);
return new String(decValue);
} |
java | @Override
protected void generateFileHeader(QualifiedName qualifiedName, ExtraLanguageAppendable appendable,
IExtraLanguageGeneratorContext context) {
appendable.append(PYTHON_FILE_HEADER);
appendable.newLine();
appendable.append(getGenerationComment(context));
appendable.newLine().newLine();
} |
python | def _compute_document_meta(self):
"""
Return documents meta information that can
be used for fast document lookups. Meta information
consists of documents titles, categories and positions
in file.
"""
meta = OrderedDict()
bounds_iter = xml_utils.bounds(se... |
python | def infer_named_tuple(node, context=None):
"""Specific inference function for namedtuple Call node"""
tuple_base_name = nodes.Name(name="tuple", parent=node.root())
class_node, name, attributes = infer_func_form(
node, tuple_base_name, context=context
)
call_site = arguments.CallSite.from_ca... |
python | def parse_parameter(self, tup_tree):
"""
::
<!ELEMENT PARAMETER (QUALIFIER*)>
<!ATTLIST PARAMETER
%CIMName;
%CIMType; #REQUIRED>
"""
self.check_node(tup_tree, 'PARAMETER', ('NAME', 'TYPE'), (),
... |
java | private PointSeries toVersionSeries(final List<BrowserUsageData> browserUsage) {
PointSeries versionSeries = new PointSeries();
for (BrowserUsageData browserData : browserUsage) {
for (VersionUsageData versionData : browserData
.getVersionUsageData()) {
versionSeries
.addPoin... |
python | def crop_square(im, r, c, sz):
'''
crop image into a square of size sz,
'''
return im[r:r+sz, c:c+sz] |
python | def extract_event_info(dstore, eidx):
"""
Extract information about the given event index.
Example:
http://127.0.0.1:8800/v1/calc/30/extract/event_info/0
"""
event = dstore['events'][int(eidx)]
serial = int(event['eid'] // TWO32)
ridx = list(dstore['ruptures']['serial']).index(serial)
... |
java | public Iterator entryIterator()
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this, cclass,
"entryIterator");
Iterator entryIterator = subList(null, null).entryIterator();
if ... |
python | def sort_by(self, fieldName, reverse=False):
'''
sort_by - Return a copy of this collection, sorted by the given fieldName.
The fieldName is accessed the same way as other filtering, so it supports custom properties, etc.
@param fieldName <str> - The name of the field o... |
java | public final UnicodeSet addAll(CharSequence s) {
checkFrozen();
int cp;
for (int i = 0; i < s.length(); i += UTF16.getCharCount(cp)) {
cp = UTF16.charAt(s, i);
add_unchecked(cp, cp);
}
return this;
} |
python | def identify(self):
"""Update client metadata on the server and negotiate features.
:returns: nsqd response data if there was feature negotiation,
otherwise ``None``
"""
self.send(nsq.identify({
# nsqd 0.2.28+
'client_id': self.client_id,
... |
java | @Around("isProfileAnnotation(profile)")
public Object profileMethod(ProceedingJoinPoint joinPoint, Profile profile) throws Throwable {
String logPrefix = null;
boolean debug = LOG.isDebugEnabled();
long time = System.currentTimeMillis();
// parse out the first arg
String arg1 = "";
Object[] args = joinPo... |
java | public static void save(String key, Object object) throws Exception {
String json = new Gson().toJson(object);
cache.put(key, json);
} |
java | private int maxOptionLength(List<OptionInfo> optList, boolean showUnpublicized) {
int maxLength = 0;
for (OptionInfo oi : optList) {
if (oi.unpublicized && !showUnpublicized) {
continue;
}
int len = oi.synopsis().length();
if (len > maxLength) {
maxLength = len;
}
... |
python | def max_min_projection(self, axis=2):
"""
Compute maximum-minimum projection along a dimension.
This computes the sum of the maximum and minimum values.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
"... |
python | def setKeyColor( self, key, color ):
"""
Sets the color used when rendering pie charts.
:param key | <str>
color | <QColor>
"""
self._keyColors[nativestring(key)] = QColor(color) |
java | @Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
final ModelNode request = buildRequest(ctx);
Attachments attachments = getAttachments(ctx);
OperationBuilder builder = new OperationBuilder(request, true);
for (String path : attachments.getAttachedF... |
java | private void process(double[] data, double min, double max, KernelDensityFunction kernel, int window, double epsilon) {
dens = new double[data.length];
var = new double[data.length];
// This is the desired bandwidth of the kernel.
double halfwidth = ((max - min) / window) * .5;
for (int current = ... |
java | @Override
public List<V> get(Object key)
{
if (key == null) {
return null;
}
K[] keys = _keys;
int size = _size;
for (int i = size - 1; i >= 0; i--) {
if (key.equals(keys[i])) {
return _values[i];
}
}
return null;
} |
java | private static boolean isLoadIgnored(final LoadInstruction instruction) {
return Stream.of(VARIABLE_NAMES_TO_IGNORE).anyMatch(instruction.getName()::equals);
} |
java | public List<VirtualMachineImageResourceInner> list(String location, String publisherName, String offer, String skus) {
return listWithServiceResponseAsync(location, publisherName, offer, skus).toBlocking().single().body();
} |
python | def set_ylimits_widgets(self, set_min=True, set_max=True):
"""Populate axis limits GUI with current plot values."""
ymin, ymax = self.tab_plot.ax.get_ylim()
if set_min:
self.w.y_lo.set_text('{0}'.format(ymin))
if set_max:
self.w.y_hi.set_text('{0}'.format(ymax)) |
java | @Override
public ControllerLinkBuilder linkTo(Class<?> controller, Method method, Object... parameters) {
return ControllerLinkBuilder.linkTo(controller, method, parameters);
} |
python | def _get_float(data, position, dummy0, dummy1, dummy2):
"""Decode a BSON double to python float."""
end = position + 8
return _UNPACK_FLOAT(data[position:end])[0], end |
python | def delete(self):
"""Returns a response after attempting to delete the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
return requests.delete(
f"{self.api_url}/{self.address}", auth=("api", self.api_key)
) |
java | public static String getDidYouMeanMessageForProtoFields(
ImmutableSet<String> fields, Descriptor descriptor, String fieldName) {
// TODO(b/27616446): when we have case enum support add a case here.
if (fields.contains(fieldName + "List")) {
return String.format(" Did you mean '%sList'?", fieldName);... |
python | def get_basic_selection(self, selection=Ellipsis, out=None, fields=None):
"""Retrieve data for an item or region of the array.
Parameters
----------
selection : tuple
A tuple specifying the requested item or region for each dimension of the
array. May be any comb... |
python | def find_ids(self, element_ids):
"""Find elements with given IDs.
Parameters
----------
element_ids : list of strings
list of IDs to find
Returns
-------
a new `Panel` object which contains all the found elements.
"""
elements = [_tra... |
python | def debug(self, *args):
"""Log a debug message. Used for debugging."""
if _canShortcutLogging(self.logCategory, DEBUG):
return
debugObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args)) |
python | def get_associations(self, env):
"""
Get all the associations for this env.
Root cannot have associations, so return None for root.
returns a map of hostnames to environments.
"""
if env.is_root:
return None
associations = self.associations.get_all... |
python | def get_overlay(self):
"""
Function make 3D data from dicom file slices. There are usualy
more overlays in the data.
"""
overlay = {}
dcmlist = self.files_in_serie
for i in range(len(dcmlist)):
onefile = dcmlist[i]
logger.info("reading '%s... |
java | @Override
protected ShardConsumer createShardConsumer(
Integer subscribedShardStateIndex,
StreamShardHandle handle,
SequenceNumber lastSeqNum,
ShardMetricsReporter shardMetricsReporter) {
return new ShardConsumer(
this,
subscribedShardStateIndex,
handle,
lastSeqNum,
DynamoDBStreamsProxy.creat... |
java | @Override
public void beginQuotation(Map<String, String> parameters)
{
if (!getBlockState().isInQuotationLine()) {
printEmptyLine();
}
if (!parameters.isEmpty()) {
printParameters(parameters);
}
} |
java | public static SourceLineAnnotation fromVisitedInstructionRange(ClassContext classContext, MethodGen methodGen,
String sourceFile, InstructionHandle start, InstructionHandle end) {
LineNumberTable lineNumberTable = methodGen.getLineNumberTable(methodGen.getConstantPool());
String className = ... |
java | static public int longToBytes(long l, byte[] buffer, int index) {
int length = buffer.length - index;
if (length > 8) length = 8;
for (int i = 0; i < length; i++) {
buffer[index + length - i - 1] = (byte) (l >> (i * 8));
}
return length;
} |
java | void addWhereClause(StringBuilder builder) {
if (!getKunderaQuery().getFilterClauseQueue().isEmpty()) {
builder.append(CQLTranslator.ADD_WHERE_CLAUSE);
}
} |
java | public void reset(Object[] btree, boolean forwards)
{
_reset(btree, null, NEGATIVE_INFINITY, false, POSITIVE_INFINITY, false, forwards);
} |
java | protected void fireCommentEvent(char[] chars, int start, int length)
throws org.xml.sax.SAXException
{
if (m_tracer != null)
{
flushMyWriter();
m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length));
}
} |
python | def star(self):
"""
Stars the project
.. deprecated:: 0.8.5
Update Taiga and use like instead
"""
warnings.warn(
"Deprecated! Update Taiga and use .like() instead",
DeprecationWarning
)
self.requester.post(
'/{endp... |
python | def simple_interaction(snps,pheno,Inter,Inter0=None,covs = None,K=None,test='lrt'):
"""
I-variate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno: [N x 1] SP.array of 1 phenotype for N individual... |
python | def _bird_core(X, scales, n_runs, Lambda_W, max_iter=100,
stop_crit=np.mean,
selection_rule=np.sum,
n_jobs=1, indep=True,
random_state=None, memory=Memory(None), verbose=False):
"""Automatically detect when noise zone has been reached and stop
MP at th... |
python | def render_startmenu(self, ctx, data):
"""
For authenticated users, add the start-menu style navigation to the
given tag. For unauthenticated users, remove the given tag from the
output.
@see L{xmantissa.webnav.startMenu}
"""
if self.username is None:
... |
python | def unfinished_objects(self):
'''
Leaves only versions of those objects that has some version with
`_end == None` or with `_end > right cutoff`.
'''
mask = self._end_isnull
if self._rbound is not None:
mask = mask | (self._end > self._rbound)
oids = se... |
java | public void setInjectionBinding(InjectionBinding<?> injectionBinding) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "setInjectionBinding : " + injectionBinding);
ivInjectionBinding = injectionBinding;
} |
java | public static BigDecimal randomBigDecimal(BigDecimal min, BigDecimal max) {
return NumberUtil.toBigDecimal(getRandom().nextDouble(min.doubleValue(), max.doubleValue()));
} |
java | public Struct createStruct(String typeName,
Object[] attributes) throws SQLException {
checkClosed();
throw Util.notSupported();
} |
java | @Override
public void write(Iterable<QueryResult> results) {
logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results);
HttpURLConnection urlConnection = null;
try {
if (proxy == null) {
urlConnection = (HttpURLConnection) url.openConnection();
} else {
urlConnection = (HttpURLConn... |
python | def list_voices(
self,
language_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Returns a list of ``Voice`` supported for synthesis.
Example:
>>> from google.... |
java | private boolean goToNextDoc() throws IOException {
if (docId == NO_MORE_DOCS) {
return true;
} else {
docId = spans1.spans.nextDoc();
if (docId == NO_MORE_DOCS) {
return true;
} else {
int spans2DocId = spans2.spans.docID();
if (spans2DocId < docId) {
sp... |
java | private void downloadBitmap(final String path, final Object into, final Transformation transformation) {
//download the bitmap from bluetooth
new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
Bitmap bitmap = getBitma... |
python | def _to_python(cls, setting, raw_value):
"""
Convert a value stored in the database for a particular setting
to its correct type, as determined by ``register_setting()``.
"""
type_fn = cls.TYPE_FUNCTIONS.get(setting["type"], setting["type"])
try:
value = typ... |
java | @Trace(dispatcher = true)
public void removeRecord(Long recordId) throws GloboDnsException {
NewRelic.setTransactionName(null, "/globodns/removeRecord");
if (recordId == null) {
throw new GloboDnsException("Record id cannot be null");
}
GloboDnsRoot<Record> globoDnsRoot = this.delete("/records/" + record... |
python | def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2**np.arange(3, 6)):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size], dtype='float32') - 1
... |
java | public PreparedStatement prepareStatement(final String sql,
final int resultSetType,
final int resultSetConcurrency,
final int resultSetHoldability)
throws SQLException {
... |
java | boolean removeFromCorruptReplicasMap(Block blk, DatanodeDescriptor datanode) {
Collection<DatanodeDescriptor> datanodes = corruptReplicasMap.get(blk);
if (datanodes==null)
return false;
if (datanodes.remove(datanode)) { // remove the replicas
if (datanodes.isEmpty()) {
// remove the bloc... |
python | def execute_command(self, args, parent_environ=None, **subprocess_kwargs):
"""Run a command within a resolved context.
This applies the context to a python environ dict, then runs a
subprocess in that namespace. This is not a fully configured subshell -
shell-specific commands such as a... |
java | public void deserialize(final ByteBuffer buf) {
wordsInUse = buf.getInt();
words = new long[wordsInUse];
for (int i = 0; i < words.length; i++) {
words[i] = buf.getLong();
}
// Assume maximum length then find real length
// because recalculateWordsInUse assumes maintenance
// or reduction in logical s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.