language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static void pause(Context context, String clientId) {
Intent intent = new Intent(context, PlaybackService.class);
intent.setAction(ACTION_PAUSE_PLAYER);
intent.putExtra(BUNDLE_KEY_SOUND_CLOUD_CLIENT_ID, clientId);
context.startService(intent);
} |
java | public final Iterable<T> getScheduledTasks() {
return Iterables.transform(this.cancellableTaskMap.asMap().values(), new Function<CancellableTask<K, T>, T>() {
@Override
public T apply(CancellableTask<K, T> cancellableTask) {
return cancellableTask.getScheduledTask();
}
});
} |
python | def info_gain(current_impurity, true_branch, false_branch, criterion):
"""Information Gain.
The uncertainty of the starting node, minus the weighted impurity of
two child nodes.
"""
measure_impurity = gini_impurity if criterion == "gini" else entropy
p = float(len(true_branch)) / (len(true... |
python | def run_process(self, process):
"""Runs a single action."""
message = u'#{bright}'
message += u'{} '.format(str(process)[:68]).ljust(69, '.')
stashed = False
if self.unstaged_changes and not self.include_unstaged_changes:
out, err, code = self.git.stash(keep_index=Tr... |
python | def get_mode(self):
"""Gets the mode of the score.
If this system is based on grades, the mode of the output score
is returned.
return: (decimal) - the median score
*compliance: mandatory -- This method must be implemented.*
"""
# http://stackoverflow.com/quest... |
java | private void readProcCpuInfoFile() {
// This directory needs to be read only once
if (readCpuInfoFile) {
return;
}
// Read "/proc/cpuinfo" file
BufferedReader in = null;
FileReader fReader = null;
try {
fReader = new FileReader(procfsCpuFile);
in = new BufferedReader(fReade... |
java | private boolean isNormal() {
if (getNameCount() == 0 || (getNameCount() == 1 && !isAbsolute())) {
return true;
}
boolean foundNonParentName = isAbsolute(); // if there's a root, the path doesn't start with ..
boolean normal = true;
for (Name name : names) {
if (name.equals(Name.PARENT))... |
python | def run(self):
"""Runs the thread
This method handles sending the heartbeat to the Discord websocket server, so the connection
can remain open and the bot remain online for those commands that require it to be.
Args:
None
"""
while self.should_run:
... |
python | def iterkeys(self):
"Returns an iterator over the keys of ConfigMap."
return chain(self._pb.StringMap.keys(),
self._pb.IntMap.keys(),
self._pb.FloatMap.keys(),
self._pb.BoolMap.keys()) |
python | def _unscramble_regressor_columns(parent_data, data):
"""Reorder the columns of a confound matrix such that the columns are in
the same order as the input data with any expansion columns inserted
immediately after the originals.
"""
matches = ['_power[0-9]+', '_derivative[0-9]+']
var = OrderedDi... |
java | @Override
public void send(final CEMI frame, final BlockingMode mode) throws KNXConnectionClosedException
{
if (frame.getMessageCode() != CEMILData.MC_LDATA_IND)
throw new KNXIllegalArgumentException("cEMI frame is not an L-Data.ind");
try {
if (loopbackEnabled) {
synchronized (loopbackFrames) {
lo... |
python | def get_monitor_physical_size(monitor):
"""
Returns the physical size of the monitor.
Wrapper for:
void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height);
"""
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
... |
python | def close(self):
"""
Deletes this Ethernet switch.
"""
yield from self._telnet.close()
self._telnet_server.close()
for nio in self._nios.values():
if nio:
yield from nio.close()
self.manager.port_manager.release_tcp_port(self._... |
python | def add_record_references(self, app_id, record_id, field_id, target_record_ids):
"""Bulk operation to directly add record references without making any additional requests
Warnings:
Does not perform any app, record, or target app/record validation
Args:
app_id (str): Fu... |
java | public void addValues(String name, List<V> values) {
List<V> lo = get(name);
if (lo == null) {
lo = new ArrayList<>();
}
lo.addAll(values);
put(name, lo);
} |
python | def _parse_port_ranges(pool_str):
"""Given a 'N-P,X-Y' description of port ranges, return a set of ints."""
ports = set()
for range_str in pool_str.split(','):
try:
a, b = range_str.split('-', 1)
start, end = int(a), int(b)
except ValueError:
log.error('Ig... |
java | public void addAttributeValue(final String attributeName, final Value attributeValue, Environment in) {
if (in == null)
in = GlobalEnvironment.INSTANCE;
Attribute attr = attributes.get(attributeName);
if (attr == null) {
attr = new Attribute(attributeName);
attributes.put(attr.getName(), attr);
}
att... |
python | def _ScanFileSystem(self, scan_node, base_path_specs):
"""Scans a file system scan node for file systems.
This method checks if the file system contains a known Windows directory.
Args:
scan_node (SourceScanNode): file system scan node.
base_path_specs (list[PathSpec]): file system base path s... |
python | def decipher(self,string):
"""Decipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).decipher(ciphertext)
:param string: The string to decipher.... |
python | def check_npndarray(val, dtype=None, writeable=True, verbose=True):
"""Check if input object is a numpy array.
Parameters
----------
val : np.ndarray
Input object
"""
if not isinstance(val, np.ndarray):
raise TypeError('Input is not a numpy array.')
if ((not isinstance(dt... |
java | public static void multTransAB(double alpha , DMatrix1Row a , DMatrix1Row b , DMatrix1Row c )
{
// TODO add a matrix vectory multiply here
if( a.numCols >= EjmlParameters.MULT_TRANAB_COLUMN_SWITCH ) {
MatrixMatrixMult_DDRM.multTransAB_aux(alpha, a, b, c, null);
} else {
... |
python | def require(f):
'''
The @require decorator, usable in an immutable class (see immutable), specifies that the
following function is actually a validation check on the immutable class. These functions
will appear as static members of the class and get called automatically when the relevant
data change... |
python | def set_current_editor(self, file):
"""
Focus the **Script_Editor_tabWidget** Widget tab Model editor with given file.
:param file: File.
:type file: unicode
:return: Method success.
:rtype: bool
"""
index = self.find_editor_tab(file)
if index is... |
java | public static CellStyle createDefaultCellStyle(Workbook workbook) {
final CellStyle cellStyle = workbook.createCellStyle();
setAlign(cellStyle, HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
setBorder(cellStyle, BorderStyle.THIN, IndexedColors.BLACK);
return cellStyle;
} |
python | def json(self, *, # type: ignore
loads: Callable[[Any], Any]=json.loads) -> None:
"""Return parsed JSON data.
.. versionadded:: 0.22
"""
return loads(self.data) |
python | def set_impact_state(self):
"""We just go an impact, so we go unreachable
But only if we enable this state change in the conf
:return: None
"""
cls = self.__class__
if cls.enable_problem_impacts_states_change:
logger.debug("%s is impacted and goes UNREACHABLE... |
python | def checksum(path, hashfunc="md5"):
"""Return checksum of files given by path.
Wildcards can be used in check sum. Function is strongly dependent on checksumdir package by 'cakepietoast'.
:param path: path of files to get hash from
:param hashfunc: function used to get hash, default 'md5'
:return:... |
python | def _or_join(self, terms):
""" Joins terms using OR operator.
Args:
terms (list): terms to join
Examples:
self._or_join(['term1', 'term2']) -> 'term1 | term2'
Returns:
str
"""
from six import text_type
if isinstance(terms, (... |
python | def create_file_new_actions(self, fnames):
"""Return actions for submenu 'New...'"""
if not fnames:
return []
new_file_act = create_action(self, _("File..."),
icon=ima.icon('filenew'),
triggered=lambda:
... |
python | def create(name, **params):
'''
Function to create device in Server Density. For more info, see the `API
docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
CLI Example:
.. code-block:: bash
salt '*' serverdensity_device.create lama
salt '*' serverden... |
python | def _scale_enum(anchor, scales):
"""
Enumerate a set of anchors for each scale wrt an anchor.
"""
w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor)
ws = w * scales
hs = h * scales
anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr)
return anchors |
python | def orng_type(self, table_name, col):
'''
Returns an Orange datatype for a given mysql column.
:param table_name: target table name
:param col: column to determine the Orange datatype
'''
mysql_type = self.types[table_name][col]
n_vals = len(self.db.col_v... |
java | public List<LabeledUtterance> list(UUID appId, String versionId, ListExamplesOptionalParameter listOptionalParameter) {
return listWithServiceResponseAsync(appId, versionId, listOptionalParameter).toBlocking().single().body();
} |
java | public final void helpComplete(int maxTasks) {
Thread t;
ForkJoinWorkerThread wt;
if (maxTasks > 0 && status >= 0) {
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
(wt = (ForkJoinWorkerThread) t).pool.helpComplete(wt.workQueue, this, maxTasks);
else
ForkJoinPoo... |
java | public ConnectedCrud<T, K> table(DataSource dataSource, String table) throws SQLException {
Connection connection = dataSource.getConnection();
try {
return new ConnectedCrud<T, K>(new DataSourceTransactionTemplate(dataSource), table(connection, table));
} finally {
conne... |
java | protected boolean needsPropertyChangeSupport(ClassNode declaringClass, SourceUnit sourceUnit) {
boolean foundAdd = false, foundRemove = false, foundFire = false;
ClassNode consideredClass = declaringClass;
while (consideredClass!= null) {
for (MethodNode method : consideredClass.getM... |
python | def get_thumbnail_image(self, page=1):
"""
Downloads and returns the thumbnail sized image of a single page.
The page kwarg specifies which page to return. One is the default.
"""
url = self.get_thumbnail_image_url(page=page)
return self._get_url(url) |
java | private double[] parseVector(String s) {
String[] entries = WHITESPACE_PATTERN.split(s);
double[] d = new double[entries.length];
for(int i = 0; i < entries.length; i++) {
try {
d[i] = ParseUtil.parseDouble(entries[i]);
}
catch(NumberFormatException e) {
throw new AbortExce... |
java | public <E> E deserialize(final String str, final Class<E> type, final Collection<Converter<?>> converters) {
logger.debug("deserialize(\"{}\", {})", str, type);
if (converters == null || converters.isEmpty()) {
// when possible, just reuse the base converter
@SuppressWarnings("u... |
java | public synchronized CounterGroup getGroup(String groupName) {
CounterGroup grp = groups.get(groupName);
if (grp == null) {
grp = new CounterGroup(groupName);
groups.put(groupName, grp);
}
return grp;
} |
java | public void banUser(Jid jid, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
changeAffiliationByAdmin(jid, MUCAffiliation.outcast, reason);
} |
java | @Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case SimpleAntlrPackage.PARAMETER__TYPE:
return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type);
case SimpleAntlrPackage.PARAMETER__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_E... |
java | public IntIterator getIntIterator() {
return new IntIterator() {
int wordindex;
int i = 0;
IntArray buf;
int currentword;
public IntIterator init(IntArray b) {
this.buf = b;
this.wordindex = this.buf.get(this.i);
this.currentword = this.buf.get(this.i + 1);
return this;
}
@Overr... |
java | @Override
public ResetJobBookmarkResult resetJobBookmark(ResetJobBookmarkRequest request) {
request = beforeClientExecution(request);
return executeResetJobBookmark(request);
} |
java | @Override
public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
Cache<ResultSet, String[]> cache = localColNames.get();
try {
String[] colLabels = cache.get(rs, () -> {
return JdbcHelper.extractColumnLabels(rs);
});
Map<... |
python | def cross_entropy_error(self, input_data, targets, average=True,
cache=None, prediction=False,
sum_errors=True):
""" Computes the cross-entropy error for all tasks.
"""
loss = []
if cache is None:
cache = self.n_tasks *... |
java | public boolean compareOneScreenshot(File baseImg, File targetImg, int rows, int columns) {
boolean match = true;
BufferedImage[][] baseBfImg = splitImage(baseImg, rows, columns);
BufferedImage[][] targetBfImg = splitImage(targetImg, rows, columns);
BufferedImage[][] diffImg = new... |
java | public static void closeAll(Logger log, java.io.Closeable... closeables) {
for (java.io.Closeable c : closeables) {
if (c != null) {
try {
if (log != null) {
log.debug("Closing {}", c);
}
c.close();
} catch (Exception e) {
if (log != null && ... |
java | private void traverse(final Path path, final boolean watch, final boolean remove) {
log.debug("traverse start. path : {}, watch : {}, remove : {}", path, watch, remove);
if (Files.notExists(path)) {
return;
}
if (Files.isDirectory(path)) {
if (validPath(path)) {
try (DirectoryStream<Path> ds = Files.n... |
java | public static String read(Container container, String ddPath) {
if (container == null || ddPath == null) {
return "";
}
Entry entry = container.getEntry(ddPath);
if (entry == null) {
throw new IllegalStateException(ddPath);
}
InputStream input;
... |
java | public HFCAAffiliationResp create(User registrar, boolean force) throws AffiliationException, InvalidArgumentException {
if (registrar == null) {
throw new InvalidArgumentException("Registrar should be a valid member");
}
String createURL = "";
try {
createURL = ... |
java | public static ObjectTypeAttributeDefinition.Builder getAttributeBuilder(boolean allowNull, boolean referenceCredentialStore) {
AttributeDefinition csAttr = referenceCredentialStore ? credentialStoreAttributeWithCapabilityReference : credentialStoreAttribute;
return getAttributeBuilder(CREDENTIAL_REFEREN... |
java | public Byte getGroupingByte(String label) {
PrimitiveObject o = getPrimitiveObject(KEY, label, ObjectUtil.BYTE, "Byte");
if (o == null) {
return null;
}
return (Byte) o.getObject();
} |
python | def get_db(db, ip='localhost', port=27017, user=None, password=None):
'''
Returns a pymongo Database object.
.. note:
Both ``user`` and ``password`` are required when connecting to a MongoDB
database that has authentication enabled.
Arguments:
db (str): Name of the MongoDB da... |
python | def add_tracks(self, subtracks):
"""
Add one or more tracks to this view.
subtracks : Track or iterable of Tracks
A single Track instance or an iterable of them.
"""
if isinstance(subtracks, Track):
subtracks = [subtracks]
for subtrack in subtrack... |
java | protected boolean isMySQLDatabase() throws HandlerException {
String dbName = determineDatabaseType();
if (dbName == null) {
return false;
}
return "MySQL".equalsIgnoreCase(dbName);
} |
java | private byte[] fetchDecoderOutput() {
final CompositeByteBuf decoded = Unpooled.compositeBuffer();
for (;;) {
final ByteBuf buf = decoder.readInbound();
if (buf == null) {
break;
}
if (!buf.isReadable()) {
buf.release();
... |
java | public void onGeometryIndexSnappingEnd(GeometryIndexSnappingEndEvent event) {
for (GeometryIndex index : event.getIndices()) {
update(event.getGeometry(), index, false);
}
} |
python | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'dig... |
python | def create_token_response(self, request, token_handler):
"""Return token or error in json format.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param token_handler: A token handler instance, for example of type
oauthlib.oauth2.Be... |
python | def add(self, phrase, id=None):
"""
Adds a new phrase to the dictionary
:param phrase: the new phrase as a list of tokens
:param phrase_id: optionally the phrase_id can be set on addition. Beware, if you set one id you should set
them all as the auto-generated ids do not tak... |
python | def discrete(self, vertices, count=None, scale=1.0):
"""
Discretize the B-Spline curve.
Parameters
-------------
vertices : (n, 2) or (n, 3) float
Points in space
scale : float
Scale of overall drawings (for precision)
count : int
Nu... |
python | def extendSection(self, sectionIndex, data):
"""
Extends an existing section in the L{PE} instance.
@type sectionIndex: int
@param sectionIndex: The index for the section to be extended.
@type data: str
@param data: The data to include in the section.
... |
java | public void process( T image , GrayS32 output ) {
InputSanityCheck.checkSameShape(image,output);
stopRequested = false;
// long time0 = System.currentTimeMillis();
search.process(image);
if( stopRequested ) return;
// long time1 = System.currentTimeMillis();
FastQueue<float[]> regionColor = search.getMo... |
python | def write_to_buffer(self, buf):
"""Save the context to a buffer."""
doc = self.to_dict()
if config.rxt_as_yaml:
content = dump_yaml(doc)
else:
content = json.dumps(doc, indent=4, separators=(",", ": "))
buf.write(content) |
java | public AVQuery<T> whereMatchesKeyInQuery(String key, String keyInQuery, AVQuery<?> query) {
Map<String, Object> inner = new HashMap<String, Object>();
inner.put("className", query.getClassName());
inner.put("where", query.conditions.compileWhereOperationMap());
if (query.conditions.getSkip() > 0) inner.... |
python | def _generate_tokens(self, text):
"""
Generates tokens for the given code.
"""
# This is technically an undocumented API for Python3, but allows us to use the same API as for
# Python2. See http://stackoverflow.com/a/4952291/328565.
for index, tok in enumerate(tokenize.generate_tokens(io.StringI... |
python | def create_multireddit(self, name, description_md=None, icon_name=None,
key_color=None, subreddits=None, visibility=None,
weighting_scheme=None, overwrite=False,
*args, **kwargs): # pylint: disable=W0613
"""Create a new multireddi... |
java | private void error(String expected, String actual) {
if (!recovering) {
recovering = true;
final String outputString = (EOF_STRING.equals(actual) || UNTERMINATED_COMMENT_STRING.equals(actual) || COMMENT_NOT_ALLOWED.equals(actual)) ? actual : "'"
+ actual + "'";
... |
java | public void getWvWAbilityInfo(int[] ids, Callback<List<WvWAbility>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getWvWAbilityInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case XbasePackage.XFOR_LOOP_EXPRESSION__FOR_EXPRESSION:
return getForExpression();
case XbasePackage.XFOR_LOOP_EXPRESSION__EACH_EXPRESSION:
return getEachExpression();
case XbasePackage.XFOR_LOOP... |
python | def save_local_scope(
self,
line_number,
saved_function_call_index
):
"""Save the local scope before entering a function call by saving all the LHS's of assignments so far.
Args:
line_number(int): Of the def of the function call about to be entered into.
... |
java | @PublicEvolving
@Deprecated
public <ACC, R> SingleOutputStreamOperator<R> fold(ACC initialValue, FoldFunction<T, ACC> foldFunction, WindowFunction<ACC, R, K, W> function) {
TypeInformation<ACC> foldAccumulatorType = TypeExtractor.getFoldReturnTypes(foldFunction, input.getType(),
Utils.getCallLocationName(), tru... |
java | public void removeObect(StringKey skey) {
if (skey == null || cache == null)
return;
cache.remove(skey.getKey());
} |
java | static void init(String configName) {
MAIN = DbKit.getConfig(configName).dbProFactory.getDbPro(configName); // new DbPro(configName);
map.put(configName, MAIN);
} |
python | def defines(self, id, domain='messages'):
"""
Checks if a message has a translation (it does not take into account
the fallback mechanism).
@rtype: bool
@return: true if the message has a translation, false otherwise
"""
assert isinstance(id, (str, unicode))
... |
java | public FirefoxProfile getFirefoxProfile() {
if (firefoxProfile == null) {
firefoxProfile = new FirefoxProfile();
firefoxProfile.setAcceptUntrustedCertificates(true);
firefoxProfile.setAssumeUntrustedCertificateIssuer(false);
/* default download folder, set to 2 ... |
java | public static void removeLocalBundle(String name, Version version, boolean removePhysical, boolean doubleTap) throws BundleException {
name = name.trim();
CFMLEngine engine = CFMLEngineFactory.getInstance();
CFMLEngineFactory factory = engine.getCFMLEngineFactory();
BundleFile bf = _getBundleFile(factory, name, ve... |
python | def buildcontainer(self):
"""generate HTML div"""
if self.container:
return
# Create HTML div with style
if self.options['chart'].width:
if str(self.options['chart'].width)[-1] != '%':
self.div_style += 'width:%spx;' % self.options['chart'].width
... |
python | def instrument(self,
container: Container
) -> None:
"""
Instruments the program inside the container for computing test suite
coverage.
Params:
container: the container that should be instrumented.
"""
path = "containers... |
java | public void run() {
try {
final byte[] buffer = new byte[512 * 1024];
while (!this.closed.get()) {
//
int r = this.is.read(buffer, 0, buffer.length);
if (r < 0) throw new EOFException();
//
int offs... |
python | def convert(model, features, target):
"""Convert a Support Vector Regressor (SVR) model to the protobuf spec.
Parameters
----------
model: SVR
A trained SVR encoder model.
feature_names: [str]
Name of the input columns.
target: str
Name of the output column.
Return... |
java | @Nonnull
public DigestAuthServerBuilder setNonce (@Nonnull final String sNonce)
{
if (!HttpStringHelper.isQuotedTextContent (sNonce))
throw new IllegalArgumentException ("nonce is invalid: " + sNonce);
m_sNonce = sNonce;
return this;
} |
python | def normalize(self, text):
""" Normalizes text.
Converts to lowercase,
Unicode NFC normalization
and removes mentions and links
:param text: Text to be normalized.
"""
#print 'Normalize...\n'
text = text.lower()
text = unicodedata.... |
java | public Properties getAttributes(Attributes attrs) {
Properties attributes = new Properties();
attributes.putAll(attributeValues);
if (defaultContent != null) {
attributes.put(ElementTags.ITEXT, defaultContent);
}
if (attrs != null) {
for (int i = 0; i < at... |
python | def y(self,*args,**kwargs):
"""
NAME:
y
PURPOSE:
return y
INPUT:
t - (optional) time at which to get y
ro= (Object-wide default) physical scale for distances to use to convert
use_physical= use to override Object-wide default for usi... |
python | def field_to_dict(fields):
"""
Build dictionnary which dependancy for each field related to "root"
fields = ["toto", "toto__tata", "titi__tutu"]
dico = {
"toto": {
EMPTY_DICT,
"tata": EMPTY_DICT
},
"titi" : {
... |
java | public String getErrorString() {
StringBuilder ret = new StringBuilder();
if (hasExceptions()) {
for (Exception ex : exceptions) {
ret.append(HBCIUtils.exception2StringShort(ex));
ret.append(System.getProperty("line.separator"));
}
}
... |
python | def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
... |
python | def hicpro_contact_chart (self):
""" Generate the HiC-Pro interaction plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['cis_shortRange'] = { 'color': '#0039e6', 'name': 'Unique: cis <= 20Kbp' }
keys['cis_longRange'] = { 'color': '#809ff... |
java | public ClientWmsLayerInfo createClientWmsLayerInfo(WmsSelectedLayerInfo wmsSelectedLayerInfo, MapWidget mapWidget) {
WmsLayerConfiguration wmsConfig = new WmsLayerConfiguration();
wmsConfig.setFormat("image/png");
wmsConfig.setLayers(wmsSelectedLayerInfo.getWmsLayerInfo().getName());
wmsConfig.setVersion(wmsSel... |
python | def features_tags_parse_str_to_dict(obj):
"""
Parse tag strings of all features in the collection into a Python
dictionary, if possible.
"""
features = obj['features']
for i in tqdm(range(len(features))):
tags = features[i]['properties'].get('tags')
if tags is not None:
... |
python | def savef(self, format, *args):
"""
Equivalent to zconfig_save, taking a format string instead of a fixed
filename.
"""
return lib.zconfig_savef(self._as_parameter_, format, *args) |
python | def element_href(name):
""" Get specified element href by element name
:param name: name of element
:return: string href location of object, else None
"""
if name:
element = fetch_meta_by_name(name)
if element.href:
return element.href |
java | public static <V> V runWithMock(EbeanServer mock, Callable<V> test) throws Exception {
return start(mock).run(test);
} |
python | def request_finished_callback(sender, **kwargs):
"""This function logs if the user acceses the page"""
logger = logging.getLogger(__name__)
level = settings.AUTOMATED_LOGGING['loglevel']['request']
user = get_current_user()
uri, application, method, status = get_current_environ()
excludes = se... |
java | public void play(Module module, int source, boolean loop, boolean start) {
this.source = source;
this.loop = loop;
this.module = module;
done = false;
ibxm = new IBXM(48000);
ibxm.set_module(module);
songDuration = ibxm.calculate_song_duration();
if (bufferNames != null) {
AL10.alSourceStop(sourc... |
java | public ModuleInfo getModuleInfo(final String moduleName) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClass... |
python | def _list_files(self, args):
'''
List files for an installed package
'''
if len(args) < 2:
raise SPMInvocationError('A package name must be specified')
package = args[-1]
files = self._pkgdb_fun('list_files', package, self.db_conn)
if files is None:
... |
java | @Override
protected String resolveField(Field field)
{
final String fallBackName = field.getName();
final String resourceName = field.getAnnotation(Resource.class).name();
return getName(resourceName, fallBackName);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.