language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Nonnull
public CSSMediaList addMedia (@Nonnull final ICSSMediaList aMediaList)
{
ValueEnforcer.notNull (aMediaList, "MediaList");
m_aMedia.addAll (aMediaList.getAllMedia ());
return this;
} |
python | def refresh_stack(self):
"""
Recompute the stack after e.g. show_hidden_frames has been modified
"""
self.stack, _ = self.compute_stack(self.fullstack)
# find the current frame in the new stack
for i, (frame, _) in enumerate(self.stack):
if frame is self.curfr... |
java | public void setTitle(String title)
{
super.setTitle(title);
if ((this.widget instanceof TitleConfigurable) && (this.titledWidgetId == null))
((TitleConfigurable) this.widget).setTitle(title);
} |
java | public Object evaluate(Object pContext,
VariableResolver pResolver,
Map functions,
String defaultPrefix,
Logger pLogger)
throws ELException {
return mValue;
} |
python | def all_arch_srcarch_pairs():
"""
Generates all valid (ARCH, SRCARCH) tuples for the kernel, corresponding to
different architectures. SRCARCH holds the arch/ subdirectory.
"""
for srcarch in os.listdir("arch"):
# Each subdirectory of arch/ containing a Kconfig file corresponds to
# ... |
java | public static void encode (Writer writer, String string) throws IOException
{
encode(writer, string, false, true);
} |
python | def iter_graph(cur):
"""Iterate over all graphs in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
tuple: A 2-tuple containing:
list: The nodelist for a graph in the cache.
... |
python | def wrap_key(self, key):
"""Translate the key into the central cell
This method is only applicable in case of a periodic system.
"""
return tuple(np.round(
self.integer_cell.shortest_vector(key)
).astype(int)) |
java | public static Object invokeClosure(Object closure, Object[] arguments) throws Throwable {
return invokeMethodN(closure.getClass(), closure, "call", arguments);
} |
python | def cmd_serve(self, *args):
'''Serve the bin directory via SimpleHTTPServer
'''
try:
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
... |
java | public ObjectDataInput initDataSerializableInputAndSkipTheHeader(Data data) throws IOException {
ObjectDataInput input = createObjectDataInput(data);
byte header = input.readByte();
if (isFlagSet(header, IDS_FLAG)) {
skipBytesSafely(input, FACTORY_AND_CLASS_ID_BYTE_LENGTH);
}... |
python | def post(self, endpoint='', url='', data=None, use_api_key=False, omit_api_version=False):
"""Perform a post to an API endpoint.
:param string endpoint: Target endpoint. (Optional).
:param string url: Override the endpoint and provide the full url (eg for pagination). (Optional).
:param... |
python | def calc(self, maxiter=100, fixedprec=1e9):
"""Min Cost Flow"""
source_data_holder = []
N = self.targets.shape[0]
K = self.origins.shape[0]
# dict of labels for each target node
M, demand = self._get_demand_graph()
max_dist_trip = 400 # kilometers
cost_... |
python | def _create_font_choice_combo(self):
"""Creates font choice combo box"""
self.fonts = get_font_list()
self.font_choice_combo = \
_widgets.FontChoiceCombobox(self, choices=self.fonts,
style=wx.CB_READONLY, size=(125, -1))
self.font_cho... |
python | def segment_midpoints(neurites, neurite_type=NeuriteType.all):
'''Return a list of segment mid-points in a collection of neurites'''
def _seg_midpoint(sec):
'''Return the mid-points of segments in a section'''
pts = sec.points[:, COLS.XYZ]
return np.divide(np.add(pts[:-1], pts[1:]), 2.0)... |
python | def to_wgs84(east, north, crs):
""" Convert any CRS with (east, north) coordinates to WGS84
:param east: east coordinate
:type east: float
:param north: north coordinate
:type north: float
:param crs: CRS enum constants
:type crs: constants.CRS
:return: latitude and longitude coordinate... |
python | def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
opt = "setup"
... |
python | def reduce(vector):
"""
Can be a vector or matrix. If data are bool, sum Trues.
"""
if type(vector) is list: # matrix
return array(list(map(add.reduce, vector)))
else:
return sum(vector) |
python | def load_xml_conf(self, xml_file, id):
'''
Creates a new config from xml file.
:param xml_file: path to xml file. Format : nutch-site.xml or nutch-default.xml
:param id:
:return: config object
'''
# converting nutch-site.xml to key:value pairs
import xml.... |
python | def mode_string_v10(msg):
'''mode string for 1.0 protocol, from heartbeat'''
if msg.autopilot == mavlink.MAV_AUTOPILOT_PX4:
return interpret_px4_mode(msg.base_mode, msg.custom_mode)
if not msg.base_mode & mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED:
return "Mode(0x%08x)" % msg.base_mode
if... |
python | def _social_auth_login(self, request, **kwargs):
'''
View function that redirects to social auth login,
in case the user is not logged in.
'''
if request.user.is_authenticated():
if not request.user.is_active or not request.user.is_staff:
raise PermissionDenied()
else... |
java | @SuppressWarnings("unchecked")
public Class<? extends T> defineClass() {
if (generatedClass == null) {
synchronized (this) {
if (generatedClass == null) {
try {
// first check that the proxy has not already been created
... |
python | def __dict_to_BetterDict(self, attr):
"""Convert the passed attr to a BetterDict if the value is a dict
Returns: The new value of the passed attribute."""
if type(self[attr]) == dict:
self[attr] = BetterDict(self[attr])
return self[attr] |
python | def load_key_bindings(
get_search_state=None,
enable_abort_and_exit_bindings=False,
enable_system_bindings=False,
enable_search=False,
enable_open_in_editor=False,
enable_extra_page_navigation=False,
enable_auto_suggest_bindings=False):
"""
Create a Regist... |
java | Object processQNAME(
StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner)
throws org.xml.sax.SAXException
{
try
{
QName qname = new QName(value, handler, true);
return qname;
}
catch (Ille... |
java | public IPv4AddressSection replace(int startIndex, int endIndex, IPv4AddressSection replacement, int replacementStartIndex, int replacementEndIndex) {
return replace(startIndex, endIndex, replacement, replacementStartIndex, replacementEndIndex, false);
} |
java | public String getMenuLink(FieldList record)
{
FieldInfo field = record.getField("Type");
if ((field != null) && (!field.isNull()))
{
String strType = field.toString();
String strParams = record.getField("Params").toString();
if (strParams == null)
... |
java | private static TableModel entity2ModelWithConfig(Class<?> entityClass) {
TableModel model;
model = entity2ModelIgnoreConfigMethod(entityClass);
Method method = null;
try {
method = entityClass.getMethod("config", TableModel.class);
} catch (Exception e) {// NOSONAR
}
if (method != null)
try {
me... |
java | public void setEncoding(String charset) {
Validator.validate(!Validator.isBlank(charset), "encoding cannot be blank");
this.encoding = charset.trim();
} |
python | def listen_tta(self, target, timeout):
"""Listen as Type A Target is not supported."""
info = "{device} does not support listen as Type A Target"
raise nfc.clf.UnsupportedTargetError(info.format(device=self)) |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.IOB__OBJ_NAME:
return getObjName();
case AfplibPackage.IOB__OBJ_TYPE:
return getObjType();
case AfplibPackage.IOB__XOA_OSET:
return getXoaOset();
case AfplibPackage.IOB__YO... |
java | private void configureInputFormat(CsvInputFormat<?> format) {
format.setCharset(this.charset);
format.setDelimiter(this.lineDelimiter);
format.setFieldDelimiter(this.fieldDelimiter);
format.setCommentPrefix(this.commentPrefix);
format.setSkipFirstLineAsHeader(skipFirstLineAsHeader);
format.setLenient(ignore... |
java | private static void validateInput(ColumnType columnType) throws ExecutionException {
if (columnType == null) {
String messagge = "The ColumnType can not be null.";
LOGGER.error(messagge);
throw new ExecutionException(messagge);
}
} |
python | def save(self):
"""
:return: save this environment on Ariane server (create or update)
"""
LOGGER.debug("Environment.save")
post_payload = {}
consolidated_osi_id = []
if self.id is not None:
post_payload['environmentID'] = self.id
if self.nam... |
java | public void marshall(ListActionTypesRequest listActionTypesRequest, ProtocolMarshaller protocolMarshaller) {
if (listActionTypesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listActionTyp... |
java | public EntityRecognizerInputDataConfig withEntityTypes(EntityTypesListItem... entityTypes) {
if (this.entityTypes == null) {
setEntityTypes(new java.util.ArrayList<EntityTypesListItem>(entityTypes.length));
}
for (EntityTypesListItem ele : entityTypes) {
this.entityTypes.... |
java | protected boolean columnTypeMatches(ColumnType columnType, boolean allColumnsShouldMatchType,
String query, boolean debugPrint, String ... groups) {
// If columnType is NULL (unspecified), then no checking of column
// types is needed
if (columnType == nu... |
python | def complete(self, flag_message="Complete", padding=None, force=False):
""" Log Level: :attr:COMPLETE
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area... |
java | @Override
public int maximumSize(Container container,
List components,
FormLayout.Measure minMeasure,
FormLayout.Measure prefMeasure,
FormLayout.Measure defaultMeasure) {
int size = basis.maximumSize(container,
components,
minMe... |
java | private CmsContainerElementData getBaseElementData(CmsResource page, CmsContainerElementBean element)
throws CmsException {
CmsResourceUtil resUtil = new CmsResourceUtil(m_cms, element.getResource());
CmsContainerElementData elementData = new CmsContainerElementData();
setElementInfo(elemen... |
java | public Iterator<String> getBshIterator(final Character obj) {
Integer value = Integer.valueOf(obj.charValue());
int check = 33, start = 0;
for (int i : unicodeBlockStarts) if (check <= value) {
start = check;
check = i;
} else break;
return IntStream.range... |
java | public void setTemplateHome(File home) {
raw.put(HOME_TEMPLATE.getKey(), home);
data.put(HOME_TEMPLATE, home);
} |
python | def wait_on_event(event, timeout=None):
"""
Waits on a single threading Event, with an optional timeout.
This is here for compatibility reasons as python 2 can't reliably wait
on an event without a timeout and python 3 doesn't define a `maxint`.
"""
if timeout is not None:
event.wait(ti... |
java | public Queue<Pair<Env<AttrContext>, JCClassDecl>> desugar(Queue<Env<AttrContext>> envs) {
ListBuffer<Pair<Env<AttrContext>, JCClassDecl>> results = new ListBuffer<>();
for (Env<AttrContext> env: envs)
desugar(env, results);
return stopIfError(CompileState.FLOW, results);
}
H... |
java | @Override
public String getColumnName(final int col)
{
try
{
return columnsModel.getColumnNames()[col];
}
catch (Exception e)
{
log.log(Level.SEVERE, "Error occured on getting column name on index " + col + ".", e);
}
return null;
} |
python | def login(self, password):
"""Attempts to log in as the current user with given password"""
if self.logged_in:
raise RuntimeError("User already logged in!")
params = {"name": self.nick, "password": password}
resp = self.conn.make_api_call("login", params)
if "error"... |
java | public static StringBuilder appendFunctionArgs(StringBuilder sb, List<Term<?>> list) {
Term<?> prev = null, pprev = null;
for (Term<?> elem : list) {
boolean sep = true;
if (elem instanceof TermOperator && ((TermOperator) elem).getValue() == ',')
sep = f... |
java | @Override
public Dictionary<String, String> getHeaders() {
final String sourceMethod = "getHeaders"; //$NON-NLS-1$
boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(PlatformServicesImpl.class.getName(), sourceMethod);
}
Dictionary<String, String> result = null... |
python | def create(mcs, name, dict=None, object_name=None):
"""
Create a new :class:`Singleton` class
:param name: Name of the new class (Used in its __repr__ if no object_name)
:type name: str
:param dict: Optional dictionary of the classes' attributes
:type dict: Optional[Dict... |
python | def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
"""Calculate the bounding pressure and height in a layer.
Given pressure, optional heights, and a bound, return either the closest pressure/height
or interpolated pressure/height. If no heights are provided, a standard atmosph... |
python | def generate_displacements(self,
distance=0.01,
is_plusminus='auto',
is_diagonal=True,
is_trigonal=False):
"""Generate displacement dataset"""
displacement_directions = get_least_d... |
python | def create_stack_user(self):
"""Create the stack user on the machine.
"""
self.run('adduser -m stack', success_status=(0, 9))
self.create_file('/etc/sudoers.d/stack', 'stack ALL=(root) NOPASSWD:ALL\n')
self.run('mkdir -p /home/stack/.ssh')
self.run('cp /root/.ssh/authoriz... |
python | def red(cls):
"Make the text foreground color red."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_RED
cls._set_text_attributes(wAttributes) |
java | @Override
public IdentifyingToken validate(IdentifyingToken token, @Nullable ChargingStationId chargingStationId) {
if (chargingStationId == null) {
LOG.warn("No charging station id passed to validation request for token {}", token.getToken());
return token;
}
ChargingStation chargingStatio... |
java | public List<? extends Archive> asList(final Class<? extends Archive> archive) {
final List<Archive> archives = new ArrayList<>();
final GradleEffectiveDependencies gradleEffectiveDependencies = GradleRunner.getEffectiveDependencies(projectDirectory);
for (ScopeType scopeType : scopeTypesDependencies... |
python | def get_property(self):
"""
Returns the property of the variable
Example
-------------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_property()
{'bowel-problem': ['position = (335, 99)'],
'dog-out'... |
python | def AgregarDatosAutorizacion(self, nro_remito=None, cod_autorizacion=None, fecha_emision=None, fecha_vencimiento=None, **kwargs):
"Agrega la información referente a los datos de autorización del remito electrónico cárnico"
self.remito['datosEmision'] = dict(nroRemito=nro_remito, codAutorizacion=cod_auto... |
python | def check_file_type(files):
""" Check whether the input files are in fasta format, reads format or
other/mix formats.
"""
all_are_fasta = True
all_are_reads = True
all_are_empty = True
if sys.version_info < (3, 0):
if isinstance(files, (str, unicode)): files = [files]
else:
if is... |
python | def stat(self, path):
"""
Retrieve information about a file on the remote system. The return
value is an object whose attributes correspond to the attributes of
python's C{stat} structure as returned by C{os.stat}, except that it
contains fewer fields. An SFTP server may return... |
java | @Override
public <T> Query<T> createSqlQuery(Class<T> entityType, String sql) {
Assert.notNull(entityType, "entityType must not null");
Assert.hasText(sql, "sql must has text");
RawSqlBuilder rawSqlBuilder = RawSqlBuilder.parse(sql);
return ebeanServer.find(entityType).setRawSql... |
java | protected boolean narrowArguments(Object[] args) {
boolean narrowed = false;
for (int a = 0; a < args.length; ++a) {
Object arg = args[a];
if (arg instanceof Number) {
Object narg = narrow((Number) arg);
if (narg != arg) {
narrowed = true;
}
args[a] = narg;
... |
java | public static CompletableFuture<IMessageSender> createMessageSenderFromConnectionStringBuilderAsync(ConnectionStringBuilder amqpConnectionStringBuilder) {
Utils.assertNonNull("amqpConnectionStringBuilder", amqpConnectionStringBuilder);
return createMessageSenderFromEntityPathAsync(amqpConnectionStringBu... |
java | public void remoteTransactionCommitted(GlobalTransaction gtx, boolean onePc) {
boolean optimisticWih1Pc = onePc && (configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC);
if (configuration.transaction().transactionProtocol().isTotalOrder() || optimisticWih1Pc) {
removeRemoteTransacti... |
python | def batch(args):
"""
%prog batch all.cds *.anchors
Compute Ks values for a set of anchors file. This will generate a bunch of
work directories for each comparisons. The anchorsfile should be in the form
of specie1.species2.anchors.
"""
from jcvi.apps.grid import MakeManager
p = OptionP... |
java | public CreatePresetResponse createPreset(
String presetName, String container, Clip clip, Audio audio, Encryption encryption) {
return createPreset(presetName, null, container, false, clip, audio, null, encryption, null);
} |
python | def elem2json(elem, options, strip_ns=1, strip=1):
"""Convert an ElementTree or Element into a JSON string."""
if hasattr(elem, 'getroot'):
elem = elem.getroot()
if options.pretty:
return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), sort_keys=True, indent=4, separato... |
java | public static ChainableStatement keydown(JsScope jsScope)
{
return new DefaultChainableStatement(KeyboardEvent.KEYDOWN.getEventLabel(),
jsScope.render());
} |
java | private int minChildOrGrandchildWithComparator(int k) {
int gc = 4 * k;
int mingc;
K gcValue;
// 4 grandchilden
if (gc + 3 <= size) {
gcValue = array[gc];
mingc = gc;
if (comparator.compare(array[++gc], gcValue) < 0) {
gcValue ... |
java | protected Object createMyInstance() throws IOException {
// would like to uninherit from AbstractFactoryBean (but it's final!)
if (!isSingleton()) {
throw new RuntimeException("ReloadablePropertiesFactoryBean only works as singleton");
}
// set listener
reloadablePro... |
java | protected void setupBodyFileInfo(ExceptionMessageBuilder br, String bodyFile, String plainText) {
br.addItem("Body File");
br.addElement(bodyFile);
br.addItem("Plain Text");
br.addElement(plainText);
} |
java | public static Function<RSocket, RSocket> safeClose() {
return source ->
new RSocketProxy(source) {
final AtomicInteger count = new AtomicInteger();
final AtomicBoolean closed = new AtomicBoolean();
@Override
public Mono<Void> fireAndForget(Payload payload) {
... |
java | public static int compilerOptionsMapFromConfig(IConfig config, Map<AccessibleObject, List<Object>> resultMap) {
return compilerOptionsMapFromConfig(config, resultMap, false);
} |
python | def extension_context(extension_name='cpu', **kw):
"""Get the context of the specified extension.
All extension's module must provide `context(**kw)` function.
Args:
extension_name (str) : Module path relative to `nnabla_ext`.
kw (dict) : Additional keyword arguments for context function i... |
python | def decrypt(s, base64 = False):
"""
对称解密函数
"""
return _cipher().decrypt(base64 and b64decode(s) or s) |
python | def set_formatter(name, func):
"""Replace the formatter function used by the trace decorator to
handle formatting a specific kind of argument. There are several
kinds of arguments that trace discriminates between:
* instance argument - the object bound to an instance method.
* class argument - the... |
python | def sky2pix(self, skypos):
"""
Get the pixel coordinates for a given sky position (degrees).
Parameters
----------
skypos : (float,float)
ra,dec position in degrees.
Returns
-------
x,y : float
Pixel coordinates.
"""
... |
python | def submit(self, method, method_args=(), method_kwargs={}, done_callback=None, done_kwargs={}, loop=None):
'''
used to send async notifications
:param method:
:param method_args:
:param method_kwargs:
:param done_callback:
:param done_kwargs:
:param loop:
... |
java | public static com.liferay.commerce.model.CommerceAddressRestriction createCommerceAddressRestriction(
long commerceAddressRestrictionId) {
return getService()
.createCommerceAddressRestriction(commerceAddressRestrictionId);
} |
python | def get_readme():
'Get the long description from the README file'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as my_fd:
result = my_fd.read()
return result |
python | def main():
"""
NAME
eqarea_magic.py
DESCRIPTION
makes equal area projections from declination/inclination data
SYNTAX
eqarea_magic.py [command line options]
INPUT
takes magic formatted sites, samples, specimens, or measurements
OPTIONS
-h prints help me... |
python | def get_runtime_vars(varset, experiment, token):
'''get_runtime_vars will return the urlparsed string of one or more runtime
variables. If None are present, None is returned.
Parameters
==========
varset: the variable set, a dictionary lookup with exp_id, token, vars
experiment... |
java | public boolean upgradeLock(LockEntry reader)
{
checkTimedOutLocks();
String oidString = reader.getOidString();
ObjectLocks objectLocks = null;
synchronized (locktable)
{
objectLocks = (ObjectLocks) locktable.get(oidString);
}
if (objectLo... |
python | def gauss_fltr_opencv(dem, size=3, sigma=1):
"""OpenCV Gaussian filter
Still propagates NaN values
"""
import cv2
dem = malib.checkma(dem)
dem_cv = cv2.GaussianBlur(dem.filled(np.nan), (size, size), sigma)
out = np.ma.fix_invalid(dem_cv)
out.set_fill_value(dem.fill_value)
return out |
java | public static boolean runWithSleepThrowOnInterrupt(long milliseconds, Runnable runnable) {
Assert.isTrue(milliseconds > 0, "Milliseconds [%d] must be greater than 0", milliseconds);
runnable.run();
if (!ThreadUtils.sleep(milliseconds, 0)) {
throw new SleepDeprivedException(String.format("Failed to ... |
java | private IConfigurationElement getParserWithHeighestPriority(
String natureId, IConfigurationElement[] config)
{
IConfigurationElement selectedParser = null;
int selectedParserPriority = 0;
for (IConfigurationElement e : config)
{
if (e.getAttribute("nature").equals(natureId))
{
if (selectedParser ... |
python | def get_display(display):
"""dname, protocol, host, dno, screen = get_display(display)
Parse DISPLAY into its components. If DISPLAY is None, use
the default display. The return values are:
DNAME -- the full display name (string)
PROTOCOL -- the protocol to use (None if automatic)
H... |
python | def marvcli_comment_add(user, message, datasets):
"""Add comment as user for one or more datasets"""
app = create_app()
try:
db.session.query(User).filter(User.name==user).one()
except NoResultFound:
click.echo("ERROR: No such user '{}'".format(user), err=True)
sys.exit(1)
id... |
java | @Exported
public String getDescription() {
Set<Node> nodes = getNodes();
if(nodes.isEmpty()) {
Set<Cloud> clouds = getClouds();
if(clouds.isEmpty())
return Messages.Label_InvalidLabel();
return Messages.Label_ProvisionedFrom(toString(clouds));
... |
java | @SuppressWarnings("rawtypes")
@WithBridgeMethods(value = SQLInsertClause.class, castRequired = true)
public <T> C populate(T obj, Mapper<T> mapper) {
Map<Path<?>, Object> values = mapper.createMap(entity, obj);
for (Map.Entry<Path<?>, Object> entry : values.entrySet()) {
set((Path) e... |
java | private <T> T pluginProxy(final Class<T> type) {
Object proxy = Proxy.newProxyInstance(classLoader, new Class<?>[]{type}, new InvocationHandler() {
@Override
public Object invoke(Object target, Method method, Object[] args) throws Throwable {
for (Object plugin : getPlugi... |
java | @Override
public void close() throws IOException {
if (upload != null) {
flush();
// close the connection
try {
upload.close();
} catch (SQLException e) {
LOG.info("JDBC statement could not be closed: " + e.getMessage());
} finally {
upload = null;
}
}
if (dbConn != null) {
try ... |
python | def loads(self, value):
"""
Deserialize value using ``msgpack.loads``.
:param value: bytes
:returns: obj
"""
raw = False if self.encoding == "utf-8" else True
if value is None:
return None
return msgpack.loads(value, raw=raw, use_list=self.use... |
python | def is_siemens(dicom_input):
"""
Use this function to detect if a dicom series is a siemens dataset
:param dicom_input: directory with dicom files for 1 scan
"""
# read dicom header
header = dicom_input[0]
# check if manufacturer is Siemens
if 'Manufacturer' not in header or 'Modality'... |
python | def validate_django_compatible_with_python():
"""
Verify Django 1.11 is present if Python 2.7 is active
Installation of pinax-cli requires the correct version of Django for
the active Python version. If the developer subsequently changes
the Python version the installed Django may no longer be comp... |
java | public static void copyMergedOutput (Logger target, String name, Process process)
{
new StreamReader(target, name + " output", process.getInputStream()).start();
} |
java | private synchronized void returnTransport(Transport returning) {
long now = System.currentTimeMillis();
PooledTransport unwrapped;
// check if they're returning a leased transport
if (returning instanceof LeasedTransport) {
LeasedTransport leasedTransport = (LeasedTransport)... |
java | @Override
public List<CommerceCountry> findByG_B_A(long groupId,
boolean billingAllowed, boolean active, int start, int end,
OrderByComparator<CommerceCountry> orderByComparator) {
return findByG_B_A(groupId, billingAllowed, active, start, end,
orderByComparator, true);
} |
python | def run_script(script_path, cwd='.'):
"""Execute a script from a working directory.
:param script_path: Absolute path to the script to run.
:param cwd: The directory to run the script from.
"""
run_thru_shell = sys.platform.startswith('win')
if script_path.endswith('.py'):
script_comman... |
python | def get_paginated_response(self, data):
"""
Annotate the response with pagination information
"""
metadata = {
'next': self.get_next_link(),
'previous': self.get_previous_link(),
'count': self.get_result_count(),
'num_pages': self.get_num_p... |
java | private TimeUnit getPollUnit() {
String unit = mProperties.getProperty(CSV_KEY_UNIT);
if (unit == null) {
unit = CSV_DEFAULT_UNIT;
}
return TimeUnit.valueOf(unit.toUpperCase());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.