language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @POST
@Consumes("application/x.json-create-api-key")
public Response createApiKey(CreateEmoApiKeyRequest request, @QueryParam("key") String key,
@Authenticated Subject subject) {
if (key != null) {
request.setCustomRequestParameter("key", key);
}
... |
java | @Override
public void parse(InputSource is, HandlerBase hb)
throws SAXException, IOException
{
if (hb != null) {
/* Ok: let's ONLY set if there are no explicit sets... not
* extremely clear, but JDK tries to set them always so
* let's at least do damage cont... |
python | def makedminfo(tabdesc, group_spec=None):
"""Creates a data manager information object.
Create a data manager information dictionary outline from a table description.
The resulting dictionary is a bare outline and is available for the purposes of
further customising the data manager via the `group_spec` argume... |
java | @Override
public Temporal adjustInto(Temporal temporal) {
if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
throw new DateTimeException("Adjustment only supported on ISO date-time");
}
temporal = temporal.with(MONTH_OF_YEAR, month);
return temporal.... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case BpsimPackage.GAMMA_DISTRIBUTION_TYPE__SCALE:
return getScale();
case BpsimPackage.GAMMA_DISTRIBUTION_TYPE__SHAPE:
return getShape();
}
return super.eGet(featureID, resolve, coreType);
} |
java | public boolean isConnected() {
if (socket != null && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown())
return true;
return false;
} |
python | def _OpenFilesForRead(self, metadata_value_pairs, token):
"""Open files all at once if necessary."""
aff4_paths = [
result.AFF4Path(metadata.client_urn)
for metadata, result in metadata_value_pairs
]
fds = aff4.FACTORY.MultiOpen(aff4_paths, mode="r", token=token)
fds_dict = dict([(fd... |
python | def build(self, project: str, groups: Iterable[str], gitlab_config: GitLabConfig) \
-> ProjectVariablesUpdaterType:
"""
Builds a `ProjectVariablesUpdater` instance using the given arguments.
:param project: the project that variables are to be updated for
:param groups: the g... |
java | @Override
public EClass getIfcFlowInstrument() {
if (ifcFlowInstrumentEClass == null) {
ifcFlowInstrumentEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(280);
}
return ifcFlowInstrumentEClass;
} |
java | public VpnSiteInner createOrUpdate(String resourceGroupName, String vpnSiteName, VpnSiteInner vpnSiteParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, vpnSiteName, vpnSiteParameters).toBlocking().last().body();
} |
java | public static IAtomContainer setSingleOrDoubleFlags(IAtomContainer ac) {
// note - we could check for any aromatic bonds to avoid RingSearch but
// RingSearch is fast enough it probably wouldn't do much to check
// before hand
RingSearch rs = new RingSearch(ac);
boolean singleOrD... |
python | def make_job_details(self, row_idx):
"""Create a `JobDetails` from an `astropy.table.row.Row` """
row = self._table[row_idx]
job_details = JobDetails.create_from_row(row)
job_details.get_file_paths(self._file_archive, self._table_id_array)
self._cache[job_details.fullkey] = job_d... |
java | public static TSSConfig getTSSConfig(Map<String, Object> props, Map<OptionsKey, List<TransportAddress>> addrMap, Bundle bundle) throws Exception {
TSSConfig tssConfig = new TSSConfig();
List<Map<String, Object>> tssConfigs = Nester.nest(CSIV2_CONFIGURATION, props);
if (!tssConfigs.isEmpty()) {
... |
python | def has_public_constructor(class_):
"""if class has any public constructor, this function will return list of
them, otherwise None"""
class_ = class_traits.get_declaration(class_)
decls = class_.constructors(
lambda c: not is_copy_constructor(c) and c.access_type == 'public',
recursive=F... |
python | def sub_index(self, sub, start=0, end=None):
"""Return the index of a subsequence.
This runs in O(len(sub))
Args:
sub (Sequence): An Iterable to search for
Returns:
int: The index of the first element of sub
Raises:
ValueError: If sub isn't a subsequence
TypeError: If sub isn't iterable
Index... |
python | def loads_sector(self, sector='res'):
"""Returns a generator for iterating over grid's sectoral loads
Parameters
----------
sector: String
possible values::
'res' (residential),
'ria' (retail, industrial, agricultural)... |
python | def digest_secure_bootloader(args):
""" Calculate the digest of a bootloader image, in the same way the hardware
secure boot engine would do so. Can be used with a pre-loaded key to update a
secure bootloader. """
if args.iv is not None:
print("WARNING: --iv argument is for TESTING PURPOSES ONLY... |
java | protected static OptionParser getParser() {
OptionParser parser = new OptionParser();
// help options
AdminParserUtils.acceptsHelp(parser);
// required options
parser.accepts(OPT_HEAD_META_CHECK, "metadata keys to be checked")
.withOptionalAr... |
java | public Update withExpressionAttributeNames(java.util.Map<String, String> expressionAttributeNames) {
setExpressionAttributeNames(expressionAttributeNames);
return this;
} |
python | def get_deployment_count(self):
"""Utility function to get the number of deployments a given project has"""
ret = self.stage_set.annotate(num_deployments=Count('deployment')).aggregate(total_deployments=Sum('num_deployments'))
return ret['total_deployments'] |
java | public <T> T get(String queryString, List<FieldAccumulator> accumulators, Object queryTypeDiscriminator, QueryCreator<T> queryCreator) {
QueryCacheKey key = new QueryCacheKey(queryString, accumulators, queryTypeDiscriminator);
return (T) getCache().computeIfAbsent(key, (k) -> queryCreator.create(k.queryStri... |
java | @Override
public EClass getIfcTelecomAddress() {
if (ifcTelecomAddressEClass == null) {
ifcTelecomAddressEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(704);
}
return ifcTelecomAddressEClass;
} |
python | def parse_multipart_headers(iterable):
"""Parses multipart headers from an iterable that yields lines (including
the trailing newline symbol). The iterable has to be newline terminated.
The iterable will stop at the line where the headers ended so it can be
further consumed.
:param iterable: iter... |
java | public long countOf(String countOfQuery) throws SQLException {
String countOfQuerySave = this.countOfQuery;
try {
setCountOf(countOfQuery);
return dao.countOf(prepare());
} finally {
setCountOf(countOfQuerySave);
}
} |
python | def _backoff(self, context):
# type: (ExponentialRetryWithMaxWait,
# azure.storage.common.models.RetryContext) -> int
"""Backoff calculator
:param ExponentialRetryWithMaxWait self: this
:param azure.storage.common.models.RetryContext context: retry context
:rtype: ... |
java | public void addConfiguredDistributer(final DistributerDef distributer) {
if (distributer == null) {
throw new NullPointerException("distributer");
}
distributer.setProject(getProject());
this.distributers.addElement(distributer);
} |
java | protected boolean updateTermAndLeader(long term, MemberId leader) {
// If the request indicates a term that is greater than the current term or no leader has been
// set for the current term, update leader and term.
if (term > raft.getTerm() || (term == raft.getTerm() && raft.getLeader() == null && leader !... |
java | public void setInputStream(InputStream inputStream, long inputStreamLength) {
// close last file when set a new inputStream
if (this.isUploadFile){
try{
this.inputStream.close();
}
catch (Exception e){
}
}
if (inputStream instanceof FDSProgressInputStream){
this.inputStream = (FDSProgressInp... |
java | public static void schemaExportPerform (String[] sqlCommands, List exporters, SchemaExport schemaExport) {
if (schemaExportPerform == null) {
try {
schemaExportPerform = SchemaExport.class.getMethod("performApi", String[].class, List.class, String.class);
} catch (NoSuchM... |
java | public void scrollToPositionWithOffset(int position, int offset) {
mCurrentPendingScrollPosition = position;
mPendingScrollPositionOffset = offset;
if (mCurrentPendingSavedState != null) {
mCurrentPendingSavedState.putInt("AnchorPosition", RecyclerView.NO_POSITION);
}
... |
java | public Object send(String... args) throws Exception
{
arguments = buildArguments();
try
{
return method.invoke( target, arguments );
}
catch (InvocationTargetException ex)
{
throw new SystemUnderDevelopmentException( ex.getTargetException() )... |
python | def graph_from_dot_file(path, encoding=None):
"""Load graphs from DOT file at `path`.
@param path: to DOT file
@param encoding: as passed to `io.open`.
For example, `'utf-8'`.
@return: Graphs that result from parsing.
@rtype: `list` of `pydot.Dot`
"""
with io.open(path, 'rt', encod... |
python | def get_throttled_read_event_count(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled read events during a given time frame
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookback_window... |
python | def get_ostypes():
"""
:return: all knows OS types
"""
LOGGER.debug("OSTypeService.get_ostypes")
args = {'http_operation': 'GET', 'operation_path': ''}
response = OSTypeService.requester.call(args)
ret = None
if response.rc == 0:
ret = []
... |
python | def equal(lhs, rhs):
"""Returns the result of element-wise **equal to** (==) comparison operation with
broadcasting.
For each element in input arrays, return 1(true) if corresponding elements are same,
otherwise return 0(false).
Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``.... |
python | def get_text_from_html(html):
"""Returns a plaintext representation of HTML content."""
try:
soup = bs4.BeautifulSoup(html, "html.parser")
except: # pylint: disable=bare-except
# Some docs don't parse
return ""
# Remove script and style tags
for s in soup(["script", "style"]):
s.decompose()
... |
python | def isrchc(value, ndim, lenvals, array):
"""
Search for a given value within a character string array. Return
the index of the first matching array entry, or -1 if the key
value was not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isrchc_c.html
:param value: Key value to be f... |
java | public void setPipeConfig(DeviceProxy deviceProxy, List<PipeInfo> pipeInfoList) throws DevFailed {
build_connection(deviceProxy);
if (deviceProxy.idl_version<5)
Except.throw_exception("TangoApi_NOT_SUPPORTED",
"Pipe not supported in IDL " + deviceProxy.idl_version);
... |
python | def connect_ssl(cls, user, password, endpoints,
ca_certs=None, validate=None):
"""
Creates an SSL transport to the first endpoint (aserver) to which
we successfully connect
"""
if isinstance(endpoints, basestring):
endpoints = [endpoints]
t... |
python | def register(self, scope, *args, **kwargs):
"""Register an option in the given scope."""
self._assert_not_frozen()
self.get_parser(scope).register(*args, **kwargs)
deprecated_scope = self.known_scope_to_info[scope].deprecated_scope
if deprecated_scope:
self.get_parser(deprecated_scope).registe... |
python | def load_transport(self, url):
'''
For remote communication. Sets the communication dispatcher of the host
at the address and port specified.
The scheme must be http if using a XMLRPC dispatcher.
amqp for RabbitMQ communications.
This methos is internal. Automatically c... |
python | def date_range(date, func='date'):
'''
Return back start and end dates given date string
:param date: metrique date (range) to apply to pql query
The tilde '~' symbol is used as a date range separated.
A tilde by itself will mean 'all dates ranges possible'
and will therefore search all objec... |
java | final PropertyDefinitionId propertyDefinitionId()
throws ItemNotFoundException, ConstraintViolationException, InvalidItemStateException {
CachedDefinition defn = cachedDefn;
NodeTypes nodeTypes = session.nodeTypes();
if (defn == null || nodeTypes.getVersion() > defn.nodeTypesVersion) {
... |
python | def submit(self, cert_type_name, csr, revoke_password, term, subject_alt_names='',
server_type='OTHER'):
"""
Submit a certificate request to Comodo.
:param string cert_type_name: The full cert type name (Example: 'PlatinumSSL Certificate') the supported
... |
python | def load_profiles(self):
"""Return configuration data.
Load on first access, otherwise return existing data.
.. code-block:: python
self.profiles = {
<profile name>: {
'data': {},
'ij_filename': <filename>,
... |
java | private int getColumnSpan(final Attributes atts) {
final String start = atts.getValue(ATTRIBUTE_NAME_NAMEST);
final String end = atts.getValue(ATTRIBUTE_NAME_NAMEEND);
if (start == null || end == null) {
return 1;
} else {
final int ret = colSpec.indexOf(end) - co... |
java | public synchronized @Nullable SourceMapConsumerV3 getSourceMap(ErrorManager errorManager) {
if (!cached) {
// Avoid re-reading or reparsing files.
cached = true;
String sourceMapPath = sourceFile.getOriginalPath();
try {
String sourceMapContents = sourceFile.getCode();
Source... |
java | public double getDistance(double[] sample1, double[] sample2) throws IllegalArgumentException {
int n = sample1.length;
if (n != sample2.length || n < 1)
throw new IllegalArgumentException("Input arrays must have the same length.");
double sumOfDifferences = 0;
for (int i = 0; i < n; i++) {
if (Double.i... |
java | private String[] stringVect2StringArray(final Vector v) {
final String[] array = new String[v.size()];
for (int i = 0; i < v.size(); i++) {
array[i] = (String) v.elementAt(i);
}
return array;
} |
python | def fill(self, name_or_slot, value):
"""Fills an output slot required by this Pipeline.
Args:
name_or_slot: The name of the slot (a string) or Slot record to fill.
value: The serializable value to assign to this slot.
Raises:
UnexpectedPipelineError if the Slot no longer exists. SlotNotD... |
java | @Nonnegative
public static int replaceMultipleTo (@Nullable final String sInputString,
@Nonnull final char [] aSearchChars,
@Nonnull final char [] [] aReplacementStrings,
@Nonnull final Writer aTarget)... |
java | protected void addNavigationBarHeader(Content body) {
Content htmlTree = (configuration.allowTag(HtmlTag.HEADER))
? HtmlTree.HEADER()
: body;
addTop(htmlTree);
addNavLinks(true, htmlTree);
if (configuration.allowTag(HtmlTag.HEADER)) {
body.addC... |
python | def _dryrun_cell(args, cell_body):
"""Implements the BigQuery cell magic used to dry run BQ queries.
The supported syntax is:
%%bigquery dryrun [-q|--sql <query identifier>]
[<YAML or JSON cell_body or inline SQL>]
Args:
args: the argument following '%bigquery dryrun'.
cell_body: optional content... |
python | def _login(self, environ, start_response):
"""Send a login response back to the client."""
response = HTTPUnauthorized()
response.www_authenticate = ('Basic', {'realm': self._realm})
return response(environ, start_response) |
python | def eff_default_transformer(fills=EFF_DEFAULT_FILLS):
"""
Return a simple transformer function for parsing EFF annotations. N.B.,
ignores all but the first effect.
"""
def _transformer(vals):
if len(vals) == 0:
return fills
else:
# ignore all but first effect... |
java | protected void removeDecorationWidget(Widget widget, int width) {
if ((widget != null) && m_decorationWidgets.remove(widget)) {
m_decorationWidth -= width;
initContent();
}
} |
java | public T visitTupleElement(TupleElement elm, C context) {
visitElement(elm.getValue(), context);
return null;
} |
python | def parse(self, data):
"""Returns a list of path template segments parsed from data.
Args:
data: A path template string.
Returns:
A list of _Segment.
"""
self.binding_var_count = 0
self.segment_count = 0
segments = self.parser.parse(data)... |
python | def draw_line2d(data, obj):
"""Returns the PGFPlots code for an Line2D environment.
"""
content = []
addplot_options = []
# If line is of length 0, do nothing. Otherwise, an empty \addplot table will be
# created, which will be interpreted as an external data source in either the file
# ''... |
java | @BetaApi
public final ListTargetSslProxiesPagedResponse listTargetSslProxies(ProjectName project) {
ListTargetSslProxiesHttpRequest request =
ListTargetSslProxiesHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.build();
return listTargetSslProx... |
java | public ServiceFuture<List<TldLegalAgreementInner>> listAgreementsNextAsync(final String nextPageLink, final ServiceFuture<List<TldLegalAgreementInner>> serviceFuture, final ListOperationCallback<TldLegalAgreementInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listAgreementsNext... |
python | def process_axes(self, obj, columns=None):
""" process axes filters """
# make a copy to avoid side effects
if columns is not None:
columns = list(columns)
# make sure to include levels if we have them
if columns is not None and self.is_multi_index:
for ... |
java | public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
final ModelNode opAddr = operation.get(OP_ADDR);
final PathAddress address = PathAddress.pathAddress(opAddr);
final String name = address.getLastElement().getValue();
final Resource depl... |
java | protected boolean isResourceInTimeWindow(CmsPublishedResource resource) {
return m_cms.existsResource(
m_cms.getRequestContext().removeSiteRoot(resource.getRootPath()),
CmsResourceFilter.DEFAULT);
} |
python | def _GetAnalysisPlugins(self, analysis_plugins_string):
"""Retrieves analysis plugins.
Args:
analysis_plugins_string (str): comma separated names of analysis plugins
to enable.
Returns:
list[AnalysisPlugin]: analysis plugins.
"""
if not analysis_plugins_string:
return [... |
java | public List<MoskitoPlugin> getPlugins() {
ArrayList<MoskitoPlugin> ret = new ArrayList<MoskitoPlugin>(plugins.values());
return ret;
} |
python | def create_plan(existing_users=None, proposed_users=None, purge_undefined=None, protected_users=None,
allow_non_unique_id=None, manage_home=True, manage_keys=True):
"""Determine what changes are required.
args:
existing_users (Users): List of discovered users
proposed_users (Use... |
python | def set_field_value(self, field_name, value):
""" Set value of response field named `field_name`.
If response contains single item, its field is set.
If response contains multiple items, all the items in response
are edited.
To edit response meta(e.g. 'count') edit response dire... |
java | private String decryptServerPassword(Server server) throws SecDispatcherException {
//CSOFF: LineLength
//The following fix was copied from:
// https://github.com/bsorrentino/maven-confluence-plugin/blob/master/maven-confluence-reporting-plugin/src/main/java/org/bsc/maven/confluence/plugin/Abs... |
python | def from_histogram(cls, histogram, bin_edges, axis_names=None):
"""Make a HistdD from numpy histogram + bin edges
:param histogram: Initial histogram
:param bin_edges: x bin edges of histogram, y bin edges, ...
:return: Histnd instance
"""
bin_edges = np.array(bin_edges)
... |
python | def run(targets, config_dir='.', check_licenses=False):
# type: (List[str], str, bool) -> None
"""Runs `pylint` and `flake8` commands and exits based off the evaluation
of both command results.
:param targets: List[str]
:param config_dir: str
:param check_licenses: bool
:return:
"""
... |
python | def tag_instance(instance_id, **tags):
"""Tag a single ec2 instance."""
logger.debug("Got request to add tags %s to instance %s."
% (str(tags), instance_id))
ec2 = boto3.resource('ec2')
instance = ec2.Instance(instance_id)
# Remove None's from `tags`
filtered_tags = {k: v for k... |
java | String tokenToString(int token)
{
if (Token.printTrees) {
String name = Token.name(token);
switch (token) {
case Token.STRING:
case Token.REGEXP:
case Token.NAME:
return name + " `" + this.string + "'";
case Token.NUMB... |
java | public Observable<InboundNatRuleInner> getAsync(String resourceGroupName, String loadBalancerName, String inboundNatRuleName, String expand) {
return getWithServiceResponseAsync(resourceGroupName, loadBalancerName, inboundNatRuleName, expand).map(new Func1<ServiceResponse<InboundNatRuleInner>, InboundNatRuleInn... |
python | def write_idat(self, outfile, idat_sequence):
"""
Write png with IDAT to file
`idat_sequence` should be iterable that produce IDAT chunks
compatible with `Writer` configuration.
"""
# http://www.w3.org/TR/PNG/#5PNG-file-signature
outfile.write(png_signature)
... |
python | def main():
"""The main entry point for command line invocation. It's output
is adjusted by command line arguments. By default it outputs 10
passwords.
For help on accepted arguments, run::
$ passgen -h
Or::
$ python -m passgen -h
"""
parser = argparse.ArgumentParser(
... |
python | def name(self):
""" Returns the recipe name which is its class name without package. """
if not hasattr(self, '_name'):
self._name = re.search('[a-z]+\.([a-z]+)\.([a-z]+)', str(self.__class__), re.IGNORECASE).group(2)
return self._name |
java | private Set<SNode> getMatchedNodes(SDocumentGraph graph) {
Set<SNode> matchedNodes = new HashSet<>();
for (SNode node: graph.getNodes()) {
if (node.getFeature(AnnisConstants.ANNIS_NS, AnnisConstants.FEAT_MATCHEDNODE) != null)
matchedNodes.add(node);
}
return matchedNodes;
} |
java | public Collection<Invocation> getUnusedStubbingsByLocation(Iterable<Object> mocks) {
Set<Stubbing> stubbings = AllInvocationsFinder.findStubbings(mocks);
//1st pass, collect all the locations of the stubbings that were used
//note that those are _not_ locations where the stubbings was used
... |
python | def _CreateAllTypes(self, enumTypes, dataTypes, managedTypes):
""" Create pyVmomi types from pyVmomi type definitions """
# Create versions
for typeInfo in managedTypes:
name = typeInfo[0]
version = typeInfo[3]
VmomiSupport.AddVersion(version, '', '1.0', 0, name)
V... |
python | def importNode(self, document, node, deep=0):
"""Implements (well enough for our purposes) DOM node import."""
nodetype = node.nodeType
if nodetype in (node.DOCUMENT_NODE, node.DOCUMENT_TYPE_NODE):
raise DOMException('Illegal node type for importNode')
if nodetype == node.ENT... |
java | private ReturnCode packageServerDumps(File packageFile, List<String> javaDumps) {
DumpProcessor processor = new DumpProcessor(serverName, packageFile, bootProps, javaDumps);
return processor.execute();
} |
python | def _MakeRanges(pairs):
"""Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]."""
ranges = []
last = -100
def evenodd(last, a, b, r):
if a != last+1 or b != _AddDelta(a, r[2]):
return False
r[1] = a
return True
def evenoddpair(last, a, b, r):
if a != last+2:
... |
java | public DnsBatchResult<Page<ChangeRequest>> listChangeRequests(
String zoneName, Dns.ChangeRequestListOption... options) {
DnsBatchResult<Page<ChangeRequest>> result = new DnsBatchResult<>();
Map<DnsRpc.Option, ?> optionMap = DnsImpl.optionMap(options);
RpcBatch.Callback<ChangesListResponse> callback =... |
java | public final void registerEventClass(String eventType, Class< ? extends ManagerEvent> clazz)
throws IllegalArgumentException
{
Constructor< ? > defaultConstructor;
if (!ManagerEvent.class.isAssignableFrom(clazz))
{
throw new IllegalArgumentException(clazz + " is not ... |
python | def get_url(self, resource, params=None):
"""
Generate url for request
"""
# replace placeholders
pattern = r'\{(.+?)\}'
resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource)
# build url
parts = (self.endpoint, '/api/', r... |
python | def _app_cache_deepcopy(obj):
"""
An helper that correctly deepcopy model cache state
"""
if isinstance(obj, defaultdict):
return deepcopy(obj)
elif isinstance(obj, dict):
return type(obj)((_app_cache_deepcopy(key), _app_cache_deepcopy(val)) for key, val in obj.items())
elif isin... |
python | def load_data(self, key=None, **kwargs):
""" Lee de disco la información y la devuelve
:param key:
"""
self.store.open()
if key:
return pd.read_hdf(self.PATH_DATABASE, key, **kwargs)
else:
data_load = dict()
for k in self.store.keys():
... |
python | def connect_sync(self, connection_id, connection_string):
"""Synchronously connect to a device
Args:
connection_id (int): A unique identifier that will refer to this connection
connection_string (string): A DeviceAdapter specific string that can be used to connect to
... |
python | def _check_file_is_under_workingdir(filename, wdir):
""" Raise error if input is being staged to a location not underneath the working dir
"""
p = filename
if not os.path.isabs(p):
p = os.path.join(wdir, p)
targetpath = os.path.realpath(p)
wdir = os.path.realp... |
java | public static Config load(String resourceBasename) {
return load(resourceBasename, ConfigParseOptions.defaults(),
ConfigResolveOptions.defaults());
} |
java | public BeanId getBeanId() {
if (ivBeanId == null) {
ivBeanId = new BeanId(ivBMD.j2eeName, null, false);
}
return ivBeanId;
} |
java | void setSize(int x, int y, int z)
{
this.sizeX = x;
this.sizeY = y;
this.sizeZ = z;
} |
python | def reward(self):
"""Returns a tuple of sum of raw and processed rewards."""
raw_rewards, processed_rewards = 0, 0
for ts in self.time_steps:
# NOTE: raw_reward and processed_reward are None for the first time-step.
if ts.raw_reward is not None:
raw_rewards += ts.raw_reward
if ts.p... |
python | def context(self, id):
"""Return a circuit breaker for the given ID."""
if id not in self.circuits:
self.circuits[id] = self.factory(self.clock, self.log.getChild(id),
self.error_types, self.maxfail,
se... |
python | def _parse_archive(self, targz, dest):
'''parse_targz will add a line to the install script to extract a
targz to a location, and also add it to the files.
Parameters
==========
targz: the targz to extract
dest: the location to extract it to
'''
... |
java | Map<CmsPrincipalBean, String> getResponsibles(CmsObject cms, CmsResource res) {
Map<CmsPrincipalBean, String> result = new HashMap<CmsPrincipalBean, String>();
List<CmsResource> parentResources = new ArrayList<CmsResource>();
// get all parent folders of the current file
try {
... |
python | def limits(self):
"""
Limits to use for the independent variable whenever
creating a linespace, plot, etc.
Defaults to `(-x, x)` where `x` is the largest absolute value
of the data corresponding to the independent variable.
If no such values are negative, defaults to `(0... |
java | public void filter(String name, EsAbstractConditionQuery.OperatorCall<BsElevateWordCQ> queryLambda,
ConditionOptionCall<FilterAggregationBuilder> opLambda, OperatorCall<BsElevateWordCA> aggsLambda) {
ElevateWordCQ cq = new ElevateWordCQ();
if (queryLambda != null) {
queryLambda.c... |
java | public static void write2File(String filePath, byte[] byteData) {
try {
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
bufferedOutputStream.write(byteData);
bufferedOutputStream.close();
} catch (FileNot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.