language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private static boolean encodeFileToFile(String infile, String outfile)
{
boolean success = false;
java.io.InputStream in = null;
java.io.OutputStream out = null;
try
{
in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);
out = new java.io.Buf... |
java | private boolean methodThrowsException(Method method,
Class<? extends Exception> exceptionType) {
// Check whether the method throws an exception of the specified type
for (Class<?> thrownType : method.getExceptionTypes()) {
if (exceptionType.isAssignableFrom(thrownType))
... |
java | public static <T, U> DictionaryFeatureVectorGenerator<T, U> createFromData(Collection<T> data,
FeatureGenerator<T, U> generator, boolean ignoreOovFeatures) {
IndexedList<U> features = new IndexedList<U>();
for (T datum : data) {
features.addAll(generator.generateFeatures(datum).keySet());
}
... |
python | def disarm(self, wait=True, timeout=None):
'''Disarm the vehicle.
If wait is True, wait for disarm operation to complete before
returning. If timeout is nonzero, raise a TimeouTerror if the
vehicle has not disarmed after timeout seconds.
'''
self.armed = False
... |
python | def packages(self, name=None, memory=None, disk=None, swap=None,
version=None, vcpus=None, group=None):
"""
::
GET /:login/packages
:param name: the label associated with the resource package
:type name: :py:class:`basestring`
... |
java | public void warnv(Throwable t, String format, Object... params) {
doLog(Level.WARN, FQCN, format, params, t);
} |
java | public void defineApplication(ApplicationDefinition appDef) {
checkServiceState();
Tenant tenant = TenantService.instance().getDefaultTenant();
defineApplication(tenant, appDef);
} |
python | def string_to_file(path, input):
"""
Write a file from a given string.
"""
mkdir_p(os.path.dirname(path))
with codecs.open(path, "w+", "UTF-8") as file:
file.write(input) |
python | def local_assortativity_wu_sign(W):
'''
Local assortativity measures the extent to which nodes are connected to
nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014
formula to allowed weighted/signed networks.
Parameters
----------
W : NxN np.ndarray
undirected conne... |
java | @Override
public UpdateUserPhoneConfigResult updateUserPhoneConfig(UpdateUserPhoneConfigRequest request) {
request = beforeClientExecution(request);
return executeUpdateUserPhoneConfig(request);
} |
python | def get_val(self):
"""
Gets attribute's value.
@return: stored value.
@rtype: int
@raise IOError: if corresponding file in /proc/sys cannot be read.
"""
with open(os.path.join(self._base, self._attr), 'r') as file_obj:
return int(file_obj.readline()) |
python | def from_socket(controller, host=None, port=None, track_path=None, log_level=logging.ERROR):
"""Create rocket instance using socket connector"""
rocket = Rocket(controller, track_path=track_path, log_level=log_level)
rocket.connector = SocketConnector(controller=controller,
... |
python | def as_dict(self):
"""Return a dictionary containing this `Fact` data."""
return {k: unfreeze(v)
for k, v in self.items()
if not self.is_special(k)} |
java | public int getParentExpressionIndex(int index) {
if (index == 0) {
return -1;
} else {
int[] parts = findSubexpression(index);
int parentIndex = subexpressions.get(parts[0]).getParentExpressionIndex(parts[1]);
if (parentIndex == -1) {
// index refers to a child of this exp... |
python | def is_set(self, key):
"""Return True if variable is a set"""
data = self.model.get_data()
return isinstance(data[key], set) |
python | def _match(self):
"""Find all matches and generate a position group for each match."""
#disable optimized matching
optimized_rows = None
optimized_columns = None
for match in self.__match_rows(optimized_rows):
#match in rows
yield match
for match i... |
python | def weld_cast_scalar(scalar, to_weld_type):
"""Returns the scalar casted to the request Weld type.
Parameters
----------
scalar : {int, float, WeldObject}
Input array.
to_weld_type : WeldType
Type of each element in the input array.
Returns
-------
WeldObject
Re... |
python | def watch():
"""Renerate documentation when it changes."""
# Start with a clean build
sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG
handler = ShellCommandTrick(
shell_command='sphinx-build -b html docs docs/_build/html',
patterns=['*.rst', '*.py'],
ignore_pa... |
python | def end(self, s=None, post=None, noraise=False):
""" Prints the end banner and raises ``ProgressOK`` exception
When ``noraise`` flag is set to ``True``, then the exception is not
raised, and progress is allowed to continue.
If ``post`` function is supplied it is invoked with no argumen... |
java | public String makeCaptureQueryUrl(String url) {
WaybackRequest newWBR = wbRequest.clone();
newWBR.setCaptureQueryRequest();
newWBR.setRequestUrl(url);
return newWBR.getAccessPoint().getQueryPrefix() + "query?" +
newWBR.getQueryArguments(1);
} |
python | def insert(self, index, value):
'''Insert a node in-place. It is highly suggested that you do not
use this method. Use assoc instead'''
newnode = LookupTreeNode(index, value)
level = 0
node = self.root
while True:
ind = _getbits(newnode.index, level)
... |
python | def nano_sub(bind, tables):
"""Nanomsg fanout sub. (Experimental)
This sub will use nanomsg to fanout the events.
:param bind: the zmq pub socket or zmq device socket.
:param tables: the events of tables to follow.
"""
logger = logging.getLogger("meepo.sub.nano_sub")
from nanomsg import S... |
java | public double f(double[] x) {
double max = Double.NEGATIVE_INFINITY;
Benchmark.Ax(m_z, m_A, x);
for (int i = 0; i < mDimension; i++) {
double temp = Math.abs(m_z[i] - m_B[i]);
if (max < temp) {
max = temp;
}
}
return (max + mBias);
} |
java | public String getUri() {
String uri = m_context.addSiteRoot(m_context.getUri());
if (m_detailViewId != null) {
uri += m_detailViewId.toString() + "/";
}
return uri;
} |
java | public void store(DataSink sink) {
try {
localControlChannel.resetReplyCount();
if (session.transferMode != GridFTPSession.MODE_EBLOCK) {
//
// no EBLOCK
//
EBlockParallelTransferContext context =
(EBlo... |
python | def _write_tree(self, tree: dict, output: Union[str, BinaryIO], file_mode: int=0o666) -> None:
"""
Write the model to disk.
:param tree: The data dict - will be the ASDF tree.
:param output: The output file path or a file object.
:param file_mode: The output file's permissions.
... |
python | def delete_repository_method(namespace, name, snapshot_id):
"""Redacts a method and all of its associated configurations.
The method should exist in the methods repository.
Args:
namespace (str): Methods namespace
method (str): method name
snapshot_id (int): snapshot_id of the meth... |
python | def draw_additive_plot(data, figsize, show, text_rotation=0):
"""Draw additive plot."""
# Turn off interactive plot
if show == False:
plt.ioff()
# Format data
neg_features, total_neg, pos_features, total_pos = format_data(data)
# Compute overall metrics
base_value = data['b... |
java | public void replaceMenuById(SubMenuItem subMenu, MenuItem toReplace) {
synchronized (subMenuItems) {
ArrayList<MenuItem> list = subMenuItems.get(subMenu);
int idx = -1;
for (int i = 0; i < list.size(); ++i) {
if (list.get(i).getId() == toReplace.getId()) {
... |
python | def GlobalAvgPooling(x, data_format='channels_last'):
"""
Global average pooling as in the paper `Network In Network
<http://arxiv.org/abs/1312.4400>`_.
Args:
x (tf.Tensor): a 4D tensor.
Returns:
tf.Tensor: a NC tensor named ``output``.
"""
assert x.shape.ndims == 4
dat... |
python | def reload(self, config=None, debug=False):
""" load/reload configuration
@dict: configuration of ldapcherry
"""
try:
# log configuration handling
# get log level
# (if not in configuration file, log level is set to debug)
level = get_logle... |
python | def change(self, inpt, hashfun=DEFAULT_HASHFUN):
"""Change the avatar by providing a new input.
Uses the standard hash function if no one is given."""
self.img = self.__create_image(inpt, hashfun) |
python | def updateEvolution(self):
'''
Updates the "population punk proportion" evolution array. Fasion victims
believe that the proportion of punks in the subsequent period is a linear
function of the proportion of punks this period, subject to a uniform
shock. Given attributes of sel... |
java | public static boolean matchMobile(String str) {
if (StringUtils.isEmpty(str)) return false;
return Pattern.matches(REG_MOBILE, str.trim());
} |
java | public static String printSymbol(SymbolToken token){
return String.format("{$%s:%s}", token.getText(), token.getSid());
} |
python | def clone(self, data=None, shared_data=True, new_type=None, link=True,
*args, **overrides):
"""Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
... |
python | def GetFormatsWithSignatures(cls, parser_filter_expression=None):
"""Retrieves the format specifications that have signatures.
This method will create a specification store for parsers that define
a format specification with signatures and a list of parser names for
those that do not.
Args:
... |
python | def get_priority(self) -> int:
"""
Rerturns the priority of the file from 1 (pre) to 3 (post)
:return: the priority
"""
dtype = self.get_type()
if dtype & DeltaType.PRE:
return 1
elif dtype & DeltaType.POST:
return 3
else:
... |
java | public void initialize(final int appId, ICallStatsTokenGenerator tokenGenerator,
final String bridgeId, final ServerInfo serverInfo,
final CallStatsInitListener callStatsInitListener) {
if (appId <= 0 || StringUtils.isBlank(bridgeId) || serverInfo == null
|| callStatsInitListener == null) {
... |
python | def validate_settings(settings):
"""Ensure all user-supplied settings exist, or throw a useful error message.
:param obj settings: The Django settings object.
"""
if not (settings.STORMPATH_ID and settings.STORMPATH_SECRET):
raise ImproperlyConfigured('Both STORMPATH_ID and STORMPATH_SECRET mus... |
java | public final static void itos(long i, int index, char[] buf) {
if (i == Long.MIN_VALUE) {
// -9223372036854775808
buf[--index] = '8';
buf[--index] = '0';
buf[--index] = '8';
buf[--index] = '5';
buf[--index] = '7';
buf[--index] = '7';
buf[--index] = '4';
buf[--index] = '5';
buf[--index] =... |
python | def l1_log_loss(event_times, predicted_event_times, event_observed=None):
r"""
Calculates the l1 log-loss of predicted event times to true event times for *non-censored*
individuals only.
.. math:: 1/N \sum_{i} |log(t_i) - log(q_i)|
Parameters
----------
event_times: a (n,) array of obs... |
python | def write(self, f):
"""
Write an SBOL file from current document contents
"""
rdf = ET.Element(NS('rdf', 'RDF'), nsmap=XML_NS)
# TODO: TopLevel Annotations
sequence_values = sorted(self._sequences.values(), key=lambda x: x.identity)
self._add_to_root(rdf, sequenc... |
python | def set_target_temp(self, temperature):
"""
Sets the target temperature, to the requested int
"""
if 35 < temperature < 5:
logging.info("Refusing to set temp outside of allowed range")
return False
else:
self._hm_send_address(self.addre... |
java | private Collection<FileStatus> toFileStatusesWithImplicitDirectories(
Collection<FileInfo> fileInfos) throws IOException {
List<FileStatus> fileStatuses = new ArrayList<>(fileInfos.size());
Set<URI> filePaths = Sets.newHashSetWithExpectedSize(fileInfos.size());
String userName = getUgiUserName();
... |
python | def main():
''' main program loop '''
conn = symphony.Config('/etc/es-bot/es-bot.cfg')
# connect to pod
try:
agent, pod, symphony_sid = conn.connect()
print ('connected: %s' % (symphony_sid))
except Exception as err:
print ('failed to connect!: %s' % (err))
# main loop
... |
python | def getFoundIns(self, projectarea_id=None, projectarea_name=None,
archived=False):
"""Get all :class:`rtcclient.models.FoundIn` objects by
project area id or name
If both `projectarea_id` and `projectarea_name` are `None`,
all the foundins in all project areas will b... |
python | def batch(samples):
"""CWL: batch together per sample, joint and germline calls for ensemble combination.
Sets up groups of same sample/batch variant calls for ensemble calling, as
long as we have more than one caller per group.
"""
samples = [utils.to_single_data(x) for x in samples]
sample_or... |
python | def weekday_series(self, start, end, weekday, return_date=False):
"""Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, ... |
python | def plot_monthly_ic_heatmap(mean_monthly_ic, ax=None):
"""
Plots a heatmap of the information coefficient or returns by month.
Parameters
----------
mean_monthly_ic : pd.DataFrame
The mean monthly IC for N periods forward.
Returns
-------
ax : matplotlib.Axes
The axes t... |
python | def get_font_options(self):
"""Copies the scaled font’s options.
:returns: A new :class:`FontOptions` object.
"""
font_options = FontOptions()
cairo.cairo_scaled_font_get_font_options(
self._pointer, font_options._pointer)
return font_options |
python | def do_POST(self):
"""
This method will be called for each POST request to one of the
listener ports.
It parses the CIM-XML export message and delivers the contained
CIM indication to the stored listener object.
"""
# Accept header check described in DSP0200
... |
java | public static <T> AsyncHandler<Response<ByteString>> autoSerialize(AsyncHandler<T> inner) {
return serialize(new AutoSerializer()).apply(inner);
} |
python | def _snort_cmd(self, pcap):
"""
Given a pcap filename, get the commandline to run.
:param pcap: Pcap filename to scan
:returns: list of snort command args to scan supplied pcap file
"""
cmdline = "'{0}' -A console -N -y -c '{1}' {2} -r '{3}'" \
.format(self.c... |
python | def filter_on_wire_representation(ava, acs, required=None, optional=None):
"""
:param ava: A dictionary with attributes and values
:param acs: List of tuples (Attribute Converter name,
Attribute Converter instance)
:param required: A list of saml.Attributes
:param optional: A list of saml.At... |
java | public void setWorkingDirectory(Path dir) throws IOException {
ensureState(JobState.DEFINE);
conf.setWorkingDirectory(dir);
} |
python | def thaw_args(subparsers):
"""Add command line options for the thaw operation"""
thaw_parser = subparsers.add_parser('thaw')
thaw_parser.add_argument('--gpg-password-path',
dest='gpg_pass_path',
help='Vault path of GPG passphrase location')
thaw_... |
python | def _set_time(self, m):
'''set time for a message'''
# really just left here for profiling
m._timestamp = self.timestamp
if len(m._fieldnames) > 0 and self.clock is not None:
self.clock.set_message_timestamp(m) |
python | def go_in(self, vertex):
"""
Tell the edge to go into this vertex.
Args:
vertex (Vertex): vertex to go into.
"""
if self.vertex_in:
self.vertex_in.edges_in.remove(self)
self.vertex_in = vertex
vertex.edges_in.add(self) |
python | def execute(self, query, vars=None, result=False):
""".. :py:method::
:param bool result: whether query return result
:rtype: bool
.. note::
True for `select`, False for `insert` and `update`
"""
with self.connection() as cur:
if self.debug:
... |
java | Mono<Void> delayAsync() {
Mono<Void> result = Mono.empty();
if (delayInMilliseconds > 0) {
result = result.delaySubscription(Duration.ofMillis(delayInMilliseconds));
}
return result;
} |
java | public static <T extends File> T createFile(final SecurityContext securityContext, final InputStream fileStream, final String contentType, final Class<T> fileType, final String name, final Folder parentFolder)
throws FrameworkException, IOException {
final PropertyMap props = new PropertyMap();
props.put(Struct... |
python | def query(self, xri, service_types):
"""Resolve some services for an XRI.
Note: I don't implement any service endpoint selection beyond what
the resolver I'm querying does, so the Services I return may well
include Services that were not of the types you asked for.
May raise fe... |
python | def set_root_prefix(self, prefix=None):
"""
Set the prefix to the root environment (default is /opt/anaconda).
This function should only be called once (right after importing
conda_api).
"""
if prefix:
self.ROOT_PREFIX = prefix
else:
# Fin... |
python | def _load_from_string(data):
'''Loads the cache from the string'''
global _CACHE
if PYTHON_3:
data = json.loads(data.decode("utf-8"))
else:
data = json.loads(data)
_CACHE = _recursively_convert_unicode_to_str(data)['data'] |
python | def build(algo, init):
'''Build and return an optimizer for the rosenbrock function.
In downhill, an optimizer can be constructed using the build() top-level
function. This function requires several Theano quantities such as the loss
being optimized and the parameters to update during optimization.
... |
python | def trim(hdu):
"""TRIM a CFHT MEGAPRIME frame using the DATASEC keyword"""
datasec = re.findall(r'(\d+)',
hdu.header.get('DATASEC'))
l=int(datasec[0])-1
r=int(datasec[1])
b=int(datasec[2])-1
t=int(datasec[3])
if opt.verbose:
print "Trimming [%d:%d,%d:%d]" % ... |
python | def call(self, transaction=None, block_identifier='latest'):
"""
Execute a contract function call using the `eth_call` interface.
This method prepares a ``Caller`` object that exposes the contract
functions and public variables as callable Python functions.
Reading a public ``o... |
java | private Result doDecode(BinaryBitmap image,
Map<DecodeHintType,?> hints) throws NotFoundException {
int width = image.getWidth();
int height = image.getHeight();
BitArray row = new BitArray(width);
boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDE... |
python | def _phiTilde(self, r, N,L):
"""
NAME:
_phiTilde
PURPOSE:
Evaluate phi_tilde as defined in equation 3.10 and 2.25 for 0 <= n < N and 0 <= l < L
INPUT:
r - Evaluate at radius r
N - size of the N dimension
L - size of the L dimension
... |
java | public Optional<Nengo> findNext() {
if (this.court == COURT_NORTHERN) {
if (this.index == NORTHERN_NENGOS.length - 1) {
return Optional.of(NENGO_OEI);
} else {
return Optional.of(NORTHERN_NENGOS[this.index + 1]);
}
} else if (this.inde... |
python | def eval_hooks(self):
"""
Evaluate the current state of this Source and
invoke any attached hooks if they've been triggered
"""
logging.debug("Evaluating hooks")
if self.get_edge_triggered():
logging.debug("Hook triggered")
for hook in [h for h in ... |
java | public void waitUntilReady() throws InterruptedException, CouldNotPerformException {
try {
while (true) {
try {
waitUntilReadyFuture().get((JPService.testMode() ? 4 : 300), TimeUnit.SECONDS);
break;
} catch (final TimeoutExcepti... |
java | public boolean isLocal()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "isLocal");
boolean isLocal = false;
if (foreignDest.getResolvedDestinationHandler().getLocalLocalizationPoint() != null)
isLocal = true;
if (TraceComponent.isAnyTracing... |
python | def _notify_breakpoint(self, event):
"""
Notify breakpoints of a breakpoint exception event.
@type event: L{ExceptionEvent}
@param event: Breakpoint exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
... |
python | def add_base_type_dynamically(error_type, additional_type):
"""
Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type
(second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names
(fully qualified for t... |
python | def request(self, verb, path, **params):
'''
A helper function for making generic POST requests calls. It is used by
every namespaced API method. It can be used to make any generic API
call that is automatically authenticated using your API credentials:
.. code-block:: python
... |
python | def load_sqlite(self, db, query=None, table=None, cls=None,
column_map=None):
"""Load data from sqlite db and return as list of specified objects."""
if column_map is None:
column_map = {}
db_path = self.profile_path(db, must_exist=True)
def obj_factory(c... |
java | @Override
public Node getParentNode(String parentNodeId)
{
NodeLink link = new NodeLink(parentNodeId, getNodeId());
if (this.parents == null)
{
return null;
}
else
{
return this.parents.get(link);
}
} |
python | def upload(df, gfile="/New Spreadsheet", wks_name=None,
col_names=True, row_names=True, clean=True, credentials=None,
start_cell = 'A1', df_size = False, new_sheet_dimensions = (1000,100)):
'''
Upload given Pandas DataFrame to Google Drive and returns
gspread Worksheet object
... |
python | def check_multi_output_plate_compatibility(source_plates, sink_plate):
"""
Check multi-output plate compatibility. This ensures that the source plates and sink plates match for a multi-
output plate
:param source_plates: The source plates
:param sink_plate: The sink plate
... |
java | public File getFileUnchecked(String fileName) {
validatePathname(fileName);
return new File(storageDir + separator + fileName);
} |
java | protected <T> RegistrationAnnotatedBindingBuilder<T> register(Class<T> type) {
return registryBinderImpl.register(type);
} |
java | private void writeNotes(int recordNumber, String text) throws IOException
{
m_buffer.setLength(0);
m_buffer.append(recordNumber);
m_buffer.append(m_delimiter);
if (text != null)
{
String note = stripLineBreaks(text, MPXConstants.EOL_PLACEHOLDER_STRING);
boolean quote... |
python | def init_app(self, app, sessionstore=None, register_blueprint=True):
"""Flask application initialization.
:param app: The Flask application.
:param sessionstore: store for sessions. Passed to
``flask-kvsession``. If ``None`` then Redis is configured.
(Default: ``None``)
... |
java | @Override
public List<String> getSSODomainList() {
WebAppSecurityConfig globalConfig = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig();
if (globalConfig != null)
return WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().getSSODomainList();
else
... |
java | public ServiceFuture<SummarizeResultsInner> summarizeForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, final ServiceCallback<SummarizeResultsInner> serviceCallback) {
return ServiceFuture.fromResponse(summarizeForResourceGroupLevelPolicyAssi... |
java | private boolean findLongestMatch(final char[] revA,
final ArrayList<Integer> list, final char[] revB, final int index)
{
int match;
longestMatch_size = -1;
int size = list.size();
int revAsize = revA.length;
int revBsize = revB.length;
int start, end, count;
for (int i = 0; i < size; i++) {
sta... |
java | public int addFunction(FunctionNode fnNode) {
if (fnNode == null) codeBug();
if (functions == null)
functions = new ArrayList<FunctionNode>();
functions.add(fnNode);
return functions.size() - 1;
} |
python | def setType(self, polygonID, polygonType):
"""setType(string, string) -> None
Sets the (abstract) type of the polygon.
"""
self._connection._beginMessage(
tc.CMD_SET_POLYGON_VARIABLE, tc.VAR_TYPE, polygonID, 1 + 4 + len(polygonType))
self._connection._packString(poly... |
java | public static String tooltip(Field field) {
final String tooltip = field.getTooltip();
if (tooltip == null) {
return "";
}
return "<img class='tooltip' title='" + tooltip + "' alt='?' src='"
+ getContextPath() + "/templates/"
+ getTemplate() + ... |
python | def get_response_structure(name):
"""
Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown
"""
return {
CreateContextName.SMB2_CREATE_DURAB... |
python | def merge_metadata(preprocess_output_dir, transforms_file):
"""Merge schema, analysis, and transforms files into one python object.
Args:
preprocess_output_dir: the output folder of preprocessing. Should contain
the schema, and the numerical and categorical
analysis files.
transforms_file: ... |
java | private void storeKey(SecretKey key) {
final String keyStoreFile = getMain().getFileSystemManager().getSystemLocation() + File.separator + "izou.keystore";
KeyStore keyStore = createKeyStore(keyStoreFile, "4b[X:+H4CS&avY<)");
try {
KeyStore.SecretKeyEntry keyStoreEntry = new KeyStor... |
java | void removeComputer(final Computer computer) {
Queue.withLock(new Runnable() {
@Override
public void run() {
Map<Node,Computer> computers = getComputerMap();
for (Map.Entry<Node, Computer> e : computers.entrySet()) {
if (e.getValue() ==... |
python | def Run(self, arg):
"""Does the actual work."""
try:
if self.grr_worker.client.FleetspeakEnabled():
raise ValueError("Not supported on Fleetspeak enabled clients.")
except AttributeError:
pass
smart_arg = {str(field): value for field, value in iteritems(arg)}
disallowed_fields ... |
python | def _get_tokens(self, authn_response, context):
"""
:param authn_response: authentication response from OP
:type authn_response: oic.oic.message.AuthorizationResponse
:return: access token and ID Token claims
:rtype: Tuple[Optional[str], Optional[Mapping[str, str]]]
"""
... |
python | def check_xups_env_ambient_temp(the_session, the_helper, the_snmp_value, the_unit=1):
"""
OID .1.3.6.1.4.1.534.1.6.1.0
MIB Excerpt
The reading of the ambient temperature in the vicinity of the
UPS or SNMP agent.
"""
the_helper.add_metric(
label=the_helper.options.type,
... |
java | public void readData(InputStream inputStream) throws IOException {
if (inputStream == null) {
return;
}
data = ParserUtils.parseBinary(inputStream, (int) size.getValue());
} |
java | @SuppressWarnings("unchecked")
public static <E, D extends Dataset<E>> D update(
URI uri, DatasetDescriptor descriptor, Class<E> type) {
Preconditions.checkArgument(
URIBuilder.DATASET_SCHEME.equals(uri.getScheme()),
"Not a dataset or view URI: " + uri);
Preconditions.checkNotNull(type,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.