language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public FieldScopeLogicMap<V> with(FieldScopeLogic fieldScopeLogic, V value) {
ImmutableList.Builder<Entry<V>> newEntries = ImmutableList.builder();
// Earlier entries override later ones, so we insert the new one at the front of the list.
newEntries.add(Entry.of(fieldScopeLogic, value));
newEntries.addA... |
python | def reduce(self, func, dim=None, axis=None, keep_attrs=None, **kwargs):
"""Reduce this array by applying `func` along some dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`f(x, axis=axis, **kwargs)` to return the resul... |
java | @Override
public JavaClass findClass(/*@Nonnull*/ String className) {
// Make sure we handle class names with slashes.
// If we don't, we can get into serious trouble: a previously
// loaded class will appear to be missing (because we're using the
// wrong name to look it up) and be ... |
python | def expand(self, vs=None, conj=False):
"""Return the Shannon expansion with respect to a list of variables."""
vs = self._expect_vars(vs)
if vs:
outer, inner = (And, Or) if conj else (Or, And)
terms = [inner(self.restrict(p),
*boolfunc.point2ter... |
java | public static <K> Matcher<Multimap<K, ?>> hasSameKeySet(final Multimap<K, ?> comparison) {
return IsMultimapWithKeySet.hasSameKeySet(comparison.keySet());
} |
python | def write(self, data):
"""Buffers some data to be sent to the host:port in a non blocking way.
So the data is always buffered and not sent on the socket in a
synchronous way.
You can give a WriteBuffer as parameter. The internal Connection
WriteBuffer will be extended with this... |
python | def script_file(self):
"""
Returns the startup script file for this VPCS VM.
:returns: path to startup script file
"""
# use the default VPCS file if it exists
path = os.path.join(self.working_dir, 'startup.vpc')
if os.path.exists(path):
return path
... |
python | def generate_values(self, *args, **kwargs):
"""
Instantiate a random variable and apply annual growth factors.
:return:
"""
assert 'ref value' in self.kwargs
# 1. Generate $\mu$
start_date = self.times[0].to_pydatetime()
end_date = self.times[-1].to_pyda... |
java | private PointF transformCoordBitmapToTouch(float bx, float by) {
matrix.getValues(m);
float origW = getDrawable().getIntrinsicWidth();
float origH = getDrawable().getIntrinsicHeight();
float px = bx / origW;
float py = by / origH;
float finalX = m[Matrix.MTRANS_X] + getIm... |
java | public SIDestinationAddress getDestinationAddress()
{
if (TraceComponent.isAnyTracingEnabled() && CoreSPIProducerSession.tc.isEntryEnabled())
SibTr.entry(
CoreSPIProducerSession.tc,
"getDestinationAddress", this);
// if(_ != null)
// {
// if (TraceComponent.isAnyTracingEnabled() ... |
java | protected <T> Map<String, CompletableFuture<T>> executeOnMasters(
Function<RedisClusterAsyncCommands<K, V>, RedisFuture<T>> function) {
return executeOnNodes(function, redisClusterNode -> redisClusterNode.is(MASTER));
} |
java | public synchronized String createTempFile(CmsObject cms, String resourceName, CmsUUID currentProjectId)
throws CmsException {
// check that the current user has write permissions
if (!cms.hasPermissions(cms.readResource(resourceName, CmsResourceFilter.ALL), CmsPermissionSet.ACCESS_WRITE)) {
... |
java | public long getDateField(String name)
{
String val = valueParameters(get(name),null);
if (val==null)
return -1;
if (_dateReceive==null)
{
_dateReceive=(SimpleDateFormat[])__dateReceiveCache.get();
if (_dateReceive==null)
{
... |
java | static Predicate<DateValue> weekIntervalFilter(
final int interval, final Weekday wkst, final DateValue dtStart) {
return new Predicate<DateValue>() {
DateValue wkStart;
{
// the latest day with day of week wkst on or before dtStart
DTBuilder ... |
python | def polygon_to_points(coords, z=None):
"""
Given a list of pairs of points which define a polygon,
return a list of points interior to the polygon
"""
bounds = array(coords).astype('int')
bmax = bounds.max(0)
bmin = bounds.min(0)
path = Path(bounds)
grid = meshgrid(range(bmin[0],... |
java | private static void writeResourceToFile(
String resourceName, File file) throws IOException
{
if (file == null)
{
throw new NullPointerException("Target file may not be null");
}
if (file.exists())
{
throw new IllegalArgumentException(... |
java | public static String calcNormalDensity(String slsnd, String slcly, String omPct) {
String satMt = calcSaturatedMoisture(slsnd, slcly, omPct);
String ret = product(substract("100", satMt), "0.0265");
LOG.debug("Calculate result for Normal density, g/cm-3 is {}", ret);
return ret;
} |
java | public static FlacFile open(InputStream inp) throws IOException, FileNotFoundException {
inp.mark(4);
byte[] header = new byte[4];
IOUtils.readFully(inp, header);
inp.reset();
if(header[0] == (byte)'O' && header[1] == (byte)'g' &&
header[2] == (byte)'g' && header[3] == (byt... |
java | protected <T> T defaultIfNotSet(String propertyName, T defaultValue, Class<T> type) {
return (isSet(propertyName) ? convert(propertyName, type) : defaultValue);
} |
python | def get_question_form_for_create(self, item_id, question_record_types):
"""Gets the question form for creating new questions.
A new form should be requested for each create transaction.
arg: item_id (osid.id.Id): an assessment item ``Id``
arg: question_record_types (osid.type.Typ... |
java | public ListResourceComplianceSummariesResult withResourceComplianceSummaryItems(ResourceComplianceSummaryItem... resourceComplianceSummaryItems) {
if (this.resourceComplianceSummaryItems == null) {
setResourceComplianceSummaryItems(new com.amazonaws.internal.SdkInternalList<ResourceComplianceSummary... |
python | def validate(self, data):
"""
Check that the video data is valid.
"""
if data is not None and not isinstance(data, dict):
raise serializers.ValidationError("Invalid data")
try:
profiles = [ev["profile"] for ev in data.get("encoded_videos", [])]
... |
java | public int clearDiskCache() {
final String methodName = "clearDiskCache()";
int returnCode = NO_EXCEPTION;
Exception diskException = null;
try {
this.invalidationBuffer.setDiskClearInProgress(true);
if (delayOffload) {
if (!this.disableDependencyI... |
python | def generate_classes(outf, msgs):
"""
Generate the implementations of the classes representing MAVLink messages.
"""
print("Generating class definitions")
wrapper = textwrap.TextWrapper(initial_indent="", subsequent_indent="")
outf.write("\nmavlink.messages = {};\n\n");
def field_descripti... |
python | def get_tip_labels(self, idx=None):
"""
Returns tip labels in the order they will be plotted on the tree, i.e.,
starting from zero axis and counting up by units of 1 (bottom to top
in right-facing trees; left to right in down-facing). If 'idx' is
indicated then a list of tip la... |
python | def get_scoring_data_iters(sources: List[str],
target: str,
source_vocabs: List[vocab.Vocab],
target_vocab: vocab.Vocab,
batch_size: int,
batch_num_devices: int,
... |
java | public EClass getEndSegmentCommand() {
if (endSegmentCommandEClass == null) {
endSegmentCommandEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(437);
}
return endSegmentCommandEClass;
} |
java | private Collection<TypeElement> subinterfaces(TypeElement te) {
Collection<TypeElement> ret = classToSubinterface.get(te);
if (ret == null) {
ret = new TreeSet<>(utils.makeClassUseComparator());
Set<TypeElement> subs = classtree.subInterfaces(te);
if (subs != null) {
... |
python | def disc(ghi, altitude, doy, pressure=101325,
min_sin_altitude=0.065, min_altitude=3, max_airmass=12):
"""
Estimate Direct Normal Irradiance from Global Horizontal Irradiance
using the DISC model.
The DISC algorithm converts global horizontal irradiance to direct
normal irradiance through ... |
java | public static boolean checkMmul(INDArray first, INDArray second, double maxRelativeDifference,
double minAbsDifference) {
if (first.size(1) != second.size(0))
throw new IllegalArgumentException("first.columns != second.rows");
RealMatrix rmFirst = convertToApacheMatrix(fi... |
java | @Override
public boolean subsumes(Atomic atomic) {
if (!atomic.isAtom()) return false;
Atom parent = (Atom) atomic;
MultiUnifier multiUnifier = this.getMultiUnifier(parent, UnifierType.SUBSUMPTIVE);
if (multiUnifier.isEmpty()) return false;
MultiUnifier inverse = multiUnifie... |
java | void undoAdd(Link newLink)
throws ObjectManagerException {
final String methodName = "undoAdd";
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this, cclass, methodName, new Object[] { newLink });
// Detach this Link from the list.
... |
java | private void verifyFrameOpcode(WebSocketFrame frame) throws WebSocketException
{
switch (frame.getOpcode())
{
case CONTINUATION:
case TEXT:
case BINARY:
case CLOSE:
case PING:
case PONG:
// Known opcode
... |
java | static Set<String> parseParametersToCheck(final String initParamValue) {
final Set<String> parameterNames = new HashSet<String>();
if (null == initParamValue) {
return parameterNames;
}
final String[] tokens = initParamValue.split("\\s+");
if (0 == tokens.length) ... |
python | def find(self):
'''
find the infors.
'''
keyword = self.get_argument('keyword').strip()
kwd = {
'pager': '',
'title': 'Searching Result',
}
self.render('user/info_list/find_list.html',
userinfo=self.userinfo,
... |
python | def plot_roc(evaluation, class_index=None, title=None, key_loc="lower right", outfile=None, wait=True):
"""
Plots the ROC (receiver operator characteristics) curve for the given predictions.
TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html
:param evaluation: the evalu... |
python | def send_frame(self, frame):
'''
Queue a frame for sending. Will send immediately if there are no
pending synchronous transactions on this connection.
'''
if self.closed:
if self.close_info and len(self.close_info['reply_text']) > 0:
raise ChannelClos... |
python | def _subproc(scons_env, cmd, error = 'ignore', **kw):
"""Do common setup for a subprocess.Popen() call
This function is still in draft mode. We're going to need something like
it in the long run as more and more places use subprocess, but I'm sure
it'll have to be tweaked to get the full desired funct... |
python | def get_key_value(parts, key_field_num, ignore_missing_keys, seen_keys,
output_type):
"""
get the key value from the line and check it's not a dup. or missing. fields
with only whitespace are considered empty (missing).
:param ignore_missing_keys: if True, return None for missing keys. If fal... |
python | def format(self, version=0x10, wipe=None):
"""Format a FeliCa Lite Tag for NDEF.
"""
return super(FelicaLite, self).format(version, wipe) |
java | public Optional<Tag> getTag() {
AttributeType tagAttributeType = annotationType.getTagAttribute();
if (tagAttributeType == null) {
return Optional.ofNullable(get(Types.TAG).as(Tag.class));
}
return Optional.ofNullable(get(tagAttributeType).as(Tag.class));
} |
java | public static final CurrencySymbolPosition parseCurrencySymbolPosition(String value)
{
CurrencySymbolPosition result = CurrencySymbolPosition.BEFORE;
switch (NumberHelper.getInt(value))
{
case 0:
{
result = CurrencySymbolPosition.BEFORE;
break;
}
... |
python | def sync_to(self, destination):
"""
Sync an RPM from a REMOTE to a LOCAL path.
Returns True if the item required a sync, False if it already
existed locally.
TODO: Remove dupe code in Cart.py:sync_remotes()
"""
rpm = RPM(self.path)
rpm.sync(destination)
... |
java | boolean runResumeReadWrite() {
boolean ret = false;
if(anyAreSet(state, FLAG_SHOULD_RESUME_WRITES)) {
responseChannel.runResume();
ret = true;
}
if(anyAreSet(state, FLAG_SHOULD_RESUME_READS)) {
requestChannel.runResume();
ret = true;
... |
java | public void updateCachingAndArtifacts(ParsedDeployment parsedDeployment) {
CommandContext commandContext = Context.getCommandContext();
final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCac... |
python | def __skeleton_difference(graph, image, boundary_term, spacing):
"""
A skeleton for the calculation of intensity difference based boundary terms.
Iterates over the images dimensions and generates for each an array of absolute
neighbouring voxel :math:`(p, q)` intensity differences :math:`|I_p, I_q|... |
python | def process(self, sched, coro):
"""This is called when the operation is to be processed by the
scheduler. Code here works modifies the scheduler and it's usualy
very crafty. Subclasses usualy overwrite this method and call it from
the superclass."""
if self.prio == priorit... |
python | def get_historical_price(self, crypto, fiat, at_time):
"""
Using the quandl.com API, get the historical price (by day).
The CRYPTOCHART source claims to be from multiple exchange sources
for price (they say best exchange is most volume).
"""
# represents the 'width' of th... |
python | def insert_before(self, obj, value, recursive=True):
"""Insert *value* immediately before *obj*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances... |
java | public synchronized XAttribute put(String key, XAttribute value) {
if(backingStore == null) {
try {
backingStore = backingStoreClass.newInstance();
} catch (Exception e) {
// Fuckup
e.printStackTrace();
}
}
return backingStore.put(key, value);
} |
java | public static Map<String, Object> createFormParamRefreshTokenGrantType(String refreshToken, String scope, String clientId) {
if (refreshToken == null) {
throw new IllegalArgumentException("Missing the required parameter 'refresh_token'");
}
Map<String, Object> formParams = new HashMa... |
python | def clipPolygons(self, polygons):
"""
Recursively remove all polygons in `polygons` that are inside this BSP
tree.
"""
if not self.plane:
return polygons[:]
front = []
back = []
for poly in polygons:
self.plane.splitPolygon(poly,... |
python | def _set_annotation_to_str(annotation_data: Mapping[str, Mapping[str, bool]], key: str) -> str:
"""Return a set annotation string."""
value = annotation_data[key]
if len(value) == 1:
return 'SET {} = "{}"'.format(key, list(value)[0])
x = ('"{}"'.format(v) for v in sorted(value))
return 'S... |
java | public static Environment declareThisWithin(Decl.FunctionOrMethod decl, Environment environment) {
if (decl instanceof Decl.Method) {
Decl.Method method = (Decl.Method) decl;
environment = environment.declareWithin("this", method.getLifetimes());
}
return environment;
} |
python | def has_object_permission(checker_name, user, obj):
"""Check if a user has permission to perform an action on an object."""
if user and user.is_superuser:
return True
checker = PermissionsManager.retrieve_checker(checker_name)
user_roles = get_user_roles(user)
if not user_roles:
us... |
java | public String getArrayClassName(Class<?> clazz) {
if (clazz.isArray()) {
return getArrayClassName(clazz.getComponentType()) + "[]";
}
return clazz.getName();
} |
python | def create_cloudwatch_log_event(app_name, env, region, rules):
"""Create cloudwatch log event for lambda from rules.
Args:
app_name (str): name of the lambda function
env (str): Environment/Account for lambda function
region (str): AWS region of the lambda function
rules (str): ... |
java | @Override
public void reconnectFailedConnection(SearchFilter searchFilter) throws SQLException {
proxy.lock.lock();
try {
if (!searchFilter.isInitialConnection()
&& (isExplicitClosed() || !isMasterHostFail())) {
return;
}
currentConnectionAttempts.incrementAndGet();
... |
python | def filter_from_url_arg(model_cls, query, arg, query_operator=and_,
arg_types=None):
"""
Parse filter URL argument ``arg`` and apply to ``query``
Example: 'column1<=value,column2==value' -> query.filter(Model.column1 <= value, Model.column2 == value)
"""
fields = arg.split(... |
java | public void moveTo(float offsetX, float offsetY) {
if (swipeVertical) {
// Check X offset
if (toCurrentScale(optimalPageWidth) < getWidth()) {
offsetX = getWidth() / 2 - toCurrentScale(optimalPageWidth) / 2;
} else {
if (offsetX > 0) {
offse... |
python | def _get_sorting_key_values(self, array1, array2):
"""return the sorting key values as a series"""
concat_arrays = numpy.concatenate([array1, array2])
unique_values = numpy.unique(concat_arrays)
return numpy.sort(unique_values) |
python | def get_computer_desc():
'''
Get PRETTY_HOSTNAME value stored in /etc/machine-info
If this file doesn't exist or the variable doesn't exist
return False.
:return: Value of PRETTY_HOSTNAME if this does not exist False.
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' sys... |
java | @Override
protected AssetInformation extractInformationFromAsset(File archive, final ArtifactMetadata metadata) throws PrivilegedActionException, ProductInfoParseException, IOException {
// Create the asset information
AssetInformation assetInformtion = new AssetInformation();
ZipFile zipFil... |
python | def replace_product_by_id(cls, product_id, product, **kwargs):
"""Replace Product
Replace all attributes of Product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_product_by_id(produc... |
java | protected void initRequest()
{
_hostHeader = null;
_xForwardedHostHeader = null;
_expect100Continue = false;
_cookies.clear();
_contentLengthIn = -1;
_hasReadStream = false;
_readEncoding = null;
//_request = request;
//_requestFacade = getHttp().createFacade(this);
_... |
python | def update(self):
"""Get all events and process them by calling update_on_event()"""
events = pygame.event.get()
for e in events:
self.update_on_event(e)
for wid, cond in self._widgets:
if cond():
wid.update(events) |
python | def create(klass, account, name):
"""
Creates a new tailored audience.
"""
audience = klass(account)
getattr(audience, '__create_audience__')(name)
try:
return audience.reload()
except BadRequest as e:
audience.delete()
raise e |
python | def _init_map(self):
"""stub"""
super(IRTItemFormRecord, self)._init_map()
self.my_osid_object_form._my_map['decimalValues']['difficulty'] = \
self._decimal_value_metadata['default_decimal_values'][1]
self.my_osid_object_form._my_map['decimalValues']['discrimination'] = \
... |
java | public Observable<ServiceResponse<RefreshIndex>> refreshIndexMethodWithServiceResponseAsync(String listId, String language) {
if (this.client.baseUrl() == null) {
throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null.");
}
if (listId == nu... |
python | def download(self, id, directory):
"""
Download the file with given identifier to the given directory
:param id: Identifier of the lot to download
:param directory: Directory where the downloaded ZIP should be stored
:return: None
"""
url = (self._base + 'lot/{0}/... |
python | def variables(self):
"""
Display a list of templatable variables present in the file.
Templating is accomplished by creating a bracketed object in the same
way that Python performs `string formatting`_. The editor is able to
replace the placeholder value of the template. Integer... |
python | def examples():
"""Prints examples of using the script to the console using colored output.
"""
script = "Continuous Integration Automation Server"
explain = ("For complex codes with many collaborators, it is often difficult to maintian "
"a pristine code that everyone can rely on. If eve... |
java | public PagedList<VulnerabilityAssessmentScanRecordInner> listByDatabase(final String resourceGroupName, final String serverName, final String databaseName) {
ServiceResponse<Page<VulnerabilityAssessmentScanRecordInner>> response = listByDatabaseSinglePageAsync(resourceGroupName, serverName, databaseName).toBloc... |
python | def _safe_release_connection(self):
"""Try to release a connection. If an exception is hit, log and return
the error string.
"""
try:
self.adapter.release_connection()
except Exception as exc:
logger.debug(
'Error releasing connection for n... |
python | def _set_factory_context(factory_class, bundle_context):
# type: (type, Optional[BundleContext]) -> Optional[FactoryContext]
"""
Transforms the context data dictionary into its FactoryContext object form.
:param factory_class: A manipulated class
:param bundle_context: The class bundle context
... |
python | def is_balance_proof_usable_onchain(
received_balance_proof: BalanceProofSignedState,
channel_state: NettingChannelState,
sender_state: NettingChannelEndState,
) -> SuccessOrError:
""" Checks the balance proof can be used on-chain.
For a balance proof to be valid it must be newer than t... |
python | def write(self, path=None, *args, **kwargs):
"""
Perform formatting and write the formatted string to a file or stdout.
Optional arguments can be used to format the editor's contents. If no
file path is given, prints to standard output.
Args:
path (str): Full file p... |
java | private void free(IoSession session) {
IoBuffer buf = buffersMap.remove(session);
if (buf != null) {
buf.free();
}
} |
python | def html5_parse_simple_color(input):
"""
Apply the simple color parsing algorithm from section 2.4.6 of
HTML5.
"""
# 1. Let input be the string being parsed.
#
# 2. If input is not exactly seven characters long, then return an
# error.
if not isinstance(input, unicode) or len(inp... |
java | @Override
public void lifecycleEvent(LifecycleEvent event) { // called several times
super.lifecycleEvent(event);
if (!alreadyFirstLifecycle) { // ContextConfig is not thread-safe so no care
alreadyFirstLifecycle = true;
if (isWebFragmentsSelectorEnabled()) {
... |
java | @Override
public Request<RequestSpotFleetRequest> getDryRunRequest() {
Request<RequestSpotFleetRequest> request = new RequestSpotFleetRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
python | def get_function(pkgpath):
"""Take a full path to a python method or class, for example
mypkg.subpkg.method and return the method or class (after importing the
required packages)
"""
# Extract the module and function name from pkgpath
elems = pkgpath.split('.')
if len(elems) <= 1:
ra... |
python | def consume_arguments(self, argument_list):
"""
Takes arguments from a list while there are parameters that can accept them
"""
while True:
argument_count = len(argument_list)
for parameter in self.values():
argument_list = parameter.consume_argume... |
java | @Override
public Map<URI, MatchResult> findOperationsClassifiedBySome(Set<URI> modelReferences) {
return findServicesClassifiedBySome(modelReferences, LogicConceptMatchType.Subsume);
} |
python | def sort_def_dict(def_dict: Dict[str, List[str]]) -> Dict[str, List[str]]:
"""Sort values of the lists of a defaultdict(list)."""
for _, dd_list in def_dict.items():
dd_list.sort()
return def_dict |
java | @SuppressWarnings("unchecked")
public void addItemEventListener(@SuppressWarnings("rawtypes") ItemEventListener listener) {
StanzaListener conListener = new ItemEventTranslator(listener);
itemEventToListenerMap.put(listener, conListener);
pubSubManager.getConnection().addSyncStanzaListener(c... |
java | @Override
public CPRuleUserSegmentRel[] findByCPRuleId_PrevAndNext(
long CPRuleUserSegmentRelId, long CPRuleId,
OrderByComparator<CPRuleUserSegmentRel> orderByComparator)
throws NoSuchCPRuleUserSegmentRelException {
CPRuleUserSegmentRel cpRuleUserSegmentRel = findByPrimaryKey(CPRuleUserSegmentRelId);
Sessio... |
python | def getInstructions(self):
'''
The same as calling ``client.getInstructions(build.setID)``
:returns: A list of instructions.
:rtype: list
'''
self._instructions = self._client.getInstructions(self.setID)
return self._instructions |
python | def individual(self, ind_id=None):
"""Return a individual object
Args:
ind_id (str): A individual id
Returns:
individual (puzzle.models.individual)
"""
for ind_obj in self.individual_objs:
if ind_obj.ind_id... |
java | public Optional<KeyTransaction> show(long transactionId)
{
return HTTP.GET(String.format("/v2/key_transactions/%d.json", transactionId), KEY_TRANSACTION);
} |
python | def parse_endnotes(document, xmlcontent):
"""Parse endnotes document.
Endnotes are defined in file 'endnotes.xml'
"""
endnotes = etree.fromstring(xmlcontent)
document.endnotes = {}
for note in endnotes.xpath('.//w:endnote', namespaces=NAMESPACES):
paragraphs = [parse_paragraph(documen... |
java | public static URL constructResourceURL(Class<?> c, String resName) {
String strUrl = "";
if (resName.startsWith("/")) // 资源名称以"/"开头,从类所在的Class Path根目录开始定位资源
strUrl = getClassRootPath(c) + resName.substring(1);
else
// 资源名称不以"/"开头,从类所在的目录开始定位资源
strUrl = getClassPath(c) + resName;
try {
re... |
python | def Convert(self, metadata, config, token=None):
"""Converts DNSClientConfiguration to ExportedDNSClientConfiguration."""
result = ExportedDNSClientConfiguration(
metadata=metadata,
dns_servers=" ".join(config.dns_server),
dns_suffixes=" ".join(config.dns_suffix))
yield result |
python | def prepare_labels(label_type, org_xml_dir=ORG_XML_DIR, label_dir=LABEL_DIR):
""" Prepare the neural network output targets."""
if not os.path.exists(os.path.join(label_dir, "TEXT")):
os.makedirs(os.path.join(label_dir, "TEXT"))
if not os.path.exists(os.path.join(label_dir, "WORDLIST")):
os... |
python | def tar_open(f):
"""Open either a filename or a file-like object as a TarFile.
Parameters
----------
f : str or file-like object
The filename or file-like object from which to read.
Returns
-------
TarFile
A `TarFile` instance.
"""
if isinstance(f, six.string_types... |
python | def wait(value, must_be_child=False):
'''Wait for a possible asynchronous value to complete.
'''
current = getcurrent()
parent = current.parent
if must_be_child and not parent:
raise MustBeInChildGreenlet('Cannot wait on main greenlet')
return parent.switch(value) if parent else value |
python | def register_converter(self, converter, conv_type, conv_format=None, *, name=None):
"""
Register custom path parameter converter.
:param BaseConverter converter: Converter
Subclass of werkzeug's BaseConverter
:param str conv_type: Parameter type
:param str conv_forma... |
java | public void marshall(DescribeGlobalTableRequest describeGlobalTableRequest, ProtocolMarshaller protocolMarshaller) {
if (describeGlobalTableRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(d... |
java | public final hqlParser.updateStatement_return updateStatement() throws RecognitionException {
hqlParser.updateStatement_return retval = new hqlParser.updateStatement_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token UPDATE6=null;
Token VERSIONED7=null;
ParserRuleReturnScope optionalFro... |
java | public static long extractTimestamp64Ascii(String id64ascii) throws NumberFormatException {
return extractTimestamp64(Long.parseLong(id64ascii, Character.MAX_RADIX));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.