language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def row(self, columnnames=[], exclude=False):
"""Return a tablerow object which includes (or excludes) the
given columns.
:class:`tablerow` makes it possible to get/put values in one or
more rows.
"""
from .tablerow import tablerow
return tablerow(self, columnna... |
python | def getchannel(samples: np.ndarray, ch:int) -> np.ndarray:
"""
Returns a view into a channel of samples.
samples : a numpy array representing the audio data
ch : the channel to extract (channels begin with 0)
"""
N = numchannels(samples)
if ch > (N - 1):
raise ValueError(... |
python | def load(self):
"""
We load the data from the key itself instead of fetching from
some external data store. Opposite of _get_session_key(),
raises BadSignature if signature fails.
"""
session_data = {}
try:
session_data = decode(self.session_key,
... |
java | static public ContentHandleFactory newFactory(Class<?>... pojoClasses) {
if (pojoClasses == null || pojoClasses.length == 0) return null;
return new JacksonDatabindHandleFactory(pojoClasses);
} |
java | public void deleteAtResourceGroupLevel(String resourceGroupName, String lockName) {
deleteAtResourceGroupLevelWithServiceResponseAsync(resourceGroupName, lockName).toBlocking().single().body();
} |
python | async def create_sentinel(sentinels, *, db=None, password=None,
encoding=None, minsize=1, maxsize=10,
ssl=None, timeout=0.2, loop=None):
"""Creates Redis Sentinel client.
`sentinels` is a list of sentinel nodes.
"""
if loop is None:
loop = as... |
java | public synchronized void start() throws IOException {
Preconditions.checkState(mProcess == null, "Worker is already running");
mProcess = new ExternalProcess(mProperties, LimitedLifeWorkerProcess.class,
new File(mLogsDir, "worker.out"));
mProcess.start();
} |
java | static PrefsTransform getMathTransform(TypeName typeName) {
if (BigDecimal.class.getName().equals(typeName.toString())) {
return new BigDecimalPrefsTransform();
} else if (BigInteger.class.getName().equals(typeName.toString())) {
return new BigIntegerPrefsTransform();
}
return null;
} |
python | def is_letter(char, strict=True):
"""
Check whether the character is a letter (as opposed to a diacritic or
suprasegmental).
In strict mode return True only if the letter is part of the IPA spec.
"""
if (char in chart.consonants) or (char in chart.vowels):
return True
if not strict:
return unicodedata.cate... |
python | def explain(self):
"""
A debugging API, exposing SQLite's I{EXPLAIN} statement.
While this is not a private method, you also probably don't have any
use for it unless you understand U{SQLite
opcodes<http://www.sqlite.org/opcode.html>} very well.
Once you do, it can be h... |
java | public ScriptResult runScript(String scriptName, Map<String, Object> parameters) {
Script script =
dataService.query(SCRIPT, Script.class).eq(ScriptMetadata.NAME, scriptName).findOne();
if (script == null) {
throw new UnknownEntityException(SCRIPT, scriptName);
}
if (script.getParameters(... |
python | def create_sparse_dtm(vocab, doc_labels, docs_terms, sum_uniques_per_doc):
"""
Create a sparse document-term-matrix (DTM) as scipy "coo_matrix" from vocabulary array `vocab`, document
IDs/labels array `doc_labels`, dict of doc_label -> document terms `docs_terms` and the sum of unique terms
per document... |
java | public ArrayList getTreePerfLevelDescriptors(int parentLevel) {
ArrayList res = new ArrayList();
int thisLevel = level;
if (instance == null) { // should be root
res.add(new PerfLevelDescriptor(new String[] { "pmi" }, thisLevel));
} else {
PmiModule instance = get... |
python | def create_composition(self, composiiton_form):
"""Creates a new ``Composition``.
arg: composiiton_form (osid.repository.CompositionForm): the
form for this ``Composition``
return: (osid.repository.Composition) - the new ``Composition``
raise: IllegalState - ``compos... |
java | public void useProtocolVersion(int version) throws IOException {
if (!objectsWritten.isEmpty()) {
throw new IllegalStateException("Cannot set protocol version when stream in use");
}
if (version != ObjectStreamConstants.PROTOCOL_VERSION_1
&& version != ObjectStreamCon... |
python | def create(cls, name, min_dst_port, max_dst_port=None, min_src_port=None,
max_src_port=None, protocol_agent=None, comment=None):
"""
Create the TCP service
:param str name: name of tcp service
:param int min_dst_port: minimum destination port value
:param int max_... |
python | def checkpoint(self, eager=True):
"""Returns a checkpointed version of this Dataset. Checkpointing can be used to truncate the
logical plan of this DataFrame, which is especially useful in iterative algorithms where the
plan may grow exponentially. It will be saved to files inside the checkpoint... |
java | private Content getInheritedTagletOutput(boolean isParameters, Element holder,
TagletWriter writer, List<? extends Element> formalParameters,
Set<String> alreadyDocumented) {
Utils utils = writer.configuration().utils;
Content result = writer.getOutputInstance();
if ((!al... |
java | public static boolean isPropertyGettable(
final Object src,
final String propertyName
)
{
if (src == null) {
throw new IllegalArgumentException( "no source object specified" );
}
return isPropertyGettable( src.getClass(... |
python | def validate_response(self):
"""Checks that the response is valid and import succeeded."""
if self.response is None:
logger.error("Failed to submit")
return False
if not self.response:
logger.error(
"HTTP status %d: failed to submit to %s",
... |
python | def add_port(self, br_name, port_name, may_exist, fake_iface,
iface_names, settings=None):
"""
:type settings: list of (column, value_json)
where column is str,
value_json is json that is represented
... |
java | protected void loadOptionalPool(final String poolBinder) {
try {
final Method bindPool = OrientModule.class.getDeclaredMethod("bindPool", Class.class, Class.class);
bindPool.setAccessible(true);
try {
Class.forName(poolBinder)
.getConst... |
java | public static String pingJmsEndpoint(MuleContext muleContext, String queueName) {
return pingJmsEndpoint(muleContext, DEFAULT_MULE_JMS_CONNECTOR, queueName);
} |
python | def size(self, filename: str) -> int:
'''Get size of file.
Coroutine.
'''
yield from self._control_stream.write_command(Command('SIZE', filename))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match('File size', ReplyCodes.file_status, reply)
... |
java | private Set<Addon> getAddonsToScan()
{
AddonFilter filter = new AddonFilter()
{
@Override
public boolean accept(Addon addon)
{
// make sure to include ourselves as well (even though we don't technically depend on ourselves)
return a... |
java | public static String getId(URI uri) {
String s = uri.toString();
return s.substring(s.lastIndexOf("/") + 1);
} |
python | def get_nodes(self, request):
"""
Return menu's node for categories
"""
nodes = []
nodes.append(NavigationNode(_('Categories'),
reverse('zinnia:category_list'),
'categories'))
for category in Category... |
python | def initialize(self):
"""See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus.
"""
Device.initialize(self)
for child in iter(self.children.values()):
child.initialize() |
java | public int fromInputStream(final InputStream in, final int iMaxSize) throws IOException {
final byte[] buffer = new byte[iMaxSize];
final int readBytesCount = in.read(buffer);
if (readBytesCount == -1) {
_source = EMPTY_SOURCE;
_size = 0;
} else if (readBytesCount == iMaxSize) {
_source = buffer... |
python | def write_handle(self, handle: int, value: bytes):
"""Write a handle to the device."""
if not self.is_connected():
raise BluetoothBackendException('Not connected to device!')
self._device.char_write_handle(handle, value, True)
return True |
python | def run_program_profile(self, n, program_or_profile='program',
timeout=10.0):
""" Runs a program/profile on the drive.
Runs program or profile 'n' on the drive, grabs its output, and
processes the output. The response from the drive is broken down
into the ec... |
python | def netconf_state_schemas_schema_format(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_state = ET.SubElement(config, "netconf-state", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
schemas = ET.SubElement(netconf_state, "schemas")
... |
python | def set_bounds(self, ymin, ymax, xmin, xmax, zmin, zmax, edist=None):
"""Set Y,X,Z bounds for the plot."""
self.ymin, self.ymax = ymin, ymax
self.xmin, self.xmax = xmin, xmax
self.zmin, self.zmax = zmin, zmax
self.edist = None |
python | def from_id(cls, id):
"""Load a `cls` entity and instantiate the Context it stores."""
from furious.context import Context
# TODO: Handle exceptions and retries here.
entity = cls.get_by_id(id)
if not entity:
raise FuriousContextNotFoundError(
"Contex... |
python | def insert(self, table_name, record, attr_names=None):
"""
Send an INSERT query to the database.
:param str table_name: Table name of executing the query.
:param record: Record to be inserted.
:type record: |dict|/|namedtuple|/|list|/|tuple|
:raises IOError: |raises_writ... |
java | public void marshall(CheckpointConfigurationDescription checkpointConfigurationDescription, ProtocolMarshaller protocolMarshaller) {
if (checkpointConfigurationDescription == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
proto... |
python | def _request(self, service, **parameters):
""" request builder """
urlformat = "{baseurl}/{service}?{parameters}&format=json"
url = urlformat.format(
baseurl=API_BASE_URL,
service=service,
parameters="&".join([
"{}={}".format(key, value) for ke... |
python | def display_value(self, ctx, value):
""" Display value to be used for this parameter. """
gandi = ctx.obj
gandi.log('%s: %s' % (self.name, (value if value is not None
else 'Not found'))) |
python | def match_positions(shape, list_of_coords):
""" In cases where we have multiple matches, each highlighted by a region of coordinates,
we need to separate matches, and find mean of each to return as match position
"""
match_array = np.zeros(shape)
try:
# excpetion hit on this line if noth... |
java | public void setSeverity(Severity severity) {
if ((severity.getOrdinal() < SEVERITY_INFO.getOrdinal()) ||
(severity.getOrdinal() > SEVERITY_FATAL.getOrdinal())) {
throw new IllegalArgumentException(String.valueOf(severity));
}
this.severity = severity;
} |
java | public static String accessToken(String key) {
if (isKeyParam(key)) {
String[] keys = key.split(KEY_JOIN);
if (keys.length == 2) {
return apiHandler.accessToken(keys[0], keys[1]);
} else if (keys.length == 1) {
return apiHandler.accessToken(keys[0]);
}
}
return key;
} |
python | def closing(self, cancelable=False):
"""Exit tasks"""
if self.already_closed or self.is_starting_up:
return True
if cancelable and CONF.get('main', 'prompt_on_exit'):
reply = QMessageBox.critical(self, 'Spyder',
'Do you reall... |
python | def rsa_check_base64_sign_str(self, cipher, sign, b64=True):
"""
验证服务端数据 ``rsa`` 签名
"""
with open(self.key_file) as fp:
key_ = RSA.importKey(fp.read())
v = pkcs.new(key_)
sign = base64.b64decode(sign) if b64 else sign
cipher = helper.t... |
python | def pieces(self, piece_type: PieceType, color: Color) -> "SquareSet":
"""
Gets pieces of the given type and color.
Returns a :class:`set of squares <chess.SquareSet>`.
"""
return SquareSet(self.pieces_mask(piece_type, color)) |
python | def _array_or_placeholder(
maybe_iterable, placeholder=PLACEHOLDER_ZEROS
) -> np.array:
"""
Return maybe_iterable's contents or a placeholder array.
Used to give bqplot its required initial points to plot even if we're using
a function to generate points.
"""
if isinstance(maybe_iterable, c... |
java | public static Point getPixelRelative(LatLong latLong, long mapSize, double x, double y) {
double pixelX = MercatorProjection.longitudeToPixelX(latLong.longitude, mapSize) - x;
double pixelY = MercatorProjection.latitudeToPixelY(latLong.latitude, mapSize) - y;
return new Point(pixelX, pixelY);
... |
python | def addmember(self, value):
"""Adds a single member to this group's list of members.
Tries to convert to :class:`tincan.Agent`
:param value: The member to add to this group
:type value: :class:`tincan.Agent`
"""
if value is not None and not isinstance(value, Agent):
... |
python | def add_kv_store(self, key, value):
"""Add a key-value store entry.
:param key: string
:param value: string
"""
data = {
'operation': 'STORE',
'key': key,
'value': value
}
return self.post(self.make_url("/useragent-kv"), data=t... |
java | protected ITreeAppendable generateStaticConstructor(JvmOperation it, ITreeAppendable appendable, GeneratorConfig config) {
appendable.newLine();
appendable.openScope();
generateJavaDoc(it, appendable, config);
final ITreeAppendable tracedAppendable = appendable.trace(it);
tracedAppendable.append("static "); /... |
python | def cosine(x):
'''
cosine(x) is equivalent to cos(x) except that it also works on sparse arrays.
'''
# cos(0) = 1 so no point in keeping these sparse
if sps.issparse(x): x = x.toarray(x)
return np.cos(x) |
python | def addDocument(self, row_dict, folder):
"""
This function adds a multifile object to the instrument folder
:param row_dict: the dictionary which contains the document information
:param folder: the instrument object
"""
if folder:
# This content type need a file
if row_dict.get(... |
python | def get_digest(self,
alias=None,
manifest=None,
verify=True,
dcd=None):
"""
(v2 schema only) Get the hash of an alias's configuration blob.
For an alias created using ``dxf``, this is the hash of the first blob
... |
java | private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException {
//cannot batch fetch by unique key (property-ref associations)
if ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) {
EntityPersister persister = session.getF... |
python | def p0(self):
"""A dictionary of the initial position of the walkers.
This is set by using ``set_p0``. If not set yet, a ``ValueError`` is
raised when the attribute is accessed.
"""
if self._p0 is None:
raise ValueError("initial positions not set; run set_p0")
... |
python | def get_proxy(self, input):
"""Gets a proxy.
:param input: a proxy condition
:type input: ``osid.proxy.ProxyCondition``
:return: a proxy
:rtype: ``osid.proxy.Proxy``
:raise: ``NullArgument`` -- ``input`` is ``null``
:raise: ``OperationFailed`` -- unable to comple... |
python | def publish(self, hierarchy_id, target_file_path, publish_format, clsid_of_exporter=""):
"""
PublishFormat
0 - Published page is in .one format.
1 - Published page is in .onea format.
2 - Published page is in .mht format.
3 - Published page is in .pdf format.
... |
python | def nsdeclarations(self):
"""
Get a string representation for all namespace declarations as xmlns=""
and xmlns:p="".
@return: A separated list of declarations.
@rtype: basestring
"""
s = []
myns = None, self.expns
if self.parent is None:
... |
java | @Override
protected void service(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse)
throws ServletException, IOException {
String path = httpServletRequest.getRequestURI();
try {
LOG.info("Service called on " + this + "... from " + path);
if (ServletUtil.isEna... |
java | public void depends(int parent, int child)
{
dag.addNode(child);
dag.addNode(parent);
dag.addEdge(parent, child);
} |
python | def ro(self):
""" Return read-only copy
:return: WHTTPCookieJar
"""
ro_jar = WHTTPCookieJar()
for cookie in self.__cookies.values():
ro_jar.add_cookie(cookie.ro())
ro_jar.__ro_flag = True
return ro_jar |
java | private void initInternal(String hosts, String defaultPrefixString, boolean debug)
throws IOException, InterruptedException {
curHost = hosts;
curDefaultPrefixString = defaultPrefixString;
store = new ResilientActiveKeyValueStore(debug);
store.connect(hosts);
LOGGE... |
python | def iterweekdays(self, d1, d2):
"""
Date iterator returning dates in d1 <= x < d2, excluding weekends
"""
for dt in self.iterdays(d1, d2):
if not self.isweekend(dt):
yield dt |
java | public AnalysisJobBuilder getAnalysisJobBuilder(final Object vertex) {
if (vertex instanceof ComponentBuilder) {
return ((ComponentBuilder) vertex).getAnalysisJobBuilder();
}
return _analysisJobBuilder;
} |
python | def create(self):
"""Create the write buffer and cache directory."""
if not self._sync and not hasattr(self, '_buffer'):
self._buffer = {}
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir) |
python | def untldict_normalizer(untl_dict, normalizations):
"""Normalize UNTL elements by their qualifier.
Takes a UNTL descriptive metadata dictionary and a dictionary of
the elements and the qualifiers for normalization:
{'element1': ['qualifier1', 'qualifier2'],
'element2': ['qualifier3']}
and norm... |
java | public boolean isMultiDay() {
if (m_isMultiDay != null) {
return m_isMultiDay.booleanValue();
}
Long instanceDuration = getInstanceDuration();
if ((null == instanceDuration) || (instanceDuration.longValue() == 0)) {
m_isMultiDay = Boolean.FALSE;
ret... |
java | @NonNull
static Bytes createViaLazyDataOutput(@NonNull IOConsumer<ExtendedDataOutput> creator, int expectedSize)
{
return new DataOutputBytes(creator, expectedSize);
} |
java | public void setImages(java.util.Collection<Image> images) {
if (images == null) {
this.images = null;
return;
}
this.images = new java.util.ArrayList<Image>(images);
} |
java | public void register(Collector m) {
List<String> names = collectorNames(m);
synchronized (collectorsToNames) {
for (String name : names) {
if (namesToCollectors.containsKey(name)) {
throw new IllegalArgumentException("Collector already registered that provides name: " + name);
}
... |
java | @Override
public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) {
AnnotationVisitor av = super.visitParameterAnnotation(parameter, desc, visible);
Set<Type> parameterAnnotations = observedParameterAnnotations.get(parameter);
if (parameterAnnotations =... |
java | @Override
protected MkCoPEntry createNewDirectoryEntry(MkCoPTreeNode<O> node, DBID routingObjectID, double parentDistance) {
return new MkCoPDirectoryEntry(routingObjectID, parentDistance, node.getPageID(), node.coveringRadiusFromEntries(routingObjectID, this), null);
// node.conservativeKnnDistanceApproximat... |
java | public MediaServiceInner create(String resourceGroupName, String mediaServiceName, MediaServiceInner parameters) {
return createWithServiceResponseAsync(resourceGroupName, mediaServiceName, parameters).toBlocking().single().body();
} |
java | public static CommerceWishListItem fetchByCProductId_Last(long CProductId,
OrderByComparator<CommerceWishListItem> orderByComparator) {
return getPersistence()
.fetchByCProductId_Last(CProductId, orderByComparator);
} |
java | @Override
public IPerson getCurrentPerson(final ExternalContext externalContext) {
final HttpServletRequest servletRequest =
getServletRequestFromExternalContext(externalContext);
return personManager.getPerson(servletRequest);
} |
python | def get_container_for(portal_type):
"""Returns the single holding container object of this content type
:param portal_type: The portal type requested
:type portal_type: string
:returns: Folderish container where the portal type can be created
:rtype: AT content object
"""
container_paths = ... |
java | @Override
public Set<Entry<String, Object>> entrySet() {
return new AbstractSet<Entry<String, Object>>() {
@Override
public Iterator<Entry<String, Object>> iterator() {
return entryIterator();
}
@Override
public int size() {
... |
java | @Override
public byte[] marshal(Context context, ObjectOutputStream os, Object object) throws IOException {
return _serializer.serialize(object, Object.class);
} |
python | def _clean_input_data(self, data, request):
""" Clean input data. """
# sanity check
if not self._is_data_method(request):
# this is not PUT or POST -> return
return data
# do cleaning
try:
if self.representation:
# representa... |
java | public final V put(K key, V value) {
BinTreeNode<K,V> prev = null;
BinTreeNode<K,V> node = root;
int key_hash_code = key.hashCode();
while(node != null) {
prev = node;
if(key_hash_code < node.keyHashCode) {
node = node.left;
}
else {
if((key_hash_code > node.keyHashCode) || !node.key.equals... |
java | @POST
@Path("/bulk/classification")
@Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
@Produces(Servlets.JSON_MEDIA_TYPE)
public void addClassification(ClassificationAssociateRequest request) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (... |
python | def load_pricing_adjustments(self, columns, dts, assets):
"""
Returns
-------
adjustments : list[dict[int -> Adjustment]]
A list, where each element corresponds to the `columns`, of
mappings from index to adjustment objects to apply at that index.
"""
... |
java | public static void addDict(Collection<String> words, String pos) {
for(String w:words){
dict.add(w, pos);
}
setDict();
} |
java | public ApiSuccessResponse consult(String id, ConsultData consultData) throws ApiException {
ApiResponse<ApiSuccessResponse> resp = consultWithHttpInfo(id, consultData);
return resp.getData();
} |
java | private void putRecursive(Class<?> type, E element, Class<?> elementType) {
Class<?> clazz = type;
while (clazz != null) {
if (isAccepted(clazz)) {
E existing = this.classMap.get(clazz);
boolean add = (existing == null);
if (existing != null) {
if (existing == element) {... |
python | def start(component, exact):
# type: (str, str) -> None
""" Create a new release branch.
Args:
component (str):
Version component to bump when creating the release. Can be *major*,
*minor* or *patch*.
exact (str):
The exact version to set for the release.... |
python | def pretty_time(timestamp: str):
"""Format timestamp for human consumption."""
try:
parsed = iso_8601.parse_datetime(timestamp)
except ValueError:
now = datetime.utcnow().replace(tzinfo=timezone.utc)
try:
delta = iso_8601.parse_delta(timestamp)
except ValueError:
... |
java | public JSONObject optJSONObject( String key ) {
verifyIsNull();
Object o = opt( key );
return o instanceof JSONObject ? (JSONObject) o : null;
} |
python | def main(*args):
"""
Invoke pip in a subprocess, with semantics very similar to `pip.main()`
Why use check_call instead of check_output?
It's behavior is slightly closer to the older `pip.main()` behavior,
printing output information directly to stdout.
check_call was added in py2.5 and is sup... |
python | def generate_payload(self, config=None, context=None):
"""
Generate payload by iterating over registered plugins. Merges .
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload.
"""
for name, plugin i... |
python | def _register_update(self, method='isel', replot=False, dims={}, fmt={},
force=False, todefault=False):
"""
Register new dimensions and formatoptions for updating
Parameters
----------
%(InteractiveArray._register_update.parameters)s"""
ArrayList... |
python | def _iterator(self, plugins, context):
"""Yield next plug-in and instance to process.
Arguments:
plugins (list): Plug-ins to process
context (pyblish.api.Context): Context to process
"""
test = pyblish.logic.registered_test()
for plug, instance in pybl... |
java | @Override
public void lookupChainedProxies(HttpRequest request, Queue<ChainedProxy> chainedProxies) {
final InetSocketAddress originalProxy = originalProxies.get(URI.create(request.getUri()).getScheme());
if (originalProxy != null) {
ChainedProxy chainProxy = new ChainedProxyAdapter() {
... |
java | @Override
public StringConverter<?> findConverter(Class<?> cls) {
if (cls == Byte[].class) {
return ByteArrayStringConverter.INSTANCE;
}
return null;
} |
java | String getHTMLForAdminPage(Map<String,String> params) {
try {
String template = m_htmlTemplates.get("admintemplate.html");
for (Entry<String, String> e : params.entrySet()) {
String key = e.getKey().toUpperCase();
String value = e.getValue();
... |
python | def generate_payment(redirect_url, client_name, client_email, payment_owner, validate_address_cmd, *validate_item_cmds):
"""
Function used to generate a payment on pagseguro
See facade_tests to undestand the steps before generating a payment
@param redirect_url: the url where payment status change mus... |
java | protected void sendDirectory(HttpServletRequest request, HttpServletResponse response, Resource resource, boolean parent) throws IOException
{
if (!_dirAllowed)
{
response.sendError(HttpResponse.__403_Forbidden);
return;
}
byte[] data = null;
if (reso... |
java | public static Optional<Scheme> tryParse(@Nullable String scheme) {
if (scheme == null) {
return Optional.empty();
}
return Optional.ofNullable(SCHEMES.get(Ascii.toLowerCase(scheme)));
} |
python | def _write_max_gradient(self)->None:
"Writes the maximum of the gradients to Tensorboard."
max_gradient = max(x.data.max() for x in self.gradients)
self._add_gradient_scalar('max_gradient', scalar_value=max_gradient) |
java | public static DevState tangoState(int taco_code)
{
switch(taco_code)
{
case DEVOFF:
return DevState.OFF;
case DEVON:
return DevState.ON;
case DEVCLOSE:
return DevState.CLOSE;
case DEVOPEN:
return DevState.OPEN;
case DEVINSERTED:
return DevState.INSERT;
case DEVEXTRACTED:
r... |
java | @Override
protected String format(String request) {
String result = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ByteArrayInputStream bis = new ByteArrayInputStream(request.getBytes());
Document doc = new SAXBuilder().build(bis);
bi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.