language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public JsProcessComponent getProcessComponent(String className) {
String thisMethodName = CLASS_NAME + ".getProcessComponent(String)";
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, thisMethodName, className);
}
if (TraceComponent.isAnyT... |
python | def GetCredential(self, path_spec, identifier):
"""Retrieves a specific credential from the key chain.
Args:
path_spec (PathSpec): path specification.
identifier (str): credential identifier.
Returns:
object: credential or None if the credential for the path specification
is no... |
python | def choices(self):
"""Menu options for new configuration files
"""
print("| {0}K{1}{2}eep the old and .new files, no changes".format(
self.red, self.endc, self.br))
print("| {0}O{1}{2}verwrite all old configuration files with new "
"ones".format(self.red, self.e... |
python | def load_local_file(self, file_path, namespace=None, graph=None, **kwargs):
""" Uploads data to the Blazegraph Triplestore that is stored in files
in directory that is available locally to blazegraph
args:
file_path: full path to the file
namespace: the B... |
java | public void reloadUsers(int contextId) {
List<User> users = new ArrayList<User>(usersExtension.getContextUserAuthManager(contextId).getUsers());
tableModel = new UsersSelectTableModel(users);
this.setModel(tableModel);
} |
java | private void increaseBeliefCount(String bName) {
Object belief = this.getBelief(bName);
int count = 0;
if (belief!=null) {
count = (Integer) belief;
}
this.setBelief(bName, count + 1);
} |
python | def _FormatOtherFileToken(self, token_data):
"""Formats an other file token as a dictionary of values.
Args:
token_data (bsm_token_data_other_file32): AUT_OTHER_FILE32 token data.
Returns:
dict[str, str]: token values.
"""
# TODO: if this timestamp is useful, it must be extracted as a ... |
python | def make_extractor(non_default):
"""
Return us a function to extract options
Anything not in non_default is wrapped in a "Default" object
"""
def extract_options(template, options):
for option, val in normalise_options(template):
name = option.replace('-', '_')
... |
java | private static void createDemoButtons() {
JPanel buttonPanel = new JPanel(new WrapLayout());
panel.scrollPaneForButtons.setViewportView(buttonPanel);
// Create each demo button, and add it to the panel.
// Add an action listener to link it to its appropriate function.
JButton sho... |
python | def _pad_plot_frame(ax, pad=0.01):
"""
Provides padding on sides of frame equal to pad fraction of plot
"""
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
xr = xmax - xmin
yr = ymax - ymin
ax.set_xlim(xmin - xr*pad, xmax + xr*pad)
ax.set_ylim(ymin - yr*pad, ymax + yr*pad)
... |
python | def recipients_incremental(self, start_time):
"""
Retrieve NPS Recipients incremental
:param start_time: time to retrieve events from.
"""
return self._query_zendesk(self.endpoint.recipients_incremental, 'recipients', start_time=start_time) |
python | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(SquidCollector, self).get_default_config()
config.update({
'hosts': ['localhost:3128'],
'path': 'squid',
})
return config |
java | @Override
public <T> ManagedObjectFactory<T> createManagedObjectFactory(ModuleMetaData mmd, Class<T> klass, boolean requestManagingInjectionAndInterceptors,
ReferenceContext referenceContext) throws ManagedObjectException {
if (isCDIEnabled(m... |
java | ImmutableMap<String, Object> readAttributes(File file, String attributes) {
state.checkOpen();
return this.attributes.readAttributes(file, attributes);
} |
java | public void setClientInfo(final Properties properties)
throws SQLClientInfoException {
if (properties == null) {
throw new IllegalArgumentException();
} // end of if
if (this.closed) {
throw new SQLClientInfoException();
} // end of if
this.cli... |
java | public WebReply determineWebReply(Subject receivedSubject, String uriName, WebRequest webRequest) {
WebReply webReply = performInitialChecks(webRequest, uriName);
if (webReply != null) {
logAuditEntriesBeforeAuthn(webReply, receivedSubject, uriName, webRequest);
return webReply;... |
java | public static void pushMessages(String queueURL, List<String> messages) {
if (!StringUtils.isBlank(queueURL) && messages != null) {
// only allow strings - ie JSON
try {
int j = 0;
List<SendMessageBatchRequestEntry> msgs = new ArrayList<>(MAX_MESSAGES);
for (int i = 0; i < messages.size(); i++) {
... |
java | public static String toBinaryString(byte[] b) {
StringBuilder s = new StringBuilder();
for (byte by : b) {
for (int j = 7; j >= 0; j--) {
if ((by & (1 << j)) > 0) {
s.append('1');
} else {
s.append('0');
}
}
s.append(' ');
}
retur... |
python | def zip(*args, **kwargs):
""" Returns a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables (or default if too short).
"""
args = [list(iterable) for iterable in args]
n = max(map(len, args))
v = kwargs.get("default", None)
ret... |
java | public static <P, T> PositionFactory<P, T> optional(Function<? super P, ? extends T> accessor) {
Validate.isInstanceOf(Accessor.class, accessor, "Cannot detect property from %s; missing %s?", accessor,
THERIAN_PROPERTY_METHOD_WEAVER);
final boolean optional = true;
return new Positio... |
python | def data(self, index, role):
"""Reimplemented from QtCore.QAbstractItemModel
:param index: the index
:type index: QModelIndex
:param role: the data role
:type role: QtCore.Qt.ItemDataRole
:returns: some data. for display role it returns the filename of the configobj
... |
java | public static Map<String, Object> toMapWithDefault(String value, Map<String, Object> defaultValue) {
Map<String, Object> result = toNullableMap(value);
return result != null ? result : defaultValue;
} |
java | public static TFImportStatus checkAllModelsForImport(File directory) throws IOException {
Preconditions.checkState(directory.isDirectory(), "Specified directory %s is not actually a directory", directory);
Collection<File> files = FileUtils.listFiles(directory, new String[]{"pb"}, true);
Precon... |
python | def get_children_as_time_series(self, json_children, time_field=['entity','occurred']):
result = []
time_field_as_path_list = time_field.strip().split(".")
if len(time_field_as_path_list) == 0:
return result
"""
FROM:
{
"id": "60411677",
... |
python | def popitem(self):
"""remove the next prioritized [key, val, priority] and return it"""
pq = self.pq
while pq:
priority, key, val = heapq.heappop(pq)
if val is None:
self.removed_count -= 1
else:
del self.item_finder[key]
... |
python | def render(self, validate=True):
"""Render the training program to perform the calculations.
The program can be rendered several times to produce new
information given the same input parameters.
Parameters
----------
validate
Boolean that indicates whethe... |
python | def execute(self, lst):
'''
execute - Execute the series of filters, in order, on the provided list.
@param lst <list/ A QueryableList type> - The list to filter. If you already know the types of items within
the list, you can pick a QueryableList implementing class to g... |
java | protected CoverageDataSourcePixel getXSourceMinAndMax(float source) {
int floor = (int) Math.floor(source);
float valueLocation = getXEncodedLocation(floor,
griddedCoverage.getGridCellEncodingType());
CoverageDataSourcePixel pixel = getSourceMinAndMax(source, floor,
valueLocation);
return pixel;
} |
java | protected void dialogButtonsHtml(StringBuffer result, int button, String attribute) {
attribute = appendDelimiter(attribute);
switch (button) {
case BUTTON_OK:
result.append("<input name=\"ok\" value=\"");
result.append(key(Messages.GUI_DIALOG_BUTTON_OK_0) +... |
python | def clear_halt(self, ep):
r""" Clear the halt/stall condition for the endpoint ep."""
if isinstance(ep, Endpoint):
ep = ep.bEndpointAddress
self._ctx.managed_open()
self._ctx.backend.clear_halt(self._ctx.handle, ep) |
java | public static base_response update(nitro_service client, cacheselector resource) throws Exception {
cacheselector updateresource = new cacheselector();
updateresource.selectorname = resource.selectorname;
updateresource.rule = resource.rule;
return updateresource.update_resource(client);
} |
java | protected static void warn(Object mojo, String msg) throws Exception {
Method method = mojo.getClass().getMethod(GET_LOG_METHOD);
method.setAccessible(true);
Object logObject = method.invoke(mojo);
method = logObject.getClass().getMethod(WARN_METHOD, CharSequence.class);
method.s... |
python | def est_entropy(self):
r"""
Estimates the entropy of the current particle distribution
as :math:`-\sum_i w_i \log w_i` where :math:`\{w_i\}`
is the set of particles with nonzero weight.
"""
nz_weights = self.particle_weights[self.particle_weights > 0]
return -np.s... |
java | public Observable<RedisResourceInner> getByResourceGroupAsync(String resourceGroupName, String name) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, name).map(new Func1<ServiceResponse<RedisResourceInner>, RedisResourceInner>() {
@Override
public RedisResourceInner... |
java | @Override
@GraphTransaction
public String getInputsGraph(String tableName) throws AtlasException {
LOG.info("Fetching lineage inputs graph for tableName={}", tableName);
tableName = ParamChecker.notEmpty(tableName, "table name");
TypeUtils.Pair<String, String> typeIdPair = validateDatase... |
python | def meth_list(args):
""" List workflows in the methods repository """
r = fapi.list_repository_methods(namespace=args.namespace,
name=args.method,
snapshotId=args.snapshot_id)
fapi._check_response_code(r, 200)
# Parse the JSON fo... |
python | def get_player_img(player_id):
"""
Returns the image of the player from stats.nba.com as a numpy array and
saves the image as PNG file in the current directory.
Parameters
----------
player_id: int
The player ID used to find the image.
Returns
-------
player_img: ndarray
... |
java | private void checkRunButton()
{
runButton.setEnabled((pcRadio.isSelected() ||
(customFileRadio.isSelected() && !modelField.getText().trim().isEmpty()) ||
(customURLRadio.isSelected() && !urlField.getText().trim().isEmpty()))
&& !outputField.getText().trim().isEmpty());
} |
python | def draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color,
draw):
"""Draws a triangle on each half of the tile with the given coordinates
and size.
"""
assert split in ('right', 'left')
# The four corners of this tile
nw = (tile_x, tile_y)
ne = (tile_x ... |
python | def mon_hosts(mons):
"""
Iterate through list of MON hosts, return tuples of (name, host).
"""
for m in mons:
if m.count(':'):
(name, host) = m.split(':')
else:
name = m
host = m
if name.count('.') > 0:
name = name.split('.'... |
java | public void mergeCluster() {
int maxc1 = -1;
int maxc2 = -1;
float maxL = Float.NEGATIVE_INFINITY;
TIntIterator it1 = slots.iterator();
while(it1.hasNext()){
int i = it1.next();
TIntIterator it2 = slots.iterator();
// System.out.print(i+": ");
while(it2.hasNext()){
int j= it2.nex... |
java | private static <T> T attemptLoad(
final Class<T> ofClass,
final String className) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Attempting service load: " + className);
}
Level level;
Throwable thrown;
try {
Class<?> clazz = Cla... |
java | public DescribeActiveReceiptRuleSetResult withRules(ReceiptRule... rules) {
if (this.rules == null) {
setRules(new com.amazonaws.internal.SdkInternalList<ReceiptRule>(rules.length));
}
for (ReceiptRule ele : rules) {
this.rules.add(ele);
}
return this;
... |
java | public static Tokenizer getTokenizer(Reader reader, Map<String, String> args) {
if (LOG.isDebugEnabled()) {
LOG.debug("to create tokenizer " + args);
}
Analysis analysis = null;
String temp = null;
String type = args.get("type");
if (type == null) {
type = AnsjAnalyzer.TYPE.base_ansj.name();
}
... |
java | @SuppressWarnings("unchecked")
public EList<IfcIrregularTimeSeriesValue> getValues() {
return (EList<IfcIrregularTimeSeriesValue>) eGet(Ifc2x3tc1Package.Literals.IFC_IRREGULAR_TIME_SERIES__VALUES,
true);
} |
java | public static Vec toStringVec(Vec src) {
switch (src.get_type()) {
case Vec.T_STR:
return src.makeCopy();
case Vec.T_CAT:
return categoricalToStringVec(src);
case Vec.T_UUID:
return UUIDToStringVec(src);
case Vec.T_TIME:
case Vec.T_NUM:
return numericToS... |
python | def filter_fh_by_metadata(self, filehandlers):
"""Filter out filehandlers using provide filter parameters."""
for filehandler in filehandlers:
filehandler.metadata['start_time'] = filehandler.start_time
filehandler.metadata['end_time'] = filehandler.end_time
if self.m... |
java | public void getExportedPackages(Set<String> exportedPackages) {
if (exportedPackages != null) {
exportedPackages.add(getCodeElementExtractor().getBasePackage());
exportedPackages.add(getCodeElementExtractor().getBuilderPackage());
if (getCodeBuilderConfig().isISourceAppendableEnable()) {
exportedPackages... |
python | def references(self):
"""
Returns the joined DataFrame of references and repositories.
>>> refs_df = repos_df.references
:rtype: ReferencesDataFrame
"""
return ReferencesDataFrame(self._engine_dataframe.getReferences(),
self._session, ... |
python | def set_attribute_xsi_type(self, el, **kw):
'''if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
'''
if kw.get('typed', self.typed):
namespaceURI,typeName = kw.get('type', _get_xsitype(self))
if namespaceU... |
java | public List<OPFItem> getSpineItems()
{
return (items != null) ? items.getSpineItems() : ImmutableList.<OPFItem> of();
} |
python | def make_regex(string):
"""Regex string for optionally signed binary or privative feature.
>>> [make_regex(s) for s in '+spam -spam spam'.split()]
['([+]?spam)', '(-spam)', '(spam)']
>>> make_regex('+eggs-spam')
Traceback (most recent call last):
...
ValueError: inappropriate feature n... |
java | public static void init(Application application) {
if (!hasInit) {
logger = _ARouter.logger;
_ARouter.logger.info(Consts.TAG, "ARouter init start.");
hasInit = _ARouter.init(application);
if (hasInit) {
_ARouter.afterInit();
}
... |
python | def get_albums(self, search, start=0, max_items=100):
"""Search for albums.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('albums', search, start,
max_items) |
python | def markov_network(potentials):
"""Creates a Markov Network from potentials.
A Markov Network is also knows as a `Markov Random Field`_
Parameters
----------
potentials : dict[tuple, dict]
A dict where the keys are either nodes or edges and the values are a
dictionary of potentials... |
java | protected void validateChildOrder() {
Log.d(TAG, "validating child count " + getChildCount());
if (getChildCount() < 1) {
return;
}
int lastPos = getPosition(getChildAt(0));
int lastScreenLoc = mOrientationHelper.getDecoratedStart(getChildAt(0));
if (mShouldRe... |
java | @Override
public UpdateRuleResult updateRule(UpdateRuleRequest request) {
request = beforeClientExecution(request);
return executeUpdateRule(request);
} |
python | def create(deg, p=0.75, mode='x', tags=None):
""" Vel factory function """
return RandomRotate(deg, p, mode, tags) |
java | private boolean isRemovable(ExtensionalDataNode node, ImmutableSet<Integer> independentIndexes,
ImmutableSet<Variable> requiredAndCooccuringVariables) {
ImmutableList<? extends VariableOrGroundTerm> arguments = node.getProjectionAtom().getArguments();
return independentI... |
java | public static boolean createScaledDownImageCacheFile(String sourcePath, String cachedFileName) {
File localFile = new File(cachedFileName);
// Retrieve image orientation
int imageOrientation = 0;
try {
ExifInterface exif = new ExifInterface(sourcePath);
imageOrientation = exif.getAttributeInt(ExifInterfa... |
python | def plot(args):
"""
%prog plot tagged.new.bed chr1
Plot gene identifiers along a particular chromosome, often to illustrate the
gene id assignment procedure.
"""
from jcvi.graphics.base import plt, savefig
from jcvi.graphics.chromosome import ChromosomeMap
p = OptionParser(plot.__doc__... |
java | public static IpAddressFetcher fetcher(final String pathAccountSid,
final String pathIpAccessControlListSid,
final String pathSid) {
return new IpAddressFetcher(pathAccountSid, pathIpAccessControlListSid, pathSid);
} |
java | public static Interval fromToBy(int from, int to, int stepBy)
{
if (stepBy == 0)
{
throw new IllegalArgumentException("Cannot use a step by of 0");
}
if (from > to && stepBy > 0 || from < to && stepBy < 0)
{
throw new IllegalArgumentException("Step by ... |
python | def run_cmd(call, cmd, *, echo=True, **kwargs):
"""Run a command and echo it first"""
if echo:
print('$> ' + ' '.join(map(pipes.quote, cmd)))
return call(cmd, **kwargs) |
python | def handle_json_GET_routes(self, params):
"""Return a list of all routes."""
schedule = self.server.schedule
result = []
for r in schedule.GetRouteList():
result.append( (r.route_id, r.route_short_name, r.route_long_name) )
result.sort(key = lambda x: x[1:3])
return result |
java | private static Shape createAtomHighlight(IAtom atom, double radius) {
double x = atom.getPoint2d().x;
double y = atom.getPoint2d().y;
return new RoundRectangle2D.Double(x - radius, y - radius, 2 * radius, 2 * radius, 2 * radius, 2 * radius);
} |
java | public static final ScopeInfo extractScopeFirst(final String str, final String beginMark, final String endMark) {
final List<ScopeInfo> scopeList = doExtractScopeList(str, beginMark, endMark, true);
if (scopeList == null || scopeList.isEmpty()) {
return null;
}
if (scopeList.... |
java | private static boolean falseForNotFound(IOException exception) {
ComputeException serviceException = translate(exception);
if (serviceException.getCode() == HTTP_NOT_FOUND) {
return false;
}
throw serviceException;
} |
java | public static <R> Stream<R> zip(final float[] a, final float[] b, final float[] c, final FloatTriFunction<R> zipFunction) {
return zip(FloatIteratorEx.of(a), FloatIteratorEx.of(b), FloatIteratorEx.of(c), zipFunction);
} |
python | def returns_annualized(returns, geometric=True, scale=None, expanding=False):
""" return the annualized cumulative returns
Parameters
----------
returns : DataFrame or Series
geometric : link the returns geometrically
scale: None or scalar or string (ie 12 for months in year),
If Non... |
java | public static ExecutionResult executeCommandWithResult(
final Logger logger,
final String[] command,
final File workingDir,
final Map<String,String> environmentVars,
final String applicationName,
final String scopedInstancePath)
throws IOException, InterruptedException {
logger.fine( "Executing co... |
java | public <T> CompletableFuture<VersionedMetadata<T>> getEntry(String tableName, String key, Function<byte[], T> fromBytes) {
log.trace("get entry called for : {} key : {}", tableName, key);
List<TableKey<byte[]>> keys = Collections.singletonList(new TableKeyImpl<>(key.getBytes(Charsets.UTF_8), null));
... |
java | public byte[] encrypt(byte[] data) {
lock.lock();
try {
if (null == this.params) {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
} else {
cipher.init(Cipher.ENCRYPT_MODE, secretKey, params);
}
return cipher.doFinal(data);
} catch (Exception e) {
throw new CryptoException(e);
} f... |
java | public int getTokId() {
if (Event_Type.featOkTst && ((Event_Type)jcasType).casFeat_tokId == null)
jcasType.jcas.throwFeatMissing("tokId", "de.unihd.dbs.uima.types.heideltime.Event");
return jcasType.ll_cas.ll_getIntValue(addr, ((Event_Type)jcasType).casFeatCode_tokId);} |
java | public ServiceFuture<ConnectionInner> createOrUpdateAsync(String resourceGroupName, String automationAccountName, String connectionName, ConnectionCreateOrUpdateParameters parameters, final ServiceCallback<ConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsy... |
python | def _Pluralize(value, unused_context, args):
"""Formatter to pluralize words."""
if len(args) == 0:
s, p = '', 's'
elif len(args) == 1:
s, p = '', args[0]
elif len(args) == 2:
s, p = args
else:
# Should have been checked at compile time
raise AssertionErr... |
java | public DataSet getDataSet()
{
if(!noMoreAdding)
{
initialLoad();
finishAdding();
}
List<DataPoint> dataPoints= new ArrayList<DataPoint>(vectors.size());
for(SparseVector vec : vectors)
dataPoints.add(new DataPoint(vec, new... |
python | def handle_data(self):
"""
handle stock data for trading signal, and make order
"""
# 读取历史数据,使用sma方式计算均线准确度和数据长度无关,但是在使用ema方式计算均线时建议将历史数据窗口适当放大,结果会更加准确
today = datetime.datetime.today()
pre_day = (today - datetime.timedelta(days=self.observation)
).strf... |
java | public Integer getSelectedLastRow() {
final Object result = getStateHelper().eval(PropertyKeys.selectedLastRow);
if (result == null) {
return null;
}
return Integer.valueOf(result.toString());
} |
python | def isFocused(self):
'''
Gets the focused value
@return: the focused value. If the property cannot be found returns C{False}
'''
try:
return True if self.map[self.isFocusedProperty].lower() == 'true' else False
except Exception:
return False |
java | public java.lang.String getUnselectedClass() {
return (java.lang.String) getStateHelper().eval(PropertyKeys.unselectedClass);
} |
python | def update(self, cardconnection, ccevent):
'''CardConnectionObserver callback.'''
apduline = ""
if 'connect' == ccevent.type:
apduline += 'connecting to ' + cardconnection.getReader()
elif 'disconnect' == ccevent.type:
apduline += 'disconnecting from ' + cardcon... |
python | def _raise_connection_failure(address, error):
"""Convert a socket.error to ConnectionFailure and raise it."""
host, port = address
# If connecting to a Unix socket, port will be None.
if port is not None:
msg = '%s:%d: %s' % (host, port, error)
else:
msg = '%s: %s' % (host, error)
... |
python | def is_common_password(raw, freq=0):
"""If the password is common used.
10k top passwords: https://xato.net/passwords/more-top-worst-passwords/
"""
frequent = WORDS.get(raw, 0)
if freq:
return frequent > freq
return bool(frequent) |
python | def solve_map(expr, vars):
"""Solves the map-form, by recursively calling its RHS with new vars.
let-forms are binary expressions. The LHS should evaluate to an IAssociative
that can be used as new vars with which to solve a new query, of which
the RHS is the root. In most cases, the LHS will be a Var ... |
java | public CompletableFuture<Void> destroy() {
CompletableFuture<Void> ret;
if (controllerProxy != null) {
ret = controllerProxy.destroy();
controllerProxy = null;
} else {
ret = new CompletableFuture<>();
ret.complete(null);
}
return r... |
python | def scan_models(self, folder='./yang', download='check'):
'''scan_models
High-level api: Download models from the device by <get-schema>
operation defined in RFC6022, and analyze dependencies among models
using pyang package.
Parameters
----------
folder : `str... |
python | def connectedPoints(actor, radius, mode=0, regions=(), vrange=(0,1), seeds=(), angle=0):
"""
Extracts and/or segments points from a point cloud based on geometric distance measures
(e.g., proximity, normal alignments, etc.) and optional measures such as scalar range.
The default operation is to segmen... |
java | public static TimelineUpdater getCurrentInstance(String id) {
FacesContext fc = FacesContext.getCurrentInstance();
@SuppressWarnings("unchecked")
Map<String, TimelineUpdater> map = (Map<String, TimelineUpdater>) fc.getAttributes().get(TimelineUpdater.class.getName());
if (map == null) {... |
python | def complement(a, b, presorted=False, buffersize=None, tempdir=None,
cache=True, strict=False):
"""
Return rows in `a` that are not in `b`. E.g.::
>>> import petl as etl
>>> a = [['foo', 'bar', 'baz'],
... ['A', 1, True],
... ['C', 7, False],
...... |
python | def get_entries_for_scope(self, user_scope, scope_name, scope_value, key=None):
"""GetEntriesForScope.
[Preview API] Get all setting entries for the given named scope
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
... |
java | public static void describeTo(PrecedencedSelfDescribing self, SelfDescribing nested, Description d) {
boolean paren = useParen(self, nested);
describeTo(paren, nested, d);
} |
python | def unmarshal_bson(
obj,
cls,
allow_extra_keys=True,
ctor=None,
):
""" Unmarshal @obj into @cls
Args:
obj: dict, A BSON object
cls: type, The class to unmarshal into
allow_extra_keys: bool, False to raise an exception when extra
... |
python | def _load_library(self):
"""Return the fortran library, loaded with """
path = self._library_path()
logger.info("Loading library from path {}".format(path))
library_dir = os.path.dirname(path)
if platform.system() == 'Windows':
import win32api
olddir = os.... |
java | public static Scan convertStringToScan(String base64) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(base64));
DataInputStream dis = new DataInputStream(bis);
Scan scan = new Scan();
scan.readFields(dis);
return scan;
} |
python | def _raise_error(self, status_code, raw_data):
""" Locate appropriate exception and raise it. """
error_message = raw_data
additional_info = None
try:
if raw_data:
additional_info = json.loads(raw_data)
error_message = additional_info.get('erro... |
python | def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-... |
java | public PutMetricDataRequest withMetricData(MetricDatum... metricData) {
if (this.metricData == null) {
setMetricData(new com.amazonaws.internal.SdkInternalList<MetricDatum>(metricData.length));
}
for (MetricDatum ele : metricData) {
this.metricData.add(ele);
}
... |
java | @SuppressWarnings("deprecation")
Result begin(String... argv) {
// Preprocess @file arguments
try {
argv = CommandLine.parse(argv);
} catch (IOException e) {
error("main.cant.read", e.getMessage());
return ERROR;
}
if (argv.length > 0 && "... |
python | def netlog(message,
source=None,
host='localhost',
port=514,
priority=syslog.LOG_DEBUG,
facility=syslog.LOG_USER):
"""
Python's built in syslog module does not support networking, so
this is the alternative.
The source argument specifies the message... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.