language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public ChannelBuffer formatQueryV1(final TSQuery query,
final List<DataPoints[]> results, final List<Annotation> globals) {
throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED,
"The requested API endpoint has not been implemented",
this.getClass().getCanonicalName() +
... |
java | @Override
public IRundeckProject createFrameworkProjectStrict(final String projectName, final Properties properties) {
return createFrameworkProjectInt(projectName,properties,true);
} |
java | public OvhTask serviceName_modem_blocIp_POST(String serviceName, OvhServiceStatusEnum status) throws IOException {
String qPath = "/xdsl/{serviceName}/modem/blocIp";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "status", status);
String resp... |
python | def _ExtractList(self, fields, ignores=(",",), terminators=()):
"""Extract a list from the given fields."""
extracted = []
i = 0
for i, field in enumerate(fields):
# Space-separated comma; ignore, but this is not a finished list.
# Similar for any other specified ignores (eg, equals sign).
... |
python | def mime_type(filename):
""" Guess mime type for the given file name
Note: this implementation uses python_magic package which is not thread-safe, as a workaround global lock is
used for the ability to work in threaded environment
:param filename: file name to guess
:return: str
"""
# TODO: write lock-free mim... |
java | public void addStaticElVarValue(final String name, final String value) {
check(!staticElValues.containsKey(name),
"Duplicate el variable %s value declaration: %s (original: %s)", name, value,
staticElValues.get(name));
check(!dynamicElValues.contains(name),
... |
python | def checkUpload(self, file_obj, full_path = '/', overwrite = False):
"""Check whether it is possible to upload a file.
>>> s = nd.checkUpload('~/flower.png','/Picture/flower.png')
:param file_obj: A file-like object to check whether possible to upload. You can pass a string as a file_obj o... |
java | public static Controller.StreamCut decode(final String scope, final String stream, Map<Long, Long> streamCut) {
return Controller.StreamCut.newBuilder().setStreamInfo(createStreamInfo(scope, stream)).putAllCut(streamCut).build();
} |
java | @SuppressWarnings("nls")
protected DataSource datasourceFromConfig(JdbcOptionsBean config) {
Properties props = new Properties();
props.putAll(config.getDsProperties());
setConfigProperty(props, "jdbcUrl", config.getJdbcUrl());
setConfigProperty(props, "username", config.getUsername(... |
python | def kde(self, name, npoints=_npoints, **kwargs):
"""
Calculate kernel density estimator for parameter
"""
data = self.get(name,**kwargs)
return kde(data,npoints) |
python | def reply_webapi(self, text, attachments=None, as_user=True, in_thread=None):
"""
Send a reply to the sender using Web API
(This function supports formatted message
when using a bot integration)
If the message was send in a thread, answer in a thread per default... |
java | @XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "businessCategory")
public JAXBElement<String> createBusinessCategory(String value) {
return new JAXBElement<String>(_BusinessCategory_QNAME, String.class, null, value);
} |
python | def merge_link_object(serializer, data, instance):
"""Add a 'links' attribute to the data that maps field names to URLs.
NOTE: This is the format that Ember Data supports, but alternative
implementations are possible to support other formats.
"""
link_object = {}
if not getattr(instance... |
java | public Pairtree getPairtree(final String aBucket, final String aBucketPath) throws PairtreeException {
if (myAccessKey.isPresent() && mySecretKey.isPresent()) {
final String accessKey = myAccessKey.get();
final String secretKey = mySecretKey.get();
if (myRegion.isPresent()) ... |
java | public void useAttachmentServiceWithWebClient() throws Exception {
final String serviceURI = "http://localhost:" + port + "/services/attachments/multipart";
JSONProvider provider = new JSONProvider();
provider.setIgnoreNamespaces(true);
provider.setInTransformElements(... |
java | @Override
public Optional<String> getMessage(final String code) {
try {
return Optional.of(messageSourceAccessor.getMessage(code));
} catch(NoSuchMessageException e) {
return Optional.empty();
}
} |
java | public void attribute(String attribute, String expectedValue) {
String value = checkAttribute(attribute, expectedValue, 0, 0);
String reason = NO_ELEMENT_FOUND;
if (value == null && getElement().is().present()) {
reason = "Attribute doesn't exist";
}
assertNotNull(rea... |
python | def read(self, n):
"""Read n bytes.
Returns exactly n bytes of data unless the underlying raw IO
stream reaches EOF.
"""
buf = self._read_buf
pos = self._read_pos
end = pos + n
if end <= len(buf):
# Fast path: the data to read is fully buffere... |
java | @Override
public Long next() {
if (!hasNext()) {
throw new NoSuchElementException(toString() + " ended");
}
current = next;
next = next + increment;
return current();
} |
java | public static List<PropertyDescriptor> getPropertyDescriptorsWithGetters(final Class<?> clazz) {
final List<PropertyDescriptor> relevantDescriptors = new ArrayList<PropertyDescriptor>();
final PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(clazz);
if (propertyDescriptors != ... |
java | public void setLocalStripedActive()
throws ClientException,
IOException {
if (gSession.serverAddressList == null) {
throw new ClientException(ClientException.CALL_PASSIVE_FIRST);
}
try {
gLocalServer.setStripedActive(gSession.serverAddressList);
... |
java | public static TransformedInputRow of(final InputRow row) {
if (row instanceof TransformedInputRow) {
// re-use existing transformed input row.
return (TransformedInputRow) row;
} else {
return new TransformedInputRow(row, row.getId());
}
} |
python | def reload(self, reload_timeout, save_config):
"""Reload the device."""
PROCEED = re.compile(re.escape("Proceed with reload? [confirm]"))
CONTINUE = re.compile(re.escape("Do you wish to continue?[confirm(y/n)]"))
DONE = re.compile(re.escape("[Done]"))
CONFIGURATION_COMPLETED = re... |
java | private synchronized void createReconstituteThreadPool()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createReconstituteThreadPool");
if (_reconstituteThreadpool == null)
{
int maxThreadPoolSize;
if (messageProcesso... |
python | async def save_form(self, form, request, **resources):
"""Save self form."""
if not self.can_create and not self.resource:
raise muffin.HTTPForbidden()
if not self.can_edit and self.resource:
raise muffin.HTTPForbidden()
resource = self.resource or self.populate... |
java | @Override
public void handleException(@Nullable Throwable e, boolean endApplication) {
final ReportBuilder builder = new ReportBuilder();
builder.exception(e)
.customData(customData);
if (endApplication) {
builder.endApplication();
}
builder.build(... |
python | def sortarai(datablock, s, Zdiff, **kwargs):
"""
sorts data block in to first_Z, first_I, etc.
Parameters
_________
datablock : Pandas DataFrame with Thellier-Tellier type data
s : specimen name
Zdiff : if True, take difference in Z values instead of vector difference
NB: this... |
python | def _trim_adapters(fastq_files, out_dir, data):
"""
for small insert sizes, the read length can be longer than the insert
resulting in the reverse complement of the 3' adapter being sequenced.
this takes adapter sequences and trims the only the reverse complement
of the adapter
MYSEQUENCEAAAARE... |
java | public static Manifest getManifest(Location jarLocation) throws IOException {
URI uri = jarLocation.toURI();
// Small optimization if the location is local
if ("file".equals(uri.getScheme())) {
JarFile jarFile = new JarFile(new File(uri));
try {
return jarFile.getManifest();
} fin... |
python | def FlagCxx11Features(filename, clean_lines, linenum, error):
"""Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to ... |
python | def _create_app(self, color_depth, term='xterm'):
"""
Create CommandLineInterface for this client.
Called when the client wants to attach the UI to the server.
"""
output = Vt100_Output(_SocketStdout(self._send_packet),
lambda: self.size,
... |
python | def _bucket_key(self):
""" Returns hash bucket key for the redis key """
return "{}.size.{}".format(
self.prefix, (self._hashed_key//1000)
if self._hashed_key > 1000 else self._hashed_key) |
java | public static ObjectInputStream newObjectInputStream(Path self, final ClassLoader classLoader) throws IOException {
return IOGroovyMethods.newObjectInputStream(Files.newInputStream(self), classLoader);
} |
java | public void marshall(DeleteAliasRequest deleteAliasRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteAliasRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteAliasRequest.getOrg... |
python | def action(method=None, **kwargs):
"""
Decorator that turns a function or controller method into an kervi action.
it is possible to call the action in other kervi processes or modules.
@action
def my_action(p)
...
call it via Actions["my_action"](10)
@a... |
java | public OperationStatusResponseInner beginDeleteInstances(String resourceGroupName, String vmScaleSetName, List<String> instanceIds) {
return beginDeleteInstancesWithServiceResponseAsync(resourceGroupName, vmScaleSetName, instanceIds).toBlocking().single().body();
} |
java | protected boolean checkForSignIn() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if ((authentication != null) && authentication.isAuthenticated()) {
LOG.debug("Security context contains CAS authentication");
return true;
}
return false;
} |
python | def create_slim_mapping(self, subset=None, subset_nodes=None, relations=None, disable_checks=False):
"""
Create a dictionary that maps between all nodes in an ontology to a subset
Arguments
---------
ont : `Ontology`
Complete ontology to be mapped. Assumed pre-filter... |
java | private static String[] readSMARTSPattern(String filename) throws Exception {
InputStream ins = StandardSubstructureSets.class.getClassLoader().getResourceAsStream(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
List<String> tmp = new ArrayList<String>();
... |
python | def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements):
"""Creates additional source- and header-files for the numbered sequence MPL-containers."""
# Create additional container-list without "map".
containersWithoutMap = containers[:]
try:
containersWithoutMap.rem... |
python | def vad_filter_features(vad_labels, features, filter_frames="trim_silence"):
""" Trim the spectrogram to remove silent head/tails from the speech sample.
Keep all remaining frames or either speech or non-speech only
@param: filter_frames: the value is either 'silence_only' (keep the speech, remove everythin... |
java | public JsAPISignature createJsAPISignature(String url){
if(jsAPITicket == null || jsAPITicket.expired()) {
getJsAPITicket();
}
long timestamp = System.currentTimeMillis() / 1000;
String nonce = RandomStringGenerator.getRandomStringByLength(16);
String ticket =... |
python | def connect(self):
"""Connect to beanstalkd server."""
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.settimeout(self._connect_timeout)
SocketError.wrap(self._socket.connect, (self.host, self.port))
self._socket.settimeout(None)
self._socket... |
java | @Override
public int compareTo(Object obj) {
if (obj instanceof URI) {
return this.toString().compareTo(obj.toString());
}
else {
return -1;
}
} |
java | public static void writeAll(GatheringByteChannel ch, ByteBuffer[] bbs, int offset, int length) throws IOException
{
long all = 0;
for (int ii=0;ii<length;ii++)
{
all += bbs[offset+ii].remaining();
}
int count = 0;
while (all > 0)
{
... |
java | @Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof IPubSub) {
System.err.println("beanName:" + beanName + " bean:" + bean);
Publisher.listen((IPubSub) bean, this.getRedis());
}
return bean;
} |
python | def is_unwrapped(f):
"""If `f` was imported and then unwrapped, this function might return True.
.. |is_unwrapped| replace:: :py:func:`is_unwrapped`"""
try:
g = look_up(object_name(f))
return g != f and unwrap(g) == f
except (AttributeError, TypeError, ImportError):
return Fals... |
java | public NotificationWithSubscribers withSubscribers(Subscriber... subscribers) {
if (this.subscribers == null) {
setSubscribers(new java.util.ArrayList<Subscriber>(subscribers.length));
}
for (Subscriber ele : subscribers) {
this.subscribers.add(ele);
}
ret... |
python | def do_printActivity(self,args):
"""Print scaling activity details"""
parser = CommandArgumentParser("printActivity")
parser.add_argument(dest='index',type=int,help='refresh');
args = vars(parser.parse_args(args))
index = args['index']
activity = self.activities[index]
... |
java | protected void configureSecurity(final T builder, final String name) {
final GrpcChannelProperties properties = getPropertiesFor(name);
final Security security = properties.getSecurity();
if (properties.getNegotiationType() != NegotiationType.TLS // non-default
|| isNonNullAndNo... |
python | def _create_genome_regions(data):
"""Create whole genome contigs we want to process, only non-alts.
Skips problem contigs like HLAs for downstream analysis.
"""
work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), "coverage", dd.get_sample_name(data)))
variant_regions = os.path.join(wo... |
java | @Override
public void clearCache() {
entityCache.clearCache(CommerceUserSegmentCriterionImpl.class);
finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
} |
python | def _stacklevel_above_module(mod_name):
"""
Return the stack level (with 1 = caller of this function) of the first
caller that is not defined in the specified module (e.g. "pywbem.cim_obj").
The returned stack level can be used directly by the caller of this
function as an argument for the stacklev... |
python | def get_dicts_generator(word_min_freq=4,
char_min_freq=2,
word_ignore_case=False,
char_ignore_case=False):
"""Get word and character dictionaries from sentences.
:param word_min_freq: The minimum frequency of a word.
:param char_min_fr... |
java | public String getPrototypeName() {
String name = getClass().getName();
if (name.startsWith(ORG_GEOMAJAS)) {
name = name.substring(ORG_GEOMAJAS.length());
}
name = name.replace(".dto.", ".impl.");
return name.substring(0, name.length() - 4) + "Impl";
} |
java | public FixedDelayBuilder<P> delay(String... delays) {
for (String d : delays) {
if (d != null) {
delayProps.add(d);
}
}
return this;
} |
python | def _merge_cfgnodes(self, cfgnode_0, cfgnode_1):
"""
Merge two adjacent CFGNodes into one.
:param CFGNode cfgnode_0: The first CFGNode.
:param CFGNode cfgnode_1: The second CFGNode.
:return: None
"""
assert cfgnode_0.addr + cfgnode_0.size ... |
java | @SuppressWarnings("unchecked")
public <T> Http2StreamChannelBootstrap attr(AttributeKey<T> key, T value) {
if (key == null) {
throw new NullPointerException("key");
}
if (value == null) {
synchronized (attrs) {
attrs.remove(key);
}
... |
python | def get_available_palettes(chosen_palette):
''' Given a chosen palette, returns tuple of those available,
or None when not found.
Because palette support of a particular level is almost always a
superset of lower levels, this should return all available palettes.
Returns:
... |
python | def is_locked(self, request: AxesHttpRequest, credentials: dict = None) -> bool:
"""
Checks if the request or given credentials are locked.
"""
if settings.AXES_LOCK_OUT_AT_FAILURE:
return self.get_failures(request, credentials) >= settings.AXES_FAILURE_LIMIT
return... |
python | def optimizer_step(self, batch_info, device, model, rollout):
""" Single optimization step for a model """
batch_info.optimizer.zero_grad()
batch_result = self.calculate_gradient(batch_info=batch_info, device=device, model=model, rollout=rollout)
clip_gradients(batch_result, model, sel... |
java | @Deprecated
public static Class<?> getRawType(Type type) {
if (type instanceof Class) {
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
return getRawType(((ParameterizedType) type).getRawType());
} else if (type instanceof TypeVariable<?>) {
return getRawType(((TypeVariable<?>) t... |
python | def get_composition(source, *fxns):
"""Compose several extractors together, on a source."""
val = source
for fxn in fxns:
val = fxn(val)
return val |
java | @GET
@Path("/validate/{token}")
@Produces(MediaType.APPLICATION_JSON)
public Response validateAccount(@PathParam("token") String token) {
try{
if (authServerLogic.validateAccount(token)) {
return Response.ok().build();
} else {
return Response.... |
python | def compare_datetimes(d1, d2):
""" Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2, 0 if they are the same, or +1 ... |
python | def get_included_resources(request, serializer=None):
""" Build a list of included resources. """
include_resources_param = request.query_params.get('include') if request else None
if include_resources_param:
return include_resources_param.split(',')
else:
return get_default_included_res... |
java | public Subscription getSubscriptionFromRequest(HttpServletRequest request) {
String tokenHeader = request.getHeader("Authorization");
if (tokenHeader == null || tokenHeader.indexOf("Token ") != 0) {
LOG.info("Empty authorizationheader, or header does not start with 'Token ': " + tokenHeader);
return null;
... |
java | public static String getResponseCacheHeaderSettings(final String contentType) {
String parameter = MessageFormat.format(RESPONSE_CACHE_HEADER_SETTINGS, contentType);
return get().getString(parameter);
} |
python | def close(self):
""" Closes the object.
"""
if self._is_open:
self.mode = None
if self.handle:
self.handle.close()
self.handle = None
self.filename = None
self._is_open = False
self.status = None |
java | public void update(String server, Transaction t, boolean deleteMissingChildren) {
on(server).update(t, deleteMissingChildren);
} |
java | public AbstractSheet<TRow, TColumn, TCell> setColumns(List<TColumn> columns) {
this.columns = columns;
return this;
} |
java | @SafeVarargs
public static <T> void split(T[] src, T[]... parts) {
int srcPos = 0;
for (T[] dest : parts) {
System.arraycopy(src, srcPos, dest, 0, dest.length);
srcPos += dest.length;
}
} |
python | def transaction_retry(max_retries=1):
"""Decorator for methods doing database operations.
If the database operation fails, it will retry the operation
at most ``max_retries`` times.
"""
def _outer(fun):
@wraps(fun)
def _inner(*args, **kwargs):
_max_retries = kwargs.pop... |
python | def get_context_data(self, **kwargs):
"""Returns the template context, including the workflow class.
This method should be overridden in subclasses to provide additional
context data to the template.
"""
context = super(WorkflowView, self).get_context_data(**kwargs)
work... |
python | def list_launch_configurations(region=None, key=None, keyid=None,
profile=None):
'''
List all Launch Configurations.
CLI example::
salt myminion boto_asg.list_launch_configurations
'''
ret = get_all_launch_configurations(region, key, keyid, profile)
retu... |
python | def cmd_output_add(self, args):
'''add new output'''
device = args[0]
print("Adding output %s" % device)
try:
conn = mavutil.mavlink_connection(device, input=False, source_system=self.settings.source_system)
conn.mav.srcComponent = self.settings.source_component
... |
python | def detector(detector_type):
""" Returns a detector of the specified type. """
if detector_type == 'point_cloud_box':
return PointCloudBoxDetector()
elif detector_type == 'rgbd_foreground_mask_query':
return RgbdForegroundMaskQueryImageDetector()
elif detector_typ... |
python | def mutant_charts_for_feature(example_protos, feature_name, serving_bundles,
viz_params):
"""Returns JSON formatted for rendering all charts for a feature.
Args:
example_proto: The example protos to mutate.
feature_name: The string feature name to mutate.
serving_bundles: ... |
python | def updateSeriesAttributes(request):
'''
This function handles the filtering of available series classes and seriesteachers when a series
is chosen on the Substitute Teacher reporting form.
'''
if request.method == 'POST' and request.POST.get('event'):
series_option = request.POST.get(... |
java | private final int m() {
int n = 0;
int i = k0;
while (true) {
if (i > j)
return n;
if (!cons(i))
break;
i++;
}
i++;
while (true) {
while (true) {
if (i > j)
return n;
if (cons(i))
break;
i++;
}
i++;
n++;
while (true) {
if (i > j)
return n;
i... |
java | public void eInit(XtendTypeDeclaration container, String name, String modifier, IJvmTypeProvider context) {
setTypeResolutionContext(context);
if (this.sarlField == null) {
this.container = container;
this.sarlField = SarlFactory.eINSTANCE.createSarlField();
this.sarlField.setAnnotationInfo(XtendFactory.eI... |
python | def search_raw(self, query, indices=None, doc_types=None, headers=None, **query_params):
"""Execute a search against one or more indices to get the search hits.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to be passed
... |
python | def _check_submodule_status(root, submodules):
"""check submodule status
Has three return values:
'missing' - submodules are absent
'unclean' - submodules have unstaged changes
'clean' - all submodules are up to date
"""
if hasattr(sys, "frozen"):
# frozen via py2exe or similar, don... |
java | public static ExpectationFailed of(Throwable cause) {
if (_localizedErrorMsg()) {
return of(cause, defaultMessage(EXPECTATION_FAILED));
} else {
touchPayload().cause(cause);
return _INSTANCE;
}
} |
python | def voight_painting(h):
"""Paint haplotypes, assigning a unique integer to each shared haplotype
prefix.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
Returns
-------
painting : ndarray, int, shape (n_variants, n_haplotypes)
... |
python | def _list_superclasses(class_def):
"""Return a list of the superclasses of the given class"""
superclasses = class_def.get('superClasses', [])
if superclasses:
# Make sure to duplicate the list
return list(superclasses)
sup = class_def.get('superClass', None)
if sup:
return ... |
java | public List<File> scan(Resource resource) {
Scanner scanner = buildContext.newScanner(new File(resource.getDirectory()), true);
setupScanner(scanner, resource);
scanner.scan();
List<File> files = new ArrayList<File>();
for (String file : scanner.getIncludedFiles()) {
... |
java | public static CProduct[] findByGroupId_PrevAndNext(long CProductId,
long groupId, OrderByComparator<CProduct> orderByComparator)
throws com.liferay.commerce.product.exception.NoSuchCProductException {
return getPersistence()
.findByGroupId_PrevAndNext(CProductId, groupId,
orderByComparator);
} |
python | def set_target(self, target: EventDispatcherBase) -> None:
"""
This method should be called by the event dispatcher that dispatches this event
to set its target property.
Args:
target (EventDispatcherBase): The event dispatcher that will dispatch this event.
... |
java | public boolean eq(LongIntSortedVector other) {
// This is slow, but correct.
LongIntSortedVector v1 = LongIntSortedVector.getWithNoZeroValues(this);
LongIntSortedVector v2 = LongIntSortedVector.getWithNoZeroValues(other);
if (v2.size() != v1.size()) {
return ... |
java | public final String getLikelyEndContextMismatchCause(SanitizedContentKind contentKind) {
Preconditions.checkArgument(!isValidEndContextForContentKind(contentKind));
if (contentKind == SanitizedContentKind.ATTRIBUTES) {
// Special error message for ATTRIBUTES since it has some specific logic.
return ... |
java | public <T> T doAs(PrivilegedAction<T> action) {
return Subject.doAs(null, action);
} |
java | public Javalin start() {
Util.logJavalinBanner(this.config.showJavalinBanner);
JettyUtil.disableJettyLogger();
long startupTimer = System.currentTimeMillis();
if (server.getStarted()) {
throw new IllegalStateException("Cannot call start() again on a started server.");
... |
python | def orthonormal_initializer(output_size, input_size, debug=False):
"""adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/linalg.py
Parameters
----------
output_size : int
input_size : int
debug : bool
Whether to skip this initializer
Returns
-------
... |
python | def getRaw(self, instance, **kwargs):
"""Returns raw field value (possible wrapped in BaseUnit)
"""
value = ObjectField.get(self, instance, **kwargs)
# getattr(instance, "Remarks") returns a BaseUnit
if callable(value):
value = value()
return value |
python | def append(self, new_points_len):
'''Allocate memory for a new run and return a reference to that memory
wrapped in an array of size ``(new_points_len, self.dim)``.
:param new_points_len:
Integer; the number of points to be stored in the target memory.
'''
new_poin... |
java | public static PluginSpec readPluginSpecFile(URL pluginSpec) throws IOException {
return (PluginSpec) mapper.reader(PluginSpec.class).readValue(pluginSpec);
} |
java | public int deleteByTableName(String tableName) throws SQLException {
DeleteBuilder<Extensions, Void> db = deleteBuilder();
db.where().eq(Extensions.COLUMN_TABLE_NAME, tableName);
int deleted = db.delete();
return deleted;
} |
python | def lcopt_bw2_forwast_setup(use_autodownload=True, forwast_path=None, db_name=FORWAST_PROJECT_NAME, overwrite=False):
"""
Utility function to set up brightway2 to work correctly with lcopt using the FORWAST database instead of ecoinvent
By default it'll try and download the forwast database as a .... |
python | def dict_find_keys(dict_, val_list):
r"""
Args:
dict_ (dict):
val_list (list):
Returns:
dict: found_dict
CommandLine:
python -m utool.util_dict --test-dict_find_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_dict import * # NOQA
>>>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.