language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def create_tar_archive(self):
""" Create a tar archive of the main simulation outputs.
"""
#file filter
EXCLUDE_FILES = glob.glob(os.path.join(self.savefolder, 'cells'))
EXCLUDE_FILES += glob.glob(os.path.join(self.savefolder,
'popu... |
python | def _read_capabilities(self):
""" Read the capabilities list from a YubiKey >= 4.0.0 """
frame = yubikey_frame.YubiKeyFrame(command=SLOT.YK4_CAPABILITIES)
self._device._write(frame)
response = self._device._read_response()
r_len = yubico_util.ord_byte(response[0])
# 1 b... |
java | private BundleNodeMap lookupScriptableBundle(String name) {
BundleNodeMap map = null;
/* check to see if the bundle was explicitly registered */
if(_registeredBundles != null && _registeredBundles.containsKey(name)) {
map = new BundleNodeMap(name, (BundleNode)_registeredBundles.get(... |
java | public void filter(String name, EsAbstractConditionQuery.OperatorCall<BsThumbnailQueueCQ> queryLambda,
ConditionOptionCall<FilterAggregationBuilder> opLambda, OperatorCall<BsThumbnailQueueCA> aggsLambda) {
ThumbnailQueueCQ cq = new ThumbnailQueueCQ();
if (queryLambda != null) {
q... |
java | protected static User decode(int contextId, String encodedString, ExtensionAuthentication authenticationExtension) {
String[] pieces = encodedString.split(FIELD_SEPARATOR, -1);
User user = null;
try {
int id = Integer.parseInt(pieces[0]);
if (id >= ID_SOURCE)
ID_SOURCE = id + 1;
boolean enabled = pie... |
java | public <T> GraphAnalytic<K, VV, EV, T> run(GraphAnalytic<K, VV, EV, T> analytic) throws Exception {
analytic.run(this);
return analytic;
} |
python | async def flush(self) -> None:
"""
Give the writer a chance to flush the pending data
out of the internal buffer.
"""
async with self._flush_lock:
if self.finished():
if self._exc:
raise self._exc
return
... |
python | def XYZ100_to_sRGB1_linear(XYZ100):
"""Convert XYZ to linear sRGB, where XYZ is normalized so that reference
white D65 is X=95.05, Y=100, Z=108.90 and sRGB is on the 0-1 scale. Linear
sRGB has a linear relationship to actual light, so it is an appropriate
space for simulating light (e.g. for alpha blend... |
python | def _assert_is_dictlike(maybe_dictlike, valid_keys):
"""Raises a TypeError iff `maybe_dictlike` is not a dictlike object."""
# This covers a common mistake when people use incorrect dictionary nesting
# for initializers / partitioners etc. The previous error message was quite
# opaque, this should be much clear... |
python | def smix(B, Bi, r, N, V, X):
'''SMix; a specific case of ROMix. See scrypt.pdf in the links above.'''
X[:32 * r] = B[Bi:Bi + 32 * r] # ROMix - 1
for i in xrange(0, N): # ROMix - 2
aod = i * 32 * r # ROMix - 3
V[aod:aod... |
java | public String getFullName()
{
final StringBuilder buffer = new StringBuilder();
if (hasFirstName())
{
buffer.append(trimToEmpty(firstName));
}
if (hasFullName())
{
buffer.append(" ");
}
if (hasLastName())
{
buffer.append(trimToEmpty(lastName));
}
return bu... |
java | public StorableIndex<S> uniquify(StorableKey<S> key) {
if (key == null) {
throw new IllegalArgumentException();
}
if (isUnique()) {
return this;
}
StorableIndex<S> index = this;
for (OrderedProperty<S> keyProp : key.getProperties()) {... |
python | def run(namespace=None, action_prefix='action_', args=None):
"""Run the script. Participating actions are looked up in the caller's
namespace if no namespace is given, otherwise in the dict provided.
Only items that start with action_prefix are processed as actions. If
you want to use all items in the... |
java | public CmsGroup createGroup(String groupFqn, String description, int flags, String parent) throws CmsException {
return m_securityManager.createGroup(m_context, groupFqn, description, flags, parent);
} |
python | def cartopy_globe(self):
"""Initialize a `cartopy.crs.Globe` from the metadata."""
if 'earth_radius' in self._attrs:
kwargs = {'ellipse': 'sphere', 'semimajor_axis': self._attrs['earth_radius'],
'semiminor_axis': self._attrs['earth_radius']}
else:
at... |
java | public HashRangeExpression build(Integer hashColumnIndex) {
Map<Integer, Integer> ranges = m_builder.build();
HashRangeExpression predicate = new HashRangeExpression();
predicate.setRanges(ranges);
predicate.setHashColumnIndex(hashColumnIndex);
return predicate;
} |
java | public static byte[] fromHex(String hex) {
try {
return Hex.decodeHex(hex.toCharArray());
} catch (DecoderException e) {
return null;
}
} |
python | def admin_required(group):
"""Decorator that requires the user to be in a certain admin group.
For example, @admin_required("polls") would check whether a user is
in the "admin_polls" group or in the "admin_all" group.
"""
def in_admin_group(user):
return user.is_authenticated and user.ha... |
python | def createL4L2Column(network, networkConfig, suffix=""):
"""
Create a a single column containing one L4 and one L2.
networkConfig is a dict that must contain the following keys (additional keys
ok):
{
"enableFeedback": True,
"externalInputSize": 1024,
"sensorInputSize": 1024,
"L4Re... |
python | def _theme_and_template_fp(self):
"""Return the full paths for theme and template in this page"""
ptheme = self._config['theme'][0]
if ptheme == "":
ptheme = self.site.site_config['default_theme']
pthemedir = os.path.join(self.site.dirs['themes'], ptheme)
ptemplate = ... |
python | def calc_common_dist(df):
'''
calculate a common distribution (for col qn only) that will be used to qn
'''
# axis is col
tmp_arr = np.array([])
col_names = df.columns.tolist()
for inst_col in col_names:
# sort column
tmp_vect = df[inst_col].sort_values(ascending=False).values
# stacking ... |
java | public boolean addMessageListener(String consumerGroupId, boolean consumeFromBeginning,
String topic, IKafkaMessageListener messageListener) {
KafkaMsgConsumer kafkaConsumer = getKafkaConsumer(consumerGroupId, consumeFromBeginning);
return kafkaConsumer.addMessageListener(topic, messageListe... |
java | public Observable<ServiceResponse<Page<PublicIPAddressInner>>> listVirtualMachineScaleSetVMPublicIPAddressesNextWithServiceResponseAsync(final String nextPageLink) {
return listVirtualMachineScaleSetVMPublicIPAddressesNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<Public... |
java | @SuppressWarnings("unchecked")
private static <E> Dataset<E> loadOrCreateJobDataset(JobContext jobContext) {
Dataset<Object> dataset = load(jobContext).getDataset();
String jobDatasetName = getJobDatasetName(jobContext);
DatasetRepository repo = getDatasetRepository(jobContext);
if (repo.exists(TEMP_N... |
python | def ppc(self, nsims=1000, T=np.mean):
""" Computes posterior predictive p-value
Parameters
----------
nsims : int (default : 1000)
How many draws for the PPC
T : function
A discrepancy measure - e.g. np.mean, np.std, np.max
Returns
-----... |
java | public boolean isValidPosterSize(String posterSize) {
if (StringUtils.isBlank(posterSize) || posterSizes.isEmpty()) {
return false;
}
return posterSizes.contains(posterSize);
} |
java | public static CommerceOrderNote fetchByC_R_First(long commerceOrderId,
boolean restricted,
OrderByComparator<CommerceOrderNote> orderByComparator) {
return getPersistence()
.fetchByC_R_First(commerceOrderId, restricted,
orderByComparator);
} |
python | def _cmd_quote(cmd):
r'''
Helper function to properly format the path to the binary for the service
Must be wrapped in double quotes to account for paths that have spaces. For
example:
``"C:\Program Files\Path\to\bin.exe"``
Args:
cmd (str): Full path to the binary
Returns:
... |
java | public SM2 setMode(SM2Mode mode) {
this.mode = mode;
if (null != this.engine) {
this.engine.setMode(mode);
}
return this;
} |
python | def Z(self):
"""
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.
"""
if not self.timezone:
return 0
offset = self.timezone.utcoffset(self.data)
# Only days can be negative... |
java | private static void validateDocumentAgainstSchema(final Document xmlRootNode) throws InvalidConfigurationException
{
final Element rootElement = xmlRootNode.getDocumentElement();
final String version = rootElement.getAttribute("version");
String schemaFileName = "persistence_" + version.... |
java | protected void appendDetail(StringBuilder buffer, String fieldName, Object[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
Object item = array[i];
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null... |
java | private float calculateDx(float distanceX) {
int currentX = view.getScrollX();
float nextX = distanceX + currentX;
boolean isInsideHorizontally = nextX >= minX && nextX <= maxX;
return isInsideHorizontally ? distanceX : 0;
} |
python | def prepare_env(app, env, docname):
"""
Prepares the sphinx environment to store sphinx-needs internal data.
"""
if not hasattr(env, 'needs_all_needs'):
# Used to store all needed information about all needs in document
env.needs_all_needs = {}
if not hasattr(env, 'needs_functions')... |
java | public static void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) throws IOException {
File file = new File(uploadedFileLocation);
file.getParentFile().mkdirs();
int read = 0;
byte[] bytes = new byte[1024];
try (OutputStream out = new Fil... |
python | def getConst(name, timeout=0.1):
"""Get a shared constant.
:param name: The name of the shared variable to retrieve.
:param timeout: The maximum time to wait in seconds for the propagation of
the constant.
:returns: The shared object.
Usage: value = getConst('name')
"""
from . imp... |
python | def handler(self, operation=None, **kwargs):
"""
In addition to the methods described above, cruddy also provides a
generic handler interface. This is mainly useful when you want to wrap
a cruddy handler in a Lambda function and then call that Lambda
function to access the CRUD ... |
python | def invite(self, channel, nick):
"""
Invite someone to a channel.
Required arguments:
* channel - Channel to invite them to.
* nick - Nick to invite.
"""
with self.lock:
self.is_in_channel(channel)
self.send('INVITE %s %s' % (nick, channel... |
python | def rehash(self, password):
"""Recreates the internal hash."""
self.hash = self._new(password, self.desired_rounds)
self.rounds = self.desired_rounds |
java | public static ScanCursor of(String cursor) {
ScanCursor scanCursor = new ScanCursor();
scanCursor.setCursor(cursor);
return scanCursor;
} |
python | def pre_save(self, instance, add: bool):
"""Ran just before the model is saved, allows us to built
the slug.
Arguments:
instance:
The model that is being saved.
add:
Indicates whether this is a new entry
to the database or... |
python | def progress_bar(iteration,
total,
prefix=None,
suffix=None,
decs=1,
length=100):
"""Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/q... |
java | public void addReadFields1(FieldSet readFields) {
if(this.readFields1 == null) {
this.readFields1 = new FieldSet(readFields);
} else {
this.readFields1.addAll(readFields);
}
} |
java | static public String serializeTime(final long millisecondTime) throws NumberFormatException
{
if (millisecondTime >= 604800000 && (millisecondTime % 604800000) == 0)
{
return String.valueOf(millisecondTime / 604800000) + "w";
}
else if (millisecondTime >= 86400000 && (millisecondTime... |
python | def _get_new_ref(self, existing_refs):
"""Get a new reference atom for a row in the ZMatrix
The reference atoms should obey the following conditions:
- They must be different
- They must be neighbours in the bond graph
- They must have an index lower than the c... |
python | def print_events(events):
"""Prints out the event log for a user"""
columns = ['Date', 'Type', 'IP Address', 'label', 'username']
table = formatting.Table(columns)
for event in events:
table.add_row([event.get('eventCreateDate'), event.get('eventName'),
event.get('ipAddres... |
python | def callback_c(*args, **kwargs):
'Update the output following a change of the input selection'
#da = kwargs['dash_app']
session_state = kwargs['session_state']
calls_so_far = session_state.get('calls_so_far', 0)
session_state['calls_so_far'] = calls_so_far + 1
user_counts = session_state.get(... |
java | public static byte[] toUnixLineEndings( InputStream input ) throws IOException {
String encoding = "ISO-8859-1";
FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding));
filter.setEol(FixCrLfFilter.CrLf.newInstance("unix"));
ByteArrayOutputStream filteredFile = ... |
java | public static String getXHELM(HELM2Notation helm2notation) throws MonomerException, HELM1FormatException,
IOException, JDOMException, NotationException, CTKException, ValidationException, ChemistryException {
set = new HashSet<Monomer>();
Element root = new Element(xHelmNotationExporter.XHELM_ELEMENT);... |
python | def select_files_from_directory(self, directory=None):
"""Find files for this reader in *directory*.
If directory is None or '', look in the current directory.
"""
filenames = []
if directory is None:
directory = ''
for pattern in self.file_patterns:
... |
python | def _openResources(self):
""" Uses numpy.loadtxt to open the underlying file.
"""
try:
rate, data = scipy.io.wavfile.read(self._fileName, mmap=True)
except Exception as ex:
logger.warning(ex)
logger.warning("Unable to read wav with memmory mapping. Try... |
java | public static QueryByCriteria newQuery(Class classToSearchFrom, Criteria criteria)
{
return newQuery(classToSearchFrom, criteria, false);
} |
python | def acquire_context(self):
"""
Inspect the stack to acquire the current context used,
to render the placeholder. I'm really sorry for this,
but if you have a better way, you are welcome !
"""
frame = None
request = None
try:
for f in inspect.s... |
java | public List<IfSystemProperty<Exclude<T>>> getAllIfSystemProperty()
{
List<IfSystemProperty<Exclude<T>>> list = new ArrayList<IfSystemProperty<Exclude<T>>>();
List<Node> nodeList = childNode.get("if-system-property");
for(Node node: nodeList)
{
IfSystemProperty<Exclude<T>> type = new... |
java | public static String toSHA(byte[] input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return byteArray2Hex(md.digest(input));
} catch (NoSuchAlgorithmException nsae) {
// this code should never be reached!
}
return null;
} |
python | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
Using a minimum distance of 5km for the calculation.
"""
dists_mod = copy.deepcopy(dists)
dists_mod.rrup[dists.rrup <= 5.] = 5.
return super().get_mean_and_stddevs(
sites, rup, dists_m... |
python | def _make_standalone_handler(preamble):
"""Class factory used so that preamble can be passed to :py:class:`_StandaloneHandler`
without use of static members"""
class _StandaloneHandler(BaseHTTPRequestHandler, object):
"""HTTP Handler for standalone mode"""
def do_GET(self):
sel... |
python | def _indexOfEndTag(istack):
"""
Go through `istack` and search endtag. Element at first index is considered
as opening tag.
Args:
istack (list): List of :class:`.HTMLElement` objects.
Returns:
int: Index of end tag or 0 if not found.
"""
if len(istack) <= 0:
return ... |
python | def parse_timers(self):
"""
Parse the TIMER section reported in the ABINIT output files.
Returns:
:class:`AbinitTimerParser` object
"""
filenames = list(filter(os.path.exists, [task.output_file.path for task in self]))
parser = AbinitTimerParser()
pa... |
java | public static GraknConceptException invalidCasting(Object concept, Class type) {
return GraknConceptException.create(ErrorMessage.INVALID_OBJECT_TYPE.getMessage(concept, type));
} |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.FNNRG__GCGID:
setGCGID(GCGID_EDEFAULT);
return;
case AfplibPackage.FNNRG__TS_OFFSET:
setTSOffset(TS_OFFSET_EDEFAULT);
return;
}
super.eUnset(featureID);
} |
python | def _to_base36(number):
"""
Convert a positive integer to a base36 string.
Taken from Stack Overflow and modified.
"""
if number < 0:
raise ValueError("Cannot encode negative numbers")
chars = ""
while number != 0:
number, i = divmod(number, 36) # 36-character alphabet
... |
java | public void printHtmlTitle(PrintWriter out, String strTag, String strParams, String strData)
{
out.print(m_recDetail.getClassDesc());
} |
java | public void registerDereferencedListener(
final Provider.DereferenceListener onProviderFreedListener) {
if (uiThreadRunner.isOnUiThread()) {
graph.registerDereferencedListener(onProviderFreedListener);
} else {
uiThreadRunner.post(new Runnable() {
@Ove... |
python | def get_table(table_name):
"""
Get a registered table.
Decorated functions will be converted to `DataFrameWrapper`.
Parameters
----------
table_name : str
Returns
-------
table : `DataFrameWrapper`
"""
table = get_raw_table(table_name)
if isinstance(table, TableFuncWr... |
java | public Boolean getAsBoolean() {
if (value instanceof String) {
return Boolean.parseBoolean((String)value);
}
return (Boolean)value;
} |
java | private boolean isEligibleDefinitionSite(String name, Node definitionSite) {
switch (definitionSite.getToken()) {
case GETPROP:
case MEMBER_FUNCTION_DEF:
case STRING_KEY:
break;
default:
// No other node types are supported.
throw new IllegalArgumentException(definit... |
java | private void loadPlugins() {
final List<T> finalPluginsList = new ArrayList<T>();
pluginsList = new ArrayList<T>();
pluginsMap = new HashMap<String, T>();
String className = null;
try {
final Class<T>[] classes = getClasses();
for (final Class<T> clazz :... |
python | def create(self, friendly_name, api_version=values.unset,
voice_url=values.unset, voice_method=values.unset,
voice_fallback_url=values.unset, voice_fallback_method=values.unset,
status_callback=values.unset, status_callback_method=values.unset,
voice_caller_id... |
python | def encode_request(username, password, uuid, owner_uuid, is_owner_connection, client_type, serialization_version, client_hazelcast_version):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(username, password, uuid, owner_uuid, is_owner_connection, client_type... |
python | def segmentAcceptable(RCV_NXT, RCV_WND, SEG_SEQ, SEG_LEN):
"""
An acceptable segment: RFC 793 page 26.
"""
if SEG_LEN == 0 and RCV_WND == 0:
return SEG_SEQ == RCV_NXT
if SEG_LEN == 0 and RCV_WND > 0:
return ((RCV_NXT <= SEG_SEQ) and (SEG_SEQ < RCV_NXT + RCV_WND))
if SEG_LEN > 0 a... |
java | public PauseSessionResponse pauseSession(PauseSessionRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(... |
java | public static String toHex(byte []bytes, int offset, int len)
{
if (bytes == null)
return "null";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
int d1 = (bytes[offset + i] >> 4) & 0xf;
int d2 = (bytes[offset + i]) & 0xf;
if (d1 < 10)
sb.appe... |
java | private static void setDpiValue(final Multimap<String, String> extraParams, final int dpi) {
String searchKey = "FORMAT_OPTIONS";
for (String key: extraParams.keys()) {
if (key.equalsIgnoreCase(searchKey)) {
Collection<String> values = extraParams.removeAll(key);
... |
java | @Override
public CommercePriceEntry findByGroupId_Last(long groupId,
OrderByComparator<CommercePriceEntry> orderByComparator)
throws NoSuchPriceEntryException {
CommercePriceEntry commercePriceEntry = fetchByGroupId_Last(groupId,
orderByComparator);
if (commercePriceEntry != null) {
return commercePric... |
java | private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName... |
python | def get_server_id():
'''
Provides an integer based on the FQDN of a machine.
Useful as server-id in MySQL replication or anywhere else you'll need an ID
like this.
'''
# Provides:
# server_id
if salt.utils.platform.is_proxy():
server_id = {}
else:
use_crc = __opts_... |
java | public static CPRuleUserSegmentRel[] findByCommerceUserSegmentEntryId_PrevAndNext(
long CPRuleUserSegmentRelId, long commerceUserSegmentEntryId,
OrderByComparator<CPRuleUserSegmentRel> orderByComparator)
throws com.liferay.commerce.product.exception.NoSuchCPRuleUserSegmentRelException {
return getPersistence()
... |
python | def fit_model(y, x, yMaxLag, xMaxLag, includesOriginalX=True, noIntercept=False, sc=None):
"""
Fit an autoregressive model with additional exogenous variables. The model predicts a value
at time t of a dependent variable, Y, as a function of previous values of Y, and a combination
of previous values of ... |
java | @FFDCIgnore(SizeLimitExceededException.class)
private Set<LdapEntry> populateResultSet(NamingEnumeration<SearchResult> neu, String base, int scope, List<String> inEntityTypes, String[] attrIds) throws WIMException {
final String METHODNAME = "populateResultSet";
Set<LdapEntry> entities = new HashSe... |
python | def loadmetadata(self):
"""Load metadata for this file. This is usually called automatically upon instantiation, except if explicitly disabled. Works both locally as well as for clients connecting to a CLAM service."""
if not self.remote:
metafile = self.projectpath + self.basedir + '/' + se... |
python | def error(self, instance, value, error_class=None, extra=''):
"""Generate a :code:`ValueError` for invalid value assignment
The instance is the containing HasProperties instance, but it may
be None if the error is raised outside a HasProperties class.
"""
error_class = error_cla... |
python | def correct(tokens, term_freq):
"""
Correct a list of tokens, according to the term_freq
"""
log = []
output = []
for token in tokens:
corrected = _correct(token, term_freq)
if corrected != token:
log.append((token, corrected))
output.append(corrected)
ret... |
java | public void setDataGridTagModel(DataGridTagModel dataGridTagModel) {
assert dataGridTagModel != null;
_gridModel = dataGridTagModel;
_pagerModel = _gridModel.getState().getPagerModel();
_request = JspUtil.getRequest(_gridModel.getJspContext());
_anchorTag = TagRenderingBase.Fact... |
java | public static double mean(double[] a) {
if (a.length == 0) return Double.NaN;
double sum = sum(a);
return sum / a.length;
} |
python | def _get_cmd_output_now(self, exe, suggest_filename=None,
root_symlink=False, timeout=300, stderr=True,
chroot=True, runat=None, env=None,
binary=False, sizelimit=None):
"""Execute a command and save the output to a file for inc... |
java | public void addComment(String tag, String comment) {
String nt = normaliseTag(tag);
if(! comments.containsKey(nt)) {
comments.put(nt, new ArrayList<String>());
}
comments.get(nt).add(comment);
} |
python | def poly_to_power_basis(bezier_coeffs):
"""Convert a B |eacute| zier curve to polynomial in power basis.
.. note::
This assumes, but does not verify, that the "B |eacute| zier
degree" matches the true degree of the curve. Callers can
guarantee this by calling :func:`.full_reduce`.
Ar... |
python | def size(self):
"""
Returns combined size in bytes for all repository files
"""
size = 0
try:
tip = self.get_changeset()
for topnode, dirs, files in tip.walk('/'):
for f in files:
size += tip.get_file_size(f.path)
... |
python | def call_method(self, method):
"""
Calls a blocking method in an executor, in order to preserve the non-blocking behaviour
If ``method`` is a coroutine, yields from it and returns, no need to execute in
in an executor.
:param method: The method or coroutine to be called (with n... |
java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
sent_sms_responses result = (sent_sms_responses) service.get_payload_formatter().string_to_resource(sent_sms_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION... |
java | public void clear() {
getElement().clear();
if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) {
logUIAction(UIActions.CLEARED);
}
} |
python | def connect_gridfs(uri, db=None):
"""
Construct a GridFS instance for a MongoDB URI.
"""
return gridfs.GridFS(
db or connect_db(uri),
collection=get_collection(uri) or 'fs',
) |
java | public long getLongByTriple(final long[] triple) {
if (n == 0) return defRetValue;
final int[] e = new int[3];
final int chunk = chunkShift == Long.SIZE ? 0 : (int)(triple[0] >>> chunkShift);
final long chunkOffset = offset[chunk];
HypergraphSorter.tripleToEdge(triple, seed[chunk], (int)(offset[chunk + 1] - c... |
java | @SuppressWarnings("unused")
public String toJson() {
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(GeocodingAdapterFactory.create())
.create();
return gson.toJson(this);
} |
python | def direction_to_nearest_place(feature, parent):
"""If the impact layer has a distance field, it will return the direction
to the nearest place.
e.g. direction_to_nearest_place() -> NW
"""
_ = feature, parent # NOQA
layer = exposure_summary_layer()
if not layer:
return None
i... |
java | public static double convertToKelvin(TemperatureScale from, double temperature) {
switch(from) {
case FARENHEIT:
return convertFarenheitToKelvin(temperature);
case CELSIUS:
return convertCelsiusToKelvin(temperature);
case KELVIN:
... |
java | private static long sumChunksLength(int[] chunkIds, Vec vec, Vec weightsVector, int[] chunkLengths) {
for (int i = 0; i < chunkIds.length; i++) {
final int chunk = chunkIds[i];
chunkLengths[i] = vec.chunkLen(chunk);
if (weightsVector == null)
continue;
... |
java | public CmsAliasImportResult importRewriteAlias(
CmsDbContext dbc,
String siteRoot,
String source,
String target,
CmsAliasMode mode)
throws CmsException {
I_CmsVfsDriver vfs = getVfsDriver(dbc);
List<CmsRewriteAlias> existingAliases = vfs.readRewriteAliases(
... |
java | public static BigQueryFileFormat getFileFormat(Configuration conf) throws IOException {
// Ensure the BigQuery output information is valid.
String fileFormatName =
ConfigurationUtil.getMandatoryConfig(conf, BigQueryConfiguration.OUTPUT_FILE_FORMAT_KEY);
return BigQueryFileFormat.fromName(fileFormat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.