language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python
|
def _normalize_subplot_ids(fig):
"""
Make sure a layout subplot property is initialized for every subplot that
is referenced by a trace in the figure.
For example, if a figure contains a `scatterpolar` trace with the `subplot`
property set to `polar3`, this function will make sure the figure's layout
has a `polar3` property, and will initialize it to an empty dict if it
does not
Note: This function mutates the input figure dict
Parameters
----------
fig: dict
A plotly figure dict
"""
layout = fig.setdefault('layout', {})
for trace in fig.get('data', None):
trace_type = trace.get('type', 'scatter')
subplot_types = _trace_to_subplot.get(trace_type, [])
for subplot_type in subplot_types:
subplot_prop_name = _get_subplot_prop_name(subplot_type)
subplot_val_prefix = _get_subplot_val_prefix(subplot_type)
subplot_val = trace.get(subplot_prop_name, subplot_val_prefix)
# extract trailing number (if any)
subplot_number = _get_subplot_number(subplot_val)
if subplot_number > 1:
layout_prop_name = subplot_type + str(subplot_number)
else:
layout_prop_name = subplot_type
if layout_prop_name not in layout:
layout[layout_prop_name] = {}
|
python
|
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB):
"""Given a vector of dB attenuations, adjust signal by
multiplication in the frequency domain"""
npts = len(signal)
padto = 1 << (npts - 1).bit_length()
X = np.fft.rfft(signal, n=padto)
npts = padto
f = np.arange((npts / 2) + 1) / (npts / fs)
fidx_low = (np.abs(f - frange[0])).argmin()
fidx_high = (np.abs(f - frange[1])).argmin()
cal_func = interp1d(calibration_frequencies, attendB)
roi = f[fidx_low:fidx_high]
Hroi = cal_func(roi)
H = np.zeros((len(X),))
H[fidx_low:fidx_high] = Hroi
H = smooth(H)
# print 'H dB max', np.amax(H)
H = 10 ** ((H).astype(float) / 20)
# print 'H amp max', np.amax(H)
# Xadjusted = X.copy()
# Xadjusted[fidx_low:fidx_high] *= H
# Xadjusted = smooth(Xadjusted)
Xadjusted = X * H
# print 'X max', np.amax(abs(X))
# print 'Xadjusted max', np.amax(abs(Xadjusted))
signal_calibrated = np.fft.irfft(Xadjusted)
return signal_calibrated[:len(signal)]
|
java
|
public static Route HEAD(String uriPattern, RouteHandler routeHandler) {
return new Route(HttpConstants.Method.HEAD, uriPattern, routeHandler);
}
|
python
|
def run_example():
r"""
Runs the example.
"""
weather = mc_e.get_weather_data('weather.csv')
my_turbine, e126, dummy_turbine = mc_e.initialize_wind_turbines()
example_farm, example_farm_2 = initialize_wind_farms(my_turbine, e126)
example_cluster = initialize_wind_turbine_cluster(example_farm,
example_farm_2)
calculate_power_output(weather, example_farm, example_cluster)
plot_or_print(example_farm, example_cluster)
|
python
|
def list_supported_drivers():
"""Returns dictionary with driver classes names as keys."""
def convert_oslo_config(oslo_options):
options = []
for opt in oslo_options:
tmp_dict = {k: str(v) for k, v in vars(opt).items()
if not k.startswith('_')}
options.append(tmp_dict)
return options
def list_drivers(queue):
cwd = os.getcwd()
# Go to the parent directory directory where Cinder is installed
os.chdir(utils.__file__.rsplit(os.sep, 2)[0])
try:
drivers = cinder_interface_util.get_volume_drivers()
mapping = {d.class_name: vars(d) for d in drivers}
# Drivers contain class instances which are not serializable
for driver in mapping.values():
driver.pop('cls', None)
if 'driver_options' in driver:
driver['driver_options'] = convert_oslo_config(
driver['driver_options'])
finally:
os.chdir(cwd)
queue.put(mapping)
# Use a different process to avoid having all driver classes loaded in
# memory during our execution.
queue = multiprocessing.Queue()
p = multiprocessing.Process(target=list_drivers, args=(queue,))
p.start()
result = queue.get()
p.join()
return result
|
python
|
def delete_event_public_discount(self, id, discount_id, **data):
"""
DELETE /events/:id/public_discounts/:discount_id/
Deletes a public discount.
"""
return self.delete("/events/{0}/public_discounts/{0}/".format(id,discount_id), data=data)
|
java
|
public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException, IllegalArgumentException
{
Params.notNull(inputStream, "Input stream");
Params.notNull(outputStream, "Output stream");
Params.isFalse(inputStream instanceof ZipInputStream, "Input stream is ZIP.");
Params.isFalse(outputStream instanceof ZipOutputStream, "Output stream is ZIP.");
if(!(inputStream instanceof BufferedInputStream)) {
inputStream = new BufferedInputStream(inputStream);
}
if(!(outputStream instanceof BufferedOutputStream)) {
outputStream = new BufferedOutputStream(outputStream);
}
long bytes = 0;
try {
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while((length = inputStream.read(buffer)) != -1) {
bytes += length;
outputStream.write(buffer, 0, length);
}
}
finally {
close(inputStream);
close(outputStream);
}
return bytes;
}
|
java
|
protected void setHeadersByAuthorizationPolicy(
Message message,
URI currentURI
) {
Headers headers = new Headers(message);
AuthorizationPolicy effectiveAuthPolicy = getEffectiveAuthPolicy(message);
String authString = authSupplier.getAuthorization(effectiveAuthPolicy, currentURI, message, null);
if (authString != null) {
headers.setAuthorization(authString);
}
String proxyAuthString = proxyAuthSupplier.getAuthorization(proxyAuthorizationPolicy,
currentURI, message, null);
if (proxyAuthString != null) {
headers.setProxyAuthorization(proxyAuthString);
}
}
|
python
|
def rate_limit(function):
"""Return a decorator that enforces API request limit guidelines.
We are allowed to make a API request every api_request_delay seconds as
specified in praw.ini. This value may differ from reddit to reddit. For
reddit.com it is 2. Any function decorated with this will be forced to
delay _rate_delay seconds from the calling of the last function
decorated with this before executing.
This decorator must be applied to a RateLimitHandler class method or
instance method as it assumes `rl_lock` and `last_call` are available.
"""
@wraps(function)
def wrapped(cls, _rate_domain, _rate_delay, **kwargs):
cls.rl_lock.acquire()
lock_last = cls.last_call.setdefault(_rate_domain, [Lock(), 0])
with lock_last[0]: # Obtain the domain specific lock
cls.rl_lock.release()
# Sleep if necessary, then perform the request
now = timer()
delay = lock_last[1] + _rate_delay - now
if delay > 0:
now += delay
time.sleep(delay)
lock_last[1] = now
return function(cls, **kwargs)
return wrapped
|
java
|
public void changePassword(String newPassword) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
if (!connection().isSecureConnection() && !allowSensitiveOperationOverInsecureConnection) {
throw new IllegalStateException("Changing password over insecure connection.");
}
Map<String, String> map = new HashMap<>();
map.put("username", connection().getUser().getLocalpart().toString());
map.put("password",newPassword);
Registration reg = new Registration(map);
reg.setType(IQ.Type.set);
reg.setTo(connection().getXMPPServiceDomain());
createStanzaCollectorAndSend(reg).nextResultOrThrow();
}
|
python
|
def frustum_height_at_distance(vfov_deg, distance):
"""Calculate the frustum height (in world units) at a given distance
(in world units) from the camera.
"""
height = 2.0 * distance * np.tan(np.radians(vfov_deg * 0.5))
return height
|
java
|
public BoxCollaborationWhitelistExemptTarget.Info getInfo() {
URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(),
this.getID());
BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET);
BoxJSONResponse response = (BoxJSONResponse) request.send();
return new Info(JsonObject.readFrom(response.getJSON()));
}
|
python
|
def main(argv=None):
"""Entry point for the `simpl` command."""
#
# `simpl server`
#
logging.basicConfig(level=logging.INFO)
server_func = functools.partial(server.main, argv=argv)
server_parser = server.attach_parser(default_subparser())
server_parser.set_defaults(_func=server_func)
# the following code shouldn't need to change when
# we add a new subcommand.
args = default_parser().parse_args(argv)
args._func()
|
python
|
def execute_on_key(self, key, entry_processor):
"""
Applies the user defined EntryProcessor to the entry mapped by the key. Returns the object which is the result
of EntryProcessor's process method.
:param key: (object), specified key for the entry to be processed.
:param entry_processor: (object), A stateful serializable object which represents the EntryProcessor defined on
server side.
This object must have a serializable EntryProcessor counter part registered on server side with the actual
``org.hazelcast.map.EntryProcessor`` implementation.
:return: (object), result of entry process.
"""
check_not_none(key, "key can't be None")
key_data = self._to_data(key)
return self._execute_on_key_internal(key_data, entry_processor)
|
python
|
def appendDefaultDrop(self):
""" Add a DROP policy at the end of the rules """
self.filters.append('-A INPUT -j DROP')
self.filters.append('-A OUTPUT -j DROP')
self.filters.append('-A FORWARD -j DROP')
return self
|
java
|
@Override
public final void reportLocalError()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "reportLocalError");
// Only need to set to LOCAL_ERROR
// if we are currently OK. We don't want
// to overwrite a GLOBAL_ERROR.
if (_healthState.isOK())
{
_healthState = JsHealthState.getLocalError();
}
if (_healthMonitor == null)
{
if (_messagingEngine != null && _messagingEngine instanceof JsHealthMonitor)
{
_healthMonitor = (JsHealthMonitor) _messagingEngine;
_healthMonitor.reportLocalError();
}
}
else
{
_healthMonitor.reportLocalError();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "reportLocalError");
}
|
java
|
public void init(Record record, Record recHistory, String iHistoryDateSeq, BaseField fldSourceHistoryDate, boolean bCloseOnFree, String strRecHistoryClass, String iSourceHistoryDateSeq)
{
if (iHistoryDateSeq == null)
iHistoryDateSeq = recHistory.getField(recHistory.getFieldCount() - 1).getFieldName(); // Last field
m_iHistoryDateSeq = iHistoryDateSeq;
m_fldSourceHistoryDate = fldSourceHistoryDate;
m_strRecHistoryClass = strRecHistoryClass;
m_iSourceDateSeq = iSourceHistoryDateSeq;
super.init(record, null, recHistory, bCloseOnFree);
if (m_recDependent != null)
{
if (m_recDependent.getListener(RecordChangedHandler.class) != null)
m_recDependent.removeListener(m_recDependent.getListener(RecordChangedHandler.class), true); // I replace this listener
}
this.setMasterSlaveFlag(FileListener.RUN_IN_SLAVE); // This runs on the slave (if there is a slave)
}
|
java
|
@Override
public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) {
if (payloadStarted) {
if (skipping == 0) {
AttributeNode<FieldDescriptor, Integer> attrNode = currentNode.getChild(fieldNumber);
if (attrNode != null) { // process only 'interesting' tags
messageContext.markField(fieldNumber);
attrNode.processValue(tagValue, this);
}
}
} else {
switch (fieldNumber) {
case WrappedMessage.WRAPPED_DESCRIPTOR_FULL_NAME:
entityTypeName = (String) tagValue;
break;
case WrappedMessage.WRAPPED_DESCRIPTOR_ID:
entityTypeName = serializationContext.getTypeNameById((Integer) tagValue);
break;
case WrappedMessage.WRAPPED_MESSAGE:
payload = (byte[]) tagValue;
break;
case WrappedMessage.WRAPPED_DOUBLE:
case WrappedMessage.WRAPPED_FLOAT:
case WrappedMessage.WRAPPED_INT64:
case WrappedMessage.WRAPPED_UINT64:
case WrappedMessage.WRAPPED_INT32:
case WrappedMessage.WRAPPED_FIXED64:
case WrappedMessage.WRAPPED_FIXED32:
case WrappedMessage.WRAPPED_BOOL:
case WrappedMessage.WRAPPED_STRING:
case WrappedMessage.WRAPPED_BYTES:
case WrappedMessage.WRAPPED_UINT32:
case WrappedMessage.WRAPPED_SFIXED32:
case WrappedMessage.WRAPPED_SFIXED64:
case WrappedMessage.WRAPPED_SINT32:
case WrappedMessage.WRAPPED_SINT64:
case WrappedMessage.WRAPPED_ENUM:
break;
// this is a primitive value, which we ignore for now due to lack of support for querying primitives
default:
throw new IllegalStateException("Unexpected field : " + fieldNumber);
}
}
}
|
java
|
private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap)
{
Project.Resources resources = project.getResources();
if (resources != null)
{
for (Project.Resources.Resource resource : resources.getResource())
{
readResource(resource, calendarMap);
}
}
}
|
python
|
def name2rgb(hue):
"""Originally used to calculate color based on module name.
"""
r, g, b = colorsys.hsv_to_rgb(hue / 360.0, .8, .7)
return tuple(int(x * 256) for x in [r, g, b])
|
python
|
def is_scalar(self):
"""
:return:
:rtype: bool
"""
return \
isinstance(self._element_template, Boolean) or \
isinstance(self._element_template, Float) or \
isinstance(self._element_template, Integer) or \
isinstance(self._element_template, String)
|
java
|
private void loadAllParts()
throws IOException
{
// Get first boundary
String line = _in.readLine();
if (!line.equals(_boundary))
{
log.warn(line);
throw new IOException("Missing initial multi part boundary");
}
// Read each part
while (!_lastPart)
{
// Read Part headers
Part part = new Part();
String content_disposition=null;
while ((line=_in.readLine())!=null)
{
// If blank line, end of part headers
if (line.length()==0)
break;
if(log.isDebugEnabled())log.debug("LINE="+line);
// place part header key and value in map
int c = line.indexOf(':',0);
if (c>0)
{
String key = line.substring(0,c).trim().toLowerCase();
String value = line.substring(c+1,line.length()).trim();
String ev = (String) part._headers.get(key);
part._headers.put(key,(ev!=null)?(ev+';'+value):value);
if(log.isDebugEnabled())log.debug(key+": "+value);
if (key.equals("content-disposition"))
content_disposition=value;
}
}
// Extract content-disposition
boolean form_data=false;
if (content_disposition==null)
{
throw new IOException("Missing content-disposition");
}
StringTokenizer tok =
new StringTokenizer(content_disposition,";");
while (tok.hasMoreTokens())
{
String t = tok.nextToken().trim();
String tl = t.toLowerCase();
if (t.startsWith("form-data"))
form_data=true;
else if (tl.startsWith("name="))
part._name=value(t);
else if (tl.startsWith("filename="))
part._filename=value(t);
}
// Check disposition
if (!form_data)
{
log.warn("Non form-data part in multipart/form-data");
continue;
}
if (part._name==null || part._name.length()==0)
{
log.warn("Part with no name in multipart/form-data");
continue;
}
if(log.isDebugEnabled())log.debug("name="+part._name);
if(log.isDebugEnabled())log.debug("filename="+part._filename);
_partMap.add(part._name,part);
part._data=readBytes();
}
}
|
python
|
def merge_entities(doc):
"""Merge entities into a single token.
doc (Doc): The Doc object.
RETURNS (Doc): The Doc object with merged entities.
DOCS: https://spacy.io/api/pipeline-functions#merge_entities
"""
with doc.retokenize() as retokenizer:
for ent in doc.ents:
attrs = {"tag": ent.root.tag, "dep": ent.root.dep, "ent_type": ent.label}
retokenizer.merge(ent, attrs=attrs)
return doc
|
python
|
def process(self, sched, coro):
"""Add the timeout in the scheduler, check for defaults."""
super(TimedOperation, self).process(sched, coro)
if sched.default_timeout and not self.timeout:
self.set_timeout(sched.default_timeout)
if self.timeout and self.timeout != -1:
self.coro = coro
if self.weak_timeout:
self.last_checkpoint = getnow()
self.delta = self.timeout - self.last_checkpoint
else:
self.last_checkpoint = self.delta = None
heapq.heappush(sched.timeouts, self)
|
java
|
@Override
public MetadataLocation buildObject(String namespaceURI, String localName, String namespacePrefix) {
return new MetadataLocationImpl(namespaceURI, localName, namespacePrefix);
}
|
java
|
@Override
public final Manufacture process(
final Map<String, Object> pAddParam,
final Manufacture pEntity,
final IRequestData pRequestData) throws Exception {
Manufacture entity = this.prcAccEntityPbCopy
.process(pAddParam, pEntity, pRequestData);
entity.setItsQuantity(BigDecimal.ZERO);
entity.setTheRest(BigDecimal.ZERO);
return entity;
}
|
java
|
private void unsafeSendRequest(final ChannelHandlerContext ctx,
final ByteBuf request,
final Promise<DcpResponse> promise) {
if (!ctx.executor().inEventLoop()) {
throw new IllegalStateException("Must not be called outside event loop");
}
try {
final int opaque = nextOpaque++;
MessageUtil.setOpaque(opaque, request);
// Don't need to be notified if/when the bytes are written,
// so use void promise to save an allocation.
ctx.writeAndFlush(request, ctx.voidPromise());
outstandingRequests.add(new OutstandingRequest(opaque, promise));
} catch (Throwable t) {
promise.setFailure(t);
}
}
|
python
|
def _download_linkode(self):
"""Download content from Linkode pastebin."""
# build the API url
linkode_id = self.url.split("/")[-1]
if linkode_id.startswith("#"):
linkode_id = linkode_id[1:]
url = "https://linkode.org/api/1/linkodes/" + linkode_id
req = request.Request(url, headers=self.HEADERS_JSON)
resp = request.urlopen(req)
raw = resp.read()
data = json.loads(raw.decode("utf8"))
content = data['content']
return content
|
java
|
public int write(OutputStreamWithBuffer os, char []cbuf, int off, int len)
throws IOException
{
for (int i = 0; i < len; i++) {
write(os, cbuf[off + i]);
}
return len;
}
|
python
|
def is_in_team(self, team_id):
"""Test if user is in team"""
if self.is_super_admin():
return True
team_id = uuid.UUID(str(team_id))
return team_id in self.teams or team_id in self.child_teams_ids
|
python
|
def function_body(self):
"""
function_body: '{' (statement)* '}'
"""
root = FunctionBody()
self._process(Nature.LBRACKET)
while self.token.nature != Nature.RBRACKET:
root.children.append(self.statement())
self._process(Nature.RBRACKET)
return root
|
python
|
def search_external_subtitles(path, directory=None):
"""Search for external subtitles from a video `path` and their associated language.
Unless `directory` is provided, search will be made in the same directory as the video file.
:param str path: path to the video.
:param str directory: directory to search for subtitles.
:return: found subtitles with their languages.
:rtype: dict
"""
# split path
dirpath, filename = os.path.split(path)
dirpath = dirpath or '.'
fileroot, fileext = os.path.splitext(filename)
# search for subtitles
subtitles = {}
for p in os.listdir(directory or dirpath):
# keep only valid subtitle filenames
if not p.startswith(fileroot) or not p.endswith(SUBTITLE_EXTENSIONS):
continue
# extract the potential language code
language = Language('und')
language_code = p[len(fileroot):-len(os.path.splitext(p)[1])].replace(fileext, '').replace('_', '-')[1:]
if language_code:
try:
language = Language.fromietf(language_code)
except (ValueError, LanguageReverseError):
logger.error('Cannot parse language code %r', language_code)
subtitles[p] = language
logger.debug('Found subtitles %r', subtitles)
return subtitles
|
python
|
def get_avatar(from_header, size=64, default="retro"):
"""Get the avatar URL from the email's From header.
Args:
from_header (str): The email's From header. May contain the sender's full name.
Returns:
str: The URL to that sender's avatar.
"""
params = OrderedDict([("s", size), ("d", default)])
query = parse.urlencode(params)
address = email.utils.parseaddr(from_header)[1]
value_hash = sha256(address.encode("utf-8")).hexdigest()
return "https://seccdn.libravatar.org/avatar/{}?{}".format(value_hash, query)
|
python
|
def NewFromRgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF):
'''Create a new instance based on the specifed RGB values.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitepoint reference, default is 2° D65.
Returns:
A grapefruit.Color instance.
>>> Color.NewFromRgb(1.0, 0.5, 0.0)
(1.0, 0.5, 0.0, 1.0)
>>> Color.NewFromRgb(1.0, 0.5, 0.0, 0.5)
(1.0, 0.5, 0.0, 0.5)
'''
return Color((r, g, b), 'rgb', alpha, wref)
|
java
|
private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {
String[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();
Object[] columnValues = new Object[columnNames.length];
for ( int i = 0; i < columnNames.length; i++ ) {
String columnName = columnNames[i];
columnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );
}
return new RowKey( columnNames, columnValues );
}
|
java
|
public static PersistenceBrokerInternal currentPersistenceBroker(PBKey key)
throws PBFactoryException, PersistenceBrokerException
{
HashMap map = (HashMap) currentBrokerMap.get();
WeakHashMap set;
PersistenceBrokerInternal broker = null;
if(map == null)
{
return null;
}
set = (WeakHashMap) map.get(key);
if(set == null)
{
return null;
}
// seek for an open broker, preferably in transaction
for(Iterator it = set.keySet().iterator(); it.hasNext();)
{
PersistenceBrokerInternal tmp = (PersistenceBrokerInternal) it.next();
if(tmp == null || tmp.isClosed())
{
it.remove();
continue;
}
broker = tmp;
if(tmp.isInTransaction())
{
break; // the best choice found
}
}
return broker;
}
|
java
|
public Sql[] generateSqlIfExists(final DropSpatialIndexStatement statement,
final Database database) {
final String catalogName = statement.getTableCatalogName();
final String schemaName = statement.getTableSchemaName();
final String tableName = statement.getTableName();
final SpatialIndexExistsPrecondition precondition = new SpatialIndexExistsPrecondition();
precondition.setCatalogName(catalogName);
precondition.setSchemaName(schemaName);
precondition.setTableName(tableName);
final DatabaseObject example = precondition.getExample(database, tableName);
try {
// If a spatial index exists on the table, drop it.
if (SnapshotGeneratorFactory.getInstance().has(example, database)) {
return generateSql(statement, database, null);
}
} catch (final Exception e) {
throw new UnexpectedLiquibaseException(e);
}
return new Sql[0];
}
|
python
|
def __write_filter_dic(wk_sheet, column):
'''
return filter dic for certain column
'''
row1_val = wk_sheet['{0}1'.format(column)].value
row2_val = wk_sheet['{0}2'.format(column)].value
row3_val = wk_sheet['{0}3'.format(column)].value
row4_val = wk_sheet['{0}4'.format(column)].value
if row1_val and row1_val.strip() != '':
row2_val = row2_val.strip()
slug_name = row1_val.strip()
c_name = row2_val.strip()
tags1 = [x.strip() for x in row3_val.split(',')]
tags_dic = {}
# if only one tag,
if len(tags1) == 1:
xx_1 = row2_val.split(':') # 'text' # HTML text input control.
if xx_1[0].lower() in INPUT_ARR:
xx_1[0] = xx_1[0].lower()
else:
xx_1[0] = 'text'
if len(xx_1) == 2:
ctr_type, unit = xx_1
else:
ctr_type = xx_1[0]
unit = ''
tags_dic[1] = unit
else:
ctr_type = 'select' # HTML selectiom control.
for index, tag_val in enumerate(tags1):
# the index of tags_dic starts from 1.
tags_dic[index + 1] = tag_val.strip()
outkey = 'html_{0}'.format(slug_name)
outval = {
'en': slug_name,
'zh': c_name,
'dic': tags_dic,
'type': ctr_type,
'display': row4_val,
}
return (outkey, outval)
else:
return (None, None)
|
java
|
public static Properties readProperties( InputStream stream, Properties mappings, boolean closeStream )
throws IOException
{
try
{
Properties p = new Properties();
p.load( stream );
mappings.putAll( p );
boolean doAgain = true;
while( doAgain )
{
doAgain = false;
for( Map.Entry<Object, Object> entry : p.entrySet() )
{
String value = (String) entry.getValue();
if( value.indexOf( "${" ) >= 0 )
{
value = resolveProperty( mappings, value );
entry.setValue( value );
doAgain = true;
}
}
}
return p;
}
finally
{
if( closeStream )
{
stream.close();
}
}
}
|
python
|
def filecache(seconds_of_validity=None, fail_silently=False):
'''
filecache is called and the decorator should be returned.
'''
def filecache_decorator(function):
@_functools.wraps(function)
def function_with_cache(*args, **kwargs):
try:
key = _args_key(function, args, kwargs)
if key in function._db:
rv = function._db[key]
if seconds_of_validity is None or _time.time() - rv.timesig < seconds_of_validity:
return rv.data
except Exception:
# in any case of failure, don't let filecache break the program
error_str = _traceback.format_exc()
_log_error(error_str)
if not fail_silently:
raise
retval = function(*args, **kwargs)
# store in cache
# NOTE: no need to _db.sync() because there was no mutation
# NOTE: it's importatnt to do _db.sync() because otherwise the cache doesn't survive Ctrl-Break!
try:
function._db[key] = _retval(_time.time(), retval)
function._db.sync()
except Exception:
# in any case of failure, don't let filecache break the program
error_str = _traceback.format_exc()
_log_error(error_str)
if not fail_silently:
raise
return retval
# make sure cache is loaded
if not hasattr(function, '_db'):
cache_name = _get_cache_name(function)
if cache_name in OPEN_DBS:
function._db = OPEN_DBS[cache_name]
else:
function._db = _shelve.open(cache_name)
OPEN_DBS[cache_name] = function._db
atexit.register(function._db.close)
function_with_cache._db = function._db
return function_with_cache
if type(seconds_of_validity) == types.FunctionType:
# support for when people use '@filecache.filecache' instead of '@filecache.filecache()'
func = seconds_of_validity
seconds_of_validity = None
return filecache_decorator(func)
return filecache_decorator
|
java
|
public Long zcount(Object key, double min, double max) {
Jedis jedis = getJedis();
try {
return jedis.zcount(keyToBytes(key), min, max);
}
finally {close(jedis);}
}
|
java
|
public MapWithProtoValuesFluentAssertion<M> ignoringExtraRepeatedFieldElementsOfFieldsForValues(
Iterable<Integer> fieldNumbers) {
return usingConfig(config.ignoringExtraRepeatedFieldElementsOfFields(fieldNumbers));
}
|
python
|
async def send(self, data, room=None, skip_sid=None, namespace=None,
callback=None, **kwargs):
"""Send a message to one or more connected clients.
This function emits an event with the name ``'message'``. Use
:func:`emit` to issue custom event names.
:param data: The data to send to the client or clients. Data can be of
type ``str``, ``bytes``, ``list`` or ``dict``. If a
``list`` or ``dict``, the data will be serialized as JSON.
:param room: The recipient of the message. This can be set to the
session ID of a client to address that client's room, or
to any custom room created by the application, If this
argument is omitted the event is broadcasted to all
connected clients.
:param skip_sid: The session ID of a client to skip when broadcasting
to a room or to all clients. This can be used to
prevent a message from being sent to the sender.
:param namespace: The Socket.IO namespace for the event. If this
argument is omitted the event is emitted to the
default namespace.
:param callback: If given, this function will be called to acknowledge
the the client has received the message. The arguments
that will be passed to the function are those provided
by the client. Callback functions can only be used
when addressing an individual client.
:param ignore_queue: Only used when a message queue is configured. If
set to ``True``, the event is emitted to the
clients directly, without going through the queue.
This is more efficient, but only works when a
single server process is used. It is recommended
to always leave this parameter with its default
value of ``False``.
Note: this method is a coroutine.
"""
await self.emit('message', data=data, room=room, skip_sid=skip_sid,
namespace=namespace, callback=callback, **kwargs)
|
java
|
@Override
public String toJSONString()
{
final JSONObject object = toJSONObject();
if (null != object)
{
return object.toString();
}
return null;
}
|
python
|
def dist01(graph, weight, source=0, target=None):
"""Shortest path in a 0,1 weighted graph
:param graph: directed graph in listlist or listdict format
:param weight: matrix or adjacency dictionary
:param int source: vertex
:param target: exploration stops once distance to target is found
:returns: distance table, predecessor table
:complexity: `O(|V|+|E|)`
"""
n = len(graph)
dist = [float('inf')] * n
prec = [None] * n
black = [False] * n
dist[source] = 0
gray = deque([source])
while gray:
node = gray.pop()
if black[node]:
continue
black[node] = True
if node == target:
break
for neighbor in graph[node]:
ell = dist[node] + weight[node][neighbor]
if black[neighbor] or dist[neighbor] <= ell:
continue
dist[neighbor] = ell
prec[neighbor] = node
if weight[node][neighbor] == 0:
gray.append(neighbor)
else:
gray.appendleft(neighbor)
return dist, prec
|
java
|
protected AbstractConfiguration addMixInAnnotations( Class<?> target, Class<?> mixinSource ) {
mapMixInAnnotations.put( target, mixinSource );
return this;
}
|
java
|
@SuppressWarnings("unchecked")
public static <T extends Number> T isNumber( String value, Class<T> adaptee ) {
if (value == null) {
return null;
}
if (adaptee == null) {
adaptee = (Class<T>) Double.class;
}
if (adaptee.isAssignableFrom(Double.class)) {
try {
Double parsed = Double.parseDouble(value);
return adaptee.cast(parsed);
} catch (Exception e) {
return null;
}
} else if (adaptee.isAssignableFrom(Float.class)) {
try {
Float parsed = Float.parseFloat(value);
return adaptee.cast(parsed);
} catch (Exception e) {
return null;
}
} else if (adaptee.isAssignableFrom(Integer.class)) {
try {
Integer parsed = Integer.parseInt(value);
return adaptee.cast(parsed);
} catch (Exception e) {
try {
// try also double and convert by truncating
Integer parsed = (int) Double.parseDouble(value);
return adaptee.cast(parsed);
} catch (Exception ex) {
return null;
}
}
} else {
throw new IllegalArgumentException();
}
}
|
java
|
public Vector3d fma(Vector3dc a, Vector3dc b) {
return fma(a, b, thisOrNew());
}
|
java
|
private boolean isNullified(Object target, Field field) {
Class<?> type = field.getType();
Object value = null;
try {
value = field.get(target);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IrohException(e);
}
if (nulls.containsKey(type)) {
/**
* Very purposefully compare the locations rather than their values,
* since we totally cheated with Objenesis obtaining instances of
* these local nulls. All hell would likely break loose if we tried
* to use the methods defined in the actual objects...
*/
if (nulls.get(type) == value) {
return true;
}
}
return false;
}
|
java
|
public List<Relationship> getPrerequisiteRelationships() {
final List<Relationship> prerequisiteRelationships = new LinkedList<Relationship>();
for (final Relationship r : relationships) {
if (r.getType() == RelationshipType.PREREQUISITE) {
prerequisiteRelationships.add(r);
}
}
return prerequisiteRelationships;
}
|
python
|
def _reverse_queue(self):
u"""When socket.timeout has occurred for Zabbix server,
this method is called.
Enqueue items in self.pool[].
"""
while self.pool:
item = self.pool.pop()
self.queue.put(item, block=False)
|
java
|
@Provides protected TvShowCollectionRendererBuilder provideTvShowCollectionRendererBuilder(
Context context) {
List<Renderer<TvShowViewModel>> prototypes = new LinkedList<Renderer<TvShowViewModel>>();
prototypes.add(new TvShowRenderer(context));
return new TvShowCollectionRendererBuilder(prototypes);
}
|
java
|
private Type extractContainingType(Attribute.Compound ca,
DiagnosticPosition pos,
TypeSymbol annoDecl)
{
// The next three checks check that the Repeatable annotation
// on the declaration of the annotation type that is repeating is
// valid.
// Repeatable must have at least one element
if (ca.values.isEmpty()) {
log.error(pos, "invalid.repeatable.annotation", annoDecl);
return null;
}
Pair<MethodSymbol,Attribute> p = ca.values.head;
Name name = p.fst.name;
if (name != names.value) { // should contain only one element, named "value"
log.error(pos, "invalid.repeatable.annotation", annoDecl);
return null;
}
if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
log.error(pos, "invalid.repeatable.annotation", annoDecl);
return null;
}
return ((Attribute.Class)p.snd).getValue();
}
|
python
|
def _blkid_output(out, fs_type=None):
'''
Parse blkid output.
'''
flt = lambda data: [el for el in data if el.strip()]
data = {}
for dev_meta in flt(out.split('\n\n')):
dev = {}
for items in flt(dev_meta.strip().split('\n')):
key, val = items.split('=', 1)
dev[key.lower()] = val
if fs_type and dev.get('type', '') == fs_type or not fs_type:
if 'type' in dev and fs_type:
dev.pop('type')
data[dev.pop('devname')] = dev
if fs_type:
mounts = _get_mounts(fs_type)
for device in six.iterkeys(mounts):
if data.get(device):
data[device]['mounts'] = mounts[device]
return data
|
java
|
public void setAdditionalTreatments(java.util.Collection<TreatmentResource> additionalTreatments) {
if (additionalTreatments == null) {
this.additionalTreatments = null;
return;
}
this.additionalTreatments = new java.util.ArrayList<TreatmentResource>(additionalTreatments);
}
|
java
|
private static boolean obtainLicenseAgreement(LicenseProvider licenseProvider) {
// Prompt for word-wrapped display of license agreement & information
boolean view;
SelfExtract.wordWrappedOut(SelfExtract.format("showAgreement", "--viewLicenseAgreement"));
view = SelfExtract.getResponse(SelfExtract.format("promptAgreement"), "", "xX");
if (view) {
SelfExtract.showLicenseFile(licenseProvider.getLicenseAgreement());
System.out.println();
}
SelfExtract.wordWrappedOut(SelfExtract.format("showInformation", "--viewLicenseInfo"));
view = SelfExtract.getResponse(SelfExtract.format("promptInfo"), "", "xX");
if (view) {
SelfExtract.showLicenseFile(licenseProvider.getLicenseInformation());
System.out.println();
}
System.out.println();
SelfExtract.wordWrappedOut(SelfExtract.format("licenseOptionDescription"));
System.out.println();
boolean accept = SelfExtract.getResponse(SelfExtract.format("licensePrompt", new Object[] { "[1]", "[2]" }),
"1", "2");
System.out.println();
return accept;
}
|
java
|
public void add(String name, V value) {
List<V> lo = get(name);
if (lo == null) {
lo = new ArrayList<>();
}
lo.add(value);
super.put(name, lo);
}
|
python
|
def serve_forever(self):
"""Call the main loop."""
# Set the server login/password (if -P/--password tag)
if self.args.password != "":
self.add_user(self.args.username, self.args.password)
# Serve forever
self.server.serve_forever()
|
java
|
public PubsubFuture<Void> deleteTopic(final String project,
final String topic) {
return deleteTopic(canonicalTopic(project, topic));
}
|
java
|
public SimpleArrayGrid view(int offset, int width)
{
return new SimpleArrayGrid(array, width, height, this.offset + offset, length, boxed);
}
|
python
|
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
|
python
|
def get_pixbeam(self, ra, dec):
"""
Determine the beam in pixels at the given location in sky coordinates.
Parameters
----------
ra , dec : float
The sly coordinates at which the beam is determined.
Returns
-------
beam : :class:`AegeanTools.fits_image.Beam`
A beam object, with a/b/pa in pixel coordinates.
"""
if ra is None:
ra, dec = self.pix2sky(self.refpix)
pos = [ra, dec]
beam = self.get_beam(ra, dec)
_, _, major, minor, theta = self.sky2pix_ellipse(pos, beam.a, beam.b, beam.pa)
if major < minor:
major, minor = minor, major
theta -= 90
if theta < -180:
theta += 180
if not np.isfinite(theta):
theta = 0
if not all(np.isfinite([major, minor, theta])):
beam = None
else:
beam = Beam(major, minor, theta)
return beam
|
python
|
def visit_Assign(self, node):
"""
Create Assign node for final Cxx representation.
It tries to handle multi assignment like:
>> a = b = c = 2
If only one local variable is assigned, typing is added:
>> int a = 2;
TODO: Handle case of multi-assignement for some local variables.
Finally, process OpenMP clause like #pragma omp atomic
"""
if not all(isinstance(n, (ast.Name, ast.Subscript))
for n in node.targets):
raise PythranSyntaxError(
"Must assign to an identifier or a subscript",
node)
value = self.visit(node.value)
targets = [self.visit(t) for t in node.targets]
alltargets = "= ".join(targets)
islocal = (len(targets) == 1 and
isinstance(node.targets[0], ast.Name) and
node.targets[0].id in self.scope[node] and
node.targets[0].id not in self.openmp_deps)
if islocal:
# remove this decls from local decls
self.ldecls.difference_update(t.id for t in node.targets)
# add a local declaration
if self.types[node.targets[0]].iscombined():
alltargets = '{} {}'.format(self.typeof(node.targets[0]),
alltargets)
elif isinstance(self.types[node.targets[0]],
self.types.builder.Assignable):
alltargets = '{} {}'.format(
self.types.builder.Assignable(
self.types.builder.NamedType(
'decltype({})'.format(value))),
alltargets)
else:
assert isinstance(self.types[node.targets[0]],
self.types.builder.Lazy)
alltargets = '{} {}'.format(
self.types.builder.Lazy(
self.types.builder.NamedType(
'decltype({})'.format(value))),
alltargets)
stmt = Assign(alltargets, value)
return self.process_omp_attachements(node, stmt)
|
java
|
private static boolean scanArchive(Connector cmd)
{
if (cmd == null)
return true;
if (cmd.getVersion() == Version.V_16 || cmd.getVersion() == Version.V_17)
{
if (!cmd.isMetadataComplete())
return true;
}
return false;
}
|
java
|
public static boolean lasRecordEqual( LasRecord dot1, LasRecord dot2 ) {
double delta = 0.000001;
boolean check = NumericsUtilities.dEq(dot1.x, dot2.x, delta);
if (!check) {
return false;
}
check = NumericsUtilities.dEq(dot1.y, dot2.y, delta);
if (!check) {
return false;
}
check = NumericsUtilities.dEq(dot1.z, dot2.z, delta);
if (!check) {
return false;
}
check = dot1.intensity == dot2.intensity;
if (!check) {
return false;
}
check = dot1.classification == dot2.classification;
if (!check) {
return false;
}
check = dot1.returnNumber == dot2.returnNumber;
if (!check) {
return false;
}
check = dot1.numberOfReturns == dot2.numberOfReturns;
if (!check) {
return false;
}
return true;
}
|
python
|
def blob_get(self, table, digest, chunk_size=1024 * 128):
"""
Returns a file like object representing the contents of the blob
with the given digest.
"""
response = self._request('GET', _blob_path(table, digest), stream=True)
if response.status == 404:
raise DigestNotFoundException(table, digest)
_raise_for_status(response)
return response.stream(amt=chunk_size)
|
python
|
def _get_spot_history(ctx, instance_type):
"""
Returns list of 1,000 most recent spot market data points represented as SpotPriceHistory
objects. Note: The most recent object/data point will be first in the list.
:rtype: list[SpotPriceHistory]
"""
one_week_ago = datetime.datetime.now() - datetime.timedelta(days=7)
spot_data = ctx.ec2.get_spot_price_history(start_time=one_week_ago.isoformat(),
instance_type=instance_type,
product_description="Linux/UNIX")
spot_data.sort(key=attrgetter("timestamp"), reverse=True)
return spot_data
|
java
|
public java.util.List<AvailableProcessorFeature> getValidProcessorFeatures() {
if (validProcessorFeatures == null) {
validProcessorFeatures = new com.amazonaws.internal.SdkInternalList<AvailableProcessorFeature>();
}
return validProcessorFeatures;
}
|
java
|
public <T> T mock(Class<T> typeToMock) {
return mock(typeToMock, namingScheme.defaultNameFor(typeToMock));
}
|
java
|
public void setRestrictions(List<IRule> rulesNew) throws CDKException {
Iterator<IRule> itRules = rulesNew.iterator();
while (itRules.hasNext()) {
IRule rule = itRules.next();
if (rule instanceof ElementRule) {
mfRange = (MolecularFormulaRange) ((Object[]) rule.getParameters())[0];
//removing the rule
Iterator<IRule> oldRuleIt = rules.iterator();
while (oldRuleIt.hasNext()) {
IRule oldRule = oldRuleIt.next();
if (oldRule instanceof ElementRule) {
rules.remove(oldRule);
rules.add(rule);
break;
}
}
this.matrix_Base = getMatrix(mfRange.getIsotopeCount());
} else if (rule instanceof ChargeRule) {
this.charge = (Double) ((Object[]) rule.getParameters())[0];
//removing the rule
Iterator<IRule> oldRuleIt = rules.iterator();
while (oldRuleIt.hasNext()) {
IRule oldRule = oldRuleIt.next();
if (oldRule instanceof ChargeRule) {
rules.remove(oldRule);
rules.add(rule);
break;
}
}
} else if (rule instanceof ToleranceRangeRule) {
this.tolerance = (Double) ((Object[]) rule.getParameters())[1];
//removing the rule
Iterator<IRule> oldRuleIt = rules.iterator();
while (oldRuleIt.hasNext()) {
IRule oldRule = oldRuleIt.next();
if (oldRule instanceof ToleranceRangeRule) {
rules.remove(oldRule);
rules.add(rule);
break;
}
}
} else {
rules.add(rule);
}
}
}
|
java
|
public void setSecrets(java.util.Collection<Secret> secrets) {
if (secrets == null) {
this.secrets = null;
return;
}
this.secrets = new com.amazonaws.internal.SdkInternalList<Secret>(secrets);
}
|
python
|
def xtime(b, n):
"""Repeated polynomial multiplication in GF(2^8)."""
b = b.reshape(8)
for _ in range(n):
b = exprzeros(1) + b[:7] ^ uint2exprs(0x1b, 8) & b[7]*8
return b
|
python
|
def add_values_to_bundle_safe(connection, bundle, values):
"""
Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added.
Args:
connection: An opened Connection instance.
bundle: Bundle instance to add values in.
values: Values, that should be added in bundle.
Raises:
YouTrackException: if something is wrong with queries.
"""
for value in values:
try:
connection.addValueToBundle(bundle, value)
except YouTrackException as e:
if e.response.status == 409:
print("Value with name [ %s ] already exists in bundle [ %s ]" %
(utf8encode(value.name), utf8encode(bundle.name)))
else:
raise e
|
java
|
public Observable<Page<DeletedSiteInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<DeletedSiteInner>>, Page<DeletedSiteInner>>() {
@Override
public Page<DeletedSiteInner> call(ServiceResponse<Page<DeletedSiteInner>> response) {
return response.body();
}
});
}
|
java
|
public Matrix4f translate(float x, float y, float z, Matrix4f dest) {
if ((properties & PROPERTY_IDENTITY) != 0)
return dest.translation(x, y, z);
return translateGeneric(x, y, z, dest);
}
|
java
|
static int calculateChecksum(ByteBuf data, int offset, int length) {
Crc32c crc32 = new Crc32c();
try {
crc32.update(data, offset, length);
return maskChecksum((int) crc32.getValue());
} finally {
crc32.reset();
}
}
|
java
|
public synchronized void synchronizeWith(UpdateSynchronizer newsync) {
// LoggingUtil.warning("Synchronizing: " + sync + " " + newsync, new
// Throwable());
if(synchronizer == newsync) {
LoggingUtil.warning("Double-synced to the same plot!", new Throwable());
return;
}
if(synchronizer != null) {
LoggingUtil.warning("Attempting to synchronize to more than one synchronizer.");
return;
}
synchronizer = newsync;
newsync.addUpdateRunner(this);
}
|
java
|
public static SqlInfo getSqlInfoSimply(String nsAtZealotId, Object paramObj) {
String[] arr = nsAtZealotId.split(ZealotConst.SP_AT);
if (arr.length != LEN) {
throw new ValidFailException("nsAtZealotId参数的值必须是xml文件中的 nameSpace + '@@' + zealotId 节点的值,"
+ "如:'student@@queryStudentById'.其中student为nameSpace, queryStudentById为XML文件中SQL的zealotId.");
}
return getSqlInfo(arr[0], arr[1], paramObj);
}
|
python
|
def setWorkingPlayAreaSize(self, sizeX, sizeZ):
"""Sets the Play Area in the working copy."""
fn = self.function_table.setWorkingPlayAreaSize
fn(sizeX, sizeZ)
|
python
|
def fill_missing_fields(self, data, columns):
""" This method fills with 0's missing fields
:param data: original Pandas dataframe
:param columns: list of columns to be filled in the DataFrame
:type data: pandas.DataFrame
:type columns: list of strings
:returns: Pandas dataframe with missing fields filled with 0's
:rtype: pandas.DataFrame
"""
for column in columns:
if column not in data.columns:
data[column] = scipy.zeros(len(data))
return data
|
python
|
def get_services_supported(self):
"""Return a ServicesSupported bit string based in introspection, look
for helper methods that match confirmed and unconfirmed services."""
if _debug: Application._debug("get_services_supported")
services_supported = ServicesSupported()
# look through the confirmed services
for service_choice, service_request_class in confirmed_request_types.items():
service_helper = "do_" + service_request_class.__name__
if hasattr(self, service_helper):
service_supported = ConfirmedServiceChoice._xlate_table[service_choice]
services_supported[service_supported] = 1
# look through the unconfirmed services
for service_choice, service_request_class in unconfirmed_request_types.items():
service_helper = "do_" + service_request_class.__name__
if hasattr(self, service_helper):
service_supported = UnconfirmedServiceChoice._xlate_table[service_choice]
services_supported[service_supported] = 1
# return the bit list
return services_supported
|
java
|
public final int compare(final Activation existing,
final Activation adding) {
final int s1 = existing.getSalience();
final int s2 = adding.getSalience();
if ( s1 > s2 ) {
return 1;
} else if ( s1 < s2 ) {
return -1;
}
return (int) (existing.getRule().getLoadOrder() - adding.getRule().getLoadOrder());
}
|
python
|
def FromReplica(self, replica):
"""
Get AccountState object from a replica.
Args:
replica (obj): must have ScriptHash, IsFrozen, Votes and Balances members.
Returns:
AccountState:
"""
return AccountState(replica.ScriptHash, replica.IsFrozen, replica.Votes, replica.Balances)
|
java
|
private JSONObject setInternal( String key, Object value, JsonConfig jsonConfig ) {
return _setInternal( key, processValue( key, value, jsonConfig ), jsonConfig );
}
|
python
|
def to_dict(self, omit=()):
"""
Return a (shallow) copy of self cast to a dictionary,
optionally omitting some key/value pairs.
"""
result = self.__dict__.copy()
for key in omit:
if key in result:
del result[key]
return result
|
java
|
private static void checkExtraFields(JSTuple tuple, int startCol, int count) throws JMFSchemaViolationException {
for (int i = startCol; i < count; i++) {
JMFType field = tuple.getField(i);
if (field instanceof JSVariant) {
JMFType firstCase = ((JSVariant)field).getCase(0);
if (firstCase instanceof JSTuple)
if (((JSTuple)firstCase).getFieldCount() == 0)
continue;
}
throw new JMFSchemaViolationException(field.getFeatureName() + " not defaulting variant");
}
}
|
python
|
def insert(self, index, option):
"""
Insert a new `option` in the Combo at `index`.
:param int option:
The index of where to insert the option.
:param string option:
The option to insert into to the Combo.
"""
option = str(option)
self._options.insert(index, option)
# if this is the first option, set it.
if len(self._options) == 1:
self.value = option
self._refresh_options()
|
java
|
protected synchronized IndexWriter getIndexWriter() throws IOException
{
if (indexReader != null)
{
indexReader.close();
log.debug("closing IndexReader.");
indexReader = null;
}
if (indexWriter == null)
{
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
config.setSimilarity(similarity);
if (config.getMergePolicy() instanceof LogMergePolicy)
{
((LogMergePolicy)config.getMergePolicy()).setUseCompoundFile(useCompoundFile);
}
else if (config.getMergePolicy() instanceof TieredMergePolicy)
{
((TieredMergePolicy)config.getMergePolicy()).setUseCompoundFile(useCompoundFile);
}
else
{
log.error("Can't set \"UseCompoundFile\". Merge policy is not an instance of LogMergePolicy. ");
}
indexWriter = new IndexWriter(directory, config);
setUseCompoundFile(useCompoundFile);
indexWriter.setInfoStream(STREAM_LOGGER);
}
return indexWriter;
}
|
java
|
public static PropertyDocument makePropertyDocument(
PropertyIdValue propertyId, List<MonolingualTextValue> labels,
List<MonolingualTextValue> descriptions,
List<MonolingualTextValue> aliases,
List<StatementGroup> statementGroups, DatatypeIdValue datatypeId) {
return makePropertyDocument(propertyId, labels, descriptions, aliases,
statementGroups, datatypeId, 0);
}
|
python
|
def complete(self):
"""
Consider a transcript complete if it has start and stop codons and
a coding sequence whose length is divisible by 3
"""
return (
self.contains_start_codon and
self.contains_stop_codon and
self.coding_sequence is not None and
len(self.coding_sequence) % 3 == 0
)
|
python
|
def isglob(value):
"""
Windows non traduce automaticamente i wildchars così lo facciamo
a mano tramite glob.
:param value: Espressione glob per la lista dei files.
:type value: str
"""
if os.name == 'nt':
if isinstance(value, basestring):
value = glob.glob(value)
return value
|
java
|
public ListAccountSasResponseInner listAccountSAS(String resourceGroupName, String accountName, AccountSasParameters parameters) {
return listAccountSASWithServiceResponseAsync(resourceGroupName, accountName, parameters).toBlocking().single().body();
}
|
python
|
def middle(self):
""" Returns the middle point of the bounding box
:return: middle point
:rtype: (float, float)
"""
return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2
|
python
|
def input_identity(interface = TerminalInterface()):
"""Get the full name, email address and SMTP information from the user."""
while True:
identity = interface.input_fields("""
In order to send your files via email, I need to get your name and
email address you will be using to send the files.""",
( 'name', 'Your full name', 'string' ),
( 'email', 'Your email address', 'string' ))
try:
(localpart, hostname) = identity['email'].split('@')
break
except ValueError:
interface.error("""
I couldn't understand the email address you entered, please try
again.""")
while True:
# Configure the SMTP information
smtp_details = interface.input_fields("""
I need details of the SMTP server used to send email for your email
address '%s'. These values can be obtained from the administrators of
your email account.
Most of the time, the default options should suffice if you are
using a free email provider such as GMail.""" % identity['email'],
( 'host', 'The SMTP server hostname', 'string', 'smtp.' + hostname),
( 'port', 'The SMTP server port', 'integer', 465),
( 'use_ssl', 'Use SSL to connect', 'boolean', True),
( 'use_tls', 'Use TLS after connecting', 'boolean', False),
( 'use_auth', 'Use a username/password to log in', 'boolean', True)
)
if smtp_details['use_auth']:
credentials = interface.input_fields("""
I need the username and password you use to log into the SMTP
server, if you provide a blank password, I'll assume you want me to
ask you each time I try to send an email for your password. This is
a more secure option but may be tiresome.""",
( 'username', 'Your username', 'string', localpart),
( 'password', 'Your password', 'password' ))
if credentials['password'] == '':
credentials['password'] = None
smtp_details['username'] = credentials['username']
smtp_details['password'] = credentials['password']
new_identity = Identity(identity['name'], identity['email'], **smtp_details)
# Ask if we want to send a test email.
interface.new_section()
interface.message("""I can try sending a test email to yourself with
all the SMTP settings you've given me. This is generally a good idea
because if we correct any mistakes now, you don't need to correct them
when you want to send a file.""")
if interface.input_boolean('Try sending a test email?', default=True):
if new_identity.send_test_email():
return new_identity
interface.message("""Sending the test email failed. You can go back
and try re-entering your SMTP server details now if you wish.""")
if not interface.input_boolean('Re-enter SMTP server details', default=True):
return new_identity
|
python
|
def parameterized_expectations(model, verbose=False, initial_dr=None,
pert_order=1, with_complementarities=True,
grid={}, distribution={},
maxit=100, tol=1e-8, inner_maxit=10,
direct=False):
'''
Find global solution for ``model`` via parameterized expectations.
Controls must be expressed as a direct function of equilibrium objects.
Algorithm iterates over the expectations function in the arbitrage equation.
Parameters:
----------
model : NumericModel
``dtcscc`` model to be solved
verbose : boolean
if True, display iterations
initial_dr : decision rule
initial guess for the decision rule
pert_order : {1}
if no initial guess is supplied, the perturbation solution at order
``pert_order`` is used as initial guess
grid : grid options
distribution : distribution options
maxit : maximum number of iterations
tol : tolerance criterium for successive approximations
inner_maxit : maximum number of iteration for inner solver
direct : if True, solve with direct method. If false, solve indirectly
Returns
-------
decision rule :
approximated solution
'''
t1 = time.time()
g = model.functions['transition']
h = model.functions['expectation']
d = model.functions['direct_response']
f = model.functions['arbitrage_exp'] # f(s, x, z, p, out)
parms = model.calibration['parameters']
if initial_dr is None:
if pert_order == 1:
initial_dr = approximate_controls(model)
if pert_order > 1:
raise Exception("Perturbation order > 1 not supported (yet).")
approx = model.get_grid(**grid)
grid = approx.grid
interp_type = approx.interpolation
dr = create_interpolator(approx, interp_type)
expect = create_interpolator(approx, interp_type)
distrib = model.get_distribution(**distribution)
nodes, weights = distrib.discretize()
N = grid.shape[0]
z = np.zeros((N, len(model.symbols['expectations'])))
x_0 = initial_dr(grid)
x_0 = x_0.real # just in case ...
h_0 = h(grid, x_0, parms)
it = 0
err = 10
err_0 = 10
verbit = True if verbose == 'full' else False
if with_complementarities is True:
lbfun = model.functions['controls_lb']
ubfun = model.functions['controls_ub']
lb = lbfun(grid, parms)
ub = ubfun(grid, parms)
else:
lb = None
ub = None
if verbose:
headline = '|{0:^4} | {1:10} | {2:8} | {3:8} |'
headline = headline.format('N', ' Error', 'Gain', 'Time')
stars = '-'*len(headline)
print(stars)
print(headline)
print(stars)
# format string for within loop
fmt_str = '|{0:4} | {1:10.3e} | {2:8.3f} | {3:8.3f} |'
while err > tol and it <= maxit:
it += 1
t_start = time.time()
# dr.set_values(x_0)
expect.set_values(h_0)
# evaluate expectation over the future state
z[...] = 0
for i in range(weights.shape[0]):
e = nodes[i, :]
S = g(grid, x_0, e, parms)
z += weights[i]*expect(S)
if direct is True:
# Use control as direct function of arbitrage equation
new_x = d(grid, z, parms)
if with_complementarities is True:
new_x = np.minimum(new_x, ub)
new_x = np.maximum(new_x, lb)
else:
# Find control by solving arbitrage equation
def fun(x): return f(grid, x, z, parms)
sdfun = SerialDifferentiableFunction(fun)
if with_complementarities is True:
[new_x, nit] = ncpsolve(sdfun, lb, ub, x_0, verbose=verbit,
maxit=inner_maxit)
else:
[new_x, nit] = serial_newton(sdfun, x_0, verbose=verbit)
new_h = h(grid, new_x, parms)
# update error
err = (abs(new_h - h_0).max())
# Update guess for decision rule and expectations function
x_0 = new_x
h_0 = new_h
# print error infomation if `verbose`
err_SA = err/err_0
err_0 = err
t_finish = time.time()
elapsed = t_finish - t_start
if verbose:
print(fmt_str.format(it, err, err_SA, elapsed))
if it == maxit:
import warnings
warnings.warn(UserWarning("Maximum number of iterations reached"))
# compute final fime and do final printout if `verbose`
t2 = time.time()
if verbose:
print(stars)
print('Elapsed: {} seconds.'.format(t2 - t1))
print(stars)
# Interpolation for the decision rule
dr.set_values(x_0)
return dr
|
python
|
def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False):
'''Pretty-print the matrix.'''
return '[{0}]'.format("\n ".join([(str(i) if label_columns else '') + vector_str(a, decimal_places, print_zero) for i, a in enumerate(p)]))
|
java
|
public Subscription changeOfferChangeCaptureDateAndRefund( String subscription, Offer offer ) {
return changeOfferChangeCaptureDateAndRefund( new Subscription( subscription ), offer );
}
|
java
|
private static List<Class<?>> getAncestorClasses(Object o, Predicate<? super Class<?>> predicate) {
if (o == null) {
return Collections.emptyList();
}
List<Class<?>> matches = new ArrayList<>();
Set<Class<?>> seen = new HashSet<>();
Queue<Class<?>> queue = new LinkedList<>();
queue.add(o.getClass());
while (!queue.isEmpty()) {
Class<?> clazz = queue.remove();
if (predicate.test(clazz)) {
matches.add(clazz);
}
seen.add(clazz);
if (clazz.getSuperclass() != null && !seen.contains(clazz.getSuperclass())) {
queue.add(clazz.getSuperclass());
}
for (Class<?> iface : clazz.getInterfaces()) {
if (!seen.contains(iface)) {
queue.add(iface);
}
}
}
return matches;
}
|
java
|
public static boolean is_yay(String str)
{
if (is_yan(str) || is_vargiya5(str) || is_vargiya4(str) || is_vargiya3(str) || is_vargiya2(str) || is_vargiya1(str)) return true;
return false;
}
|
java
|
protected static String printException(final Throwable throwable)
{
if (null == throwable) {
return null;
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(baos);
throwable.printStackTrace(printStream);
String exceptionStr = "";
try {
exceptionStr = baos.toString("UTF-8");
} catch (Exception ex) {
exceptionStr = "Unavailable";
} finally {
closeStream(printStream);
closeStream(baos);
}
return exceptionStr;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.