language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void removeAll()
{
if (m_gridList != null)
m_gridList.removeAll();
if (m_gridBuffer != null)
m_gridBuffer.removeAll();
if (m_gridNew != null)
m_gridNew.removeAll();
m_iEndOfFileIndex = UNKNOWN_POSITION;
m_iPhysicalFilePosition = UNKN... |
python | def roles_accepted(*role_names):
"""| This decorator ensures that the current user is logged in,
| and has *at least one* of the specified roles (OR operation).
Example::
@route('/edit_article')
@roles_accepted('Writer', 'Editor')
def edit_article(): # User must be 'Writer' OR 'Ed... |
python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
C = self.COEFFS[imt]
M = rup.mag - 6
R = np.sqrt(dist... |
java | private String bytesToString(byte[] bytes, boolean truncate) {
CharsetDecoder decoder = Charset.defaultCharset()
.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
ByteBuffer byteBuffer = ByteBuffe... |
python | def xpathNewNodeSet(self):
"""Create a new xmlXPathObjectPtr of type NodeSet and
initialize it with the single Node @val """
ret = libxml2mod.xmlXPathNewNodeSet(self._o)
if ret is None:raise xpathError('xmlXPathNewNodeSet() failed')
return xpathObjectRet(ret) |
python | def check_debug():
"""Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwi... |
java | public MethodRefConstant addMethodRef(String className,
String name,
String type)
{
MethodRefConstant entry = getMethodRef(className, name, type);
if (entry != null)
return entry;
ClassConstant classEntry = addClass(cl... |
java | public static Query logical(LogOp op, Collection<Query> expressions) {
Query q = new Query(true);
for (Query x : expressions) {
((ArrayNode) q.node).add(x.toJson());
}
Query a = new Query(false);
a.add(op.toString(), q.toJson());
return a;
} |
java | public Observable<List<ModelInfoResponse>> listModelsAsync(UUID appId, String versionId, ListModelsOptionalParameter listModelsOptionalParameter) {
return listModelsWithServiceResponseAsync(appId, versionId, listModelsOptionalParameter).map(new Func1<ServiceResponse<List<ModelInfoResponse>>, List<ModelInfoRespo... |
java | protected void closeConnection(ThriftConnectionHandle<T> connection) {
if (connection != null) {
try {
connection.internalClose();
} catch (Throwable t) {
logger.error("Destroy connection exception", t);
} finally {
this.thriftConnectionPool.postDestroyConnection(connection);
}
}
} |
python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
# pylint: disable=too-many-arguments
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for specification of input and result values.
Implements the following eq... |
python | def initialize(self):
"""
Initializes network by calling Connection.initialize() and
Layer.initialize(). self.count is set to zero.
"""
print("Initializing '%s' weights..." % self.name, end=" ", file=sys.stderr)
if self.sharedWeights:
raise AttributeError("sha... |
java | public java.lang.String getProtocol() {
java.lang.Object ref = protocol_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
protoc... |
java | public void enableFollowLocation() {
mIsFollowing = true;
// set initial location when enabled
if (isMyLocationEnabled()) {
Location location = mMyLocationProvider.getLastKnownLocation();
if (location != null) {
setLocation(location);
}
}
// Update the screen to see changes take effect
if (mM... |
python | def convert_type(self, type):
"""Convert type to BigQuery
"""
# Mapping
mapping = {
'any': 'STRING',
'array': None,
'boolean': 'BOOLEAN',
'date': 'DATE',
'datetime': 'DATETIME',
'duration': None,
'geojso... |
python | def friction_plate_Martin_VDI(Re, plate_enlargement_factor):
r'''Calculates Darcy friction factor for single-phase flow in a
Chevron-style plate heat exchanger according to [1]_.
.. math::
\frac{1}{\sqrt{f_d}} = \frac{\cos \phi}{\sqrt{0.28\tan\phi
+ 0.36\sin\phi + f_0/\cos(\phi)}} + \... |
java | private void actionWrite() throws PageException {
if (output == null) throw new ApplicationException("attribute output is not defined for tag file");
checkFile(pageContext, securityManager, file, serverPassword, createPath, true, false, true);
if (file.exists()) {
// Error
if (nameconflict == NAMECONFLICT_... |
python | def write_data(self,variable_id, value, task):
"""
write values to the device
"""
variable = self._variables[variable_id]
if task.property_name != '':
# write the freq property to VariableProperty use that for later read
vp = VariableProperty.objects.updat... |
python | def snapshot(self):
"""Snapshot current state."""
self._snapshot = {
'muted': self.muted,
'volume': self.volume,
'stream': self.stream
}
_LOGGER.info('took snapshot of current state of %s', self.friendly_name) |
java | @Override
public AuditUtilityReturnCodes handleTask(ConsoleWrapper stdin, PrintStream stdout, PrintStream stderr, String[] args) throws Exception {
Map<String, String> argMap = parseArgumentList(args);
Map<String, String> props = convertToProperties(argMap);
if (props.isEmpty()) {
... |
java | public void getAllAchievementGroupID(Callback<List<String>> callback) throws NullPointerException {
gw2API.getAllAchievementGroupIDs().enqueue(callback);
} |
python | def end_frequency(self, index):
""" Return the end frequency of the waveform at the given index value
"""
from pycbc.waveform.waveform import props
return pycbc.waveform.get_waveform_end_frequency(
self.table[index],
approx... |
python | def rename(self, channel_name, new_name):
""" https://api.slack.com/methods/channels.rename
"""
channel_id = self.get_channel_id(channel_name)
self.params.update({
'channel': channel_id,
'name': new_name,
})
return FromUrl('https://slack.c... |
python | def _comment_type_from_line(line):
"""Return the "comment header" (' * ', '# ', 'rem ', '// ', '/* ').
This header goes before the content of a start of the
line in a replacement.
"""
regex = re.compile(r"^{0}".format(_ALL_COMMENT))
match = regex.match(line)
if match:
return "{0} ".... |
python | def reshape_axes(axes, shape, newshape, unknown=None):
"""Return axes matching new shape.
By default, unknown dimensions are labelled 'Q'.
>>> reshape_axes('YXS', (219, 301, 1), (219, 301))
'YX'
>>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1))
'QQYQXQ'
"""
shape = tuple... |
java | public static Single<Boolean> exists(String key, Object member) {
return exists(CacheService.CACHE_CONFIG_BEAN, key, member);
} |
java | public Set<Integer> getUnstoppedSlots(Set<Integer> aliveTasks, Map<String, SupervisorInfo> supInfos,
Assignment existAssignment) {
Set<Integer> ret = new HashSet<>();
Set<ResourceWorkerSlot> oldWorkers = existAssignment.getWorkers();
Set<String> aliveSu... |
python | def create_data_element(self, mapped_class=None):
"""
Returns a new data element for the given mapped class.
:returns: object implementing :class:`IResourceDataElement`.
"""
if not mapped_class is None and mapped_class != self.__mapped_cls:
mp = self.__mp_reg.find_or... |
python | def highlight_matches(self):
"""Highlight found results"""
if self.is_code_editor and self.highlight_button.isChecked():
text = self.search_text.currentText()
words = self.words_button.isChecked()
regexp = self.re_button.isChecked()
self.editor.highl... |
java | @Override
public MPSubscription getSubscription()
throws SIDurableSubscriptionNotFoundException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getSubscription");
ConsumerDispatcher cd = (ConsumerDispatcher) _localConsumerPoint... |
python | def get_paths(self, key):
''' Retrieve a set of environment paths from the config
Parameters:
key (str):
The section name to grab from the environment
Returns:
self.environ[newkey] (OrderedDict):
An ordered dict containing all of the path... |
java | @Override
public void initialize(JsMEConfig config) throws Exception {
String thisMethodName = CLASS_NAME + ".initialize(Object)";
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, thisMethodName, "");
}
meConfig = config;
creat... |
python | def simplify(self):
"""Return a simplified expression."""
node = self.node.simplify()
if node is self.node:
return self
else:
return _expr(node) |
java | public static double[] minusTimesEquals(final double[] v1, final double[] v2, final double s2) {
assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
for(int i = 0; i < v1.length; i++) {
v1[i] -= v2[i] * s2;
}
return v1;
} |
java | public JsonLdModule configure(ConfigParam param, String value) {
Objects.requireNonNull(param);
configuration.set(param, value);
return this;
} |
java | @FFDCIgnore({ SSLPeerUnverifiedException.class, Exception.class })
private Subject tryToAuthenticate(SSLSession session) throws SASException {
Subject transportSubject = null;
try {
transportSubject = authenticateWithCertificateChain(session);
} catch (SSLPeerUnverifiedException ... |
python | def send(self, sender=None, senders=None, key=None, keys=None, **kwargs):
'''
*This method is a coroutine.*
Schedules connected callbacks for execution. You may optionally supply ``senders`` and/or
``keys`` to include callbacks that were connected with one or more matching
``sen... |
python | def create_deployment(applicationName=None, deploymentGroupName=None, revision=None, deploymentConfigName=None, description=None, ignoreApplicationStopFailures=None, targetInstances=None, autoRollbackConfiguration=None, updateOutdatedInstancesOnly=None, fileExistsBehavior=None):
"""
Deploys an application revis... |
python | def splitword(self, originalword, *newwords, **kwargs):
"""TODO: Write documentation"""
if isstring(originalword):
originalword = self.doc[u(originalword)]
return self.correctwords([originalword], newwords, **kwargs) |
python | def safe_makedir(dname):
"""Make a directory if it doesn't exist, handling concurrent race conditions.
"""
if not dname:
return dname
num_tries = 0
max_tries = 5
while not os.path.exists(dname):
# we could get an error here if multiple processes are creating
# the directo... |
python | def get_outgroup(self):
"""Generates the outgroup line from the voucher code specified by the
user.
"""
if self.outgroup is not None:
outgroup_taxonomy = ''
for i in self.data.seq_records:
if self.outgroup == i.voucher_code:
out... |
python | def main():
""" The entry point for this module """
# first, check we can import aeneas package, exiting on failure
if check_import():
sys.exit(1)
# import and run the built-in diagnostics
from aeneas.diagnostics import Diagnostics
errors, warnings, c_ext_warnings = Diagnostics.check_al... |
python | def metadata_to_intermediary(metadata):
""" Transforms SQLAlchemy metadata to the intermediary representation. """
tables = [table_to_intermediary(table) for table in metadata.tables.values()]
relationships = [relation_to_intermediary(fk) for table in metadata.tables.values() for fk in table.foreign_keys]
... |
java | public RequestEvent waitNotify(long timeout) {
initErrorInfo();
synchronized (this) {
if (reqEvents.isEmpty()) {
try {
LOG.trace("about to block, waiting");
this.wait(timeout);
LOG.trace("we've come out of the block");
} catch (Exception ex) {
setEx... |
python | async def whois(self, nickname):
"""
Return information about user.
This is an blocking asynchronous method: it has to be called from a coroutine, as follows:
info = await self.whois('Nick')
"""
# Some IRCDs are wonky and send strange responses for spaces in nickname... |
java | @Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Status codeDecode() {
return Status.CODE_KEY.parseBytes("15".getBytes(Charset.forName("US-ASCII")));
} |
python | def integrate_gamma(v, v0, gamma0, q0, q1, theta0):
"""
internal function to calculate Debye temperature
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param ... |
python | def set_options(self, force_read=False, force_fulltext=False):
"""Set the options for this run."""
self.options['force_read'] = force_read
self.options['force_fulltext'] = force_fulltext
return |
python | def com_google_fonts_check_name_postscriptname(ttFont, style, familyname):
""" Check name table: POSTSCRIPT_NAME entries. """
from fontbakery.utils import name_entry_id
failed = False
for name in ttFont['name'].names:
if name.nameID == NameID.POSTSCRIPT_NAME:
expected_value = f"{familyname}-{style}"
... |
python | def visit_grouping(self, grouping, asfrom=False, **kwargs):
""""
TODO:
"""
return {
'type': 'grouping',
'grouping': grouping.element._compiler_dispatch(self, **kwargs)
} |
java | public static HttpResponse parseMessage(byte[] in) throws IOException {
HttpResponse m = new HttpResponse();
m.parse(new ByteArrayInputStream(in));
return m;
} |
python | def add_particles_ascii(self, s):
"""
Adds particles from an ASCII string.
Parameters
----------
s : string
One particle per line. Each line should include particle's mass, radius, position and velocity.
"""
for l in s.split("\n"):
r = l.... |
python | def to_one(dest_class, type=RelationType.DIRECT, resource_classes=None,
reverse=None, reverse_type=RelationType.DIRECT,
writable=False):
"""Create a one to one relation to a given target :class:`Resource`.
Args:
dest_class(Resource): The *target* class for the relationship
K... |
java | public void setCharset(Charset charset)
{
mutationCheck();
if (charset == null
|| charset.equals(ASCII)
|| charset.equals(UTF8))
{
myCharset = charset;
}
else
{
throw new IllegalArgumentException("Unsupported Charset "
... |
java | @Before("external() && access()")
public void lazilyInjectField(JoinPoint thisJoinPoint) {
FieldSignature fs = (FieldSignature) thisJoinPoint.getSignature();
Field field = fs.getField();
Object target = thisJoinPoint.getTarget();
injector.lazilyInject(target, field);
} |
java | @SuppressWarnings("checkstyle:magicnumber")
void writeLong(long value) {
if (value == Long.MIN_VALUE) {
write(STR_LONG_MIN_VALUE);
return;
}
if (value < 0) {
write('-');
value = -value;
}
int digitsWithoutComma = 0;
tm... |
python | def sendReset(self, sequenceId=0):
"""
Sends a reset signal to the network.
"""
for col in xrange(self.numColumns):
self.sensorInputs[col].addResetToQueue(sequenceId)
self.network.run(1) |
java | public NamedStoredProcedureQuery<T> resultSetMapping(String ... values)
{
if (values != null)
{
for(String name: values)
{
childNode.createChild("result-set-mapping").text(name);
}
}
return this;
} |
java | @Pure
public static GeodesicPosition L3_WSG84(double x, double y) {
final Point2d ntfLambdaPhi = NTFLambert_NTFLambdaPhi(x, y,
LAMBERT_3_N,
LAMBERT_3_C,
LAMBERT_3_XS,
LAMBERT_3_YS);
return NTFLambdaPhi_WSG84(ntfLambdaPhi.getX(), ntfLambdaPhi.getY());
} |
python | def before_request(request, tracer=None):
"""
Attempts to extract a tracing span from incoming request.
If no tracing context is passed in the headers, or the data
cannot be parsed, a new root span is started.
:param request: HTTP request with `.headers` property exposed
that satisfies a re... |
java | @Override
public void close() {
try {
xmlSerializer.close();
} catch (Exception e) {
e.printStackTrace();
throw new KriptonRuntimeException(e);
}
} |
python | def check_signature(params):
"""
Verify the signature of the parameters in an OTP v2.0 verify request.
Returns ValResultBool, Key
"""
if 'id' in params:
try:
id_int = int(params['id'][0])
except:
my_log_message(args, syslog.LOG_INFO, "Non-numerical client id ... |
python | def getChangeSets(self):
"""Get all the ChangeSets of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.ChangeSet` objects
:rtype: list
"""
changeset_tag = ("rtc_cm:com.ibm.team.filesystem.workitems."
"change_s... |
java | public void process(final String beanName,
final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
InputStream is = request.getInputStream();
OutputStream os = response.getOutputStream();
Hessian2Input in = new Hessian2Input(is);
AbstractHessi... |
java | protected final String replaceMacro(String macroName, String text, String replacement, ReplacementType type,
File sourceFile, int sourceLine) {
return replaceMacro(macroName, text, replacement, type, false, sourceFile, sourceLine);
} |
java | static synchronized Mutator mutatorFor(Class<?> type, String name, InheritingConfiguration configuration) {
PropertyInfoKey key = new PropertyInfoKey(type, name, configuration);
if (!MUTATOR_CACHE.containsKey(key) || !FIELD_CACHE.containsKey(key)) {
@SuppressWarnings("unchecked")
Class<Object> u... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "measure")
public JAXBElement<MeasureType> createMeasure(MeasureType value) {
return new JAXBElement<MeasureType>(_Measure_QNAME, MeasureType.class, null, value);
} |
python | def match_all_concepts(self,string):
'''Returns sorted list of all :class:`Concept`s matching ``string``'''
multipliers = {'exact':10**5,'fname':10**4,'fuzzy':10**2,'fuzzy_fragment':1}
matches = []
for concept in self.vocab:
matches += concept.matches(string,self.fuzzy,self.f... |
python | def update(self, batch_size, ignore_stale_grad=False):
"""Makes one step of parameter update.
Should be called after `autograd.backward()` and outside of `record()` scope,
and after `trainer.update()`.
For normal parameter updates, `step()` should be used, which internally calls
... |
java | public PolylineMarkers addPolylineToMapAsMarkers(GoogleMap map,
PolylineOptions polylineOptions,
MarkerOptions polylineMarkerOptions,
PolylineOptions globalPolyl... |
java | private int getStartingPoint(String buffer) {
for (int i = 0; i < buffer.length(); i++) {
if (!Character.isWhitespace(buffer.charAt(i))) {
return i;
}
}
return buffer.length();
} |
python | def activate(self, key):
"""
Activates a new registree on the LEX with given activation key
:rtype: None
"""
url = self._base + 'user/activate'
r = requests.get(url, params={
'activation_key': key
})
r.raise_for_status() |
java | @Override
public List<Object> getServices(Class<?> root,Class<?> transactionType){
Map<Class<?>, List<Object>> map = mapBusinessProvider.get(root);
if(map != null){
List<Object> list = map.get(transactionType);
if(list != null){
return Collections.unmodifiableList(list);
}
}
return null;
... |
java | protected ResourceAdapterMBeanImpl setResourceAdapterChild(String key, ResourceAdapterMBeanImpl ra) {
return raMBeanChildrenList.put(key, ra);
} |
python | def import_env(*envs):
'import environment variables from host'
for env in envs:
parts = env.split(':', 1)
if len(parts) == 1:
export_as = env
else:
env, export_as = parts
env_val = os.environ.get(env)
if env_val is not None:
yield '{}=... |
java | private void redimNodeArrays(int newsize) {
int len = newsize < lo.length ? newsize : lo.length;
char[] na = new char[newsize];
System.arraycopy(lo, 0, na, 0, len);
lo = na;
na = new char[newsize];
System.arraycopy(hi, 0, na, 0, len);
hi = na;
na = new cha... |
python | def get_sari_score(source_ids, prediction_ids, list_of_targets,
max_gram_size=4, beta_for_deletion=0):
"""Compute the SARI score for a single prediction and one or more targets.
Args:
source_ids: a list / np.array of SentencePiece IDs
prediction_ids: a list / np.array of SentencePiece ID... |
java | public static void isNotBlankThen(String str, Consumer<String> consumer) {
notBankAccept(str, Function.identity(), consumer);
} |
java | protected void actionBack() {
if (m_dialogIndex <= 0) {
return;
}
m_dialogIndex--;
m_uploadPropertyPanel.getPropertyEditor().getForm().validateAndSubmit();
m_nextAction = new Runnable() {
public void run() {
loadDialogBean(m_resources.ge... |
java | public static void writeProteinSequence(OutputStream outputStream,
Collection<ProteinSequence> proteinSequences) throws Exception {
GenbankWriter<ProteinSequence, AminoAcidCompound> genbankWriter = new GenbankWriter<ProteinSequence, AminoAcidCompound>(
outputStream,
proteinSequences,
new GenericGenban... |
java | public static String[] partitionOptions(String[] options) {
for (int i = 0; i < options.length; i++) {
if (options[i].equals("--")) {
options[i++] = "";
String[] result = new String [options.length - i];
for (int j = i; j < options.length; j++) {
result[j - i] = options[j];
options[j] = "";
}
retu... |
python | def _update(self, data):
"""Update the object with new data."""
for k, v in six.iteritems(data):
new_value = v
if isinstance(v, dict):
new_value = type(self)(v)
elif isinstance(v, list):
new_value = [(type(self)(e) if isinstance(e, dict... |
java | public OpportunitiesTasksResponse getOpportunitiesTasksTaskId(Integer taskId, String datasource, String ifNoneMatch)
throws ApiException {
ApiResponse<OpportunitiesTasksResponse> resp = getOpportunitiesTasksTaskIdWithHttpInfo(taskId, datasource,
ifNoneMatch);
return resp.getD... |
python | def get_workunit(self, ignore_list=None):
"""
Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been proce... |
python | def _generate_command(self, func, name=None, **kwargs):
"""Generates a command parser for given func.
:param func: func to generate related command parser
:param type: function
:param name: command name
:param type: str
:param **kwargs: keyword arguments those passed t... |
java | public static <T> Id<T> newId(final TypeToken<T> type) {
return (Id<T>) Ids.newId(type.getType());
} |
java | public int getPredictedClass(){
if(predictedClass == -1){
if(classPredictions.rank() == 1){
predictedClass = classPredictions.argMax().getInt(0);
} else {
// ravel in case we get a column vector, or rank 2 row vector, etc
predictedClass = c... |
python | def logout(self):
"""Logout from anaconda cloud."""
logger.debug('Logout')
method = self._anaconda_client_api.remove_authentication
return self._create_worker(method) |
python | def parse_session_cookie(cookie_to_cook):
""" cookie_to_cook = http_header['cookie']
"""
#print("cookie_to_cook: %s"%str(cookie_to_cook))
session_value = None
tokens = cookie_to_cook.split(";")
for tok in tokens:
if 'remi_session=' in tok:
#print("found session id: %s"%str(to... |
python | def surveys(self):
"""
Returns the list of timesteps when survey measures has been captured
None if xml document is mailformed
xpath: /scenario/monitoring/survey
https://github.com/SwissTPH/openmalaria/wiki/GeneratedSchema32Doc#survey-times-time-steps
"""
survey_t... |
java | private Object decodeResult(IoBuffer data) {
log.debug("decodeResult - data limit: {}", (data != null ? data.limit() : 0));
processHeaders(data);
int count = data.getUnsignedShort();
if (count != 1) {
throw new RuntimeException("Expected exactly one result but got " + co... |
java | public float[][] getPhi() {
float[][] phi = new float[K][V];
if (SAMPLE_LAG > 0) {
for (int k = 0; k < K; k++) {
for (int w = 0; w < V; w++) {
phi[k][w] = phisum[k][w] / numstats;
}
}
} else {
for (i... |
python | def savestate(self, state):
"""Save the sampler's state in a state.txt file."""
oldstate = np.get_printoptions()
np.set_printoptions(threshold=1e6)
try:
with open(os.path.join(self._directory, 'state.txt'), 'w') as f:
print_(state, file=f)
finally:
... |
java | private GroupElement find_i(final String n, final boolean fwd) {
if (name_equals(n)) {
return this;
}
GroupElement e = null;
Iterator it = elements.iterator();
while (it.hasNext()) {
e = (GroupElement) it.next();
if (e.name_equals(n)) {
return e;
}
}
if (fwd) {
it = elements.iterator()... |
java | public synchronized void removeExpired()
{
final List<String> removeLockList = new ArrayList<String>();
for (LockData lock : getLockList())
{
if (!lock.isSessionScoped() && lock.getTimeToDeath() < 0)
{
removeLockList.add(lock.getNodeIdentifier());
}
}
... |
python | def gen_gmfs(self):
"""
Compute the GMFs for the given realization and
yields arrays of the dtype (sid, eid, imti, gmv), one for rupture
"""
self.sig_eps = []
for computer in self.computers:
rup = computer.rupture
sids = computer.sids
e... |
python | def load_data_split(proc_data_dir):
"""Loads a split dataset
Args:
proc_data_dir: Directory with the split and processed data
Returns:
(Training Data, Validation Data, Test Data)
"""
ds_train = Dataset.load(path.join(proc_data_dir, 'train.bin'))
ds_val = Dataset... |
java | public static ClassFileVersion ofMinorMajor(int versionNumber) {
ClassFileVersion classFileVersion = new ClassFileVersion(versionNumber);
if (classFileVersion.getMajorVersion() <= BASE_VERSION) {
throw new IllegalArgumentException("Class version " + versionNumber + " is not valid");
... |
python | def to_pn(self, sub_letter=None):
"""
Returns the part number equivalent. For instance,
a '1k' would still be '1k', but a
'1.2k' would, instead, be a '1k2'
:return:
"""
string = str(self)
if '.' not in string:
return string
# take car... |
java | private void loadTemplates( Element parent )
{
// Load templates
List templates = DomUtils.getChildElementsByName( parent, URL_TEMPLATE );
for ( int i = 0; i < templates.size(); i++ )
{
Element template = ( Element ) templates.get( i );
String name = getElemen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.