language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void endExport() {
try {
m_resultSet.close();
m_statement.close();
m_connection.close();
}
catch (SQLException e) {
throw new RuntimeException(e);
}
} |
java | public static byte[] inputStreamToBytes(InputStream in)
{
try
{
FastByteArrayOutputStream out = new FastByteArrayOutputStream(16384);
transfer(in, out);
return Arrays.copyOf(out.buffer, out.size);
}
catch (Exception e)
{
return ... |
python | def list_cron_job_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_cron_job_for_all_namespaces(async_req=Tr... |
python | def _delete_resource(self, url):
"""
DELETEs the resource at url
"""
conn, head = self._construct_request()
conn.request("DELETE", url, "", head)
resp = conn.getresponse()
self._handle_response_errors('DELETE', url, resp) |
python | def fnmatch(self, pattern, normcase=None):
""" Return ``True`` if `self.name` matches the given `pattern`.
`pattern` - A filename pattern with wildcards,
for example ``'*.py'``. If the pattern contains a `normcase`
attribute, it is applied to the name and path prior to compariso... |
python | def get_calculation_dependants_for(service):
"""Collect all services which depend on this service
:param service: Analysis Service Object/ZCatalog Brain
:returns: List of services that depend on this service
"""
def calc_dependants_gen(service, collector=None):
"""Generator for recursive r... |
python | def post(self, request, *args, **kwargs):
"""
Builds a dynamic form that targets only the field in question, and saves the modification.
"""
self.object_list = None
form = self.get_xeditable_form(self.get_xeditable_form_class())
if form.is_valid():
obj = self.... |
java | public static <A> ProgramChromosome<A> of(
final int depth,
final ISeq<? extends Op<A>> operations,
final ISeq<? extends Op<A>> terminals
) {
return of(
depth,
(Predicate<? super ProgramChromosome<A>> & Serializable)ProgramChromosome::isSuperValid,
operations,
terminals
);
} |
java | public void setConfigurationItems(java.util.Collection<ConfigurationItem> configurationItems) {
if (configurationItems == null) {
this.configurationItems = null;
return;
}
this.configurationItems = new com.amazonaws.internal.SdkInternalList<ConfigurationItem>(configurati... |
python | def visitTypeExceptions(self, ctx: jsgParser.TypeExceptionsContext):
""" typeExceptions: DASH idref+ """
for tkn in as_tokens(ctx.idref()):
self._context.directives.append('_CONTEXT.TYPE_EXCEPTIONS.append("{}")'.format(tkn)) |
python | def _process_monomial(self, monomial, n_vars):
"""Process a single monomial when building the moment matrix.
"""
processed_monomial, coeff = separate_scalar_factor(monomial)
# Are we substituting this moment?
try:
substitute = self.moment_substitutions[processed_monom... |
python | def authenticate(self, authenticator=None, username=None, password=None):
"""
Set the type of authenticator to use when opening buckets or performing
cluster management operations
:param authenticator: The new authenticator to use
:param username: The username to authenticate wit... |
python | def auth_user_remote_user(self, username):
"""
REMOTE_USER user Authentication
:param username: user's username for remote auth
:type self: User model
"""
user = self.find_user(username=username)
# User does not exist, create one if auto user registr... |
java | @Override
public <T> void send(NotificationType type, List<T> messages) throws NotificationException {
String[] strMessages = new String[messages.size()];
for (int index = 0; index < messages.size(); index++) {
strMessages[index] = getMessageJson(messages.get(index));
}
s... |
python | def create_cms_plugin_page(apphook, apphook_namespace, placeholder_slot=None):
"""
Create cms plugin page in all existing languages.
Add a link to the index page.
:param apphook: e.g...........: 'FooBarApp'
:param apphook_namespace: e.g.: 'foobar'
:return:
"""
creator = CmsPluginPageCre... |
java | static List<String> iterateDownPids(List<String> segments) {
List<String> res = new ArrayList<>();
for (int i = segments.size(); i > 0; i--) {
StringBuilder sb = new StringBuilder();
sb.append(JMX_ACL_PID_PREFIX);
for (int j = 0; j < i; j++) {
sb.appen... |
java | @Override
public void doLayout() {
if (contentPane != null) {
setPreferredSize(contentPane.getPreferredSize());
contentPane.setLocation(0, 0);
contentPane.setSize(getWidth(), getHeight());
}
if (glassPane != null) {
glassPane.setLocation(0, 0);
glassPane.setSize(getWidth(), getHeight());
... |
python | def list_instance_configs(self, page_size=None, page_token=None):
"""List available instance configurations for the client's project.
.. _RPC docs: https://cloud.google.com/spanner/docs/reference/rpc/\
google.spanner.admin.instance.v1#google.spanner.admin.\
i... |
python | def list(self):
"""List the users you have blocked.
:return: a list of :class:`~groupy.api.blocks.Block`'s
:rtype: :class:`list`
"""
params = {'user': self.user_id}
response = self.session.get(self.url, params=params)
blocks = response.data['blocks']
retu... |
java | private static boolean hasUnsafeChars(String s) {
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (Character.isLetter(c) || c == '.')
continue;
else
return true;
}
return false;
} |
java | public LocalDateTime getOldDateTimeStrict() {
// If there is no change event, then the old value is the same as the current value.
LocalDate oldDateValue = datePicker.getDate();
LocalTime oldTimeValue = timePicker.getTime();
// If a change event exists, then the old value can be retrieve... |
java | public static void deregisterAllDrivers ()
{
final Enumeration <Driver> aAllDrivers = DriverManager.getDrivers ();
while (aAllDrivers.hasMoreElements ())
{
final Driver aDriver = aAllDrivers.nextElement ();
try
{
DriverManager.deregisterDriver (aDriver);
LOGGER.info ("Der... |
python | def _implementation():
"""Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 2.7.5 it will return
{'name': 'CPython', 'version': '2.7.5'}.
This function works best on CPython and Py... |
java | public static SimpleMatrix randomNormal( SimpleMatrix covariance , Random random ) {
SimpleMatrix found = new SimpleMatrix(covariance.numRows(), 1,covariance.getType());
switch( found.getType() ) {
case DDRM:{
CovarianceRandomDraw_DDRM draw = new CovarianceRandomDraw_DDRM(r... |
python | def check_dimensional_vertical_coordinate(self, ds):
'''
Check units for variables defining vertical position are valid under
CF.
CF §4.3.1 The units attribute for dimensional coordinates will be a string
formatted as per the udunits.dat file.
The acceptable units for v... |
python | def classify_segmented_recording(recording, result_format=None):
"""Use this function if you are sure you have a single symbol.
Parameters
----------
recording : string
The recording in JSON format
Returns
-------
list of dictionaries
Each dictionary contains the keys 'symb... |
python | def get_directory(self, identifier):
"""Implements the policy for naming directories for image objects. Image
object directories are name by their identifier. In addition, these
directories are grouped in parent directories named by the first two
characters of the identifier. The aim is ... |
java | public void showErrors(final Set<String> messages) {
final InputElement inputElement = this.getInputElement();
if (messages.isEmpty()) {
if (FeatureCheck.supportCustomValidity(inputElement)) {
inputElement.setCustomValidity(StringUtils.EMPTY);
}
if (this.validationMessageElement == nul... |
python | def _get_partition_info(storage_system, device_path):
'''
Returns partition informations for a device path, of type
vim.HostDiskPartitionInfo
'''
try:
partition_infos = \
storage_system.RetrieveDiskPartitionInfo(
devicePath=[device_path])
except vim.fa... |
python | def fcoe_fcoe_fabric_map_fcoe_fip_advertisement_fcoe_fip_advertisement_interval(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_fabric_map = ET.SubElement(fcoe, "fcoe-fa... |
java | protected static Object protectNull(Object rawAttributeValue, AttributeType type) {
if (rawAttributeValue == null) {
if (type.isNullAllowed()) {
return new NullAttribute(type);
}
throw new NullPointerException();
}
return rawAttributeValue;
} |
java | public static double bachelierOptionImpliedVolatility(
double forward,
double optionMaturity,
double optionStrike,
double payoffUnit,
double optionValue)
{
if(forward == optionStrike) {
return optionValue / Math.sqrt(optionMaturity / Math.PI / 2.0) / payoffUnit;
}
// Limit the maximum number o... |
java | public static void removePreferenceDirective(
IPerson person, String elementId, String attributeName) {
removeDirective(elementId, attributeName, Constants.ELM_PREF, person);
} |
java | public List<Specification> getSpecifications(SystemUnderTest systemUnderTest, Repository repository) throws GreenPepperServerException {
try {
sessionService.startSession();
List<Specification> specifications = documentDao.getSpecifications(systemUnderTest, repository);
l... |
java | public String [] getParamNames() {
Vector<String> v = new Vector<>();
// Get the params names from the query
SortedSet<String> pns = this.getParamNameSet(HtmlParameter.Type.url);
Iterator<String> iterator = pns.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (name != nu... |
java | private void deleteExecutorDirs(String[] dirs) {
for (String localDir : dirs) {
try {
JavaUtils.deleteRecursively(new File(localDir));
logger.debug("Successfully cleaned up directory: {}", localDir);
} catch (Exception e) {
logger.error("Failed to delete directory: " + localDir, ... |
python | def get_object_directory(self, obj):
"""
Return the directory containing an object's defining class.
Returns None if there is no such directory, for example if the
class was defined in an interactive Python session, or in a
doctest that appears in a text file (rather than a Pyth... |
java | private static int[] readInfoFile(File tmpFile) {
int[] info = new int[8];
try (RandomAccessFile infoFile = new RandomAccessFile(tmpFile, "r")) {
// audio codec id
info[0] = infoFile.readInt();
// video codec id
info[1] = infoFile.readInt();
//... |
java | byte[] readCodewords() throws FormatException {
FormatInformation formatInfo = readFormatInformation();
Version version = readVersion();
// Get the data mask for the format used in this QR Code. This will exclude
// some bits from reading as we wind through the bit matrix.
DataMask dataMask = Data... |
python | def _alpha(self, L):
""" Covariance-derived term to construct expectations. See Rasmussen & Williams.
Parameters
----------
L : np.ndarray
Cholesky triangular
Returns
----------
np.ndarray (alpha)
"""
return la.cho_solve(... |
python | def on_session_created(self, session_context):
''' Invoked to execute code when a new session is created.
This method calls ``on_session_created`` on each handler, in order,
with the session context passed as the only argument.
May return a ``Future`` which will delay session creation ... |
python | def fast_count_associators(server):
"""
Create count of associators for CIM_ReferencedProfile using the
antecedent and dependent reference properties as ResultRole for each profile
defined in server.profiles and return a dictionary of the count. This
code does a shortcut in executing EnumerateInstan... |
java | protected ArrayList filterXidsByCruuidAndEpoch(ArrayList xidList,
byte[] cruuid,
int epoch) {
if (tc.isEntryEnabled())
Tr.entry(tc, "filterXidsByCruuidAndEpoch", new Object[] {
... |
python | def jwt_required(fn):
"""
A decorator to protect a Flask endpoint.
If you decorate an endpoint with this, it will ensure that the requester
has a valid access token before allowing the endpoint to be called. This
does not check the freshness of the access token.
See also: :func:`~flask_jwt_ext... |
java | @Nullable
public TransitionValues getTransitionValues(@NonNull View view, boolean start) {
if (mParent != null) {
return mParent.getTransitionValues(view, start);
}
TransitionValuesMaps valuesMaps = start ? mStartValues : mEndValues;
return valuesMaps.viewValues.get(view)... |
python | def error_string(self):
"""Returns a well formed error message
e.g at least 5 times but was called 4 times
:rtype string
"""
if self.has_correct_call_count():
return ''
return '{} instead of {} {} '.format(
self._restriction_string(),
... |
python | def get_objective_ids_by_objective_bank(self, objective_bank_id):
"""Gets the list of ``Objective`` ``Ids`` associated with an ``ObjectiveBank``.
arg: objective_bank_id (osid.id.Id): ``Id`` of the
``ObjectiveBank``
return: (osid.id.IdList) - list of related objectives
... |
python | def absolute(self):
"""
The FQDN as a string in absolute form
"""
if not self.is_valid:
raise ValueError('invalid FQDN `{0}`'.format(self.fqdn))
if self.is_valid_absolute:
return self.fqdn
return '{0}.'.format(self.fqdn) |
python | def referenceframe(self, event):
"""Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message
"""
self.log("Got a reference frame update! ", event, lvl=e... |
java | @Override
public int size() {
// Try a few times to get accurate count. On failure due to
// continuous async changes in table, resort to locking.
final Segment<K,V>[] segments = this.segments;
int size;
boolean overflow; // true if size overflows 32 bits
long sum; ... |
python | def agents(self):
"""
| Description: IDs of agents involved in the chat
"""
if self.api and self.agent_ids:
return self.api._get_agents(self.agent_ids) |
python | def add_candidate_adapter_ports(self, ports):
"""
Add a list of storage adapter ports to this storage group's candidate
adapter ports list.
This operation only applies to storage groups of type "fcp".
These adapter ports become candidates for use as backing adapters when
... |
python | def _get_stddevs(self, coeffs, stddev_types):
"""
Look up values from Table 5 on p. 483 and convert to natural logarithm.
Interpretation of "sigma_log(Y)" as the common logarithm is based on
the order of magnitude of the values and consistent use of "log" and
"ln" to denote commo... |
python | def intent(self, intent_name):
"""Decorator routes an Rogo IntentRequest.
Functions decorated as an intent are registered as the view function for the Intent's URL,
and provide the backend responses to give your Skill its functionality.
@ask.intent('WeatherIntent')
def weather(ci... |
python | def to_unicode(path, errors="replace"):
"""Given a bytestring/unicode path, return it as unicode."""
if isinstance(path, UNICODE):
return path
return path.decode(sys.getfilesystemencoding(), errors) |
python | def to_period(self, freq=None, copy=True):
"""
Convert Series from DatetimeIndex to PeriodIndex with desired
frequency (inferred from index if not passed).
Parameters
----------
freq : str, default None
Frequency associated with the PeriodIndex.
copy ... |
python | def has_field(cls, field_name):
"""
Check if the current class has a field with the name "field_name"
Add management of dynamic fields, to return True if the name matches an
existing dynamic field without existing copy for this name.
"""
if super(ModelWithDynamicFieldMixi... |
python | def by_content_type():
"""
:return:
A key function that returns a 2-tuple (content_type, (msg[content_type],)).
In plain English, it returns the message's *content type* as the key,
and the corresponding content as a positional argument to the handler
function.
"""
def f(... |
java | private Object getPropertyValue(HashMap<String, PropertyDescriptor> proDscMap, Object oldInstance, String propName) throws Exception
{
// Try to get the read method for the property
Method getter = null;
if (null != proDscMap)
{
PropertyDescriptor pd = proDscMap.get(Introspector.decapitalize(propName));
... |
java | private void appendBehaviorMembersToBlock(final PolymerClassDefinition cls, Node block) {
String qualifiedPath = cls.target.getQualifiedName() + ".prototype.";
Map<String, Node> nameToExprResult = new HashMap<>();
for (BehaviorDefinition behavior : cls.behaviors) {
for (MemberDefinition behaviorFuncti... |
java | public Optional<PipelineSchedule> getOptionalPipelineSchedule (Object projectIdOrPath, Integer pipelineScheduleId) {
try {
return (Optional.ofNullable(getPipelineSchedule(projectIdOrPath, pipelineScheduleId)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalF... |
java | public <T> T get(final Object key) {
@SuppressWarnings("unchecked")
// cast is not safe but convenient
T value = (T) additionalData.get(key);
return value;
} |
python | def append(self, record):
"""
Adds the passed +record+ to satisfy the query. Only intended to be
used in conjunction with associations (i.e. do not use if self.record
is None).
Intended use case (DO THIS):
post.comments.append(comment)
NOT THIS:
Query(... |
java | private boolean prepareAddActiveMessage()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "prepareAddActiveMessage");
boolean messageAccepted = true;
// We can't even accept the next message if the consumer is already
// suspende... |
python | def add_final_state(self, f):
"""
:param f: int , the state qi to be added to F, epsilon is
conventionally defined as the last node (q_|S|)
"""
if f not in self.Q:
LOG.error("The specified value is invalid, f must be a member of Q")
raise InputError("The ... |
python | def make_hone_cache_wrapper(inner_func, maxsize, maxage, finder,
store_partials):
""" Keeps a cache of requests we've already made and use that for
generating results if possible. If the user asked for a root prior
to this call we can use it to skip a new lookup using `finder`. ... |
java | private void fetchResource(HttpMessage msg) throws IOException {
if (parent.getHttpSender() == null) {
return;
}
try {
parent.getHttpSender().sendAndReceive(msg);
} catch (ConnectException e) {
log.debug("Failed to connect to: " + msg.getRequestHeader().getURI(), e);
throw e;
} catch (SocketTim... |
python | def gpio_trigger(self, user_gpio, pulse_len=10, level=1):
"""
Send a trigger pulse to a GPIO. The GPIO is set to
level for pulse_len microseconds and then reset to not level.
user_gpio:= 0-31
pulse_len:= 1-100
level:= 0-1
...
pi.gpio_trigger(23, 10, 1... |
python | def build_modules(is_training, vocab_size):
"""Construct the modules used in the graph."""
# Construct the custom getter which implements Bayes by Backprop.
if is_training:
estimator_mode = tf.constant(bbb.EstimatorModes.sample)
else:
estimator_mode = tf.constant(bbb.EstimatorModes.mean)
lstm_bbb_cus... |
java | public void localCommit()
{
if (log.isDebugEnabled()) log.debug("commit was called");
if (!this.isInLocalTransaction)
{
throw new TransactionNotInProgressException("Not in transaction, call begin() before commit()");
}
try
{
if(!broker... |
java | public static JavaPairRDD<Long, List<Writable>> restoreMapFile(String path, JavaSparkContext sc) {
Configuration c = new Configuration();
c.set(FileInputFormat.INPUT_DIR, FilenameUtils.normalize(path, true));
JavaPairRDD<LongWritable, RecordWritable> pairRDD =
sc.newAPIHa... |
java | @Override
public Future<Message> add(StaticBuffer content) {
return add(content,manager.defaultWritePartitionIds[random.nextInt(manager.defaultWritePartitionIds.length)]);
} |
python | def get_conf(cls, builder, doctree=None):
"""Return a dictionary of slide configuration for this doctree."""
# set up the default conf
result = {
'theme': builder.config.slide_theme,
'autoslides': builder.config.autoslides,
'slide_classes': [],
}
... |
java | protected void initializePropertyEditor() {
Map<String, CmsXmlContentProperty> propertyConfig = m_values.getPropertyDefinitions();
m_propertyEditorHandler = new CmsUploadPropertyEditorHandler(m_dialog, m_values);
CmsSimplePropertyEditor propertyEditor = new CmsUploadPropertyEditor(propertyC... |
python | def _build_logger(self, level=logging.INFO):
""" return a logger. if logger is none, generate a logger from stdout """
self._debug_stream = StringIO()
logger = logging.getLogger('sprinter')
# stdout log
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setLevel(level)... |
java | @Override
public boolean isAcceptableChange(
Changes changes, Tree node, MethodSymbol symbol, VisitorState state) {
return findArgumentsForOtherInstances(symbol, node, state).stream()
.allMatch(arguments -> !anyArgumentsMatch(changes.changedPairs(), arguments));
} |
java | public <T> T fromJson(@Nullable String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) mapper.readValue(jsonString, javaType);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
} |
java | public T AddEx(T value) {
if (m_Count < m_Capacity) {
m_Array[++m_Count] = value;
UpHeap();
return null;
}
else if (m_Capacity == 0) return value;
else if (greaterThan(m_Array[1], value)) {
T retVal = m_Array[1];
m_Arra... |
java | @Nonnull
public static String getRequestPathInfo (@Nullable final HttpServletRequest aRequest)
{
String ret = null;
if (aRequest != null)
try
{
// They may return null!
if (aRequest.isAsyncSupported () && aRequest.isAsyncStarted ())
ret = (String) aRequest.getAttribute ... |
java | public final Ix<T> remove(IxPredicate<? super T> predicate) {
return new IxRemove<T>(this, nullCheck(predicate, "predicate is null"));
} |
python | def _compile_update_join_wheres(self, query):
"""
Compile the "join" clauses for an update.
:param query: A QueryBuilder instance
:type query: QueryBuilder
:return: The compiled sql
:rtype: str
"""
join_wheres = []
for join in query.joins:
... |
python | def getRequiredAttrs(self):
"""Get the type URIs for all attributes that have been marked
as required.
@returns: A list of the type URIs for attributes that have
been marked as required.
@rtype: [str]
"""
required = []
for type_uri, attribute in self.... |
python | def _check_errors(self):
"""Call this function after parsing the args to see if there are any
errors in the way things are input. Specifically for glotk-sweep, make
sure that all of the parameters for sweep have arguemnts if at least one
does."""
# use this to make sure that swee... |
python | def _parse_remind(self, filename, lines=''):
"""Calls remind and parses the output into a dict
filename -- the remind file (included files will be used as well)
lines -- used as stdin to remind (filename will be set to -)
"""
files = {}
reminders = {}
if lines:
... |
python | def get_port_switch_bindings(port_id, switch_ip):
"""List all vm/vlan bindings on a Nexus switch port."""
LOG.debug("get_port_switch_bindings() called, "
"port:'%(port_id)s', switch:'%(switch_ip)s'",
{'port_id': port_id, 'switch_ip': switch_ip})
try:
return _lookup_all_ne... |
python | def get_backend_expiry(self, expiry=DEFAULT_EXPIRY):
"""
Return the expiry value usable by this backend based upon the provided
timeout.
"""
if expiry == DEFAULT_EXPIRY:
expiry = self.default_expiry
elif expiry == 0:
# avoid time.time() related pre... |
java | public JavadocQuirks getJavadocVersion() {
if ( javadocVersion == null ) {
String javaVersion = System.getProperty("java.version");
if ( javaVersion != null && javaVersion.compareTo("1.8") >= 0 ) {
return JavadocQuirks.V8;
}
else {
... |
java | public Template globalLoad(String name, boolean lookupOnly) {
// If this context was created without a Compiler object specified, then
// no global lookups can be done. Just return null indicating that the
// requested template can't be found.
if (compiler == null) {
return null;
}
// Use the full look... |
java | public void addContentsList(Content contentTree, Content contentListTree) {
Content titleContent = getResource(
"doclet.Constants_Summary");
Content pHeading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, true,
HtmlStyle.title, titleContent);
Content div = HtmlTr... |
java | public void setAttribute(Class sender, Object object, String attribute, Object newValue, boolean useSuper, boolean fromInsideClass) {
checkInitalised();
boolean isStatic = theClass != Class.class && object instanceof Class;
if (isStatic && object != theClass) {
MetaClass mc = regist... |
python | def uiFile(modulefile, inst, theme='', className=None):
"""
Returns the ui file for the given instance and module file.
:param moduleFile | <str>
inst | <QWidget>
:return <str>
"""
if className is None:
className = inst.__class__.__name_... |
python | def registerbuilder(self, builder, name=None):
"""Register a schema builder with a key name.
Can be used such as a decorator where the builder can be the name for a
short use.
:param SchemaBuilder builder: schema builder.
:param str name: builder name. Default is builder name o... |
java | public static com.liferay.commerce.product.type.virtual.order.model.CommerceVirtualOrderItem fetchCommerceVirtualOrderItemByUuidAndGroupId(
String uuid, long groupId) {
return getService()
.fetchCommerceVirtualOrderItemByUuidAndGroupId(uuid, groupId);
} |
python | def round_sigfigs(x, n=2):
"""
Rounds the number to the specified significant figures. x can also be
a list or array of numbers (in these cases, a numpy array is returned).
"""
iterable = is_iterable(x)
if not iterable: x = [x]
# make a copy to be safe
x = _n.array(x)
# loop o... |
python | def from_conll(this_class, text):
"""Construct a Token from a line in CoNLL-X format."""
fields = text.split('\t')
fields[0] = int(fields[0]) # index
fields[6] = int(fields[6]) # head index
if fields[5] != '_': # feats
fields[5] = tuple(fields[5].split('|'))
f... |
python | def pretty_print_counters(counters):
"""print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
... |
java | public double get(int i) {
for (Entry e : array) {
if (e.i == i) {
return e.x;
}
}
return 0.0;
} |
java | private Collection<Ticket> getNonExpiredTicketGrantingTickets() {
return this.centralAuthenticationService.getTickets(ticket -> ticket instanceof TicketGrantingTicket && !ticket.isExpired());
} |
java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
af_persistant_stat_info_responses result = (af_persistant_stat_info_responses) service.get_payload_formatter().string_to_resource(af_persistant_stat_info_responses.class, response);
if(result.errorcode !... |
python | def runcmd(self, cmd, args):
'''Run a single command from pre-parsed arguments.
This is intended to be run from :meth:`main` or somewhere else
"at the top level" of the program. It may raise
:exc:`exceptions.SystemExit` if an argument such as ``--help``
that normally causes exe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.