language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def bggreen(cls, string, auto=False):
"""Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
"""
return cls.colorize('bggreen', st... |
java | private boolean containsKey(K key, int keyGroupIndex, N namespace) {
checkKeyNamespacePreconditions(key, namespace);
Map<N, Map<K, S>> namespaceMap = getMapForKeyGroup(keyGroupIndex);
if (namespaceMap == null) {
return false;
}
Map<K, S> keyedMap = namespaceMap.get(namespace);
return keyedMap != nul... |
python | def screenshot(self, *args):
"""Take a screenshot, crop and save"""
from mss import mss
if not os.path.exists("screenshots"):
os.makedirs("screenshots")
box = {
"top": self.winfo_y(),
"left": self.winfo_x(),
"width": self.winfo_width(),
... |
python | def _delete(self, ):
"""Internal implementation for deleting a reftrack.
This will just delete the reftrack, set the children to None,
update the status, and the rootobject. If the object is an alien,
it will also set the parent to None, so it dissapears from the model.
:return... |
python | def get_all_items(self):
"""
Returns all items in the combobox dictionary.
"""
return [self._widget.itemText(k) for k in range(self._widget.count())] |
python | def update(self, other, join='left', overwrite=True, filter_func=None,
errors='ignore'):
"""
Modify in place using non-NA values from another DataFrame.
Aligns on indices. There is no return value.
Parameters
----------
other : DataFrame, or object coerci... |
python | def cast_to_a1_notation(method):
"""
Decorator function casts wrapped arguments to A1 notation
in range method calls.
"""
@wraps(method)
def wrapper(self, *args, **kwargs):
try:
if len(args):
int(args[0])
# Convert to A1 notation
range... |
java | public NameParser getNameParser() throws WIMException {
if (iNameParser == null) {
TimedDirContext ctx = iContextManager.getDirContext();
try {
try {
iNameParser = ctx.getNameParser("");
} catch (NamingException e) {
... |
java | @Override
public XBELDocument convert(Document source) {
if (source == null) return null;
XBELDocument xd = new XBELDocument();
List<StatementGroup> stmtGroups = source.getStatementGroups();
List<XBELStatementGroup> xstmtGroups = xd.getStatementGroup();
StatementGroupConver... |
java | private SslContext getSslContext(URI uri) {
if (!"https".equalsIgnoreCase(uri.getScheme())) {
return null;
}
try {
return SslContextBuilder.forClient().build();
} catch (SSLException e) {
throw new SdkClientException("Could not create SSL context", e);... |
java | private void fillEDBObjectWithEngineeringObjectInformation(EDBObject object, OpenEngSBModel model)
throws IllegalAccessException {
if (!new AdvancedModelWrapper(model).isEngineeringObject()) {
return;
}
for (Field field : model.getClass().getDeclaredFields()) {
Op... |
python | def get_sign_key(exported_session_key, magic_constant):
"""
3.4.5.2 SIGNKEY
@param exported_session_key: A 128-bit session key used to derive signing and sealing keys
@param magic_constant: A constant value set in the MS-NLMP documentation (constants.SignSealConstants)
@return sign_key: Key used to... |
java | private Type pageableMixin(RepositoryRestConfiguration restConfiguration) {
return new AlternateTypeBuilder()
.fullyQualifiedClassName(
String.format("%s.generated.%s",
Pageable.class.getPackage().getName(),
Pageable.class.getSimpleName()))
.withProperties... |
java | private String getPostData(final ICommandLine cl) throws Exception {
// String encoded = "";
StringBuilder encoded = new StringBuilder();
String data = cl.getOptionValue("post");
if (data == null) {
return null;
}
String[] values = data.split("&");
for... |
python | def prior_rev(C, alpha=-1.0):
r"""Prior counts for sampling of reversible transition
matrices.
Prior is defined as
b_ij= alpha if i<=j
b_ij=0 else
The reversible prior adds -1 to the upper triagular part of
the given count matrix. This prior respects the fact that
for a revers... |
python | def show_option(self, option, _global=False):
"""Return a list of options for the window.
Parameters
----------
option : str
option name
_global : bool, optional
use global option scope, same as ``-g``
Returns
-------
str, int, or... |
java | public String getValuesAsString() {
StringBuilder builder = new StringBuilder();
for(E row: rowKeys.keySet())
for(E col: colKeys.keySet()) {
builder.append(getValueAsString(row, col, true));
builder.append('\n');
}
return builder.toString();
} |
java | @Override
public void open(FileInputSplit split) throws IOException {
super.open(split);
dataFileReader = initReader(split);
dataFileReader.sync(split.getStart());
lastSync = dataFileReader.previousSync();
} |
java | private void popAndResetToOldLevel() {
this.levelStack.pop();
if (!this.levelStack.isEmpty()) {
JsonLevel newTop = levelStack.peek();
if (newTop != null) {
newTop.removeLastTokenFromJsonPointer();
}
}
} |
java | private boolean nestedContains(ArchivePath path) {
// Iterate through nested archives
for (Entry<ArchivePath, ArchiveAsset> nestedArchiveEntry : nestedArchives.entrySet()) {
ArchivePath archivePath = nestedArchiveEntry.getKey();
ArchiveAsset archiveAsset = nestedArchiveEntry.getV... |
python | def get_candidate_delegates(self, candidate):
"""
Get all pledged delegates for a candidate in this election.
"""
candidate_election = CandidateElection.objects.get(
candidate=candidate, election=self
)
return candidate_election.delegates.all() |
python | def search(self, filepath=None, basedir=None, kind=None):
"""
Search for a settings file.
Keyword Arguments:
filepath (string): Path to a config file, either absolute or
relative. If absolute set its directory as basedir (omitting
given basedir argume... |
java | public ResultSet getColumnPrivileges(final String catalog, final String schema, final String table, final String columnNamePattern)
throws SQLException {
log.info("getting empty result set, column privileges");
return getEmptyResultSet();
} |
python | def clean_inasafe_fields(layer):
"""Clean inasafe_fields based on keywords.
1. Must use standard field names.
2. Sum up list of fields' value and put in the standard field name.
3. Remove un-used fields.
:param layer: The layer
:type layer: QgsVectorLayer
"""
fields = []
# Exposure... |
python | def make_input_from_multiple_strings(sentence_id: SentenceId, strings: List[str]) -> TranslatorInput:
"""
Returns a TranslatorInput object from multiple strings, where the first element corresponds to the surface tokens
and the remaining elements to additional factors. All strings must parse into token sequ... |
java | public ResolveRoomResult withRoomSkillParameters(RoomSkillParameter... roomSkillParameters) {
if (this.roomSkillParameters == null) {
setRoomSkillParameters(new java.util.ArrayList<RoomSkillParameter>(roomSkillParameters.length));
}
for (RoomSkillParameter ele : roomSkillParameters) ... |
java | @Override
public Object getValue(ELContext context, Object base, Object property) throws NullPointerException,
PropertyNotFoundException, ELException {
Iterator<?> pos;
try {
pos = seek(context, base, property);
} catch(PropertyNotFoundException e) {
... |
java | public static Promise<Void> createDirectories(Executor executor, Path dir, FileAttribute... attrs) {
return ofBlockingRunnable(executor, () -> {
try {
Files.createDirectories(dir, attrs);
} catch (IOException e) {
throw new UncheckedException(e);
}
});
} |
java | public void setLocale(Locale locale)
{
List<SimpleDateFormat> formats = new ArrayList<SimpleDateFormat>();
for (SimpleDateFormat format : m_formats)
{
formats.add(new SimpleDateFormat(format.toPattern(), locale));
}
m_formats = formats.toArray(new SimpleDateFormat[formats.size... |
java | public void shutdown() {
gossipServiceRunning.set(false);
gossipThreadExecutor.shutdown();
if (passiveGossipThread != null) {
passiveGossipThread.shutdown();
}
if (activeGossipThread != null) {
activeGossipThread.shutdown();
}
try {
boolean result = gossipThreadExecutor.awa... |
python | def reset(self):
""" Reset target collection (rebuild index).
"""
self.connection.rebuild_index(
self.index, coll_name=self.target_coll_name) |
java | @SuppressWarnings({"unchecked"})
@Override
public void writeTo(Viewable viewable, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException,
WebApplicationException {
... |
python | def pkeys(self,parent,field):
"returns a list of pkey tuples by combining parent[field] with our attrs"
template=[(parent[k] if k is not None else None) for k in self.pkey]
inull=template.index(None)
def mk(x):
"helper for constructing pkey tuples in a list comp"
template[inull]=x
... |
python | def errorObject(object, cat, format, *args):
"""
Log a fatal error message in the given category.
This will also raise a L{SystemExit}.
"""
doLog(ERROR, object, cat, format, args)
# we do the import here because having it globally causes weird import
# errors if our gstreactor also imports ... |
python | def prepare_attached(self, action, a_name, **kwargs):
"""
Prepares an attached volume for a container configuration.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param a_name: The full name or id of the container sharing the volume.
... |
java | private Function<HttpRequestContext, String> createQuerySubstitution(final String param) {
return new Function<HttpRequestContext, String>() {
@Override
public String apply(HttpRequestContext request) {
MultivaluedMap<String, String> params = request.getQueryParameters();... |
python | def __load_unique_identities(self, uidentities, matcher, match_new,
reset, verbose):
"""Load unique identities"""
self.new_uids.clear()
n = 0
if reset:
self.__reset_unique_identities()
self.log("Loading unique identities...")
... |
python | def _dict_contents(self, use_dict=None, as_class=dict):
"""Return the contents of an object as a dict."""
if _debug: Object._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
# make/extend the dictionary of content
if use_dict is None:
use_dict = as_class()
... |
java | public void setCustomAnimation(BaseAnimationInterface animation){
mCustomAnimation = animation;
if(mViewPagerTransformer != null){
mViewPagerTransformer.setCustomAnimationInterface(mCustomAnimation);
}
} |
java | public boolean isAnnotatable() {
return ObjectUtils.defaultIfNull((Boolean) configurationValues.get(ConfigurationOption.ANNOTATE), Boolean.TRUE)
.booleanValue();
} |
python | def make_prediction_output_tensors(args, features, input_ops, model_fn_ops,
keep_target):
"""Makes the final prediction output layer."""
target_name = feature_transforms.get_target_name(features)
key_names = get_key_names(features)
outputs = {}
outputs.update({key_name: tf.... |
java | public static <T> InputReader getInstance(T input, int size, String cs) throws IOException
{
return getInstance(input, size, Charset.forName(cs), NO_FEATURES);
} |
java | private void addPostParams(final Request request) {
if (friendlyName != null) {
request.addPostParam("FriendlyName", friendlyName);
}
if (chatServiceSid != null) {
request.addPostParam("ChatServiceSid", chatServiceSid);
}
if (channelType != null) {
... |
python | def alias_catalog(self, catalog_id, alias_id):
"""Adds an ``Id`` to a ``Catalog`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Catalog`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to anoth... |
python | def stationary_distribution_sensitivity(T, j):
r"""Sensitivity matrix of a stationary distribution element.
Parameters
----------
T : (M, M) ndarray
Transition matrix (stochastic matrix).
j : int
Index of stationary distribution element
for which sensitivity matrix is compute... |
java | @GetMapping(path = CasProtocolConstants.ENDPOINT_VALIDATE)
protected ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
return super.handleRequestInternal(request, response);
} |
python | def download(objects):
"""
Retrieve remote file object
"""
def exists(object):
if os.path.exists(TMPDIR + '/' + filename):
return True
else:
msg = 'File object %s failed to download to %s. Exit' % (filename, TMPDIR)
logger.warning(msg)
stdo... |
python | def verifyComponents(self, samplerate):
"""Checks the current components for invalidating conditions
:param samplerate: generation samplerate (Hz), passed on to component verification
:type samplerate: int
:returns: str -- error message, if any, 0 otherwise
"""
# flatten... |
java | public Object getObject(int idx) {
if (idx < 0) {
throw new IllegalArgumentException("Negative size: " + idx);
}
if (idx >= fields.size()) {
return null;
}
return fields.get(idx);
} |
java | private ValidationMessage<Origin> reportError(ValidationResult result, Feature feature, String messageId, Object ... params) {
ValidationMessage<Origin> message =
EntryValidations.createMessage(feature.getOrigin(), Severity.ERROR, messageId, params);
if (SequenceEntryUtils.isQualifierAv... |
java | protected void parse(Node node) {
queryable = isQueryable(node);
styleInfo.clear();
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node child = childNodes.item(i);
String nodeName = child.getNodeName();
if ("Name".equalsIgnoreCase(nodeName)) {
name =... |
python | def get_info(self):
"""Return a list with all information available about this process"""
return [self.display_name.encode(),
self.enabled and b'enabled' or b'disabled',
STATE_NAMES[self.state].encode() + b':',
self.last_printed_line.strip()] |
python | def measure(*qubits: raw_types.Qid,
key: Optional[str] = None,
invert_mask: Tuple[bool, ...] = ()
) -> gate_operation.GateOperation:
"""Returns a single MeasurementGate applied to all the given qubits.
The qubits are measured in the computational basis.
Args:
*q... |
java | public static BufferedWriter newWriter(File file, String charset) throws IOException {
return newWriter(file, charset, false);
} |
python | def request_generic(self, act, coro, perform, complete):
"""
Performs an overlapped request (via `perform` callable) and saves
the token and the (`overlapped`, `perform`, `complete`) trio.
"""
overlapped = pywintypes.OVERLAPPED()
overlapped.object = act
sel... |
python | def get_reference_line_numeration_marker_patterns(prefix=u''):
"""Return a list of compiled regex patterns used to search for the marker.
Marker of a reference line in a full-text document.
:param prefix: (string) the possible prefix to a reference line
:return: (list) of compiled regex patterns.
... |
python | def get_string_at_rva(self, rva):
"""Get an ASCII string located at the given address."""
s = self.get_section_by_rva(rva)
if not s:
return self.get_string_from_data(0, self.__data__[rva:rva+MAX_STRING_LENGTH])
return self.get_string_from_data( 0, s.get_data(rva, le... |
python | def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
"""Shift this dataset by an offset along one or more dimensions.
Only data variables are moved; coordinates stay in place. This is
consistent with the behavior of ``shift`` in pandas.
Parameters
----------
... |
python | def get_subject(self):
"""
Returns:
subject : Reactive Extension Subject
"""
if not self._run_flag.running:
raise Exception('RuuviTagReactive stopped')
subject = Subject()
self._subjects.append(subject)
return subject |
java | @Override
public ValidationReport validateBond(IBond subject) {
ValidationReport report = new ValidationReport();
// only consider two atom bonds
if (subject.getAtomCount() == 2) {
double distance = subject.getBegin().getPoint3d().distance(subject.getEnd().getPoint3d());
... |
java | public long getDepth() throws SIMPControllableNotFoundException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "getDepth");
long count=0;
SIMPIterator iterator = getStreams();
while(iterator.hasNext())
{
InternalOutputStreamControl ios =
(In... |
python | def _read(self, fp, fpname):
"""Parse a sectioned setup file.
The sections in setup file contains a title line at the top,
indicated by a name in square brackets (`[]'), plus key/value
options lines, indicated by `name: value' format lines.
Continuations are represented by an em... |
java | static public byte[] asByteArray(long inValue) {
long value = inValue;
// check for 0
if (0 == value) {
return ZERO_BYTEARRAY;
}
// make space for the largest long number
byte[] bytes = new byte[SIZE_MAXLONG];
// check for negative ints
boole... |
java | @Override
public void clearCache(CPDAvailabilityEstimate cpdAvailabilityEstimate) {
entityCache.removeResult(CPDAvailabilityEstimateModelImpl.ENTITY_CACHE_ENABLED,
CPDAvailabilityEstimateImpl.class,
cpdAvailabilityEstimate.getPrimaryKey());
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
f... |
java | @ManagedAttribute()
public List<String> getEffectiveProperties() {
final List<String> properties = new LinkedList<String>();
for (final String key : myProperties.stringPropertyNames()) {
properties.add(key + "=" + myProperties.get(key));
}
return properties;
} |
java | public void setResult(Result result) throws IllegalArgumentException {
Check.notNull(result);
if(result instanceof SAXResult) {
setTarget((SAXResult)result);
} else {
TransformerHandler th = saxHelper.newIdentityTransformerHandler();
th.setResult(result);
setTarget(new SAXResult(th));
}
} |
java | @Override
public void write(DataOutput out) throws IOException {
out.writeInt(values.size());
for (ValueWritable vw : values) {
vw.write(out);
}
} |
java | @Override
public void process(TestDeployment testDeployment, Archive<?> protocolArchive) {
final TestClass testClass = this.testClass.get();
final Archive<?> applicationArchive = testDeployment.getApplicationArchive();
if (WarpCommons.isWarpTest(testClass.getJavaClass())) {
if (... |
java | @Override
public EClass getIfcElementAssembly() {
if (ifcElementAssemblyEClass == null) {
ifcElementAssemblyEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(222);
}
return ifcElementAssemblyEClass;
} |
python | def read_whole_packet(self):
""" Reads single packet and returns bytes payload of the packet
Can only be called when transport's read pointer is at the beginning
of the packet.
"""
self._read_packet()
return readall(self, self._size - _header.size) |
python | def _find_bounds(py_line_no, py_by_line_no, cheetah_by_line_no):
"""Searches before and after in the python source to find comments which
denote cheetah line numbers. If a lower bound is not found, 0 is
substituted. If an upper bound is not found, len(cheetah lines) is
returned. The result is a lower... |
java | private void checkIndices(int row, int col) {
if (row < 0 || col < 0 || row >= rows || col >= cols) {
throw new IndexOutOfBoundsException();
}
} |
python | def questions(self):
"""获取用户的所有问题.
:return: 用户的所有问题,返回生成器.
:rtype: Question.Iterable
"""
from .question import Question
if self.url is None or self.question_num == 0:
return
for page_index in range(1, (self.question_num - 1) // 20 + 2):
h... |
python | def detect_intent_texts(project_id, session_id, texts, language_code):
"""Returns the result of detect intent with texts as inputs.
Using the same `session_id` between requests allows continuation
of the conversation."""
import dialogflow_v2 as dialogflow
session_client = dialogflow.SessionsClient... |
python | def user_role_add(user_id=None, user=None, tenant_id=None,
tenant=None, role_id=None, role=None, profile=None,
project_id=None, project_name=None, **connection_args):
'''
Add role for user in tenant (keystone user-role-add)
CLI Examples:
.. code-block:: bash
... |
java | @Override
public Task<UserApiKey> createApiKey(@NonNull final String name) {
return dispatcher.dispatchTask(new Callable<UserApiKey>() {
@Override
public UserApiKey call() {
return createApiKeyInternal(name);
}
});
} |
java | @Override
public List<PlanNode> getAlternativePlans(CostEstimator estimator) {
// check if we have a cached version
if (this.cachedPlans != null) {
return this.cachedPlans;
}
// calculate alternative sub-plans for predecessor
List<? extends PlanNode> subPlans = getPredecessorNode().getAlternativePlans(... |
java | @Pure
public static Map<String, List<Object>> getCommandLineOptions() {
if (commandLineOptions != null) {
return Collections.unmodifiableSortedMap(commandLineOptions);
}
return Collections.emptyMap();
} |
java | public void setDomainStatusList(java.util.Collection<ElasticsearchDomainStatus> domainStatusList) {
if (domainStatusList == null) {
this.domainStatusList = null;
return;
}
this.domainStatusList = new java.util.ArrayList<ElasticsearchDomainStatus>(domainStatusList);
} |
python | def configure(
cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
) -> None:
"""Configures the `AsyncHTTPClient` subclass to use.
``AsyncHTTPClient()`` actually creates an instance of a subclass.
This method may be called with either a class object or the
fully... |
java | @Override
public BeanDeploymentArchive loadBeanDeploymentArchive(Class<?> beanClass) {
BeanDeploymentArchive bda = getBeanDeploymentArchiveFromClass(beanClass);
//return the bda if the class is contained in one of the bdas;
if (bda == null) {
try {
bda = createBD... |
python | def update(self, **kwargs):
u"""Updating or creation of new simple nodes.
Each dict key is used as a tagname and value as text.
"""
for key, value in kwargs.items():
helper = helpers.CAST_DICT.get(type(value), str)
tag = self._get_aliases().get(key, key)
... |
java | public static Path serialize(Object source, FileSystem fs, Path targetPath) {
Assert.notNull(targetPath, "'targetPath' must not be null");
Assert.notNull(fs, "'fs' must not be null");
Assert.notNull(source, "'source' must not be null");
Path resultPath = targetPath.makeQualified(fs.getUri(), fs.getWorkingDirec... |
java | public static Cipher getCipher(final @NotNull Key key, int mode) {
try {
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(mode, key);
return cipher;
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
th... |
java | private boolean calcBool() {
int cmp;
switch (left.getType()) { // same as right.getType()
case BOOL:
switch (op) {
case AND:
return left.evalBool() && right.evalBool();
case OR:
return left.evalBool() || right.evalBool();
... |
java | public void subtract(final DoubleHistogram otherHistogram) {
int arrayLength = otherHistogram.integerValuesHistogram.countsArrayLength;
AbstractHistogram otherIntegerHistogram = otherHistogram.integerValuesHistogram;
for (int i = 0; i < arrayLength; i++) {
long otherCount = otherInte... |
python | def _authGetDBusCookie(self, cookie_context, cookie_id):
"""
Reads the requested cookie_id from the cookie_context file
"""
# XXX Ensure we obtain the correct directory for the
# authenticating user and that that user actually
# owns the keyrings directory
... |
java | @Override
public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
if (!matchWithinClass) {
return Description.NO_MATCH;
}
Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(tree);
Symbol.MethodSymbol funcInterfaceSymbol =
NullabilityUtil.getFuncti... |
java | private String replaceDelimiter(String value, char delimiter, String delimiterReplacement) {
return CmsStringUtil.substitute(value, String.valueOf(delimiter), delimiterReplacement);
} |
python | def punToEnglish_number(number):
"""Thee punToEnglish_number function will take a string num which is
the number written in punjabi, like ੧੨੩, this is 123, the function
will convert it to 123 and return the output as 123 of type int
"""
output = 0 #This is a simple logic, here we go to each digit an... |
python | def _readline(self, timeout=1):
"""
Read line from serial port.
:param timeout: timeout, default is 1
:return: stripped line or None
"""
line = self.port.readline(timeout=timeout)
return strip_escape(line.strip()) if line is not None else line |
java | protected void destroyConnectionFactories(boolean destroyImmediately) {
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(this, tc, "destroyConnectionFactories", destroyImmediately, destroyWasDeferred);
// Notify the application r... |
python | def _make_serializer(meas, schema, rm_none, extra_tags, placeholder): # noqa: C901
"""Factory of line protocol parsers"""
_validate_schema(schema, placeholder)
tags = []
fields = []
ts = None
meas = meas
for k, t in schema.items():
if t is MEASUREMENT:
meas = f"{{i.{k}}}... |
java | public VoltTable[] run(SystemProcedureExecutionContext ctx) {
VoltTable[] result = null;
try {
result = createAndExecuteSysProcPlan(SysProcFragmentId.PF_quiesce_sites,
SysProcFragmentId.PF_quiesce_processed_sites);
} catch (Exception ex) {
ex.printSta... |
java | public boolean save()
{
boolean blnRet = false;
File objFile = null;
String strName = null;
String strTemp = null;
Iterator<String> itrSec = null;
INISection objSec = null;
FileWriter objWriter = null;
try
... |
java | public void setCompileDirectory(String directory) {
if (directory != null && directory.trim().length() > 0) {
File file = new File(directory);
if (file.exists() || file.mkdirs()) {
this.compileDirectory = file;
}
}
} |
python | def _expr2sat(ex, litmap): # pragma: no cover
"""Convert an expression to a DIMACS SAT string."""
if isinstance(ex, Literal):
return str(litmap[ex])
elif isinstance(ex, NotOp):
return "-(" + _expr2sat(ex.x, litmap) + ")"
elif isinstance(ex, OrOp):
return "+(" + " ".join(_expr2sat... |
java | public Set<CmsResource> getPublishListFiles() throws CmsException {
String context = "[" + RandomStringUtils.randomAlphabetic(8) + "] ";
List<CmsResource> offlineResults = computeCollectorResults(OFFLINE);
if (LOG.isDebugEnabled()) {
LOG.debug(context + "Offline collector results f... |
python | def get_F1_EM(dataset, predict_data):
"""Calculate the F1 and EM scores of the predicted results.
Use only with the SQuAD1.1 dataset.
Parameters
----------
dataset_file: string
Path to the data file.
predict_data: dict
All final predictions.
Returns
-------
scores: ... |
python | def get_most_frequent_value(values: list):
"""
Return the most frequent value in list.
If there is no unique one, return the maximum of the most frequent values
:param values:
:return:
"""
if len(values) == 0:
return None
most_common = Counter(values).most_common()
result, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.