language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void marshall(ListRecordHistorySearchFilter listRecordHistorySearchFilter, ProtocolMarshaller protocolMarshaller) {
if (listRecordHistorySearchFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.m... |
python | def representative_sample(X, num_samples, save=False):
"""Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set
"""
X = X.values if hasattr(X, 'values') else np.array(X)
N, M = X.shape
rownums = np.arange(N)
np.random.shuffle(rownums)
idx = Annoy... |
python | def get_baudrate_message(baudrate):
"""
Converts a given baud rate value for GW-001/GW-002 to the appropriate message string.
:param Baudrate baudrate:
Bus Timing Registers, BTR0 in high order byte and BTR1 in low order byte
(see enum :class:`Baudrate`)
:return: ... |
python | def substitution_rate(Nref, Nsubstitutions, eps=numpy.spacing(1)):
"""Substitution rate
Parameters
----------
Nref : int >=0
Number of entries in the reference.
Nsubstitutions : int >=0
Number of substitutions.
eps : float
eps.
Default value numpy.spacing(1)
... |
java | @SuppressWarnings("unchecked")
static <T extends SAMLObject> MessageContext<T> toSamlObject(
AggregatedHttpMessage msg, String name,
Map<String, SamlIdentityProviderConfig> idpConfigs,
@Nullable SamlIdentityProviderConfig defaultIdpConfig) {
requireNonNull(msg, "msg");
... |
python | def OnDoubleClick(self, event):
"""Double click on a given square in the map"""
node = HotMapNavigator.findNodeAtPosition(self.hot_map, event.GetPosition())
if node:
wx.PostEvent( self, SquareActivationEvent( node=node, point=event.GetPosition(), map=self ) ) |
java | public static String jsonObjectToReturnString(JSONObject jsonObj)
{
String strReturn = jsonObj.toString();
if (strReturn != null)
if (!strReturn.startsWith("("))
strReturn = "(" + strReturn + ")";
return strReturn;
} |
python | def get_crimes_location(self, location_id, date=None):
"""
Get crimes at a particular snap-point location. Uses the
crimes-at-location_ API call.
.. _crimes-at-location:
https://data.police.uk/docs/method/crimes-at-location/
:rtype: list
:param int location_... |
java | @Override
public Future<M> getDataFuture() {
try {
return FutureProcessor.completedFuture(getData());
} catch (NotAvailableException ex) {
CompletableFuture future = new CompletableFuture();
future.completeExceptionally(ex);
return future;
}
... |
python | def Rsync(url, tgt_name, tgt_root=None):
"""
RSync a folder.
Args:
url (str): The url of the SOURCE location.
fname (str): The name of the TARGET.
to (str): Path of the target location.
Defaults to ``CFG["tmpdir"]``.
"""
if tgt_root is None:
tgt_root = st... |
python | def trigger_actions(self, subsystem):
"""
Refresh all modules which subscribed to the given subsystem.
"""
for py3_module, trigger_action in self.udev_consumers[subsystem]:
if trigger_action in ON_TRIGGER_ACTIONS:
self.py3_wrapper.log(
"%s ... |
java | public static Date getDateParameter (
HttpServletRequest req, String name, String invalidDataMessage)
throws DataValidationException
{
String value = getParameter(req, name, false);
if (StringUtil.isBlank(value) ||
DATE_TEMPLATE.equalsIgnoreCase(value)) {
retu... |
java | MolgenisValidationException translateNotNullViolation(PSQLException pSqlException) {
ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage();
String tableName = serverErrorMessage.getTable();
String message = serverErrorMessage.getMessage();
Matcher matcher =
Pattern.compil... |
python | def tag(self, name, action='ADD', params=None):
"""
Adds a tag to a Indicator/Group/Victim/Security Label
Args:
params:
action:
name: The name of the tag
"""
if not name:
self._tcex.handle_error(925, ['name', 'tag', 'name', '... |
python | def size(col):
"""
Collection function: returns the length of the array or map stored in the column.
:param col: name of column or expression
>>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data'])
>>> df.select(size(df.data)).collect()
[Row(size(data)=3), Row(size(data)=1), Row(... |
python | def delete_file(self, path):
"""Delete the file or directory at path.
"""
self.log.debug("S3contents.GenericManager: delete_file '%s'", path)
if self.file_exists(path) or self.dir_exists(path):
self.fs.rm(path)
else:
self.no_such_entity(path) |
java | public BatchWriteItemResponse batchWriteItem(BatchWriteItemRequest request)
throws BceClientException, BceServiceException {
checkNotNull(request, "request should not be null.");
InternalRequest httpRequest = createRequestUnderInstance(HttpMethodName.POST,
MolaDbConstants.URI... |
python | def request(self, method, url, bearer_auth=True, **req_kwargs):
'''
A loose wrapper around Requests' :class:`~requests.sessions.Session`
which injects OAuth 2.0 parameters.
:param method: A string representation of the HTTP method to be used.
:type method: str
:param url... |
python | def _compare_title(self, other):
"""Return False if titles have different gender associations"""
# If title is omitted, assume a match
if not self.title or not other.title:
return True
titles = set(self.title_list + other.title_list)
return not (titles & MALE_TITLE... |
java | public List<JCCompilationUnit> enterTrees(List<JCCompilationUnit> roots) {
//enter symbols for all files
if (!taskListener.isEmpty()) {
for (JCCompilationUnit unit: roots) {
TaskEvent e = new TaskEvent(TaskEvent.Kind.ENTER, unit);
taskListener.started(e);
... |
python | def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for ca... |
java | public ServerSideEncryptionByDefault withSSEAlgorithm(SSEAlgorithm sseAlgorithm) {
setSSEAlgorithm(sseAlgorithm == null ? null : sseAlgorithm.toString());
return this;
} |
python | def unpack(self, data, namedstruct):
'''
Unpack the struct from specified bytes. If the struct is sub-classed, definitions from the sub type
is not unpacked.
:param data: bytes of the struct, including fields of sub type and "extra" data.
:param namedstruct: a N... |
python | def get_raid_fgi_status(report):
"""Gather fgi(foreground initialization) information of raid configuration
This function returns a fgi status which contains activity status
and its values from the report.
:param report: SCCI report information
:returns: dict of fgi status of logical_drives, such ... |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
protected void ensureLocalSpaceDefinition(SpaceID id, Object[] initializationParameters) {
synchronized (getSpaceRepositoryMutex()) {
if (!this.spaces.containsKey(id)) {
createSpaceInstance((Class) id.getSpaceSpecification(), id, false, initializationParameters);... |
java | public void mainFindBestValEntropy(Node root) {
if (root != null) {
DoubleVector parentClassCL = new DoubleVector();
DoubleVector classCountL = root.classCountsLeft; //class count left
DoubleVector classCountR = root.classCountsRight; //class count left
double numInst = root.classCountsLeft.sumOfValues() ... |
java | public static long searchMin(long[] longArray) {
if(longArray.length == 0) {
throw new IllegalArgumentException("The array you provided does not have any elements");
}
long min = longArray[0];
for(int i = 1; i < longArray.length; i++) {
if(longArray[i] < min) {
... |
python | def get_arrow(self, likes):
"""
Curses does define constants for symbols (e.g. curses.ACS_BULLET).
However, they rely on using the curses.addch() function, which has been
found to be buggy and a general PITA to work with. By defining them as
unicode points they can be added via t... |
python | def get_percent(self):
"""get_percent()
Returns the weighted percentage of the score from min-max values"""
if not (self.votes and self.score):
return 0
return 100 * (self.get_rating() / self.field.range) |
java | protected void validateSingle(
CmsUUID structureId,
Map<String, String> sitePaths,
String newSitePath,
final AsyncCallback<String> errorCallback) {
Map<String, String> newMap = new HashMap<String, String>(sitePaths);
newMap.put("NEW", newSitePath); //$NON-NLS-1$
... |
java | @Override
public void open(AudioFormat format, int bufferSize) throws LineUnavailableException {
opening();
sourceDataLine.open(format, bufferSize);
} |
python | def economic_qs_linear(G):
r"""Economic eigen decomposition for symmetric matrices ``dot(G, G.T)``.
It is theoretically equivalent to ``economic_qs(dot(G, G.T))``.
Refer to :func:`numpy_sugar.economic_qs` for further information.
Args:
G (array_like): Matrix.
Returns:
tuple: ``((Q... |
java | public <T> Subscription bind(
Property<T> target,
ObservableValue<? extends T> source) {
return bind(() -> {
target.bind(source);
return target::unbind;
});
} |
java | public final void sendBroadCastVariables(Configuration config) throws IOException {
try {
int broadcastCount = config.getInteger(PLANBINDER_CONFIG_BCVAR_COUNT, 0);
String[] names = new String[broadcastCount];
for (int x = 0; x < names.length; x++) {
names[x] = config.getString(PLANBINDER_CONFIG_BCVAR_N... |
python | def uninstall(cls):
"""Remove the package manager from the system."""
if os.path.exists(cls.home):
shutil.rmtree(cls.home) |
java | protected String[] getRowClasses(PanelGrid grid) {
String rowClasses = grid.getRowClasses();
if (null == rowClasses || rowClasses.trim().length()==0)
return null;
String[] rows = rowClasses.split(",");
return rows;
} |
python | def distinct_on(self, value):
"""Set fields used to group query results.
:type value: str or sequence of strings
:param value: Each value is a string giving the name of a
property to use to group results together.
"""
if isinstance(value, str):
... |
java | public <S> S queryOne(Class<S> type, String sql, Object[] params) {
Connection conn = getConn();
try {
Query query = conn.createQuery(sql)
.withParams(params)
.setAutoDeriveColumnNames(true)
.throwOnMappingFailure(false);
... |
java | private DateTime providedOrDefaultFromValue(DateTime from, DateTime to,
AggregateCounterResolution resolution) {
if (from != null) {
return from;
}
switch (resolution) {
case minute:
return to.minusMinutes(59);
case hour:
return to.minusHours(23);
case day:
return to.minusDays(6);
case mont... |
java | public Location lastKnownLocation() {
final HandlingEvent lastEvent = this.lnkDeliveryHistory.lastEvent();
if (lastEvent != null) {
return lastEvent.getLocation();
} else {
return null;
}
} |
python | def phenotypeAssociationSetsGenerator(self, request):
"""
Returns a generator over the (phenotypeAssociationSet, nextPageToken)
pairs defined by the specified request
"""
dataset = self.getDataRepository().getDataset(request.dataset_id)
return self._topLevelObjectGenerato... |
python | async def play(self, ctx, *, query):
"""Plays a file from the local filesystem"""
source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query))
ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('Now playing: {}'.format(que... |
python | def convert(self, value, view):
"""Ensure that the value is among the choices (and remap if the
choices are a mapping).
"""
if (SUPPORTS_ENUM and isinstance(self.choices, type)
and issubclass(self.choices, enum.Enum)):
try:
return self.choices(... |
python | def generic_ref_formatter(view, context, model, name, lazy=False):
"""
For GenericReferenceField and LazyGenericReferenceField
See Also
--------
diff_formatter
"""
try:
if lazy:
rel_model = getattr(model, name).fetch()
else:
rel_model = getattr(model,... |
python | def _publish_match(self, publish, names=False, name_only=False):
"""
Check if publish name matches list of names or regex patterns
"""
if names:
for name in names:
if not name_only and isinstance(name, re._pattern_type):
if re.match(name, p... |
python | def _eval_model(self):
"""
Convenience method for evaluating the model with the current parameters
:return: named tuple with results
"""
arguments = self._x_grid.copy()
arguments.update({param: param.value for param in self.model.params})
return self.model(**key2... |
java | public final int getPersistableInMemorySizeApproximation(TransactionState tranState)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getPersistableInMemorySizeApproximation", tranState);
int size;
if ((tranState == TransactionState.STATE_COMMITTED)... |
python | def config_id_exists(search_id):
"""
Test if a build configuration matching search_id exists
:param search_id: id to test for
:return: True if a build configuration with search_id exists, False otherwise
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_specific', id=search_id)
... |
java | @Override
@FFDCIgnore(SecurityException.class)
public ExtendedConfiguration[] listConfigurations(String filterString) throws InvalidSyntaxException {
if (filterString == null)
filterString = "(" + Constants.SERVICE_PID + "=*)"; //$NON-NLS-1$ //$NON-NLS-2$
try {
this.caFa... |
python | def deserialize(self, value, **kwargs):
"""De-serialize the property value from JSON
If no deserializer has been registered, this converts the value
to the wrapper class with given dtype.
"""
kwargs.update({'trusted': kwargs.get('trusted', False)})
if self.deserializer i... |
python | def ask(self, question, default=False):
""" Ask a y/n question to the user.
"""
choices = '[%s/%s]' % ('Y' if default else 'y', 'n' if default else 'N')
while True:
response = raw_input('%s %s' % (question, choices)).strip()
if not response:
return... |
java | public <T extends Type> T resolve(String typeName, Class<T> clazz) {
Type instance = resolve(typeName);
if (instance == null) {
return null;
}
if (clazz.isAssignableFrom(instance.getClass())) {
return clazz.cast(instance);
} else {
throw new Pa... |
java | private Map<String, RouteEntry> getAcceptedMimeTypes(List<RouteEntry> routes) {
Map<String, RouteEntry> acceptedTypes = new HashMap<>();
for (RouteEntry routeEntry : routes) {
if (!acceptedTypes.containsKey(routeEntry.acceptedType)) {
acceptedTypes.put(routeEntry.acceptedTyp... |
python | def load_config(files=None, root_path=None, local_path=None):
"""Load the configuration from specified files."""
config = cfg.ConfigOpts()
config.register_opts([
cfg.Opt('root_path', default=root_path),
cfg.Opt('local_path', default=local_path),
])
# XXX register actual config group... |
python | def _get_and_assert_slice_param(url_dict, param_name, default_int):
"""Return ``param_str`` converted to an int.
If str cannot be converted to int or int is not zero or positive, raise
InvalidRequest.
"""
param_str = url_dict['query'].get(param_name, default_int)
try:
n = int(param_str... |
python | def _load_image_set_index(self, shuffle):
"""
get total number of images, init indices
Parameters
----------
shuffle : bool
whether to shuffle the initial indices
"""
self.num_images = 0
for db in self.imdbs:
self.num_images += db.... |
python | def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
... |
java | protected void handleVersion(
EntityDesc entityDesc, EntityPropertyDesc propertyDesc, ColumnMeta columnMeta) {
if (isVersionAnnotatable(propertyDesc.getPropertyClassName())) {
if (versionColumnNamePattern.matcher(columnMeta.getName()).matches()) {
propertyDesc.setVersion(true);
}
}
} |
java | public Map<String, Monomer> loadMonomerStore(Map<String, Attachment> attachmentDB)
throws IOException, URISyntaxException, EncoderException {
Map<String, Monomer> monomers = new TreeMap<String, Monomer>(String.CASE_INSENSITIVE_ORDER);
CloseableHttpClient httpclient = HttpClients.createDefault();
// There... |
python | def print_summary(self, heading: str) -> None:
"""Print the summary of a graph.
:param str heading: Title of the graph.
"""
logger.info(heading)
logger.info("Number of nodes: {}".format(len(self.graph.vs)))
logger.info("Number of edges: {}".format(len(self.graph.es))) |
python | def write_workflow(self, request, opts, cwd, wftype='cwl'):
"""Writes a cwl, wdl, or python file as appropriate from the request dictionary."""
workflow_url = request.get("workflow_url")
# link the cwl and json into the cwd
if workflow_url.startswith('file://'):
os.link(wor... |
python | def set_(name, target, module_parameter=None, action_parameter=None):
'''
Verify that the given module is set to the given target
name
The name of the module
target
The target to be set for this module
module_parameter
additional params passed to the defined module
ac... |
java | public void setIdleMax(int max)
{
if (max == _idleMax) {
// avoid update() overhead if unchanged
return;
}
if (max <= 0) {
max = DEFAULT_IDLE_MAX;
}
if (_threadMax < max)
throw new ConfigException(L.l("IdleMax ({0}) must be less than ThreadMax ({1})", max, _threadM... |
python | def load(path, filetype=None, as_df=False, retries=None,
_oid=None, quiet=False, **kwargs):
'''Load multiple files from various file types automatically.
Supports glob paths, eg::
path = 'data/*.csv'
Filetypes are autodetected by common extension strings.
Currently supports loadings... |
python | def split_df(df):
'''
Split a dataframe in two dataframes: one with the history of agents,
and one with the environment history
'''
envmask = (df['agent_id'] == 'env')
n_env = envmask.sum()
if n_env == len(df):
return df, None
elif n_env == 0:
return None, df
agents, ... |
python | def replace(
self,
accountID,
orderSpecifier,
**kwargs
):
"""
Replace an Order in an Account by simultaneously cancelling it and
creating a replacement Order
Args:
accountID:
Account Identifier
orderSpecifier:
... |
java | public boolean removeRunCompression() {
boolean answer = false;
for (int i = 0; i < this.highLowContainer.size(); i++) {
Container c = this.highLowContainer.getContainerAtIndex(i);
if (c instanceof RunContainer) {
Container newc = ((RunContainer) c).toBitmapOrArrayContainer(c.getCardinality(... |
java | public String get(String command) throws PHPException {
try {
String s = php.execGet(command);
flushContent();
return s;
} catch (IOException e) {
LOGGER.error("IO Error with PhpDriver : " + e.toString());
throw new IOErrorException(flushContentAndDropIOException());
}
} |
python | def get_report(self):
"""
Return a string containing a report of the result.
This can used to print or save to a text file.
Returns:
str: String containing infos about the result
"""
lines = [
self.name,
'=' * len(self.name)
]... |
java | public static appflowaction[] get(nitro_service service, options option) throws Exception{
appflowaction obj = new appflowaction();
appflowaction[] response = (appflowaction[])obj.get_resources(service,option);
return response;
} |
python | def _set_vlan(self, v, load=False):
"""
Setter method for vlan, mapped from YANG variable /interface_vlan/interface/vlan (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_vlan is considered as a private
method. Backends looking to populate this variable should
... |
python | def decorator(f):
"""Creates a paramatric decorator from a function. The resulting decorator
will optionally take keyword arguments."""
@functools.wraps(f)
def decoratored_function(*args, **kwargs):
if args and len(args) == 1:
return f(*args, **kwargs)
if args:
r... |
java | void addMessageHandler(SubscriptionMessageHandler messageHandler)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "addMessageHandler", messageHandler);
final boolean inserted = _subscriptionMessagePool.add(messageHandler);
// If the message wasn't inserted, then t... |
python | def _get_value_from_value_pb(value_pb):
"""Given a protobuf for a Value, get the correct value.
The Cloud Datastore Protobuf API returns a Property Protobuf which
has one value set and the rest blank. This function retrieves the
the one value provided.
Some work is done to coerce the return value... |
java | public void setCoveragesByTime(java.util.Collection<CoverageByTime> coveragesByTime) {
if (coveragesByTime == null) {
this.coveragesByTime = null;
return;
}
this.coveragesByTime = new java.util.ArrayList<CoverageByTime>(coveragesByTime);
} |
java | @Override
public void paint(final RenderContext renderContext) {
WebXmlRenderContext webRenderContext = (WebXmlRenderContext) renderContext;
PrintWriter writer = webRenderContext.getWriter();
beforePaint(writer);
getBackingComponent().paint(renderContext);
afterPaint(writer);
} |
java | @Override
public void run() {
if (!isRegistered()) {
try {
register();
} catch (IOException ex) {
throw new RuntimeException("Failed to register prefix, aborting.", ex);
}
}
// continuously serve packets
while (true) {
try {
synchronized (face) {
... |
java | private static BatchExecutor getSetBatchExecutor(BeanMappingParam param, BeanMappingObject config) {
BatchExecutor executor = config.getSetBatchExecutor();
if (executor != null) { // 如果已经生成,则直接返回
return executor;
}
if (canBatch(config.getBehavior()) == false) {
c... |
java | public Table addHeading(Object o,String attributes)
{
addHeading(o);
cell.attribute(attributes);
return this;
} |
java | public static IVdmStackFrame getEvaluationContext(IWorkbenchWindow window)
{
List<IWorkbenchWindow> alreadyVisited = new ArrayList<IWorkbenchWindow>();
if (window == null)
{
window = fgManager.fActiveWindow;
}
return getEvaluationContext(window, alreadyVisited);
} |
java | public static FormItem createFormItem(AbstractReadOnlyAttributeInfo info, AttributeProvider attributeProvider) {
FormItem formItem = null;
if (info.getFormInputType() != null) {
FormItemFactory factory = FORM_ITEMS.get(info.getFormInputType());
if (null != factory) {
formItem = factory.create();
} else... |
python | def get_gemeente_by_id(self, id):
'''
Retrieve a `gemeente` by id (the NIScode).
:rtype: :class:`Gemeente`
'''
def creator():
url = self.base_url + '/municipality/%s' % id
h = self.base_headers
p = {
'geometry': 'full',
... |
python | def print_error(msg):
""" Print an error message """
if IS_POSIX:
print(u"%s[ERRO] %s%s" % (ANSI_ERROR, msg, ANSI_END))
else:
print(u"[ERRO] %s" % (msg)) |
python | def get(self, request):
"""
Redirects to CAS logout page
:param request:
:return:
"""
next_page = request.GET.get('next')
# try to find the ticket matching current session for logout signal
try:
st = SessionTicket.objects.get(session_key=requ... |
python | def require_data(self):
"""
raise a DatacatsError if the datadir or volumes are missing or damaged
"""
files = task.source_missing(self.target)
if files:
raise DatacatsError('Missing files in source directory:\n' +
'\n'.join(files))
... |
java | public boolean removeOrderbookCallback(final BitfinexOrderBookSymbol symbol,
final BiConsumer<BitfinexOrderBookSymbol, BitfinexOrderBookEntry> callback) throws BitfinexClientException {
return channelCallbacks.removeCallback(symbol, callback);
} |
java | @Pure
@Override
public int compare(Tuple3f<?> o1, Tuple3f<?> o2) {
if (o1==o2) return 0;
if (o1==null) return Integer.MIN_VALUE;
if (o2==null) return Integer.MAX_VALUE;
int cmp = Double.compare(o1.getX(), o2.getX());
if (cmp!=0) return cmp;
cmp = Double.compare(o1.getY(), o2.getY());
if (cmp!=0) return ... |
python | def create_qgis_template_output(output_path, layout):
"""Produce QGIS Template output.
:param output_path: The output path.
:type output_path: str
:param composition: QGIS Composition object to get template.
values
:type composition: qgis.core.QgsLayout
:return: Generated output path.... |
python | def new(arg_name, annotated_with=None):
"""Creates a BindingKey.
Args:
arg_name: the name of the bound arg
annotation: an Annotation, or None to create an unannotated binding key
Returns:
a new BindingKey
"""
if annotated_with is not None:
annotation = annotations.Annotati... |
python | def doctree_resolved(app, doctree, fromdocname):
"""
When the document, and all the links are fully resolved, we inject one
raw html element for running the command for processing the wavedrom
diagrams at the onload event.
"""
# Skip for non-html or if javascript is not inlined
if not app.en... |
java | public CreateSessionResponse createSession(String description, String preset, String notification,
String securityPolicy, String recording, LivePublishInfo publish) {
CreateSessionRequest request = new CreateSessionRequest();
request.withPreset(preset).withDescription(description).withNotifi... |
java | public static void setFollowRedirects(boolean set) {
SecurityManager sec = System.getSecurityManager();
if (sec != null) {
// seems to be the best check here...
sec.checkSetFactory();
}
followRedirects = set;
} |
python | def normalize_hex(hex_value):
"""
Normalize a hexadecimal color value to 6 digits, lowercase.
"""
match = HEX_COLOR_RE.match(hex_value)
if match is None:
raise ValueError(
u"'{}' is not a valid hexadecimal color value.".format(hex_value)
)
hex_digits = match.group(1)... |
java | private void loadGrid() {
if (fetch() == 0) {
initGrid(0);
return;
}
Iterator<String> data = template.iterator();
String[] pcs = StrUtil.split(data.next(), StrUtil.U, 3);
int testcnt = StrUtil.toInt(pcs[0]);
int datecnt = StrUtil.toInt(pcs... |
python | def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(404/405). '''
targets, urlargs = self._match_path(environ)
if not targets:
raise HTTPError(404, "Not found: " + repr(environ['PATH_INFO']))
method = environ['REQUEST_METHOD'].upper()
if... |
python | def create_view(self, request):
"""
Initiates the organization and user account creation process
"""
try:
if request.user.is_authenticated():
return redirect("organization_add")
except TypeError:
if request.user.is_authenticated:
... |
python | def create_store_credit_transaction(cls, store_credit_transaction, **kwargs):
"""Create StoreCreditTransaction
Create a new StoreCreditTransaction
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = a... |
java | public void deleteLocalizationPoint(JsBus bus, LWMConfig dest) throws SIBExceptionBase, SIException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
SibTr.entry(tc, "deleteLocalizationPoint", ((BaseDestination)dest).getName());
}
DestinationDefinition destDef = (... |
python | def send_fence(self):
'''send fence points from fenceloader'''
# must disable geo-fencing when loading
self.fenceloader.target_system = self.target_system
self.fenceloader.target_component = self.target_component
self.fenceloader.reindex()
action = self.get_mav_param('FEN... |
python | def infer_namespaces(ac):
"""infer possible namespaces of given accession based on syntax
Always returns a list, possibly empty
>>> infer_namespaces("ENST00000530893.6")
['ensembl']
>>> infer_namespaces("ENST00000530893")
['ensembl']
>>> infer_namespaces("ENSQ00000530893")
[]
>>> in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.