language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def form_b(self, n: float)->tuple:
"""
formats a bps as bps/kbps/mbps/gbps etc
handles whether its meant to be in bytes
:param n: input float
:rtype tuple:
:return: tuple of float-number of mbps etc, str-units
"""
unit = 'bps'
kilo = 1000
m... |
java | public static <V> PnkyPromise<List<V>> all(
final Iterable<? extends PnkyPromise<? extends V>> promises)
{
final Pnky<List<V>> pnky = Pnky.create();
final int numberOfPromises = Iterables.size(promises);
// Special case, no promises to wait for
if (numberOfPromises == 0)
{
return Pnk... |
python | def override_if_not_in_args(flag, argument, args):
"""Checks if flags is in args, and if not it adds the flag to args."""
if flag not in args:
args.extend([flag, argument]) |
java | public boolean registerConsumerSetMonitor(
DestinationHandler topicSpace,
String discriminatorExpression,
ConnectionImpl connection,
ConsumerSetChangeCallback callback)
throws
SIDiscriminatorSyntaxException,
SIErrorException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEna... |
java | public void setConfigurationIndex(int revision) throws IOException {
if (revision < 1) {
throw new IllegalArgumentException("revision must be greater than or equal to 1");
}
this.configurationIndex = revision;
if (this.started) {
advertiser.setConfigurationIndex(revision);
}
} |
java | public void setInstance(String newInstance) {
String oldInstance = instance;
instance = newInstance;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.PARAMETER_VALUE__INSTANCE, oldInstance, instance));
} |
python | def set_speed(self, speed=None, auto=False, adaptive=False):
"""Sets the speed of the JTAG communication with the ARM core.
If no arguments are present, automatically detects speed.
If a ``speed`` is provided, the speed must be no larger than
``JLink.MAX_JTAG_SPEED`` and no smaller tha... |
python | def _pvi_path(granule):
"""Determine the PreView Image (PVI) path inside the SAFE pkg."""
pvi_name = granule._metadata.iter("PVI_FILENAME").next().text
pvi_name = pvi_name.split("/")
pvi_path = os.path.join(
granule.granule_path,
pvi_name[len(pvi_name)-2], pvi_name[len(pvi_name)-1]
)... |
java | public OvhRecord zone_zoneName_record_POST(String zoneName, OvhNamedResolutionFieldTypeEnum fieldType, String subDomain, String target, Long ttl) throws IOException {
String qPath = "/domain/zone/{zoneName}/record";
StringBuilder sb = path(qPath, zoneName);
HashMap<String, Object>o = new HashMap<String, Object>()... |
java | protected String computeCurrentFolder() {
String currentFolder = getSettings().getExplorerResource();
if (currentFolder == null) {
// set current folder to root folder
try {
currentFolder = getCms().getSitePath(getCms().readFolder("/", CmsResourceFilter.IGNORE_EX... |
java | @Nullable
public T poll() throws Exception {
if (exception != null) throw exception;
if (put != null && willBeExhausted()) {
T item = doPoll();
SettablePromise<Void> put = this.put;
this.put = null;
put.set(null);
return item;
}
return !isEmpty() ? doPoll() : null;
} |
java | @Override
public java.util.List<com.liferay.commerce.product.model.CPOption> getCPOptionsByUuidAndCompanyId(
String uuid, long companyId) {
return _cpOptionLocalService.getCPOptionsByUuidAndCompanyId(uuid,
companyId);
} |
java | public static double constraint(TrifocalTensor tensor,
Point2D_F64 p1, Vector3D_F64 l2, Vector3D_F64 l3)
{
DMatrixRMaj sum = new DMatrixRMaj(3,3);
CommonOps_DDRM.add(p1.x,tensor.T1,sum,sum);
CommonOps_DDRM.add(p1.y,tensor.T2,sum,sum);
CommonOps_DDRM.add(tensor.T3, sum, sum);
return GeometryMath_F6... |
java | private void setChromeOptions(final DesiredCapabilities capabilities, ChromeOptions chromeOptions) {
// Set custom downloaded file path. When you check content of downloaded file by robot.
final HashMap<String, Object> chromePrefs = new HashMap<>();
chromePrefs.put("download.default_directo... |
java | public void filterPaths(PathImpl path, String prefix, PathCallback cb)
{
if (! path.exists() || ! path.canRead()) {
return;
}
if (! isValidPrefix(path, prefix)) {
return;
}
if (path.isDirectory()) {
try {
String []list = path.list();
for (int i = 0; i <... |
java | @Override
public String readMultiByte(int length, String charSet) {
return dataInput.readMultiByte(length, charSet);
} |
python | def _parse(self, infile):
"""Actually parse the config file."""
temp_list_values = self.list_values
if self.unrepr:
self.list_values = False
comment_list = []
done_start = False
this_section = self
maxline = len(infile) - 1
cur_index = -1
... |
python | def apply(self, func, *args, **kwargs):
"""Apply the provided function and combine the results together in the
same way as apply from groupby in pandas.
This returns a DataFrame.
"""
self._prep_pandas_groupby()
def key_by_index(data):
"""Key each row by its ... |
python | def sym_log_map(cls, q, p):
"""Quaternion symmetrized logarithm map.
Find the symmetrized logarithm map on the quaternion Riemannian manifold.
Params:
q: the base point at which the logarithm is computed, i.e.
a Quaternion object
p: the argument of the... |
python | def get_index(self, name):
"""get an index by name
TODO: Combine indexes of relevant catalogs depending on the portal_type
which is searched for.
"""
catalog = self.get_catalog()
index = catalog._catalog.getIndex(name)
logger.debug("get_index={} of catalog '{}' -... |
python | def element_to_objects(
element: etree.ElementTree, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List:
"""Transform an Element to a list of entities recursively.
Possible child entities are added to each entity ``_children`` list.
:param tree: Element
:... |
python | def db_scan_block( block_id, op_list, db_state=None ):
"""
(required by virtualchain state engine)
Given the block ID and the list of virtualchain operations in the block,
do block-level preprocessing:
* find the state-creation operations we will accept
* make sure there are no collisions.
... |
java | public Content propertyTagOutput(Tag tag, String prefix) {
Content body = new ContentBuilder();
body.addContent(new RawHtml(prefix));
body.addContent(" ");
body.addContent(HtmlTree.CODE(new RawHtml(tag.text())));
body.addContent(".");
Content result = HtmlTree.P(body);
... |
java | private String extractErrorMessageFromResponse(HttpResponse response) {
String contentType = response.getEntity().getContentType().getValue();
if(contentType.contains("application/json")) {
Gson gson = GsonResponseParser.getDefaultGsonParser(false);
String responseBody = null;
... |
java | public SortedSet<HmmerResult> scan(ProteinSequence sequence, URL serviceLocation) throws IOException{
StringBuffer postContent = new StringBuffer();
postContent.append("hmmdb=pfam");
// by default hmmscan runs with the HMMER3 cut_ga parameter enabled, the "gathering threshold", which depends on
// the cutof... |
python | def clip(self, lower=0, upper=127):
"""
Clip the pianorolls of all tracks by the given lower and upper bounds.
Parameters
----------
lower : int or float
The lower bound to clip the pianorolls. Defaults to 0.
upper : int or float
The upper bound t... |
java | protected void swapFragments(final AjaxRequestTarget target, final Form<?> form)
{
if (modeContext.equals(ModeContext.VIEW_MODE))
{
onSwapToEdit(target, form);
}
else
{
onSwapToView(target, form);
}
} |
java | private static Properties load() {
Properties properties = new Properties();
String file = System.getProperty(CONFIGURATION_PROPERTY);
try {
if (file != null) {
InputStream stream;
if (URL_DETECTION_PATTERN.matcher(file).matches()) {
stream = new URL(file).openStream();
} else {
stream =... |
java | @Nullable
public static String readSafeUTF (@Nonnull final DataInput aDI) throws IOException
{
ValueEnforcer.notNull (aDI, "DataInput");
final int nLayout = aDI.readByte ();
final String ret;
switch (nLayout)
{
case 0:
{
// If the first byte has value "0" it means the whole ... |
python | def analysis(analysis_id):
"""Display a single analysis."""
analysis_obj = store.analysis(analysis_id)
if analysis_obj is None:
return abort(404)
if request.method == 'PUT':
analysis_obj.update(request.json)
store.commit()
data = analysis_obj.to_dict()
data['failed_jobs... |
java | public String toJSONString(final boolean compact) {
final StringBuilder builder = new StringBuilder();
formatAsJSON(builder, 0, !compact);
return builder.toString();
} |
python | def rotate(name, pattern=None, conf_file=default_conf, **kwargs):
'''
Set up pattern for logging.
name : string
alias for entryname
pattern : string
alias for log_file
conf_file : string
optional path to alternative configuration file
kwargs : boolean|string|int
... |
python | def distributions(self, complexes, counts, volume, maxstates=1e7,
ordered=False, temp=37.0):
'''Runs the \'distributions\' NUPACK command. Note: this is intended
for a relatively small number of species (on the order of ~20
total strands for complex size ~14).
:par... |
python | def _ActivateBreakpoint(self, module):
"""Sets the breakpoint in the loaded module, or complete with error."""
# First remove the import hook (if installed).
self._RemoveImportHook()
line = self.definition['location']['line']
# Find the code object in which the breakpoint is being set.
status... |
python | def tree_to_graph(bbltree:BubbleTree) -> Graph or Digraph:
"""Compute as a graphviz.Graph instance the given graph.
If given BubbleTree instance is oriented, returned value
is a graphviz.Digraph.
See http://graphviz.readthedocs.io/en/latest/examples.html#cluster-py
for graphviz API
"""
Gr... |
java | @Override
public ExtensionProcessor getLogoutProcessor()
{
//do not cache the processor in the webcontainer code, always return the result from security
IWebAppSecurityCollaborator secCollab = this.collabHelper.getSecurityCollaborator();
logoutProcessor = secCollab.getFormLogoutExtensionProcessor(... |
java | private void _recurse (@Nonnull final Block aRoot, final boolean bListMode)
{
Block aBlock;
Block aList;
Line aLine = aRoot.m_aLines;
if (bListMode)
{
aRoot.removeListIndent (m_bUseExtensions);
if (m_bUseExtensions && aRoot.m_aLines != null && aRoot.m_aLines.getLineType (m_bUseExtensi... |
python | def _remove_identical_contigs(self, containing_contigs, contig_lengths):
'''Input is dictionary of containing contigs made by self._expand_containing_using_transitivity().
Removes redundant identical contigs, leaving one representative (the longest) of
each set of identical contigs.
... |
java | public static long getMinimumSequence(final Sequence[] sequences, long minimum)
{
for (int i = 0, n = sequences.length; i < n; i++)
{
long value = sequences[i].get();
minimum = Math.min(minimum, value);
}
return minimum;
} |
java | static int mask(Class<? extends ChannelHandler> clazz) {
// Try to obtain the mask from the cache first. If this fails calculate it and put it in the cache for fast
// lookup in the future.
Map<Class<? extends ChannelHandler>, Integer> cache = MASKS.get();
Integer mask = cache.get(clazz)... |
python | def hmtk_histogram_2D(xvalues, yvalues, bins, x_offset=1.0E-10,
y_offset=1.0E-10):
"""
See the explanation for the 1D case - now applied to 2D.
:param numpy.ndarray xvalues:
Values of x-data
:param numpy.ndarray yvalues:
Values of y-data
:param tuple bins:
... |
java | public void marshall(AccelerationSettings accelerationSettings, ProtocolMarshaller protocolMarshaller) {
if (accelerationSettings == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(accelerationSetting... |
python | def rename_image(self, ami_name, new_ami_name, source_region='us-east-1'):
"""
Method which renames an ami by copying to a new ami with a new name (only way this is possible in AWS)
:param ami_name:
:param new_ami_name:
:return:
"""
print "Re-naming/moving AMI to ... |
java | public ApiResponse<List<FactionWarfareWarsResponse>> getFwWarsWithHttpInfo(String datasource, String ifNoneMatch)
throws ApiException {
com.squareup.okhttp.Call call = getFwWarsValidateBeforeCall(datasource, ifNoneMatch, null);
Type localVarReturnType = new TypeToken<List<FactionWarfareWarsR... |
python | def to_text(self, line):
"""
Return the textual representation of the given `line`.
"""
return getattr(self, self.ENTRY_TRANSFORMERS[line.__class__])(line) |
python | def request(self, action, data={}, headers={}, method='GET'):
"""
Append the user authentication details to every incoming request
"""
data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId})
return Transport.request(self, action, data, he... |
python | def _ParseCachedEntry8(self, value_data, cached_entry_offset):
"""Parses a Windows 8.0 or 8.1 cached entry.
Args:
value_data (bytes): value data.
cached_entry_offset (int): offset of the first cached entry data
relative to the start of the value data.
Returns:
AppCompatCacheCac... |
python | def __parse(self) -> object:
"""Selects the appropriate method to decode next bencode element and returns the result."""
char = self.data[self.idx: self.idx + 1]
if char in [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0']:
str_len = int(self.__read_to(b':'))
r... |
python | def get_logging_fields(self, model):
"""
Returns a dictionary mapping of the fields that are used for
keeping the acutal audit log entries.
"""
rel_name = '_%s_audit_log_entry'%model._meta.object_name.lower()
def entry_instance_to_unicode(log_entry):
try:
... |
python | def load_config(self, config_file_name):
""" Load configuration file from prt or str.
Configuration file type is extracted from the file suffix - prt or str.
:param config_file_name: full path to the configuration file.
IxTclServer must have access to the file location. either:
... |
python | def clear_cached_endpoints(self, prefix=None):
""" Invalidate all cached endpoints, meta included
Loop over all meta endpoints to generate all cache key the
invalidate each of them. Doing it this way will prevent the
app not finding keys as the user may change its prefixes
Meta ... |
java | public int decompose(CharSequence s, int src, int limit,
ReorderingBuffer buffer) {
int minNoCP=minDecompNoCP;
int prevSrc;
int c=0;
int norm16=0;
// only for quick check
int prevBoundary=src;
int prevCC=0;
for(;;) {
... |
java | public static Pattern mappingToRegex(String mapping)
{
return Pattern.compile(mapping.replaceAll("\\.", "\\.")
.replaceAll("^\\*(.*)", "^(.*)$1\\$")
.replaceAll("(.*)\\*$", "^$1(.*)\\$"));
} |
java | @Override
public void format(Buffer buf) {
int slotSize = RecordPage.slotSize(ti.schema());
Constant emptyFlag = new IntegerConstant(EMPTY);
for (int pos = 0; pos + slotSize <= Buffer.BUFFER_SIZE; pos += slotSize) {
setVal(buf, pos, emptyFlag);
makeDefaultRecord(buf, pos);
}
} |
java | @Override
public RebootReplicationInstanceResult rebootReplicationInstance(RebootReplicationInstanceRequest request) {
request = beforeClientExecution(request);
return executeRebootReplicationInstance(request);
} |
java | @Override
public LoadBalancerNodeFilter and(LoadBalancerNodeFilter otherFilter) {
if (evaluation instanceof SingleFilterEvaluation &&
otherFilter.evaluation instanceof SingleFilterEvaluation) {
return
new LoadBalancerNodeFilter(
getLoadBalancerPool... |
python | def get_student_enrollments(self):
"""
Returns an Enrollments object with the user enrollments
Returns:
Enrollments: object representing the student enrollments
"""
# the request is done in behalf of the current logged in user
resp = self.requester.get(
... |
python | def compute_acl(cls, filename, start_index=None, end_index=None,
min_nsamples=10):
"""Computes the autocorrleation length for all model params and
temperatures in the given file.
Parameter values are averaged over all walkers at each iteration and
temperature. The A... |
python | def inspect_plugin(self, name):
"""
Retrieve plugin metadata.
Args:
name (string): The name of the plugin. The ``:latest`` tag is
optional, and is the default if omitted.
Returns:
A dict containing plugin info
"""
... |
java | protected boolean inViewPort(final int dataIndex) {
boolean inViewPort = true;
for (Layout layout: mLayouts) {
inViewPort = inViewPort && (layout.inViewPort(dataIndex) || !layout.isClippingEnabled());
}
return inViewPort;
} |
java | public Cluster withSubnetMapping(java.util.Map<String, String> subnetMapping) {
setSubnetMapping(subnetMapping);
return this;
} |
java | public Decision<Flow<T>> getOrCreateDecision()
{
List<Node> nodeList = childNode.get("decision");
if (nodeList != null && nodeList.size() > 0)
{
return new DecisionImpl<Flow<T>>(this, "decision", childNode, nodeList.get(0));
}
return createDecision();
} |
python | def _format_data(self, data):
"""
Sort the data in blue wavelengths to red, and ignore any spectra that
have entirely non-finite or negative fluxes.
"""
return [spectrum for spectrum in \
sorted(data if isinstance(data, (list, tuple)) else [data],
key=... |
java | public static Word2Vec fromPair(Pair<InMemoryLookupTable, VocabCache> pair) {
Word2Vec vectors = new Word2Vec();
vectors.setLookupTable(pair.getFirst());
vectors.setVocab(pair.getSecond());
vectors.setModelUtils(new BasicModelUtils());
return vectors;
} |
python | def quality_comparator(video_data):
"""Custom comparator used to choose the right format based on the resolution."""
def parse_resolution(res: str) -> Tuple[int, ...]:
return tuple(map(int, res.split('x')))
raw_resolution = video_data['resolution']
resolution = parse_resolut... |
java | public CompletableFuture<Object> optionsAsync(@DelegatesTo(HttpConfig.class) final Closure closure) {
return CompletableFuture.supplyAsync(() -> options(closure), getExecutor());
} |
java | public Matrix solve (Matrix B) throws SingularityException {
if (B.getRowCount() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isNonsingular()) {
throw new SingularityException("Matrix is singular.");
}
// Copy right hand si... |
java | public void doWrite(FieldTable vectorTable, KeyAreaInfo keyArea, BaseBuffer bufferNew) throws DBException
{
super.doWrite(vectorTable, keyArea, bufferNew);
} |
java | @Nonnull
@Override
public String getProviderTermForIpAddress(@Nonnull Locale locale) {
try {
return getCapabilities().getProviderTermForIpAddress(locale);
} catch (CloudException e) {
throw new RuntimeException("Unexpected problem with capabilities", e);
} catch (... |
python | def sorted_feed_cols(df):
"""
takes a dataframe's columns that would be of the form:
['feed003', 'failsafe_feed999', 'override_feed000', 'feed001', 'feed002']
and returns:
['override_feed000', 'feed001', 'feed002', 'feed003', 'failsafe_feed999']
"""
cols = df.columns
ind = [int(c.split("... |
python | def backColor(self, bc=None):
"""
Set/get actor's backface color.
"""
backProp = self.GetBackfaceProperty()
if bc is None:
if backProp:
return backProp.GetDiffuseColor()
return None
if self.GetProperty().GetOpacity() < 1:
... |
python | def load_from_file(path, fmt=None, is_training=True):
'''
load data from file
'''
if fmt is None:
fmt = 'squad'
assert fmt in ['squad', 'csv'], 'input format must be squad or csv'
qp_pairs = []
if fmt == 'squad':
with open(path) as data_file:
data = json.load(data... |
java | @Override
public void rollback() throws CpoException {
JdbcCpoAdapter currentResource = getCurrentResource();
if (currentResource != getLocalResource())
((JdbcCpoTrxAdapter)currentResource).rollback();
} |
python | def _nodedev_event_lifecycle_cb(conn, dev, event, detail, opaque):
'''
Node device lifecycle events handler
'''
_salt_send_event(opaque, conn, {
'nodedev': {
'name': dev.name()
},
'event': _get_libvirt_enum_string('VIR_NODE_DEVICE_EVENT_', event),
'detail': 'u... |
java | private void read(InputStream is, Table table) throws IOException
{
byte[] headerBytes = new byte[6];
is.read(headerBytes);
byte[] recordCountBytes = new byte[2];
is.read(recordCountBytes);
//int recordCount = getShort(recordCountBytes, 0);
//System.out.println("Header: " + new S... |
java | public void write_attribute_asynch(final DeviceProxy deviceProxy,
final DeviceAttribute[] attribs, final CallBack cb) throws DevFailed {
final int id = write_attribute_asynch(deviceProxy, attribs);
ApiUtil.set_async_reply_model(id, CALLBACK);
ApiUtil.set_async_reply_cb(id, cb);
// ... |
python | def _set_alert(self, v, load=False):
"""
Setter method for alert, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_alert is considered as a private
method. Backends looking... |
java | private void redirectToJavaLoggerProxy() {
DefaultLoggerProxy lp = DefaultLoggerProxy.class.cast(this.loggerProxy);
JavaLoggerProxy jlp = new JavaLoggerProxy(lp.name, lp.level);
// the order of assignments is important
this.javaLoggerProxy = jlp; // isLoggable checks javaLoggerProxy if... |
python | def compute():
"""Compute the polynomial."""
if what == "numpy":
y = eval(expr)
else:
y = ne.evaluate(expr)
return len(y) |
python | def get_gtf_argument_parser(desc, default_field_name='gene'):
"""Return an argument parser with basic options for reading GTF files.
Parameters
----------
desc: str
Description of the ArgumentParser
default_field_name: str, optional
Name of field in GTF file to look for.
Return... |
java | protected LightweightTypeReference internalFindTopLevelType(Class<?> rawType) {
try {
ResourceSet resourceSet = getOwner().getContextResourceSet();
Resource typeResource = resourceSet.getResource(URIHelperConstants.OBJECTS_URI.appendSegment(rawType.getName()), true);
List<EObject> resourceContents = typeReso... |
python | def paths_to_polygons(paths, scale=None):
"""
Given a sequence of connected points turn them into
valid shapely Polygon objects.
Parameters
-----------
paths : (n,) sequence
Of (m,2) float, closed paths
scale: float
Approximate scale of drawing for precision
Returns
... |
python | def encode2(self):
"""Return the base64 encoding of the fig attribute and insert in html image tag."""
buf = BytesIO()
self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
buf.seek(0)
string = b64encode(buf.read())
return '<img src="data:image/png;base64,{0}"... |
java | private static BufferedImage encodeImg(BufferedImage desImg, Float quality) {
ByteArrayOutputStream baos = null;
ByteArrayInputStream bais = null;
BufferedImage bufferedImage = null;
try {
if (quality != null) {
if (quality > 1.0 || quality < 0.0) {
... |
java | public String getSemtype() {
if (SurfaceForm_Type.featOkTst && ((SurfaceForm_Type)jcasType).casFeat_semtype == null)
jcasType.jcas.throwFeatMissing("semtype", "ch.epfl.bbp.uima.types.SurfaceForm");
return jcasType.ll_cas.ll_getStringValue(addr, ((SurfaceForm_Type)jcasType).casFeatCode_semtype);} |
python | def newest_packages(
pypi_server="https://pypi.python.org/pypi?%3Aaction=packages_rss"):
"""
Constructs a request to the PyPI server and returns a list of
:class:`yarg.parse.Package`.
:param pypi_server: (option) URL to the PyPI server.
>>> import yarg
>>> yarg.newest_packages(... |
java | public Set<String> keys() {
Set<String> list = new LinkedHashSet<>();
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
list.add(keys.nextElement());
}
return list;
} |
python | def auth(username, password):
'''
Try and authenticate
'''
try:
keystone = client.Client(username=username, password=password,
auth_url=get_auth_url())
return keystone.authenticate()
except (AuthorizationFailure, Unauthorized):
return False |
java | private InputStream getInputStreamFromFile(File f) throws FileNotFoundException{
InputStream stream = null;
if ( cacheRawFiles ){
stream = FlatFileCache.getInputStream(f.getAbsolutePath());
if ( stream == null){
FlatFileCache.addToCache(f.getAbsolutePath(),f);
stream = FlatFileCache.getInputStream... |
python | def from_dict(cls, cls_dict, fallback_xsi_type=None):
"""Parse the dictionary and return an Entity instance.
This will attempt to extract type information from the input
dictionary and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_dict... |
python | def _is_partial_index(gbi_file):
"""Check for truncated output since grabix doesn't write to a transactional directory.
"""
with open(gbi_file) as in_handle:
for i, _ in enumerate(in_handle):
if i > 2:
return False
return True |
python | def oplot(self,x,y,panel=None,**kw):
"""generic plotting method, overplotting any existing plot """
if panel is None:
panel = self.current_panel
opts = {}
opts.update(self.default_panelopts)
opts.update(kws)
self.panels[panel].oplot(x, y, **opts) |
python | def make_symbols(symbols, *args):
"""Return a list of uppercase strings like "GOOG", "$SPX, "XOM"...
Arguments:
symbols (str or list of str): list of market ticker symbols to normalize
If `symbols` is a str a get_symbols_from_list() call is used to retrieve the list of symbols
Returns:
... |
python | def _validate_prepare_time(self, t, pos_c):
"""
Make sure that t is a 1D array and compatible with the C position array.
"""
if hasattr(t, 'unit'):
t = t.decompose(self.units).value
if not isiterable(t):
t = np.atleast_1d(t)
t = np.ascontiguousar... |
java | public static boolean isSupportedWriteTransactionOperation(String methodName) {
return (ObjectUtils.nullSafeEquals(methodName, BIND_METHOD_NAME)
|| ObjectUtils.nullSafeEquals(methodName, REBIND_METHOD_NAME)
|| ObjectUtils.nullSafeEquals(methodName, RENAME_METHOD_NAME)
... |
java | public final Table getTable(TableName name) {
GetTableRequest request =
GetTableRequest.newBuilder().setName(name == null ? null : name.toString()).build();
return getTable(request);
} |
python | def phmsdms(hmsdms):
"""Parse a string containing a sexagesimal number.
This can handle several types of delimiters and will process
reasonably valid strings. See examples.
Parameters
----------
hmsdms : str
String containing a sexagesimal number.
Returns
-------
d : dict
... |
java | private static RoundRectangle2D.Double toRoundRect(final Rectangle2D pRectangle, final int pArcW, final int pArcH) {
return new RoundRectangle2D.Double(
pRectangle.getX(), pRectangle.getY(),
pRectangle.getWidth(), pRectangle.getHeight(),
pArcW, pArcH);
} |
java | private void registerInternal(final JobID id, final String[] requiredJarFiles) throws IOException {
// Use spin lock here
while (this.lockMap.putIfAbsent(id, LOCK_OBJECT) != null);
try {
if (incrementReferenceCounter(id) > 1) {
return;
}
// Check if library manager entry for this id already exists... |
java | public static mpsuser add(nitro_service client, mpsuser resource) throws Exception
{
resource.validate("add");
return ((mpsuser[]) resource.perform_operation(client, "add"))[0];
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.