language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Override
public <B> Try<T, B> pure(B b) {
return success(b);
} |
java | @SuppressWarnings("rawtypes")
public List<Interval> getIntervals() {
List<Interval> lstIntervals = new ArrayList<Interval>();
for (AbstractEdge<T> e : this.edges) {
lstIntervals.addAll(e.getIntervals());
}
return lstIntervals;
} |
python | def ints(l, ifilter=lambda x: x, idescr=None):
""" Parses a comma-separated list of ints. """
if isinstance(l, string_types):
if l[0] == '[' and l[-1] == ']':
l = l[1:-1]
l = list(map(lambda x: x.strip(), l.split(',')))
try:
l = list(map(ifilter, list(map(int, l))))
e... |
java | public void subDivide() {
northWest = new QuadTree(this, data, new Cell(boundary.getX() - .5 * boundary.getHw(),
boundary.getY() - .5 * boundary.getHh(), .5 * boundary.getHw(), .5 * boundary.getHh()));
northEast = new QuadTree(this, data, new Cell(boundary.getX() + .5 * boundary.... |
python | def get_services(self):
"""Returns a list of FritzService-objects."""
result = []
nodes = self.root.iterfind(
'.//ns:service', namespaces={'ns': self.namespace})
for node in nodes:
result.append(FritzService(
node.find(self.nodename('serviceType'))... |
python | def _csv_str(self, param, stats, quantiles, index=None):
"""Support function for write_csv"""
buffer = param
if not index:
buffer += ', '
else:
buffer += '_' + '_'.join([str(i) for i in index]) + ', '
for stat in ('mean', 'standard deviation', 'mc error'... |
python | def download(self, image, url_field='url', suffix=None):
"""Download the binary data of an image attachment.
:param image: an image attachment
:type image: :class:`~groupy.api.attachments.Image`
:param str url_field: the field of the image with the right URL
:param str suffix: a... |
java | public static JsScopeUiDatePickerOnChangeEvent quickScope(final JsStatement jsStatement)
{
return new JsScopeUiDatePickerOnChangeEvent()
{
private static final long serialVersionUID = 1L;
@Override
protected void execute(JsScopeContext scopeContext)
{
scopeContext.append(jsStatement == null ? "" :... |
python | def command(name=None, cls=None, **attrs):
"""
Commands are the basic building block of command line interfaces in
Click. A basic command handles command line parsing and might dispatch
more parsing to commands nested below it.
:param name: the name of the command to use unless a group overrides i... |
python | def connect(self, **kwargs):
''' Connect to an InfluxDB instance
Connects to an InfluxDB instance and switches to a given database.
If the database doesn't exist it is created first via :func:`create`.
**Configuration Parameters**
host
The host for the connection. Pa... |
python | def _handleLegacyResult(result):
"""
make sure the result is backward compatible
"""
if not isinstance(result, dict):
warnings.warn('The Gerrit status callback uses the old way to '
'communicate results. The outcome might be not what is '
'expected.')... |
java | static String toFormattedString(final String iban) {
final StringBuilder ibanBuffer = new StringBuilder(iban);
final int length = ibanBuffer.length();
for (int i = 0; i < length / 4; i++) {
ibanBuffer.insert((i + 1) * 4 + i, ' ');
}
return ibanBuffer.toString().trim... |
python | def po_file_path(self):
"""Based on the url kwargs, infer and return the path to the .po file to
be shown/updated.
Throw a 404 if a file isn't found.
"""
# This was formerly referred to as 'rosetta_i18n_fn'
idx = self.kwargs['idx']
idx = int(idx) # idx matched u... |
python | def visit_folder(self, item, parent):
"""
Adds create folder command to task runner if folder doesn't already exist.
"""
if not item.remote_id:
command = CreateFolderCommand(self.settings, item, parent)
self.task_runner_add(parent, item, command) |
python | def write_message(self, status=messages.INFO, message=None):
"""
Writes a message to django's messaging framework and
returns the written message.
:param status: The message status level. Defaults to \
messages.INFO.
:param message: The message to write. If not given, \
... |
python | def validate_username_for_rename_person(username, person):
""" Validate the new username to rename a person. If the username is
invalid or in use, raises :py:exc:`UsernameInvalid` or
:py:exc:`UsernameTaken`.
:param username: Username to validate.
:param person: We exclude this person when checking ... |
java | public DbAttribute[] get_class_attribute_property(String classname, String[] attnames) throws DevFailed {
return databaseDAO.get_class_attribute_property(this, classname, attnames);
} |
python | def http_request_headers(instance):
"""Ensure the keys of the 'request_headers' property of the http-request-
ext extension of network-traffic objects conform to the format for HTTP
request headers. Use a regex because there isn't a definitive source.
https://www.iana.org/assignments/message-headers/mes... |
java | @Nullable
public static LocalTime getLocalTime (@Nullable final XMLGregorianCalendar aCal)
{
if (aCal == null)
return null;
return getGregorianCalendar (aCal).toZonedDateTime ().toLocalTime ();
} |
java | public static Set<Field> getFields(Class<?> target, FieldFilter filter) {
Class<?> clazz = target;
Set<Field> fields = getDeclaredFields(clazz, filter);
while((clazz = clazz.getSuperclass()) != null) {
fields.addAll(getDeclaredFields(clazz, filter));
}
return fiel... |
python | def _parse_ver(ver):
'''
>>> _parse_ver("'3.4' # pyzmq 17.1.0 stopped building wheels for python3.4")
'3.4'
>>> _parse_ver('"3.4"')
'3.4'
>>> _parse_ver('"2.6.17"')
'2.6.17'
'''
if '#' in ver:
ver, _ = ver.split('#', 1)
ver = ver.strip()
return ver.strip('\'').st... |
python | def _call_widget_constructed(widget):
"""Static method, called when a widget is constructed."""
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget) |
python | def folio_room_lines(self):
'''
This method is used to validate the room_lines.
------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
folio_rooms = []
for room in self[0].room_li... |
python | def crop_image(img, padding=5):
"Crops an image or slice to its extents"
if padding < 1:
return img
beg_coords, end_coords = crop_coords(img, padding)
if len(img.shape) == 3:
img = crop_3dimage(img, beg_coords, end_coords)
elif len(img.shape) == 2:
img = crop_2dimage(img, ... |
java | public static void runExample(
AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId)
throws RemoteException {
// Enable partial failure.
session.setPartialFailure(true);
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface adGroupCriterionService ... |
python | def create_client(self, config_path):
"""Create an :class:`EnsimeClient` for a project, given its config file path.
This will launch the ENSIME server for the project as a side effect.
"""
config = ProjectConfig(config_path)
editor = Editor(self._vim)
launcher = EnsimeLa... |
python | def utcoffset(self, dt):
"""
http://docs.python.org/library/datetime.html#datetime.tzinfo.utcoffset
"""
if self.__is_daylight_time(dt):
return self.__dst_offset
else:
return self.__offset |
java | @Override
public final synchronized void set(final String pBeanName,
final IConverterByName<IRecordSet<RS>, ?> pBean) throws Exception {
this.convertersMap.put(pBeanName, pBean);
} |
python | def _sanitize_usecols(usecols):
"""Make a tuple of sorted integers and return it. Return None if
usecols is None"""
if usecols is None:
return None
try:
pats = usecols.split(',')
pats = [p.strip() for p in pats if p]
except AttributeError:
usecols = [int(c) for c in... |
java | public static void write(final PrivateKey privateKey, final @NonNull File file)
throws IOException
{
write(privateKey, new FileOutputStream(file));
} |
java | protected void unsigned16(final int size, final int value) throws IOException {
requireValidSizeUnsigned16(size);
final int quotient = size / Byte.SIZE;
final int remainder = size % Byte.SIZE;
if (remainder > 0) {
unsigned8(remainder, value >> (quotient * Byte.SIZE));
... |
java | public Set<URI> getNonConrefCopytoTargets() {
final Set<URI> res = new HashSet<>(nonConrefCopytoTargets.size());
for (final Reference r : nonConrefCopytoTargets) {
res.add(r.filename);
}
return res;
} |
java | public Matrix3f rotateLocalZ(float ang, Matrix3f dest) {
float sin = (float) Math.sin(ang);
float cos = (float) Math.cosFromSin(sin, ang);
float nm00 = cos * m00 - sin * m01;
float nm01 = sin * m00 + cos * m01;
float nm10 = cos * m10 - sin * m11;
float nm11 = sin * m10 + ... |
python | def from_dict_hook(data):
"""Decode internal objects encoded using `to_dict_hook`.
This automatically imports the class defined in the `_type` metadata field,
and calls the `from_dict` method hook to instantiate an object of that
class.
Note:
Because this function will do automatic module ... |
python | def create_object(self, filename, img_properties=None):
"""Create an image object on local disk from the given file. The file
is copied to a new local directory that is created for the image object.
The optional list of image properties will be associated with the new
object together wit... |
java | public synchronized KeyStroke getNextCharacter(boolean blockingIO) throws IOException {
KeyStroke bestMatch = null;
int bestLen = 0;
int curLen = 0;
while(true) {
if ( curLen < currentMatching.size() ) {
// (re-)consume characters previously read:
... |
python | def json_loads(cls, s, **kwargs):
"""
A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg
:param s:
:param kwargs:
:return:
:rtype: dict
"""
if 'cls' not in kwargs:
kwargs['cls'] = cls.json_decoder
return json.l... |
python | def forall(self, method):
"""
TODO: I AM NOT HAPPY THAT THIS WILL NOT WORK WELL WITH WINDOW FUNCTIONS
THE parts GIVE NO INDICATION OF NEXT ITEM OR PREVIOUS ITEM LIKE rownum
DOES. MAYBE ALGEBRAIC EDGES SHOULD BE LOOPED DIFFERENTLY? ON THE
OTHER HAND, MAYBE WINDOW FUNCTIONS ARE R... |
java | @Override
public void setData(final Object data) {
// This override is necessary to maintain other internal state
NumberFieldModel model = getOrCreateComponentModel();
try {
super.setData(convertValue(data));
model.text = null;
model.validNumber = true;
} catch (SystemException e) {
super.setData(... |
java | public EntityBuilder setHref(String href) {
if(StringUtils.isBlank(href)) {
throw new IllegalArgumentException("href cannot be null or empty.");
}
addStep("setHref", new Object[] { href });
isEmbedded = true;
return this;
} |
python | def storage_del(self, key=None):
"""
Remove the value stored with the key from storage.
If key is not supplied then all values for the module are removed.
"""
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
... |
python | def put(self, key, value, minutes):
"""
Store an item in the cache for a given number of minutes.
:param key: The cache key
:type key: str
:param value: The cache value
:type value: mixed
:param minutes: The lifetime in minutes of the cached value
:type... |
python | def to_hdf5(cls, network=None, phases=[], element=['pore', 'throat'],
filename='', interleave=True, flatten=False, categorize_by=[]):
r"""
Creates an HDF5 file containing data from the specified objects,
and categorized according to the given arguments.
Parameters
... |
java | protected void appendGroupByClause(List groupByFields, StringBuffer buf)
{
if (groupByFields == null || groupByFields.size() == 0)
{
return;
}
buf.append(" GROUP BY ");
for (int i = 0; i < groupByFields.size(); i++)
{
FieldHelper cf ... |
java | @Override
public Object get() throws InterruptedException, ExecutionException {
Future<?> wrapped = (Future<?>) future.get();
return wrapped.get();
} |
python | def remove_all_filters(self):
""" Removes all filters """
# attitude: None = no attitude, True = positive, False = negative
self.attitude_filter = self.source_filter = None
self.question_filter = self.link_filter = False |
java | @Override
public CommerceDiscount[] findByLtE_S_PrevAndNext(long commerceDiscountId,
Date expirationDate, int status,
OrderByComparator<CommerceDiscount> orderByComparator)
throws NoSuchDiscountException {
CommerceDiscount commerceDiscount = findByPrimaryKey(commerceDiscountId);
Session session = null;
t... |
java | void init() throws V4L4JException{
try {
super.init();
} catch (ImageFormatException ife){
if(format == -1){
String msg =
"v4l4j was unable to find image format supported by the"
+ " \nvideo device and that can be converted to YUV420.\n"
+ "Please let the author know about this, so that su... |
java | protected float findLimitsPoint(ArrayList wall) {
lineStatus = LINE_STATUS_OK;
if (yLine < minY || yLine > maxY) {
lineStatus = LINE_STATUS_OFFLIMITS;
return 0;
}
for (int k = 0; k < wall.size(); ++k) {
float r[] = (float[])wall.get(k);
if ... |
java | public void init(BaseField field, BaseField fldDest, Converter fldCheckMark, String fieldName)
{
BaseField fldSource = null;
boolean bClearIfThisNull = true;
boolean bOnlyIfDestNull = false;
boolean bDontMoveNull = false;
super.init(field, fldDest, fldSource, bClearIfThisNull... |
java | @PublicEvolving
public <OUT> DataStreamSource<OUT> readFile(FileInputFormat<OUT> inputFormat,
String filePath,
FileProcessingMode watchType,
long interval,
TypeInformation<OUT> typeInformation) {
Preconditions.checkNotNull(inputFormat, "InputFormat must not be null.")... |
java | public Protos.Wallet walletToProto(Wallet wallet) {
Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
if (wallet.getDescription() != null) {
walletBuilder.setDescription(wallet.getDescription()... |
java | protected SqlNode getAggregate(SqlSelect select) {
SqlNode node = select.getGroup();
if (node != null) {
return node;
}
node = select.getHaving();
if (node != null) {
return node;
}
return getAgg(select);
} |
python | def strip_empty_values(obj):
"""Recursively strips empty values."""
if isinstance(obj, dict):
new_obj = {}
for key, val in obj.items():
new_val = strip_empty_values(val)
if new_val is not None:
new_obj[key] = new_val
return new_obj or None
elif... |
java | public void idle(final int workCount)
{
if (workCount > 0)
{
return;
}
try
{
Thread.sleep(sleepPeriodMs);
}
catch (final InterruptedException ignore)
{
Thread.currentThread().interrupt();
}
} |
python | def factory_chat(js_obj, driver=None):
"""Factory function for creating appropriate object given selenium JS object"""
if js_obj["kind"] not in ["chat", "group", "broadcast"]:
raise AssertionError("Expected chat, group or broadcast object, got {0}".format(js_obj["kind"]))
if js_obj["isGroup"]:
... |
python | def action(atomic=None, **kwargs):
"""
Mark a method as an action.
"""
def decorator(func):
if atomic is None:
_atomic = getattr(settings, 'ATOMIC_REQUESTS', False)
else:
_atomic = atomic
func.action = True
func.kwargs = kwargs
if asyncio.... |
java | static SquareNode pickNot( SquareNode target , SquareNode child0 , SquareNode child1 ) {
for (int i = 0; i < 4; i++) {
SquareEdge e = target.edges[i];
if( e == null ) continue;
SquareNode c = e.destination(target);
if( c != child0 && c != child1 )
return c;
}
throw new RuntimeException("There was ... |
java | private Expr parseBitwiseXorExpression(EnclosingScope scope, boolean terminated) {
int start = index;
Expr lhs = parseBitwiseAndExpression(scope, terminated);
if (tryAndMatch(terminated, Caret) != null) {
Expr rhs = parseExpression(scope, terminated);
return annotateSourceLocation(new Expr.BitwiseXor(Type.... |
python | def depth(self, local: bool = True) -> int:
"""Return the circuit depth.
Args:
local: If True include local one-qubit gates in depth
calculation. Else return the multi-qubit gate depth.
"""
G = self.graph
if not local:
def remove_local(da... |
python | def is_analysis_edition_allowed(self, analysis_brain):
"""Returns if the analysis passed in can be edited by the current user
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the analysis, otherwise False
"""
if not self.context_active:... |
java | public ServerAzureADAdministratorInner beginCreateOrUpdate(String resourceGroupName, String serverName, ServerAzureADAdministratorInner properties) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, properties).toBlocking().single().body();
} |
python | def vjp(func,
wrt=(0,),
optimized=True,
check_dims=True,
preserve_result=False,
verbose=0):
"""Convenience function to produce vector-Jacobian products.
See `autodiff` for function arguments.
Uses reverse-mode joint-motion autodiff to produce the VJP.
"""
return autodi... |
java | public WebType<ModuleType<T>> getOrCreateWeb()
{
Node node = childNode.getOrCreate("web");
WebType<ModuleType<T>> web = new WebTypeImpl<ModuleType<T>>(this, "web", childNode, node);
return web;
} |
java | public static String ipV4Address() {
StringBuffer sb = new StringBuffer();
sb.append(JDefaultNumber.randomIntBetweenTwoNumbers(2, 254) + "");
sb.append(".");
sb.append(JDefaultNumber.randomIntBetweenTwoNumbers(2, 254) + "");
sb.append(".");
sb.append(JDefaultNumber.random... |
python | def _triggering_ctx(self):
"""
Context manager that ensures that a hook is not re-triggered by one of its handlers.
"""
if self._is_triggering:
raise RuntimeError('{} cannot be triggered while it is being handled'.format(self))
self._is_triggering = True
try:
... |
java | public String getValueSchema() throws IOException {
Schema schema = getInputPathAvroSchema();
String valueSchema = schema.getField(valueFieldName).schema().toString();
return valueSchema;
} |
python | def send_command(self, command):
"""Send command to service via the command queue."""
if self._pipe_commands:
self._pipe_commands.send(command)
else:
if self.shutdown:
# Stop delivering messages in shutdown.
self.log.info(
... |
java | public java.util.List<? extends org.tensorflow.framework.OpDef.ArgDefOrBuilder>
getOutputArgOrBuilderList() {
return outputArg_;
} |
java | public static SumChartCost create(ChartCost ... filters) {
List<ChartCost> nonNullFilters = Lists.newArrayList();
for (ChartCost filter : filters) {
if (filter != null) {
nonNullFilters.add(filter);
}
}
if (nonNullFilters.size() > 0) {
return new SumChartCost(nonNullFilter... |
java | @Override
public double[][] processQueryResults(DoubleDBIDList results, Relation<? extends NumberVector> database, int k) {
final int dim = RelationUtil.dimensionality(database);
final CovarianceMatrix cmat = new CovarianceMatrix(dim);
// avoid bad parameters
k = k <= results.size() ? k : results.siz... |
java | public List<Node> link() {
List<Module> dependencies;
Module module;
Module resolved;
StringBuilder problems;
List<Node> result;
problems = new StringBuilder();
for (Map.Entry<Module, List<String>> entry : notLinked.entrySet()) {
module = entry.getKey... |
java | public static float median(final float a, final float b, final float c) {
int ab = Float.compare(a, b);
int ac = Float.compare(a, c);
int bc = 0;
if ((ab >= 0 && ac <= 0) || (ac >= 0 && ab <= 0)) {
return a;
} else if ((((bc = Float.compare(b, c)) <= 0) && ab ... |
java | private void init()
throws IOException, InterruptedException {
nakedDone = false;
// initialize the total length
float recToFragRatio = conf.getFloat(RECORD_TO_FRAGMENT_RATIO,
getDefaultRatio());
length = mlSplit.getLength() * recToFragRatio;
// generate the... |
java | public void sendWarning(Object source, String msg)
{
try {
String s = getClass().getSimpleName() + ": " + msg;
// if warning is high-priority then send to high priority handlers first
System.err.println(s);
for (WarningHandler handler : _priorityHandlers) {
handler.warn... |
java | public ServiceFuture<Void> updateStorageAccountAsync(String resourceGroupName, String accountName, String storageAccountName, AddStorageAccountParameters parameters, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(updateStorageAccountWithServiceResponseAsync(resourceGroupName, a... |
python | def ascii(graph):
"""Format graph as an ASCII art."""
from .._ascii import DAG
from .._echo import echo_via_pager
echo_via_pager(str(DAG(graph))) |
python | def remove_suffix(text, suffix):
"""
Remove the suffix from the text if it exists.
>>> remove_suffix('name.git', '.git')
'name'
>>> remove_suffix('something special', 'sample')
'something special'
"""
rest, suffix, null = text.partition(suffix)
return rest |
python | def set_datetime(self, section, option, value):
"""
Return UTC datetime from timestamp in config file.
:param section: Config section
:param option: Config option
:param value: Datetime value to set
:type value: :class:`datetime.datetime`
"""
self[section... |
java | @Nullable
@CheckForNull
public String getDescription(String languageCode) {
String i18nDescription = getString(getI18nAttributeName(DESCRIPTION, languageCode));
return i18nDescription != null ? i18nDescription : getDescription();
} |
python | def check_file_existence(path):
"""
:return: FileType
:rtype: int
:raises InvalidFilePathError:
:raises FileNotFoundError:
:raises RuntimeError:
"""
pathvalidate.validate_file_path(path)
if not os.path.lexists(path):
raise FileNotFoundError(path)
if os.path.isfile(path... |
python | def excepthook(exc_type, exc_value, tracebackobj):
"""
Global function to catch unhandled exceptions.
Parameters
----------
exc_type : str
exception type
exc_value : int
exception value
tracebackobj : traceback
traceback object
"""
separator = "-" * 80
no... |
java | public void marshall(CloudWatchOutputConfig cloudWatchOutputConfig, ProtocolMarshaller protocolMarshaller) {
if (cloudWatchOutputConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(cloudWatchOut... |
java | @GwtIncompatible // doesn't work
public static int fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES);
return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]);
} |
java | public void executeWithoutTrigger(final OutputStream _out)
throws EFapsException
{
Resource storeRsrc = null;
try {
storeRsrc = Context.getThreadContext().getStoreResource(getInstance(), Resource.StoreEvent.READ);
storeRsrc.read(_out);
this.fileLength = st... |
java | public static String getStubClassName(Class<?> remoteInterface)
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "getStubClassName : " + remoteInterface.getName());
String result = JIT_Stub.getStubClassName(remo... |
python | def setDataCollector( self, collector ):
"""
Sets the method that will be used to collect mime data for dragging \
items from this tree.
:warning The data collector is stored as a weak-reference, so using \
mutable methods will not be stored well. T... |
python | def meta_tags(cls, **kwargs):
"""
Meta allows you to add meta data to site
:params **kwargs:
meta keys we're expecting:
title (str)
description (str)
url (str) (Will pick it up by itself if not set)
image (str)
site_name (str) ... |
java | private void loadCollisionGroups(MapTileCollision mapCollision, Media groupsConfig)
{
Verbose.info(INFO_LOAD_GROUPS, groupsConfig.getFile().getPath());
this.groupsConfig = groupsConfig;
final Xml nodeGroups = new Xml(groupsConfig);
final CollisionGroupConfig config = Collision... |
python | def create_addon(name):
"""
Create a Skeleton AddOn (needs internet connection to github)
"""
try:
full_name = "fab_addon_" + name
dirname = "Flask-AppBuilder-Skeleton-AddOn-master"
url = urlopen(ADDON_REPO_URL)
zipfile = ZipFile(BytesIO(url.read()))
zipfile.e... |
python | def cache_key_name(cls, *args):
"""Return the name of the key to use to cache the current configuration"""
if cls.KEY_FIELDS != ():
if len(args) != len(cls.KEY_FIELDS):
raise TypeError(
"cache_key_name() takes exactly {} arguments ({} given)".format(len(cl... |
python | def LeerDatosLiquidacion(self, pop=True):
"Recorro los datos devueltos y devuelvo el primero si existe"
if self.DatosLiquidacion:
# extraigo el primer item
if pop:
datos_liq = self.DatosLiquidacion.pop(0)
else:
datos_liq = self... |
python | def squish(incs, f):
"""
This function applies an flattening factor (f) to inclination data
(incs) and returns 'squished' values.
Parameters
----------
incs : list of inclination values or a single value
f : flattening factor (between 0.0 and 1.0)
Returns
---------
incs_squishe... |
java | private static boolean isToken(String value) {
// ----- BEGIN android -----
if (RESERVED_NAMES.contains(value.toLowerCase(Locale.US))) {
return false;
}
// ----- END android -----
int len = value.length();
for (int i = 0; i < len; i++) {
char c =... |
python | def MaxPooling(
inputs,
pool_size,
strides=None,
padding='valid',
data_format='channels_last'):
"""
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
"""
if strides is None:
strides = pool_size
layer = tf.layers.MaxPooling2D(pool... |
python | def get_default(self, node):
"""
Unless specified otherwise, intr fields are implicitly stickybit
"""
if node.inst.properties.get("intr", False):
# Interrupt is set!
# Default is implicitly stickybit, unless the mutually-exclusive
# sticky property was... |
python | def _format_level_1(rows, root_table_name):
"""
Transform sqlalchemy source:
[{'a_id' : 'id1',
'a_name' : 'name1,
'b_id' : 'id2',
'b_name' : 'name2},
{'a_id' : 'id3',
'a_name' : 'name3,
'b_id' : 'id4',
'b_name' : 'name4}
]
to
[{'id' : 'id1',
'name':... |
python | def nvmlDeviceGetSupportedEventTypes(handle):
r"""
/**
* Returns information about events supported on device
*
* For Fermi &tm; or newer fully supported devices.
*
* Events are not supported on Windows. So this function returns an empty mask in \a eventTypes on Windows.
*
* @... |
java | @Override
public final void setItsId(final BuyerPriceCategoryId pItsId) {
this.itsId = pItsId;
if (this.itsId != null) {
this.priceCategory = this.itsId.getPriceCategory();
this.buyer = this.itsId.getBuyer();
} else {
this.priceCategory = null;
this.buyer = null;
}
} |
python | def import_from_hdf5(network, path, skip_time=False):
"""
Import network data from HDF5 store at `path`.
Parameters
----------
path : string
Name of HDF5 store
skip_time : bool, default False
Skip reading in time dependent attributes
"""
basename = os.path.basename(path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.