language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def branches(self):
"""Return a list of branches for given repository
:return: [str]
"""
# get all remote branches
refs = filter(lambda l: isinstance(l, git.RemoteReference), self.repo.references)
# filter out HEAD branch
refs = filter(lambda l: l.name != "origin/HEAD", refs)
# filter out all branches ... |
java | public void setCharacterSpacing(float charSpace) {
state.charSpace = charSpace;
content.append(charSpace).append(" Tc").append_i(separator);
} |
java | public void setFloat(int index, float value)
{
checkIndexLength(index, SizeOf.SIZE_OF_FLOAT);
unsafe.putFloat(base, address + index, value);
} |
python | def _make_stream_reader(cls, stream):
"""
Return a |StreamReader| instance with wrapping *stream* and having
"endian-ness" determined by the 'MM' or 'II' indicator in the TIFF
stream header.
"""
endian = cls._detect_endian(stream)
return StreamReader(stream, endia... |
java | private void analyze(final List<Metric> metrics, final long elapsed, final Date now, final Date date) {
long diff = 0;
boolean behind = false;
if (now.before(date)) {
behind = true;
diff = date.getTime() - now.getTime();
} else if (now.after(date)) {
... |
java | @BetaApi
public final Operation updateBackendBucket(
String backendBucket, BackendBucket backendBucketResource, List<String> fieldMask) {
UpdateBackendBucketHttpRequest request =
UpdateBackendBucketHttpRequest.newBuilder()
.setBackendBucket(backendBucket)
.setBackendBucketRe... |
java | private List<String> wordsForArguments(String command, List<String> words) {
int wordsUsedForCommandKey = command.split(" ").length;
List<String> args = words.subList(wordsUsedForCommandKey, words.size());
int last = args.size() - 1;
if (last >= 0 && "".equals(args.get(last))) {
args.remove(last);
}
retu... |
java | protected int process(char[] chars, int charIndex, StringBuilder buffer) {
char c = chars[charIndex];
if (c == '*') {
buffer.append(".*");
} else if (c == '?') {
buffer.append('.');
} else {
for (char esc : CHARS_TO_ESCAPE) {
if (c == esc) {
// escape
... |
java | public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption)
{ // Read a valid record
int iErrorCode = super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record
if (iErrorCode != DBConstants.NORMAL_RETURN)
return iErrorCode;
if... |
python | def log_to_logger(fn):
"""
Wrap a Bottle request so that a log line is emitted after it's handled.
"""
@wraps(fn)
def _log_to_logger(*args, **kwargs):
actual_response = fn(*args, **kwargs)
# modify this to log exactly what you need:
logger.info('%s %s %s %s' % (bottle.reques... |
java | public void marshall(TransactWriteItemsRequest transactWriteItemsRequest, ProtocolMarshaller protocolMarshaller) {
if (transactWriteItemsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(tran... |
python | def patched_contractfunction_estimateGas(self, transaction=None, block_identifier=None):
"""Temporary workaround until next web3.py release (5.X.X)"""
if transaction is None:
estimate_gas_transaction = {}
else:
estimate_gas_transaction = dict(**transaction)
if 'data' in estimate_gas_tra... |
java | protected void checkedUpdate (final String query, final int count)
throws PersistenceException
{
executeUpdate(new Operation<Object>() {
public Object invoke (Connection conn, DatabaseLiaison liaison)
throws SQLException, PersistenceException
{
... |
java | private Session loadSession(String id) throws Exception {
if (sessionDataStore == null) {
return null; // can't load it
}
try {
SessionData data = sessionDataStore.load(id);
if (data == null) { // session doesn't exist
return null;
... |
java | private OrQueryBuilder getOrFilterBuilder(Expression logicalExp, EntityMetadata m)
{
OrExpression orExp = (OrExpression) logicalExp;
Expression leftExpression = orExp.getLeftExpression();
Expression rightExpression = orExp.getRightExpression();
return new OrQueryBuilder(populateFilt... |
python | def _query(action=None,
routing_key=None,
args=None,
method='GET',
header_dict=None,
data=None):
'''
Make a web call to VictorOps
'''
api_key = __salt__['config.get']('victorops.api_key') or \
__salt__['config.get']('victorops:api_key')
... |
python | def interruptRead(self, endpoint, length, timeout=0):
"""
Synchronous interrupt write.
timeout: in milliseconds, how long to wait for data. Set to 0 to
disable.
See interruptWrite for other parameters description.
To avoid memory copies, use an object implementing the ... |
python | def convertafield(field_comm, field_val, field_iddname):
"""convert field based on field info in IDD"""
convinidd = ConvInIDD()
field_typ = field_comm.get('type', [None])[0]
conv = convinidd.conv_dict().get(field_typ, convinidd.no_type)
return conv(field_val, field_iddname) |
python | async def takelast(source, n):
"""Forward the last ``n`` elements from an asynchronous sequence.
If ``n`` is negative, it simply terminates after iterating the source.
Note: it is required to reach the end of the source before the first
element is generated.
"""
queue = collections.deque(maxle... |
java | public ArrayList getConsumerListForExpression(
String topicExpression,
boolean selector,
boolean isWildcarded)
{
if (tc.isEntryEnabled())
SibTr.entry(tc,
"getConsumerListForExpression",
new Object[]{topicExpression,
new Boolea... |
java | public static void scale(GVRMesh mesh, float x, float y, float z) {
final float [] vertices = mesh.getVertices();
final int vsize = vertices.length;
for (int i = 0; i < vsize; i += 3) {
vertices[i] *= x;
vertices[i + 1] *= y;
vertices[i + 2] *= z;
... |
python | def resources_with_possible_perms(
cls, instance, resource_ids=None, resource_types=None, db_session=None
):
"""
returns list of permissions and resources for this user
:param instance:
:param resource_ids: restricts the search to specific resources
:param resource_t... |
java | private static int finalizeConverter(
char c, String pattern, int i,
final StringBuffer currentLiteral, final ExtrasFormattingInfo formattingInfo,
final Map converterRegistry, final Map rules, final List patternConverters,
final List formattingInfos) {
StringBuffer convBuf = new StringBuffer();
... |
java | public static void calculateDsspSecondaryStructure(Structure bioJavaStruct) {
SecStrucCalc ssp = new SecStrucCalc();
try{
ssp.calculate(bioJavaStruct, true);
}
catch(StructureException e) {
LOGGER.warn("Could not calculate secondary structure (error {}). Will try to get a DSSP file from the RCSB web serv... |
java | public static <D extends Document<?>> Observable<D> read(final ClusterFacade core, final String id,
final ReplicaMode type, final String bucket,
final Map<Class<? extends Document>, Transcoder<? extends Document, ?>> transcoders, final Class<D> target,
final CouchbaseEnvironment environment, fin... |
python | def _read_json_file(self, json_file):
""" Helper function to read JSON file as OrderedDict """
self.log.debug("Reading '%s' JSON file..." % json_file)
with open(json_file, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict) |
python | def get_port_monitor(self):
"""
Gets the port monitor configuration of a logical interconnect.
Returns:
dict: The Logical Interconnect.
"""
uri = "{}{}".format(self.data["uri"], self.PORT_MONITOR_PATH)
return self._helper.do_get(uri) |
java | public WhereCondition Col(String columnName) {
mSgSQL.append(columnName);
checkTokenOrderIsCorrect(ESqlToken.COLUMN);
return WhereCondition.this;
} |
java | public void afterStatementCreate(java.sql.Statement stmt) throws PlatformException
{
super.afterStatementCreate(stmt);
// Check for OracleStatement-specific row prefetching support
final Method methodSetRowPrefetch;
methodSetRowPrefetch = ClassHelper.getMethod(stmt, "setRowPre... |
java | public static ConverterInitializer newInstance(State state, WorkUnitStream workUnits) {
int branches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1);
if (branches == 1) {
return newInstance(state, workUnits, branches, 0);
}
List<ConverterInitializer> cis = Lists.newArrayList();
f... |
python | def search(self, search_phrase, limit=None):
""" Finds partitions by search phrase.
Args:
search_phrase (str or unicode):
limit (int, optional): how many results to generate. None means without limit.
Generates:
PartitionSearchResult instances.
"""
... |
java | private void handleFrameAvailable(SurfaceTexture surfaceTexture) {
if (TRACE) Trace.beginSection("handleFrameAvail");
synchronized (mReadyForFrameFence) {
if (!mReadyForFrames) {
if (VERBOSE) Log.i(TAG, "Ignoring available frame, not ready");
return;
... |
java | public static <T> ListRandomizer<T> aNewListRandomizer(final Randomizer<T> elementRandomizer, final int nbElements) {
return new ListRandomizer<>(elementRandomizer, nbElements);
} |
java | public void setChannel(final int channelConfig){
if(channelConfig != AudioFormat.CHANNEL_IN_MONO && channelConfig !=AudioFormat.CHANNEL_IN_STEREO && channelConfig != AudioFormat.CHANNEL_IN_DEFAULT){
throw new IllegalArgumentException("Invalid channel given.");
}
else if (currentAudio... |
python | def feedkeys(self, keys, options='', escape_csi=True):
"""Push `keys` to Nvim user input buffer.
Options can be a string with the following character flags:
- 'm': Remap keys. This is default.
- 'n': Do not remap keys.
- 't': Handle keys as if typed; otherwise they are handled a... |
java | public void updateCurrentUsername(String newUsername) {
final String originalThreadName = originalThreadNameLocal.get();
if (originalThreadName != null && newUsername != null) {
final Thread currentThread = Thread.currentThread();
final String threadName = getThreadName(originalT... |
python | def dom_to_dict(root_node):
""" Serializes the given node to the dictionary
Serializes the given node to the documented dictionary format.
:param root_node: Node to serialize
:returns: The dictionary
:rtype: dict
"""
# Remove namespaces from tagname
tag = root_node.tagName
if "... |
java | @Override
protected void writeTo(JournalFile journalFile) throws JournalException
{
super.writeTo(journalFile);
journalFile.writeInt(operationsCount);
} |
java | public static StringBuffer getSqlData(final String[] columns, final String[] columnTypes,
final String[] columnTypesEdit, final Map<Integer, Integer> lineOrder,
final List<String[]> lines, final boolean withEndSemicolon)
{
final StringBuffer sb = new StringBuffer();
int autoincrement = 0;
for (final Iterator... |
java | @Override
public void propagate(int evtmask) throws ContradictionException {
// trivial case
k.updateLowerBound(0, this);
if (g.getPotentialNodes().size() == 0) {
k.instantiateTo(0, this);
return;
}
if (k.getUB() == 0) {
for (int i : g.getPotentialNodes()) {
g.removeNode(i, this);
}
return... |
python | def _fill_parameters(self):
"""
Fill in the _parameters dict from the properties file.
Args:
None
Returns:
True
Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist.
"""
... |
java | public <B> CompletableFutureT<W,B> flatMapT(final Function<? super T, CompletableFutureT<W,B>> f) {
return of(run.map(future -> future.thenCompose(a -> f.apply(a).run.stream()
.toList()
... |
python | def recalculate_stock_values_into_base(self):
""" Loads the exchange rates and recalculates stock holding values into
base currency """
from .currency import CurrencyConverter
conv = CurrencyConverter()
cash = self.model.get_cash_asset_class()
for stock in self.model.s... |
python | def _execute_autohash_on_class(object_type, # type: Type[T]
include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
only_constructor_args=False,... |
java | public void updateGalleryData(
CmsGallerySearchBean searchObj,
CmsGalleryDataBean dialogBean,
CmsGalleryController controller) {
if ((m_galleryDialog.getGalleriesTab() != null) && (dialogBean.getGalleries() != null)) {
Collections.sort(dialogBean.getGalleries(), new CmsCompa... |
java | protected List<Integer> cancelAllActiveOperations() {
final List<Integer> operations = new ArrayList<Integer>();
for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {
activeOperation.asyncCancel(false);
operations.add(activeOperation.getOperationId());
... |
java | public static UnsafeMappedBuffer allocate(File file, FileChannel.MapMode mode, long initialCapacity, long maxCapacity) {
if (file == null)
throw new NullPointerException("file cannot be null");
if (mode == null)
mode = MappedMemoryAllocator.DEFAULT_MAP_MODE;
if (initialCapacity > maxCapacity)
... |
java | public static String validateConstraintName(@Nullable String constraintName) {
requireNonNull(constraintName, "Constraint name cannot be null");
checkDbIdentifier(constraintName, "Constraint name", CONSTRAINT_NAME_MAX_SIZE);
return constraintName;
} |
java | public void setValue(Token[] tokens) {
if (type == null) {
type = ItemType.SINGLE;
}
if (type != ItemType.SINGLE) {
throw new IllegalArgumentException("The type of this item must be 'single'");
}
this.tokens = tokens;
} |
java | @Override
public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
for (ExchangeRateProvider prov : this.providers) {
try {
if (prov.isAvailable(conversionQuery)) {
ExchangeRate rate = prov.getExchangeRate(conversionQuery);
if... |
java | public static <T extends AbstractJaxb> void removeDescendants(T target,
Class<T> tagType) {
execute(target, tagType, null);
} |
java | public final AnalyzeSyntaxResponse analyzeSyntax(Document document, EncodingType encodingType) {
AnalyzeSyntaxRequest request =
AnalyzeSyntaxRequest.newBuilder()
.setDocument(document)
.setEncodingType(encodingType)
.build();
return analyzeSyntax(request);
} |
java | public void useNamespace(SerializerContext serializerContext, ElementDescriptor<?> elementDescriptor)
{
useNamespace(serializerContext, elementDescriptor.qualifiedName.namespace);
} |
python | def _do_stale_devices_callback(self, msg):
"""Call registered callback functions."""
for callback in self._stale_devices_callbacks:
_LOGGER.debug('Stale Devices callback %s', callback)
self._event_loop.call_soon(callback, msg) |
java | public void setResourceArns(java.util.Collection<String> resourceArns) {
if (resourceArns == null) {
this.resourceArns = null;
return;
}
this.resourceArns = new java.util.ArrayList<String>(resourceArns);
} |
java | @Override
public Middleware init(@NotNull final Yoke yoke, @NotNull final String mount) {
try {
super.init(yoke, mount);
if (path == null) {
icon = new Icon(Utils.readResourceToBuffer(getClass(), "favicon.ico"));
} else {
icon = new Icon(fi... |
java | @Override
public com.liferay.commerce.model.CommerceWarehouseItem deleteCommerceWarehouseItem(
long commerceWarehouseItemId)
throws com.liferay.portal.kernel.exception.PortalException {
return _commerceWarehouseItemLocalService.deleteCommerceWarehouseItem(commerceWarehouseItemId);
} |
java | public void setSource(String v) {
if (Keyword_Type.featOkTst && ((Keyword_Type)jcasType).casFeat_source == null)
jcasType.jcas.throwFeatMissing("source", "de.julielab.jules.types.Keyword");
jcasType.ll_cas.ll_setStringValue(addr, ((Keyword_Type)jcasType).casFeatCode_source, v);} |
python | def svg_data_uri(self, xmldecl=False, encode_minimal=False,
omit_charset=False, nl=False, **kw):
"""\
Converts the QR Code into a SVG data URI.
The XML declaration is omitted by default (set ``xmldecl`` to ``True``
to enable it), further the newline is omitted by de... |
python | def buttons_pressed(self):
"""
Returns list of names of pressed buttons.
"""
for b in self._buffer_cache:
fcntl.ioctl(self._button_file(b), self.EVIOCGKEY, self._buffer_cache[b])
pressed = []
for k, v in self._buttons.items():
buf = self._buffer_c... |
java | public void activityEnded(ActivityHandle activityHandle) {
if (tracer.isFineEnabled()) {
tracer.fine("activityEnded( handle = " + activityHandle + ")");
}
activities.remove(activityHandle);
} |
java | public static tmsessionaction[] get_filtered(nitro_service service, String filter) throws Exception{
tmsessionaction obj = new tmsessionaction();
options option = new options();
option.set_filter(filter);
tmsessionaction[] response = (tmsessionaction[]) obj.getfiltered(service, option);
return response;
} |
java | private Set<VarBindingDef> getPropertyProviders( Set<String> properties)
{
Set<VarBindingDef> bindings = new HashSet<VarBindingDef>();
for( String property : properties)
{
bindings.addAll( propertyProviders_.get( property));
}
return bindings;
} |
java | public void marshall(ContainerOverride containerOverride, ProtocolMarshaller protocolMarshaller) {
if (containerOverride == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(containerOverride.getName(),... |
java | public static final void registerNodeDataInstance(
Class<? extends NodeData> clazz) {
try {
@SuppressWarnings("unused")
NodeData test = clazz.newInstance();
ndImpl = clazz;
} catch (InstantiationException e) {
throw new RuntimeException("NodeData implemenation ("
+ clazz.getName() + ") doesn't p... |
python | def butter_filter(cutoff, fs, order=5, btype='low'):
'''Create a digital butter fileter with cutoff frequency in Hz
Args
----
cutoff: float
Cutoff frequency where filter should separate signals
fs: float
sampling frequency
btype: str
Type of filter type to create. 'low' ... |
python | def deserialize(self, *args, **kwargs):
"""Deserialize Resource Map XML doc.
The source is specified using one of source, location, file or data.
Args:
source: InputSource, file-like object, or string
In the case of a string the string is the location of the source.
... |
java | public void parseBatchResult(ClientResponse response) throws IOException,
ServiceException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStream inputStream = response.getEntityInputStream();
ReaderWriter.writeTo(inputStream, byteArrayOutputStream);... |
python | def close(self):
""" Deletes all static mask objects. """
for key in self.masklist.keys():
self.masklist[key] = None
self.masklist = {} |
python | def _is_missing_tags_strict(self):
"""
Return whether missing_tags is set to strict.
"""
val = self.missing_tags
if val == MissingTags.strict:
return True
elif val == MissingTags.ignore:
return False
raise Exception("Unsupported 'missing... |
java | public static void printTargetInformationBlockFromType2Message(
byte[] msg, Integer msgFlags, PrintWriter out)
throws UnsupportedEncodingException {
int flags = msgFlags == null ? extractFlagsFromType2Message(msg)
: msgFlags;
byte[] infoBlock = extractTargetInfoF... |
java | private ComparisonState compareAttributes(Attr control,
XPathContext controlContext,
Attr test,
XPathContext testContext) {
return compareAttributeExplicitness(control, contr... |
java | AbstractPlanNode applyOptimization(OrderByPlanNode orderbyNode) {
// Find all child RECEIVE nodes. We are not interested in the MERGERECEIVE nodes there
// because they could only come from subqueries.
List<AbstractPlanNode> receives = orderbyNode.findAllNodesOfType(PlanNodeType.RECEIVE);
... |
java | public DescribeTransitGatewaysRequest withTransitGatewayIds(String... transitGatewayIds) {
if (this.transitGatewayIds == null) {
setTransitGatewayIds(new com.amazonaws.internal.SdkInternalList<String>(transitGatewayIds.length));
}
for (String ele : transitGatewayIds) {
th... |
java | @Override
public void onSelection(SelectionEvent<MaterialStep> event) {
if (stepSkippingAllowed) {
if (event.getSelectedItem().getState() == State.SUCCESS) {
goToStep(event.getSelectedItem());
}
}
} |
python | def remove_stage(self, stage, edit_version=None, **kwargs):
'''
:param stage: A number for the stage index (for the nth stage, starting from 0), or a string of the stage index, name, or ID
:type stage: int or string
:param edit_version: if provided, the edit version of the workflow that ... |
python | def status(id):
"""
View status of all jobs in a project.
The command also accepts a specific job name.
"""
if id:
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
print_e... |
java | public void setSortedColumn(String sortedColumn) throws CmsIllegalArgumentException {
// check if the parameter is valid
if ((getMetadata().getColumnDefinition(sortedColumn) == null)
|| !getMetadata().getColumnDefinition(sortedColumn).isSorteable()) {
return;
}
/... |
python | def parse(self, rrstr):
# type: (bytes) -> None
'''
Parse a Rock Ridge Time Stamp record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.P... |
java | public ResultList<MovieBasic> getKeywordMovies(String keywordId, String language, Integer page) throws MovieDbException {
return tmdbKeywords.getKeywordMovies(keywordId, language, page);
} |
java | @Override
protected void configureFindbugsEngine() {
if (not != null) {
addArg("-not");
}
addBoolOption("-notAProblem", notAProblem);
addBoolOption("-withSource", withSource);
addOption("-exclude", exclude);
addOption("-include", include);
addOptio... |
java | public static void splitFile(File file, long[] splitPoints, String storageFolder) throws IOException {
splitPoints = ArrayUtils.concatArrays(new long[]{0}, splitPoints, new long[]{file.length()});
String[] fileName = file.getName().split("\\.", 2);
storageFolder += ValueConsts.SEPARATOR;
... |
python | def sheetpack(fn, sheet=0, header=True, startcell=None, stopcell=None,
usecols=None):
"""Return a ChannelPack instance loaded with data from the spread
sheet file fn, (xls, xlsx).
fn: str
The file to read from.
sheet: int or str
If int, it is the index for the sheet 0-bas... |
python | def apply_security_groups(self, security_groups):
"""
Applies security groups to the load balancer.
Applying security groups that are already registered with the
Load Balancer has no effect.
:type security_groups: string or List of strings
:param security_groups: The na... |
java | public static <T extends Model> ManyQuery<T> all(Class<T> clazz) {
return many(clazz, "SELECT * FROM " + Utils.getTableName(clazz));
} |
java | @Override
public AnnotationDesc[] annotations() {
List<? extends TypeCompound> tas = type.getAnnotationMirrors();
if (tas == null ||
tas.isEmpty()) {
return new AnnotationDesc[0];
}
AnnotationDesc res[] = new AnnotationDesc[tas.length()];
int i = 0... |
java | static void close(boolean delete) {
if (openedFile != null) {
out.close();
out = System.err;
if (delete) {
openedFile.delete();
}
}
} |
java | public static int inc(int value, int r, int g, int b)
{
final int alpha = value >> Constant.BYTE_4 & 0xFF;
if (alpha == 0)
{
return 0;
}
final int red = value >> Constant.BYTE_3 & 0xFF;
final int green = value >> Constant.BYTE_2 & 0xFF;
fi... |
java | @Override
public GetConfigurationSetResult getConfigurationSet(GetConfigurationSetRequest request) {
request = beforeClientExecution(request);
return executeGetConfigurationSet(request);
} |
java | @Nonnull
public static FieldValue arrayUnion(@Nonnull Object... elements) {
Preconditions.checkArgument(elements.length > 0, "arrayUnion() expects at least 1 element");
return new ArrayUnionFieldValue(Arrays.asList(elements));
} |
java | public static String unwrapHtmlTag(String content, String... tagNames) {
return removeHtmlTag(content, false, tagNames);
} |
java | private static LookupResult tryAsScript(String name, CompilationUnit compilationUnit, ClassNode oldClass) {
LookupResult lr = null;
if (oldClass!=null) {
lr = new LookupResult(null, oldClass);
}
if (name.startsWith("java.")) return lr;
//TODO: don't ignore in... |
python | def _get_voronoi_centroid_array(lsm_lat_array, lsm_lon_array, extent):
"""
This function generates a voronoi centroid point
list from arrays of latitude and longitude
"""
YMin = extent[2]
YMax = extent[3]
XMin = extent[0]
XMax = extent[1]
ptList = []
if (lsm_lat_array.ndim == 2)... |
python | def full_split(text, regex):
"""
Split the text by the regex, keeping all parts.
The parts should re-join back into the original text.
>>> list(full_split('word', re.compile('&.*?')))
['word']
"""
while text:
m = regex.search(text)
if not m:
yield text
... |
java | public static UserGroupInformation getUGI(Configuration conf)
throws LoginException {
UserGroupInformation ugi = null;
if (conf.getBoolean(UGI_SOURCE, true)) {
// get the ugi from configuration
ugi = UnixUserGroupInformation.readFromConf(conf,
UnixUserGroupInformation.UGI_PROPERTY_NAME);
... |
python | def get_protocol(self, protocol):
"""Returns the firstly found protocol that matches to the
specified protocol.
"""
result = self.get_protocols(protocol)
if len(result) > 0:
return result[0]
return None |
python | def apply_config(self, config):
"""
Applies config
"""
self.hash_name = config['hash_name']
self.dim = config['dim']
self.projection_count = config['projection_count']
self.normals = config['normals']
self.tree_root = config['tree_root']
self.minim... |
python | def slistFloat(slist):
""" Converts signed list to float. """
values = [v / 60**(i) for (i,v) in enumerate(slist[1:])]
value = sum(values)
return -value if slist[0] == '-' else value |
java | public int update(User registrar) throws IdentityException, InvalidArgumentException {
if (this.deleted) {
throw new IdentityException("Identity has been deleted");
}
if (registrar == null) {
throw new InvalidArgumentException("Registrar should be a valid member");
... |
python | def get_base_url(url, include_path=False):
""" :return: the url without the query or fragment segments """
if not url:
return None
parts = _urlsplit(url)
base_url = _urlunsplit((
parts.scheme, parts.netloc, (parts.path if include_path else ''), None, None
))
return base_url if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.