language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def ssh_sa_ssh_client_cipher(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services")
ssh = ET.SubElement(ssh_sa, "ssh")
client = ET.SubElement(ssh, "client")
... |
python | def _get_matrix(self):
"""
Build a matrix of scenarios with sequence to include and returns a
dict.
{
scenario_1: {
'subcommand': [
'action-1',
'action-2',
],
},
scenario_2: {
... |
java | @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public int getMaxLines (){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
return mInputView.getMaxLines();
return -1;
} |
java | public Class<? extends Message> getMessageClass(String topic) {
return allTopics ? messageClassForAll : messageClassByTopic.get(topic);
} |
python | def render_particles(self):
"""
Render visible particles at each strip position, by modifying
the strip's color list.
"""
for strip_pos in range(self._start, self._end + 1):
blended = COLORS.black
# Render visible emitters
if self.has_e_color... |
java | protected void setProgressMessage(final String message) {
runOnUiThread(new Runnable() {
public void run() {
synchronized ( lockProgress ) {
if( progressDialog != null ) {
// a dialog is already open, change the message
progressDialog.setMessage(message);
return;
}
progressDial... |
python | def is_ancestor_of(self, other, inclusive=False):
""" class or instance level method which returns True if self is
ancestor (closer to root) of other else False. Optional flag
`inclusive` on whether or not to treat self as ancestor of self.
For example see:
* :mod:`sqlalchemy_m... |
java | private boolean tryToNotifyReset() {
if ((mStatus == PTR_STATUS_COMPLETE || mStatus == PTR_STATUS_PREPARE) && mPtrIndicator.isInStartPosition()) {
if (mPtrUIHandlerHolder.hasHandler()) {
mPtrUIHandlerHolder.onUIReset(this);
if (DEBUG) {
PtrCLog.i(L... |
java | public String toType(ClassTemplateSpec spec, boolean isOptional) {
String type = toTypeString(spec);
return type + (isOptional ? "?" : "");
} |
python | def synthetic_grad(X, theta, sigma1, sigma2, sigmax, rescale_grad=1.0, grad=None):
"""Get synthetic gradient value"""
if grad is None:
grad = nd.empty(theta.shape, theta.context)
theta1 = theta.asnumpy()[0]
theta2 = theta.asnumpy()[1]
v1 = sigma1 ** 2
v2 = sigma2 ** 2
vx = sigmax ** ... |
java | private void checkRequiredCreateDiscussionArguments(String body,
String positionBaseSha, String positionStartSha, String positionHeadSha) {
if (body == null || body.isEmpty()) {
throw new IllegalArgumentException("Missing required argument 'body'!");
} else if (positionBaseSha ==... |
java | public Observable<Page<ExpressRouteCircuitAuthorizationInner>> listAsync(final String resourceGroupName, final String circuitName) {
return listWithServiceResponseAsync(resourceGroupName, circuitName)
.map(new Func1<ServiceResponse<Page<ExpressRouteCircuitAuthorizationInner>>, Page<ExpressRouteCircu... |
java | public static JCATranWrapper getTxWrapper(Xid xid, boolean addAssociation) throws XAException
{
if (tc.isEntryEnabled()) Tr.entry(tc, "getTxWrapper", new Object[] { xid, addAssociation});
final ByteArray key = new ByteArray(xid.getGlobalTransactionId());
final JCATranWrapper txWrapper;
... |
java | @Override
public String getSubmittedFileName() {
if (_part.isFormField()) {
return null;
}
if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15
logger.logp(Level.FINE, CLASS_NAME,"getSubmittedFileName()",_part.getName());
}
... |
java | public static @CheckForNull
TypeQualifierAnnotation getInheritedTypeQualifierAnnotation(XMethod xmethod, int parameter,
TypeQualifierValue<?> typeQualifierValue) {
assert !xmethod.isStatic();
ParameterAnnotationAccumulator accumulator = new ParameterAnnotationAccumulator(typeQualifierVa... |
python | def _update_keycache(self, *args, forward):
"""Add or remove a key in the set describing the keys that exist."""
entity, key, branch, turn, tick, value = args[-6:]
parent = args[:-6]
kc = self._get_keycache(parent + (entity,), branch, turn, tick, forward=forward)
if value is None... |
python | def put(self, event):
"""Store a given configuration"""
self.log("Configuration put request ",
event.user)
try:
component = model_factory(Schema).find_one({
'uuid': event.data['uuid']
})
component.update(event.data)
... |
java | private SherdogBaseObject getOpponent(Element td) {
SherdogBaseObject opponent = new SherdogBaseObject();
Element opponentLink = td.select("a").get(0);
opponent.setName(opponentLink.html());
opponent.setSherdogUrl(opponentLink.attr("abs:href"));
return opponent;
} |
java | public static base_response update(nitro_service client, ipsecparameter resource) throws Exception {
ipsecparameter updateresource = new ipsecparameter();
updateresource.ikeversion = resource.ikeversion;
updateresource.encalgo = resource.encalgo;
updateresource.hashalgo = resource.hashalgo;
updateresource.lif... |
python | async def send(self, data: Union[bytes, str], final: bool = True):
"""
Sends some data down the connection.
"""
MsgType = TextMessage if isinstance(data, str) else BytesMessage
data = MsgType(data=data, message_finished=final)
data = self._connection.send(event=data)
... |
java | public static UUID nameUUIDFromString(String name, UUID namespace, String encoding) {
byte[] nameAsBytes = name.getBytes();
byte[] concat = new byte[UUID_BYTE_LENGTH + nameAsBytes.length];
System.arraycopy(namespace.getRawBytes(), 0, concat, 0, UUID_BYTE_LENGTH);
System.arraycopy(nameAsBytes, 0, concat, UUID_BY... |
java | static Environment create(TemplateNode template, SoyRecord data, SoyRecord ijData) {
return new Impl(template, data, ijData);
} |
python | def from_string(cls, s):
"""Create an istance from string s containing a YAML dictionary."""
stream = cStringIO(s)
stream.seek(0)
return cls(**yaml.safe_load(stream)) |
java | @NullSafe
public static Set<Class<?>> getInterfaces(Class type) {
return Optional.ofNullable(type).map(theType -> getInterfaces(type, new HashSet<>()))
.orElse(Collections.emptySet());
} |
java | @Override
public String get(String url) throws HttpServiceException, TechnicalException {
logger.debug("HttpService GET on url: {}", url);
Response response;
try {
response = getClient().newCall(new Request.Builder().url(new URL(url)).header("Accept", "application/json").build())... |
python | def get_roles(username, **kwargs):
'''
Get roles assigned to a username.
.. code-block: bash
salt '*' nxos.cmd get_roles username=admin
'''
user = get_user(username)
if not user:
return []
command = 'show user-account {0}'.format(username)
info = ''
info = show(comm... |
python | def splitall(path):
"""
Splits path in its components:
foo/bar, /foo/bar and /foo/bar/ will all return
['foo', 'bar']
"""
head, tail = os.path.split(os.path.normpath(path))
components = []
while tail:
components.insert(0, tail)
head, tail = os.path.split(head)
return ... |
python | def del_design(self, design_name):
"""
Removes the specified design
design_name <str>
"""
try:
design = self.get_design(design_name)
r = requests.request(
"DELETE",
"%s/%s/_design/%s" % (
self.host,
self.database_name,
design_name
... |
java | private static List<List<XYZPoint>> loopsFromWkt(String wkt) throws IllegalArgumentException {
final String msgPrefix = "Improperly formatted WKT for polygon: ";
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(wkt));
tokenizer.lowerCaseMode(true);
tokenizer.eolIsSignifi... |
java | public byte[] compress(byte[] src, int srcOff, int srcLen) {
final int maxCompressedLength = maxCompressedLength(srcLen);
final byte[] compressed = new byte[maxCompressedLength];
final int compressedLength = compress(src, srcOff, srcLen, compressed, 0);
return Arrays.copyOf(compressed, compressedLength)... |
java | public Atom rewriteWithTypeVariable(Atom parentAtom) {
if (parentAtom.getPredicateVariable().isReturned()
&& !this.getPredicateVariable().isReturned()
&& this.getClass() == parentAtom.getClass()) {
return rewriteWithTypeVariable();
}
return this;
} |
java | public int getMedianIndex(final List<Integer> data, int pivot)
{
int medianIndex = data.size()/2;
//What if more than one point have the samve value? Keep incrementing until that dosn't happen
while(medianIndex < data.size()-1 && allVecs.get(data.get(medianIndex)).get(pivot) == allVecs.get(d... |
python | def to_array(self, dim='variable', name=None):
"""Convert this dataset into an xarray.DataArray
The data variables of this dataset will be broadcast against each other
and stacked along the first axis of the new array. All coordinates of
this dataset will remain coordinates.
Pa... |
java | public Mono<AccessLevel> getAccessLevel(String token, String applicationId)
throws CloudFoundryAuthorizationException {
String uri = getPermissionsUri(applicationId);
return this.webClient.get().uri(uri).header("Authorization", "bearer " + token)
.retrieve().bodyToMono(Map.class).map(this::getAccessLevel)
... |
python | def run(self):
'''
Execute salt-run
'''
import salt.runner
self.parse_args()
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
profiling_enabled = self.options.profiling_enabled
runner = salt.runner.Runner(self.con... |
python | def repository_data(self, repo):
"""
Grap data packages
"""
sum_pkgs, size, unsize, last_upd = 0, [], [], ""
for line in (Utils().read_file(
self.meta.lib_path + repo + "_repo/PACKAGES.TXT").splitlines()):
if line.startswith("PACKAGES.TXT;"):
... |
python | def reset(self):
"""Resets the sampler to its initial state
Note
----
This will destroy the label cache and history of estimates.
"""
self._TP = np.zeros(self._n_class)
self._FP = np.zeros(self._n_class)
self._FN = np.zeros(self._n_class)
self._TN... |
java | public void getWorkspaceFile(String accountId, String workspaceId, String folderId, String fileId) throws ApiException {
getWorkspaceFile(accountId, workspaceId, folderId, fileId, null);
} |
java | public List<OcelotService> getServices(HttpSession httpSession) {
List<OcelotService> result = new ArrayList<>();
Options options = (Options) httpSession.getAttribute(Constants.Options.OPTIONS);
if(options == null) {
options = new Options();
httpSession.setAttribute(Constants.Options.OPTIONS, options);
}
... |
python | def temporary_file(contents, suffix='', prefix='tmp'):
"""Creates a temporary file with specified contents that persists for the context.
:param contents: binary string that will be written to the file.
:param prefix: will be prefixed to the filename.
:param suffix: will be appended to the filename.
... |
java | @Override
public <T> Future<T> submit(Runnable task, T result) {
return schedule(Executors.callable(task, result), getDefaultDelayForTask(), TimeUnit.MILLISECONDS);
} |
python | def insert(self, index, option):
"""
Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the f... |
python | def remove_ifcfg_file(device_index='0'):
"""Removes the ifcfg file at the specified device index
and restarts the network service
:param device_index: (int) Device Index
:return: None
:raises CommandError
"""
log = logging.getLogger(mod_logger + '.remove_ifcfg_file')
if not isinstance(d... |
python | def sync_with(self, config, conflict_resolver):
'''Synchronizes current set of key/values in this instance with those in the config.'''
if not config.has_section(self._name):
config.add_section(self._name)
resolved = self._sync_and_resolve(config, conflict_resolver)
self._add... |
java | public Pair<ListenableFuture<?>, Boolean> streamMore(SystemProcedureExecutionContext context,
List<DBBPool.BBContainer> outputBuffers,
int[] rowCountAccumulator)
{
ListenableFuture<?> writeFuture = nu... |
python | def _set_rstp(self, v, load=False):
"""
Setter method for rstp, mapped from YANG variable /protocol/spanning_tree/rstp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_rstp is considered as a private
method. Backends looking to populate this variable shoul... |
java | public ServletContextHandler getHandler() {
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setContextPath(SERVLET_PATH);
contextHandler.addServlet(new ServletHolder(new MetricsServlet(mCollectorRegistry)), "/");
return contextHandler;
} |
java | @Override
public MtasTokenCollection createTokenCollection(Reader reader)
throws MtasParserException, MtasConfigException {
AtomicInteger position = new AtomicInteger(0);
MtasCRMAncestors unknownAncestors = new MtasCRMAncestors();
Map<String, Set<Integer>> idPositions = new HashMap<>();
Map<Str... |
java | public static Expression arrayPosition(String expression, Expression value) {
return arrayPosition(x(expression), value);
} |
java | public FessMessages addErrorsFailedToUploadStopwordsFile(String property) {
assertPropertyNotNull(property);
add(property, new UserMessage(ERRORS_failed_to_upload_stopwords_file));
return this;
} |
java | public ProductionOrStagingEndpointInfo publish(UUID appId, ApplicationPublishObject applicationPublishObject) {
return publishWithServiceResponseAsync(appId, applicationPublishObject).toBlocking().single().body();
} |
python | def GetRootKey(self):
"""Retrieves the Windows Registry root key.
Returns:
WinRegistryKey: Windows Registry root key.
Raises:
RuntimeError: if there are multiple matching mappings and
the correct mapping cannot be resolved.
"""
root_registry_key = virtual.VirtualWinRegistryKe... |
python | def convert_argmax(node, **kwargs):
"""Map MXNet's argmax operator attributes to onnx's ArgMax operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("axis"))
keepdims = get_boolean_attribute_value(attrs, "keepdims")
node = onnx.h... |
python | def curl(self):
"""
This will generate a curl equivalent call
:return: str
"""
ret = 'curl -X %s ' % self.method
ret += self.url
if self.request_data:
ret += " -d '%s'" % json.dumps(self.request_data)
if self.headers:
ret += ''.join... |
python | def parse_email(self, email_info):
"""Allows passing emails as "Example Name <example@example.com>"
:param email_info: Allows passing emails as
"Example Name <example@example.com>"
:type email_info: string
"""
name, email = rfc822.parseaddr(email_info)... |
java | public void reject() throws NotConnectedException, InterruptedException {
RejectPacket rejectPacket = new RejectPacket(this.session.getWorkgroupJID());
connection.sendStanza(rejectPacket);
// TODO: listen for a reply.
rejected = true;
} |
python | def set_list(self, name: str, plist) -> None:
"""Add or update an existing list."""
self.lists[zlib.crc32(name.encode())] = plist |
java | public static UnitRequest create(String group, String unit) {
return new UnitRequest().setContext(RequestContext.create().setGroup(group).setUnit(unit));
} |
java | public void marshall(EventDetailsErrorItem eventDetailsErrorItem, ProtocolMarshaller protocolMarshaller) {
if (eventDetailsErrorItem == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(eventDetailsErro... |
python | def _get_lua_path(self, name):
"""
Joins the given name with the relative path of the module.
"""
parts = (os.path.dirname(os.path.abspath(__file__)), "lua", name)
return os.path.join(*parts) |
python | def undecorated(o):
"""Remove all decorators from a function, method or class"""
# class decorator
if type(o) is type:
return o
try:
# python2
closure = o.func_closure
except AttributeError:
pass
try:
# python3
closure = o.__closure__
except ... |
java | public static VarLocal newLocal(Context ctx, Type type) {
int local = ctx.getGeneratorAdapter().newLocal(type);
return new VarLocal(local);
} |
java | @Override public IsolationForestModel createImpl() {
IsolationForestV3.IsolationForestParametersV3 p = this.parameters;
IsolationForestModel.IsolationForestParameters parms = p.createImpl();
return new IsolationForestModel( model_id.key(), parms, new IsolationForestModel.IsolationForestOutput(null) );
} |
java | @Override
public synchronized void refresh() {
IntervalProperty[] properties = getProperties();
for(IntervalProperty p : properties ) {
p.refresh();
}
} |
java | protected double valueAt(int row, int col) {
iter.seek(row);
return relation.get(iter).doubleValue(col);
} |
python | def remove_ip(enode, portlbl, addr, shell=None):
"""
Remove an IP address from an interface.
All parameters left as ``None`` are ignored and thus no configuration
action is taken for that parameter (left "as-is").
:param enode: Engine node to communicate with.
:type enode: topology.platforms.b... |
python | def deserialize_from_headers(headers):
"""Deserialize a DataONE Exception that is stored in a map of HTTP headers (used in
responses to HTTP HEAD requests)."""
return create_exception_by_name(
_get_header(headers, 'DataONE-Exception-Name'),
_get_header(headers, 'DataONE-Exception-DetailCode'... |
java | @Override
public void createFacade(String table, FacadeOptions facadeOptions, Audit audit) {
checkLegalTableName(table);
checkNotNull(facadeOptions, "facadeDefinition");
checkNotNull(audit, "audit");
_tableDao.createFacade(table, facadeOptions, audit);
} |
python | def _Gunzip(gzipped_content):
"""Returns gunzipped content from gzipped contents."""
f = tempfile.NamedTemporaryFile(suffix='gz', mode='w+b', delete=False)
try:
f.write(gzipped_content)
f.close() # force file synchronization
with gzip.open(f.name, 'rb') as h:
decompresse... |
python | def build_wheel(source_dir, wheel_dir, config_settings=None):
"""Build a wheel from a source directory using PEP 517 hooks.
:param str source_dir: Source directory containing pyproject.toml
:param str wheel_dir: Target directory to create wheel in
:param dict config_settings: Options to pass to build b... |
java | private JSType getJSType(Node n) {
JSType jsType = n.getJSType();
if (jsType == null) {
// TODO(nicksantos): This branch indicates a compiler bug, not worthy of
// halting the compilation but we should log this and analyze to track
// down why it happens. This is not critical and will be resol... |
java | public ListIPSetsResult withIPSets(IPSetSummary... iPSets) {
if (this.iPSets == null) {
setIPSets(new java.util.ArrayList<IPSetSummary>(iPSets.length));
}
for (IPSetSummary ele : iPSets) {
this.iPSets.add(ele);
}
return this;
} |
java | public V putIfAbsent( K key, V value )
{
if( value == null )
{
throw new NullPointerException();
}
int hash = hash( key.hashCode() );
return segmentFor( hash ).put( key, hash, value, true );
} |
java | public void put(K key,V value){
List<V> list;
if (map.containsKey(key)){
list=(List<V>)map.get(key);
} else {
list=new Vector<V>();
map.put(key,list);
}
list.add(value);
} |
python | def get_version(path):
"""Return the project version from VERSION file."""
with open(os.path.join(path, 'VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip()
return version.strip() |
java | @SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
try {
if (isLenientOnJson) {
JsonReader jsonReader = new JsonReader(new StringReader(body));
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/g... |
python | def siteblock(parser, token):
"""Two notation types are acceptable:
1. Two arguments:
{% siteblock "myblock" %}
Used to render "myblock" site block.
2. Four arguments:
{% siteblock "myblock" as myvar %}
Used to put "myblock" site block into "m... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "multiExtentOf")
public JAXBElement<MultiSurfacePropertyType> createMultiExtentOf(MultiSurfacePropertyType value) {
return new JAXBElement<MultiSurfacePropertyType>(_MultiExtentOf_QNAME, MultiSurfacePropertyType.class, null, value);
} |
java | @Pure
public static URL makeCanonicalURL(URL url) {
if (url != null) {
final String[] pathComponents = url.getPath().split(Pattern.quote(URL_PATH_SEPARATOR));
final List<String> canonicalPath = new LinkedList<>();
for (final String component : pathComponents) {
if (!CURRENT_DIRECTORY.equals(component))... |
python | def shared_options(rq):
"Default class options to pass to the CLI commands."
return {
'url': rq.redis_url,
'config': None,
'worker_class': rq.worker_class,
'job_class': rq.job_class,
'queue_class': rq.queue_class,
'connection_class': rq.connection_class,
} |
java | public String info() throws IOException, BackupExecuteException
{
String sURL =
path + HTTPBackupAgent.Constants.BASE_URL + HTTPBackupAgent.Constants.OperationType.BACKUP_SERVICE_INFO;
BackupAgentResponse response = transport.executeGET(sURL);
if (response.getStatus() == Respo... |
python | def get_port_channel_detail_output_lacp_actor_system_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
output = ET.SubElement(get_port_channel_detai... |
python | def generate_transpose(node_name, in_name, out_name, axes, base_name, func_counter):
"""Generate a Transpose operator to transpose the specified buffer.
"""
trans = nnabla_pb2.Function()
trans.type = "Transpose"
set_function_name(trans, node_name, base_name, func_counter)
trans.input.extend([in_... |
java | public static snmp_view add(nitro_service client, snmp_view resource) throws Exception
{
resource.validate("add");
return ((snmp_view[]) resource.perform_operation(client, "add"))[0];
} |
java | public static <I extends Request, O extends Response>
Function<Client<I, O>, LoggingClient<I, O>> newDecorator() {
return new LoggingClientBuilder()
.requestLogLevel(LogLevel.INFO)
.successfulResponseLogLevel(LogLevel.INFO)
.failureResponseLogLevel(LogLevel.WA... |
python | def _sign_button_press(self):
"""Validate input from ent_id, then sign in to the Timesheet."""
user_id = self.ent_id.text().strip()
try:
status = controller.sign(user_id)
# ERROR: User type is unknown (!student and !tutor)
except ValueError as e:
logger.... |
python | def get_x(self, var, coords=None):
"""
Get the x-coordinate of a variable
This method searches for the x-coordinate in the :attr:`ds`. It first
checks whether there is one dimension that holds an ``'axis'``
attribute with 'X', otherwise it looks whether there is an intersection
... |
java | public void connect() throws Exception {
adminClients = new ArrayList<AdminClient>(urls.size());
// bootstrap from two urls
Map<String, Cluster> clusterMap = new HashMap<String, Cluster>(urls.size());
Map<String, StoreDefinition> storeDefinitionMap = new HashMap<String, StoreDefinition>(... |
java | static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bo... |
python | def create_alarm(self, member_id=0):
"""Create an alarm.
If no member id is given, the alarm is activated for all the
members of the cluster. Only the `no space` alarm can be raised.
:param member_id: The cluster member id to create an alarm to.
If 0, the alar... |
java | public static JndiConfigurationSource create(Context context, int priority) {
return new JndiConfigurationSource(createJndiConfiguration(context, null), priority);
} |
python | def visit_Dict(self, pattern):
""" Dict can match with unordered values. """
if not isinstance(self.node, Dict):
return False
if len(pattern.keys) > MAX_UNORDERED_LENGTH:
raise DamnTooLongPattern("Pattern for Dict is too long")
for permutation in permutations(rang... |
java | public static byte[] getConfigureBytes(int partitionCount, int tokenCount) {
Preconditions.checkArgument(partitionCount > 0);
Preconditions.checkArgument(tokenCount > partitionCount);
Buckets buckets = new Buckets(partitionCount, tokenCount);
ElasticHashinator hashinator = new ElasticHas... |
java | public static <K, V> void forEachKeyValue(Map<K, V> map, Procedure2<? super K, ? super V> procedure2)
{
ParallelMapIterate.forEachKeyValue(map, procedure2, 2, map.size());
} |
python | def _create_eval_metric_composite(metric_names: List[str]) -> mx.metric.CompositeEvalMetric:
"""
Creates a composite EvalMetric given a list of metric names.
"""
metrics = [EarlyStoppingTrainer._create_eval_metric(metric_name) for metric_name in metric_names]
return mx.metric.cre... |
python | def is_valid_command(self, word: str) -> Tuple[bool, str]:
"""Determine whether a word is a valid name for a command.
Commands can not include redirection characters, whitespace,
or termination characters. They also cannot start with a
shortcut.
If word is not a valid command, ... |
python | def _invert(self):
"""
Invert coverage data from {test_context: {file: line}}
to {file: {test_context: line}}
"""
result = defaultdict(dict)
for test_context, src_context in six.iteritems(self.data):
for src, lines in six.iteritems(src_context):
... |
java | @Override
public IProofObligationList caseASpecificationStm(ASpecificationStm node,
IPOContextStack question) throws AnalysisException
{
try
{
IProofObligationList obligations = new ProofObligationList();
if (node.getErrors() != null)
{
for (AErrorCase err : node.getErrors())
{
obligatio... |
java | public List<LocalTime> top(int n) {
List<LocalTime> top = new ArrayList<>();
int[] values = data.toIntArray();
IntArrays.parallelQuickSort(values, descendingIntComparator);
for (int i = 0; i < n && i < values.length; i++) {
top.add(PackedLocalTime.asLocalTime(values[i]));
... |
python | def get_user(self, id=None, name=None, email=None):
""" Get user object by email or id.
"""
log.info("Picking user: %s (%s) (%s)" % (name, email, id))
from qubell.api.private.user import User
if email:
user = User.get(self._router, organization=self, email=email)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.