language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | private static RequestConfig getRequestConfig(Integer readTimeoutInMillis) {
return RequestConfig.custom().setConnectionRequestTimeout(600)
.setConnectTimeout(XianConfig.getIntValue("apache.httpclient.connectTimeout", 600))
.setSocketTimeout(readTimeoutInMillis).build();
} |
python | def findlayer(self, z):
'''
Returns layer-number, layer-type and model-layer-number'''
if z > self.z[0]:
modellayer, ltype = -1, 'above'
layernumber = None
elif z < self.z[-1]:
modellayer, ltype = len(self.layernumber), 'below'
layernumber = None
else:
modellayer = np.argwhere((z <= self.z[:-1]) & (z >= self.z[1:]))[0, 0]
layernumber = self.layernumber[modellayer]
ltype = self.ltype[modellayer]
return layernumber, ltype, modellayer |
java | public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TYPE:
return isSetType();
case COLUMN_PATH:
return isSetColumnPath();
}
throw new IllegalStateException();
} |
java | protected Component newDisclaimerPanel(final String id,
final IModel<HeaderContentListModelBean> model)
{
return new DisclaimerPanel(id, Model.of(model.getObject()));
} |
python | def _get_salt_call(*dirs, **namespaces):
'''
Return salt-call source, based on configuration.
This will include additional namespaces for another versions of Salt,
if needed (e.g. older interpreters etc).
:dirs: List of directories to include in the system path
:namespaces: Dictionary of namespace
:return:
'''
template = '''# -*- coding: utf-8 -*-
import os
import sys
# Namespaces is a map: {namespace: major/minor version}, like {'2016.11.4': [2, 6]}
# Appears only when configured in Master configuration.
namespaces = %namespaces%
# Default system paths alongside the namespaces
syspaths = %dirs%
syspaths.append('py{0}'.format(sys.version_info[0]))
curr_ver = (sys.version_info[0], sys.version_info[1],)
namespace = ''
for ns in namespaces:
if curr_ver == tuple(namespaces[ns]):
namespace = ns
break
for base in syspaths:
sys.path.insert(0, os.path.join(os.path.dirname(__file__),
namespace and os.path.join(namespace, base) or base))
if __name__ == '__main__':
from salt.scripts import salt_call
salt_call()
'''
for tgt, cnt in [('%dirs%', dirs), ('%namespaces%', namespaces)]:
template = template.replace(tgt, salt.utils.json.dumps(cnt))
return salt.utils.stringutils.to_bytes(template) |
java | private void addPostParams(final Request request) {
if (attributes != null) {
request.addPostParam("Attributes", attributes);
}
if (dateCreated != null) {
request.addPostParam("DateCreated", dateCreated.toString());
}
if (dateUpdated != null) {
request.addPostParam("DateUpdated", dateUpdated.toString());
}
} |
java | static Document.OutputSettings outputSettings(Node node) {
Document owner = node.ownerDocument();
return owner != null ? owner.outputSettings() : (new Document("")).outputSettings();
} |
python | def send_empty(self, message):
"""
Eventually remove from the observer list in case of a RST message.
:type message: Message
:param message: the message
:return: the message unmodified
"""
host, port = message.destination
key_token = hash(str(host) + str(port) + str(message.token))
if key_token in self._relations and message.type == defines.Types["RST"]:
del self._relations[key_token]
return message |
python | def max_width(*args, **kwargs):
"""Returns formatted text or context manager for textui:puts.
>>> from clint.textui import puts, max_width
>>> max_width('123 5678', 8)
'123 5678'
>>> max_width('123 5678', 7)
'123 \n5678'
>>> with max_width(7):
... puts('123 5678')
'123 \n5678'
"""
args = list(args)
if not args:
args.append(kwargs.get('string'))
args.append(kwargs.get('cols'))
args.append(kwargs.get('separator'))
elif len(args) == 1:
args.append(kwargs.get('cols'))
args.append(kwargs.get('separator'))
elif len(args) == 2:
args.append(kwargs.get('separator'))
string, cols, separator = args
if separator is None:
separator = '\n' # default value
if cols is None:
# cols should be specified vitally
# because string can be specified at textui:puts function
string, cols = cols, string
if string is None:
MAX_WIDTHS.append((cols, separator))
return _max_width_context()
else:
return _max_width_formatter(string, cols, separator) |
java | public FrutillaParser.Scenario scenario(String text) {
mRoot = FrutillaParser.scenario(text);
return (FrutillaParser.Scenario) mRoot;
} |
java | public static Map<String, PreparedAttachment> prepareAttachments(String attachmentsDir,
AttachmentStreamFactory attachmentStreamFactory,
Map<String, Attachment> attachments)
throws AttachmentException {
Map<String, PreparedAttachment> preparedAttachments = new HashMap<String, PreparedAttachment>();
for (Map.Entry<String, Attachment> a : attachments.entrySet()) {
PreparedAttachment pa = AttachmentManager.prepareAttachment(attachmentsDir, attachmentStreamFactory, a.getValue());
preparedAttachments.put(a.getKey(), pa);
}
return preparedAttachments;
} |
java | public void perform(TaskRequest req, TaskResponse res) {
HttpServletResponse sres = (HttpServletResponse) response.evaluate(req, res);
String rsc = (String) resource.evaluate(req, res);
try {
// Send the redirect (HTTP status code 302)
sres.sendRedirect(rsc);
} catch (Throwable t) {
String msg = "Error redirecting to the specified resource: " + rsc;
throw new RuntimeException(msg, t);
}
} |
python | def insert_one(self, doc, *args, **kwargs):
"""
Inserts one document into the collection
If contains '_id' key it is used, else it is generated.
:param doc: the document
:return: InsertOneResult
"""
if self.table is None:
self.build_table()
if not isinstance(doc, dict):
raise ValueError(u'"doc" must be a dict')
_id = doc[u'_id'] = doc.get('_id') or generate_id()
bypass_document_validation = kwargs.get('bypass_document_validation')
if bypass_document_validation is True:
# insert doc without validation of duplicated `_id`
eid = self.table.insert(doc)
else:
existing = self.find_one({'_id': _id})
if existing is None:
eid = self.table.insert(doc)
else:
raise DuplicateKeyError(
u'_id:{0} already exists in collection:{1}'.format(
_id, self.tablename
)
)
return InsertOneResult(eid=eid, inserted_id=_id) |
java | private void recycleByLayoutStateExpose(RecyclerView.Recycler recycler, LayoutState layoutState) {
if (!layoutState.mRecycle) {
return;
}
if (layoutState.mLayoutDirection == LayoutState.LAYOUT_START) {
recycleViewsFromEndExpose(recycler, layoutState.mScrollingOffset);
} else {
recycleViewsFromStartExpose(recycler, layoutState.mScrollingOffset);
}
} |
python | def get_smart_contract(self, hex_contract_address: str, is_full: bool = False) -> dict:
"""
This interface is used to get the information of smart contract based on the specified hexadecimal hash value.
:param hex_contract_address: str, a hexadecimal hash value.
:param is_full:
:return: the information of smart contract in dictionary form.
"""
if not isinstance(hex_contract_address, str):
raise SDKException(ErrorCode.param_err('a hexadecimal contract address is required.'))
if len(hex_contract_address) != 40:
raise SDKException(ErrorCode.param_err('the length of the contract address should be 40 bytes.'))
payload = self.generate_json_rpc_payload(RpcMethod.GET_SMART_CONTRACT, [hex_contract_address, 1])
response = self.__post(self.__url, payload)
if is_full:
return response
return response['result'] |
java | @Override public void writeTo(DataOutput out) throws IOException {
byte leading=0;
if(dest != null)
leading=Util.setFlag(leading, DEST_SET);
if(sender != null)
leading=Util.setFlag(leading, SRC_SET);
if(buf != null)
leading=Util.setFlag(leading, BUF_SET);
// 1. write the leading byte first
out.write(leading);
// 2. the flags (e.g. OOB, LOW_PRIO), skip the transient flags
out.writeShort(flags);
// 3. dest_addr
if(dest != null)
Util.writeAddress(dest, out);
// 4. src_addr
if(sender != null)
Util.writeAddress(sender, out);
// 5. headers
Header[] hdrs=this.headers;
int size=Headers.size(hdrs);
out.writeShort(size);
if(size > 0) {
for(Header hdr : hdrs) {
if(hdr == null)
break;
out.writeShort(hdr.getProtId());
writeHeader(hdr, out);
}
}
// 6. buf
if(buf != null) {
out.writeInt(length);
out.write(buf, offset, length);
}
} |
python | def Storage_getUsageAndQuota(self, origin):
"""
Function path: Storage.getUsageAndQuota
Domain: Storage
Method name: getUsageAndQuota
Parameters:
Required arguments:
'origin' (type: string) -> Security origin.
Returns:
'usage' (type: number) -> Storage usage (bytes).
'quota' (type: number) -> Storage quota (bytes).
'usageBreakdown' (type: array) -> Storage usage per type (bytes).
Description: Returns usage and quota in bytes.
"""
assert isinstance(origin, (str,)
), "Argument 'origin' must be of type '['str']'. Received type: '%s'" % type(
origin)
subdom_funcs = self.synchronous_command('Storage.getUsageAndQuota',
origin=origin)
return subdom_funcs |
java | public static long longValue(String key, long defaultValue) {
String value = System.getProperty(key);
long longValue = defaultValue;
if (value != null) {
try {
longValue = Long.parseLong(value);
} catch (NumberFormatException e) {
LOG.warning(e, "Ignoring invalid long system propert: ''{0}'' = ''{1}''", key, value);
}
}
return longValue;
} |
java | @Override
public XMLObject unmarshall(Element domElement) throws UnmarshallingException {
Document newDocument = null;
Node childNode = domElement.getFirstChild();
while (childNode != null) {
if (childNode.getNodeType() != Node.TEXT_NODE) {
// We skip everything except for a text node.
log.info("Ignoring node {} - it is not a text node", childNode.getNodeName());
}
else {
newDocument = parseContents((Text) childNode, domElement);
if (newDocument != null) {
break;
}
}
childNode = childNode.getNextSibling();
}
return super.unmarshall(newDocument != null ? newDocument.getDocumentElement() : domElement);
} |
python | def get_state_id_for_port(port):
"""This method returns the state ID of the state containing the given port
:param port: Port to check for containing state ID
:return: State ID of state containing port
"""
parent = port.parent
from rafcon.gui.mygaphas.items.state import StateView
if isinstance(parent, StateView):
return parent.model.state.state_id |
python | def text_channels(self):
"""List[:class:`TextChannel`]: A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r |
python | def bit_size(self):
"""
:return:
The bit size of the private key, as an integer
"""
if self._bit_size is None:
if self.algorithm == 'rsa':
prime = self['private_key'].parsed['modulus'].native
elif self.algorithm == 'dsa':
prime = self['private_key_algorithm']['parameters']['p'].native
elif self.algorithm == 'ec':
prime = self['private_key'].parsed['private_key'].native
self._bit_size = int(math.ceil(math.log(prime, 2)))
modulus = self._bit_size % 8
if modulus != 0:
self._bit_size += 8 - modulus
return self._bit_size |
java | public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method method,
Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
return getRepeatableAnnotation((AnnotatedElement) resolvedMethod, containerAnnotationType, annotationType);
} |
java | public static int[] compressOneBlock(int[] inputBlock, int bits,
int blockSize) {
int[] expAux = new int[blockSize * 2];
int maxCompBitSize = HEADER_SIZE + blockSize
* (MAX_BITS + MAX_BITS + MAX_BITS) + 32;
int[] tmpCompressedBlock = new int[(maxCompBitSize >>> 5)];
int outputOffset = HEADER_SIZE;
int expUpperBound = 1 << bits;
int expNum = 0;
for (int elem : inputBlock) {
if (elem >= expUpperBound) {
expNum++;
}
}
int expIndex = 0;
// compress the b-bit slots
for (int i = 0; i < blockSize; ++i) {
if (inputBlock[i] < expUpperBound) {
writeBits(tmpCompressedBlock, inputBlock[i],
outputOffset, bits);
} else // exp
{
// store the lower bits-bits of the exception
writeBits(tmpCompressedBlock, inputBlock[i]
& MASK[bits], outputOffset, bits);
// write the position of exception
expAux[expIndex] = i;
// write the higher 32-bits bits of the
// exception
expAux[expIndex + expNum] = (inputBlock[i] >>> bits)
& MASK[32 - bits];
expIndex++;
}
outputOffset += bits;
}
// the first int in the compressed block stores the value of b
// and the number of exceptions
// tmpCompressedBlock[0] = ((bits & MASK[POSSIBLE_B_BITS]) <<
// (31-POSSIBLE_B_BITS)) | (expNum & MASK[31-POSSIBLE_B_BITS]);
tmpCompressedBlock[0] = ((bits & MASK[10]) << 10)
| (expNum & 0x3ff);
tmpCompressedBlock[1] = inputBlock[blockSize - 1];
// compress exceptions
if (expNum > 0) {
int compressedBitSize = compressBlockByS16(
tmpCompressedBlock, outputOffset, expAux,
expNum * 2);
outputOffset += compressedBitSize;
}
// discard the redundant parts in the tmpCompressedBlock
int compressedSizeInInts = (outputOffset + 31) >>> 5;
int[] compBlock;
compBlock = new int[compressedSizeInInts];
System.arraycopy(tmpCompressedBlock, 0, compBlock, 0,
compressedSizeInInts);
return compBlock;
} |
java | public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch)
throws org.xml.sax.SAXException
{
ch.characters((char[])m_obj, m_start, m_length);
} |
java | public void validateWithDtd(String filename, String dtdPath, String docType) throws IOException {
try (InputStream xmlStream = this.getClass().getResourceAsStream(filename)) {
if (xmlStream == null) {
throw new IOException("Not found in classpath: " + filename);
}
try {
String xml = StringTools.readStream(xmlStream, "utf-8");
validateInternal(xml, dtdPath, docType);
} catch (Exception e) {
throw new IOException("Cannot load or parse '" + filename + "'", e);
}
}
} |
python | def import_model(model_file):
"""Imports the supplied ONNX model file into MXNet symbol and parameters.
Parameters
----------
model_file : ONNX model file name
Returns
-------
sym : mx.symbol
Compatible mxnet symbol
params : dict of str to mx.ndarray
Dict of converted parameters stored in mx.ndarray format
"""
graph = GraphProto()
# loads model file and returns ONNX protobuf object
model_proto = onnx.load(model_file)
sym, params = graph.from_onnx(model_proto.graph)
return sym, params |
java | @Override
public DBConnection stage1ConnectKAMStore(String jdbcUrl, String user,
String pass) throws DBConnectionFailure {
try {
return ds.dbConnection(jdbcUrl, user, pass);
} catch (SQLException e) {
// rethrow as fatal exception since we couldn't connect to KAMStore
throw new DBConnectionFailure(jdbcUrl, e.getMessage(), e);
}
} |
java | public static <T> int detectLastIndex(List<T> list, Predicate<? super T> predicate)
{
if (list instanceof RandomAccess)
{
return RandomAccessListIterate.detectLastIndex(list, predicate);
}
int size = list.size();
int i = size - 1;
ListIterator<T> reverseIterator = list.listIterator(size);
while (reverseIterator.hasPrevious())
{
if (predicate.accept(reverseIterator.previous()))
{
return i;
}
i--;
}
return -1;
} |
java | private long[] getRowAddressesFromHeader( ByteBuffer header ) {
/*
* Jump over the no more needed first byte (used in readHeader to define the header size)
*/
byte firstbyte = header.get();
/* Read the data row addresses inside the file */
long[] adrows = new long[fileWindow.getRows() + 1];
if (firstbyte == 4) {
for( int i = 0; i <= fileWindow.getRows(); i++ ) {
adrows[i] = header.getInt();
}
} else if (firstbyte == 8) {
for( int i = 0; i <= fileWindow.getRows(); i++ ) {
adrows[i] = header.getLong();
}
} else {
// problems
}
return adrows;
} |
java | protected void writeTimedOut(ChannelHandlerContext ctx) throws Exception {
if (!closed) {
ctx.fireExceptionCaught(WriteTimeoutException.INSTANCE);
ctx.close();
closed = true;
}
} |
java | @Override
protected void preparePaintComponent(final Request request) {
super.preparePaintComponent(request);
if (Cache.getCache().get(DATA_KEY) != null) {
poller.disablePoll();
}
} |
python | def _vector(x, type='row'):
"""Convert an object to a row or column vector."""
if isinstance(x, (list, tuple)):
x = np.array(x, dtype=np.float32)
elif not isinstance(x, np.ndarray):
x = np.array([x], dtype=np.float32)
assert x.ndim == 1
if type == 'column':
x = x[:, None]
return x |
java | private int[] convertBatch(int[] batch) {
int[] conv = new int[batch.length];
for (int i=0; i<batch.length; i++) {
conv[i] = sample[batch[i]];
}
return conv;
} |
python | def topological_sorting(nodes, relations):
'''An implementation of Kahn's algorithm.
'''
ret = []
nodes = set(nodes) | _nodes(relations)
inc = _incoming(relations)
out = _outgoing(relations)
free = _free_nodes(nodes, inc)
while free:
n = free.pop()
ret.append(n)
out_n = list(out[n])
for m in out_n:
out[n].remove(m)
inc[m].remove(n)
if _is_free(m, inc):
free.add(m)
if not all(_is_free(node, inc) and _is_free(node, out) for node in nodes):
raise ValueError("Cycle detected")
return ret |
java | protected void checkLimit() {
synchronized (this.getSyncObject()) {
if (this.byteLimit != -1 && this.traceLogfile != null && this.traceLogfile.length() > this.byteLimit) {
close();
int pos = this.traceLogfile.getAbsolutePath().lastIndexOf('\u002e');
String splitFilename = this.traceLogfile.getAbsolutePath().substring(0, pos) + "." + (++this.counter) + ".log";
File splitFile = new File(splitFilename);
if (splitFile.exists()) {
if (!splitFile.delete())
System.err.printf("WARNING: Couldn't delete old file: %s%n", splitFile.getName());
}
this.traceLogfile.renameTo(splitFile);
open();
}
}
} |
python | def checkUserAccess(self):
""" Checks if the current user has granted access to this worksheet.
Returns False if the user has no access, otherwise returns True
"""
# Deny access to foreign analysts
allowed = True
pm = getToolByName(self, "portal_membership")
member = pm.getAuthenticatedMember()
analyst = self.getAnalyst().strip()
if analyst != _c(member.getId()):
roles = member.getRoles()
restrict = 'Manager' not in roles \
and 'LabManager' not in roles \
and 'LabClerk' not in roles \
and 'RegulatoryInspector' not in roles \
and self.bika_setup.getRestrictWorksheetUsersAccess()
allowed = not restrict
return allowed |
java | public List<GeneratorOutput> getGenerateOutput(Filer filer) throws IOException
{
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("intf", this); // the control interface
map.put("bean", _bean);
ArrayList<GeneratorOutput> genList = new ArrayList<GeneratorOutput>();
//
// the ControlBean MANIFEST.MF section
//
Writer manifestWriter = filer.createTextFile(Filer.Location.CLASS_TREE, _bean.getPackage(),
new File(_bean.getShortName() + ".class.manifest"),
null);
GeneratorOutput beanManifest =
new GeneratorOutput(manifestWriter,
"org/apache/beehive/controls/runtime/generator/ControlManifest.vm",
map);
genList.add(beanManifest);
return genList;
} |
python | def saml_name_id_format_to_hash_type(name_format):
"""
Translate pySAML2 name format to satosa format
:type name_format: str
:rtype: satosa.internal_data.UserIdHashType
:param name_format: SAML2 name format
:return: satosa format
"""
msg = "saml_name_id_format_to_hash_type is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
name_id_format_to_hash_type = {
NAMEID_FORMAT_TRANSIENT: UserIdHashType.transient,
NAMEID_FORMAT_PERSISTENT: UserIdHashType.persistent,
NAMEID_FORMAT_EMAILADDRESS: UserIdHashType.emailaddress,
NAMEID_FORMAT_UNSPECIFIED: UserIdHashType.unspecified,
}
return name_id_format_to_hash_type.get(
name_format, UserIdHashType.transient
) |
python | def assert_headers(context):
"""
:type context: behave.runner.Context
"""
expected_headers = [(k, v) for k, v in row_table(context).items()]
request = httpretty.last_request()
actual_headers = request.headers.items()
for expected_header in expected_headers:
assert_in(expected_header, actual_headers) |
python | def is_tagged(required_tags, has_tags):
"""Checks if tags match"""
if not required_tags and not has_tags:
return True
elif not required_tags:
return False
found_tags = []
for tag in required_tags:
if tag in has_tags:
found_tags.append(tag)
return len(found_tags) == len(required_tags) |
java | public CassandraJavaRDD<R> toEmptyCassandraRDD() {
CassandraRDD<R> newRDD = rdd().toEmptyCassandraRDD();
return wrap(newRDD);
} |
java | @Override
public com.liferay.commerce.account.model.CommerceAccount addCommerceAccount(
com.liferay.commerce.account.model.CommerceAccount commerceAccount) {
return _commerceAccountLocalService.addCommerceAccount(commerceAccount);
} |
python | def _inner_dataset_template(cls, dataset):
"""
Returns a Dataset template used as a wrapper around the data
contained within the multi-interface dataset.
"""
from . import Dataset
vdims = dataset.vdims if getattr(dataset, 'level', None) is None else []
return Dataset(dataset.data[0], datatype=cls.subtypes,
kdims=dataset.kdims, vdims=vdims) |
java | public static boolean hasFOPInstalled() {
try {
Class<?> c1 = Class.forName("org.apache.fop.svg.PDFTranscoder");
Class<?> c2 = Class.forName("org.apache.fop.render.ps.PSTranscoder");
Class<?> c3 = Class.forName("org.apache.fop.render.ps.EPSTranscoder");
return (c1 != null) && (c2 != null) && (c3 != null);
}
catch(ClassNotFoundException e) {
return false;
}
} |
java | @Override
@Transactional(enabled = false)
public CPMeasurementUnit createCPMeasurementUnit(long CPMeasurementUnitId) {
return cpMeasurementUnitPersistence.create(CPMeasurementUnitId);
} |
python | def create_user(self, username, password, name, email):
"""Create a sub account."""
method = 'POST'
endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username)
body = json.dumps({'username': username, 'password': password,
'name': name, 'email': email, })
return self.client.request(method, endpoint, body) |
java | private static Optional<String> getColumnLocalityGroup(String columnName, Optional<Map<String, Set<String>>> groups)
{
if (groups.isPresent()) {
for (Map.Entry<String, Set<String>> group : groups.get().entrySet()) {
if (group.getValue().contains(columnName.toLowerCase(Locale.ENGLISH))) {
return Optional.of(group.getKey());
}
}
}
return Optional.empty();
} |
python | def select(self, name_or_index):
"""Locate a dataset.
Args::
name_or_index dataset name or index number
Returns::
SDS instance for the dataset
C library equivalent : SDselect
"""
if isinstance(name_or_index, type(1)):
idx = name_or_index
else:
try:
idx = self.nametoindex(name_or_index)
except HDF4Error:
raise HDF4Error("select: non-existent dataset")
id = _C.SDselect(self._id, idx)
_checkErr('select', id, "cannot execute")
return SDS(self, id) |
java | public FacesConfigFlowDefinitionViewType<FacesConfigFlowDefinitionType<T>> getOrCreateView()
{
List<Node> nodeList = childNode.get("view");
if (nodeList != null && nodeList.size() > 0)
{
return new FacesConfigFlowDefinitionViewTypeImpl<FacesConfigFlowDefinitionType<T>>(this, "view", childNode, nodeList.get(0));
}
return createView();
} |
java | public BoxError getAsBoxError() {
try {
BoxError error = new BoxError();
error.createFromJson(getResponse());
return error;
} catch (Exception e) {
return null;
}
} |
java | private void validateData( )
{
boolean isValid = ( m_queryTextField != null &&
getQueryText() != null && getQueryText().trim().length() > 0 );
if( isValid )
setMessage( DEFAULT_MESSAGE );
else
setMessage( "Requires input value.", ERROR );
setPageComplete( isValid );
} |
java | public void setFiducial( double x0 , double y0 , double x1 , double y1 ,
double x2 , double y2 , double x3 , double y3 ) {
points.get(0).location.set(x0,y0,0);
points.get(1).location.set(x1,y1,0);
points.get(2).location.set(x2,y2,0);
points.get(3).location.set(x3,y3,0);
} |
python | def load_image_imread(file, shape=None, max_range=1.0):
'''
Load image from file like object.
:param file: Image contents
:type file: file like object.
:param shape: shape of output array
e.g. (3, 128, 192) : n_color, height, width.
:type shape: tuple of int
:param float max_range: the value of return array ranges from 0 to `max_range`.
:return: numpy array
'''
img255 = imread(
file) # return value is from zero to 255 (even if the image has 16-bitdepth.)
if len(img255.shape) == 2: # gray image
height, width = img255.shape
if shape is None:
out_height, out_width, out_n_color = height, width, 1
else:
out_n_color, out_height, out_width = shape
assert(out_n_color == 1)
if out_height != height or out_width != width:
# imresize returns 0 to 255 image.
img255 = imresize(img255, (out_height, out_width))
img255 = img255.reshape((out_n_color, out_height, out_width))
elif len(img255.shape) == 3: # RGB image
height, width, n_color = img255.shape
if shape is None:
out_height, out_width, out_n_color = height, width, n_color
else:
out_n_color, out_height, out_width = shape
assert(out_n_color == n_color)
if out_height != height or out_width != width or out_n_color != n_color:
# imresize returns 0 to 255 image.
img255 = imresize(img255, (out_height, out_width, out_n_color))
img255 = img255.transpose(2, 0, 1)
if max_range < 0 or max_range == 255.0:
return img255
else:
return img255 * (max_range / 255.0) |
java | public void waitForDelete() throws InterruptedException {
Waiter waiter = client.waiters().tableNotExists();
try {
waiter.run(new WaiterParameters<DescribeTableRequest>(new DescribeTableRequest(tableName))
.withPollingStrategy(new PollingStrategy(new MaxAttemptsRetryStrategy(25), new FixedDelayStrategy(5))));
} catch (Exception exception) {
throw new IllegalArgumentException("Table " + tableName + " is not deleted.", exception);
}
} |
python | def connect_timeout(self):
""" Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
"""
if self.total is None:
return self._connect
if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
return self.total
return min(self._connect, self.total) |
java | @Override
public CommercePriceListUserSegmentEntryRel create(
long commercePriceListUserSegmentEntryRelId) {
CommercePriceListUserSegmentEntryRel commercePriceListUserSegmentEntryRel =
new CommercePriceListUserSegmentEntryRelImpl();
commercePriceListUserSegmentEntryRel.setNew(true);
commercePriceListUserSegmentEntryRel.setPrimaryKey(commercePriceListUserSegmentEntryRelId);
String uuid = PortalUUIDUtil.generate();
commercePriceListUserSegmentEntryRel.setUuid(uuid);
commercePriceListUserSegmentEntryRel.setCompanyId(companyProvider.getCompanyId());
return commercePriceListUserSegmentEntryRel;
} |
java | public void enableDTD(boolean enable) {
//允许DTD会有XXE漏洞,关于XXE漏洞:https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
if (enable) {
//不允许DTD
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
setFeature("http://xml.org/sax/features/external-general-entities", false);
setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} else {
setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
setFeature("http://xml.org/sax/features/external-general-entities", true);
setFeature("http://xml.org/sax/features/external-parameter-entities", true);
}
} |
java | public void marshall(SanitizationWarning sanitizationWarning, ProtocolMarshaller protocolMarshaller) {
if (sanitizationWarning == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(sanitizationWarning.getAttributeName(), ATTRIBUTENAME_BINDING);
protocolMarshaller.marshall(sanitizationWarning.getElementName(), ELEMENTNAME_BINDING);
protocolMarshaller.marshall(sanitizationWarning.getReason(), REASON_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.GSLT__LINETYPE:
return getLINETYPE();
}
return super.eGet(featureID, resolve, coreType);
} |
java | protected void processIncludes(Map<String, String> mergeProps, URL rootURL, String includeProps) {
if (includeProps == null)
return;
String props[] = includeProps.trim().split("\\s*,\\s*");
for (String pname : props) {
mergeProperties(mergeProps, rootURL, pname);
}
} |
java | public long getDateLastVisitedBy(CmsObject cms, CmsUser user, String resourcePath) throws CmsException {
CmsResource resource = cms.readResource(resourcePath, CmsResourceFilter.ALL);
return m_securityManager.getDateLastVisitedBy(cms.getRequestContext(), getPoolName(), user, resource);
} |
java | public Map<String, String> loadNucleotideStore() throws IOException,
URISyntaxException {
Map<String, String> nucleotides = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
LOG.debug("Loading nucleotide store by Webservice Loader");
LOG.debug(MonomerStoreConfiguration.getInstance().toString());
CloseableHttpResponse response = null;
try {
response =
WSAdapterUtils.getResource(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL());
LOG.debug(response.getStatusLine().toString());
JsonFactory jsonf = new JsonFactory();
InputStream instream = response.getEntity().getContent();
JsonParser jsonParser = jsonf.createJsonParser(instream);
nucleotides = deserializeNucleotideStore(jsonParser);
LOG.debug(nucleotides.size() + " nucleotides loaded");
EntityUtils.consume(response.getEntity());
} catch (ClientProtocolException e) {
/* read file */
JsonFactory jsonf = new JsonFactory();
InputStream instream =
new FileInputStream(new File(MonomerStoreConfiguration.getInstance().getWebserviceNucleotidesFullURL()));
JsonParser jsonParser = jsonf.createJsonParser(instream);
nucleotides = deserializeNucleotideStore(jsonParser);
LOG.debug(nucleotides.size() + " nucleotides loaded");
} finally {
if (response != null) {
response.close();
}
}
return nucleotides;
} |
java | @Override
public final void makeEntries(final Map<String, Object> pAddParam,
final IDoc pEntity) throws Exception {
Calendar calCurrYear = Calendar.getInstance(new Locale("en", "US"));
calCurrYear.setTime(getSrvAccSettings().lazyGetAccSettings(pAddParam)
.getCurrentAccYear());
calCurrYear.set(Calendar.MONTH, 0);
calCurrYear.set(Calendar.DAY_OF_MONTH, 1);
calCurrYear.set(Calendar.HOUR_OF_DAY, 0);
calCurrYear.set(Calendar.MINUTE, 0);
calCurrYear.set(Calendar.SECOND, 0);
calCurrYear.set(Calendar.MILLISECOND, 0);
Calendar calDoc = Calendar.getInstance(new Locale("en", "US"));
calDoc.setTime(pEntity.getItsDate());
calDoc.set(Calendar.MONTH, 0);
calDoc.set(Calendar.DAY_OF_MONTH, 1);
calDoc.set(Calendar.HOUR_OF_DAY, 0);
calDoc.set(Calendar.MINUTE, 0);
calDoc.set(Calendar.SECOND, 0);
calDoc.set(Calendar.MILLISECOND, 0);
if (calCurrYear.getTime().getTime() != calDoc.getTime().getTime()) {
throw new ExceptionWithCode(ExceptionWithCode.WRONG_PARAMETER,
"wrong_year");
}
StringBuffer sb = new StringBuffer();
List<AccEntriesSourcesLine> sourcesLines = srvAccSettings
.lazyGetAccSettings(pAddParam).getAccEntriesSources();
java.util.Collections.sort(sourcesLines, this.cmprAccSourcesByType);
int i = 0;
for (AccEntriesSourcesLine sourcesLine : sourcesLines) {
if (sourcesLine.getIsUsed()
&& sourcesLine.getSourceType().equals(pEntity.constTypeCode())) {
String query = lazyGetQuery(sourcesLine.getFileName());
String idName = "ITSID";
if (pEntity.getIdBirth() != null) {
idName = "IDBIRTH";
}
query = query.replace(":IDNAME", idName);
//for foreign document this algorithm is also right:
String strWhereDocId = sourcesLine.getSourceIdName() + " = "
+ pEntity.getItsId().toString();
if (query.contains(":WHEREADD")) {
query = query.replace(":WHEREADD", " and " + strWhereDocId);
} else if (query.contains(":WHERE")) {
query = query.replace(":WHERE", " where " + strWhereDocId);
}
if (i++ > 0) {
sb.append("\nunion all\n\n");
}
sb.append(query);
}
}
String langDef = (String) pAddParam.get("langDef");
DateFormat dateFormat = DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT, new Locale(langDef));
String query = sb.toString();
if (query.trim().length() == 0) {
throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
"there_is_no_accounting_sources");
}
IRecordSet<RS> recordSet = null;
try {
recordSet = getSrvDatabase().retrieveRecords(query);
if (recordSet.moveToFirst()) {
Long itsDateLong = null;
do {
AccountingEntry accEntry = new AccountingEntry();
accEntry.setIdDatabaseBirth(getSrvDatabase().getIdDatabase());
if (itsDateLong == null) {
itsDateLong = pEntity.getItsDate().getTime();
getSrvBalance().handleNewAccountEntry(pAddParam, null, null,
new Date(itsDateLong)); //This is for SrvBalanceStd only!!!
}
Date itsDate = new Date(itsDateLong++);
accEntry.setItsDate(itsDate);
accEntry.setSourceType(pEntity.constTypeCode());
if (pEntity.getIdBirth() != null) { //accounting foreign document
accEntry.setSourceId(pEntity.getIdBirth());
} else {
accEntry.setSourceId(pEntity.getItsId());
}
accEntry.setSourceDatabaseBirth(pEntity.getIdDatabaseBirth());
String accDebitId = recordSet.getString("ACCDEBIT");
Account accDebit = new Account();
accDebit.setItsId(accDebitId);
accEntry.setAccDebit(accDebit);
accEntry.setSubaccDebitType(recordSet.getInteger("SUBACCDEBITTYPE"));
accEntry.setSubaccDebitId(recordSet.getLong("SUBACCDEBITID"));
accEntry.setSubaccDebit(recordSet.getString("SUBACCDEBIT"));
accEntry.setDebit(BigDecimal.valueOf(recordSet.getDouble("DEBIT"))
.setScale(getSrvAccSettings().lazyGetAccSettings(pAddParam)
.getCostPrecision(), getSrvAccSettings()
.lazyGetAccSettings(pAddParam).getRoundingMode()));
String accCreditId = recordSet.getString("ACCCREDIT");
Account accCredit = new Account();
accCredit.setItsId(accCreditId);
accEntry.setAccCredit(accCredit);
accEntry
.setSubaccCreditType(recordSet.getInteger("SUBACCCREDITTYPE"));
accEntry.setSubaccCreditId(recordSet.getLong("SUBACCCREDITID"));
accEntry.setSubaccCredit(recordSet.getString("SUBACCCREDIT"));
accEntry.setCredit(BigDecimal
.valueOf(recordSet.getDouble("CREDIT")).setScale(
getSrvAccSettings().lazyGetAccSettings(pAddParam)
.getCostPrecision(), getSrvAccSettings()
.lazyGetAccSettings(pAddParam).getRoundingMode()));
String docId = pEntity.getItsId().toString();
if (pEntity.getIdBirth() != null) {
docId = pEntity.getIdBirth().toString();
}
String descr = "";
if (pEntity.getDescription() != null) {
descr = " " + pEntity.getDescription();
}
accEntry.setDescription(getSrvI18n().getMsg(pEntity.getClass().
getSimpleName() + "short", langDef) + " #" + pEntity.getIdDatabaseBirth()
+ "-" + docId + ", " + dateFormat.format(pEntity.getItsDate()) + descr);
this.srvOrm.insertEntity(pAddParam, accEntry);
accEntry.setIsNew(false);
} while (recordSet.moveToNext());
}
} finally {
if (recordSet != null) {
recordSet.close();
}
}
pEntity.setHasMadeAccEntries(true);
srvOrm.updateEntity(pAddParam, pEntity);
} |
python | def _decodeTimestamp(byteIter):
""" Decodes a 7-octet timestamp """
dateStr = decodeSemiOctets(byteIter, 7)
timeZoneStr = dateStr[-2:]
return datetime.strptime(dateStr[:-2], '%y%m%d%H%M%S').replace(tzinfo=SmsPduTzInfo(timeZoneStr)) |
python | def checksum(path):
"""Calculcate checksum for a file."""
hasher = hashlib.sha1()
with open(path, 'rb') as stream:
buf = stream.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = stream.read(BLOCKSIZE)
return hasher.hexdigest() |
python | def _chain_forks(elements):
"""Detect whether a sequence of elements leads to a fork of streams"""
# we are only interested in the result, so unwind from the end
for element in reversed(elements):
if element.chain_fork:
return True
elif element.chain_join:
return False
return False |
python | def migrate_value(value):
"""Convert `value` to a new-style value, if necessary and possible.
An "old-style" value is a value that uses any `value` field other than
the `tensor` field. A "new-style" value is a value that uses the
`tensor` field. TensorBoard continues to support old-style values on
disk; this method converts them to new-style values so that further
code need only deal with one data format.
Arguments:
value: A `Summary.Value` object. This argument is not modified.
Returns:
If the `value` is an old-style value for which there is a new-style
equivalent, the result is the new-style value. Otherwise---if the
value is already new-style or does not yet have a new-style
equivalent---the value will be returned unchanged.
:type value: Summary.Value
:rtype: Summary.Value
"""
handler = {
'histo': _migrate_histogram_value,
'image': _migrate_image_value,
'audio': _migrate_audio_value,
'simple_value': _migrate_scalar_value,
}.get(value.WhichOneof('value'))
return handler(value) if handler else value |
python | def construct_survival_curves(hazard_rates, timelines):
"""
Given hazard rates, reconstruct the survival curves
Parameters
----------
hazard_rates: (n,t) array
timelines: (t,) the observational times
Returns
-------
t: survial curves, (n,t) array
"""
cumulative_hazards = cumulative_integral(hazard_rates.values, timelines)
return pd.DataFrame(np.exp(-cumulative_hazards), index=timelines) |
java | @Bean
@ConditionalOnMissingBean({WroManagerFactory.class, ProcessorsFactory.class})
ProcessorsFactory processorsFactory(final Wro4jProperties wro4jProperties) {
final List<ResourcePreProcessor> preProcessors = new ArrayList<>();
if (wro4jProperties.getPreProcessors() != null) {
for (Class<? extends ResourcePreProcessor> c : wro4jProperties.getPreProcessors()) {
preProcessors.add(getBeanOrInstantiateProcessor(c));
}
}
final List<ResourcePostProcessor> postProcessors = new ArrayList<>();
if (wro4jProperties.getPostProcessors() != null) {
for (Class<? extends ResourcePostProcessor> c : wro4jProperties.getPostProcessors()) {
postProcessors.add(getBeanOrInstantiateProcessor(c));
}
}
ProcessorsFactory rv;
if (wro4jProperties.getManagerFactory() != null) {
final Properties properties = new Properties();
if (wro4jProperties.getManagerFactory().getPreProcessors() != null) {
properties.setProperty("preProcessors", wro4jProperties.getManagerFactory().getPreProcessors());
}
if (wro4jProperties.getManagerFactory().getPostProcessors() != null) {
properties.setProperty("postProcessors", wro4jProperties.getManagerFactory().getPostProcessors());
}
rv = new ConfigurableProcessorsFactory();
((ConfigurableProcessorsFactory) rv).setProperties(properties);
}
else if (preProcessors.isEmpty() && postProcessors.isEmpty()) {
rv = new DefaultProcessorsFactory();
}
else {
rv = new SimpleProcessorsFactory();
((SimpleProcessorsFactory) rv).setResourcePreProcessors(preProcessors);
((SimpleProcessorsFactory) rv).setResourcePostProcessors(postProcessors);
}
LOGGER.debug("Using ProcessorsFactory of type '{}'", rv.getClass().getName());
return rv;
} |
python | def check_data_complete(data, parameter_columns):
""" For any parameters specified with edges, make sure edges
don't overlap and don't have any gaps. Assumes that edges are
specified with ends and starts overlapping (but one exclusive and
the other inclusive) so can check that end of previous == start
of current.
If multiple parameters, make sure all combinations of parameters
are present in data."""
param_edges = [p[1:] for p in parameter_columns if isinstance(p, (Tuple, List))] # strip out call column name
# check no overlaps/gaps
for p in param_edges:
other_params = [p_ed[0] for p_ed in param_edges if p_ed != p]
if other_params:
sub_tables = data.groupby(list(other_params))
else:
sub_tables = {None: data}.items()
n_p_total = len(set(data[p[0]]))
for _, table in sub_tables:
param_data = table[[p[0], p[1]]].copy().sort_values(by=p[0])
start, end = param_data[p[0]].reset_index(drop=True), param_data[p[1]].reset_index(drop=True)
if len(set(start)) < n_p_total:
raise ValueError(f'You must provide a value for every combination of {parameter_columns}.')
if len(start) <= 1:
continue
for i in range(1, len(start)):
e = end[i-1]
s = start[i]
if e > s or s == start[i-1]:
raise ValueError(f'Parameter data must not contain overlaps. Parameter {p} '
f'contains overlapping data.')
if e < s:
raise NotImplementedError(f'Interpolation only supported for parameter columns '
f'with continuous bins. Parameter {p} contains '
f'non-continuous bins.') |
java | public List<OrganizationMembership> getOrganizationMembershipByUser(long user_id) {
return complete(submit(req("GET", tmpl("/users/{user_id}/organization_memberships.json").set("user_id", user_id)),
handleList(OrganizationMembership.class, "organization_memberships")));
} |
python | def ctor_args(self):
"""Return arguments for constructing a copy"""
return dict(
config=self._config,
search=self._search,
echo=self._echo,
read_only=self.read_only
) |
python | def _height_and_width(self):
"""Return a tuple of (terminal height, terminal width).
Start by trying TIOCGWINSZ (Terminal I/O-Control: Get Window Size),
falling back to environment variables (LINES, COLUMNS), and returning
(None, None) if those are unavailable or invalid.
"""
# tigetnum('lines') and tigetnum('cols') update only if we call
# setupterm() again.
for descriptor in self._init_descriptor, sys.__stdout__:
try:
return struct.unpack(
'hhhh', ioctl(descriptor, TIOCGWINSZ, '\000' * 8))[0:2]
except IOError:
# when the output stream or init descriptor is not a tty, such
# as when when stdout is piped to another program, fe. tee(1),
# these ioctls will raise IOError
pass
try:
return int(environ.get('LINES')), int(environ.get('COLUMNS'))
except TypeError:
return None, None |
java | public int countTokens() {
int count = 0;
int currpos = currentPosition;
while (currpos < maxPosition) {
currpos = skipDelimiters(currpos);
if (currpos >= maxPosition)
break;
currpos = scanToken(currpos);
count++;
}
return count;
} |
java | private static XmlOptions getXmlOptions() {
if (System.getProperty("runtimeEnv") == null && System.getProperty("mdw.runtime.env") == null)
return new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(2); // avoid errors when running in Designer
String[] xmlOptionsProperties = new String[] { PropertyNames.MDW_TRANSLATOR_XMLBEANS_LOAD_OPTIONS,
PropertyNames.MDW_TRANSLATOR_XMLBEANS_SAVE_OPTIONS };
/**
* First set it up with default compatibility options
*/
xmlOptions = new XmlOptions();
/**
* Next get the options that the user needs from the properties file.
*/
Class<?> xmlOptionsClass = xmlOptions.getClass();
for (int i = 0; i < xmlOptionsProperties.length; i++) {
String property = xmlOptionsProperties[i];
String opt = PropertyManager.getProperty(property);
/**
* Only do reflection if we need to
*/
if (opt != null && !"".equals(opt)) {
try {
String[] propTable = opt.split(",");
for (int j = 0; j < propTable.length; j++) {
String prop = propTable[j];
String[] optTable = prop.split("=");
String option = optTable[0];
String value = null;
Class<?>[] classArray = new Class<?>[] { Object.class };
if (optTable.length > 1) {
// Check for int
value = optTable[1];
classArray = new Class<?>[] { Object.class, Object.class };
boolean gotInteger = true;
try {
Integer.parseInt(value);
}
catch (NumberFormatException e) {
// It's not an integer
gotInteger = false;
}
Method method = xmlOptionsClass.getMethod("put", classArray);
method.invoke(xmlOptions, new Object[] { option,
gotInteger ? Integer.valueOf(value) : value });
}
else {
Method method = xmlOptionsClass.getMethod("put", classArray);
method.invoke(xmlOptions, new Object[] { option });
}
}
}
catch (Exception ex) {
// Just log it
logger.severeException("Unable to set XMLOption " + opt + " due to " + ex.getMessage(), ex);
}
}
}
return xmlOptions;
} |
java | protected final void copyTextNode(final int nodeID, SerializationHandler handler)
throws SAXException
{
if (nodeID != DTM.NULL) {
int dataIndex = m_dataOrQName.elementAt(nodeID);
if (dataIndex >= 0) {
m_chars.sendSAXcharacters(handler,
dataIndex >>> TEXT_LENGTH_BITS,
dataIndex & TEXT_LENGTH_MAX);
} else {
m_chars.sendSAXcharacters(handler, m_data.elementAt(-dataIndex),
m_data.elementAt(-dataIndex+1));
}
}
} |
python | def build_url_field(self, field_name, model_class):
"""
Create a field representing the object's own URL.
"""
field_class = self.serializer_url_field
field_kwargs = rest_framework.serializers.get_url_kwargs(model_class)
field_kwargs.update({"parent_lookup_field": self.get_parent_lookup_field()})
return field_class, field_kwargs |
java | @Override
public void setSubProtocols(String... protocols) {
subProtocols.clear();
Collections.addAll(subProtocols, protocols);
} |
python | def get_basic_logger(level=logging.WARN, scope='reliure'):
""" return a basic logger that print on stdout msg from reliure lib
"""
logger = logging.getLogger(scope)
logger.setLevel(level)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(level)
# create formatter and add it to the handlers
formatter = ColorFormatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(ch)
return logger |
python | def reset(self):
""" Sets initial conditions for the experiment.
"""
self.stepid = 0
for task, agent in zip(self.tasks, self.agents):
task.reset()
agent.module.reset()
agent.history.reset() |
java | @Override
public void eUnset(int featureID)
{
switch (featureID)
{
case SimpleAntlrPackage.UNTIL_ELEMENT__LEFT:
setLeft((RuleElement)null);
return;
case SimpleAntlrPackage.UNTIL_ELEMENT__RIGHT:
setRight((RuleElement)null);
return;
}
super.eUnset(featureID);
} |
python | def prepare_token_request(self, token_url, authorization_response=None,
redirect_url=None, state=None, body='', **kwargs):
"""Prepare a token creation request.
Note that these requests usually require client authentication, either
by including client_id or a set of provider specific authentication
credentials.
:param token_url: Provider token creation endpoint URL.
:param authorization_response: The full redirection URL string, i.e.
the location to which the user was redirected after successfull
authorization. Used to mine credentials needed to obtain a token
in this step, such as authorization code.
:param redirect_url: The redirect_url supplied with the authorization
request (if there was one).
:param state:
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
:param kwargs: Additional parameters to included in the request.
:returns: The prepared request tuple with (url, headers, body).
"""
if not is_secure_transport(token_url):
raise InsecureTransportError()
state = state or self.state
if authorization_response:
self.parse_request_uri_response(
authorization_response, state=state)
self.redirect_url = redirect_url or self.redirect_url
body = self.prepare_request_body(body=body,
redirect_uri=self.redirect_url, **kwargs)
return token_url, FORM_ENC_HEADERS, body |
python | def _to_numeric(val):
"""
Helper function for conversion of various data types into numeric representation.
"""
if isinstance(val, (int, float, datetime.datetime, datetime.timedelta)):
return val
return float(val) |
java | public ChannelHandler[] getServerChannelHandlers() {
PartitionRequestQueue queueOfPartitionQueues = new PartitionRequestQueue();
PartitionRequestServerHandler serverHandler = new PartitionRequestServerHandler(
partitionProvider, taskEventPublisher, queueOfPartitionQueues, creditBasedEnabled);
return new ChannelHandler[] {
messageEncoder,
new NettyMessage.NettyMessageDecoder(!creditBasedEnabled),
serverHandler,
queueOfPartitionQueues
};
} |
python | def expand_curielike(namespaces, curie):
"""Expand a CURIE (or a CURIE-like string with a period instead of colon
as separator) into URIRef. If the provided curie is not a CURIE, return it
unchanged."""
if curie == '':
return None
if sys.version < '3' and not isinstance(curie, type(u'')):
# Python 2 ConfigParser gives raw byte strings
curie = curie.decode('UTF-8') # ...make those into Unicode objects
if curie.startswith('[') and curie.endswith(']'):
# decode SafeCURIE
curie = curie[1:-1]
if ':' in curie:
ns, localpart = curie.split(':', 1)
elif '.' in curie:
ns, localpart = curie.split('.', 1)
else:
return curie
if ns in namespaces:
return URIRef(namespaces[ns].term(localpart))
else:
logging.warning("Unknown namespace prefix %s", ns)
return URIRef(curie) |
python | def en010(self, value=None):
""" Corresponds to IDD Field `en010`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 1.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `en010`
Unit: kJ/kg
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value
"""
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError('value {} need to be of type float '
'for field `en010`'.format(value))
self._en010 = value |
java | protected PermissionModel getPermission(int index) {
if (permissions().isEmpty()) return null;
if ((index) <= permissions().size()) {// avoid accessing index does not exists.
return permissions().get(index);
}
return null;
} |
java | public boolean recordOverride() {
if (!currentInfo.isOverride()) {
currentInfo.setOverride(true);
populated = true;
return true;
} else {
return false;
}
} |
java | public void setAuthorGroup(final SpecTopic authorGroup) {
if (authorGroup == null && this.authorGroup == null) {
return;
} else if (authorGroup == null) {
removeChild(this.authorGroup);
this.authorGroup = null;
} else if (this.authorGroup == null) {
authorGroup.setTopicType(TopicType.AUTHOR_GROUP);
this.authorGroup = new KeyValueNode<SpecTopic>(CommonConstants.CS_AUTHOR_GROUP_TITLE, authorGroup);
appendChild(this.authorGroup, false);
} else {
authorGroup.setTopicType(TopicType.AUTHOR_GROUP);
this.authorGroup.setValue(authorGroup);
}
} |
python | def schedule(self, when=None, action=None, **kwargs):
"""
Schedule an update of this object.
when: The date for the update.
action: if provided it will be looked up
on the implementing class and called with
**kwargs. If action is not provided each k/v pair
in kwargs will be set on self and then self
is saved.
kwargs: any other arguments you would like passed
for this change. Saved as a json object so must cleanly
serialize.
"""
# when is empty or passed, just save it now.
if not when or when <= timezone.now():
self.do_scheduled_update(action, **kwargs)
else:
ctype = ContentType.objects.get_for_model(self.__class__)
Schedule(
content_type=ctype,
object_args=self.get_scheduled_filter_args(),
when=when,
action=action,
json_args=kwargs
).save() |
python | def generate_component_id_namespace_overview(model, components):
"""
Tabulate which MIRIAM databases the component's identifier matches.
Parameters
----------
model : cobra.Model
A cobrapy metabolic model.
components : {"metabolites", "reactions", "genes"}
A string denoting `cobra.Model` components.
Returns
-------
pandas.DataFrame
The index of the table is given by the component identifiers. Each
column corresponds to one MIRIAM database and a Boolean entry
determines whether the annotation matches.
"""
patterns = {
"metabolites": METABOLITE_ANNOTATIONS,
"reactions": REACTION_ANNOTATIONS,
"genes": GENE_PRODUCT_ANNOTATIONS
}[components]
databases = list(patterns)
data = list()
index = list()
for elem in getattr(model, components):
index.append(elem.id)
data.append(tuple(patterns[db].match(elem.id) is not None
for db in databases))
df = pd.DataFrame(data, index=index, columns=databases)
if components != "genes":
# Clean up of the dataframe. Unfortunately the Biocyc patterns match
# broadly. Hence, whenever a Metabolite or Reaction ID matches to any
# DB pattern AND the Biocyc pattern we have to assume that this is a
# false positive.
# First determine all rows in which 'biocyc' and other entries are
# True simultaneously and use this Boolean series to create another
# column temporarily.
df['duplicate'] = df[df['biocyc']].sum(axis=1) >= 2
# Replace all nan values with False
df['duplicate'].fillna(False, inplace=True)
# Use the additional column to index the original dataframe to identify
# false positive biocyc hits and set them to False.
df.loc[df['duplicate'], 'biocyc'] = False
# Delete the additional column
del df['duplicate']
return df |
java | public boolean matches(ServiceType serviceType)
{
if (serviceType == null) return false;
if (equals(serviceType)) return true;
if (isAbstractType())
{
if (serviceType.isAbstractType())
{
if (!getPrincipleTypeName().equals(serviceType.getPrincipleTypeName())) return false;
return getConcreteTypeName().equals(serviceType.getConcreteTypeName());
}
else
{
return false;
}
}
else
{
if (serviceType.isAbstractType())
{
return getPrincipleTypeName().equals(serviceType.getPrincipleTypeName());
}
else
{
return getPrincipleTypeName().equals(serviceType.getPrincipleTypeName());
}
}
} |
java | @Override
public ServerConnector createSecureConnector(Server server, String name, int port,
String sslKeystore, String sslKeystorePassword, String sslKeyPassword,
String host, String sslKeystoreType, String sslKeyAlias,
String trustStore, String trustStorePassword, String trustStoreType,
boolean isClientAuthNeeded, boolean isClientAuthWanted,
List<String> cipherSuitesIncluded, List<String> cipherSuitesExcluded,
List<String> protocolsIncluded, List<String> protocolsExcluded,
Boolean sslRenegotiationAllowed,
String crlPath,
Boolean enableCRLDP,
Boolean validateCerts,
Boolean validatePeerCerts,
Boolean enableOCSP,
String ocspResponderURL,
Boolean checkForwaredHeaders,
String sslKeystoreProvider,
String sslTrustStoreProvider,
String sslProvider) {
// SSL Context Factory for HTTPS and SPDY
SslContextFactory sslContextFactory = new SslContextFactory();
if (null != sslProvider && !"".equals(sslProvider.trim())) {
sslContextFactory.setProvider(sslProvider);
}
sslContextFactory.setKeyStorePath(sslKeystore);
sslContextFactory.setKeyStorePassword(sslKeystorePassword);
sslContextFactory.setKeyManagerPassword(sslKeyPassword);
sslContextFactory.setNeedClientAuth(isClientAuthNeeded);
sslContextFactory.setWantClientAuth(isClientAuthWanted);
sslContextFactory.setEnableCRLDP(enableCRLDP);
sslContextFactory.setValidateCerts(validateCerts);
sslContextFactory.setValidatePeerCerts(validatePeerCerts);
sslContextFactory.setEnableOCSP(enableOCSP);
if ((null != crlPath) && (!"".equals(crlPath))) {
sslContextFactory.setCrlPath(crlPath);
}
if ((null != ocspResponderURL) && (!"".equals(ocspResponderURL))) {
sslContextFactory.setOcspResponderURL(ocspResponderURL);
}
if (sslKeystoreType != null) {
sslContextFactory.setKeyStoreType(sslKeystoreType);
}
if (null != sslKeystoreProvider && (!"".equals(sslKeystoreProvider.trim()))) {
sslContextFactory.setKeyStoreProvider(sslKeystoreProvider);
}
// Java key stores may contain more than one private key entry.
// Specifying the alias tells jetty which one to use.
if ((null != sslKeyAlias) && (!"".equals(sslKeyAlias))) {
sslContextFactory.setCertAlias(sslKeyAlias);
}
// Quite often it is useful to use a certificate trust store other than the JVM default.
if ((null != trustStore) && (!"".equals(trustStore))) {
sslContextFactory.setTrustStorePath(trustStore);
}
if ((null != trustStorePassword) && (!"".equals(trustStorePassword))) {
sslContextFactory.setTrustStorePassword(trustStorePassword);
}
if ((null != trustStoreType) && (!"".equals(trustStoreType))) {
sslContextFactory.setTrustStoreType(trustStoreType);
}
if (null != sslTrustStoreProvider && (!"".equals(sslTrustStoreProvider.trim()))) {
sslContextFactory.setTrustStoreProvider(sslTrustStoreProvider);
}
// In light of well-known attacks against weak encryption algorithms such as RC4,
// it is usefull to be able to include or exclude certain ciphersuites.
// Due to the overwhelming number of cipher suites using regex to specify inclusions
// and exclusions greatly simplifies configuration.
final String[] cipherSuites;
try {
SSLContext context = SSLContext.getDefault();
SSLSocketFactory sf = context.getSocketFactory();
cipherSuites = sf.getSupportedCipherSuites();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to get supported cipher suites.", e);
}
if (cipherSuitesIncluded != null && !cipherSuitesIncluded.isEmpty()) {
final List<String> cipherSuitesToInclude = new ArrayList<>();
for (final String cipherSuite : cipherSuites) {
for (final String includeRegex : cipherSuitesIncluded) {
if (cipherSuite.matches(includeRegex)) {
cipherSuitesToInclude.add(cipherSuite);
}
}
}
sslContextFactory.setIncludeCipherSuites(cipherSuitesToInclude.toArray(new String[cipherSuitesToInclude.size()]));
}
if (cipherSuitesExcluded != null && !cipherSuitesExcluded.isEmpty()) {
final List<String> cipherSuitesToExclude = new ArrayList<>();
for (final String cipherSuite : cipherSuites) {
for (final String excludeRegex : cipherSuitesExcluded) {
if (cipherSuite.matches(excludeRegex)) {
cipherSuitesToExclude.add(cipherSuite);
}
}
}
sslContextFactory.setExcludeCipherSuites(cipherSuitesToExclude.toArray(new String[cipherSuitesToExclude.size()]));
}
// In light of attacks against SSL 3.0 as "POODLE" it is useful to include or exclude
// SSL/TLS protocols as needed.
if ((null != protocolsIncluded) && (!protocolsIncluded.isEmpty())) {
sslContextFactory.setIncludeProtocols(protocolsIncluded.toArray(new String[protocolsIncluded.size()]));
}
if ((null != protocolsExcluded) && (!protocolsExcluded.isEmpty())) {
sslContextFactory.setExcludeProtocols(protocolsExcluded.toArray(new String[protocolsExcluded.size()]));
}
if (sslRenegotiationAllowed != null) {
sslContextFactory.setRenegotiationAllowed(sslRenegotiationAllowed);
}
// HTTP Configuration
HttpConfiguration httpConfig = getHttpConfiguration(port, checkForwaredHeaders, server);
// HTTPS Configuration
HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig);
httpsConfig.addCustomizer(new SecureRequestCustomizer());
List<AbstractConnectionFactory> connectionFactories = new ArrayList<>();
HttpConnectionFactory httpConFactory = new HttpConnectionFactory(httpsConfig);
SslConnectionFactory sslFactory = null;
AbstractConnectionFactory http2Factory = null;
NegotiatingServerConnectionFactory alpnFactory = null;
if (alpnCLassesAvailable()) {
log.info("HTTP/2 available, creating HttpSpdyServerConnector for Https");
// SPDY connector
try {
Class<?> comparatorClass = bundle.loadClass("org.eclipse.jetty.http2.HTTP2Cipher");
Comparator<String> cipherComparator = (Comparator<String>) FieldUtils.readDeclaredStaticField(comparatorClass, "COMPARATOR");
sslContextFactory.setCipherComparator(cipherComparator);
sslFactory = new SslConnectionFactory(sslContextFactory, "h2");
connectionFactories.add(sslFactory);
//org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory
Class<?> loadClass = bundle.loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory");
//
// //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1");
// alpnFactory = (NegotiatingServerConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, (Object) new String[] {"ssl", "http/2", "http/1.1"});
// alpnFactory.setDefaultProtocol("http/1.1");
// connectionFactories.add(alpnFactory);
//HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig);
// loadClass = bundle.loadClass("org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory");
// loadClass = bundle.loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory");
http2Factory = (AbstractConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, httpsConfig);
connectionFactories.add(http2Factory);
} catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException | IllegalAccessException | InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
log.info("SPDY not available, creating standard ServerConnector for Https");
sslFactory = new SslConnectionFactory(sslContextFactory, "http/1.1");
}
// HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig);
//
// ServerConnector https = new ServerConnector(server);
// HTTPS connector
ServerConnector https = new ServerConnector(server,
sslFactory,
httpConFactory);
for (AbstractConnectionFactory factory : connectionFactories) {
https.addConnectionFactory(factory);
}
https.setPort(port);
https.setName(name);
https.setHost(host);
https.setIdleTimeout(500000);
/*
SslContextFactory sslContextFactory = new SslContextFactory();
HttpConfiguration httpConfig = new HttpConfiguration();
SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "alpn");
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1");
alpn.setDefaultProtocol("http/1.1");
HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig);
HttpConnectionFactory http = new HttpConnectionFactory(httpConfig);
Server server = new Server();
ServerConnector connector = new ServerConnector(server, new ConnectionFactory[]{ssl, alpn, spdy, http});
*/
return https;
} |
java | public static String formatParam(Object value, String delimiter) {
if (value != null) {
if (byte[].class.getSimpleName().equals(value.getClass().getSimpleName())) {
return checkSize((byte[]) value, VIEW_SIZE);
}
String str = value.toString();
if (str.length() > VIEW_SIZE) {
return delimiter + str.substring(0, VIEW_SIZE - 3) + "..." + delimiter;
} else
return delimiter + str + delimiter;
} else
return "<undefined>";
} |
java | public ModifyImageAttributeRequest withProductCodes(String... productCodes) {
if (this.productCodes == null) {
setProductCodes(new com.amazonaws.internal.SdkInternalList<String>(productCodes.length));
}
for (String ele : productCodes) {
this.productCodes.add(ele);
}
return this;
} |
java | public Object getProperty(String name) {
if (!StringUtils.isBlank(name)) {
return getProperties().get(name);
}
return null;
} |
python | def run(self):
"""runner"""
# change version in code and changelog before running this
subprocess.check_call("git commit CHANGELOG.rst pyros/_version.py CHANGELOG.rst -m 'v{0}'".format(__version__), shell=True)
subprocess.check_call("git push", shell=True)
print("You should verify travis checks, and you can publish this release with :")
print(" python setup.py publish")
sys.exit() |
java | public static void classNotMapped(Object sourceClass, Class<?> configuredClass){
String sourceName = sourceClass instanceof Class?((Class<?>)sourceClass).getSimpleName():sourceClass.getClass().getSimpleName();
throw new ClassNotMappedException(MSG.INSTANCE.message(classNotMappedException2,sourceName, configuredClass.getSimpleName()));
} |
java | public static SignatureValidationFilter buildSignatureValidationFilter(final ResourceLoader resourceLoader,
final String signatureResourceLocation) {
try {
val resource = resourceLoader.getResource(signatureResourceLocation);
return buildSignatureValidationFilter(resource);
} catch (final Exception e) {
LOGGER.debug(e.getMessage(), e);
}
return null;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.