language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @SuppressWarnings("unchecked")
public static GrammaticalRelation valueOf(Object o) {
if (o instanceof GrammaticalRelation) {
return (GrammaticalRelation) o;
} else if (o instanceof Class) {
try {
return getRelation((Class<? extends GrammaticalRelationAnnotation>) o);
} catch (... |
java | public static HostAndPort fromString(String hostPort, int defaultPort) {
if (hostPort == null) throw new NullPointerException("hostPort == null");
String host = hostPort;
int endHostIndex = hostPort.length();
if (hostPort.startsWith("[")) { // Bracketed IPv6
endHostIndex = hostPort.lastIndexOf(']... |
java | public <T> T[] readSpecOrImage(final Class<T> type) throws DevFailed {
update();
return extractSpecOrImage(type);
} |
java | public List<String> getSites() {
List<String> sites = new ArrayList<String>();
if (this.sessions == null) {
return sites;
}
synchronized (sessionLock) {
sites.addAll(this.sessions.keySet());
}
return sites;
} |
python | def _compute_full_ts(self, data):
"""Perform calculation and create yearly timeseries at each point."""
# Get results at each desired timestep and spatial point.
full_ts, dt = self._compute(data)
# Vertically integrate.
vert_types = ('vert_int', 'vert_av')
if self.dtype_o... |
python | def scope(self, key, *tags, default=None):
"""Only apply tags and default for top-level key, effectively scoping the tags."""
scope = self._scopes[key]
tags = self._ensure_exclamation(tags)
default = default if not default or default.startswith("!") else "!" + default
if scope:
... |
java | protected String invoke(CommandProvider provider, CommandInterpreterWrapper interpreter) throws Exception {
Method method = provider.getClass().getMethod("_aggregator", new Class[]{CommandInterpreter.class}); //$NON-NLS-1$
method.invoke(provider, new Object[]{interpreter});
return interpreter.getOutput();
} |
python | def make_wsgi_app(matching, not_found_app=not_found_app):
""" Making a WSGI application from Matching object
registered other WSGI applications on each 'case' argument.
"""
def wsgi_app(environ, start_response):
environ['matcha.matching'] = matching
try:
matched_case, matched... |
python | def _stop_vibration_win(self):
"""Stop the vibration."""
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
stop_vibration = ctypes.byref(XinputVi... |
java | public PrincipalIdFormat withStatuses(IdFormat... statuses) {
if (this.statuses == null) {
setStatuses(new com.amazonaws.internal.SdkInternalList<IdFormat>(statuses.length));
}
for (IdFormat ele : statuses) {
this.statuses.add(ele);
}
return this;
} |
python | def isNonPairTag(self, isnonpair=None):
"""
True if element is listed in nonpair tag table (``br`` for example) or
if it ends with ``/>`` (``<hr />`` for example).
You can also change state from pair to nonpair if you use this as
setter.
Args:
isnonpair (boo... |
python | def client(self):
"""Return client for current application."""
if self._client is None:
self._client = self._client_builder()
return self._client |
java | @Nonnull
@CheckReturnValue
public static <T, R> LifecycleTransformer<T> bind(@Nonnull Observable<R> lifecycle,
@Nonnull final Function<R, R> correspondingEvents) {
checkNotNull(lifecycle, "lifecycle == null");
checkNotNull(correspondingEvents... |
python | def cysparse_type_to_real_sum_cysparse_type(cysparse_type):
"""
Returns the best **real** type for a **real** sum for a given type.
For instance:
INT32_t -> FLOAT64_t
Args:
cysparse_type:
"""
r_type = None
if cysparse_type in ['INT32_t', 'UINT32_t', 'INT64_t', 'UINT64_t... |
python | def send_packed_virtual_touch_event(xpos, ypos, phase, device_id, finger):
"""Create a new WAKE_DEVICE_MESSAGE."""
message = create(protobuf.SEND_PACKED_VIRTUAL_TOUCH_EVENT_MESSAGE)
event = message.inner()
# The packed version of VirtualTouchEvent contains X, Y, phase, deviceID
# and finger stored ... |
python | def categorical(pvals, size=None, random_state=None):
"""Return random integer from a categorical distribution
Parameters
----------
pvals : sequence of floats, length p
Probabilities of each of the ``p`` different outcomes. These
should sum to 1.
size : int or tuple of ints, optio... |
java | @Override
public <N,V> MutationResult insert(final K key, final String cf, final HColumn<N,V> c) {
addInsertion(key, cf, c);
return execute();
} |
python | def put(self, *args, **kwargs) -> 'SharedCache':
"""
Adds one or more variables to the cache.
:param args:
Variables can be specified by two consecutive arguments where the
first argument is a key and the second one the corresponding value.
For example:
... |
python | def check_pth_processing(self):
"""Empirically verify whether .pth files are supported in inst. dir"""
instdir = self.install_dir
log.info("Checking .pth file support in %s", instdir)
pth_file = self.pseudo_tempname() + ".pth"
ok_file = pth_file + '.ok'
ok_exists = os.pat... |
java | boolean sanityCheck(Intrinsic calib ) {
if(UtilEjml.isUncountable(calib.fx))
return false;
if(UtilEjml.isUncountable(calib.fy))
return false;
if(UtilEjml.isUncountable(calib.skew))
return false;
if( calib.fx < 0 )
return false;
if( calib.fy < 0 )
return false;
return true;
} |
python | def accept_dict(match, include_rejected=False, include_denied=False):
'''
Accept keys based on a dict of keys. Returns a dictionary.
match
The dictionary of keys to accept.
include_rejected
To include rejected keys in the match along with pending keys, set this
to ``True``. Def... |
python | def _get_parameter_signatures(self):
"""Get the signature of the parameters for the CL function declaration.
This should return the list of signatures of the parameters for use inside the function signature.
Returns:
list: the signatures of the parameters for the use in the CL code... |
python | def add(name, gid=None, **kwargs):
'''
Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456
'''
### NOTE: **kwargs isn't used here but needs to be included in this
### function for compatibility with the group.present state
if info(name):
... |
java | @Override
public void sawOpcode(int seen) {
if ((seen == Const.INVOKEINTERFACE) || (seen == Const.INVOKEVIRTUAL) || (seen == Const.INVOKESPECIAL) || (seen == Const.INVOKESTATIC)) {
String clsName = getClassConstantOperand();
String mName = getNameConstantOperand();
Strin... |
java | @Override
public String calculateContentDeterminismMessage() {
String ans = getContentDeterminismMessage();
if (ans != null) {
return ans;
}
if (m_subquery != null) {
updateContentDeterminismMessage(m_subquery.calculateContentDeterminismMessage());
... |
python | def _set_default_namespace(self, default_namespace):
"""Internal setter function."""
if default_namespace is not None:
default_namespace = default_namespace.strip('/')
else:
default_namespace = DEFAULT_NAMESPACE
self._default_namespace = _ensure_unicode(default_na... |
python | def record_markdown(text, cellid):
"""Records the specified markdown text to the acorn database.
Args:
text (str): the *raw* markdown text entered into the cell in the ipython
notebook.
"""
from acorn.logging.database import record
from time import time
ekey = "nb-{}".format(c... |
java | public boolean setWritable(boolean writable, boolean ownerOnly) {
return doChmod(ownerOnly ? S_IWUSR : (S_IWUSR | S_IWGRP | S_IWOTH), writable);
} |
java | public boolean remove (Toast toast) {
boolean removed = toasts.removeValue(toast, true);
if (removed) {
toast.getMainTable().remove();
Timer.Task timerTask = timersTasks.remove(toast);
if (timerTask != null) timerTask.cancel();
updateToastsPositions();
}
return removed;
} |
python | def serialize(self, f):
"""
Decorator to serialize access to a callable *f*
"""
s = self.router()
@self.spawn
def _():
for f, a, kw, r in s.recver:
try:
r.send(f(*a, **kw))
except Exception, e:
... |
python | def update_contact(self, contact):
"""Update name and/or email for contact.
:param contact: with updated info
:type contact: ``dict``
:rtype: ``bool``
"""
if not isinstance(contact, dict):
raise AttributeError('contact must be a <dict>')
method, url... |
python | async def _receive_reconfig_param(self, param):
"""
Handle a RE-CONFIG parameter.
"""
self.__log_debug('<< %s', param)
if isinstance(param, StreamResetOutgoingParam):
# mark closed inbound streams
for stream_id in param.streams:
self._inbo... |
java | public <T extends InvocationMarshaller<?>> T registerDispatcher (
InvocationDispatcher<T> dispatcher)
{
return registerDispatcher(dispatcher, null);
} |
java | public static <A, B, C, D, E> Choice5<A, B, C, D, E> c(C c) {
return new _C<>(c);
} |
java | public static int getPort(Config config, String path) {
try {
return new InetSocketAddress(config.getInt(path)).getPort();
} catch (IllegalArgumentException e) {
throw badValue(e, config, path);
}
} |
java | public static PlaceDetailsRequest placeDetails(GeoApiContext context, String placeId) {
PlaceDetailsRequest request = new PlaceDetailsRequest(context);
request.placeId(placeId);
return request;
} |
java | public static <T> T[] addToArray(T[] array, T item, Class<?> type) {
if (array == null) {
if (type == null && item != null) {
type = item.getClass();
}
@SuppressWarnings("unchecked")
T[] na = (T[]) Array.newInstance(type, 1);
na[0] = it... |
java | @Override
public CommerceNotificationTemplate findByUUID_G(String uuid, long groupId)
throws NoSuchNotificationTemplateException {
CommerceNotificationTemplate commerceNotificationTemplate = fetchByUUID_G(uuid,
groupId);
if (commerceNotificationTemplate == null) {
StringBundler msg = new StringBundler(6)... |
python | def to_python(self, value):
"""
"Called during deserialization and during the clean() method used
from forms.... [s]hould deal gracefully with... (*) an instance of
the correct type; (*) a string; (*) None (if the field allows
null=True)."
"For ``to_python()``, if anythi... |
python | def user_field_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/user_fields#show-user-field"
api_path = "/api/v2/user_fields/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
python | def finalize(self, album_cache, image_cache, warn_node):
"""Update attributes after Sphinx cache is updated.
:param dict album_cache: Cache of Imgur albums to read. Keys are Imgur IDs, values are Album instances.
:param dict image_cache: Cache of Imgur images to read. Keys are Imgur IDs, values... |
java | @Override
public void openForTraffic(ApplicationInfoManager applicationInfoManager, int count) {
super.openForTraffic(applicationInfoManager,
count == 0 ? this.defaultOpenForTrafficCount : count);
} |
java | public void setCommerceUserSegmentCriterionLocalService(
com.liferay.commerce.user.segment.service.CommerceUserSegmentCriterionLocalService commerceUserSegmentCriterionLocalService) {
this.commerceUserSegmentCriterionLocalService = commerceUserSegmentCriterionLocalService;
} |
python | def _mmUpdateDutyCycles(self):
"""
Update the duty cycle variables internally tracked by the TM mixin.
"""
period = self.getDutyCyclePeriod()
unionSDRArray = numpy.zeros(self.getNumColumns())
unionSDRArray[list(self._mmTraces["unionSDR"].data[-1])] = 1
self._mmData["unionSDRDutyCycle"] = \... |
java | @Nonnull
public static <Message extends PMessage<Message, Field>, Field extends PField>
String debugString(Message message) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DEBUG_STRING_SERIALIZER.serialize(baos, message);
return new String(baos.toByteArray(), UTF_8);
} |
java | private void initApplyPersistedChangesTask()
{
applyPersistedChangesTask = new RemoteCommand()
{
/**
* {@inheritDoc}
*/
public String getId()
{
return "ChangesListener-" + uniqueName + "-applyPersistedChangesTask";
}
/**
... |
java | public void alarm(Object alarmContext)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "alarm", alarmContext);
boolean alarmValid = false;
boolean presentInConnectionList = false;
Object[] listEntry = null;
// Take the pools monitor so that no-... |
java | private void copy(final InputStream in, final SeekableByteChannel out) throws IOException {
assert in != null : "InStream must be specified";
assert out != null : "Channel must be specified";
final byte[] backingBuffer = new byte[1024 * 4];
final ByteBuffer byteBuffer = ByteBuffer.wrap(... |
python | def _get_time_bins(index, freq, closed, label, base):
"""Obtain the bins and their respective labels for resampling operations.
Parameters
----------
index : CFTimeIndex
Index object to be resampled (e.g., CFTimeIndex named 'time').
freq : xarray.coding.cftime_offsets.BaseCFTimeOffset
... |
python | def __get_segments_from_cycle(graph, cycle_path):
"""Calculates the segments that emanate from the main cycle."""
list_of_segments = []
# We work through the cycle in a bottom-up fashion
for n in cycle_path[::-1]:
segments = __get_segments_from_node(n, graph)
if segments:
lis... |
python | def escape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
"""
Escape a string to let it go in an LDAP filter
:param ldap_string: The string to escape
:return: The protected string
"""
if not ldap_string:
# No content
return ldap_string
# Protect esc... |
python | def range_parse(s):
"""
>>> range_parse("chr1:1000-1")
Range(seqid='chr1', start=1, end=1000, score=0, id=0)
"""
chr, se = s.split(":")
start, end = se.split("-")
start, end = int(start), int(end)
if start > end:
start, end = end, start
return Range(chr, start, end, 0, 0) |
python | def _init_kind_converter(self):
"""Make a dictionary mapping kind ids to the names."""
from ..utils import invert_dict
kinds = self.session.query(Kind).all()
self._kind_id_to_name = {
kind.id: kind.name for kind in kinds
}
self._kind_name_to_id = invert_dict(... |
java | public static String getPinyin(String text, PinyinFormat format) {
char[] array = text.toCharArray();
StringBuffer sb = new StringBuffer();
String sep = ""; // 分隔符
if ($.notNull(format)) {
String separator = format.getSeparator();
sep = $.notNull(separator) ? separator : sep;
}
for (int i = 0;... |
python | def process(self, obj, parent=None, parent_key=None, depth=0):
"""Recursively process the data for sideloading.
Converts the nested representation into a sideloaded representation.
"""
if isinstance(obj, list):
for key, o in enumerate(obj):
# traverse into li... |
python | def load(cls, path):
"""
Load a SOM from a JSON file saved with this package..
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class.
"""
data = json.load... |
java | public static String generate(String controllerPath, String action, String id, boolean restful, Map params) {
//prepend slash if missing
StringBuilder uri = new StringBuilder(controllerPath.startsWith("/") ? controllerPath : "/" + controllerPath);
if (restful) {
if (id != null) {
... |
python | def parse_object_type_extension(lexer: Lexer) -> ObjectTypeExtensionNode:
"""ObjectTypeExtension"""
start = lexer.token
expect_keyword(lexer, "extend")
expect_keyword(lexer, "type")
name = parse_name(lexer)
interfaces = parse_implements_interfaces(lexer)
directives = parse_directives(lexer, ... |
java | protected void handleMappingFailureException(Object bean, String name, Object value, StringBuilder pathSb, PropertyDesc pd,
RuntimeException e) {
if (!isBadRequestMappingFailureException(e)) {
throw e;
}
// e.g. non-number GET but number type property
// suppress ... |
java | @Override
public Object visitNegation(ExcellentParser.NegationContext ctx) {
return Conversions.toDecimal(visit(ctx.expression()), m_evalContext).negate();
} |
python | def from_response(cls, response, attrs):
""" Create an index from returned Dynamo data """
proj = response['Projection']
index = cls(proj['ProjectionType'], response['IndexName'],
attrs[response['KeySchema'][1]['AttributeName']],
proj.get('NonKeyAttributes... |
java | public static <T> Level0ArrayOperator<Float[],Float> onArrayFor(final Float... elements) {
return onArrayOf(Types.FLOAT, VarArgsUtil.asRequiredObjectArray(elements));
} |
java | private void _substringmatch() throws
IOException
{
if (debug)
{
checkState(reader.curChar == '*');
}
builder.type = Type.SUBSTRINGMATCH;
builder.append("*=");
reader.next();
if (debug)
{
checkState(reader.curChar == '=');
}
} |
python | def run_loop(leds=all_leds):
"""
Start the loop.
:param `leds`: Which LEDs to light up upon switch press.
:type `leds`: sequence of LED objects
"""
print('Loop started.\nPress Ctrl+C to break out of the loop.')
while 1:
try:
if switch():
[led.on() for led... |
python | def load_preseed():
""" Update JobPriority information from preseed.json
The preseed data has these fields: buildtype, testtype, platform, priority, expiration_date
The expiration_date field defaults to 2 weeks when inserted in the table
The expiration_date field has the format "YYYY-MM-DD", however, i... |
python | def _execute_query(self):
'''Execute the query without fetching data. Returns the number of
elements in the query.'''
pipe = self.pipe
if not self.card:
if self.meta.ordering:
self.ismember = getattr(self.backend.client, 'zrank')
self.card = get... |
java | public Login login(TokenResult token, String username, String password,
String domain) throws Exception {
username = encode(username);
if (domain != null) {
domain = encode(domain);
}
Api apiResult = null;
// depends on MediaWiki version see
// https://test2.wikipedia.org/w/api.php?a... |
python | def create_event():
"""
Create Win32 event.
"""
event = windll.kernel32.CreateEventA(
None, # Default security attributes.
BOOL(True), # Manual reset event.
BOOL(True), # Initial state = signaled.
None # Unnamed event object.
)
if not event:
raise Exce... |
python | def _implementations(cls):
"""Returns all the concrete subclasses of MetadataExtractor.
"""
if cls.__implementations:
return cls.__implementations
cls.__implementations = {}
for implementation in all_subclasses(MetadataExtractor):
try:
fe... |
java | public final void setAppsRootDirectory(final String directory) throws URISyntaxException, IOException {
this.appsRootDirectory = directory;
final File realRoot;
if (!directory.contains(":/")) {
realRoot = new File(directory);
} else {
final Optional<File> fileOpt... |
python | def get_uids(self, filename=None):
"""UIDs of all reminders in the file excluding included files
If a filename is specified, only it's UIDs are return, otherwise all.
filename -- the remind file
"""
self._update()
if filename:
if filename not in self._remind... |
python | def resolve_model(self, model):
'''
Resolve a model given a name or dict with `class` entry.
:raises ValueError: model specification is wrong or does not exists
'''
if not model:
raise ValueError('Unsupported model specifications')
if isinstance(model, basest... |
python | def _find_single(self, match_class, **keywds):
"""implementation details"""
self._logger.debug('find single query execution - started')
start_time = timeit.default_timer()
norm_keywds = self.__normalize_args(**keywds)
decl_matcher = self.__create_matcher(match_class, **norm_keywd... |
java | @Override
public void encodeEnd(FacesContext context) throws IOException {
super.encodeEnd(context);
encodeViewParameters(context);
notifyAfter(context, PhaseId.RENDER_RESPONSE);
} |
java | @Override
public void update(double extrp)
{
for (final MessageData messageData : messages)
{
if (messageData.elapsed())
{
delete.add(messageData);
deleted = true;
}
}
if (deleted)
{
... |
python | def _fetch(self, request: Request, is_file: bool):
'''Fetch the request
Coroutine.
'''
_logger.info(_('Fetching ‘{url}’.'), url=request.url)
self._item_session.request = request
response = None
try:
with self._processor.ftp_client.session() as sessi... |
java | public Iterator<String> list() {
try {
final Enumeration<String> keys = pathRegistry.keys();
return new Iterator<String>() {
public boolean hasNext() { return keys.hasMoreElements(); }
public String next() { return keys.nextElement(); }
pub... |
python | def install_json_params(self, ij=None):
"""Return install.json params in a dict with name param as key.
Args:
ij (dict, optional): Defaults to None. The install.json contents.
Returns:
dict: A dictionary containing the install.json input params with name as key.
... |
python | def _cache_morlist_raw(self, instance):
"""
Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery.
"""
i_key = self._instance_key(instance)
self.log.debug("Caching... |
java | public Observable<ServiceResponse<GeoBackupPolicyInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String serverName, String databaseName, GeoBackupPolicyState state) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscr... |
java | public void setAttributeUpdates(java.util.Collection<TypedLinkFacetAttributeUpdate> attributeUpdates) {
if (attributeUpdates == null) {
this.attributeUpdates = null;
return;
}
this.attributeUpdates = new java.util.ArrayList<TypedLinkFacetAttributeUpdate>(attributeUpdates... |
java | public EClass getObjectByteExtent() {
if (objectByteExtentEClass == null) {
objectByteExtentEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(509);
}
return objectByteExtentEClass;
} |
python | def set_default_style(style):
"""Sets default global style to be used by ``prettyprinter.cpprint``.
:param style: the style to set, either subclass of
``pygments.styles.Style`` or one of ``'dark'``, ``'light'``
"""
global default_style
if style == 'dark':
style = default_d... |
java | public Matrix4f set(Matrix3fc mat) {
if (mat instanceof Matrix3f) {
MemUtil.INSTANCE.copy((Matrix3f) mat, this);
} else {
setMatrix3fc(mat);
}
this._properties(PROPERTY_AFFINE);
return this;
} |
python | def error_response(error_type="Internal server error",
error_text=None,
status=400,
participant=None):
"""Return a generic server error response."""
traceback.print_exc()
print("Error: {}.".format(error_type))
page = error_page(
error_tex... |
python | def _update_consumers(self):
"""Update Consumers.
- Add more if requested.
- Make sure the consumers are healthy.
- Remove excess consumers.
:return:
"""
# Do we need to start more consumers.
consumer_to_start = \
min(max(self.num... |
java | public void setFromPointCloud(Iterable<? extends Point3D> pointCloud) {
Vector3f r = new Vector3f();
Vector3f s = new Vector3f();
Vector3f t = new Vector3f();
Point3f c = new Point3f();
double[] extents = new double[3];
computeOBBCenterAxisExtents(
pointCloud,
r, s, t,
c,
extents);
set(c.g... |
java | @BetaApi
public final ListSecurityPoliciesPagedResponse listSecurityPolicies(ProjectName project) {
ListSecurityPoliciesHttpRequest request =
ListSecurityPoliciesHttpRequest.newBuilder()
.setProject(project == null ? null : project.toString())
.build();
return listSecurityPolic... |
java | public static void newCertificateRevocationList(File caRevocationList, File caKeystoreFile, String caKeystorePassword) {
try {
// read the Fathom CA key and certificate
KeyStore store = openKeyStore(caKeystoreFile, caKeystorePassword);
PrivateKey caPrivateKey = (PrivateKey) s... |
python | def get_values(self):
"""
Returns the CPD of the variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_values()
{'bowel-problem': array([[ 0.01],
[ 0.99]]),
... |
java | public static String urlEncode(final String text) {
try {
return URLEncoder.encode(text, StandardCharsets.UTF_8.name());
} catch (final UnsupportedEncodingException e) {
final String message = "Unable to encode text : " + text;
throw new TechnicalException(message, e)... |
python | def get_jump_targets(code, opc):
"""Returns a list of instruction offsets in the supplied bytecode
which are the targets of some sort of jump instruction.
"""
offsets = []
for offset, op, arg in unpack_opargs_bytecode(code, opc):
if arg is not None:
jump_offset = -1
i... |
python | def _generate_random_word(self, length):
"""
Generates a random word
"""
return ''.join(random.choice(string.ascii_lowercase) for _ in range(length)) |
java | public void addSiteInternally(
String server,
String uri,
String title,
String position,
String errorPage,
String webserver,
String sslMode,
String secureServer,
String exclusive,
String error,
String usePermanentRedirects)
thro... |
python | def extra_space_exists(str1: str, str2: str) -> bool: # noqa
"""
Return True if a space shouldn't exist between two items
"""
ls1, ls2 = len(str1), len(str2)
if str1.isdigit():
# 10 SM
if str2 in ['SM', '0SM']:
return True
# 12 /10
if ls2 > 2 and str2[0] ... |
python | def set_autostart_entry(autostart_data: AutostartSettings):
"""
Activates or deactivates autostarting autokey during user login.
Autostart is handled by placing a .desktop file into '$XDG_CONFIG_HOME/autostart', typically '~/.config/autostart'
"""
_logger.info("Save autostart settings: {}".format(au... |
java | @Override
public String getPageSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey) {
String sql = boundSql.getSql();
Page page = this.getLocalPage();
String orderBy = page.getOrderBy();
if (StringUtil.isNotEmpty(orderBy)) {
... |
python | def needs_path(f):
"""Wraps a function that accepts path-like to give it a pathlib.Path"""
@wraps(f)
def wrapped(pathlike, *args, **kwargs):
path = pathlib.Path(pathlike)
return f(path, *args, **kwargs)
return wrapped |
java | public static <S extends Solution<?>> void nash(List<S> solutionsList) {
nash(solutionsList, getNadirValues(solutionsList));
} |
java | protected void registerDefaultDatatypes() {
registerStandardDatatype(String.class);
registerStandardDatatype(Boolean.class);
registerStandardDatatype(Character.class);
registerStandardDatatype(Currency.class);
registerCustomDatatype(Datatype.class); // internal trick...
registerNumberDatatypes(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.