language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void backup(final File storageDir) throws BackupException
{
LOG.info("Start to backup lucene indexes of the workspace '"+workspaceName+"'");
try
{
final File indexDir = getIndexDirectory();
SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<V... |
java | public void setDistanceInstancePool(DistanceInstanceIterator it)
{
// need to save out the i-th field, if it's been prepared.
List buffer = asMultiDistanceInstanceList(it);
if (buffer.size()==0) return;
MyMultiDistanceInstance instance = (MyMultiDistanceInstance)buffer.get(0);
MultiStringWrapper prototype =... |
python | def api_related(self, query):
'''
Find related objects through SoltraEdge API
'''
url = "{0}/{1}/related/?format=json".format(self.base_url, query)
response = requests.get(url, headers=self.headers, verify=self.verify_ssl)
if response.status_code == 200:
ret... |
python | def clear_restore_points(self, name=None):
'''Deleting all/a configuration restore points/point.
Parameters
----------
name : str
Name of the restore point to be deleted. If not given, all restore points will be deleted.
'''
if name is None:
... |
java | @Pure
public static <P1, P2> Procedure1<P2> curry(final Procedure2<? super P1, ? super P2> procedure, final P1 argument) {
if (procedure == null)
throw new NullPointerException("procedure");
return new Procedure1<P2>() {
@Override
public void apply(P2 p) {
procedure.apply(argument, p);
}
};
} |
python | def send(self):
"""Send this message to the controller."""
self._file.write(self.as_bytes())
self._file.write(b'\r\n') |
python | def split_text(text, separators=re.compile('\s'), brackets=None, strip=False):
"""Split text along the separators unless they appear within brackets.
:param separators: An iterable single characters or a compiled regex pattern.
:param brackets: `dict` mapping start tokens to end tokens of what is to be \
... |
java | public V replace(K key, V val) {
// synchronized( this ) {
if( !containsKey(key) ) {
return null;
}
return put(key, val);
//}
} |
python | def to_bool(text):
'''
Convert the string name of a boolean to that boolean value.
'''
downcased_text = six.text_type(text).strip().lower()
if downcased_text == 'false':
return False
elif downcased_text == 'true':
return True
return text |
python | def pool_delete(name, fast=True, **kwargs):
'''
Delete the resources of a defined libvirt storage pool.
:param name: libvirt storage pool name
:param fast: if set to False, zeroes out all the data.
Default value is True.
:param connection: libvirt connection URI, overriding default... |
python | def set_type(self, value):
"""Setter for type attribute"""
if value not in self.types_available:
log = "Sources field 'type' should be in one of %s" % (
self.types_available
)
raise MalFormattedSource(log)
self._type = value |
java | public static String formatJsonDate(Instant value) {
if (value == null) {
return null;
}
return JSON_DATETIME_FORMAT.format(value.atOffset(ZoneOffset.UTC));
} |
python | def new_schedule(self, program, station, time, duration, new, stereo,
subtitled, hdtv, closeCaptioned, ei, tvRating, dolby,
partNumber, partTotal):
"""Callback run for each new schedule entry"""
raise NotImplementedError() |
java | public void putData(double coord, T value) {
// Store in cache
if(cachefill >= 0 && cachefill < cacheposs.length) {
cacheposs[cachefill] = coord;
cachevals[cachefill++] = cloneForCache(value);
return;
}
if(coord == Double.NEGATIVE_INFINITY) {
aggregateSpecial(value, 0);
}
... |
python | def is_choked_turbulent_g(x, Fgamma, xT=None, xTP=None):
r'''Calculates if a gas flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 gas valve sizing calculations.
Either xT or xTP must be provided, depending on the calculation process.
.. math::
x \ge F_\gamma x_T
.. m... |
python | def watch_profile(self):
"""Analyzes queries from a given log file"""
profile_parser = ProfileParser()
databases = self._get_requested_databases()
connection = pymongo.MongoClient(self._db_uri,
document_class=OrderedDict,
... |
java | private boolean validate(PooledTransport transport) {
try {
Response response = transport.execute(validationRequest);
return response.hasSucceeded();
} catch (IOException ioe) {
log.warn("Could not validate pooled connection on lease. Releasing pooled connection and t... |
java | public String getRawBodyAsString() {
if (raw == null) {
return null;
}
return raw.toString(Charsets.UTF_8.displayName());
} |
python | def parse_auth_headers(self, authorization):
"""Parses the authorization headers from the authorization header taken from a request.
Returns a dict that is accepted by all other API functions which expect authorization headers in a dict format.
parse_auth_headers(unroll_auth_headers(A)) should r... |
python | def toolchain_spec_compile_entries(
toolchain, spec, entries, process_name, overwrite_log=None):
"""
The standardized Toolchain Spec Entries compile function
This function accepts a toolchain instance, the spec to be operated
with and the entries provided for the process name. The standard
... |
python | def get_weather_name(self, ip):
''' Get weather_name '''
rec = self.get_all(ip)
return rec and rec.weather_name |
java | private void toTextFromIdle(int length)
{
TempBuffer tBuf = TempBuffer.create();
_tBuf = tBuf;
if (length >> 2 < 0x7d) {
_frameLength = 2;
}
else {
_frameLength = 4;
}
_headOffset = 0;
tBuf.length(_headOffset + _frameLength);
} |
python | def SetRowsCustomProperties(self, rows, custom_properties):
"""Sets the custom properties for given row(s).
Can accept a single row or an iterable of rows.
Sets the given custom properties for all specified rows.
Args:
rows: The row, or rows, to set the custom properties for.
custom_proper... |
java | public String toJavaIdentifier(final String text, final boolean uppercaseFirst) {
return GrammarAccessUtil.toJavaIdentifier(text, Boolean.valueOf(uppercaseFirst));
} |
java | @Override
public FileObject getFileForOutput(JavaFileManager.Location location,
String packageName,
String relativeName,
FileObject sibling)
throws IOException {
throw new UnsupportedOperationException("getFileForOutput: location: " + location +
... |
java | public String getStatus() {
StringBuffer s = new StringBuffer();
s.append("Maps : " + completedMaps + "/" + totalMaps);
s.append(" (" + mapProgress + ")");
s.append(" Reduces : " + completedReduces + "/" + totalReduces);
s.append(" (" + reduceProgress + ")");
return s.toString();
} |
java | public static <T> T median(List<? extends T> data, Comparator<? super T> comparator) {
return median(data, comparator, 0, data.size());
} |
java | @Deprecated
public static FilteredBreakIteratorBuilder createInstance(ULocale where) {
FilteredBreakIteratorBuilder ret = new SimpleFilteredSentenceBreakIterator.Builder(where);
return ret;
} |
java | private Project.Tasks.Task writeTask(Task mpx)
{
Project.Tasks.Task xml = m_factory.createProjectTasksTask();
xml.setActive(Boolean.valueOf(mpx.getActive()));
xml.setActualCost(DatatypeConverter.printCurrency(mpx.getActualCost()));
xml.setActualDuration(DatatypeConverter.printDuration(this, ... |
java | public long getImageSize() {
long x = 0, y = 0;
if (tags.containsTagId(TiffTags.getTagId("ImageLength")))
x = tags.get("ImageLength").getFirstNumericValue();
if (tags.containsTagId(TiffTags.getTagId("ImageWidth")))
y = tags.get("ImageWidth").getFirstNumericValue();
return x * y;
} |
python | def libvlc_media_list_new(p_instance):
'''Create an empty media list.
@param p_instance: libvlc instance.
@return: empty media list, or NULL on error.
'''
f = _Cfunctions.get('libvlc_media_list_new', None) or \
_Cfunction('libvlc_media_list_new', ((1,),), class_result(MediaList),
... |
python | def process_response(self, request, response):
"""Sets "Ok" cookie on unknown users."""
if COOKIE_KEY not in request.COOKIES:
# Unknown user, set cookie and go on...
response.set_cookie(COOKIE_KEY, COOKIE_PASS, httponly=True,
expires=datetime.now()+tim... |
java | public HttpSessionActivity getHttpSessionActivity(HttpSession httpSession)
throws NullPointerException, IllegalArgumentException, IllegalStateException,
ActivityAlreadyExistsException, StartActivityException,
SLEEException {
if (httpSession == null) {
throw new NullPointerException("null http session... |
python | def get_return_from(self, e_handler):
"""Setter of the following attributes::
* exit_status
* output
* long_output
* check_time
* execution_time
* perf_data
:param e_handler: event handler to get data from
:type e_handler: alignak.eventhandler.Ev... |
python | def _low_level_exec_command(self, conn, cmd, tmp, sudoable=False, executable=None):
''' execute a command string over SSH, return the output '''
if executable is None:
executable = '/bin/sh'
sudo_user = self.sudo_user
rc, stdin, stdout, stderr = conn.exec_command(cmd, tmp, ... |
python | def resultcallback(self, replace=False):
"""Adds a result callback to the chain command. By default if a
result callback is already registered this will chain them but
this can be disabled with the `replace` parameter. The result
callback is invoked with the return value of the subcomm... |
java | static double[] incremental(final double[] values) {
final DoubleAdder adder = new DoubleAdder(values[0]);
for (int i = 1; i < values.length; ++i) {
values[i] = adder.add(values[i]).doubleValue();
}
return values;
} |
python | def parse_cgmlst_alleles(cgmlst_fasta):
"""Parse cgMLST alleles from fasta file
cgMLST FASTA file must have a header format of ">{marker name}|{allele name}"
Args:
cgmlst_fasta (str): cgMLST fasta file path
Returns:
dict of list: Marker name to list of allele sequences
"""
out ... |
java | private static Campaign createCampaign(
AdWordsServicesInterface services, AdWordsSession session, long merchantId, long budgetId)
throws RemoteException {
CampaignServiceInterface campaignService =
services.get(session, CampaignServiceInterface.class);
Campaign campaign = new Campaign();
... |
python | def _setDeviceID(self, value, device, message):
"""
Set the hardware device number. This is only needed if more that one
device is on the same serial buss.
:Parameters:
value : `int`
The device ID to set in the range of 0 - 127.
device : `int`
... |
python | def check(self):
"""
Check that this table is complete, that is, every character of this
table can be followed by a new character.
:return: True if the table is complete, False otherwise.
"""
for character, followers in self.items():
for follower in followers... |
java | private FPTree buildFPTree(final Relation<BitVector> relation, int[] iidx, final int items) {
FPTree tree = new FPTree(items);
FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Building FP-tree", relation.size(), LOG) : null;
int[] buf = new int[items];
for(DBIDIter iditer = relation.iterDBIDs... |
java | public static Date localDateToDate(LocalDate localDate) {
Objects.requireNonNull(localDate, Required.LOCAL_DATE.toString());
Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
return Date.from(instant);
} |
python | def user_config_dir():
r"""Return the per-user config dir (full path).
- Linux, *BSD, SunOS: ~/.config/glances
- macOS: ~/Library/Application Support/glances
- Windows: %APPDATA%\glances
"""
if WINDOWS:
path = os.environ.get('APPDATA')
elif MACOS:
path = os.path.expanduser('... |
java | private String getValueOrDefault(HttpServletRequest req, String paramName, String defaultValue) {
final String value = req.getParameter(paramName);
return StringUtils.isEmpty(value) ? defaultValue : value;
} |
python | def resolve_container_id_or_name(raw_string, is_error=False, multi=False):
'''
:param raw_string: A potential project or container ID or name
:type raw_string: string
:param is_error: Whether to raise an exception if the project or
container ID cannot be resolved
:type is_error: boolean
... |
java | public Observable<InstanceFailoverGroupInner> forceFailoverAllowDataLossAsync(String resourceGroupName, String locationName, String failoverGroupName) {
return forceFailoverAllowDataLossWithServiceResponseAsync(resourceGroupName, locationName, failoverGroupName).map(new Func1<ServiceResponse<InstanceFailoverGro... |
python | def camelToSnake(s):
"""
https://gist.github.com/jaytaylor/3660565
Is it ironic that this function is written in camel case, yet it
converts to snake case? hmm..
"""
_underscorer1 = re.compile(r'(.)([A-Z][a-z]+)')
_underscorer2 = re.compile('([a-z0-9])([A-Z])')
subbed = _underscorer1.su... |
python | def gen_lock(self, lock_type='update', timeout=0, poll_interval=0.5):
'''
Set and automatically clear a lock
'''
if not isinstance(lock_type, six.string_types):
raise GitLockError(
errno.EINVAL,
'Invalid lock_type \'{0}\''.format(lock_type)
... |
java | private void createProxyJsMethod(Builder componentExposedTypeBuilder,
ExecutableElement originalMethod, String proxyMethodName) {
Emit emitAnnotation = originalMethod.getAnnotation(Emit.class);
MethodSpec.Builder proxyMethodBuilder = MethodSpec
.methodBuilder(proxyMethodName)
.addModifier... |
java | public S unmarshal(T string) {
try {
return getBoundClass().cast(unmarshalHandle.invoke(string));
} catch (Throwable ex) {
if (ex.getCause() instanceof RuntimeException) {
throw (RuntimeException) ex.getCause();
}
throw new BindingExc... |
java | private void parameterize(Parameterized parameterized) {
try {
parameterized.configure(parameters);
} catch (RuntimeException ex) {
throw new ProgramParametrizationException(ex.getMessage());
}
} |
python | def lstltd(x, n, array):
"""
Given a number x and an array of non-decreasing floats
find the index of the largest array element less than x.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstltd_c.html
:param x: Value to search against
:type x: float
:param n: Number elements in a... |
java | public static void drawStringCentered (
Graphics g, String str, int x, int y, int width, int height)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
int xpos = x + ((width - fm.stringWidth(str)) / 2);
int ypos = y + ((height + fm.getAscent()) / 2);
g.drawString(str, xpos, y... |
java | public void setupListeners() {
// Getting the list of views
QueryInterfaceViewsList queryInterfaceViews = (QueryInterfaceViewsList) this.getOWLEditorKit().get(QueryInterfaceViewsList.class.getName());
if ((queryInterfaceViews == null)) {
queryInterfaceViews = new QueryInterfaceViewsList();
getOWLEditorKit(... |
java | public static String appendUri(final String baseUri, String path, final boolean escapeDoubleSlash) {
String resultUri = baseUri;
if (path != null && path.length() > 0) {
if (path.startsWith("/")) {
// trim the trailing slash in baseUri, since the path already starts with a sl... |
python | def clear_matplotlib_ticks(self, axis="both"):
"""Clears the default matplotlib ticks."""
ax = self.get_axes()
plotting.clear_matplotlib_ticks(ax=ax, axis=axis) |
java | public synchronized void addRange(final float range, final GVRSceneObject sceneObject)
{
if (null == sceneObject) {
throw new IllegalArgumentException("sceneObject must be specified!");
}
if (range < 0) {
throw new IllegalArgumentException("range cannot be negative");... |
java | @Deprecated
public SummaryScanRequest newSummaryScanRequest(String orgToken,
String product,
String productVersion,
Collection<AgentProjectInfo> projects,
... |
java | public Properties getOptionProperties(String opt)
{
Properties props = new Properties();
for (Option option : options)
{
if (opt.equals(option.getOpt()) || opt.equals(option.getLongOpt()))
{
List<String> values = option.getValuesList();
... |
python | def delete_user(self, user_id):
"""Delete a user."""
content = self._fetch("/user/%s" % user_id, method="DELETE")
return self._status(content) |
python | def describe(self):
"""
Return basic statistics about the curve.
"""
stats = {}
stats['samples'] = self.shape[0]
stats['nulls'] = self[np.isnan(self)].shape[0]
stats['mean'] = float(np.nanmean(self.real))
stats['min'] = float(np.nanmin(self.real))
... |
java | public com.google.api.ads.admanager.axis.v201902.RetractionDetails getRetractionDetails() {
return retractionDetails;
} |
python | def fetch(**kwargs):
'''
.. versionadded:: 2016.3.4
freebsd-update fetch wrapper. Based on the currently installed world and the
configuration options set, fetch all available binary updates.
kwargs:
Parameters of freebsd-update command.
'''
# fetch continues when no controlling te... |
java | public File getDirectory(String sPath) {
File directory = new File(sPath);
if (!directory.isDirectory()) {
URL resource = FilterFileManager.class.getClassLoader().getResource(sPath);
try {
directory = new File(resource.toURI());
} catch (Exception e) ... |
python | def search(self, regex=None, spec=None, **kwargs):
"""Search for packages."""
cmd_list = ['search', '--json']
if regex and spec:
raise TypeError('conda search: only one of regex or spec allowed')
if regex:
cmd_list.append(regex)
if spec:
cmd... |
java | public void stopChecking() {
// synchronize with other attempts to update the running task
synchronized(runningTaskLock){
if(runningTask != null) {
// cancel task (let it complete its current run if running)
runningTaskFuture.cancel(false);
// ... |
python | def HMAC(self, message, use_sha256=False):
"""Calculates the HMAC for a given message."""
h = self._NewHMAC(use_sha256=use_sha256)
h.update(message)
return h.finalize() |
java | public static <K, V> ImmutableListMultimap<K, V> indexToListMultimapWithMultipleKeys(
Iterable<? extends V> values, Function<? super V, ? extends Collection<? extends K>> keyFunction) {
final ImmutableListMultimap.Builder<K,V> ret = ImmutableListMultimap.builder();
for (final V value : values) {
//... |
python | def to_json(self):
"""
Serialises a HucitWork to a JSON formatted string.
"""
titles = self.get_titles()
return json.dumps({
"uri" : self.subject
, "urn" : str(self.get_urn())
, "titles" : [{"language":lang, "label":label} for lang,... |
java | void initXmlReader() throws SAXException {
if (parserMap.containsKey(ATTR_FORMAT_VALUE_DITA)) {
reader = XMLReaderFactory.createXMLReader(parserMap.get(ATTR_FORMAT_VALUE_DITA));
final Map<String, Boolean> features = parserFeatures.getOrDefault(ATTR_FORMAT_VALUE_DITA, emptyMap());
... |
java | @Override
public JournalAmp open(String name) // , int maxCount, long timeout)
{
JournalSystem system = JournalSystem.getCurrent();
/*
if (maxCount < 0) {
maxCount = _maxCount;
}
if (timeout < 0) {
timeout = _timeout;
}
*/
if (system != null) {
return... |
java | @SuppressWarnings( "unchecked" )
protected void collectProjectArtifactsAndClasspath( List<Artifact> artifacts, List<File> theClasspathFiles )
{
if ( "compile".equals( classpathScope ) )
{
artifacts.addAll( project.getCompileArtifacts() );
theClasspathFiles.add( new File(... |
python | def format(self, response_data):
"""
Make Flask `Response` object, with data returned as a generator for the CSV content
The CSV is built from JSON-like object (Python `dict` or list of `dicts`)
"""
if "items" in response_data:
list_response_data = response_data["ite... |
java | @Override
public List<Address> search(final String query) throws IOException {
final NominatimSearchRequest q = new NominatimSearchRequest();
q.setQuery(query);
return this.search(q);
} |
python | def validate(
self,
point: Tuple[float, float, float],
point_num: int,
pipette_mount) -> str:
"""
:param point: Expected values from mechanical drawings
:param point_num: The current position attempting to be validated
:param pipette: 'Z' f... |
python | def fetch(self):
"""
Method for getting artifact's content.
Could only be applicable for file type.
:return: content of the artifact.
"""
if self.data.type == self._manager.FOLDER_TYPE:
raise YagocdException("Can't fetch folder <{}>, only file!".format(self._... |
java | public void logError(String pTemplate,
Throwable pRootCause,
Object pArg0,
Object pArg1,
Object pArg2,
Object pArg3)
throws ELException {
if (isLoggingError()) {
l... |
java | private boolean delBlockFromDisk(File blockFile, File metaFile, Block b) {
if (blockFile == null) {
DataNode.LOG.warn("No file exists for block: " + b);
return true;
}
if (!blockFile.delete()) {
DataNode.LOG.warn("Not able to delete the block file: " + blockFile);
return false;
... |
java | public OmdbBuilder setResultType(final ResultType resultType) {
if (!ResultType.isDefault(resultType)) {
params.add(Param.RESULT, resultType);
}
return this;
} |
python | def ball_and_stick(target, pore_area='pore.area',
throat_area='throat.area',
pore_diameter='pore.diameter',
throat_diameter='throat.diameter',
conduit_lengths='throat.conduit_lengths'):
r"""
Calculate conduit shape factors for hydraulic... |
java | public void execute(@Observes ExecuteWarp event, HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain, RequestPayload requestPayload, ResponsePayload responsePayload) throws Throwable {
List<Inspection> inspections = requestPayload.getInspections();
try {
... |
java | public static NavigationAnimation createZoomIn(MapPresenter mapPresenter, Coordinate position) {
View endView = null;
int index = mapPresenter.getViewPort().getResolutionIndex(mapPresenter.getViewPort().getResolution());
if (index < mapPresenter.getViewPort().getResolutionCount() - 1) {
endView = new View(posi... |
python | def get_parent_objective_banks(self, objective_bank_id):
"""Gets the parents of the given objective bank.
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (osid.learning.ObjectiveBankList) - the parents of the
objective bank
... |
python | def _sysapi_changed_nilrt():
'''
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an
extensible, plugin-based device enumeration and configuration interface named "System API".
When an installed package is extending the API it is very hard to know all repercurssio... |
java | @Override
public double getParameter(Compound referenceComponent, Compound nonReferenceComponent, InteractionParameter params, int index) {
int numberOfParametersOfActivity = activityModel.numberOfParameters();
ActivityModelBinaryParameter activityParams = (ActivityModelBinaryParameter)params;
... |
java | public void forAllProcedures(String template, Properties attributes) throws XDocletException
{
for (Iterator it = _curClassDef.getProcedures(); it.hasNext(); )
{
_curProcedureDef = (ProcedureDef)it.next();
generate(template);
}
_curProcedureDef = null;
... |
java | public Coordinate getHillslopeClosure() {
Coordinate[] coords = ((Geometry) linkFeature.getDefaultGeometry()).getCoordinates();
return coords[coords.length - 1];
} |
java | public static Filter createFilter(Class<? extends FilterFactory> filterFactoryClass, FilterFactoryParams params)
throws FilterFactory.FilterNotCreatedException {
FilterFactory filterFactory = createFilterFactory(filterFactoryClass);
return filterFactory.createFilter(params);
} |
java | public void waitForData() throws InterruptedException {
try {
if (registryRemote == null) {
waitForValue();
return;
}
getRegistryRemote().waitForData();
} catch (CouldNotPerformException ex) {
ExceptionPrinter.printHistory("... |
java | public static double Sinc(double x) {
return Math.sin(Math.PI * x) / (Math.PI * x);
} |
java | public static InputStream toInputStream(Publisher<String> publisher, Charset charset) {
return FlowableStringInputStream.createInputStream(publisher, charset);
} |
python | def _build_encryption_key(self, subtitle_id, key_size=ENCRYPTION_KEY_SIZE):
"""Generate the encryption key for a given media item
Encryption key is basically just
sha1(<magic value based on subtitle_id> + '"#$&).6CXzPHw=2N_+isZK') then
padded with 0s to 32 chars
@param int subt... |
python | def from_pymatgen_molecule(cls, molecule):
"""Create an instance of the own class from a pymatgen molecule
Args:
molecule (:class:`pymatgen.core.structure.Molecule`):
Returns:
Cartesian:
"""
new = cls(atoms=[el.value for el in molecule.species],
... |
java | @RequirePOST
public HttpResponse doInstallNecessaryPlugins(StaplerRequest req) throws IOException {
prevalidateConfig(req.getInputStream());
return HttpResponses.redirectViaContextPath("updateCenter");
} |
java | public static void computeNormalization(List<Point2D_F64> points, NormalizationPoint2D normalize )
{
double meanX = 0;
double meanY = 0;
for( Point2D_F64 p : points ) {
meanX += p.x;
meanY += p.y;
}
meanX /= points.size();
meanY /= points.size();
double stdX = 0;
double stdY = 0;
for( Point... |
python | def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, ... |
python | def astral(msg):
"""Does `msg` have characters outside the Basic Multilingual Plane?"""
# Python2 narrow builds present astral characters as surrogate pairs.
# By encoding as utf32, and decoding DWORDS, we can get at the real code
# points.
utf32 = msg.encode("utf32")[4:] # [4:] to drop the ... |
python | def add_items(self, dataframe, hide_cols=()):
"""
Add items and/or update existing items in grid
"""
# replace "None" values with ""
dataframe = dataframe.fillna("")
# remove any columns that shouldn't be shown
for col in hide_cols:
if col in dataframe... |
java | public boolean setProtectionLevel(int level) {
boolean result = false;
switch(level) {
case RtfProtection.LEVEL_NONE:
if(this.protectionHash == null) {
break;
}
case RtfProtection.LEVEL_ANNOTPROT:
case RtfProtection.LEVEL_FORMPROT:
case RtfProtection.LEVEL_REVPROT:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.