language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def build(self, **variables):
"""Formats the locator with specified parameters"""
return Locator(self.by, self.locator.format(**variables), self.description) |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case BpsimPackage.VENDOR_EXTENSION__ANY:
return any != null && !any.isEmpty();
case BpsimPackage.VENDOR_EXTENSION__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case BpsimPackage.VENDOR_EXTENSION... |
python | def check_existens_of_staging_tag_in_remote_repo():
"""
This method will check, if the given tag exists as a staging tag in the remote repository.
The intention is, that every tag, which should be deployed on a production envirnment,
has to be deployed on a staging environment before.
... |
java | public ServiceFuture<CognitiveServicesAccountInner> updateAsync(String resourceGroupName, String accountName, Sku sku, Map<String, String> tags, final ServiceCallback<CognitiveServicesAccountInner> serviceCallback) {
return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, accountName... |
python | def run_apps(app_lists):
"""Run a set of Ryu applications
A convenient method to load and instantiate apps.
This blocks until all relevant apps stop.
"""
app_mgr = AppManager.get_instance()
app_mgr.load_apps(app_lists)
contexts = app_mgr.create_contexts()
... |
java | @Override
public boolean isPresent(int accessor) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
JmfTr.entry(this, tc, "isPresent", new Object[] { Integer.valueOf(accessor) });
boolean result;
checkIndex(accessor);
synchronized (getMessageLockArtefact... |
java | public ArrayList<Long> billingAccount_easyHunting_serviceName_timeConditions_conditions_GET(String billingAccount, String serviceName, OvhTimeConditionsPolicyEnum policy) throws IOException {
String qPath = "/telephony/{billingAccount}/easyHunting/{serviceName}/timeConditions/conditions";
StringBuilder sb = path(qP... |
python | def write(self):
""" Writes generated presentation code into the destination file.
"""
html = self.render()
if self.file_type == 'pdf':
self.write_pdf(html)
else:
with codecs.open(self.destination_file, 'w',
encoding='utf_8') ... |
python | def next_down(x, context=None):
"""next_down(x): return the greatest representable float that's
strictly less than x.
This operation is quiet: flags are not affected.
"""
x = BigFloat._implicit_convert(x)
# make sure we don't alter any flags
with _saved_flags():
with (context if c... |
python | def is_overexposed(ims):
"""Simple test to check if image is overexposed
Parameters
----------
im: 2d array integer
the image
Returns
-------
overexposed: Bool
Is the image overexposed
"""
if len(np.shape(ims)) == 3:
return [is_overexposed(im) for im in ims]
... |
python | def is_lambda(fun):
"""
Check whether the given function is a lambda function.
.. testsetup::
from proso.func import is_lambda
.. testcode::
def not_lambda_fun():
return 1
lambda_fun = lambda: 1
print(
is_lambda(not_lambda_fun),
i... |
java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLSubClassOfAxiomImpl instance) throws SerializationException {
serialize(streamWriter, instance);
} |
python | def train_batch(self, batch_info: BatchInfo) -> None:
"""
Batch - the most atomic unit of learning.
For this reinforforcer, that involves:
1. Roll out environment and store out experience in the buffer
2. Sample the buffer and train the algo on sample batch
"""
... |
python | def print_model(self, include_unsigned_edges=False):
"""Return a SIF string of the assembled model.
Parameters
----------
include_unsigned_edges : bool
If True, includes edges with an unknown activating/inactivating
relationship (e.g., most PTMs). Default is Fals... |
java | public static final Atom vectorProduct(Atom a , Atom b){
Atom c = new AtomImpl();
c.setX( a.getY() * b.getZ() - a.getZ() * b.getY() ) ;
c.setY( a.getZ() * b.getX() - a.getX() * b.getZ() ) ;
c.setZ( a.getX() * b.getY() - a.getY() * b.getX() ) ;
return c ;
} |
python | def deploy(self, target, overwrite=False):
'''
deploy this contract
:param target:
:param account: the account address to use
:return: address, err
'''
name = self.name.replace('<stdin>:', "")
key = DB.pkey([EZO.DEPLOYED, name, target, self.hash])
... |
python | def isdir(self):
"""Returns True if entry is a directory.
"""
if self.type == RAR_BLOCK_FILE:
return (self.flags & RAR_FILE_DIRECTORY) == RAR_FILE_DIRECTORY
return False |
java | public static String getLockRoot(Long pipelineId) {
// 根据channelId , pipelineId构造path
return MessageFormat.format(ArbitrateConstants.NODE_LOCK_ROOT, getChannelId(pipelineId),
String.valueOf(pipelineId));
} |
python | def from_spec(spec):
"""Return a schema object from a spec.
A spec is either a string for a scalar type, or a list of 0 or 1 specs,
or a dictionary with two elements: {'fields': { ... }, required: [...]}.
"""
if spec == '':
return any_schema
if framework.is_str(spec):
# Scalar type
if spec not... |
java | public void deleteLdapGroupLink(Object groupIdOrPath, String cn) throws GitLabApiException {
if (cn == null || cn.trim().isEmpty()) {
throw new RuntimeException("cn cannot be null or empty");
}
delete(Response.Status.OK, null, "groups", getGroupIdOrPath(groupIdOrPath), "ldap_group_... |
java | void setChildrenContexts(Map<String, List<TraverserContext<T>>> children) {
assertTrue(this.children == null, "children already set");
this.children = children;
} |
python | def email_address(self, email_address):
"""
Sets the email_address of this OrderFulfillmentRecipient.
The email address of the fulfillment recipient. If provided, overrides the value from customer profile indicated by customer_id.
:param email_address: The email_address of this OrderFu... |
java | @SuppressWarnings("unused")
public void onCountryCodeSelected(String isoCode, String dialCode) {
Country selectedCountry = new Country(isoCode, dialCode);
countryCodeSelector.setSelectedCountry(selectedCountry);
} |
python | def auto_migrate_storage_system(*, persistent_storage_system=None, new_persistent_storage_system=None, data_item_uuids=None, deletions: typing.List[uuid.UUID] = None, utilized_deletions: typing.Set[uuid.UUID] = None, ignore_older_files: bool = True):
"""Migrate items from the storage system to the object context.
... |
python | async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
"""
Get multiple values from the cache, values not found are Nones.
:param keys: list of str
:param loads_fn: callable alternative to use as loads function
:param namespace: str alternative namespace to ... |
java | static Parser<Expression> simpleNewExpression(Parser<Expression> arg, Parser<DefBody> body) {
return Parsers.sequence(
term("new").next(TypeLiteralParser.ELEMENT_TYPE_LITERAL),
argumentList(arg),
body.optional(),
(type, args, defBody) -> new NewExpression(null, type, args, defBody));... |
java | public long readBits(int bit) throws IOException, JPEGMarkerException {
if (bit < 0) {
throw new IllegalArgumentException("bit must be greater than zero");
}
int i = 0, v = 0;
while (i != bit) {
i++;
v = (v << 1) | readBit();
}
return... |
java | @Override
public FilterSupportStatus isFilterSupported(
FilterAdapterContext context, KeyOnlyFilter filter) {
// We don't support replacing the value of a stripped cell with
// the its length (8-byte-big-endian). The KeyOnlyFilter supports this
// via a constructor parameter that is not exposed via ... |
java | void cleanUpInitializedJobsList() {
Iterator<Entry<JobID, JobInProgress>> jobsIterator =
initializedJobs.entrySet().iterator();
while(jobsIterator.hasNext()) {
Entry<JobID,JobInProgress> entry = jobsIterator.next();
JobInProgress job = entry.getValue();
if (job.getStatus().getRunState()... |
java | private static Element createResultElement(final Document document) {
return document.createElementNS(JaxRxConstants.URL, JaxRxConstants.JAXRX + ":results");
} |
python | def implements_storage(self):
"""
True if combination of field access properties imply that the field
implements a storage element.
"""
# 9.4.1, Table 12
sw = self.get_property('sw')
hw = self.get_property('hw')
if sw in (rdltypes.AccessType.rw, rdltypes.... |
java | public void disconnect() {
if (sendThread != null) {
sendThread.interrupt();
try {
sendThread.join();
} catch (InterruptedException e) {
}
sendThread = null;
}
if (receiveThread != null) {
receiveThread.interrupt();
try {
receiveThread.join();
} catch (InterruptedException e) {
... |
java | @Nullable
static DCLInfo findDCL(IfTree outerIf) {
// TODO(cushon): Optional.ifPresent...
ExpressionTree outerIfTest = getNullCheckedExpression(outerIf.getCondition());
if (outerIfTest == null) {
return null;
}
SynchronizedTree synchTree = getChild(outerIf.getThenStatement(), SynchronizedTre... |
java | static void put(final TypePath typePath, final ByteVector output) {
if (typePath == null) {
output.putByte(0);
} else {
int length = typePath.typePathContainer[typePath.typePathOffset] * 2 + 1;
output.putByteArray(typePath.typePathContainer, typePath.typePathOffset, length);
}
} |
python | def _activate(self):
"""Activates a number of streams"""
self.distribution_ = 1. / self.n_streams * np.ones(self.n_streams)
self.valid_streams_ = np.ones(self.n_streams, dtype=bool)
self.streams_ = [None] * self.k
self.stream_weights_ = np.zeros(self.k)
self.stream_coun... |
python | def setup(self):
"""Get default configuration."""
self.allow = self.config['allow']
self.halt = self.config['halt']
self.skip = self.config['skip'] |
python | def _get_candidates(self, v):
""" Collect candidates from all buckets from all hashes """
candidates = []
for lshash in self.lshashes:
for bucket_key in lshash.hash_vector(v, querying=True):
bucket_content = self.storage.get_bucket(
lshash.hash_nam... |
java | public void set(long startIndex, long endIndex)
{
if (endIndex <= startIndex) return;
int startWord = (int) (startIndex >> 6);
// since endIndex is one past the end, this is index of the last
// word to be changed.
int endWord = expandingWordNum(endIndex - 1);
long... |
python | def run(self, path=None):
"""
Runs the scaffold option generation for this scaffold in the given
path. If no path is supplied, then the current path is used.
:param path | <str> || None
"""
if path is None:
path = '.'
for prop in self._... |
python | def _insert_entity(entity, encryption_required=False,
key_encryption_key=None, encryption_resolver=None):
'''
Constructs an insert entity request.
:param entity:
The entity to insert. Could be a dict or an entity object.
:param object key_encryption_key:
The user-provi... |
java | public Waiter<DescribeInstanceHealthRequest> instanceDeregistered() {
return new WaiterBuilder<DescribeInstanceHealthRequest, DescribeInstanceHealthResult>().withSdkFunction(new DescribeInstanceHealthFunction(client))
.withAcceptors(new InstanceDeregistered.IsOutOfServiceMatcher(), new Instance... |
java | public static final Enumeration<String> getAvailableVariants(String source,
String target) {
return registry.getAvailableVariants(source, target);
} |
java | @Override
public EEnum getIfcStructuralSurfaceActivityTypeEnum() {
if (ifcStructuralSurfaceActivityTypeEnumEEnum == null) {
ifcStructuralSurfaceActivityTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE
.getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(1075);
}
return ifcStructuralSurfaceActi... |
python | def parse_env_zones(self):
'''returns a list of comma separated zones parsed from the GCE_ZONE environment variable.
If provided, this will be used to filter the results of the grouped_instances call'''
import csv
reader = csv.reader([os.environ.get('GCE_ZONE',"")], skipinitialspace=True... |
python | def request_name(self, name, allow_replacement=True, replace=False):
"""Aquires a bus name.
Returns
-------
NameOwner
An object you can use as a context manager to unown the name later.
"""
return NameOwner(self, name, allow_replacement, replace) |
python | def _set_qsfp(self, v, load=False):
"""
Setter method for qsfp, mapped from YANG variable /brocade_interface_ext_rpc/get_media_detail/output/interface/qsfp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_qsfp is considered as a private
method. Backends lo... |
java | public static Bundle installBundle(BundleContext context, Resource bundle, boolean checkExistence) throws IOException, BundleException {
if (checkExistence) {
BundleFile bf = new BundleFile(bundle);
if (!bf.isBundle()) throw new BundleException(bundle + " is not a valid bundle!");
Bundle existing = loa... |
python | def ConsultarUltimoComprobante(self, tipo_cbte=151, pto_vta=1):
"Consulta el último No de Comprobante registrado"
ret = self.client.consultarUltimoNroComprobantePorPtoVta(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit... |
python | def get_program_files_dir():
""" returns the location of the "program files" directory on a windows
platform
"""
ProgramFiles = bjam.variable("ProgramFiles")
if ProgramFiles:
ProgramFiles = ' '.join(ProgramFiles)
else:
ProgramFiles = "c:\\Program Files"
return ProgramFile... |
java | public LaunchConfig withEnvironmentVariables(java.util.Map<String, String> environmentVariables) {
setEnvironmentVariables(environmentVariables);
return this;
} |
python | def get_groups_of_user(self, user_id, **kwargs): # noqa: E501
"""Get groups of the user. # noqa: E501
An endpoint for retrieving groups of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/users/{user-id}/groups -H 'Authorization: Bearer API_KEY'` # noqa: E501
This ... |
java | public Piece getPiece(int index) {
if (this.pieces == null) {
throw new IllegalStateException("Torrent not initialized yet.");
}
if (index >= this.pieces.length) {
throw new IllegalArgumentException("Invalid piece index!");
}
return this.pieces[index];
} |
python | def clean_email(self):
"""
Validate that the e-mail address is unique.
"""
if get_user_model().objects.filter(
email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_('This email is already in use. Please supply a different email.'))
retur... |
java | public static void writeElement(Element e,
XMLStreamWriter writer,
boolean repairing,
boolean endElement)
throws XMLStreamException {
String prefix = e.getPrefix();
String ns = e.getNamesp... |
python | def ReadArtifact(self, name, cursor=None):
"""Looks up an artifact with given name from the database."""
cursor.execute("SELECT definition FROM artifacts WHERE name = %s", [name])
row = cursor.fetchone()
if row is None:
raise db.UnknownArtifactError(name)
else:
return _RowToArtifact(row... |
java | @Deprecated
public ApnsServiceBuilder withProxySocket(Socket proxySocket) {
return this.withProxy(new Proxy(Proxy.Type.SOCKS,
proxySocket.getRemoteSocketAddress()));
} |
java | public static <T> Iterator<T> iterator(T first, T second) {
return ArrayIterator.of(first, second);
} |
java | public ServiceFuture<String> cloneAsync(UUID appId, String versionId, CloneOptionalParameter cloneOptionalParameter, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(cloneWithServiceResponseAsync(appId, versionId, cloneOptionalParameter), serviceCallback);
} |
java | public String notifications_sendEmailPlain(Collection<Integer> recipientIds, CharSequence subject, CharSequence text)
throws FacebookException, IOException {
return notifications_sendEmail(recipientIds, subject, /*fbml*/null, text);
} |
java | public Map<String, String> getDataAsMap(String prefix, String separator) {
return getDataAsMap(prefix, separator, 0);
} |
java | public void addItemPersistenceListener(ItemsPersistenceListener listener)
{
if (listener instanceof ExtendedMandatoryItemsPersistenceListener)
{
extendedMandatoryListeners.add((ExtendedMandatoryItemsPersistenceListener)listener);
}
else if (listener instanceof MandatoryItemsPersisten... |
python | def modify_column_if_table_exists(self,
tablename: str,
fieldname: str,
newdef: str) -> Optional[int]:
"""Alters a column's definition without renaming it."""
if not self.table_exists(tablen... |
python | def do_continue(self, args):
"""Continue the interpreter
"""
self._do_print_from_last_cmd = True
self._interp.cont()
return True |
java | @Override
public void prepare(FeatureProvider provider)
{
super.prepare(provider);
if (provider instanceof ProducibleListener)
{
addListener((ProducibleListener) provider);
}
} |
python | def _map_to_processors(self, f, objective):
"""Map a function to a list of processors, and return the output that
best satisfies a transitive objective function. The list of
processors will differ according to the number of evil qubits and
:func:`_proc_limit`, see details in :func:`self... |
java | public final void finalizeStream(Stream stream) {
FinalizeStreamRequest request = FinalizeStreamRequest.newBuilder().setStream(stream).build();
finalizeStream(request);
} |
python | def file_name(self, file_name):
"""
Updates the file_name.
Args:
file_name:
"""
if not self.can_update():
self._tcex.handle_error(910, [self.type])
self._data['fileName'] = file_name
request = {'fileName': file_name}
return self.t... |
python | def plot_zt_dop(self, temps='all', output='average', relaxation_time=1e-14):
"""
Plot the figure of merit zT in function of doping levels for different
temperatures.
Args:
temps: the default 'all' plots all the temperatures in the analyzer.
Specify a list ... |
python | def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False):
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
from disco.core import Disco
"""
training_data - training samples
fitting_data - dataset to b... |
python | def api_exception(http_code):
"""Convenience decorator to associate HTTP status codes with :class:`.ApiError` subclasses.
:param http_code: (int) HTTP status code.
:return: wrapper function.
"""
def wrapper(*args):
code = args[0]
ErrorMapping.mapping[http_code] = code
return... |
java | @Override
public Set<StringTextValue<?>> asSet()
{
final Set<StringTextValue<?>> allSettings = new HashSet<>();
allSettings.add(getOpen());
allSettings.add(getClose());
allSettings.add(getAccordion());
allSettings.add(getPersist());
allSettings.add(getQuery());
allSettings.add(getClickQuery());
return... |
java | protected void validateFetchOrientation(FetchOrientation orientation,
EnumSet<FetchOrientation> supportedOrientations) throws HiveSQLException {
if (!supportedOrientations.contains(orientation)) {
throw new HiveSQLException("The fetch type " + orientation.toString() +
" is not supported for th... |
java | @Override
public void filter(final ContainerRequestContext containerRequestContext) {
if (backend.getConfiguration().shouldProcessContext(IncomingRequest)) {
final List<String> serializedTraceeHeaders = containerRequestContext.getHeaders().get(TraceeConstants.TPIC_HEADER);
if (serializedTraceeHeaders != null ... |
java | public void setTextByReflection(Object obj, String text)
{
try {
java.lang.reflect.Method method = obj.getClass().getMethod("setText", String.class);
if (method != null)
method.invoke(obj, text);
} catch (Exception e) {
e.printStackTra... |
java | public static INDArray toMatrix(Matrix arr) {
// we assume that Matrix always has F order
return Nd4j.create(arr.toArray(), new int[] {arr.numRows(), arr.numCols()}, 'f');
} |
java | public static void main(String[] args)
{
// Default to System.out, autoflushing
PrintWriter sendOutputTo = new PrintWriter(System.out, true);
// Read our simplistic input args, if supplied
for (int i = 0; i < args.length; i++)
{
if ("-out".equalsIgnoreCase(args[i]))
{
i++;
... |
python | def get_quote(self, code, as_json=False):
"""
gets the quote for a given stock code
:param code:
:return: dict or None
:raises: HTTPError, URLError
"""
code = code.upper()
if self.is_valid_code(code):
url = self.build_url_for_quote(code)
... |
java | public JavaFileObject asJavaFileObject(File file) {
JavacFileManager fm = (JavacFileManager)context.get(JavaFileManager.class);
return fm.getRegularFile(file);
} |
java | public static void doAssert(boolean bSuccess)
{
if (!bSuccess)
{
Exception ex = new Exception();
System.out.println("Assert False:");
ex.printStackTrace();
System.out.println("---Assert False");
}
} |
python | def license2marc(self, key, value):
"""Populate the ``540`` MARC field."""
return {
'a': value.get('license'),
'b': value.get('imposing'),
'u': value.get('url'),
'3': value.get('material'),
} |
python | def update_recurring_item(self, recurring_item_id, recurring_item_dict):
"""
Updates a recurring item
:param recurring_item_id: the recurring item id
:param recurring_item_dict: dict
:return: dict
"""
return self._create_put_request(
resource=RECURRIN... |
java | public Observable<ServiceResponse<RestorePointInner>> createWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName, String restorePointLabel) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot b... |
python | def create_consul_client(consul_configuration: ConsulConfiguration) -> Consul:
"""
Creates a Consul client using the given configuration.
:param consul_configuration: the configuration to use to create the client
:return: the created client
"""
consul_client = Consul(
host=consul_configu... |
python | def add(self, item):
"""
Add an item to the work queue.
:param item: The work item to add. An item may be of any
type; however, if it is not hashable, then the
work queue must either be initialized with
``unique`` set to ``False``,... |
python | def erase(self, message=None):
"""Erase something whose you write before: message"""
if not message:
message = self.last_message
# Move cursor to the beginning of line
super(Animation, self).write("\033[G")
# Erase in line from cursor
super(Animation, self).wr... |
java | @Override
public CompletableFuture<Void> onStop() {
log.info("Stopping the JobMaster for job {}({}).", jobGraph.getName(), jobGraph.getJobID());
// disconnect from all registered TaskExecutors
final Set<ResourceID> taskManagerResourceIds = new HashSet<>(registeredTaskManagers.keySet());
final FlinkException c... |
java | public static <T, U extends Closeable> T withCloseable(U self, @ClosureParams(value=FirstParam.class) Closure<T> action) throws IOException {
try {
T result = action.call(self);
Closeable temp = self;
self = null;
temp.close();
return result;
... |
python | def dead_code_elimination(graph, du, ud):
"""
Run a dead code elimination pass.
Instructions are checked to be dead. If it is the case, we remove them and
we update the DU & UD chains of its variables to check for further dead
instructions.
"""
for node in graph.rpo:
for i, ins in no... |
java | public Set<MongoNamespace> getSynchronizedNamespaces() {
this.waitUntilInitialized();
try {
ongoingOperationsGroup.enter();
return this.syncConfig.getSynchronizedNamespaces();
} finally {
ongoingOperationsGroup.exit();
}
} |
java | private void handleLifecycleTransitionFailure(Throwable t) {
if (t.getCause() != null && t.getCause() instanceof CacheConfigurationException)
throw (CacheConfigurationException) t.getCause();
else if (t.getCause() != null && t.getCause() instanceof InvocationTargetException && t.getCause().getCause... |
python | def put(self, filename, chunkIdx, totalChunks):
"""
stores a chunk of new file, this is a nop if the file already exists.
:param filename: the filename.
:param chunkIdx: the chunk idx.
:param totalChunks: the no of chunks expected.
:return: the no of bytes written and 200... |
python | def remove_initial_spaces_and_mark_message_lines(lines):
"""
Removes the initial spaces in each line before marking message lines.
This ensures headers can be identified if they are indented with spaces.
"""
i = 0
while i < len(lines):
lines[i] = lines[i].lstrip(' ')
i += 1
... |
python | def calcWeightedAvg(data,weights):
'''
Generates a weighted average of simulated data. The Nth row of data is averaged
and then weighted by the Nth element of weights in an aggregate average.
Parameters
----------
data : numpy.array
An array of data with N rows of J floats
weights ... |
java | public static CellStyle setBorder(CellStyle cellStyle, BorderStyle borderSize, IndexedColors colorIndex) {
cellStyle.setBorderBottom(borderSize);
cellStyle.setBottomBorderColor(colorIndex.index);
cellStyle.setBorderLeft(borderSize);
cellStyle.setLeftBorderColor(colorIndex.index);
cellStyle.setBorderR... |
python | def get_os_filename (path):
"""Return filesystem path for given URL path."""
if os.name == 'nt':
path = prepare_urlpath_for_nt(path)
res = urllib.url2pathname(fileutil.pathencode(path))
if os.name == 'nt' and res.endswith(':') and len(res) == 2:
# Work around http://bugs.python.org/issue... |
java | @SuppressWarnings("unchecked")
public static <T> T invokeNoArgs(Object instance, ReflectionMethod method) {
method.setAccessible(true);
try {
return (T) method.invoke(instance, NO_ARGS);
} catch (Exception e) {
throw SneakyException.sneakyThrow(e);
}
} |
java | @Override
public Object getConnection( Subject subject,
ConnectionRequestInfo cxRequestInfo ) throws ResourceException {
JcrSessionHandle handle = new JcrSessionHandle(this);
addHandle(handle);
return handle;
} |
java | public void abortExternalTx(TransactionImpl odmgTrans)
{
if (log.isDebugEnabled()) log.debug("abortExternTransaction was called");
if (odmgTrans == null) return;
TxBuffer buf = (TxBuffer) txRepository.get();
Transaction extTx = buf != null ? buf.getExternTx() : null;
tr... |
python | def get_data_length(self):
"""QR codes contain a "data length" field. This method creates this
field. A binary string representing the appropriate length is
returned.
"""
#The "data length" field varies by the type of code and its mode.
#discover how long the "data lengt... |
python | def remove_block(self, name):
""" Removes an existing block from the AST.
`name`
Block name.
* Raises a ``ValueError`` exception if `name` hasn't been added.
"""
if not self._ast or not name in self._block_map:
raise ValueError(u"Block '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.