language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private void triangulateFeatures(List<AssociatedTriple> inliers,
DMatrixRMaj P1, DMatrixRMaj P2, DMatrixRMaj P3) {
List<DMatrixRMaj> cameraMatrices = new ArrayList<>();
cameraMatrices.add(P1);
cameraMatrices.add(P2);
cameraMatrices.add(P3);
// need elements to be non-empty so that it can use set().... |
python | def noisy_layer(self, prefix, action_in, out_size, sigma0,
non_linear=True):
"""
a common dense layer: y = w^{T}x + b
a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x +
(b+\epsilon_b*\sigma_b)
where \epsilon are random variables sampled from factorized no... |
java | public static List<CommerceCurrency> findByG_P_A(long groupId,
boolean primary, boolean active, int start, int end,
OrderByComparator<CommerceCurrency> orderByComparator,
boolean retrieveFromCache) {
return getPersistence()
.findByG_P_A(groupId, primary, active, start, end,
orderByComparator, retrieve... |
java | public static String decodeStr(String source, String charset) {
return StrUtil.str(decode(source), charset);
} |
java | public static Optional<Double> getDoubleOptional(Config config, String path) {
return Optional.ofNullable(getDouble(config, path));
} |
python | def trace_memory_usage(self, frame, event, arg):
"""Callback for sys.settrace"""
if event in ('line', 'return') and frame.f_code in self.code_map:
lineno = frame.f_lineno
if event == 'return':
lineno += 1
entry = self.code_map[frame.f_c... |
java | public ScheduleDescriptor generateScheduleDescriptor(LocalDate startDate, LocalDate endDate) {
return new ScheduleDescriptor(startDate, endDate, getFrequency(), getDaycountConvention(), getShortPeriodConvention(), getDateRollConvention(),
getBusinessdayCalendar(), getFixingOffsetDays(), getPaymentOffsetDays(), ... |
java | public DeploymentNode getDeploymentNodeWithName(String name, String environment) {
for (DeploymentNode deploymentNode : getDeploymentNodes()) {
if (deploymentNode.getEnvironment().equals(environment) && deploymentNode.getName().equals(name)) {
return deploymentNode;
}
... |
python | def create(gandi, vhost, paas, ssl, private_key, alter_zone, poll_cert,
background):
""" Create a new vhost. """
if not gandi.hostedcert.activate_ssl(vhost, ssl, private_key, poll_cert):
return
paas_info = gandi.paas.info(paas)
result = gandi.vhost.create(paas_info, vhost, alter_zone... |
python | def add_get(self, path: str, handler: _WebHandler, *,
name: Optional[str]=None, allow_head: bool=True,
**kwargs: Any) -> AbstractRoute:
"""
Shortcut for add_route with method GET, if allow_head is true another
route is added allowing head requests to the same endp... |
java | private static byte doEncodeOpcode(byte b, WsMessage message) {
Kind kind = message.getKind();
switch (kind) {
case CONTINUATION:
b |= Opcode.CONTINUATION.getCode();
break;
case TEXT: {
b |= Opcode.TEXT.getCode();
break;
}
case B... |
python | def ok_cred_def_id(token: str, issuer_did: str = None) -> bool:
"""
Whether input token looks like a valid credential definition identifier from input issuer DID (default any); i.e.,
<issuer-did>:3:CL:<schema-seq-no>:<cred-def-id-tag> for protocol >= 1.4, or
<issuer-did>:3:CL:<schema-seq-no> for protoco... |
python | def lower_extension(filename):
'''
This is a helper used by :meth:`Storage.save` to provide lowercase extensions for
all processed files, to compare with configured extensions in the same
case.
:param str filename: The filename to ensure has a lowercase extension.
'''
if '.' in filename:
... |
python | def tenengrad(img, ksize=3):
''''TENG' algorithm (Krotkov86)'''
Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
FM = Gx*Gx + Gy*Gy
mn = cv2.mean(FM)[0]
if np.isnan(mn):
return np.nanmean(FM)
retur... |
python | def main():
""" command line script """
print("Ontospy " + ontospy.VERSION)
ontospy.get_or_create_home_repo()
opts, args = parse_options()
if len(args) < 2:
printDebug("Please provide two arguments, or use -h for more options.")
sys.exit(0)
var = input("Match classes or properties? [c|p, c=default]:")
if... |
python | def set_min_level_to_syslog(self, level):
"""Allow to change syslog level after creation
"""
self.min_log_level_to_syslog = level
handler_class = logging.handlers.SysLogHandler
self._set_min_level(handler_class, level) |
java | public static void submitTopology(String name, Map stormConf, StormTopology topology, SubmitOptions opts)
throws AlreadyAliveException,
InvalidTopologyException {
if (!Utils.isValidConf(stormConf)) {
throw new IllegalArgumentException("Storm conf is not valid. Must be json-se... |
python | def create_object(self, obj_type, payload, return_fields=None):
"""Create an Infoblox object of type 'obj_type'
Args:
obj_type (str): Infoblox object type,
e.g. 'network', 'range', etc.
payload (dict): Payload with data to send
... |
java | public Any execute(DeviceImpl device,Any in_any) throws DevFailed
{
Util.out4.println("RestartServer.execute(): arrived ");
((DServer)(device)).restart_server();
return Util.return_empty_any("RestartServer");
} |
python | def make_client(api_version, session=None,
endpoint=None, service_type='monitoring'):
"""Returns an monitoring API client."""
client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP)
c = client_cls(
session=session,
service_type=service_type,
endpo... |
java | private HiveJdbcConnector withHiveEmbeddedConnection() throws SQLException {
if (this.hiveServerVersion == 1) {
this.conn = DriverManager.getConnection(HIVE_EMBEDDED_CONNECTION_STRING);
} else {
this.conn = DriverManager.getConnection(HIVE2_EMBEDDED_CONNECTION_STRING);
}
return this;
} |
python | def address_info(self):
"""Get a dictionary of addresses."""
return {
"node_ip_address": self._node_ip_address,
"redis_address": self._redis_address,
"object_store_address": self._plasma_store_socket_name,
"raylet_socket_name": self._raylet_socket_name,
... |
python | def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False):
""" Traverses the list of query paths to find the data requested
:param query_path: (list(str), str), list of query path branches or query string
Default b... |
python | def get_roles_paths(self):
'''
Returns all absolute paths to the roles/ directories, while considering
the ``BASEDIR`` and ``ROLES`` config variables.
'''
roles = []
for path in self.config.ROLES:
roles.append(self.get_absolute_path(path))
return ro... |
java | public java.util.List<String> getStepIds() {
if (stepIds == null) {
stepIds = new com.amazonaws.internal.SdkInternalList<String>();
}
return stepIds;
} |
java | public void InvokeEvent(String eventName, JSONArray args)
{
HubOnDataCallback subscription;
if(mSubscriptions.containsKey(eventName))
{
subscription = mSubscriptions.get(eventName);
subscription.OnReceived(args);
}
} |
java | public Theme theme(String name, Project project, Map<String, Object> attributes) {
Theme theme = new Theme(instance);
theme.setName(name);
theme.setProject(project);
addAttributes(theme, attributes);
theme.save();
return theme;
} |
python | def to_array_with_default(value, default_value):
"""
Converts value into array object with specified default.
Single values are converted into arrays with single element.
:param value: the value to convert.
:param default_value: default array object.
:return: array obj... |
java | private List<UpdateLifecycle> getUpdateLifecycles()
{
final List<UpdateLifecycle> ret = new ArrayList<>();
for (final UpdateLifecycle cycle : UpdateLifecycle.values()) {
ret.add(cycle);
}
Collections.sort(ret, (_cycle1, _cycle2) -> _cycle1.getOrder().compareTo(_cycle2.get... |
java | public PathImpl fsWalk(String userPath,
Map<String,Object> attributes,
String path)
{
return new ClasspathPath(_root, userPath, path);
} |
java | public CompletableFuture<TxnStatus> commitTxn(final String scope, final String stream, final UUID txId,
final OperationContext contextOpt) {
final OperationContext context = getNonNullOperationContext(scope, stream, contextOpt);
return withRetriesAsync((... |
python | def _send(self, email_message):
"""Sends an individual message via the Amazon SES HTTP API.
Args:
email_message: A single Django EmailMessage object.
Returns:
True if the EmailMessage was sent successfully, otherwise False.
Raises:
ClientError: An int... |
java | public List<CorporationContractsItemsResponse> getCorporationsCorporationIdContractsContractIdItems(
Integer contractId, Integer corporationId, String datasource, String ifNoneMatch, String token)
throws ApiException {
ApiResponse<List<CorporationContractsItemsResponse>> resp = getCorpor... |
java | public java.util.List<String> getDnsSearchDomains() {
if (dnsSearchDomains == null) {
dnsSearchDomains = new com.amazonaws.internal.SdkInternalList<String>();
}
return dnsSearchDomains;
} |
python | def ndfrom2d(xtr, rsi):
"""Undo the array shape conversion applied by :func:`ndto2d`,
returning the input 2D array to its original shape.
Parameters
----------
xtr : array_like
Two-dimensional input array
rsi : tuple
A tuple containing the shape of the axis-permuted array and the
... |
python | def read_chunk_body(self):
'''Read a fragment of a single chunk.
Call :meth:`read_chunk_header` first.
Returns:
tuple: 2-item tuple with the content data and raw data.
First item is empty bytes string when chunk is fully read.
Coroutine.
'''
# c... |
java | @UiThread
int getNearestParentPosition(int flatPosition) {
if (flatPosition == 0) {
return 0;
}
int parentCount = -1;
for (int i = 0; i <= flatPosition; i++) {
ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);
if (listItem.isParent()) {
... |
java | @Override
public ViewMetadata getViewMetadata(FacesContext context, String viewId)
{
// Not necessary given that this method always returns null, but staying true to
// the spec.
checkNull(context, "context");
//checkNull(viewId, "viewId");
// JSP impl must return null.
... |
python | def foreign_key_sets(chain, node):
"""
When a Django model has a ForeignKey to another model, the target
of the foreign key gets a '<modelname>_set' attribute for accessing
a queryset of the model owning the foreign key - eg:
class ModelA(models.Model):
pass
class ModelB(models.Model):... |
java | private String[] expandArgs(String[] originalArgv) {
List<String> vResult1 = Lists.newArrayList();
//
// Expand @
//
for (String arg : originalArgv) {
if (arg.startsWith("@") && options.expandAtSign) {
String fileName = arg.substring(1);
... |
python | def _verify_sector_identifier(self, request):
"""
Verify `sector_identifier_uri` is reachable and that it contains
`redirect_uri`s.
:param request: Provider registration request
:return: si_redirects, sector_id
:raises: InvalidSectorIdentifier
"""
si_url... |
java | public ServiceFuture<Void> removeNodesAsync(String poolId, NodeRemoveParameter nodeRemoveParameter, PoolRemoveNodesOptions poolRemoveNodesOptions, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromHeaderResponse(removeNodesWithServiceResponseAsync(poolId, nodeRemoveParameter, poolRemoveNod... |
java | public void removeConsumerListForExpression(
String topicExpression,
boolean selector,
boolean isWildcarded)
{
if (tc.isEntryEnabled())
SibTr.entry(tc,
"removeConsumerListForExpression",
new Object[]{topicExpression,
new Bool... |
java | public static String getStatusForItem(Long lastActivity) {
if (lastActivity.longValue() < CmsSessionsTable.INACTIVE_LIMIT) {
return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_BROADCAST_COLS_STATUS_ACTIVE_0);
}
return CmsVaadinUtils.getMessageText(Messages.GUI_MESSAGES_BROAD... |
python | def alignment_to_partials(alignment, missing_data=None):
""" Generate a partials dictionary from a treeCl.Alignment """
partials_dict = {}
for (name, sequence) in alignment.get_sequences():
datatype = 'dna' if alignment.is_dna() else 'protein'
partials_dict[name] = seq_to_partials(sequence, ... |
python | def _attempt_to_choose_formatting_pattern(self):
"""Attempts to set the formatting template and returns a string which
contains the formatted version of the digits entered so far."""
# We start to attempt to format only when at least MIN_LEADING_DIGITS_LENGTH digits of national
# number ... |
python | def from_name(cls, name, *, queue=DefaultJobQueueName.Workflow,
clear_data_store=True, arguments=None):
""" Create a workflow object from a workflow script.
Args:
name (str): The name of the workflow script.
queue (str): Name of the queue the workflow should be... |
python | def random_line_data(chars_per_line=80):
"""
Function to create a line of a random string
Args:
chars_per_line: An integer that says how many characters to return
Returns:
A String
"""
return ''.join(__random.choice(__string.ascii_letters) for x in range(chars_per_line)) |
python | def _rotate_tr(self):
"""Rotate the transformation matrix based on camera parameters"""
up, forward, right = self._get_dim_vectors()
self.transform.rotate(self.elevation, -right)
self.transform.rotate(self.azimuth, up) |
python | def set_persistent_git_options(self, **kwargs):
"""Specify command line options to the git executable
for subsequent subcommand calls
:param kwargs:
is a dict of keyword arguments.
these arguments are passed as in _call_process
but will be passed to the git c... |
java | public ComparatorChain<E> setComparator(final int index, final Comparator<E> comparator) throws IndexOutOfBoundsException {
return setComparator(index, comparator, false);
} |
python | def ma_plot(self, thresh, up_kwargs=None, dn_kwargs=None,
zero_line=None, **kwargs):
"""
MA plot
Plots the average read count across treatments (x-axis) vs the log2
fold change (y-axis).
Additional kwargs are passed to self.scatter (useful ones might include
... |
java | public BoostDocumentRuleCB acceptPK(String id) {
assertObjectNotNull("id", id);
BsBoostDocumentRuleCB cb = this;
cb.query().docMeta().setId_Equal(id);
return (BoostDocumentRuleCB) this;
} |
python | def get_group_members(self, group):
"""Returns a ``list`` with the group's members or ``None`` if
unsuccessful.
:param str group: Group we want users for.
"""
conn = self.bind
try:
records = conn.search_s(
current_app.config['LDAP_BASE_DN'], ... |
java | public boolean readThisMethod(String strMethodName)
{
Record recClassInfo = this.getMainRecord();
LogicFile recLogicFile = (LogicFile)this.getRecord(LogicFile.LOGIC_FILE_FILE);
try {
String strClassName = recClassInfo.getField(ClassInfo.CLASS_NAME).getString();
recL... |
java | public static void times(Number self, @ClosureParams(value=SimpleType.class,options="int") Closure closure) {
for (int i = 0, size = self.intValue(); i < size; i++) {
closure.call(i);
if (closure.getDirective() == Closure.DONE) {
break;
}
}
} |
java | public static int getOpCode(String opCodeName) {
if (opCodeNameMap.containsKey(opCodeName))
return opCodeNameMap.get(opCodeName);
return OP_INVALIDOPCODE;
} |
java | @Override
public void init(FilterConfig filterConfig) {
String m = "L init() ";
try {
logger.debug(m + ">");
super.init(filterConfig);
m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " init() ";
inited = false;
if (!initErrors) {
... |
python | def generate_export(self, export_type):
"""
Start a new export.
- **export_type** is a string specifying which type of export to start.
Returns a :py:class:`dict` containing metadata for the new export.
"""
if export_type in TALK_EXPORT_TYPES:
return talk.p... |
java | public void marshall(Relationship relationship, ProtocolMarshaller protocolMarshaller) {
if (relationship == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(relationship.getType(), TYPE_BINDING);
... |
java | public HttpUrl authorizeUrl(String scopes, HttpUrl redirectUrl, ByteString state, String team) {
HttpUrl.Builder builder = baseUrl.newBuilder("/oauth/authorize")
.addQueryParameter("client_id", clientId)
.addQueryParameter("scope", scopes)
.addQueryParameter("redirect_uri", redirectUrl.toStr... |
java | @Override
public OutlierResult run(Database db, Relation<V> relation) {
DBIDs ids = relation.getDBIDs();
WritableDoubleDataStore abodvalues = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_STATIC);
DoubleMinMax minmaxabod = new DoubleMinMax();
if(kernelFunction.getClass() == LinearKernelFu... |
java | public void forceFlush(SIBUuid12 streamID)
throws SIResourceException, SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "forceFlush", new Object[] { streamID });
// Synchronize to resolve racing messages.
synchronized (flushMap)
{
... |
python | def from_bin(class_, blob):
"""Return the Tx for the given binary blob.
:param blob: a binary blob containing a transaction streamed in standard
form. The blob may also include the unspents (a nonstandard extension,
optionally written by :func:`Tx.stream <stream>`), and they wil... |
python | def gammaRDD(sc, shape, scale, size, numPartitions=None, seed=None):
"""
Generates an RDD comprised of i.i.d. samples from the Gamma
distribution with the input shape and scale.
:param sc: SparkContext used to create the RDD.
:param shape: shape (> 0) parameter for the Gamma dis... |
python | def tagversion(repo, level='patch', special=''):
"""Increment and return tagged version in git.
Increment levels are patch, minor and major.
Using semver.org versioning: {major}.{minor}.{patch}{special}
Special must start with a-z and consist of _a-zA-Z0-9.
"""
prepend = 'v'
with lcd(repo):... |
python | def is_complete(self):
"""Returns True if this is a complete solution, i.e, all nodes are allocated
Returns
-------
bool
True if all nodes are llocated.
"""
return all(
[node.route_allocation() is not None for node in list(self._nodes.valu... |
java | public ServiceFuture<VaultInner> createOrUpdateAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParameters parameters, final ServiceCallback<VaultInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, parameters), serv... |
java | public void setVpnConnectionIds(java.util.Collection<String> vpnConnectionIds) {
if (vpnConnectionIds == null) {
this.vpnConnectionIds = null;
return;
}
this.vpnConnectionIds = new com.amazonaws.internal.SdkInternalList<String>(vpnConnectionIds);
} |
python | def dist(self, x1, x2):
"""Return the weighted distance between ``x1`` and ``x2``.
Parameters
----------
x1, x2 : `NumpyTensor`
Tensors whose mutual distance is calculated.
Returns
-------
dist : float
The distance between the tensors.
... |
java | protected InputStream getInputStream(String pdbId) throws IOException{
if ( pdbId.length() != 4)
throw new IOException("The provided ID does not look like a PDB ID : " + pdbId);
// Check existing
File file = downloadStructure(pdbId);
if(!file.exists()) {
throw new IOException("Structure "+pdbId+" not f... |
java | public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == cancel_button)
onCancel();
else if (source == add_button || source == direct_text)
onAdd();
else if (source == remove_button)
onRemove();
else if (source == dismiss_button)
onDismiss();
else if (source ... |
java | public void variableRectangle(Rectangle rect) {
float t = rect.getTop();
float b = rect.getBottom();
float r = rect.getRight();
float l = rect.getLeft();
float wt = rect.getBorderWidthTop();
float wb = rect.getBorderWidthBottom();
float wr = rect.getBorderWidthRig... |
java | public Object func(String param) {
ReqInfo reqInfo = ContextUtils.getReqInfo();
StringBuffer sb = new StringBuffer();
// if (reqInfo.m_bUseAjax)
// sb.append("document.");
sb.append(param);
sb.append(reqInfo.getRequestId());
return sb.toString();
} |
python | def resolve_parameters(value, parameters, date_time=datetime.datetime.now(), macros=False):
""" Resolve a format modifier with the corresponding value.
Args:
value: The string (path, table, or any other artifact in a cell_body) which may have format
modifiers. E.g. a table name could be <projec... |
java | private DisplayMode isSupported(DisplayMode display)
{
final DisplayMode[] supported = dev.getDisplayModes();
for (final DisplayMode current : supported)
{
final boolean multiDepth = current.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && display.equals(current);
if (... |
python | def git_tags() -> str:
"""
Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags.
"""
try:
subprocess.check_call(['git', 'fetch', '--tags'])
except CalledProce... |
python | def get_form_kwargs(self):
"""
Return the form kwargs.
This method injects the context variable, defined in
:meth:`get_agnocomplete_context`. Override this method to adjust it to
your needs.
"""
data = super(UserContextFormViewMixin, self).get_form_kwargs()
... |
python | def activate(self):
"""
Activates GwDocumentsInfo by registering:
* 2 commands (doc, doc_list)
* 1 document (documents_overview)
"""
self.commands.register("doc_list", "List all documents", self._list_documents)
self.commands.register("doc", "Shows the documentat... |
java | private IRI getLiteralPropertyIRI(Attribute attr) {
return rdfFactory.createIRI(baseIRI + R2RMLIRISafeEncoder.encode(attr.getRelation().getID().getTableName())
+ "#" + R2RMLIRISafeEncoder.encode(attr.getID().getName()));
} |
python | async def save_session( # type: ignore
self, app: 'Quart', session: SecureCookieSession, response: Response,
) -> None:
"""Saves the session to the response in a secure cookie."""
domain = self.get_cookie_domain(app)
path = self.get_cookie_path(app)
if not session:
... |
python | def _parse_pg_lscluster(output):
'''
Helper function to parse the output of pg_lscluster
'''
cluster_dict = {}
for line in output.splitlines():
version, name, port, status, user, datadir, log = (
line.split())
cluster_dict['{0}/{1}'.format(version, name)] = {
... |
java | public <K, EV> Graph<K, NullValue, EV> edgeTypes(Class<K> vertexKey, Class<EV> edgeValue) {
if (edgeReader == null) {
throw new RuntimeException("The edge input file cannot be null!");
}
DataSet<Tuple3<K, K, EV>> edges = edgeReader
.types(vertexKey, vertexKey, edgeValue)
.name(GraphCsvReader.class.get... |
java | public static IntegerBinding abs(final ObservableIntegerValue a) {
return createIntegerBinding(() -> Math.abs(a.get()), a);
} |
java | public static ProductBiddingCategory createBiddingCategory(
ProductDimensionType productDimensionType, @Nullable Long biddingCategoryId) {
Preconditions.checkNotNull(productDimensionType,
"ProductDimensionType is required when creating a ProductBiddingCategory");
ProductBiddingCategory productBidd... |
python | def _set_cam_share(self, v, load=False):
"""
Setter method for cam_share, mapped from YANG variable /hardware/profile/tcam/cam_share (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_cam_share is considered as a private
method. Backends looking to populate ... |
python | def c_avar(self):
""" return tau exponent "c" for noise type.
AVAR = prefactor * h_a * tau^c
"""
if self.b == -4:
return 1.0
elif self.b == -3:
return 0.0
elif self.b == -2:
return -1.0
elif self.b == -1:
return ... |
python | def ranges(self):
"""The expanded lists of values generated from the parameter fields
:returns: list<list>, outer list is for each parameter, inner loops are that
parameter's values to loop through
"""
steps = []
for p in self._parameters:
# inclusive range
... |
python | def get_schema_version_from_xml(xml):
""" Get schemaVersion attribute from OpenMalaria scenario file
xml - open file or content of xml document to be processed
"""
if isinstance(xml, six.string_types):
xml = StringIO(xml)
try:
tree = ElementTree.parse(xml)
except ParseError:
... |
java | protected void parsePropertyDefinition( TokenStream tokens,
JcrNodeTypeTemplate nodeType ) throws ConstraintViolationException {
tokens.consume('-');
Name name = parseName(tokens);
JcrPropertyDefinitionTemplate propDefn = new JcrPropertyDefinitionTempl... |
java | public int getReplaceContextLength() {
if (replaceContextLength == null) {
int replacementOffset = getReplaceRegion().getOffset();
ITextRegion currentRegion = getCurrentNode().getTextRegion();
int replaceContextLength = currentRegion.getLength() - (replacementOffset - currentRegion.getOffset());
this.repl... |
python | def is_same_host(host1, host2):
"""
Returns true if host1 == host2 OR map to the same host (using DNS)
"""
try:
if host1 == host2:
return True
else:
ips1 = get_host_ips(host1)
ips2 = get_host_ips(host2)
return len(set(ips1) & set(ips2)) >... |
java | @NonNull
public Parameters setBoolean(@NonNull String name, boolean value) {
return setValue(name, value);
} |
python | def _get_tag_match(self, ele, tree):
"""
Match tag
:param ele:
:type ele:
:param tree:
:type tree: None, list
:return:
:rtype: None | list
"""
if tree in [None, []]:
return [ele]
res = []
t = tree[0]
br... |
python | def notCalled(cls, spy): #pylint: disable=invalid-name
"""
Checking the inspector is not called
Args: SinonSpy
"""
cls.__is_spy(spy)
if not (not spy.called):
raise cls.failException(cls.message) |
java | private static MutableLongArrayND validate(
LongArrayND a, MutableLongArrayND result)
{
if (result == null)
{
result = LongArraysND.create(a.getSize());
}
else
{
Utils.checkForEqualSizes(a, result);
}
return result;
... |
java | @POST
@Path("/user/data/{userId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response recieveUserData(@Context Session session, @PathParam("userId") String userId, Map<String,?> data) {
try{
authServerLogic.recieveUserData(userId,data);
... |
java | protected CLIQUEUnit leftNeighbor(CLIQUEUnit unit, int dim) {
for(CLIQUEUnit u : denseUnits) {
if(u.containsLeftNeighbor(unit, dim)) {
return u;
}
}
return null;
} |
java | private <T> String format(final T t,
final IClassContainer container) {
final List<ExportContainer> exportContainers = extractExportContainers(t, container);
final String resultValues = exportContainers.stream()
.map(c -> convertFieldValue(container.getFiel... |
python | def relay_info(self, relay, attribute=None):
"""
Return information about a relay.
:param relay: The relay being queried.
:type relay: int
:param attribute: The attribute being queried, or all attributes for
that relay if None is specified.
:typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.