language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public InternalFieldErrorBuilder createFieldConversionError(final String field, final Class<?> fieldType, final Object rejectedValue) {
final String fieldPath = buildFieldPath(field);
final String[] codes = messageCodeGenerator.generateTypeMismatchCodes(getObjectName(), fieldPath, fieldType)... |
python | def add_output(self, out_name, type_or_serialize=None, **kwargs):
""" Declare an output
"""
if out_name not in self.engine.all_outputs():
raise ValueError("'%s' is not generated by the engine %s" % (out_name, self.engine.all_outputs()))
if type_or_serialize is None:
... |
python | def set_data(self, data):
""" Set the scalar array data
Parameters
----------
data : ndarray
A 2D array of scalar values. The isocurve is constructed to show
all locations in the scalar field equal to ``self.levels``.
"""
self._data = data
... |
java | public <T extends Variable> Object deserialize(AgentClassWrapper wrapper,
List<T> variables) {
return deserialize(wrapper, wrapper.newInstance(), variables);
} |
java | private void processPredecessors(Gantt gantt)
{
for (Gantt.Tasks.Task ganttTask : gantt.getTasks().getTask())
{
String predecessors = ganttTask.getP();
if (predecessors != null && !predecessors.isEmpty())
{
String wbs = ganttTask.getID();
Task task = m_t... |
java | public AsyncQueryRunnerService overrideOnce(String operation, Object value) {
this.queryRunner.overrideOnce(operation, value);
return this;
} |
java | public static String colorToHex(Color color) {
return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
} |
python | def _wait_for_files(path):
"""
Retry with backoff up to 1 second to delete files from a directory.
:param str path: The path to crawl to delete files from
:return: A list of remaining paths or None
:rtype: Optional[List[str]]
"""
timeout = 0.001
remaining = []
while timeout < 1.0:
... |
python | def get_id(self):
"""
get unique identifier of this container
:return: str
"""
if self._id is None:
# FIXME: provide a better error message when key is not defined
self._id = self.inspect(refresh=False)["Id"]
return self._id |
python | def get_derived_from(self, address):
"""Get the target the specified target was derived from.
If a Target was injected programmatically, e.g. from codegen, this allows us to trace its
ancestry. If a Target is not derived, default to returning itself.
:API: public
"""
parent_address = self._de... |
java | public SetSubtitleVodNonDvdOperation buildSetSubtitleVodNonDvdOperation(String track, String color, int fontSize, int position, String encoding, String timeOffset){
return new SetSubtitleVodNonDvdOperation(getOperationFactory(), track, color, fontSize, position, encoding, timeOffset);
} |
java | private Expression parseBooleanExpression(Expression expr) {
if (tokens.positiveLookahead(AND)) {
tokens.consume();
expr = new And(expr, parseSemVerExpression());
} else if (tokens.positiveLookahead(OR)) {
tokens.consume();
expr = new Or(expr, parseSemVerExpression());
}
return e... |
python | def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_val... |
java | public void writeComment(String comment) throws KNXMLException
{
try {
w.write("<!--");
w.write(comment);
w.write("-->");
w.newLine();
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} |
python | def resendLast(self):
"Resend the last sent packet due to a timeout."
log.warning("Resending packet %s on sessions %s"
% (self.context.last_pkt, self))
self.context.metrics.resent_bytes += len(self.context.last_pkt.buffer)
self.context.metrics.add_dup(self.context.last_pkt)
... |
java | public void setAccessKey(char accessKey) {
if (accessKey == 0x00)
return;
_anchorState.registerAttribute(AbstractHtmlState.ATTR_GENERAL, HtmlConstants.ACCESSKEY, Character.toString(accessKey));
} |
java | private void writeHierarchy(Object object, ObjectStreamClass classDesc)
throws IOException, NotActiveException {
if (object == null) {
throw new NotActiveException();
}
// Fields are written from class closest to Object to leaf class
// (down the chain)
L... |
java | public static boolean storeOnApplicationPrivateDir(Context context, Bitmap bitmap, String filename, Bitmap.CompressFormat format, int quality) {
OutputStream out = null;
try {
out = new BufferedOutputStream(context.openFileOutput(filename, Context.MODE_PRIVATE));
return bitmap.co... |
python | def tunnel(self, local_port, remote_port=None, remote_host="localhost"):
"""
Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context.
Remember to close() the returned "tunnel" object in order to clean up
after yourself when you are d... |
java | protected SparseArray<ReleaseItem> readChangeLog(XmlPullParser xml, boolean full) {
SparseArray<ReleaseItem> result = new SparseArray<ReleaseItem>();
try {
int eventType = xml.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlP... |
java | public void dumpTo(AreaTree tree, PrintWriter out)
{
if (produceHeader)
out.println("<?xml version=\"1.0\"?>");
out.println("<areaTree base=\"" + HTMLEntities(tree.getRoot().getPage().getSourceURL().toString()) + "\">");
recursiveDump(tree.getRoot(), 1, out);
out.println(... |
python | def clip_upper(self, threshold, axis=None, inplace=False):
"""
Trim values above a given threshold.
.. deprecated:: 0.24.0
Use clip(upper=threshold) instead.
Elements above the `threshold` will be changed to match the
`threshold` value(s). Threshold can be a single ... |
python | def to_bool(self, value):
""" Converts a sheet string value to a boolean value.
Needed because of utf-8 conversions
"""
try:
value = value.lower()
except:
pass
try:
value = value.encode('utf-8')
except:
pass
... |
java | public void setReadOnly(boolean readOnly) throws SQLException {
if (!changable) {
throw new SQLException(AdapterUtil.getNLSMessage("WS_INTERNAL_ERROR",
new Object[] {
... |
python | def close_client(self, index=None, client=None, force=False):
"""Close client tab from index or widget (or close current tab)"""
if not self.tabwidget.count():
return
if client is not None:
index = self.tabwidget.indexOf(client)
# if index is not found i... |
java | public static double getTMScore(Atom[] atomSet1, Atom[] atomSet2, int len1, int len2) throws StructureException {
return getTMScore(atomSet1, atomSet2, len1, len2,true);
} |
java | @Override
public void readPoiFileInfo() {
PoiFileInfoBuilder poiFileInfoBuilder = new PoiFileInfoBuilder();
Cursor cursor = null;
try {
cursor = this.db.rawQuery(DbConstants.FIND_METADATA_STATEMENT, null);
while (cursor.moveToNext()) {
String name = c... |
java | @SuppressWarnings("unchecked") @Override
public double magnitude() {
// Check whether the current magnitude is valid and if not, recompute it
if (magnitude < 0) {
double m = 0;
// Special case if we can iterate in time linear to the number of
// non-zero values
... |
python | def get_object(model, cid, engine_name=None, connection=None):
"""
Get cached object from redis
if id is None then return None:
"""
from uliweb import settings
if not id:
return
if not check_enable():
return
redis = get_redis()
if not redis: retur... |
java | public Connection beginTransaction(ConnectionSource connectionSource, int isolationLevel) {
Connection connection = new Connection(this, connectionSource, false);
boolean success = false;
try {
connection.getJdbcConnection().setAutoCommit(false);
connection.getJdbcConne... |
python | def on_delete_interpretation_button(self, event):
"""
delete the current interpretation temporarily (not to a file)
"""
del self.Data[self.s]['pars']
self.Data[self.s]['pars'] = {}
self.Data[self.s]['pars']['deleted'] = True
self.Data[self.s]['pars']['lab_dc_fiel... |
python | def frames_adapter(process_func):
'''
Pre-processing decorator that adapt frames to match input_blocksize and
input_stepsize of the decorated analyzer
>>> from timeside.core.preprocessors import frames_adapter
>>> @frames_adapter
... def process(analyzer,frames,eod):
... analyzer.frames... |
python | def parse_footnote(document, container, elem):
"Parse the footnote element."
_rid = elem.attrib[_name('{{{w}}}id')]
foot = doc.Footnote(_rid)
container.elements.append(foot) |
python | def _render_pages(self):
"""Render the complete document once and return the number of pages
rendered."""
self.style_log = StyleLog(self.stylesheet)
self.floats = set()
self.placed_footnotes = set()
self._start_time = time.time()
part_page_counts = {}
par... |
python | def detect_algorithm(cls, link):
"""Detect the hashing algorithm from the fragment in the link, if any."""
if any(link.fragment.startswith('%s=' % algorithm) for algorithm in HASHLIB_ALGORITHMS):
algorithm, value = link.fragment.split('=', 2)
try:
return hashlib.new(algorithm), value
e... |
java | public boolean isDeathRelatedEvent(final Attribute event) {
if (isDeathEvent(event)) {
return true;
}
if (isPostDeathEvent(event)) {
return true;
}
return isUnorderedEvent(event);
} |
java | int doIO(ByteBuffer buf, int ops) throws IOException {
/* For now only one thread is allowed. If user want to read or write
* from multiple threads, multiple streams could be created. In that
* case multiple threads work as well as underlying channel supports it.
*/
if (!buf.hasRemaining()) ... |
java | public DescribeTagsResult withTags(ConfigurationTag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<ConfigurationTag>(tags.length));
}
for (ConfigurationTag ele : tags) {
this.tags.add(ele);
}
return this;
} |
java | public <V> SortedMap<T, V> toSortedMap(Function<? super T, ? extends V> valMapper) {
return toSortedMap(Function.identity(), valMapper);
} |
java | protected void readTemporalProposition(ObjectInputStream s)
throws IOException, ClassNotFoundException {
int mode = s.readChar();
try {
switch (mode) {
case 0:
setInterval(INTERVAL_FACTORY.getInstance(s.readLong(),
(... |
java | @Override
public void run() {
synchronized (this) {
started = true;
}
finished = false;
final byte[] buf = new byte[bufferSize];
try {
int length;
while (true) {
waitForInput(is);
if (finish || Thread.interrupted()) {
break;
}
length ... |
java | public void resetPage() {
CmsConfirmDialog dialog = new CmsConfirmDialog(
Messages.get().key(Messages.GUI_DIALOG_RESET_TITLE_0),
"<p>" + Messages.get().key(Messages.GUI_DIALOG_PAGE_RESET_0) + "</p>");
dialog.setCloseText(Messages.get().key(Messages.GUI_BUTTON_CANCEL_TEXT_0));
... |
java | public void setStateChanges(java.util.Collection<AssessmentRunStateChange> stateChanges) {
if (stateChanges == null) {
this.stateChanges = null;
return;
}
this.stateChanges = new java.util.ArrayList<AssessmentRunStateChange>(stateChanges);
} |
java | @Override
public com.liferay.commerce.model.CommerceOrder createCommerceOrder(
long commerceOrderId) {
return _commerceOrderLocalService.createCommerceOrder(commerceOrderId);
} |
python | def get_random_subreddit(self, nsfw=False):
"""Return a random Subreddit object.
:param nsfw: When true, return a random NSFW Subreddit object. Calling
in this manner will set the 'over18' cookie for the duration of the
PRAW session.
"""
path = 'random'
... |
python | def pca(df, n_components=2, mean_center=False, **kwargs):
"""
Principal Component Analysis, based on `sklearn.decomposition.PCA`
Performs a principal component analysis (PCA) on the supplied dataframe, selecting the first ``n_components`` components
in the resulting model. The model scores and weights ... |
python | def get_sequence(self, c, i, depth):
"""
Get the sequence.
Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc.
It will basically crawl to the end or find a valid series.
"""
result = []
release = self.set_expanding()
has_comma = False # U... |
java | private void putDataPoint(final int i, final DataPoint dp) {
timestamps[i] = dp.timestamp();
if (dp.isInteger()) {
//LOG.debug("Putting #" + i + " (long) " + dp.longValue()
// + " @ time " + dp.timestamp());
values[i] = dp.longValue();
} else {
//LOG.debug("Putting #" + i + ... |
python | def run_once(runner_list=None, extra_tick=Sleep(0.001), use_poll=False, auto_stop=True):
"""
:param auto_stop when tick error occur, stop all runners, except:
if error was from a runner tick and the runner has set 'only_stop_self_when_tick_error' to True,
then only this runner stop
"""
i... |
java | public static void warn(final Object message, final Throwable t) {
warnStream.println(APP_WARN + message.toString());
warnStream.println(stackTraceToString(t));
} |
java | JPanel createSourceCodePanel() {
Font sourceFont = new Font("Monospaced", Font.PLAIN, (int) Driver.getFontSize());
mainFrame.getSourceCodeTextPane().setFont(sourceFont);
mainFrame.getSourceCodeTextPane().setEditable(false);
mainFrame.getSourceCodeTextPane().getCaret().setSelectionVisible... |
java | protected void computeOutlierScores(KNNQuery<O> knnq, final DBIDs ids, WritableDataStore<double[]> densities, WritableDoubleDataStore kdeos, DoubleMinMax minmax) {
final int knum = kmax + 1 - kmin;
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Computing KDEOS scores", ids.size(), LOG) : null;
... |
python | def update(self, **kwargs):
"""
Overrides update to concatenate streamed data up to defined length.
"""
data = kwargs.get('data')
if data is not None:
if (util.pd and isinstance(data, util.pd.DataFrame) and
list(data.columns) != list(self.data.columns)... |
python | def spaceless(context, nodelists):
"""
Removes whitespace between HTML tags, including tab and newline characters.
Example usage::
{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
This example would return this HTML::
... |
python | def _latex_(self):
r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
... |
python | def _check_total_z_extents(self, ds, z_variable):
'''
Check the entire array of Z for minimum and maximum and compare that to
the vertical extents defined in the global attributes
:param netCDF4.Dataset ds: An open netCDF dataset
:param str z_variable: Name of the variable repre... |
java | protected void reload(final boolean forceReload) throws IOException {
boolean reload = forceReload;
for (int i = 0; i < locations.length; i++) {
Resource location = locations[i];
File file;
try {
file = location.getFile();
} catch (IOExce... |
java | private static int runCommand(final TSDB tsdb,
final boolean use_data_table,
final String[] args) throws Exception {
final int nargs = args.length;
if (args[0].equals("lookup")) {
if (nargs < 2) { // need a query
usage(null, "Not enou... |
python | def _prepare_request(self, url, method, headers, data):
"""Prepare HTTP request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: JSON-encodable object.
:rtype: httpclient.HTTPRequest
"""
... |
python | def logout (self):
'''Sends exit to the remote shell.
If there are stopped jobs then this automatically sends exit twice.
'''
self.sendline("exit")
index = self.expect([EOF, "(?i)there are stopped jobs"])
if index==1:
self.sendline("exit")
self.ex... |
java | @Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case SimpleAntlrPackage.AND_EXPRESSION__LEFT:
return left != null;
case SimpleAntlrPackage.AND_EXPRESSION__RIGHT:
return right != null;
}
return super.eIsSet(featureID);
} |
java | public void setChaincodeEndorsementPolicy(LifecycleChaincodeEndorsementPolicy chaincodeEndorsementPolicy) throws InvalidArgumentException {
if (null == chaincodeEndorsementPolicy) {
throw new InvalidArgumentException(" The parameter chaincodeEndorsementPolicy may not be null.");
}
va... |
java | public void parseUnixListReply(String reply)
throws FTPException {
if (reply == null) return;
StringTokenizer tokens = new StringTokenizer(reply);
String token, previousToken;
int numTokens = tokens.countTokens();
if (numTokens < 8) {
throw new FTPException... |
java | public static void fillBand(InterleavedF64 input, int band , double value) {
final int numBands = input.numBands;
for (int y = 0; y < input.height; y++) {
int index = input.getStartIndex() + y * input.getStride() + band;
int end = index + input.width*numBands - band;
for (; index < end; index += numBands ... |
python | def replay_job(self, task, submission, copy=False, debug=False):
"""
Replay a submission: add the same job in the queue, keeping submission id, submission date and input data
:param submission: Submission to replay
:param copy: If copy is true, the submission will be copied to admin subm... |
java | private void throwQError(final QConnectorError e) {
this.executor.execute(new Runnable() {
@Override
public void run() {
QConnectorAsyncImpl.this.listener.error(e);
}
});
} |
python | def has_attr(self, name):
"""Returns boolean indicating presence of given attribute name
Case-insensitive check
Notes
-----
Does not check higher order meta objects
Parameters
----------
name : str
name of variable to... |
python | def identify(**kwargs):
"""Create OAI-PMH response for verb Identify."""
cfg = current_app.config
e_tree, e_identify = verb(**kwargs)
e_repositoryName = SubElement(
e_identify, etree.QName(NS_OAIPMH, 'repositoryName'))
e_repositoryName.text = cfg['OAISERVER_REPOSITORY_NAME']
e_baseURL... |
python | def update(self):
'''
Use primitive parameters (and perfect foresight calibrations) to make
interest factor and wage rate functions (of capital to labor ratio),
as well as discrete approximations to the aggregate shock distributions.
Parameters
----------
None
... |
java | @Override public ValFrame apply(Env env, Env.StackHelp stk, AstRoot asts[]) {
Frame fr = stk.track(asts[1].exec(env)).getFrame(); // first argument is dataframe
int[] groupbycols = ((AstParameter)asts[2]).columns(fr.names());
int[] sortcols =((AstParameter)asts[3]).columns(fr.names()); // sort columns
... |
java | public static <R> Function<Object,R[]> arrayOf(final Type<R> resultType, final String methodName, final Object... optionalParameters) {
return methodForArrayOf(resultType, methodName, optionalParameters);
} |
python | def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
result = super(JSONLDTransformerMixin, self).transform_record(
pid, record, links_factory, **kwargs
)
return self.transform_jsonld(result) |
python | def extract_morphological_information(mrph_object, is_feature, is_surface):
# type: (pyknp.Morpheme, bool, bool) -> TokenizedResult
"""This method extracts morphlogical information from token object.
"""
assert isinstance(mrph_object, pyknp.Morpheme)
assert isinstance(is_feature, bool)
assert is... |
python | def verify_is_not(self, first, second, msg=None):
"""
Soft assert for whether the parameters do not evaluate to the same object
:params want: the object to compare against
:params second: the object to compare with
:params msg: (Optional) msg explaining the difference
""... |
java | @Override
public double getFinishedPercentage() {
if (done) return 1d;
final int[] lastDecomposition = this.lastDecomposition;
if (lastDecomposition == null) return 0;
double result = 0.0;
double remainingPerc = 1.0;
for (int i = lastDecomposition.length - 1; i >= 0;... |
java | public synchronized long endCopy(CopyOperationImpl op) throws SQLException {
if (!hasLock(op)) {
throw new PSQLException(GT.tr("Tried to end inactive copy"), PSQLState.OBJECT_NOT_IN_STATE);
}
try {
LOGGER.log(Level.FINEST, " FE=> CopyDone");
pgStream.sendChar('c'); // CopyDone
pgSt... |
java | public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {
final ContentItem item = createBundleItem(moduleName, slot, newHash);
addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));
return return... |
python | def toggle_mute(self, controller, zone):
""" Toggle mute on/off for a zone
Note: Not tested (acambitsis) """
send_msg = self.create_send_message("F0 @cc 00 7F 00 @zz @kk 05 02 02 00 00 F1 40 00 00 00 0D 00 01",
controller, zone)
self.send_data... |
python | def monmap(cluster, hostname):
"""
Example usage::
>>> from ceph_deploy.util.paths import mon
>>> mon.monmap('mycluster', 'myhostname')
/var/lib/ceph/tmp/mycluster.myhostname.monmap
"""
monmap
mon_map_file = '%s.%s.monmap' % (cluster, hostname)
return join(constants.tmp_... |
java | public Variable createVariable(Object groupIdOrPath, String key, String value, Boolean isProtected) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("key", key, true)
.withParam("value", value, true)
.withParam("protected", isPr... |
python | def get_ordered_entries(self, queryset=False):
"""
Custom ordering. First we get the average views and rating for
the categories's entries. Second we created a rank by multiplying
both. Last, we sort categories by this rank from top to bottom.
Example:
- Cat_1
... |
java | public <T extends TextView> T searchFor(Callable<Collection<T>> viewFetcherCallback, String regex, int expectedMinimumNumberOfMatches, long timeout, boolean scroll) throws Exception {
final long endTime = SystemClock.uptimeMillis() + timeout;
Collection<T> views;
while (true) {
final boolean timedOut = timeo... |
python | def _wrap(value):
"""
Wraps the passed value in a Sequence if it is not a primitive. If it is a string
argument it is expanded to a list of characters.
>>> _wrap(1)
1
>>> _wrap("abc")
['a', 'b', 'c']
>>> type(_wrap([1, 2]))
functional.pipeline.Sequence
:param value: value to ... |
java | private static void updateCloseable(boolean register,Closeable closeable)
{
boolean updated=false;
synchronized(CloseableResourceManager.class)
{
if(register)
{
if(CloseableResourceManager.active)
{
//update resource... |
python | def installed(name, user, admin_user, admin_password, admin_email, title, url):
'''
Run the initial setup of wordpress
name
path to the wordpress installation
user
user that owns the files for the wordpress installation
admin_user
username for wordpress website administrat... |
java | public Optional<PluginsAlertCondition> create(long policyId, PluginsAlertCondition condition)
{
return HTTP.POST(String.format("/v2/alerts_plugins_conditions/policies/%d.json", policyId), condition, PLUGINS_ALERT_CONDITION);
} |
python | def get_arrhenius_plot(temps, diffusivities, diffusivity_errors=None,
**kwargs):
"""
Returns an Arrhenius plot.
Args:
temps ([float]): A sequence of temperatures.
diffusivities ([float]): A sequence of diffusivities (e.g.,
from DiffusionAnalyzer.diffusivit... |
java | public boolean isCacheable(Cache cache, Object target, Object[] arguments, Object result) throws Exception {
boolean rv = true;
if (null != cache.condition() && cache.condition().length() > 0) {
rv = this.getElValue(cache.condition(), target, arguments, result, true, Boolean.class);
... |
java | public static Object getByXPath(String expression, Object source, QName returnType) {
final XPath xPath = createXPath();
try {
if (source instanceof InputSource) {
return xPath.evaluate(expression, (InputSource) source, returnType);
} else {
return xPath.evaluate(expression, source, returnType);... |
java | @Override
public void cleanUpTempCatalogJar() {
File configInfoDir = getConfigDirectory();
if (!configInfoDir.exists()) {
return;
}
File tempJar = new VoltFile(configInfoDir.getPath(),
InMemoryJarfile.TMP_CATALOG_JAR_FILENAME);
... |
python | def execute(self, conn, block_name="", transaction = False):
"""
block: /a/b/c#d
"""
if not conn:
dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/BlockParent/List. Expects db connection from upper layer.", self.logger.exception)
sql = self.sql
if i... |
java | @Override
public void onActivityResumed(Activity activity) {
HMSAgentLog.d("onResumed:" + StrUtils.objDesc(activity));
setCurActivity(activity);
List<IActivityResumeCallback> tmdCallbacks = new ArrayList<IActivityResumeCallback>(resumeCallbacks);
for (IActivityResumeCallback c... |
java | public void visit(int version, int access, String name, String signature,
String supername, String[] interfaces) {
this.version = version;
this.access = access;
this.name = name;
this.signature = signature;
this.supername = supername;
this.interfaces... |
java | public static Document parse(URL url, int timeoutMillis) throws IOException {
Connection con = HttpConnection.connect(url);
con.timeout(timeoutMillis);
return con.get();
} |
python | def overrides(method):
'''
Meant to be used as
class B:
@overrides(A.m1)
def m1(self):
pass
'''
def wrapper(func):
if func.__name__ != method.__name__:
msg = "Wrong @override: %r expected, but overwriting %r."
msg = msg % (func.__name_... |
java | private CalculateAge resolveCalculateAge(Expression e, DateTimePrecision p) {
CalculateAge operator = of.createCalculateAge()
.withPrecision(p)
.withOperand(e);
builder.resolveUnaryCall("System", "CalculateAge", operator);
return operator;
} |
python | def respond(self, prompt_id, response):
"""Respond to the prompt with the given ID.
If there is no active prompt or the given ID doesn't match the active
prompt, do nothing.
Args:
prompt_id: A string uniquely identifying the prompt.
response: A string response to the given prompt.
Ret... |
python | def register_alarm(self, alarm):
"""Register (create) an alarm.
:param AlarmType|list[AlarmType] alarm: Alarm.
"""
for alarm in listify(alarm):
if alarm not in self._alarms:
self._set('alarm', alarm, multi=True)
self._alarms.append(alarm)
... |
java | @Override
public ListConfigurationRevisionsResult listConfigurationRevisions(ListConfigurationRevisionsRequest request) {
request = beforeClientExecution(request);
return executeListConfigurationRevisions(request);
} |
python | def _resolv_name(self, hostname):
"""Convert hostname to IP address."""
ip = hostname
try:
ip = socket.gethostbyname(hostname)
except Exception as e:
logger.debug("{}: Cannot convert {} to IP address ({})".format(self.plugin_name, hostname, e))
return ip |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.