language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
query = query.replace(',', ' ')
vals = query.split()
coords = [float(v) for v in vals]
return tuple(coords[:2]) |
java | public int writeBytesTo(byte[] dest, int offset, int maxLength) {
maxLength = N.min(maxLength, bits() / 8);
Util.checkPositionIndexes(offset, offset + maxLength, dest.length);
writeBytesToImpl(dest, offset, maxLength);
return maxLength;
} |
java | protected TypeData mergeTypeData(final XExpression expression, List<TypeData> allValues, boolean returnType, boolean nullIfEmpty) {
int allSize = allValues.size();
if (nullIfEmpty && allSize == 0) {
return null;
}
final List<TypeData> values;
if (allSize == 1) {
TypeData result = allValues.get(0);
if... |
python | def simplify_scalar(self, func=sympy.simplify):
"""Simplify all scalar expressions appearing in the Matrix."""
def element_simplify(v):
if isinstance(v, sympy.Basic):
return func(v)
elif isinstance(v, QuantumExpression):
return v.simplify_scalar(f... |
python | def primers(self, tm=60):
'''Design primers for amplifying the assembled sequence.
:param tm: melting temperature (lower than overlaps is best).
:type tm: float
:returns: Primer list (the output of coral.design.primers).
:rtype: list
'''
self.primers = coral.des... |
java | @PostMapping("/setting/auth")
public ValidationSessionInfo login(@RequestBody ValidationLoginInfo info, HttpServletRequest req, HttpServletResponse res) {
return this.validationSessionComponent.checkAuth(info, req, res);
} |
java | public Optional<String> getOptionalRawSnippetContent(Object projectIdOrPath, Integer snippetId) {
try {
return (Optional.ofNullable(getRawSnippetContent(projectIdOrPath, snippetId)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
... |
java | public static <T> int safeCompare(Comparable<T> d1, T d2) {
if (d1 != null && d2 != null) {
return d1.compareTo(d2);
} else if (d1 == null && d2 != null) {
return -1;
} else if (d1 != null && d2 == null) {
return 1;
} else {
return 0;
... |
java | @Override
public List<GroupDef> getGroups() {
List<GroupDef> groups = new ArrayList<GroupDef>();
for (Node group : model.get("group")) {
groups.add(new GroupDefImpl(getDescriptorName(), model, group));
}
return groups;
} |
java | public static String getFormattedMessageFromLocalizedMessage(String localizedMessage, Object[] args, boolean quiet) {
return TraceNLSResolver.getInstance().getFormattedMessage(localizedMessage, args);
} |
java | @Override
protected boolean isValidProposal(String proposal, String prefix, ContentAssistContext context) {
// A valid proposal cannot be an hidden feature
return !Utils.isHiddenMember(proposal) && super.isValidProposal(proposal, prefix, context);
} |
python | def uuid_to_slug(uuid):
"""
Return IOTile Cloud compatible Device Slug
:param uuid: UUID
:return: string in the form of d--0000-0000-0000-0001
"""
if not isinstance(uuid, int):
raise ArgumentError("Invalid id that is not an integer", id=uuid)
if uuid < 0 or uuid > 0x7fffffff:
... |
python | def delete_role(self, role, mount_point=DEFAULT_MOUNT_POINT):
"""Delete the previously registered role.
Supported methods:
DELETE: /auth/{mount_point}/role/{role}. Produces: 204 (empty body)
:param role: The name of the role to delete.
:type role: str | unicode
:pa... |
python | def generator(self):
"""
Returns a generator which yields the items added to the bar during
construction, and updates the progress bar *after* the yielded block
returns.
"""
if not self.entered:
raise RuntimeError('You need to use progress bars in a with block... |
java | LinkedList<Change> bisect(String text1, String text2) {
// Cache the text lengths to prevent multiple calls.
int text1_length = text1.length();
int text2_length = text2.length();
int max_d = (text1_length + text2_length + 1) / 2;
int v_offset = max_d;
int v_length = 2 * m... |
java | public static boolean matchRegex(Object left, Object right) {
if (left == null || right == null) return false;
Pattern pattern;
if (right instanceof Pattern) {
pattern = (Pattern) right;
} else {
pattern = Pattern.compile(toString(right));
}
String... |
java | public static String dehyphenate(LineNumberReader reader, String docId) {
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = reader.readLine()) != null) {
String lineOut = line;
Matcher matcher = patternHyphen.matcher(line);
... |
python | def resolve(self, spec):
"""Returns an iterator over the target(s) the given address points to."""
address = Address.parse(spec)
# NB: This is an idempotent, short-circuiting call.
self.inject_address_closure(address)
return self.transitive_subgraph_of_addresses([address]) |
java | public static Indentation tabs(final int level) {
return level < TABS.length ? TABS[level > 0 ? level : 0] : new Indentation(1, '\t', level);
} |
python | def post_execute(self):
"""Cache the modification times of any modules imported in this execution
"""
newly_loaded_modules = set(sys.modules) - self.loaded_modules
for modname in newly_loaded_modules:
_, pymtime = self._reloader.filename_and_mtime(sys.modules[modname])
... |
java | public void initializeFromFile(TreeIndexHeader header, PageFile<N> file) {
this.dirCapacity = header.getDirCapacity();
this.leafCapacity = header.getLeafCapacity();
this.dirMinimum = header.getDirMinimum();
this.leafMinimum = header.getLeafMinimum();
if(getLogger().isDebugging()) {
StringBuil... |
java | public static String removeLeft(final String value, final String prefix, final boolean caseSensitive) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
validate(prefix, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (caseSensitive) {
return value.startsWith(pr... |
python | def get_package_version():
"""return package version without importing it"""
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, 'policy', '__init__.py'),
mode='rt',
encoding='utf-8') as initf:
for line in initf:
m = version.match(li... |
java | public OvhUser serviceName_users_POST(String serviceName, OvhInputUser body) throws IOException {
String qPath = "/caas/registry/{serviceName}/users";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "POST", sb.toString(), body);
return convertTo(resp, OvhUser.class);
} |
java | private static ImmutableList<Rule> initRules(
AbstractCompiler compiler, ImmutableList<ConformanceConfig> configs) {
ImmutableList.Builder<Rule> builder = ImmutableList.builder();
List<Requirement> requirements = mergeRequirements(compiler, configs);
for (Requirement requirement : requirements) {
... |
java | public Observable<FirewallRuleInner> replaceAsync(String resourceGroupName, String serverName) {
return replaceWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<FirewallRuleInner>, FirewallRuleInner>() {
@Override
public FirewallRuleInner call(ServiceR... |
python | def atomic_copy(src, dst):
"""Copy the file src to dst, overwriting dst atomically."""
with temporary_file(root_dir=os.path.dirname(dst)) as tmp_dst:
shutil.copyfile(src, tmp_dst.name)
os.chmod(tmp_dst.name, os.stat(src).st_mode)
os.rename(tmp_dst.name, dst) |
python | def head_bucket(self, name):
"""
Check if a bucket exists
:param name:
:return:
"""
try:
self.s3.head_bucket(Bucket=name)
info = self.s3.get_bucket_website(Bucket=self.sitename)
if not info:
return False, 404, "Configure... |
python | def create_by_natural_key(self, *args):
"""
Create a new object from the provided natural key values. If the
natural key contains related objects, recursively get or create them by
their natural keys.
"""
kwargs = self.natural_key_kwargs(*args)
for name, rel_to ... |
python | async def upload_sticker_file(self, user_id: base.Integer, png_sticker: base.InputFile) -> types.File:
"""
Use this method to upload a .png file with a sticker for later use in createNewStickerSet
and addStickerToSet methods (can be used multiple times).
Source: https://core.telegram.or... |
java | private static void initInstability(){
double[][] instability = {
//W C M H Y F Q N I R D P T K E V S G A L
{1.0, 1.0, 24.68, 24.68, 1.0, 1.0, 1.0, 13.34, 1.0, 1.0, 1.0, 1.0, -14.03, 1.0, 1.0, -7.49, 1.0, -9.37, -14.03, 13.34},
{24.68, 1.0, 33.6, 33.6, 1.0, 1.0, -6.54, 1.0, ... |
python | def _FormatMessage(self, event):
"""Formats the message.
Args:
event (EventObject): event.
Returns:
str: message field.
Raises:
NoFormatterFound: if no event formatter can be found to match the data
type in the event.
"""
message, _ = self._output_mediator.GetForma... |
java | public void marshall(RemoveTagsFromResourceRequest removeTagsFromResourceRequest, ProtocolMarshaller protocolMarshaller) {
if (removeTagsFromResourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.m... |
python | def notify(self, message):
"""Callback function which checks lines of output, tries to match
against regex defined in subclass's "dispatch" dict, and passes through
to a handler on match.
"""
for regex, handler in self.dispatch.items():
match = re.search(regex, messag... |
python | def handler(event, context):
"""
Historical {{cookiecutter.technology_name}} event poller.
This poller is run at a set interval in order to ensure that changes do not go undetected by historical.
Historical pollers generate `polling events` which simulate changes. These polling events contain configu... |
python | def _input_handler_decorator(self, data):
"""Adds positional parameters to selected input_handler's results.
"""
input_handler = getattr(self, self.__InputHandler)
input_parts = [
self.Parameters['taxonomy_file'],
input_handler(data),
self.Parameters['... |
java | @Override
public long dynamicQueryCount(DynamicQuery dynamicQuery,
Projection projection) {
return commerceDiscountUsageEntryPersistence.countWithDynamicQuery(dynamicQuery,
projection);
} |
java | public void validate() {
StringBuilder validationErrorBuilder = new StringBuilder("Process engine configuration is invalid: \n");
boolean isValid = true;
if(datasourceJndiName == null || datasourceJndiName.isEmpty()) {
isValid = false;
validationErrorBuilder.append(" property 'datasourc... |
python | def build_weights(realizations, imt_dt):
"""
:returns: an array with the realization weights of shape (R, M)
"""
arr = numpy.zeros((len(realizations), len(imt_dt.names)))
for m, imt in enumerate(imt_dt.names):
arr[:, m] = [rlz.weight[imt] for rlz in realizations]
return arr |
java | public ApiSuccessResponse redirect(String id, RedirectData redirectData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = redirectWithHttpInfo(id, redirectData);
return resp.getData();
} |
python | def inject(module_name, new_globals, *additional_modules):
"""Base method for "injecting" greened modules into an imported module. It
imports the module specified in *module_name*, arranging things so
that the already-imported modules in *additional_modules* are used when
*module_name* makes its import... |
java | public static appqoeaction get(nitro_service service, String name) throws Exception{
appqoeaction obj = new appqoeaction();
obj.set_name(name);
appqoeaction response = (appqoeaction) obj.get_resource(service);
return response;
} |
java | private static double getDurationInSecs(
ViewData.AggregationWindowData.CumulativeData cumulativeData) {
return toDoubleSeconds(cumulativeData.getEnd().subtractTimestamp(cumulativeData.getStart()));
} |
java | public void setMap(Map map) throws JspException
{
if (map == null) {
String s = Bundle.getString("Tags_MapAttrValueRequired", new Object[]{"map"});
registerTagError(s, null);
}
_map = map;
} |
python | def depends_on(options, **kwargs):
"""
Analysis function
Get list of files that depend on given configs
If there is 'graph=name' in analysis parameters, instead graph of includes will be rendered into name.svg
"""
include_graph = options['include_graph']
include_graph.render('full_graph')
... |
python | def check_dependencies():
"""
Check that dependencies are installed:
- require git 2.7+, so that credential-cache--daemon ignores SIGHUP
https://github.com/git/git/blob/v2.7.0/credential-cache--daemon.c
"""
# Check that git is installed
if not shutil.which("git"):
raise Error(_(... |
java | @Override
public void sawOpcode(int seen) {
JPAUserValue userValue = null;
try {
switch (seen) {
case Const.INVOKEVIRTUAL:
case Const.INVOKEINTERFACE: {
userValue = processInvoke();
break;
}
... |
python | def get_message_plain_text(msg: Message):
"""
Converts an HTML message to plain text.
:param msg: A :class:`~flask_mail.Message`
:return: The plain text message.
"""
if msg.body:
return msg.body
if BeautifulSoup is None or not msg.html:
return msg.html
plain_text = '\n... |
python | def is_bare(self):
"""
:data:`True` if the repository has no working tree, :data:`False` if it does.
The value of this property is computed by running the ``hg id`` command
to check whether the special global revision id ``000000000000`` is
reported.
"""
# Make s... |
python | def eeg_microstates_clustering(data, n_microstates=4, clustering_method="kmeans", n_jobs=1, n_init=25, occurence_rejection_treshold=0.05, max_refitting=5, verbose=True):
"""
Fit the clustering algorithm.
"""
# Create training set
training_set = data.copy()
if verbose is True:
print("- I... |
python | def session_exists(self, ticket):
'''
Test if a session records exists for a service ticket.
'''
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
exists = self.session_storage_adapter.exists(ticket)
logging.debug('[CAS] Session [{}] exists: {}'.format(ti... |
python | def _lower_if_str(item):
"""
Try to convert item to lowercase, if it is string.
Args:
item (obj): Str, unicode or any other object.
Returns:
obj: ``item.lower()`` if `item` is ``str`` or ``unicode``, else just \
`item` itself.
"""
# python 2 / 3 shill
try:
... |
python | def update_relationship(self, relationship_form):
"""Updates an existing relationship.
arg: relationship_form (osid.relationship.RelationshipForm):
the form containing the elements to be updated
raise: IllegalState - ``relationship_form`` already used in an
u... |
java | public <K, V> void build(CommandArgs<K, V> args) {
// PAUSE <queue-name> [option option ... option]
if (bcast != null) {
args.add(CommandKeyword.BCAST.getBytes());
}
if (state != null) {
args.add(CommandKeyword.STATE.getBytes());
}
if (option !... |
java | public boolean skipUntil(long txid) throws IOException {
while (true) {
FSEditLogOp op = readOp();
if (op == null) {
return false;
}
if (op.getTransactionId() >= txid) {
cachedOp = op;
return true;
}
}
} |
python | def exit(self):
'''Close connection.'''
self.output.write("Happy hacking!")
self.output.nextLine()
self.output.loseConnection() |
java | static long adjustForField(long sizeSoFar, final Field f) {
final Class<?> type = f.getType();
final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
// TODO: No alignments based on field type/ subclass fields alignments?
return sizeSoFar + fsize;
} |
java | public JobBuilder withIdentity (final String name, final String group)
{
m_aKey = new JobKey (name, group);
return this;
} |
python | def unattach_team(context, id, team_id):
"""unattach_team(context, id, team_id)
Unattach a team from a topic.
>>> dcictl topic-unattach-team [OPTIONS]
:param string id: ID of the topic to unattach from [required]
:param string team_id: ID of team to unattach from this topic,
default is th... |
python | def to_segment_xml(self, override_file_if_exists=False):
"""
Write the segment list in self.segmentList to self.storage_path.
"""
# create XML doc and add process table
outdoc = ligolw.Document()
outdoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.regist... |
python | def get(id_, hwid, type_, unit, precision, as_json):
"""Get temperature of a specific sensor"""
if id_ and (hwid or type_):
raise click.BadOptionUsage(
"If --id is given --hwid and --type are not allowed."
)
if id_:
try:
sensor = W1ThermSensor.get_available_s... |
java | private Block<Void> toBlock(final Runnable code) {
return new Block<Void>() {
public Void run() {
code.run();
return null;
}
};
} |
python | def most_by_mask(self, mask, y, mult):
""" Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contain... |
python | def create_log_dict(request, response):
"""
Create a dictionary with logging data.
"""
remote_addr = request.META.get('REMOTE_ADDR')
if remote_addr in getattr(settings, 'INTERNAL_IPS', []):
remote_addr = request.META.get(
'HTTP_X_FORWARDED_FOR') or remote_addr
user_email = "... |
python | def clean_text(self, name, **kwargs):
"""Basic clean-up."""
name = strip_quotes(name)
name = collapse_spaces(name)
return name |
python | def _optionalPrompt(self, mode):
"""Interactively prompt for parameter if necessary
Prompt for value if
(1) mode is hidden but value is undefined or bad, or
(2) mode is query and value was not set on command line
Never prompt for "u" mode parameters, which are local variables.
... |
python | def write_xml(self, as_string=False):
"""Write the XML report"""
if not as_string:
et.ElementTree(self.xmlreport).write('{}/{}.xml'.format(self.outpath, self.outputprefix), pretty_print=True, xml_declaration=True)
else:
output = et.tostring(self.xmlreport, pretty_print=Tr... |
python | def _gather_keys_by_type(self, type):
"""
Gather all of the foreign keys for a given type.
:param type: The type
:type type: str
:rtype: BaseCollection
"""
foreign = self._foreign_key
keys = (
BaseCollection.make(list(self._dictionary[type].... |
java | public static void init(AuthAPI authzAPI, AuthzFacade facade) throws Exception {
/**
* Get History
*/
authzAPI.route(GET,"/authz/hist/user/:user",API.HISTORY,new Code(facade,"Get History by User", true) {
@Override
public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) th... |
java | public int setBytes(int index, InputStream in, int length)
throws IOException
{
checkPositionIndexes(index, index + length, this.length);
index += offset;
int readBytes = 0;
do {
int localReadBytes = in.read(data, index, length);
if (localReadBytes... |
java | public static ThreadPoolExecutor newCachedThreadPool(int corePoolSize,
int maximumPoolSize) {
return new ThreadPoolExecutor(corePoolSize,
maximumPoolSize,
DateUtils.MILLISECONDS_PER_MINUTE,
TimeUnit.MILLISECONDS,
... |
python | def _pfp__set_watch(self, watch_fields, update_func, *func_call_info):
"""Subscribe to update events on each field in ``watch_fields``, using
``update_func`` to update self's value when ``watch_field``
changes"""
self._pfp__watch_fields = watch_fields
for watch_field in watch_fi... |
java | @Override
public String getUserAgent(){
String[] uas = new String[]{"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0",
"Mozilla/5.0 (... |
python | def get_spectrum_as_string(self, index):
"""
Reads m/z array and intensity array of the spectrum at specified location
from the binary file as a byte string. The string can be unpacked by the struct
module. To get the arrays as numbers, use getspectrum
:param index:
... |
java | public static int getLength(final List<TagAndLength> pList) {
int ret = 0;
if (pList != null) {
for (TagAndLength tl : pList) {
ret += tl.getLength();
}
}
return ret;
} |
python | def check_rollout(edits_service, package_name, days):
"""Check if package_name has a release on staged rollout for too long"""
edit = edits_service.insert(body={}, packageName=package_name).execute()
response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execu... |
python | def set_info(self, info):
""" set my state from the passed info """
idx = info.get(self.name)
if idx is not None:
self.__dict__.update(idx) |
python | def join_where(self, table, one, operator, two, type='inner'):
"""
Add a "join where" clause to the query
:param table: The table to join with, can also be a JoinClause instance
:type table: str or JoinClause
:param one: The first column of the join condition
:type one:... |
java | @Override
public void calcInnerBounds() {
final Insets INSETS = getInsets();
final int SIZE = (getWidth() - INSETS.left - INSETS.right) <= (getHeight() - INSETS.top - INSETS.bottom) ? (getWidth() - INSETS.left - INSETS.right) : (getHeight() - INSETS.top - INSETS.bottom);
if (!isFrameVisible(... |
java | public boolean removeBusHub(String name) {
Iterator<BusHub> iterator;
BusHub busHub;
iterator = this.validBusHubs.iterator();
while (iterator.hasNext()) {
busHub = iterator.next();
if (name.equals(busHub.getName())) {
iterator.remove();
busHub.setContainer(null);
busHub.setEventFirable(true);... |
python | def export(local=False, path="/tmp", format='qcow2'):
'''
Export an image description for Kiwi.
Parameters:
* **local**: Specifies True or False if the export has to be in the local file. Default: False.
* **path**: If `local=True`, then specifies the path where file with the Kiwi description is w... |
java | public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor ... |
java | public static <T> T pickRandom (Iterator<T> iter, int count, Random r)
{
if (count < 1) {
throw new IllegalArgumentException(
"Must have at least one element [count=" + count + "]");
}
for (int ii = 0, ll = getInt(count, r); ii < ll; ii++) {
iter.next... |
python | def get_resolution(pdb_id):
"""Quick way to get the resolution of a PDB ID using the table of results from the REST service
Returns infinity if the resolution is not available.
Returns:
float: resolution of a PDB ID in Angstroms
TODO:
- Unit test
"""
pdb_id = pdb_id.upper()
... |
java | private void notifyFactories(Object item) {
for(VisualizationProcessor f : factories) {
try {
f.processNewResult(this, item);
}
catch(Throwable e) {
LOG.warning("VisFactory " + f.getClass().getCanonicalName() + " failed:", e);
}
}
} |
java | private void addSupertypeEdges(ClassVertex vertex, LinkedList<XClass> workList) {
XClass xclass = vertex.getXClass();
// Direct superclass
ClassDescriptor superclassDescriptor = xclass.getSuperclassDescriptor();
if (superclassDescriptor != null) {
addInheritanceEdge(vertex, ... |
java | public void set(Point3D point1, Point3D point2, Point3D point3) {
this.p1.set(point1);
this.p2.set(point2);
this.p3.set(point3);
clearBufferedData();
} |
java | public boolean parse(ByteBuffer buffer) {
while (buffer.hasRemaining()) {
switch (state) {
case LENGTH: {
int octet = buffer.get() & 0xFF;
length = (length << 8) + octet;
if (++cursor == 3) {
length &... |
java | public CreateDBClusterEndpointRequest withStaticMembers(String... staticMembers) {
if (this.staticMembers == null) {
setStaticMembers(new com.amazonaws.internal.SdkInternalList<String>(staticMembers.length));
}
for (String ele : staticMembers) {
this.staticMembers.add(ele... |
python | def _set_peripheral_update(self, v, load=False):
"""
Setter method for peripheral_update, mapped from YANG variable /firmware/peripheral_update (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_peripheral_update is considered as a private
method. Backends l... |
python | def activated(self, value):
"""
Setter for **self.__activated** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value)
... |
python | def ldContains(self, what, key):
"""List/dictinary/missing-aware contains.
If the value is a "missing_value", we'll treat it as non-existent
so it will be overwritten by an empty list/dict when necessary to
assign child keys.
"""
if isListKey(key):
i = listKeyIndex(key)
return i < l... |
java | public static boolean isAllUpperCase(String str) {
if (str == null) return false;
boolean hasLetters = false;
char c;
for (int i = str.length() - 1; i >= 0; i--) {
c = str.charAt(i);
if (Character.isLetter(c)) {
if (!Character.isUpperCase(c)) return false;
hasLetters = true;
}
}
return h... |
java | @SuppressWarnings("unchecked")
@Override
public Boolean execute() {
for(int i = 0 ; i < agents.length ; i++) {
createRoom(i);
}
return Boolean.TRUE;
} |
python | def _set_intvals(kws, keys):
"""Convert keyword values to int."""
for key in keys:
if key in kws:
kws[key] = int(kws[key]) |
java | public static boolean isValidServiceId(String name) {
return name != null && name.length() > 0 && SERVICE_ID_REGEX.matcher(name).matches() && Character.isLetter(name.charAt(0));
} |
java | public static Timestamp plus(Timestamp self, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(self);
calendar.add(Calendar.DATE, days);
Timestamp ts = new Timestamp(calendar.getTime().getTime());
ts.setNanos(self.getNanos());
return ts;
} |
java | @Override
public String getPhone() {
StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(random.nextInt(9) + 1);
for (int i = 0; i < 2; i++) {
sb.append(random.nextInt(10));
}
sb.append(") ");
sb.append(random.nextInt(9) + 1);
for (int i = 0; i < 2; i++) {
sb.append(random.nextInt... |
java | @Nonnull
public EChange setUserPassword (@Nullable final String sUserID, @Nonnull final String sNewPlainTextPassword)
{
// Resolve user
final User aUser = getOfID (sUserID);
if (aUser == null)
{
AuditHelper.onAuditModifyFailure (User.OT, sUserID, "no-such-user-id", "password");
return EC... |
python | def _get_fault_type_dummy_variables(self, rake):
"""
Defines the fault type dummy variables for normal faulting (f_n) and
reverse faulting (f_r) from rake. Classification based on that
found in the original fortran code of Lin (2009)
"""
f_n, f_r = 0, 0
if rake >=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.