language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def _get_requested_filters(self, **kwargs):
"""
Convert 'filters' query params into a dict that can be passed
to Q. Returns a dict with two fields, 'include' and 'exclude',
which can be used like:
result = self._get_requested_filters()
q = Q(**result['include'] & ~Q(... |
python | def get_template(name):
"""
Look for 'name' in the vr.runners.templates folder. Return its contents.
"""
path = pkg_resources.resource_filename('vr.runners', 'templates/' + name)
with open(path, 'r') as f:
return f.read() |
python | def check_bam(bam, o):
"""
Check reads in BAM file for read type and lengths.
:param str bam: BAM file path.
:param int o: Number of reads to look at for estimation.
"""
try:
p = sp.Popen(['samtools', 'view', bam], stdout=sp.PIPE)
# Count paired alignments
paired = 0
... |
java | public static systembackup get(nitro_service service, String filename) throws Exception{
systembackup obj = new systembackup();
obj.set_filename(filename);
systembackup response = (systembackup) obj.get_resource(service);
return response;
} |
python | def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_imag... |
python | def index(value, array):
"""
Array search that behaves like I want it to. Totally dumb, I know.
"""
i = array.searchsorted(value)
if i == len(array): return -1
else: return i |
java | public <T extends Client<I, O>, R extends Client<I, O>, I extends HttpRequest, O extends HttpResponse>
B decorator(Function<T, R> decorator) {
decoration.add(decorator);
return self();
} |
java | @Override
public EClass getIfcPort() {
if (ifcPortEClass == null) {
ifcPortEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(438);
}
return ifcPortEClass;
} |
java | @UiHandler("m_everyDay")
void onDaysValueChange(ValueChangeEvent<String> event) {
if (handleChange()) {
m_controller.setInterval(m_everyDay.getText());
}
} |
python | def DbDeleteClassProperty(self, argin):
""" Delete class properties from database
:param argin: Str[0] = Tango class name
Str[1] = Property name
Str[n] = Property name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
self._log.debug("In D... |
python | def running_window(iterable, size):
"""Generate n-size running window.
Example::
>>> for i in running_windows([1, 2, 3, 4, 5], size=3):
... print(i)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
**中文文档**
简单滑窗函数。
"""
if size > len(iterable):
raise ValueErro... |
java | public String getRewriteDirective(CaptureSearchResult capture) {
String directive = null;
// use getter, as it may be overridden in sub-classes.
RewriteDirector rd = getRewriteDirector();
if (rd != null) {
directive = rd.getRewriteDirective(this, capture);
}
return directive;
} |
java | public EClass getIfcSpaceHeaterType() {
if (ifcSpaceHeaterTypeEClass == null) {
ifcSpaceHeaterTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(523);
}
return ifcSpaceHeaterTypeEClass;
} |
python | def shuffle(self):
"""
Re-indexes the dataset in random order
:return: the shuffled dataset instance
"""
order = range(len(self))
random.shuffle(order)
for name, data in self.fields.items():
reindexed = []
for _, i in enumerate(order):
... |
java | public String serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(object);
return new String(Base64.encodeBase64(bos.toByteArray()));
} catch (IOException e) {
LOGGE... |
java | public static Matcher<ExpressionTree> booleanConstant(final boolean value) {
return new Matcher<ExpressionTree>() {
@Override
public boolean matches(ExpressionTree expressionTree, VisitorState state) {
if (expressionTree instanceof JCFieldAccess) {
Symbol symbol = ASTHelpers.getSymbol(... |
java | @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4691")
public <T> void discardAll(Key<T> key) {
if (isEmpty()) {
return;
}
int writeIdx = 0;
int readIdx = 0;
for (; readIdx < size; readIdx++) {
if (bytesEqual(key.asciiName(), name(readIdx))) {
continue;
}
... |
java | public EClass getIfcStructuralLinearActionVarying() {
if (ifcStructuralLinearActionVaryingEClass == null) {
ifcStructuralLinearActionVaryingEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(544);
}
return ifcStructuralLinearActionVaryingEClass;
... |
java | public boolean decompose( ZMatrixRMaj a )
{
decomposeCommonInit(a);
double LUcolj[] = vv;
for( int j = 0; j < n; j++ ) {
// make a copy of the column to avoid cache jumping issues
for( int i = 0; i < m; i++) {
LUcolj[i*2] = dataLU[i*stride + j*2];
... |
java | @Nonnull
public JSInvocation staticInvoke (@Nullable final AbstractJSClass aType, @Nonnull final String sMethod)
{
final JSInvocation aInvocation = new JSInvocation (aType, sMethod);
return addStatement (aInvocation);
} |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSIPAddress ipaddress_validator = new MPSIPAddress();
ipaddress_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true);
ipaddress_validator.validate(operationType, ipaddress, "\"ipaddress\"");
... |
java | public final long getTotalSize()
{
long result = 0;
result = result + _storedItemManager.getStatistics().getTotalSize();
result = result + _unstoredItemManager.getStatistics().getTotalSize();
return result;
} |
java | public ServiceFuture<VnetValidationFailureDetailsInner> verifyHostingEnvironmentVnetAsync(VnetParameters parameters, final ServiceCallback<VnetValidationFailureDetailsInner> serviceCallback) {
return ServiceFuture.fromResponse(verifyHostingEnvironmentVnetWithServiceResponseAsync(parameters), serviceCallback);
... |
python | def choose_ancestral_states_joint(tree, feature, states, frequencies):
"""
Chooses node ancestral states based on their marginal probabilities using joint method.
:param frequencies: numpy array of state frequencies
:param tree: ete3.Tree, the tree of interest
:param feature: str, character for whi... |
java | public final void merge(final Record oldRecord, final Record newRecord) {
Preconditions.checkNotNull(oldRecord);
for (final URI property : newRecord.getProperties()) {
if (appliesTo(property)) {
oldRecord.set(property,
merge(property, oldRecord.get(p... |
python | def _kendall_tau_add(self, len_old, diff_pos, tau_old):
"""Compute Kendall tau delta.
The new sequence has length len_old + 1.
Parameters
----------
len_old : int
The length of the old sequence, used to compute tau_old.
diff_pos : int
Difference ... |
python | def unconvert_coord_object(tile):
"""Convert rawr_tiles.tile.Tile -> ModestMaps.Core.Coordinate"""
assert isinstance(tile, Tile)
return Coordinate(zoom=tile.z, column=tile.x, row=tile.y) |
java | private boolean waitForPermissionIfNecessary(final long timeoutInNanos, final long nanosToWait) {
boolean canAcquireImmediately = nanosToWait <= 0;
boolean canAcquireInTime = timeoutInNanos >= nanosToWait;
if (canAcquireImmediately) {
return true;
}
if (canAcquireInT... |
java | public static Ticker adaptTicker(
MercadoBitcoinTicker mercadoBitcoinTicker, CurrencyPair currencyPair) {
BigDecimal last = mercadoBitcoinTicker.getTicker().getLast();
BigDecimal bid = mercadoBitcoinTicker.getTicker().getBuy();
BigDecimal ask = mercadoBitcoinTicker.getTicker().getSell();
BigDecim... |
java | public static void glBindRenderbuffer(int target, int renderBuffer)
{
checkContextCompatibility();
nglBindRenderbuffer(target, WebGLObjectMap.get().toRenderBuffer(renderBuffer));
} |
java | private State calculateNextState(final long timeoutInNanos, final State activeState) {
long cyclePeriodInNanos = activeState.config.getLimitRefreshPeriodInNanos();
int permissionsPerCycle = activeState.config.getLimitForPeriod();
long currentNanos = currentNanoTime();
long currentCycle ... |
java | public ServerGroup updateServerGroupName(int serverGroupId, String name) {
ServerGroup serverGroup = null;
BasicNameValuePair[] params = {
new BasicNameValuePair("name", name),
new BasicNameValuePair("profileIdentifier", this._profileName)
};
try {
JSO... |
python | def _ParseHeader(self, format_type, value_data):
"""Parses the header.
Args:
format_type (int): format type.
value_data (bytes): value data.
Returns:
AppCompatCacheHeader: header.
Raises:
ParseError: if the value data could not be parsed.
"""
data_type_map_name = self.... |
java | public void resolveBeanClass(ScheduleRule scheduleRule) throws IllegalRuleException {
String beanId = scheduleRule.getSchedulerBeanId();
if (beanId != null) {
Class<?> beanClass = resolveBeanClass(beanId, scheduleRule);
if (beanClass != null) {
scheduleRule.setSch... |
python | def get_broadcast_transactions(coin_symbol='btc', limit=10, api_key=None):
"""
Get a list of broadcast but unconfirmed transactions
Similar to bitcoind's getrawmempool method
"""
url = make_url(coin_symbol, 'txs')
params = {}
if api_key:
params['token'] = api_key
if limit:
... |
java | public static <E> boolean iterableSizeEq(Iterable<E> itrbl, int k) {
// 1) try to iterate k times over itrbl;
Iterator<E> it = itrbl.iterator();
for(int i = 0; i < k; i++) {
if(!it.hasNext()) return false;
it.next();
}
// 2) next check that there are no more elements in itrbl
return !it.hasNext();
} |
java | private String fixSpecials(final String inString) {
StringBuilder tmp = new StringBuilder();
for (int i = 0; i < inString.length(); i++) {
char chr = inString.charAt(i);
if (isSpecial(chr)) {
tmp.append(this.escape);
tmp.append(chr);
} else {
tmp.append(chr);
}
}
return tmp.toString()... |
java | static StatsData aggregateStats(Collection<StatsData> dataSet) {
StatsData combined = new StatsData();
for (StatsData stats : dataSet) {
if (stats.count == 0) {
continue;
}
if (combined.total == 0) {
combined.min = stats.min;
... |
java | public void marshall(EventRiskType eventRiskType, ProtocolMarshaller protocolMarshaller) {
if (eventRiskType == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(eventRiskType.getRiskDecision(), RISKDEC... |
java | public boolean findAndReportCycles(DependencyGraph graph) {
this.graph = graph;
cycleDetected = false;
visitedEdge = new LinkedHashMap<Key<?>, Dependency>(graph.size());
for (Key<?> key : graph.getAllKeys()) {
visit(key, null);
}
return cycleDetected;
} |
python | def block_layer(inputs, filters, bottleneck, block_fn, blocks, strides,
training, name, data_format):
"""Creates one layer of blocks for the ResNet model.
Args:
inputs: A tensor of size [batch, channels, height_in, width_in] or
[batch, height_in, width_in, channels] depending on data_form... |
python | def has_file(self, name: str):
'''
check whether this directory contains the file.
'''
return os.path.isfile(self._path / name) |
python | def clear_all():
"""
Clear any and all stored state from Orca.
"""
_TABLES.clear()
_COLUMNS.clear()
_STEPS.clear()
_BROADCASTS.clear()
_INJECTABLES.clear()
_TABLE_CACHE.clear()
_COLUMN_CACHE.clear()
_INJECTABLE_CACHE.clear()
for m in _MEMOIZED.values():
m.value.c... |
java | private void addCommentTags(Element element, List<? extends DocTree> tags, boolean depr,
boolean first, Content htmltree) {
addCommentTags(element, null, tags, depr, first, htmltree);
} |
python | def generate_dylib_load_command(header, libary_install_name):
""" Generates a LC_LOAD_DYLIB command for the given header and a library install path.
Note: the header must already contain at least one LC_LOAD_DYLIB command (see code comments).
Returns a ready-for-use load_command in terms of macholib.
"""
# One... |
python | def doBenchmark(plats):
'''
Perform the benchmark...
'''
logger = logging.getLogger("osrframework.utils")
# defining the results dict
res = {}
# args
args = []
#for p in plats:
# args.append( (str(p),) )
# selecting the number of tries to be performed
tries = [1, 4, 8 ,16, 24, 32, 40, 48, 56, 64]
... |
python | def delete(cls, label='default', path=None):
"""Delete a server configuration.
This method is thread safe.
:param label: A string. The configuration identified by ``label`` is
deleted.
:param path: A string. The configuration file to be manipulated.
Defaults to ... |
java | public boolean initOutPathLocalFS(Path outPath, WriteMode writeMode, boolean createDirectory) throws IOException {
if (isDistributedFS()) {
return false;
}
// NOTE: We actually need to lock here (process wide). Otherwise, multiple threads that
// concurrently work in this method (multiple output formats wri... |
python | def filename_add_custom_url_params(filename, request):
""" Adds custom url parameters to filename string
:param filename: Initial filename
:type filename: str
:param request: OGC-type request with specified bounding box, cloud coverage for specific product.
:type request: OgcReq... |
python | def remove_class(self, ioclass):
"""Remove VNXIOClass instance from policy."""
current_ioclasses = self.ioclasses
new_ioclasses = filter(lambda x: x.name != ioclass.name,
current_ioclasses)
self.modify(new_ioclasses=new_ioclasses) |
java | public void checkcast(TypeElement objectref) throws IOException
{
int index = subClass.resolveClassIndex(objectref);
checkcast(index);
} |
java | @Override
protected String getInstanceIdName(int id)
{
switch (id - super.getMaxInstanceId()) {
case Id_prefix: return "prefix";
case Id_uri: return "uri";
}
return super.getInstanceIdName(id);
} |
java | public static Partitions parse(String nodes) {
Partitions result = new Partitions();
try {
List<RedisClusterNode> mappedNodes = TOKEN_PATTERN.splitAsStream(nodes).filter(s -> !s.isEmpty())
.map(ClusterPartitionParser::parseNode).collect(Collectors.toList());
... |
python | def webhooks(request):
"""
Handles all known webhooks from stripe, and calls signals.
Plug in as you need.
"""
if request.method != "POST":
return HttpResponse("Invalid Request.", status=400)
json = simplejson.loads(request.POST["json"])
if json["event"] == "recurring_payment_fail... |
python | def is_new_preorder( self, preorder_hash, lastblock=None ):
"""
Given a preorder hash of a name, determine whether or not it is unseen before.
"""
if lastblock is None:
lastblock = self.lastblock
preorder = namedb_get_name_preorder( self.db, preorder_hash, lastblock... |
java | public static Map<String, QueryParameter> getUsedNotHiddenParametersMap(Report report) {
return getUsedParametersMap(report, false, false);
} |
python | def set_value(self, key, field, value):
"""Add the state of the key and field"""
self._db.hset(key, field, value) |
python | def transform(self, vector):
"""
Computes the Hadamard product of the vector.
"""
if isinstance(vector, RDD):
vector = vector.map(_convert_to_vector)
else:
vector = _convert_to_vector(vector)
return callMLlibFunc("elementwiseProductVector", self.s... |
java | protected Object getReceiver(CreationalContext<?> productCreationalContext, CreationalContext<?> receiverCreationalContext) {
// This is a bit dangerous, as it means that producer methods can end up
// executing on partially constructed instances. Also, it's not required
// by the spec...
... |
python | def object_data(self, multihash, **kwargs):
r"""Returns the raw bytes in an IPFS object.
.. code-block:: python
>>> c.object_data('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x08\x01'
Parameters
----------
multihash : str
Key of the ... |
python | def write(self, data):
"""! @brief Write bytes into the connection."""
# If nobody is connected, act like all data was written anyway.
if self.connected is None:
return 0
data = to_bytes_safe(data)
size = len(data)
remaining = size
while remaining:
... |
java | public static Map<Key<?>, Binding<?>> findBindingsInScope(Injector injector, Class<? extends Annotation>... scopeAnnotations) {
Map<Key<?>,Binding<?>> bindings = new LinkedHashMap<Key<?>, Binding<?>>();
ALL_BINDINGS: for( Map.Entry<Key<?>, Binding<?>> entry : injector.getAllBindings().entrySet() ) {
for( ... |
java | public void free() {
if (consumer != null) {
if (array != null) {
consumer.freeArray(array);
}
array = null;
}
} |
python | def subnet_absent(name=None, subnet_id=None, region=None, key=None, keyid=None, profile=None):
'''
Ensure subnet with passed properties is absent.
name
Name of the subnet.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
... |
java | @NullSafe
public static String getClassSimpleName(Object obj) {
return obj != null ? obj.getClass().getSimpleName() : null;
} |
python | def exists(instance_id=None, name=None, tags=None, region=None, key=None,
keyid=None, profile=None, in_states=None, filters=None):
'''
Given an instance id, check to see if the given instance id exists.
Returns True if the given instance with the given id, name, or tags
exists; otherwise, Fa... |
java | T clipInput(T input, T output) {
double ratioInput = input.width/(double)input.height;
double ratioOutput = output.width/(double)output.height;
T a = input;
if( ratioInput > ratioOutput ) { // clip the width
int width = input.height*output.width/output.height;
int x0 = (input.width-width)/2;
int x1 =... |
java | public void setVec2(String key, float x, float y)
{
checkKeyIsUniform(key);
NativeShaderData.setVec2(getNative(), key, x, y);
} |
python | def set_children(self, item, *newchildren):
"""
Replaces item’s children with newchildren.
Children present in item that are not present in newchildren are detached
from tree. No items in newchildren may be an ancestor of item.
:param newchildren: new item's children (list of i... |
python | def process_frames_face(self, frames):
"""
Preprocess from frames using face detector
"""
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(self.face_predictor_path)
mouth_frames = self.get_frames_mouth(detector, predictor, frames)
self.... |
python | def create_config(config_fname, override_url=None):
'''
Create the config file from the defaults under the given name.
'''
config_path = os.path.dirname(config_fname)
os.makedirs(config_path, exist_ok=True)
# Consider override URL. Only used by test suite runs
settings = DEFAULT_SETTINGS_FL... |
python | def get_three_parameters(self, regex_exp, parameters):
"""
Get three parameters from a given regex expression
Raise an exception if more than three were found
:param regex_exp:
:param parameters:
:return:
"""
Rx, Ry, Rz, other = self.get_parameters(regex_... |
python | def get_adjacency_matrix(self, fmt='coo'):
r"""
Returns an adjacency matrix in the specified sparse format, with 1's
indicating the non-zero values.
Parameters
----------
fmt : string, optional
The sparse storage format to return. Options are:
*... |
python | def init_nn_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a list of (weights, biases) tuples, one for each layer."""
return [(rs.randn(insize, outsize) * scale, # weight matrix
rs.randn(outsize) * scale) # bias vector
for insize, outsize in zip(layer_sizes[:-1]... |
java | public boolean enlist(XAResource xaRes, int recoveryId)
throws RollbackException, IllegalStateException, SystemException
{
if (tc.isEntryEnabled())
Tr.entry(tc, "enlist", new Object[] { xaRes, recoveryId });
if (tx == null)
{
final String msg = "N... |
python | def prepare_package(err, path, expectation=0, for_appversions=None,
timeout=-1):
"""Prepares a file-based package for validation.
timeout is the number of seconds before validation is aborted.
If timeout is -1 then no timeout checking code will run.
"""
package = None
try:
... |
python | def tail(conn, stack_name, log_func=_tail_print, sleep_time=5,
include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_nam... |
java | public EmblReference copyEmblReference(EmblReference emblReference) {
EmblReference copy = new EmblReference();
copy.setReferenceAuthor(emblReference.getReferenceAuthor());
copy.setReferenceComment(emblReference.getReferenceComment());
copy.setReferenceCrossReference(emblReference.getReferenceCrossReference());... |
java | public static String decodeTPCI(int tpci, KNXAddress dst)
{
final int ctrl = tpci & 0xff;
if ((ctrl & 0xFC) == 0) {
if (dst == null)
return "T-broadcast/group/ind";
if (dst.getRawAddress() == 0)
return "T-broadcast";
if (dst instanceof GroupAddress)
return "T-group";
return "T-ind... |
java | @SuppressWarnings("rawtypes")
public static long importCSV(final File file, final Connection conn, final String insertSQL, final Map<String, ? extends Type> columnTypeMap)
throws UncheckedSQLException, UncheckedIOException {
return importCSV(file, 0, Long.MAX_VALUE, conn, insertSQL, 200, 0, c... |
python | def get_callable(subcommand):
# type: (config.RcliEntryPoint) -> Union[FunctionType, MethodType]
"""Return a callable object from the subcommand.
Args:
subcommand: A object loaded from an entry point. May be a module,
class, or function.
Returns:
The callable entry point fo... |
python | def get_container_host_config_kwargs(self, action, container_name, kwargs=None):
"""
Generates keyword arguments for the Docker client to set up the HostConfig or start a container.
:param action: Action configuration.
:type action: ActionConfig
:param container_name: Container ... |
java | protected void bulkInsertWithComparator() {
if (insertionBufferSize == 0) {
return;
}
int right = size + insertionBufferSize - 2;
int left = Math.max(size, right / 2);
while (insertionBufferSize > 0) {
--insertionBufferSize;
array[size] = inser... |
java | @Given("^I insert in keyspace '(.+?)' and table '(.+?)' with:$")
public void insertData(String keyspace, String table, DataTable datatable) {
try {
commonspec.getCassandraClient().useKeyspace(keyspace);
int attrLength = datatable.getPickleRows().get(0).getCells().size();
... |
java | public static String startNewPipeline(
JobSetting[] settings, Job<?> jobInstance, Object... params) {
UpdateSpec updateSpec = new UpdateSpec(null);
Job<?> rootJobInstance = jobInstance;
// If rootJobInstance has exceptionHandler it has to be wrapped to ensure that root job
// ends up in finalized ... |
java | public boolean update(File directory, String fileName, String fileExtension, int maxFiles) {
this.maxFiles = maxFiles;
boolean updateLocation = !directory.equals(this.directory) || !fileName.equals(this.fileName) || !fileExtension.equals(this.fileExtension);
if (updateLocation) {
th... |
java | protected <JavaTypeT> TypeCodec<JavaTypeT> codecFor(
DataType cqlType, GenericType<JavaTypeT> javaType, boolean isJavaCovariant) {
LOG.trace("[{}] Looking up codec for {} <-> {}", logPrefix, cqlType, javaType);
TypeCodec<?> primitiveCodec = primitiveCodecsByCode.get(cqlType.getProtocolCode());
if (pri... |
python | def fetch_routing_info(self, address):
""" Fetch raw routing info from a given router address.
:param address: router address
:return: list of routing records or
None if no connection could be established
:raise ServiceUnavailable: if the server does not support routing... |
python | def get_levels_of_description(self):
"""
Returns an array of all levels of description defined in this Archivist's Toolkit instance.
"""
if not hasattr(self, "levels_of_description"):
cursor = self.db.cursor()
levels = set()
cursor.execute("SELECT dist... |
python | def rectangle(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
... |
java | @Override
public void close() throws IOException
{
if(this.in != null && this.inStream != null){
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {
logger.logp(Level.FINE, CLASS_NAME,"close", "close called->"+this);
}
this.in.close();
... |
java | @PostConstruct
protected boolean connect() {
String path = ZkPathUtil.buildPath(zooConf.getNodePathPrefix());
try {
zkClient = doConnect();
LOG.info("Connect to zookeeper server successfully!");
List<String> children = zkClient.getChildren(path);
LOG.i... |
java | public static final boolean isSingletonInstantiated (@Nullable final IScope aScope,
@Nonnull final Class <? extends AbstractSingleton> aClass)
{
return getSingletonIfInstantiated (aScope, aClass) != null;
} |
python | def get_file_size(path):
"""The the size of a file in bytes.
Parameters
----------
path: str
The path of the file.
Returns
-------
int
The size of the file in bytes.
Raises
------
IOError
If the file does not exist.
OSError
If a file system ... |
java | public boolean viewExists(FacesContext context,
String viewId) {
boolean result = false;
ResourceHandler rh = context.getApplication().getResourceHandler();
result = null != rh.createViewResource(context, viewId);
return result;
} |
java | private double getElementRank(String symbol) {
for (int f = 0; f < rankedSymbols.length; f++) {
if (rankedSymbols[f].equals(symbol)) {
return symbolRankings[f];
}
}
IIsotope isotope = isotopeFac.getMajorIsotope(symbol);
if (isotope.getMassNumber() ... |
python | def execute(self, sql, args=None):
"""It is used for update, delete records.
:param sql string: the sql stamtement like 'select * from %s'
:param args list: Wen set None, will use dbi execute(sql), else
dbi execute(sql, args), the args keep the original rules, it shuld be tuple or ... |
java | public void setViewSetting(final String viewId, final String item, final String value) {
final ConfigItemMapEntrySet view = this.viewById.get(viewId);
if (view == null)
return;
view.set(item, value);
} |
java | protected void buildEnvVars(EnvVars env, MavenInstallation mi) throws IOException, InterruptedException {
if(mi!=null) {
// if somebody has use M2_HOME they will get a classloading error
// when M2_HOME points to a different version of Maven2 from
// MAVEN_HOME (as Maven 2 gi... |
java | @Override
public String getServersDirectory() {
if (WLP_OUTPUT_DIR != null) {
return WLP_OUTPUT_DIR + SLASH;
} else if (WLP_USER_DIR != null) {
return WLP_USER_DIR + SLASH + "servers" + SLASH;
} else {
return System.getProperty("user.dir") + SLASH + "usr" ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.