language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | @GET
@Path(WEBUI_WORKERS)
@ReturnType("alluxio.wire.MasterWebUIWorkers")
public Response getWebUIWorkers() {
return RestUtils.call(() -> {
MasterWebUIWorkers response = new MasterWebUIWorkers();
response.setDebug(ServerConfiguration.getBoolean(PropertyKey.DEBUG));
List<WorkerInfo> workerInfos = mBlockMaster.getWorkerInfoList();
NodeInfo[] normalNodeInfos = WebUtils.generateOrderedNodeInfos(workerInfos);
response.setNormalNodeInfos(normalNodeInfos);
List<WorkerInfo> lostWorkerInfos = mBlockMaster.getLostWorkersInfoList();
NodeInfo[] failedNodeInfos = WebUtils.generateOrderedNodeInfos(lostWorkerInfos);
response.setFailedNodeInfos(failedNodeInfos);
return response;
}, ServerConfiguration.global());
} |
python | def echo_to_output_stream(self, email_messages):
""" Write all messages to the stream in a thread-safe way. """
if not email_messages:
return
with self._lock:
try:
stream_created = self.open()
for message in email_messages:
self.write_to_stream(message)
self.stream.flush() # flush after each message
if stream_created:
self.close()
except Exception:
if not self.fail_silently:
raise |
java | public synchronized void clear(ApplicationDefinition appDef) {
String appName = appDef.getAppName();
for (TableDefinition tableDef : appDef.getTableDefinitions().values()) {
m_cacheMap.remove(appName + "/" + tableDef.getTableName()); // might have no entry
}
m_appShardMap.remove(appName);
} |
java | private static void processItems(Map<DisconfKey, List<IDisconfUpdate>> inverseMap,
DisconfUpdateService disconfUpdateService, IDisconfUpdate iDisconfUpdate) {
List<String> itemKeys = Arrays.asList(disconfUpdateService.itemKeys());
// 反索引
for (String key : itemKeys) {
DisconfKey disconfKey = new DisconfKey(DisConfigTypeEnum.ITEM, key);
addOne2InverseMap(disconfKey, inverseMap, iDisconfUpdate);
}
} |
python | def _elementtree_to_dict(self, element):
"""Convert XML elementtree to dictionary.
Converts the actual response from the ILO for an API
to the dictionary.
"""
node = {}
text = getattr(element, 'text')
if text is not None:
text = text.strip()
if len(text) != 0:
node['text'] = text
node.update(element.items()) # element's attributes
child_nodes = {}
for child in element: # element's children
child_nodes.setdefault(child.tag, []).append(
self._elementtree_to_dict(child))
# convert all single-element lists into non-lists
for key, value in child_nodes.items():
if len(value) == 1:
child_nodes[key] = value[0]
node.update(child_nodes.items())
return node |
java | public MessagePacker packString(String s)
throws IOException
{
if (s.length() <= 0) {
packRawStringHeader(0);
return this;
}
else if (CORRUPTED_CHARSET_ENCODER || s.length() < smallStringOptimizationThreshold) {
// Using String.getBytes is generally faster for small strings.
// Also, when running on a platform that has a corrupted CharsetEncoder (i.e. Android 4.x), avoid using it.
packStringWithGetBytes(s);
return this;
}
else if (s.length() < (1 << 8)) {
// ensure capacity for 2-byte raw string header + the maximum string size (+ 1 byte for falback code)
ensureCapacity(2 + s.length() * UTF_8_MAX_CHAR_SIZE + 1);
// keep 2-byte header region and write raw string
int written = encodeStringToBufferAt(position + 2, s);
if (written >= 0) {
if (str8FormatSupport && written < (1 << 8)) {
buffer.putByte(position++, STR8);
buffer.putByte(position++, (byte) written);
position += written;
}
else {
if (written >= (1 << 16)) {
// this must not happen because s.length() is less than 2^8 and (2^8) * UTF_8_MAX_CHAR_SIZE is less than 2^16
throw new IllegalArgumentException("Unexpected UTF-8 encoder state");
}
// move 1 byte backward to expand 3-byte header region to 3 bytes
buffer.putMessageBuffer(position + 3, buffer, position + 2, written);
// write 3-byte header
buffer.putByte(position++, STR16);
buffer.putShort(position, (short) written);
position += 2;
position += written;
}
return this;
}
}
else if (s.length() < (1 << 16)) {
// ensure capacity for 3-byte raw string header + the maximum string size (+ 2 bytes for fallback code)
ensureCapacity(3 + s.length() * UTF_8_MAX_CHAR_SIZE + 2);
// keep 3-byte header region and write raw string
int written = encodeStringToBufferAt(position + 3, s);
if (written >= 0) {
if (written < (1 << 16)) {
buffer.putByte(position++, STR16);
buffer.putShort(position, (short) written);
position += 2;
position += written;
}
else {
if (written >= (1L << 32)) { // this check does nothing because (1L << 32) is larger than Integer.MAX_VALUE
// this must not happen because s.length() is less than 2^16 and (2^16) * UTF_8_MAX_CHAR_SIZE is less than 2^32
throw new IllegalArgumentException("Unexpected UTF-8 encoder state");
}
// move 2 bytes backward to expand 3-byte header region to 5 bytes
buffer.putMessageBuffer(position + 5, buffer, position + 3, written);
// write 3-byte header header
buffer.putByte(position++, STR32);
buffer.putInt(position, written);
position += 4;
position += written;
}
return this;
}
}
// Here doesn't use above optimized code for s.length() < (1 << 32) so that
// ensureCapacity is not called with an integer larger than (3 + ((1 << 16) * UTF_8_MAX_CHAR_SIZE) + 2).
// This makes it sure that MessageBufferOutput.next won't be called a size larger than
// 384KB, which is OK size to keep in memory.
// fallback
packStringWithGetBytes(s);
return this;
} |
python | def edit(self, name=None, description=None, start_date=None, due_date=None, assignees=None, assignees_ids=None,
status=None):
"""Edit the details of an activity.
:param name: (optionally) edit the name of the activity
:type name: basestring or None
:param description: (optionally) edit the description of the activity
:type description: basestring or None
:param start_date: (optionally) edit the start date of the activity as a datetime object (UTC time/timezone
aware preferred)
:type start_date: datetime or None
:param due_date: (optionally) edit the due_date of the activity as a datetime object (UTC time/timzeone
aware preferred)
:type due_date: datetime or None
:param assignees: (optionally) edit the assignees (usernames) of the activity as a list, will overwrite all
assignees
:type assignees: list(basestring) or None
:param assignees_ids: (optionally) edit the assignees (user id's) of the activity as a list, will overwrite all
assignees
:type assignees_ids: list(basestring) or None
:param status: (optionally) edit the status of the activity as a string based
on :class:`~pykechain.enums.ActivityType`
:type status: basestring or None
:raises NotFoundError: if a `username` in the list of assignees is not in the list of scope members
:raises IllegalArgumentError: if the type of the inputs is not correct
:raises APIError: if another Error occurs
:warns: UserWarning - When a naive datetime is provided. Defaults to UTC.
Example
-------
>>> from datetime import datetime
>>> my_task = project.activity('Specify the wheel diameter')
>>> my_task.edit(name='Specify wheel diameter and circumference',
... description='The diameter and circumference are specified in inches',
... start_date=datetime.utcnow(), # naive time is interpreted as UTC time
... assignee='testuser')
If we want to provide timezone aware datetime objects we can use the 3rd party convenience library :mod:`pytz`.
Mind that we need to fetch the timezone first and use `<timezone>.localize(<your datetime>)` to make it
work correctly.
Using `datetime(2017,6,1,23,59,0 tzinfo=<tz>)` does NOT work for most timezones with a
daylight saving time. Check the `pytz <http://pythonhosted.org/pytz/#localized-times-and-date-arithmetic>`_
documentation.
To make it work using :mod:`pytz` and timezone aware :mod:`datetime` see the following example::
>>> import pytz
>>> start_date_tzaware = datetime.now(pytz.utc)
>>> mytimezone = pytz.timezone('Europe/Amsterdam')
>>> due_date_tzaware = mytimezone.localize(datetime(2019, 10, 27, 23, 59, 0))
>>> my_task.edit(due_date=due_date_tzaware, start_date=start_date_tzaware)
"""
update_dict = {'id': self.id}
if name:
if isinstance(name, (str, text_type)):
update_dict.update({'name': name})
self.name = name
else:
raise IllegalArgumentError('Name should be a string')
if description:
if isinstance(description, (str, text_type)):
update_dict.update({'description': description})
self.description = description
else:
raise IllegalArgumentError('Description should be a string')
if start_date:
if isinstance(start_date, datetime.datetime):
if not start_date.tzinfo:
warnings.warn("The startdate '{}' is naive and not timezone aware, use pytz.timezone info. "
"This date is interpreted as UTC time.".format(start_date.isoformat(sep=' ')))
update_dict.update({'start_date': start_date.isoformat(sep='T')})
else:
raise IllegalArgumentError('Start date should be a datetime.datetime() object')
if due_date:
if isinstance(due_date, datetime.datetime):
if not due_date.tzinfo:
warnings.warn("The duedate '{}' is naive and not timezone aware, use pytz.timezone info. "
"This date is interpreted as UTC time.".format(due_date.isoformat(sep=' ')))
update_dict.update({'due_date': due_date.isoformat(sep='T')})
else:
raise IllegalArgumentError('Due date should be a datetime.datetime() object')
if isinstance(assignees_ids, (list, tuple)) or isinstance(assignees, (list, tuple)):
update_assignees_ids = []
if isinstance(assignees_ids, (list, tuple)):
users = self._client.users()
update_assignees_ids = [u.id for u in users if u.id in assignees_ids]
if len(update_assignees_ids) != len(assignees_ids):
raise NotFoundError("All assignees should be a member of the project")
elif isinstance(assignees, (list, tuple)):
users = self._client.users()
update_assignees_ids = [u.id for u in users if u.username in assignees]
if len(update_assignees_ids) != len(assignees):
raise NotFoundError("All assignees should be a member of the project")
else:
raise IllegalArgumentError("Provide the usernames either as list of usernames of user id's")
if isinstance(update_assignees_ids, list):
project = self._client.scope(pk=self.scope_id, status=None)
member_ids_list = [member['id'] for member in project._json_data['members']]
for assignee_id in update_assignees_ids:
if assignee_id not in member_ids_list:
raise NotFoundError("Assignee '{}' should be a member of the project".format(assignee_id))
update_dict.update({'assignees_ids': update_assignees_ids})
elif assignees_ids or assignees:
raise IllegalArgumentError("If assignees_ids or assignees are provided, they should be a list or tuple")
if status:
if isinstance(status, (str, text_type)) and status in ActivityStatus.values():
update_dict.update({'status': status})
else:
raise IllegalArgumentError('Status should be a string and in the list of acceptable '
'status strings: {}'.format(ActivityStatus.values()))
url = self._client._build_url('activity', activity_id=self.id)
r = self._client._request('PUT', url, json=update_dict)
if r.status_code != requests.codes.ok: # pragma: no cover
raise APIError("Could not update Activity ({})".format(r))
self.refresh() |
java | public JsonResponse cancelBlast(Integer blastId) throws IOException {
Blast blast = new Blast();
Date d = null;
blast
.setBlastId(blastId)
.setScheduleTime(d);
return apiPost(blast);
} |
java | protected void updateAddedCount() {
SpiderScan sc = this.getSelectedScanner();
if (sc != null) {
this.getAddedCountValueLabel().setText(Integer.toString(sc.getNumberOfNodesAdded()));
} else {
this.getAddedCountValueLabel().setText(ZERO_REQUESTS_LABEL_TEXT);
}
} |
python | def create_without_data(cls, id_):
"""
根据 objectId 创建一个 leancloud.Object,代表一个服务器上已经存在的对象。可以调用 fetch 方法来获取服务器上的数据
:param id_: 对象的 objectId
:type id_: string_types
:return: 没有数据的对象
:rtype: Object
"""
if cls is Object:
raise RuntimeError('can not call create_without_data on leancloud.Object')
obj = cls()
obj.id = id_
return obj |
java | public <R> R forEach(def<R> func, int index) {
return forThose($.alwaysTrue(), func, index);
} |
python | def remove(self, key, glob=False):
"""Remove key value pair in a local or global namespace."""
ns = self.namespace(key, glob)
try:
self.keyring.delete_password(ns, key)
except PasswordDeleteError: # OSX and gnome have no delete method
self.set(key, '', glob) |
python | def add_basemap(ax, zoom=12):
"""
Adds map to a plot.
"""
url = ctx.sources.ST_TONER_LITE
xmin, xmax, ymin, ymax = ax.axis()
basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax,
zoom=zoom, url=url)
ax.imshow(basemap, extent=extent, interpolation='bilinear')
# restore original x/y limits
ax.axis((xmin, xmax, ymin, ymax)) |
python | def euclidean3d(v1, v2):
"""Faster implementation of euclidean distance for the 3D case."""
if not len(v1) == 3 and len(v2) == 3:
print("Vectors are not in 3D space. Returning None.")
return None
return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2) |
python | def text_to_data(self, text, elt, ps):
'''convert text into typecode specific data.
'''
if text is None:
return None
m = self.lex_pattern.match(text)
if not m:
raise EvaluateException('Bad Gregorian: %s' %text, ps.Backtrace(elt))
try:
retval = _dict_to_tuple(m.groupdict())
except ValueError, e:
#raise EvaluateException(str(e))
raise
if self.pyclass is not None:
return self.pyclass(retval)
return retval |
java | public static boolean isWorkplaceUri(URI uri) {
return (uri != null) && uri.getPath().startsWith(OpenCms.getSystemInfo().getWorkplaceContext());
} |
java | public final Collection<State> acceptStates() {
if(acceptStates == null) {
final Collection<State> states = this.states();
acceptStates =
DSUtil.filterColl(_acceptStates(),
new Predicate<State>() {
public boolean check(State state) {
return states.contains(state);
}
},
new LinkedHashSet<State>());
}
return acceptStates;
} |
python | def delete_stream(stream_name, region=None, key=None, keyid=None, profile=None):
'''
Delete the stream with name stream_name. This cannot be undone! All data will be lost!!
CLI example::
salt myminion boto_kinesis.delete_stream my_stream region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = _execute_with_retries(conn,
"delete_stream",
StreamName=stream_name)
if 'error' not in r:
r['result'] = True
return r |
python | def add_object(self, obj):
"""
Adds a RiakObject to the inputs.
:param obj: the object to add
:type obj: RiakObject
:rtype: :class:`RiakMapReduce`
"""
return self.add_bucket_key_data(obj._bucket._name, obj._key, None) |
java | @Deprecated
public StreamReadsRequest getStreamReadsRequest(String readGroupSetId) {
return StreamReadsRequest.newBuilder()
.setReadGroupSetId(readGroupSetId)
.setReferenceName(referenceName)
.setStart(start)
.setEnd(end)
.build();
} |
python | def _evaluate(self,z,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential
INPUT:
z
t
OUTPUT:
Pot(z,t;R)
HISTORY:
2010-07-13 - Written - Bovy (NYU)
"""
return self._Pot(self._R,z,phi=self._phi,t=t,use_physical=False)\
-self._Pot(self._R,0.,phi=self._phi,t=t,use_physical=False) |
python | def delete(self):
"""Delete this column family.
For example:
.. literalinclude:: snippets_table.py
:start-after: [START bigtable_delete_column_family]
:end-before: [END bigtable_delete_column_family]
"""
modification = table_admin_v2_pb2.ModifyColumnFamiliesRequest.Modification(
id=self.column_family_id, drop=True
)
client = self._table._instance._client
# data it contains are the GC rule and the column family ID already
# stored on this instance.
client.table_admin_client.modify_column_families(
self._table.name, [modification]
) |
java | private void setResourceInformation() {
String sitePath = m_cms.getSitePath(m_resource);
int pathEnd = sitePath.lastIndexOf('/') + 1;
String baseName = sitePath.substring(pathEnd);
m_sitepath = sitePath.substring(0, pathEnd);
switch (CmsMessageBundleEditorTypes.BundleType.toBundleType(
OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())) {
case PROPERTY:
String localeSuffix = CmsStringUtil.getLocaleSuffixForName(baseName);
if ((null != localeSuffix) && !localeSuffix.isEmpty()) {
baseName = baseName.substring(
0,
baseName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));
m_locale = CmsLocaleManager.getLocale(localeSuffix);
}
if ((null == m_locale) || !m_locales.contains(m_locale)) {
m_switchedLocaleOnOpening = true;
m_locale = m_locales.iterator().next();
}
break;
case XML:
m_locale = OpenCms.getLocaleManager().getBestAvailableLocaleForXmlContent(
m_cms,
m_resource,
m_xmlBundle);
break;
case DESCRIPTOR:
m_basename = baseName.substring(
0,
baseName.length() - CmsMessageBundleEditorTypes.Descriptor.POSTFIX.length());
m_locale = new Locale("en");
break;
default:
throw new IllegalArgumentException(
Messages.get().container(
Messages.ERR_UNSUPPORTED_BUNDLE_TYPE_1,
CmsMessageBundleEditorTypes.BundleType.toBundleType(
OpenCms.getResourceManager().getResourceType(m_resource).getTypeName())).toString());
}
m_basename = baseName;
} |
java | static List<String> getExecutableNames() {
List<String> executableNames = new ArrayList<>();
if (Platform.getCurrent().is(Platform.WINDOWS)) {
Collections.addAll(executableNames, ProcessNames.PHANTOMJS.getWindowsImageName(),
ProcessNames.CHROMEDRIVER.getWindowsImageName(), ProcessNames.IEDRIVER.getWindowsImageName(),
ProcessNames.EDGEDRIVER.getWindowsImageName(), ProcessNames.GECKODRIVER.getWindowsImageName());
} else {
Collections.addAll(executableNames, ProcessNames.PHANTOMJS.getUnixImageName(),
ProcessNames.CHROMEDRIVER.getUnixImageName(), ProcessNames.GECKODRIVER.getUnixImageName());
}
return executableNames;
} |
java | protected void setSuccessMessageInCookie(final HttpServletResponse response,
final String message) {
final Cookie cookie = new Cookie(AZKABAN_SUCCESS_MESSAGE, message);
cookie.setPath("/");
response.addCookie(cookie);
} |
java | static void encodeInteger(ByteBuffer source, int value, int n) {
int twoNminus1 = PREFIX_TABLE[n];
int pos = source.position() - 1;
if (value < twoNminus1) {
source.put(pos, (byte) (source.get(pos) | value));
} else {
source.put(pos, (byte) (source.get(pos) | twoNminus1));
value = value - twoNminus1;
while (value >= 128) {
source.put((byte) (value % 128 + 128));
value = value / 128;
}
source.put((byte) value);
}
} |
java | public static double conditionP(DMatrixRMaj A , double p )
{
if( p == 2 ) {
return conditionP2(A);
} else if( A.numRows == A.numCols ){
// square matrices are the typical case
DMatrixRMaj A_inv = new DMatrixRMaj(A.numRows,A.numCols);
if( !CommonOps_DDRM.invert(A,A_inv) )
throw new IllegalArgumentException("A can't be inverted.");
return normP(A,p) * normP(A_inv,p);
} else {
DMatrixRMaj pinv = new DMatrixRMaj(A.numCols,A.numRows);
CommonOps_DDRM.pinv(A,pinv);
return normP(A,p) * normP(pinv,p);
}
} |
python | def bootstrap_modulator(self, protocol: ProtocolAnalyzer):
"""
Set initial parameters for default modulator if it was not edited by user previously
:return:
"""
if len(self.modulators) != 1 or len(self.table_model.protocol.messages) == 0:
return
modulator = self.modulators[0]
modulator.samples_per_bit = protocol.messages[0].bit_len
if protocol.signal:
modulator.sample_rate = protocol.signal.sample_rate
modulator.modulation_type = protocol.signal.modulation_type
auto_freq = modulator.estimate_carrier_frequency(protocol.signal, protocol)
if auto_freq is not None and auto_freq != 0:
modulator.carrier_freq_hz = auto_freq
self.show_modulation_info() |
java | public static SessionProvider createAnonimProvider()
{
Identity id = new Identity(IdentityConstants.ANONIM, new HashSet<MembershipEntry>());
return new SessionProvider(new ConversationState(id));
} |
java | public static Field[] getFields(Class<?> clazz, String... fieldNames) {
return WhiteboxImpl.getFields(clazz, fieldNames);
} |
java | protected void handleUndefinedMode(CliOptionContainer option) {
CliStyle style = this.cliState.getCliStyle();
CliStyleHandling handling = style.modeUndefined();
if (handling != CliStyleHandling.OK) {
ObjectNotFoundException exception = new ObjectNotFoundException(CliMode.class, option.getOption().mode());
handling.handle(getLogger(), exception);
}
} |
python | def unpack_value(self, tup_tree):
"""
Find VALUE or VALUE.ARRAY under tup_tree and convert to a Python value.
Looks at the TYPE of the node to work out how to decode it.
Handles nodes with no value (e.g. when representing NULL by omitting
VALUE)
"""
valtype = attrs(tup_tree)['TYPE']
raw_val = self.list_of_matching(tup_tree, ('VALUE', 'VALUE.ARRAY'))
if not raw_val:
return None
if len(raw_val) > 1:
raise CIMXMLParseError(
_format("Element {0!A} has too many child elements {1!A} "
"(allowed is one of 'VALUE' or 'VALUE.ARRAY')",
name(tup_tree)),
conn_id=self.conn_id)
raw_val = raw_val[0]
if type(raw_val) == list: # pylint: disable=unidiomatic-typecheck
return [self.unpack_single_value(data, valtype)
for data in raw_val]
return self.unpack_single_value(raw_val, valtype) |
java | public static double[] minusEquals(final double[] v1, final double[] v2) {
assert v1.length == v2.length : ERR_VEC_DIMENSIONS;
for(int i = 0; i < v1.length; i++) {
v1[i] -= v2[i];
}
return v1;
} |
java | public void parse(DefaultHandler dh, File f) throws SAXException, ParserConfigurationException, IOException {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(dh);
xr.parse(new InputSource(new FileInputStream(f)));
} |
python | def time_seconds(tc_array, year):
"""Return the time object from the timecodes
"""
tc_array = np.array(tc_array, copy=True)
word = tc_array[:, 0]
day = word >> 1
word = tc_array[:, 1].astype(np.uint64)
msecs = ((127) & word) * 1024
word = tc_array[:, 2]
msecs += word & 1023
msecs *= 1024
word = tc_array[:, 3]
msecs += word & 1023
return (np.datetime64(
str(year) + '-01-01T00:00:00Z', 's') +
msecs[:].astype('timedelta64[ms]') +
(day - 1)[:].astype('timedelta64[D]')) |
python | def first(self, default=None, as_dict=False, as_ordereddict=False):
"""Returns a single record for the RecordCollection, or `default`. If
`default` is an instance or subclass of Exception, then raise it
instead of returning it."""
# Try to get a record, or return/raise default.
try:
record = self[0]
except IndexError:
if isexception(default):
raise default
return default
# Cast and return.
if as_dict:
return record.as_dict()
elif as_ordereddict:
return record.as_dict(ordered=True)
else:
return record |
python | def _load_json_module():
"""Try to load a valid json module.
There are more than one json modules that might be installed. They are
mostly compatible with one another but some versions may be different.
This function attempts to load various json modules in a preferred order.
It does a basic check to guess if a loaded version of json is compatible.
Returns:
Compatible json module.
Raises:
ImportError if there are no json modules or the loaded json module is
not compatible with ProtoRPC.
"""
first_import_error = None
for module_name in ['json',
'simplejson']:
try:
module = __import__(module_name, {}, {}, 'json')
if not hasattr(module, 'JSONEncoder'):
message = (
'json library "%s" is not compatible with ProtoRPC' %
module_name)
logging.warning(message)
raise ImportError(message)
else:
return module
except ImportError as err:
if not first_import_error:
first_import_error = err
logging.error('Must use valid json library (json or simplejson)')
raise first_import_error |
python | def set_sort_cb(self, w, index):
"""This callback is invoked when the user selects a new sort order
from the preferences pane."""
name = self.sort_options[index]
self.t_.set(sort_order=name) |
java | public Observable<Void> beginStopAsync(String groupName, String serviceName) {
return beginStopWithServiceResponseAsync(groupName, serviceName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} |
python | def _set_main_widget(self, widget, redraw):
"""
add provided widget to widget list and display it
:param widget:
:return:
"""
self.set_body(widget)
self.reload_footer()
if redraw:
logger.debug("redraw main widget")
self.refresh() |
java | public void arcTo(double x1, double y1, double x2, double y2, double radius) {
this.gc.arcTo(
doc2fxX(x1), doc2fxY(y1),
doc2fxX(x2), doc2fxY(y2),
doc2fxSize(radius));
} |
java | public static List<String> getTextfileFromUrl(String _url, Charset _charset) {
return getTextfileFromUrl(_url, _charset, false);
} |
python | def partition_query(
self,
session,
sql,
transaction=None,
params=None,
param_types=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates a set of partition tokens that can be used to execute a query
operation in parallel. Each of the returned partition tokens can be used
by ``ExecuteStreamingSql`` to specify a subset of the query result to
read. The same session and read-only transaction must be used by the
PartitionQueryRequest used to create the partition tokens and the
ExecuteSqlRequests that use the partition tokens.
Partition tokens become invalid when the session used to create them is
deleted, is idle for too long, begins a new transaction, or becomes too
old. When any of these happen, it is not possible to resume the query,
and the whole operation must be restarted from the beginning.
Example:
>>> from google.cloud import spanner_v1
>>>
>>> client = spanner_v1.SpannerClient()
>>>
>>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]')
>>>
>>> # TODO: Initialize `sql`:
>>> sql = ''
>>>
>>> response = client.partition_query(session, sql)
Args:
session (str): Required. The session used to create the partitions.
sql (str): The query request to generate partitions for. The request will fail if
the query is not root partitionable. The query plan of a root
partitionable query has a single distributed union operator. A
distributed union operator conceptually divides one or more tables into
multiple splits, remotely evaluates a subquery independently on each
split, and then unions all results.
This must not contain DML commands, such as INSERT, UPDATE, or DELETE.
Use ``ExecuteStreamingSql`` with a PartitionedDml transaction for large,
partition-friendly DML operations.
transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): Read only snapshot transactions are supported, read/write and single use
transactions are not.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.TransactionSelector`
params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter
placeholder consists of ``'@'`` followed by the parameter name.
Parameter names consist of any combination of letters, numbers, and
underscores.
Parameters can appear anywhere that a literal value is expected. The
same parameter name can be used more than once, for example:
``"WHERE id > @msg_id AND id < @msg_id + 100"``
It is an error to execute an SQL query with unbound parameters.
Parameter values are specified using ``params``, which is a JSON object
whose keys are parameter names, and whose values are the corresponding
parameter values.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Struct`
param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type
from a JSON value. For example, values of type ``BYTES`` and values of
type ``STRING`` both appear in ``params`` as JSON strings.
In these cases, ``param_types`` can be used to specify the exact SQL
type for some or all of the SQL query parameters. See the definition of
``Type`` for more information about SQL types.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.Type`
partition_options (Union[dict, ~google.cloud.spanner_v1.types.PartitionOptions]): Additional options that affect how many partitions are created.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.spanner_v1.types.PartitionOptions`
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.spanner_v1.types.PartitionResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "partition_query" not in self._inner_api_calls:
self._inner_api_calls[
"partition_query"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.partition_query,
default_retry=self._method_configs["PartitionQuery"].retry,
default_timeout=self._method_configs["PartitionQuery"].timeout,
client_info=self._client_info,
)
request = spanner_pb2.PartitionQueryRequest(
session=session,
sql=sql,
transaction=transaction,
params=params,
param_types=param_types,
partition_options=partition_options,
)
if metadata is None:
metadata = []
metadata = list(metadata)
try:
routing_header = [("session", session)]
except AttributeError:
pass
else:
routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
routing_header
)
metadata.append(routing_metadata)
return self._inner_api_calls["partition_query"](
request, retry=retry, timeout=timeout, metadata=metadata
) |
python | def receive_nack(self, msg):
'''
Returns a new Prepare message if the number of Nacks received reaches
a quorum.
'''
self.observe_proposal(msg.promised_proposal_id)
if msg.proposal_id == self.proposal_id and self.nacks_received is not None:
self.nacks_received.add(msg.from_uid)
if len(self.nacks_received) == self.quorum_size:
return self.prepare() |
java | public static String getSubstitutedProperty( String value,
PropertyAccessor propertyAccessor ) {
if (value == null || value.trim().length() == 0) return value;
StringBuilder sb = new StringBuilder(value);
// Get the index of the first constant, if any
int startName = sb.indexOf(CURLY_PREFIX);
if (startName == -1) return value;
// process as many different variable groupings that are defined, where one group will resolve to one property
// substitution
while (startName != -1) {
String defaultValue = null;
int endName = sb.indexOf(CURLY_SUFFIX, startName);
if (endName == -1) {
// if no suffix can be found, then this variable was probably defined incorrectly
// but return what there is at this point
return sb.toString();
}
String varString = sb.substring(startName + 2, endName);
if (varString.indexOf(DEFAULT_DELIM) > -1) {
List<String> defaults = split(varString, DEFAULT_DELIM);
// get the property(s) variables that are defined left of the default delimiter.
varString = defaults.get(0);
// if the default is defined, then capture in case none of the other properties are found
if (defaults.size() == 2) {
defaultValue = defaults.get(1);
}
}
String constValue = null;
// split the property(s) based VAR_DELIM, when multiple property options are defined
List<String> vars = split(varString, VAR_DELIM);
for (final String var : vars) {
constValue = System.getenv(var);
if (constValue == null) {
constValue = propertyAccessor.getProperty(var);
}
// the first found property is the value to be substituted
if (constValue != null) {
break;
}
}
// if no property is found to substitute, then use the default value, if defined
if (constValue == null && defaultValue != null) {
constValue = defaultValue;
}
if (constValue != null) {
sb = sb.replace(startName, endName + 1, constValue);
// Checking for another constants
startName = sb.indexOf(CURLY_PREFIX);
} else {
// continue to try to substitute for other properties so that all defined variables
// are tried to be substituted for
startName = sb.indexOf(CURLY_PREFIX, endName);
}
}
return sb.toString();
} |
java | @NullSafe
public static boolean isWhole(Number value) {
return (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long
|| value instanceof BigInteger);
} |
java | public static String getResponseHeadersOutput(Response response) {
if (response == null) {
return "";
}
StringBuilder responseHeaders = new StringBuilder();
String uuid = getUUID();
responseHeaders.append(ONCLICK_TOGGLE).append(uuid).append("\")'>Toggle Headers</a> ");
responseHeaders.append(SPAN_ID).append(uuid).append(DISPLAY_NONE);
responseHeaders.append(formatKeyPair(response.getHeaders()));
responseHeaders.append(END_SPAN);
return responseHeaders.toString();
} |
python | def install_cmd(argv):
'''Use Pythonz to download and build the specified Python version'''
installer = InstallCommand()
options, versions = installer.parser.parse_args(argv)
if len(versions) != 1:
installer.parser.print_help()
sys.exit(1)
else:
try:
actual_installer = PythonInstaller.get_installer(versions[0], options)
return actual_installer.install()
except AlreadyInstalledError as e:
print(e) |
java | public String readLongUTF() throws IOException {
int length = readCompressedInt();
StringBuilder SB = new StringBuilder(length);
for(int position = 0; position<length; position+=20480) {
int expectedLen = length - position;
if(expectedLen>20480) expectedLen = 20480;
String block = readUTF();
if(block.length()!=expectedLen) throw new IOException("Block has unexpected length: expected "+expectedLen+", got "+block.length());
SB.append(block);
}
if(SB.length()!=length) throw new IOException("StringBuilder has unexpected length: expected "+length+", got "+SB.length());
return SB.toString();
} |
python | def upload_gallery_photo(self, gallery_id, source_amigo_id, file_obj,
chunk_size=CHUNK_SIZE, force_chunked=False,
metadata=None):
"""
Upload a photo to a dataset's gallery.
"""
simple_upload_url = 'related_tables/%s/upload' % gallery_id
chunked_upload_url = 'related_tables/%s/chunked_upload' % gallery_id
data = {'source_amigo_id': source_amigo_id}
if isinstance(file_obj, basestring):
data['filename'] = os.path.basename(file_obj)
else:
data['filename'] = os.path.basename(file_obj.name)
if metadata:
data.update(metadata)
return self.upload_file(simple_upload_url, chunked_upload_url,
file_obj, chunk_size=chunk_size,
force_chunked=force_chunked, extra_data=data) |
java | ServerHeartbeat createServer(String serverId)
{
int p = serverId.indexOf(':');
String address = serverId.substring(0, p);
int port = Integer.parseInt(serverId.substring(p + 1));
boolean isSSL = false;
return _heartbeatService.createServer(address, port, isSSL);
} |
python | def fill_empty_slots(self, items):
"""Append dicts to the items passed in for those slots that don't have
any analysis assigned but the row needs to be rendered still.
:param items: dictionary with the items to be rendered in the list
"""
for pos in self.get_empty_slots():
item = {
"obj": self.context,
"id": self.context.id,
"uid": self.context.UID(),
"title": self.context.Title(),
"type_class": "blank-worksheet-row",
"url": self.context.absolute_url(),
"relative_url": self.context.absolute_url(),
"view_url": self.context.absolute_url(),
"path": "/".join(self.context.getPhysicalPath()),
"before": {},
"after": {},
"replace": {
"Pos": "<span class='badge'>{}</span> {}".format(
pos, _("Reassignable Slot"))
},
"choices": {},
"class": {},
"state_class": "state-empty",
"allow_edit": [],
"Pos": pos,
"pos_sortkey": "{:010}:{:010}".format(pos, 1),
"Service": "",
"Attachments": "",
"state_title": "",
"disabled": True,
}
items.append(item) |
python | def sequence_to_graph(G, seq, color='black'):
"""
Automatically construct graph given a sequence of characters.
"""
for x in seq:
if x.endswith("_1"): # Mutation
G.node(x, color=color, width="0.1", shape="circle", label="")
else:
G.node(x, color=color)
for a, b in pairwise(seq):
G.edge(a, b, color=color) |
java | public void setErrorTime(com.google.api.ads.admanager.axis.v201805.DateTime errorTime) {
this.errorTime = errorTime;
} |
java | public static void showErrorDialog(Throwable t, Runnable onClose) {
showErrorDialog(t.getLocalizedMessage(), t, onClose);
} |
java | public Observable<ManagementLockObjectInner> getAtResourceLevelAsync(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String lockName) {
return getAtResourceLevelWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, lockName).map(new Func1<ServiceResponse<ManagementLockObjectInner>, ManagementLockObjectInner>() {
@Override
public ManagementLockObjectInner call(ServiceResponse<ManagementLockObjectInner> response) {
return response.body();
}
});
} |
java | public Collection<Monitor> list(String name, String type, int offset, int limit)
{
List<Monitor> ret = new ArrayList<Monitor>();
Collection<Monitor> monitors = list(offset, limit);
for(Monitor monitor : monitors)
{
if((name == null || monitor.getName().toLowerCase().indexOf(name) != -1)
&& (type == null || monitor.getType().equals(type)))
{
ret.add(monitor);
}
}
return ret;
} |
python | def _parse_udf_vol_descs(self, extent, length, descs):
# type: (int, int, PyCdlib._UDFDescriptors) -> None
'''
An internal method to parse a set of UDF Volume Descriptors.
Parameters:
extent - The extent at which to start parsing.
length - The number of bytes to read from the incoming ISO.
descs - The _UDFDescriptors object to store parsed objects into.
Returns:
Nothing.
'''
# Read in the Volume Descriptor Sequence
self._seek_to_extent(extent)
vd_data = self._cdfp.read(length)
# And parse it. Since the sequence doesn't have to be in any set order,
# and since some of the entries may be missing, we parse the Descriptor
# Tag (the first 16 bytes) to find out what kind of descriptor it is,
# then construct the correct type based on that. We keep going until we
# see a Terminating Descriptor.
block_size = self.pvd.logical_block_size()
offset = 0
current_extent = extent
done = False
while not done:
desc_tag = udfmod.UDFTag()
desc_tag.parse(vd_data[offset:], current_extent)
if desc_tag.tag_ident == 1:
descs.pvd.parse(vd_data[offset:offset + 512], current_extent, desc_tag)
elif desc_tag.tag_ident == 4:
descs.impl_use.parse(vd_data[offset:offset + 512], current_extent, desc_tag)
elif desc_tag.tag_ident == 5:
descs.partition.parse(vd_data[offset:offset + 512], current_extent, desc_tag)
elif desc_tag.tag_ident == 6:
descs.logical_volume.parse(vd_data[offset:offset + 512], current_extent, desc_tag)
elif desc_tag.tag_ident == 7:
descs.unallocated_space.parse(vd_data[offset:offset + 512], current_extent, desc_tag)
elif desc_tag.tag_ident == 8:
descs.terminator.parse(current_extent, desc_tag)
done = True
else:
raise pycdlibexception.PyCdlibInvalidISO('UDF Tag identifier not %d' % (desc_tag.tag_ident))
offset += block_size
current_extent += 1 |
python | def find_favorite_videos_by_username(self, user_name,
orderby='favorite-time',
page=1, count=20):
"""doc: http://open.youku.com/docs/doc?id=54
"""
url = 'https://openapi.youku.com/v2/videos/favorite/by_user.json'
params = {
'client_id': self.client_id,
'user_name': user_name,
'orderby': orderby,
'page': page,
'count': count
}
r = requests.get(url, params=params)
check_error(r)
return r.json() |
java | public static Matrix zero(int rows, int columns) {
long size = (long) rows * columns;
return size > 1000 ? SparseMatrix.zero(rows, columns) : DenseMatrix.zero(rows, columns);
} |
java | protected static void assertion(boolean b, String msg)
{
if(!b)
{
throw new RuntimeException(XSLMessages.createMessage(XSLTErrorResources.ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR, new Object[]{msg}));
// "Programmer's assertion in RundundentExprEliminator: "+msg);
}
} |
java | public synchronized EventScope<T> register(final Class<? extends T> eventClass, final Object receiver,
final Pattern namePattern) {
final Method method = this.detectReceiverMethod(receiver, eventClass, namePattern);
this.registerInternal(receiver, method, eventClass);
return this;
} |
java | public void sendWithBulkProcessor(Map<String, ?> source, String index,
String type, String id) {
sendWithBulkProcessor(
buildIndexRequest(index, type, id).source(source));
} |
python | def get_securitygroup(vm_):
'''
Return the security group
'''
sgs = list_securitygroup()
securitygroup = config.get_cloud_config_value(
'securitygroup', vm_, __opts__, search_global=False
)
if not securitygroup:
raise SaltCloudNotFound('No securitygroup ID specified for this VM.')
if securitygroup and six.text_type(securitygroup) in sgs:
return sgs[securitygroup]['SecurityGroupId']
raise SaltCloudNotFound(
'The specified security group, \'{0}\', could not be found.'.format(
securitygroup)
) |
java | protected void open(int remoteid, long remotewindow, int remotepacket)
throws IOException {
this.remoteid = remoteid;
this.remotewindow = new DataWindow(remotewindow, remotepacket);
this.state = CHANNEL_OPEN;
synchronized (listeners) {
for (Enumeration<ChannelEventListener> e = listeners.elements(); e
.hasMoreElements();) {
(e.nextElement()).channelOpened(this);
}
}
} |
python | def equalizer(self, frequency, q=1.0, db=-3.0):
"""equalizer takes three parameters: filter center frequency in Hz, "q"
or band-width (default=1.0), and a signed number for gain or
attenuation in dB.
Beware of clipping when using positive gain.
"""
self.command.append('equalizer')
self.command.append(frequency)
self.command.append(str(q) + 'q')
self.command.append(db)
return self |
python | def _concat_compat(to_concat, axis=0):
"""
provide concatenation of an array of arrays each of which is a single
'normalized' dtypes (in that for example, if it's object, then it is a
non-datetimelike and provide a combined dtype for the resulting array that
preserves the overall dtype if possible)
Parameters
----------
to_concat : array of arrays
axis : axis to provide concatenation
Returns
-------
a single array, preserving the combined dtypes
"""
# filter empty arrays
# 1-d dtypes always are included here
def is_nonempty(x):
try:
return x.shape[axis] > 0
except Exception:
return True
# If all arrays are empty, there's nothing to convert, just short-cut to
# the concatenation, #3121.
#
# Creating an empty array directly is tempting, but the winnings would be
# marginal given that it would still require shape & dtype calculation and
# np.concatenate which has them both implemented is compiled.
typs = get_dtype_kinds(to_concat)
_contains_datetime = any(typ.startswith('datetime') for typ in typs)
_contains_period = any(typ.startswith('period') for typ in typs)
if 'category' in typs:
# this must be priort to _concat_datetime,
# to support Categorical + datetime-like
return _concat_categorical(to_concat, axis=axis)
elif _contains_datetime or 'timedelta' in typs or _contains_period:
return _concat_datetime(to_concat, axis=axis, typs=typs)
# these are mandated to handle empties as well
elif 'sparse' in typs:
return _concat_sparse(to_concat, axis=axis, typs=typs)
all_empty = all(not is_nonempty(x) for x in to_concat)
if any(is_extension_array_dtype(x) for x in to_concat) and axis == 1:
to_concat = [np.atleast_2d(x.astype('object')) for x in to_concat]
if all_empty:
# we have all empties, but may need to coerce the result dtype to
# object if we have non-numeric type operands (numpy would otherwise
# cast this to float)
typs = get_dtype_kinds(to_concat)
if len(typs) != 1:
if (not len(typs - {'i', 'u', 'f'}) or
not len(typs - {'bool', 'i', 'u'})):
# let numpy coerce
pass
else:
# coerce to object
to_concat = [x.astype('object') for x in to_concat]
return np.concatenate(to_concat, axis=axis) |
python | def current_task(self, args):
"""Name of current action for progress-bar output.
The specific task string is depends on the configuration via `args`.
Returns
-------
ctask : str
String representation of this task.
"""
ctask = self.nice_name if self.nice_name is not None else self.name
if args is not None:
if args.update:
ctask = ctask.replace('%pre', 'Updating')
else:
ctask = ctask.replace('%pre', 'Loading')
return ctask |
python | def tryCComment(self, block):
"""C comment checking. If the previous line begins with a "/*" or a "* ", then
return its leading white spaces + ' *' + the white spaces after the *
return: filler string or null, if not in a C comment
"""
indentation = None
prevNonEmptyBlock = self._prevNonEmptyBlock(block)
if not prevNonEmptyBlock.isValid():
return None
prevNonEmptyBlockText = prevNonEmptyBlock.text()
if prevNonEmptyBlockText.endswith('*/'):
try:
foundBlock, notUsedColumn = self.findTextBackward(prevNonEmptyBlock, prevNonEmptyBlock.length(), '/*')
except ValueError:
foundBlock = None
if foundBlock is not None:
dbg("tryCComment: success (1) in line %d" % foundBlock.blockNumber())
return self._lineIndent(foundBlock.text())
if prevNonEmptyBlock != block.previous():
# inbetween was an empty line, so do not copy the "*" character
return None
blockTextStripped = block.text().strip()
prevBlockTextStripped = prevNonEmptyBlockText.strip()
if prevBlockTextStripped.startswith('/*') and not '*/' in prevBlockTextStripped:
indentation = self._blockIndent(prevNonEmptyBlock)
if CFG_AUTO_INSERT_STAR:
# only add '*', if there is none yet.
indentation += ' '
if not blockTextStripped.endswith('*'):
indentation += '*'
secondCharIsSpace = len(blockTextStripped) > 1 and blockTextStripped[1].isspace()
if not secondCharIsSpace and \
not blockTextStripped.endswith("*/"):
indentation += ' '
dbg("tryCComment: success (2) in line %d" % block.blockNumber())
return indentation
elif prevBlockTextStripped.startswith('*') and \
(len(prevBlockTextStripped) == 1 or prevBlockTextStripped[1].isspace()):
# in theory, we could search for opening /*, and use its indentation
# and then one alignment character. Let's not do this for now, though.
indentation = self._lineIndent(prevNonEmptyBlockText)
# only add '*', if there is none yet.
if CFG_AUTO_INSERT_STAR and not blockTextStripped.startswith('*'):
indentation += '*'
if len(blockTextStripped) < 2 or not blockTextStripped[1].isspace():
indentation += ' '
dbg("tryCComment: success (2) in line %d" % block.blockNumber())
return indentation
return None |
python | def laser_hook(self, hook_type: str) -> Callable:
"""Registers the annotated function with register_laser_hooks
:param hook_type:
:return: hook decorator
"""
def hook_decorator(func: Callable):
""" Hook decorator generated by laser_hook
:param func: Decorated function
"""
self.register_laser_hooks(hook_type, func)
return func
return hook_decorator |
java | static ConnectionInfo newForwardedConnectionInfo(HttpRequest request, Channel channel) {
if (request.headers().contains(FORWARDED_HEADER)) {
return parseForwardedInfo(request, (SocketChannel)channel);
}
else {
return parseXForwardedInfo(request, (SocketChannel)channel);
}
} |
python | def _make_random_string(length):
"""Returns a random lowercase, uppercase, alphanumerical string.
:param int length: The length in bytes of the string to generate.
"""
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
return ''.join(random.choice(chars) for x in range(length)) |
java | public void createAgent(String agent_name, String path) {
IComponentIdentifier agent = cmsService.createComponent(agent_name,
path, null, null).get(new ThreadSuspendable());
createdAgents.put(agent_name, agent);
} |
python | def bind(self):
"""Attempts to bind to the LDAP server using the credentials of the
service account.
:return: Bound LDAP connection object if successful or ``None`` if
unsuccessful.
"""
conn = self.initialize
try:
conn.simple_bind_s(
current_app.config['LDAP_USERNAME'],
current_app.config['LDAP_PASSWORD'])
return conn
except ldap.LDAPError as e:
raise LDAPException(self.error(e.args)) |
python | def get_facet_serializer_class(self):
"""
Return the class to use for serializing facets.
Defaults to using ``self.facet_serializer_class``.
"""
if self.facet_serializer_class is None:
raise AttributeError(
"%(cls)s should either include a `facet_serializer_class` attribute, "
"or override %(cls)s.get_facet_serializer_class() method." %
{"cls": self.__class__.__name__}
)
return self.facet_serializer_class |
java | public ContinueUpdateRollbackRequest withResourcesToSkip(String... resourcesToSkip) {
if (this.resourcesToSkip == null) {
setResourcesToSkip(new com.amazonaws.internal.SdkInternalList<String>(resourcesToSkip.length));
}
for (String ele : resourcesToSkip) {
this.resourcesToSkip.add(ele);
}
return this;
} |
python | def get_colours(color_group, color_name, reverse=False):
color_group = color_group.lower()
cmap = get_map(color_group, color_name, reverse=reverse)
return cmap.hex_colors
"""
if not reverse:
return cmap.hex_colors
else:
return cmap.hex_colors[::-1]
""" |
python | def upvotes(self, option):
"""
Set whether to filter by a user's upvoted list. Options available are
user.ONLY, user.NOT, and None; default is None.
"""
params = join_params(self.parameters, {"upvotes": option})
return self.__class__(**params) |
python | def as_yaml(self):
"""
Render the YAML node and subnodes as string.
"""
dumped = dump(self.as_marked_up(), Dumper=StrictYAMLDumper, allow_unicode=True)
return dumped if sys.version_info[0] == 3 else dumped.decode("utf8") |
python | def crude_search_scicrunch_via_label(self, label:str) -> dict:
""" Server returns anything that is simlar in any catagory """
url = self.base_url + 'term/search/{term}?key={api_key}'.format(
term = label,
api_key = self.api_key,
)
return self.get(url) |
java | protected JRDesignChart createChart(DJChart djChart) {
JRDesignGroup jrGroupChart = getJRGroupFromDJGroup(djChart.getColumnsGroup());
JRDesignChart chart = new JRDesignChart(new JRDesignStyle().getDefaultStyleProvider(), djChart.getType());
JRDesignGroup parentGroup = getParent(jrGroupChart);
List<JRDesignVariable> chartVariables = registerChartVariable(djChart);
JRDesignChartDataset chartDataset = DataSetFactory.getDataset(djChart, jrGroupChart, parentGroup, chartVariables);
chart.setDataset(chartDataset);
interpeterOptions(djChart, chart);
chart.setEvaluationTime(EvaluationTimeEnum.GROUP);
chart.setEvaluationGroup(jrGroupChart);
return chart;
} |
python | def _get_location_descriptor(self, location):
"""
Get corresponding :class:`LocationDescriptor` object from a string or a :class:`LocationDescriptor` itself.
Args:
location: a string or a :class:`LocationDescriptor`.
Returns:
A corresponding :class:`LocationDescriptor` object. If ``location`` is a :class:`LocationDescriptor`,
we simply return it.
Raises:
A ``RuntimeError`` is raised whenever the `location` object is not recognized a string or :class:`self._nbr_of_nodes`.
"""
loc_descriptor = None
if isinstance(location, basestring):
loc_descriptor = LocationDescriptor(location)
elif isinstance(location, LocationDescriptor):
loc_descriptor = location
else:
raise RuntimeError("Argument is neither a string nor a self._nbr_of_nodes")
return loc_descriptor |
java | public static boolean isGroundTerm(Term term) {
if (term instanceof Function) {
return ((Function)term).getVariables().isEmpty();
}
return term instanceof Constant;
} |
python | def make_diffuse_comp_info(self, merged_name, galkey):
""" Make the information about a single merged component
Parameters
----------
merged_name : str
The name of the merged component
galkey : str
A short key identifying the galprop parameters
Returns `Model_component.ModelComponentInfo`
"""
kwargs = dict(source_name=merged_name,
source_ver=galkey,
model_type='MapCubeSource',
Spatial_Filename=self.make_merged_name(
merged_name, galkey, fullpath=True),
srcmdl_name=self.make_xml_name(merged_name, galkey, fullpath=True))
return MapCubeComponentInfo(**kwargs) |
python | def from_frames(self, path):
"""
Read from frames
"""
frames_path = sorted([os.path.join(path, x) for x in os.listdir(path)])
frames = [ndimage.imread(frame_path) for frame_path in frames_path]
self.handle_type(frames)
return self |
python | def find_pareto_front(population):
"""Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals
"""
pareto_front = set(range(len(population)))
for i in range(len(population)):
if i not in pareto_front:
continue
ind1 = population[i]
for j in range(i + 1, len(population)):
ind2 = population[j]
# if individuals are equal on all objectives, mark one of them (the first encountered one) as dominated
# to prevent excessive growth of the Pareto front
if ind2.fitness.dominates(ind1.fitness) or ind1.fitness == ind2.fitness:
pareto_front.discard(i)
if ind1.fitness.dominates(ind2.fitness):
pareto_front.discard(j)
return pareto_front |
python | def merge_inner(clsdict):
"""
Merge the inner class(es) of a class:
e.g class A { ... } class A$foo{ ... } class A$bar{ ... }
==> class A { class foo{...} class bar{...} ... }
"""
samelist = False
done = {}
while not samelist:
samelist = True
classlist = list(clsdict.keys())
for classname in classlist:
parts_name = classname.rsplit('$', 1)
if len(parts_name) > 1:
mainclass, innerclass = parts_name
innerclass = innerclass[:-1] # remove ';' of the name
mainclass += ';'
if mainclass in clsdict:
clsdict[mainclass].add_subclass(innerclass,
clsdict[classname])
clsdict[classname].name = innerclass
done[classname] = clsdict[classname]
del clsdict[classname]
samelist = False
elif mainclass in done:
cls = done[mainclass]
cls.add_subclass(innerclass, clsdict[classname])
clsdict[classname].name = innerclass
done[classname] = done[mainclass]
del clsdict[classname]
samelist = False |
python | def _set_char(self, char, type):
'''
Sets the currently active character, e.g. ト. We save some information
about the character as well. active_char_info contains the full
tuple of rōmaji info, and active_ro_vowel contains e.g. 'o' for ト.
We also set the character type: either a consonant-vowel pair
or a vowel. This affects the way the character is flushed later.
'''
self.next_char_info = self._char_lookup(char)
self.next_char_type = type
self._flush_char()
self.active_char = char
self.active_char_type = type
self.active_char_info = self._char_lookup(char)
self.active_vowel_ro = self._char_ro_vowel(self.active_char_info, type) |
java | @Override
public Token retrieveToken() {
log.debug("DefaultTokenProvider retrieveToken()");
try {
SSLContext sslContext;
/*
* If SSL cert checking for endpoints has been explicitly disabled,
* register a new scheme for HTTPS that won't cause self-signed
* certs to error out.
*/
if (SDKGlobalConfiguration.isCertCheckingDisabled()) {
if (log.isWarnEnabled()) {
log.warn("SSL Certificate checking for endpoints has been " + "explicitly disabled.");
}
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new TrustingX509TrustManager() }, null);
} else {
sslContext = SSLContexts.createDefault();
}
SSLConnectionSocketFactory sslsf = new SdkTLSSocketFactory(sslContext, new DefaultHostnameVerifier());
HttpClientBuilder builder = HttpClientBuilder.create();
if (httpClientSettings != null){
DefaultTokenManager.addProxyConfig(builder, httpClientSettings);
}
HttpClient client = builder.setSSLSocketFactory(sslsf).build();
HttpPost post = new HttpPost(iamEndpoint);
post.setHeader("Authorization", BASIC_AUTH);
post.setHeader("Content-Type", CONTENT_TYPE);
post.setHeader("Accept", ACCEPT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
urlParameters.add(new BasicNameValuePair("response_type", RESPONSE_TYPE));
urlParameters.add(new BasicNameValuePair("apikey", apiKey));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
final HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != 200) {
log.info("Response code= " + response.getStatusLine().getStatusCode()
+ ", Reason= " + response.getStatusLine().getReasonPhrase()
+ ".Throwing OAuthServiceException");
OAuthServiceException exception = new OAuthServiceException("Token retrieval from IAM service failed");
exception.setStatusCode(response.getStatusLine().getStatusCode());
exception.setStatusMessage(response.getStatusLine().getReasonPhrase());
throw exception;
}
final HttpEntity entity = response.getEntity();
final String resultStr = EntityUtils.toString(entity);
final ObjectMapper mapper = new ObjectMapper();
final Token token = mapper.readValue(resultStr, Token.class);
return token;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
} |
java | public DescribeEndpointsResult withEndpoints(Endpoint... endpoints) {
if (this.endpoints == null) {
setEndpoints(new java.util.ArrayList<Endpoint>(endpoints.length));
}
for (Endpoint ele : endpoints) {
this.endpoints.add(ele);
}
return this;
} |
java | public double[] getBasisVector( int which ) {
if( which < 0 || which >= numComponents )
throw new IllegalArgumentException("Invalid component");
DMatrixRMaj v = new DMatrixRMaj(1,A.numCols);
CommonOps_DDRM.extract(V_t,which,which+1,0,A.numCols,v,0,0);
return v.data;
} |
java | private boolean shouldGwtDotCreate(TypeLiteral<?> typeLiteral) throws BindingCreationException {
Class<?> rawType = typeLiteral.getRawType();
if (rawType.isInterface()) {
// Check whether we can GWT.create() the interface.
// Remote service proxies don't have rebind rules; we handle them
// specially by creating the corresponding synchronous interface (which
// does have a rebind rule).
if (RemoteServiceProxyBinding.isRemoteServiceProxy(typeLiteral)) {
// We could check whether the synchronous interface has a rebind rule;
// however, the user is probably expecting us to GWT.create() a service
// interface for them. If there isn't a rebind rule, a GWT rebind error
// probably makes more sense than a Gin error.
return true;
}
return hasRebindRule(rawType);
} else {
return hasAccessibleZeroArgConstructor(rawType) || hasRebindRule(rawType);
}
} |
java | public static void runExample(
AdWordsServicesInterface adWordsServices, AdWordsSession session, Long campaignId)
throws RemoteException {
// Get the campaign criterion service.
CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(session,
CampaignCriterionServiceInterface.class);
ProductScope productScope = new ProductScope();
// This set of dimensions is for demonstration purposes only. It would be
// extremely unlikely that you want to include so many dimensions in your
// product scope.
ProductBrand productBrand = new ProductBrand();
productBrand.setValue("Nexus");
ProductCanonicalCondition productCanonicalCondition = new ProductCanonicalCondition();
productCanonicalCondition.setCondition(ProductCanonicalConditionCondition.NEW);
ProductCustomAttribute productCustomAttribute = new ProductCustomAttribute();
productCustomAttribute.setType(ProductDimensionType.CUSTOM_ATTRIBUTE_0);
productCustomAttribute.setValue("my attribute value");
ProductOfferId productOfferId = new ProductOfferId();
productOfferId.setValue("book1");
ProductType productTypeLevel1Media = new ProductType();
productTypeLevel1Media.setType(ProductDimensionType.PRODUCT_TYPE_L1);
productTypeLevel1Media.setValue("Media");
ProductType productTypeLevel2Books = new ProductType();
productTypeLevel2Books.setType(ProductDimensionType.PRODUCT_TYPE_L2);
productTypeLevel2Books.setValue("Books");
// The value for the bidding category is a fixed ID for the 'Luggage & Bags'
// category. You can retrieve IDs for categories from the ConstantDataService.
// See the 'GetProductCategoryTaxonomy' example for more details.
ProductBiddingCategory productBiddingCategory = new ProductBiddingCategory();
productBiddingCategory.setType(ProductDimensionType.BIDDING_CATEGORY_L1);
productBiddingCategory.setValue(-5914235892932915235L);
productScope.setDimensions(new ProductDimension[]{ productBrand, productCanonicalCondition,
productCustomAttribute, productOfferId, productTypeLevel1Media, productTypeLevel2Books,
productBiddingCategory});
CampaignCriterion campaignCriterion = new CampaignCriterion();
campaignCriterion.setCampaignId(campaignId);
campaignCriterion.setCriterion(productScope);
// Create operation.
CampaignCriterionOperation criterionOperation = new CampaignCriterionOperation();
criterionOperation.setOperand(campaignCriterion);
criterionOperation.setOperator(Operator.ADD);
// Make the mutate request.
CampaignCriterionReturnValue result =
campaignCriterionService.mutate(new CampaignCriterionOperation[] {criterionOperation});
// Display the result.
System.out.printf("Created a ProductScope criterion with ID %d.%n",
result.getValue(0).getCriterion().getId());
} |
python | def _start_of_century(self):
"""
Reset the date to the first day of the century.
:rtype: Date
"""
year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + 1
return self.set(year, 1, 1) |
java | @Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case AfplibPackage.PAGE_OVERLAY_CONDITIONAL_PROCESSING__PG_OV_TYPE:
setPgOvType((Integer)newValue);
return;
case AfplibPackage.PAGE_OVERLAY_CONDITIONAL_PROCESSING__LEVEL:
setLevel((Integer)newValue);
return;
}
super.eSet(featureID, newValue);
} |
java | private String getCDCQueryJson(CDCQuery cdcQuery) throws SerializationException {
ObjectMapper mapper = getObjectMapper();
String json = null;
try {
json = mapper.writeValueAsString(cdcQuery);
} catch (Exception e) {
throw new SerializationException(e);
}
return json;
} |
java | private HandlerAdapter getHandlerAdapter(HttpRequest request) {
for (HandlerAdapter ha : mAdapterList) {
if (ha.intercept(request)) return ha;
}
return null;
} |
java | private void setTranslationChain() {
for (final Converter<String, String> t : minimalTranslationChain) {
forward = forward.andThen(t);
}
for (final Converter<String, String> t : Lists.reverse(minimalTranslationChain)) {
reverse = reverse.andThen(t.reverse());
}
} |
java | public void addChar(char nextCh)
throws IOException
{
int ch;
while ((ch = readChar()) >= 0) {
outputChar((char) ch);
}
outputChar(nextCh);
} |
python | def update_views(self):
"""Update stats views."""
# Call the father's method
super(Plugin, self).update_views()
# Add specifics informations
# Optional
for key in iterkeys(self.stats):
self.views[key]['optional'] = True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.